OSDN Git Service

BugTrack2/151: Added lastmodified_add().
[pukiwiki/pukiwiki.git] / lib / file.php
1 <?php
2 // PukiWiki - Yet another WikiWikiWeb clone.
3 // $Id: file.php,v 1.60 2006/04/12 15:45:26 henoheno Exp $
4 // Copyright (C)
5 //   2002-2006 PukiWiki Developers Team
6 //   2001-2002 Originally written by yu-ji
7 // License: GPL v2 or (at your option) any later version
8 //
9 // File related functions
10
11 // RecentChanges
12 define('PKWK_MAXSHOW_ALLOWANCE', 10);
13 define('PKWK_MAXSHOW_CACHE', 'recent.dat');
14
15 // AutoLink
16 define('PKWK_AUTOLINK_REGEX_CACHE', 'autolink.dat');
17
18 // Get source(wiki text) data of the page
19 function get_source($page = NULL, $lock = TRUE)
20 {
21         $array = array();
22
23         if (is_page($page)) {
24                 $path  = get_filename($page);
25
26                 if ($lock) {
27                         $fp = @fopen($path, 'r');
28                         if ($fp == FALSE) return $array;
29                         flock($fp, LOCK_SH);
30                 }
31
32                 // Removing line-feeds: Because file() doesn't remove them.
33                 $array = str_replace("\r", '', file($path));
34
35                 if ($lock) {
36                         flock($fp, LOCK_UN);
37                         @fclose($fp);
38                 }
39         }
40
41         return $array;
42 }
43
44 // Get last-modified filetime of the page
45 function get_filetime($page)
46 {
47         return is_page($page) ? filemtime(get_filename($page)) - LOCALZONE : 0;
48 }
49
50 // Get physical file name of the page
51 function get_filename($page)
52 {
53         return DATA_DIR . encode($page) . '.txt';
54 }
55
56 // Put a data(wiki text) into a physical file(diff, backup, text)
57 function page_write($page, $postdata, $notimestamp = FALSE)
58 {
59         global $trackback;
60
61         if (PKWK_READONLY) return; // Do nothing
62
63         $postdata = make_str_rules($postdata);
64
65         // Create and write diff
66         $oldpostdata = is_page($page) ? join('', get_source($page)) : '';
67         $diffdata    = do_diff($oldpostdata, $postdata);
68         file_write(DIFF_DIR, $page, $diffdata);
69
70         // Create backup
71         make_backup($page, $postdata == ''); // Is $postdata null?
72
73         // Create wiki text
74         file_write(DATA_DIR, $page, $postdata, $notimestamp);
75
76         if ($trackback) {
77                 // TrackBack Ping
78                 $_diff = explode("\n", $diffdata);
79                 $plus  = join("\n", preg_replace('/^\+/', '', preg_grep('/^\+/', $_diff)));
80                 $minus = join("\n", preg_replace('/^-/',  '', preg_grep('/^-/',  $_diff)));
81                 tb_send($page, $plus, $minus);
82         }
83
84         links_update($page);
85 }
86
87 // Modify original text with user-defined / system-defined rules
88 function make_str_rules($source)
89 {
90         global $str_rules, $fixed_heading_anchor;
91
92         $lines = explode("\n", $source);
93         $count = count($lines);
94
95         $modify    = TRUE;
96         $multiline = 0;
97         $matches   = array();
98         for ($i = 0; $i < $count; $i++) {
99                 $line = & $lines[$i]; // Modify directly
100
101                 // Ignore null string and preformatted texts
102                 if ($line == '' || $line{0} == ' ' || $line{0} == "\t") continue;
103
104                 // Modify this line?
105                 if ($modify) {
106                         if (! PKWKEXP_DISABLE_MULTILINE_PLUGIN_HACK &&
107                             $multiline == 0 &&
108                             preg_match('/#[^{]*(\{\{+)\s*$/', $line, $matches)) {
109                                 // Multiline convert plugin start
110                                 $modify    = FALSE;
111                                 $multiline = strlen($matches[1]); // Set specific number
112                         }
113                 } else {
114                         if (! PKWKEXP_DISABLE_MULTILINE_PLUGIN_HACK &&
115                             $multiline != 0 &&
116                             preg_match('/^\}{' . $multiline . '}\s*$/', $line)) {
117                                 // Multiline convert plugin end
118                                 $modify    = TRUE;
119                                 $multiline = 0;
120                         }
121                 }
122                 if ($modify === FALSE) continue;
123
124                 // Replace with $str_rules
125                 foreach ($str_rules as $pattern => $replacement)
126                         $line = preg_replace('/' . $pattern . '/', $replacement, $line);
127                 
128                 // Adding fixed anchor into headings
129                 if ($fixed_heading_anchor &&
130                     preg_match('/^(\*{1,3}.*?)(?:\[#([A-Za-z][\w-]*)\]\s*)?$/', $line, $matches) &&
131                     (! isset($matches[2]) || $matches[2] == '')) {
132                         // Generate unique id
133                         $anchor = generate_fixed_heading_anchor_id($matches[1]);
134                         $line = rtrim($matches[1]) . ' [#' . $anchor . ']';
135                 }
136         }
137
138         // Multiline part has no stopper
139         if (! PKWKEXP_DISABLE_MULTILINE_PLUGIN_HACK &&
140             $modify === FALSE && $multiline != 0)
141                 $lines[] = str_repeat('}', $multiline);
142
143         return implode("\n", $lines);
144 }
145
146 // Generate ID
147 function generate_fixed_heading_anchor_id($seed)
148 {
149         // A random alphabetic letter + 7 letters of random strings from md()
150         return chr(mt_rand(ord('a'), ord('z'))) .
151                 substr(md5(uniqid(substr($seed, 0, 100), TRUE)),
152                 mt_rand(0, 24), 7);
153 }
154
155 // Read top N lines as an array
156 // (Use PHP file() function if you want to get ALL lines)
157 function file_head($file, $count = 1, $lock = TRUE, $buffer = 8192)
158 {
159         $array = array();
160
161         $fp = @fopen($file, 'r');
162         if ($fp === FALSE) return FALSE;
163         set_file_buffer($fp, 0);
164         if ($lock) flock($fp, LOCK_SH);
165         rewind($fp);
166         $index = 0;
167         while (! feof($fp)) {
168                 $line = fgets($fp, $buffer);
169                 if ($line != FALSE) $array[] = $line;
170                 if (++$index >= $count) break;
171         }
172         if ($lock) flock($fp, LOCK_UN);
173         if (! fclose($fp)) return FALSE;
174
175         return $array;
176 }
177
178 // Output to a file
179 function file_write($dir, $page, $str, $notimestamp = FALSE)
180 {
181         global $update_exec, $_msg_invalidiwn, $notify, $notify_diff_only, $notify_subject;
182         global $whatsdeleted, $maxshow_deleted;
183
184         if (PKWK_READONLY) return; // Do nothing
185         if ($dir != DATA_DIR && $dir != DIFF_DIR) die('file_write(): Invalid directory');
186
187         $page = strip_bracket($page);
188         $file = $dir . encode($page) . '.txt';
189         $file_exists = file_exists($file);
190
191         // ----
192         // Delete?
193
194         if ($dir == DATA_DIR && $str === '') {
195                 // Page deletion
196                 if (! $file_exists) return; // Ignore null posting for DATA_DIR
197
198                 // Update RecentDeleted (Add the $page)
199                 add_recent($page, $whatsdeleted, '', $maxshow_deleted);
200
201                 unlink($file);
202
203                 // Update RecentChanges (Remove the $page from RecentChanges)
204                 put_lastmodified();
205
206                 // Clear is_page() cache
207                 is_page($page, TRUE);
208
209                 return;
210
211         } else if ($dir == DIFF_DIR && $str === " \n") {
212                 return; // Ignore null posting for DIFF_DIR
213         }
214
215         // ----
216         // File replacement (Edit)
217
218         if (! is_pagename($page))
219                 die_message(str_replace('$1', htmlspecialchars($page),
220                             str_replace('$2', 'WikiName', $_msg_invalidiwn)));
221
222         $str = rtrim(preg_replace('/' . "\r" . '/', '', $str)) . "\n";
223         $timestamp = ($file_exists && $notimestamp) ? filemtime($file) : FALSE;
224
225         $fp = fopen($file, 'a') or die('fopen() failed: ' .
226                 htmlspecialchars(basename($dir) . '/' . encode($page) . '.txt') .       
227                 '<br />' . "\n" .
228                 'Maybe permission is not writable or filename is too long');
229         set_file_buffer($fp, 0);
230         flock($fp, LOCK_EX);
231         ftruncate($fp, 0);
232         rewind($fp);
233         fputs($fp, $str);
234         flock($fp, LOCK_UN);
235         fclose($fp);
236
237         if ($timestamp) pkwk_touch_file($file, $timestamp);
238
239         // Optional actions
240         if ($dir == DATA_DIR) {
241                 // Update RecentChanges (Add or renew the $page)
242                 if ($timestamp === FALSE) lastmodified_add($page);
243
244                 // Execute $update_exec here
245                 if ($update_exec) system($update_exec . ' > /dev/null &');
246
247         } else if ($dir == DIFF_DIR && $notify) {
248                 if ($notify_diff_only) $str = preg_replace('/^[^-+].*\n/m', '', $str);
249                 $footer['ACTION'] = 'Page update';
250                 $footer['PAGE']   = & $page;
251                 $footer['URI']    = get_script_uri() . '?' . rawurlencode($page);
252                 $footer['USER_AGENT']  = TRUE;
253                 $footer['REMOTE_ADDR'] = TRUE;
254                 pkwk_mail_notify($notify_subject, $str, $footer) or
255                         die('pkwk_mail_notify(): Failed');
256         }
257
258         is_page($page, TRUE); // Clear is_page() cache
259 }
260
261 // Update RecentDeleted
262 function add_recent($page, $recentpage, $subject = '', $limit = 0)
263 {
264         if (PKWK_READONLY || $limit == 0 || $page == '' || $recentpage == '' ||
265             check_non_list($page)) return;
266
267         // Load
268         $lines = $matches = array();
269         foreach (get_source($recentpage) as $line)
270                 if (preg_match('/^-(.+) - (\[\[.+\]\])$/', $line, $matches))
271                         $lines[$matches[2]] = $line;
272
273         $_page = '[[' . $page . ']]';
274
275         // Remove a report about the same page
276         if (isset($lines[$_page])) unset($lines[$_page]);
277
278         // Add
279         array_unshift($lines, '-' . format_date(UTIME) . ' - ' . $_page .
280                 htmlspecialchars($subject) . "\n");
281
282         // Get latest $limit reports
283         $lines = array_splice($lines, 0, $limit);
284
285         // Update
286         $fp = fopen(get_filename($recentpage), 'w') or
287                 die_message('Cannot write page file ' .
288                 htmlspecialchars($recentpage) .
289                 '<br />Maybe permission is not writable or filename is too long');
290         set_file_buffer($fp, 0);
291         flock($fp, LOCK_EX);
292         rewind($fp);
293         fputs($fp, '#freeze'    . "\n");
294         fputs($fp, '#norelated' . "\n"); // :)
295         fputs($fp, join('', $lines));
296         flock($fp, LOCK_UN);
297         fclose($fp);
298 }
299
300 // Update PKWK_MAXSHOW_CACHE itself (Add or renew about the $page) (Light)
301 // Use without $autolink
302 function lastmodified_add($page = '')
303 {
304         global $maxshow, $whatsnew, $autolink;
305
306         $file = CACHE_DIR . PKWK_MAXSHOW_CACHE;
307         if ($autolink || ! file_exists($file)) {
308                 put_lastmodified(); // Try to (re)create ALL
309                 return;
310         }
311
312         // Open
313         pkwk_touch_file($file);
314         $fp = fopen($file, 'r+') or
315                 die_message('Cannot open ' . 'CACHE_DIR/' . PKWK_MAXSHOW_CACHE);
316         set_file_buffer($fp, 0);
317         flock($fp, LOCK_EX);
318
319         // Read
320         $recent_pages = $matches = array();
321         foreach(file_head($file, $maxshow + PKWK_MAXSHOW_ALLOWANCE, FALSE) as $line)
322                 if (preg_match('/^([0-9]+)\t(.+)/', $line, $matches))
323                         $recent_pages[$matches[2]] = $matches[1];
324
325         // Remove if exists
326         if (isset($recent_pages[$page])) unset($recent_pages[$page]);
327
328         // Add: array_unshift()
329         $recent_pages = array($page => get_filetime($page)) + $recent_pages;
330
331         // Write
332         ftruncate($fp, 0);
333         rewind($fp);
334         foreach ($recent_pages as $_page=>$time)
335                 fputs($fp, $time . "\t" . $_page . "\n");
336
337         flock($fp, LOCK_UN);
338         fclose($fp);
339
340
341         // ----
342         // Update the page 'RecentChanges'
343
344         $recent_pages = array_splice($recent_pages, 0, $maxshow);
345         $file = get_filename($whatsnew);
346
347         // Open
348         pkwk_touch_file($file);
349         $fp = fopen($file, 'r+') or
350                 die_message('Cannot open ' . htmlspecialchars($whatsnew));
351         set_file_buffer($fp, 0);
352         flock($fp, LOCK_EX);
353
354         // Write
355         ftruncate($fp, 0);
356         rewind($fp);
357         foreach ($recent_pages as $_page=>$time)
358                 fputs($fp, '-' . htmlspecialchars(format_date($time)) .
359                         ' - ' . '[[' . htmlspecialchars($_page) . ']]' . "\n");
360         fputs($fp, '#norelated' . "\n"); // :)
361
362         flock($fp, LOCK_UN);
363         fclose($fp);
364 }
365
366 // Re-create PKWK_MAXSHOW_CACHE (Heavy)
367 function put_lastmodified()
368 {
369         global $maxshow, $whatsnew, $autolink;
370
371         if (PKWK_READONLY) return; // Do nothing
372
373         // Get WHOLE page list
374         $pages = get_existpages();
375
376         // Check ALL filetime
377         $recent_pages = array();
378         foreach($pages as $page)
379                 if ($page != $whatsnew && ! check_non_list($page))
380                         $recent_pages[$page] = get_filetime($page);
381
382         // Sort decending order of last-modification date
383         arsort($recent_pages, SORT_NUMERIC);
384
385         // Cut unused lines
386         $recent_pages = array_splice($recent_pages, 0, $maxshow + PKWK_MAXSHOW_ALLOWANCE);
387
388         // Re-create PKWK_MAXSHOW_CACHE
389         $file = CACHE_DIR . PKWK_MAXSHOW_CACHE;
390         pkwk_touch_file($file);
391         $fp = fopen($file, 'r+') or
392                 die_message('Cannot open' . 'CACHE_DIR/' . PKWK_MAXSHOW_CACHE);
393         set_file_buffer($fp, 0);
394         flock($fp, LOCK_EX);
395         ftruncate($fp, 0);
396         rewind($fp);
397         foreach ($recent_pages as $page=>$time)
398                 fputs($fp, $time . "\t" . $page . "\n");
399         flock($fp, LOCK_UN);
400         fclose($fp);
401
402         // Create RecentChanges
403         $file = get_filename($whatsnew);
404         pkwk_touch_file($file);
405         $fp = fopen($file, 'r+') or
406                 die_message('Cannot open ' . htmlspecialchars($whatsnew));
407         set_file_buffer($fp, 0);
408         flock($fp, LOCK_EX);
409         ftruncate($fp, 0);
410         rewind($fp);
411         foreach (array_keys($recent_pages) as $page) {
412                 $time      = $recent_pages[$page];
413                 $s_lastmod = htmlspecialchars(format_date($time));
414                 $s_page    = htmlspecialchars($page);
415                 fputs($fp, '-' . $s_lastmod . ' - [[' . $s_page . ']]' . "\n");
416         }
417         fputs($fp, '#norelated' . "\n"); // :)
418         flock($fp, LOCK_UN);
419         fclose($fp);
420
421         // For AutoLink
422         if ($autolink) {
423                 list($pattern, $pattern_a, $forceignorelist) =
424                         get_autolink_pattern($pages);
425
426                 $file = CACHE_DIR . PKWK_AUTOLINK_REGEX_CACHE;
427                 pkwk_touch_file($file);
428                 $fp = fopen($file, 'r+') or
429                         die_message('Cannot open ' . 'CACHE_DIR/' . PKWK_AUTOLINK_REGEX_CACHE);
430                 set_file_buffer($fp, 0);
431                 flock($fp, LOCK_EX);
432                 ftruncate($fp, 0);
433                 rewind($fp);
434                 fputs($fp, $pattern   . "\n");
435                 fputs($fp, $pattern_a . "\n");
436                 fputs($fp, join("\t", $forceignorelist) . "\n");
437                 flock($fp, LOCK_UN);
438                 fclose($fp);
439         }
440 }
441
442 // Get elapsed date of the page
443 function get_pg_passage($page, $sw = TRUE)
444 {
445         global $show_passage;
446         if (! $show_passage) return '';
447
448         $time = get_filetime($page);
449         $pg_passage = ($time != 0) ? get_passage($time) : '';
450
451         return $sw ? '<small>' . $pg_passage . '</small>' : ' ' . $pg_passage;
452 }
453
454 // Last-Modified header
455 function header_lastmod($page = NULL)
456 {
457         global $lastmod;
458
459         if ($lastmod && is_page($page)) {
460                 pkwk_headers_sent();
461                 header('Last-Modified: ' .
462                         date('D, d M Y H:i:s', get_filetime($page)) . ' GMT');
463         }
464 }
465
466 // Get a page list of this wiki
467 function get_existpages($dir = DATA_DIR, $ext = '.txt')
468 {
469         $aryret = array();
470
471         $pattern = '((?:[0-9A-F]{2})+)';
472         if ($ext != '') $ext = preg_quote($ext, '/');
473         $pattern = '/^' . $pattern . $ext . '$/';
474
475         $dp = @opendir($dir) or
476                 die_message($dir . ' is not found or not readable.');
477         $matches = array();
478         while ($file = readdir($dp))
479                 if (preg_match($pattern, $file, $matches))
480                         $aryret[$file] = decode($matches[1]);
481         closedir($dp);
482
483         return $aryret;
484 }
485
486 // Get PageReading(pronounce-annotated) data in an array()
487 function get_readings()
488 {
489         global $pagereading_enable, $pagereading_kanji2kana_converter;
490         global $pagereading_kanji2kana_encoding, $pagereading_chasen_path;
491         global $pagereading_kakasi_path, $pagereading_config_page;
492         global $pagereading_config_dict;
493
494         $pages = get_existpages();
495
496         $readings = array();
497         foreach ($pages as $page) 
498                 $readings[$page] = '';
499
500         $deletedPage = FALSE;
501         $matches = array();
502         foreach (get_source($pagereading_config_page) as $line) {
503                 $line = chop($line);
504                 if(preg_match('/^-\[\[([^]]+)\]\]\s+(.+)$/', $line, $matches)) {
505                         if(isset($readings[$matches[1]])) {
506                                 // This page is not clear how to be pronounced
507                                 $readings[$matches[1]] = $matches[2];
508                         } else {
509                                 // This page seems deleted
510                                 $deletedPage = TRUE;
511                         }
512                 }
513         }
514
515         // If enabled ChaSen/KAKASI execution
516         if($pagereading_enable) {
517
518                 // Check there's non-clear-pronouncing page
519                 $unknownPage = FALSE;
520                 foreach ($readings as $page => $reading) {
521                         if($reading == '') {
522                                 $unknownPage = TRUE;
523                                 break;
524                         }
525                 }
526
527                 // Execute ChaSen/KAKASI, and get annotation
528                 if($unknownPage) {
529                         switch(strtolower($pagereading_kanji2kana_converter)) {
530                         case 'chasen':
531                                 if(! file_exists($pagereading_chasen_path))
532                                         die_message('ChaSen not found: ' . $pagereading_chasen_path);
533
534                                 $tmpfname = tempnam(realpath(CACHE_DIR), 'PageReading');
535                                 $fp = fopen($tmpfname, 'w') or
536                                         die_message('Cannot write temporary file "' . $tmpfname . '".' . "\n");
537                                 foreach ($readings as $page => $reading) {
538                                         if($reading != '') continue;
539                                         fputs($fp, mb_convert_encoding($page . "\n",
540                                                 $pagereading_kanji2kana_encoding, SOURCE_ENCODING));
541                                 }
542                                 fclose($fp);
543
544                                 $chasen = "$pagereading_chasen_path -F %y $tmpfname";
545                                 $fp     = popen($chasen, 'r');
546                                 if($fp === FALSE) {
547                                         unlink($tmpfname);
548                                         die_message('ChaSen execution failed: ' . $chasen);
549                                 }
550                                 foreach ($readings as $page => $reading) {
551                                         if($reading != '') continue;
552
553                                         $line = fgets($fp);
554                                         $line = mb_convert_encoding($line, SOURCE_ENCODING,
555                                                 $pagereading_kanji2kana_encoding);
556                                         $line = chop($line);
557                                         $readings[$page] = $line;
558                                 }
559                                 pclose($fp);
560
561                                 unlink($tmpfname) or
562                                         die_message('Temporary file can not be removed: ' . $tmpfname);
563                                 break;
564
565                         case 'kakasi':  /*FALLTHROUGH*/
566                         case 'kakashi':
567                                 if(! file_exists($pagereading_kakasi_path))
568                                         die_message('KAKASI not found: ' . $pagereading_kakasi_path);
569
570                                 $tmpfname = tempnam(realpath(CACHE_DIR), 'PageReading');
571                                 $fp       = fopen($tmpfname, 'w') or
572                                         die_message('Cannot write temporary file "' . $tmpfname . '".' . "\n");
573                                 foreach ($readings as $page => $reading) {
574                                         if($reading != '') continue;
575                                         fputs($fp, mb_convert_encoding($page . "\n",
576                                                 $pagereading_kanji2kana_encoding, SOURCE_ENCODING));
577                                 }
578                                 fclose($fp);
579
580                                 $kakasi = "$pagereading_kakasi_path -kK -HK -JK < $tmpfname";
581                                 $fp     = popen($kakasi, 'r');
582                                 if($fp === FALSE) {
583                                         unlink($tmpfname);
584                                         die_message('KAKASI execution failed: ' . $kakasi);
585                                 }
586
587                                 foreach ($readings as $page => $reading) {
588                                         if($reading != '') continue;
589
590                                         $line = fgets($fp);
591                                         $line = mb_convert_encoding($line, SOURCE_ENCODING,
592                                                 $pagereading_kanji2kana_encoding);
593                                         $line = chop($line);
594                                         $readings[$page] = $line;
595                                 }
596                                 pclose($fp);
597
598                                 unlink($tmpfname) or
599                                         die_message('Temporary file can not be removed: ' . $tmpfname);
600                                 break;
601
602                         case 'none':
603                                 $patterns = $replacements = $matches = array();
604                                 foreach (get_source($pagereading_config_dict) as $line) {
605                                         $line = chop($line);
606                                         if(preg_match('|^ /([^/]+)/,\s*(.+)$|', $line, $matches)) {
607                                                 $patterns[]     = $matches[1];
608                                                 $replacements[] = $matches[2];
609                                         }
610                                 }
611                                 foreach ($readings as $page => $reading) {
612                                         if($reading != '') continue;
613
614                                         $readings[$page] = $page;
615                                         foreach ($patterns as $no => $pattern)
616                                                 $readings[$page] = mb_convert_kana(mb_ereg_replace($pattern,
617                                                         $replacements[$no], $readings[$page]), 'aKCV');
618                                 }
619                                 break;
620
621                         default:
622                                 die_message('Unknown kanji-kana converter: ' . $pagereading_kanji2kana_converter . '.');
623                                 break;
624                         }
625                 }
626
627                 if($unknownPage || $deletedPage) {
628
629                         asort($readings); // Sort by pronouncing(alphabetical/reading) order
630                         $body = '';
631                         foreach ($readings as $page => $reading)
632                                 $body .= '-[[' . $page . ']] ' . $reading . "\n";
633
634                         page_write($pagereading_config_page, $body);
635                 }
636         }
637
638         // Pages that are not prounouncing-clear, return pagenames of themselves
639         foreach ($pages as $page) {
640                 if($readings[$page] == '')
641                         $readings[$page] = $page;
642         }
643
644         return $readings;
645 }
646
647 // Get a list of encoded files (must specify a directory and a suffix)
648 function get_existfiles($dir, $ext)
649 {
650         $pattern = '/^(?:[0-9A-F]{2})+' . preg_quote($ext, '/') . '$/';
651         $aryret = array();
652         $dp = @opendir($dir) or die_message($dir . ' is not found or not readable.');
653         while ($file = readdir($dp))
654                 if (preg_match($pattern, $file))
655                         $aryret[] = $dir . $file;
656         closedir($dp);
657         return $aryret;
658 }
659
660 // Get a list of related pages of the page
661 function links_get_related($page)
662 {
663         global $vars, $related;
664         static $links = array();
665
666         if (isset($links[$page])) return $links[$page];
667
668         // If possible, merge related pages generated by make_link()
669         $links[$page] = ($page == $vars['page']) ? $related : array();
670
671         // Get repated pages from DB
672         $links[$page] += links_get_related_db($vars['page']);
673
674         return $links[$page];
675 }
676
677 // _If needed_, re-create the file to change/correct ownership into PHP's
678 // NOTE: Not works for Windows
679 function pkwk_chown($filename, $preserve_time = TRUE)
680 {
681         static $php_uid; // PHP's UID
682
683         if (! isset($php_uid)) {
684                 if (extension_loaded('posix')) {
685                         $php_uid = posix_getuid(); // Unix
686                 } else {
687                         $php_uid = 0; // Windows
688                 }
689         }
690
691         // Lock for pkwk_chown()
692         $lockfile = CACHE_DIR . 'pkwk_chown.lock';
693         $flock = fopen($lockfile, 'a') or
694                 die('pkwk_chown(): fopen() failed for: CACHEDIR/' .
695                         basename(htmlspecialchars($lockfile)));
696         flock($flock, LOCK_EX) or die('pkwk_chown(): flock() failed for lock');
697
698         // Check owner
699         $stat = stat($filename) or
700                 die('pkwk_chown(): stat() failed for: '  . basename(htmlspecialchars($filename)));
701         if ($stat[4] === $php_uid) {
702                 // NOTE: Windows always here
703                 $result = TRUE; // Seems the same UID. Nothing to do
704         } else {
705                 $tmp = $filename . '.' . getmypid() . '.tmp';
706
707                 // Lock source $filename to avoid file corruption
708                 // NOTE: Not 'r+'. Don't check write permission here
709                 $ffile = fopen($filename, 'r') or
710                         die('pkwk_chown(): fopen() failed for: ' .
711                                 basename(htmlspecialchars($filename)));
712
713                 // Try to chown by re-creating files
714                 // NOTE:
715                 //   * touch() before copy() is for 'rw-r--r--' instead of 'rwxr-xr-x' (with umask 022).
716                 //   * (PHP 4 < PHP 4.2.0) touch() with the third argument is not implemented and retuns NULL and Warn.
717                 //   * @unlink() before rename() is for Windows but here's for Unix only
718                 flock($ffile, LOCK_EX) or die('pkwk_chown(): flock() failed');
719                 $result = touch($tmp) && copy($filename, $tmp) &&
720                         ($preserve_time ? (touch($tmp, $stat[9], $stat[8]) || touch($tmp, $stat[9])) : TRUE) &&
721                         rename($tmp, $filename);
722                 flock($ffile, LOCK_UN) or die('pkwk_chown(): flock() failed');
723
724                 fclose($ffile) or die('pkwk_chown(): fclose() failed');
725
726                 if ($result === FALSE) @unlink($tmp);
727         }
728
729         // Unlock for pkwk_chown()
730         flock($flock, LOCK_UN) or die('pkwk_chown(): flock() failed for lock');
731         fclose($flock) or die('pkwk_chown(): fclose() failed for lock');
732
733         return $result;
734 }
735
736 // touch() with trying pkwk_chown()
737 function pkwk_touch_file($filename, $time = FALSE, $atime = FALSE)
738 {
739         // Is the owner incorrected and unable to correct?
740         if (! file_exists($filename) || pkwk_chown($filename)) {
741                 if ($time === FALSE) {
742                         $result = touch($filename);
743                 } else if ($atime === FALSE) {
744                         $result = touch($filename, $time);
745                 } else {
746                         $result = touch($filename, $time, $atime);
747                 }
748                 return $result;
749         } else {
750                 die('pkwk_touch_file(): Invalid UID and (not writable for the directory or not a flie): ' .
751                         htmlspecialchars(basename($filename)));
752         }
753 }
754 ?>