OSDN Git Service

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