OSDN Git Service

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