OSDN Git Service

BugTrack/2213 Set Absolute URI or Root relative path
[pukiwiki/pukiwiki.git] / lib / file.php
1 <?php
2 // PukiWiki - Yet another WikiWikiWeb clone.
3 // file.php
4 // Copyright
5 //   2002-2017 PukiWiki Development 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 // Returns FALSE if error occurerd
20 function get_source($page = NULL, $lock = TRUE, $join = FALSE)
21 {
22         //$result = NULL;       // File is not found
23         $result = $join ? '' : array();
24                 // Compat for "implode('', get_source($file))",
25                 //      -- this is slower than "get_source($file, TRUE, TRUE)"
26                 // Compat for foreach(get_source($file) as $line) {} not to warns
27
28         $path = get_filename($page);
29         if (file_exists($path)) {
30
31                 if ($lock) {
32                         $fp = @fopen($path, 'r');
33                         if ($fp === FALSE) return FALSE;
34                         flock($fp, LOCK_SH);
35                 }
36
37                 if ($join) {
38                         // Returns a value
39                         $size = filesize($path);
40                         if ($size === FALSE) {
41                                 $result = FALSE;
42                         } else if ($size == 0) {
43                                 $result = '';
44                         } else {
45                                 $result = fread($fp, $size);
46                                 if ($result !== FALSE) {
47                                         // Removing Carriage-Return
48                                         $result = str_replace("\r", '', $result);
49                                 }
50                         }
51                 } else {
52                         // Returns an array
53                         $result = file($path);
54                         if ($result !== FALSE) {
55                                 // Removing Carriage-Return
56                                 $result = str_replace("\r", '', $result);
57                         }
58                 }
59
60                 if ($lock) {
61                         flock($fp, LOCK_UN);
62                         @fclose($fp);
63                 }
64         }
65
66         return $result;
67 }
68
69 // Get last-modified filetime of the page
70 function get_filetime($page)
71 {
72         return is_page($page) ? filemtime(get_filename($page)) - LOCALZONE : 0;
73 }
74
75 // Get physical file name of the page
76 function get_filename($page)
77 {
78         return DATA_DIR . encode($page) . '.txt';
79 }
80
81 // Put a data(wiki text) into a physical file(diff, backup, text)
82 function page_write($page, $postdata, $notimestamp = FALSE)
83 {
84         if (PKWK_READONLY) return; // Do nothing
85
86         $postdata = make_str_rules($postdata);
87         $timestamp_to_keep = null;
88         if ($notimestamp) {
89                 $timestamp_to_keep = get_filetime($page);
90         }
91         $text_without_author = remove_author_info($postdata);
92         $postdata = add_author_info($text_without_author, $timestamp_to_keep);
93         $is_delete = empty($text_without_author);
94
95         // Do nothing when it has no changes
96         $oldpostdata = is_page($page) ? join('', get_source($page)) : '';
97         $oldtext_without_author = remove_author_info($oldpostdata);
98         if (!$is_delete && $text_without_author === $oldtext_without_author) {
99                 // Do nothing on updating with unchanged content
100                 return;
101         }
102         // Create and write diff
103         $diffdata    = do_diff($oldpostdata, $postdata);
104         file_write(DIFF_DIR, $page, $diffdata);
105
106         // Create backup
107         make_backup($page, $is_delete, $postdata); // Is $postdata null?
108
109         // Create wiki text
110         file_write(DATA_DIR, $page, $postdata, $notimestamp, $is_delete);
111
112         links_update($page);
113 }
114
115 // Modify original text with user-defined / system-defined rules
116 function make_str_rules($source)
117 {
118         global $str_rules, $fixed_heading_anchor;
119
120         $lines = explode("\n", $source);
121         $count = count($lines);
122
123         $modify    = TRUE;
124         $multiline = 0;
125         $matches   = array();
126         for ($i = 0; $i < $count; $i++) {
127                 $line = & $lines[$i]; // Modify directly
128
129                 // Ignore null string and preformatted texts
130                 if ($line == '' || $line{0} == ' ' || $line{0} == "\t") continue;
131
132                 // Modify this line?
133                 if ($modify) {
134                         if (! PKWKEXP_DISABLE_MULTILINE_PLUGIN_HACK &&
135                             $multiline == 0 &&
136                             preg_match('/#[^{]*(\{\{+)\s*$/', $line, $matches)) {
137                                 // Multiline convert plugin start
138                                 $modify    = FALSE;
139                                 $multiline = strlen($matches[1]); // Set specific number
140                         }
141                 } else {
142                         if (! PKWKEXP_DISABLE_MULTILINE_PLUGIN_HACK &&
143                             $multiline != 0 &&
144                             preg_match('/^\}{' . $multiline . '}\s*$/', $line)) {
145                                 // Multiline convert plugin end
146                                 $modify    = TRUE;
147                                 $multiline = 0;
148                         }
149                 }
150                 if ($modify === FALSE) continue;
151
152                 // Replace with $str_rules
153                 foreach ($str_rules as $pattern => $replacement)
154                         $line = preg_replace('/' . $pattern . '/', $replacement, $line);
155                 
156                 // Adding fixed anchor into headings
157                 if ($fixed_heading_anchor &&
158                     preg_match('/^(\*{1,3}.*?)(?:\[#([A-Za-z][\w-]*)\]\s*)?$/', $line, $matches) &&
159                     (! isset($matches[2]) || $matches[2] == '')) {
160                         // Generate unique id
161                         $anchor = generate_fixed_heading_anchor_id($matches[1]);
162                         $line = rtrim($matches[1]) . ' [#' . $anchor . ']';
163                 }
164         }
165
166         // Multiline part has no stopper
167         if (! PKWKEXP_DISABLE_MULTILINE_PLUGIN_HACK &&
168             $modify === FALSE && $multiline != 0)
169                 $lines[] = str_repeat('}', $multiline);
170
171         return implode("\n", $lines);
172 }
173
174 /**
175  * Add author plugin text for wiki text body
176  *
177  * @param string $wikitext
178  * @param integer $timestamp_to_keep Set null when not to keep timestamp
179  */
180 function add_author_info($wikitext, $timestamp_to_keep)
181 {
182         global $auth_user, $auth_user_fullname;
183         $author = preg_replace('/"/', '', $auth_user);
184         $fullname = $auth_user_fullname;
185         if (!$fullname && $author) {
186                 // Fullname is empty, use $author as its fullname
187                 $fullname = preg_replace('/^[^:]*:/', '', $author);
188         }
189         $datetime_to_keep = '';
190         if (!is_null($timestamp_to_keep)) {
191                 $datetime_to_keep .= ';' . get_date_atom($timestamp_to_keep + LOCALZONE);
192         }
193         $displayname = preg_replace('/"/', '', $fullname);
194         $user_prefix = get_auth_user_prefix();
195         $author_text = sprintf('#author("%s","%s","%s")',
196                 get_date_atom(UTIME + LOCALZONE) . $datetime_to_keep,
197                 ($author ? $user_prefix . $author : ''),
198                 $displayname) . "\n";
199         return $author_text . $wikitext;
200 }
201
202 function remove_author_info($wikitext)
203 {
204         return preg_replace('/^\s*#author\([^\n]*(\n|$)/m', '', $wikitext);
205 }
206
207 function get_date_atom($timestamp)
208 {
209         // Compatible with DATE_ATOM format
210         // return date(DATE_ATOM, $timestamp);
211         $zmin = abs(LOCALZONE / 60);
212         return date('Y-m-d\TH:i:s', $timestamp) . sprintf('%s%02d:%02d',
213                 (LOCALZONE < 0 ? '-' : '+') , $zmin / 60, $zmin % 60);
214 }
215
216 // Generate ID
217 function generate_fixed_heading_anchor_id($seed)
218 {
219         // A random alphabetic letter + 7 letters of random strings from md()
220         return chr(mt_rand(ord('a'), ord('z'))) .
221                 substr(md5(uniqid(substr($seed, 0, 100), TRUE)),
222                 mt_rand(0, 24), 7);
223 }
224
225 // Read top N lines as an array
226 // (Use PHP file() function if you want to get ALL lines)
227 function file_head($file, $count = 1, $lock = TRUE, $buffer = 8192)
228 {
229         $array = array();
230
231         $fp = @fopen($file, 'r');
232         if ($fp === FALSE) return FALSE;
233         set_file_buffer($fp, 0);
234         if ($lock) flock($fp, LOCK_SH);
235         rewind($fp);
236         $index = 0;
237         while (! feof($fp)) {
238                 $line = fgets($fp, $buffer);
239                 if ($line != FALSE) $array[] = $line;
240                 if (++$index >= $count) break;
241         }
242         if ($lock) flock($fp, LOCK_UN);
243         if (! fclose($fp)) return FALSE;
244
245         return $array;
246 }
247
248 // Output to a file
249 function file_write($dir, $page, $str, $notimestamp = FALSE, $is_delete = FALSE)
250 {
251         global $_msg_invalidiwn, $notify, $notify_diff_only, $notify_subject;
252         global $whatsdeleted, $maxshow_deleted;
253
254         if (PKWK_READONLY) return; // Do nothing
255         if ($dir != DATA_DIR && $dir != DIFF_DIR) die('file_write(): Invalid directory');
256
257         $page = strip_bracket($page);
258         $file = $dir . encode($page) . '.txt';
259         $file_exists = file_exists($file);
260
261         // ----
262         // Delete?
263
264         if ($dir == DATA_DIR && $is_delete) {
265                 // Page deletion
266                 if (! $file_exists) return; // Ignore null posting for DATA_DIR
267
268                 // Update RecentDeleted (Add the $page)
269                 add_recent($page, $whatsdeleted, '', $maxshow_deleted);
270
271                 // Remove the page
272                 unlink($file);
273
274                 // Update RecentDeleted, and remove the page from RecentChanges
275                 lastmodified_add($whatsdeleted, $page);
276
277                 // Clear is_page() cache
278                 is_page($page, TRUE);
279
280                 return;
281
282         } else if ($dir == DIFF_DIR && $str === " \n") {
283                 return; // Ignore null posting for DIFF_DIR
284         }
285
286         // ----
287         // File replacement (Edit)
288
289         if (! is_pagename($page))
290                 die_message(str_replace('$1', htmlsc($page),
291                             str_replace('$2', 'WikiName', $_msg_invalidiwn)));
292
293         $str = rtrim(preg_replace('/' . "\r" . '/', '', $str)) . "\n";
294         $timestamp = ($file_exists && $notimestamp) ? filemtime($file) : FALSE;
295
296         $fp = fopen($file, 'a') or die('fopen() failed: ' .
297                 htmlsc(basename($dir) . '/' . encode($page) . '.txt') . 
298                 '<br />' . "\n" .
299                 'Maybe permission is not writable or filename is too long');
300         set_file_buffer($fp, 0);
301         flock($fp, LOCK_EX);
302         ftruncate($fp, 0);
303         rewind($fp);
304         fputs($fp, $str);
305         flock($fp, LOCK_UN);
306         fclose($fp);
307
308         if ($timestamp) pkwk_touch_file($file, $timestamp);
309
310         // Optional actions
311         if ($dir == DATA_DIR) {
312                 // Update RecentChanges (Add or renew the $page)
313                 if ($timestamp === FALSE) lastmodified_add($page);
314
315                 // Command execution per update
316                 if (defined('PKWK_UPDATE_EXEC') && PKWK_UPDATE_EXEC)
317                         system(PKWK_UPDATE_EXEC . ' > /dev/null &');
318
319         } else if ($dir == DIFF_DIR && $notify) {
320                 if ($notify_diff_only) $str = preg_replace('/^[^-+].*\n/m', '', $str);
321                 $footer['ACTION'] = 'Page update';
322                 $footer['PAGE']   = $page;
323                 $footer['URI']    = get_script_uri(PKWK_URI_ABSOLUTE) . '?' . pagename_urlencode($page);
324                 $footer['USER_AGENT']  = TRUE;
325                 $footer['REMOTE_ADDR'] = TRUE;
326                 pkwk_mail_notify($notify_subject, $str, $footer) or
327                         die('pkwk_mail_notify(): Failed');
328         }
329         if ($dir === DIFF_DIR) {
330                 pkwk_log_updates($page, $str);
331         }
332         is_page($page, TRUE); // Clear is_page() cache
333 }
334
335 // Update RecentDeleted
336 function add_recent($page, $recentpage, $subject = '', $limit = 0)
337 {
338         if (PKWK_READONLY || $limit == 0 || $page == '' || $recentpage == '' ||
339             check_non_list($page)) return;
340
341         // Load
342         $lines = $matches = array();
343         foreach (get_source($recentpage) as $line)
344                 if (preg_match('/^-(.+) - (\[\[.+\]\])$/', $line, $matches))
345                         $lines[$matches[2]] = $line;
346
347         $_page = '[[' . $page . ']]';
348
349         // Remove a report about the same page
350         if (isset($lines[$_page])) unset($lines[$_page]);
351
352         // Add
353         array_unshift($lines, '-' . format_date(UTIME) . ' - ' . $_page .
354                 htmlsc($subject) . "\n");
355
356         // Get latest $limit reports
357         $lines = array_splice($lines, 0, $limit);
358
359         // Update
360         $fp = fopen(get_filename($recentpage), 'w') or
361                 die_message('Cannot write page file ' .
362                 htmlsc($recentpage) .
363                 '<br />Maybe permission is not writable or filename is too long');
364         set_file_buffer($fp, 0);
365         flock($fp, LOCK_EX);
366         rewind($fp);
367         fputs($fp, '#freeze'    . "\n");
368         fputs($fp, '#norelated' . "\n"); // :)
369         fputs($fp, join('', $lines));
370         flock($fp, LOCK_UN);
371         fclose($fp);
372 }
373
374 // Update PKWK_MAXSHOW_CACHE itself (Add or renew about the $page) (Light)
375 // Use without $autolink
376 function lastmodified_add($update = '', $remove = '')
377 {
378         global $maxshow, $whatsnew, $autolink;
379
380         // AutoLink implimentation needs everything, for now
381         if ($autolink) {
382                 put_lastmodified(); // Try to (re)create ALL
383                 return;
384         }
385
386         if (($update == '' || check_non_list($update)) && $remove == '')
387                 return; // No need
388
389         $file = CACHE_DIR . PKWK_MAXSHOW_CACHE;
390         if (! file_exists($file)) {
391                 put_lastmodified(); // Try to (re)create ALL
392                 return;
393         }
394
395         // Open
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
402         // Read (keep the order of the lines)
403         $recent_pages = $matches = array();
404         foreach(file_head($file, $maxshow + PKWK_MAXSHOW_ALLOWANCE, FALSE) as $line)
405                 if (preg_match('/^([0-9]+)\t(.+)/', $line, $matches))
406                         $recent_pages[$matches[2]] = $matches[1];
407
408         // Remove if it exists inside
409         if (isset($recent_pages[$update])) unset($recent_pages[$update]);
410         if (isset($recent_pages[$remove])) unset($recent_pages[$remove]);
411
412         // Add to the top: like array_unshift()
413         if ($update != '')
414                 $recent_pages = array($update => get_filetime($update)) + $recent_pages;
415
416         // Check
417         $abort = count($recent_pages) < $maxshow;
418
419         if (! $abort) {
420                 // Write
421                 ftruncate($fp, 0);
422                 rewind($fp);
423                 foreach ($recent_pages as $_page=>$time)
424                         fputs($fp, $time . "\t" . $_page . "\n");
425         }
426
427         flock($fp, LOCK_UN);
428         fclose($fp);
429
430         if ($abort) {
431                 put_lastmodified(); // Try to (re)create ALL
432                 return;
433         }
434
435
436
437         // ----
438         // Update the page 'RecentChanges'
439
440         $recent_pages = array_splice($recent_pages, 0, $maxshow);
441         $file = get_filename($whatsnew);
442
443         // Open
444         pkwk_touch_file($file);
445         $fp = fopen($file, 'r+') or
446                 die_message('Cannot open ' . htmlsc($whatsnew));
447         set_file_buffer($fp, 0);
448         flock($fp, LOCK_EX);
449
450         // Recreate
451         ftruncate($fp, 0);
452         rewind($fp);
453         foreach ($recent_pages as $_page=>$time)
454                 fputs($fp, '-' . htmlsc(format_date($time)) .
455                         ' - ' . '[[' . htmlsc($_page) . ']]' . "\n");
456         fputs($fp, '#norelated' . "\n"); // :)
457
458         flock($fp, LOCK_UN);
459         fclose($fp);
460 }
461
462 // Re-create PKWK_MAXSHOW_CACHE (Heavy)
463 function put_lastmodified()
464 {
465         global $maxshow, $whatsnew, $autolink;
466
467         if (PKWK_READONLY) return; // Do nothing
468
469         // Get WHOLE page list
470         $pages = get_existpages();
471
472         // Check ALL filetime
473         $recent_pages = array();
474         foreach($pages as $page)
475                 if ($page !== $whatsnew && ! check_non_list($page))
476                         $recent_pages[$page] = get_filetime($page);
477
478         // Sort decending order of last-modification date
479         arsort($recent_pages, SORT_NUMERIC);
480
481         // Cut unused lines
482         // BugTrack2/179: array_splice() will break integer keys in hashtable
483         $count   = $maxshow + PKWK_MAXSHOW_ALLOWANCE;
484         $_recent = array();
485         foreach($recent_pages as $key=>$value) {
486                 unset($recent_pages[$key]);
487                 $_recent[$key] = $value;
488                 if (--$count < 1) break;
489         }
490         $recent_pages = & $_recent;
491
492         // Re-create PKWK_MAXSHOW_CACHE
493         $file = CACHE_DIR . PKWK_MAXSHOW_CACHE;
494         pkwk_touch_file($file);
495         $fp = fopen($file, 'r+') or
496                 die_message('Cannot open' . 'CACHE_DIR/' . PKWK_MAXSHOW_CACHE);
497         set_file_buffer($fp, 0);
498         flock($fp, LOCK_EX);
499         ftruncate($fp, 0);
500         rewind($fp);
501         foreach ($recent_pages as $page=>$time)
502                 fputs($fp, $time . "\t" . $page . "\n");
503         flock($fp, LOCK_UN);
504         fclose($fp);
505
506         // Create RecentChanges
507         $file = get_filename($whatsnew);
508         pkwk_touch_file($file);
509         $fp = fopen($file, 'r+') or
510                 die_message('Cannot open ' . htmlsc($whatsnew));
511         set_file_buffer($fp, 0);
512         flock($fp, LOCK_EX);
513         ftruncate($fp, 0);
514         rewind($fp);
515         foreach (array_keys($recent_pages) as $page) {
516                 $time      = $recent_pages[$page];
517                 $s_lastmod = htmlsc(format_date($time));
518                 $s_page    = htmlsc($page);
519                 fputs($fp, '-' . $s_lastmod . ' - [[' . $s_page . ']]' . "\n");
520         }
521         fputs($fp, '#norelated' . "\n"); // :)
522         flock($fp, LOCK_UN);
523         fclose($fp);
524
525         // For AutoLink
526         if ($autolink) {
527                 list($pattern, $pattern_a, $forceignorelist) =
528                         get_autolink_pattern($pages);
529
530                 $file = CACHE_DIR . PKWK_AUTOLINK_REGEX_CACHE;
531                 pkwk_touch_file($file);
532                 $fp = fopen($file, 'r+') or
533                         die_message('Cannot open ' . 'CACHE_DIR/' . PKWK_AUTOLINK_REGEX_CACHE);
534                 set_file_buffer($fp, 0);
535                 flock($fp, LOCK_EX);
536                 ftruncate($fp, 0);
537                 rewind($fp);
538                 fputs($fp, $pattern   . "\n");
539                 fputs($fp, $pattern_a . "\n");
540                 fputs($fp, join("\t", $forceignorelist) . "\n");
541                 flock($fp, LOCK_UN);
542                 fclose($fp);
543         }
544 }
545
546 /**
547  * Update RecentChanges page / Invalidate recent.dat
548  */
549 function delete_recent_changes_cache() {
550         $file = CACHE_DIR . PKWK_MAXSHOW_CACHE;
551         unlink($file);
552 }
553
554 // Get elapsed date of the page
555 function get_pg_passage($page, $sw = TRUE)
556 {
557         global $show_passage;
558         if (! $show_passage) return '';
559
560         $time = get_filetime($page);
561         $pg_passage = ($time != 0) ? get_passage($time) : '';
562
563         return $sw ? '<small>' . $pg_passage . '</small>' : ' ' . $pg_passage;
564 }
565
566 // Last-Modified header
567 function header_lastmod($page = NULL)
568 {
569         global $lastmod;
570
571         if ($lastmod && is_page($page)) {
572                 pkwk_headers_sent();
573                 header('Last-Modified: ' .
574                         date('D, d M Y H:i:s', get_filetime($page)) . ' GMT');
575         }
576 }
577
578 // Get a list of encoded files (must specify a directory and a suffix)
579 function get_existfiles($dir = DATA_DIR, $ext = '.txt')
580 {
581         $aryret = array();
582         $pattern = '/^(?:[0-9A-F]{2})+' . preg_quote($ext, '/') . '$/';
583
584         $dp = @opendir($dir) or die_message($dir . ' is not found or not readable.');
585         while (($file = readdir($dp)) !== FALSE) {
586                 if (preg_match($pattern, $file)) {
587                         $aryret[] = $dir . $file;
588                 }
589         }
590         closedir($dp);
591
592         return $aryret;
593 }
594
595 // Get a page list of this wiki
596 function get_existpages($dir = DATA_DIR, $ext = '.txt')
597 {
598         $aryret = array();
599         $pattern = '/^((?:[0-9A-F]{2})+)' . preg_quote($ext, '/') . '$/';
600
601         $dp = @opendir($dir) or die_message($dir . ' is not found or not readable.');
602         $matches = array();
603         while (($file = readdir($dp)) !== FALSE) {
604                 if (preg_match($pattern, $file, $matches)) {
605                         $aryret[$file] = decode($matches[1]);
606                 }
607         }
608         closedir($dp);
609
610         return $aryret;
611 }
612
613 // Get PageReading(pronounce-annotated) data in an array()
614 function get_readings()
615 {
616         global $pagereading_enable, $pagereading_kanji2kana_converter;
617         global $pagereading_kanji2kana_encoding, $pagereading_chasen_path;
618         global $pagereading_kakasi_path, $pagereading_config_page;
619         global $pagereading_config_dict;
620
621         $pages = get_existpages();
622
623         $readings = array();
624         foreach ($pages as $page) 
625                 $readings[$page] = '';
626
627         $deletedPage = FALSE;
628         $matches = array();
629         foreach (get_source($pagereading_config_page) as $line) {
630                 $line = chop($line);
631                 if(preg_match('/^-\[\[([^]]+)\]\]\s+(.+)$/', $line, $matches)) {
632                         if(isset($readings[$matches[1]])) {
633                                 // This page is not clear how to be pronounced
634                                 $readings[$matches[1]] = $matches[2];
635                         } else {
636                                 // This page seems deleted
637                                 $deletedPage = TRUE;
638                         }
639                 }
640         }
641
642         // If enabled ChaSen/KAKASI execution
643         if($pagereading_enable) {
644
645                 // Check there's non-clear-pronouncing page
646                 $unknownPage = FALSE;
647                 foreach ($readings as $page => $reading) {
648                         if($reading == '') {
649                                 $unknownPage = TRUE;
650                                 break;
651                         }
652                 }
653
654                 // Execute ChaSen/KAKASI, and get annotation
655                 if($unknownPage) {
656                         switch(strtolower($pagereading_kanji2kana_converter)) {
657                         case 'chasen':
658                                 if(! file_exists($pagereading_chasen_path))
659                                         die_message('ChaSen not found: ' . $pagereading_chasen_path);
660
661                                 $tmpfname = tempnam(realpath(CACHE_DIR), 'PageReading');
662                                 $fp = fopen($tmpfname, 'w') or
663                                         die_message('Cannot write temporary file "' . $tmpfname . '".' . "\n");
664                                 foreach ($readings as $page => $reading) {
665                                         if($reading != '') continue;
666                                         fputs($fp, mb_convert_encoding($page . "\n",
667                                                 $pagereading_kanji2kana_encoding, SOURCE_ENCODING));
668                                 }
669                                 fclose($fp);
670
671                                 $chasen = "$pagereading_chasen_path -F %y $tmpfname";
672                                 $fp     = popen($chasen, 'r');
673                                 if($fp === FALSE) {
674                                         unlink($tmpfname);
675                                         die_message('ChaSen execution failed: ' . $chasen);
676                                 }
677                                 foreach ($readings as $page => $reading) {
678                                         if($reading != '') continue;
679
680                                         $line = fgets($fp);
681                                         $line = mb_convert_encoding($line, SOURCE_ENCODING,
682                                                 $pagereading_kanji2kana_encoding);
683                                         $line = chop($line);
684                                         $readings[$page] = $line;
685                                 }
686                                 pclose($fp);
687
688                                 unlink($tmpfname) or
689                                         die_message('Temporary file can not be removed: ' . $tmpfname);
690                                 break;
691
692                         case 'kakasi':  /*FALLTHROUGH*/
693                         case 'kakashi':
694                                 if(! file_exists($pagereading_kakasi_path))
695                                         die_message('KAKASI not found: ' . $pagereading_kakasi_path);
696
697                                 $tmpfname = tempnam(realpath(CACHE_DIR), 'PageReading');
698                                 $fp       = fopen($tmpfname, 'w') or
699                                         die_message('Cannot write temporary file "' . $tmpfname . '".' . "\n");
700                                 foreach ($readings as $page => $reading) {
701                                         if($reading != '') continue;
702                                         fputs($fp, mb_convert_encoding($page . "\n",
703                                                 $pagereading_kanji2kana_encoding, SOURCE_ENCODING));
704                                 }
705                                 fclose($fp);
706
707                                 $kakasi = "$pagereading_kakasi_path -kK -HK -JK < $tmpfname";
708                                 $fp     = popen($kakasi, 'r');
709                                 if($fp === FALSE) {
710                                         unlink($tmpfname);
711                                         die_message('KAKASI execution failed: ' . $kakasi);
712                                 }
713
714                                 foreach ($readings as $page => $reading) {
715                                         if($reading != '') continue;
716
717                                         $line = fgets($fp);
718                                         $line = mb_convert_encoding($line, SOURCE_ENCODING,
719                                                 $pagereading_kanji2kana_encoding);
720                                         $line = chop($line);
721                                         $readings[$page] = $line;
722                                 }
723                                 pclose($fp);
724
725                                 unlink($tmpfname) or
726                                         die_message('Temporary file can not be removed: ' . $tmpfname);
727                                 break;
728
729                         case 'none':
730                                 $patterns = $replacements = $matches = array();
731                                 foreach (get_source($pagereading_config_dict) as $line) {
732                                         $line = chop($line);
733                                         if(preg_match('|^ /([^/]+)/,\s*(.+)$|', $line, $matches)) {
734                                                 $patterns[]     = $matches[1];
735                                                 $replacements[] = $matches[2];
736                                         }
737                                 }
738                                 foreach ($readings as $page => $reading) {
739                                         if($reading != '') continue;
740
741                                         $readings[$page] = $page;
742                                         foreach ($patterns as $no => $pattern)
743                                                 $readings[$page] = mb_convert_kana(mb_ereg_replace($pattern,
744                                                         $replacements[$no], $readings[$page]), 'aKCV');
745                                 }
746                                 break;
747
748                         default:
749                                 die_message('Unknown kanji-kana converter: ' . $pagereading_kanji2kana_converter . '.');
750                                 break;
751                         }
752                 }
753
754                 if($unknownPage || $deletedPage) {
755
756                         asort($readings, SORT_STRING); // Sort by pronouncing(alphabetical/reading) order
757                         $body = '';
758                         foreach ($readings as $page => $reading)
759                                 $body .= '-[[' . $page . ']] ' . $reading . "\n";
760
761                         page_write($pagereading_config_page, $body);
762                 }
763         }
764
765         // Pages that are not prounouncing-clear, return pagenames of themselves
766         foreach ($pages as $page) {
767                 if($readings[$page] == '')
768                         $readings[$page] = $page;
769         }
770
771         return $readings;
772 }
773
774 // Get a list of related pages of the page
775 function links_get_related($page)
776 {
777         global $vars, $related;
778         static $links = array();
779
780         if (isset($links[$page])) return $links[$page];
781
782         // If possible, merge related pages generated by make_link()
783         $links[$page] = ($page === $vars['page']) ? $related : array();
784
785         // Get repated pages from DB
786         $links[$page] += links_get_related_db($vars['page']);
787
788         return $links[$page];
789 }
790
791 // _If needed_, re-create the file to change/correct ownership into PHP's
792 // NOTE: Not works for Windows
793 function pkwk_chown($filename, $preserve_time = TRUE)
794 {
795         static $php_uid; // PHP's UID
796
797         if (! isset($php_uid)) {
798                 if (extension_loaded('posix')) {
799                         $php_uid = posix_getuid(); // Unix
800                 } else {
801                         $php_uid = 0; // Windows
802                 }
803         }
804
805         // Lock for pkwk_chown()
806         $lockfile = CACHE_DIR . 'pkwk_chown.lock';
807         $flock = fopen($lockfile, 'a') or
808                 die('pkwk_chown(): fopen() failed for: CACHEDIR/' .
809                         basename(htmlsc($lockfile)));
810         flock($flock, LOCK_EX) or die('pkwk_chown(): flock() failed for lock');
811
812         // Check owner
813         $stat = stat($filename) or
814                 die('pkwk_chown(): stat() failed for: '  . basename(htmlsc($filename)));
815         if ($stat[4] === $php_uid) {
816                 // NOTE: Windows always here
817                 $result = TRUE; // Seems the same UID. Nothing to do
818         } else {
819                 $tmp = $filename . '.' . getmypid() . '.tmp';
820
821                 // Lock source $filename to avoid file corruption
822                 // NOTE: Not 'r+'. Don't check write permission here
823                 $ffile = fopen($filename, 'r') or
824                         die('pkwk_chown(): fopen() failed for: ' .
825                                 basename(htmlsc($filename)));
826
827                 // Try to chown by re-creating files
828                 // NOTE:
829                 //   * touch() before copy() is for 'rw-r--r--' instead of 'rwxr-xr-x' (with umask 022).
830                 //   * (PHP 4 < PHP 4.2.0) touch() with the third argument is not implemented and retuns NULL and Warn.
831                 //   * @unlink() before rename() is for Windows but here's for Unix only
832                 flock($ffile, LOCK_EX) or die('pkwk_chown(): flock() failed');
833                 $result = touch($tmp) && copy($filename, $tmp) &&
834                         ($preserve_time ? (touch($tmp, $stat[9], $stat[8]) || touch($tmp, $stat[9])) : TRUE) &&
835                         rename($tmp, $filename);
836                 flock($ffile, LOCK_UN) or die('pkwk_chown(): flock() failed');
837
838                 fclose($ffile) or die('pkwk_chown(): fclose() failed');
839
840                 if ($result === FALSE) @unlink($tmp);
841         }
842
843         // Unlock for pkwk_chown()
844         flock($flock, LOCK_UN) or die('pkwk_chown(): flock() failed for lock');
845         fclose($flock) or die('pkwk_chown(): fclose() failed for lock');
846
847         return $result;
848 }
849
850 // touch() with trying pkwk_chown()
851 function pkwk_touch_file($filename, $time = FALSE, $atime = FALSE)
852 {
853         // Is the owner incorrected and unable to correct?
854         if (! file_exists($filename) || pkwk_chown($filename)) {
855                 if ($time === FALSE) {
856                         $result = touch($filename);
857                 } else if ($atime === FALSE) {
858                         $result = touch($filename, $time);
859                 } else {
860                         $result = touch($filename, $time, $atime);
861                 }
862                 return $result;
863         } else {
864                 die('pkwk_touch_file(): Invalid UID and (not writable for the directory or not a flie): ' .
865                         htmlsc(basename($filename)));
866         }
867 }
868
869 /**
870  * Lock-enabled file_get_contents
871  *
872  * Require: PHP5+
873  */
874 function pkwk_file_get_contents($filename) {
875         if (! file_exists($filename)) {
876                 return false;
877         }
878         $fp   = fopen($filename, 'rb');
879         flock($fp, LOCK_SH);
880         $file = file_get_contents($filename);
881         flock($fp, LOCK_UN);
882         return $file;
883 }
884
885 /**
886  * Prepare some cache files for convert_html()
887  *
888  * * Make cache/autolink.dat if needed
889  */
890 function prepare_display_materials() {
891         global $autolink;
892         if ($autolink) {
893                 // Make sure 'cache/autolink.dat'
894                 $file = CACHE_DIR . PKWK_AUTOLINK_REGEX_CACHE;
895                 if (!file_exists($file)) {
896                         // Re-create autolink.dat
897                         put_lastmodified();
898                 }
899         }
900 }
901
902 /**
903  * Prepare page related links and references for links_get_related()
904  */
905 function prepare_links_related($page) {
906         $enc_name = encode($page);
907         $rel_file = CACHE_DIR . encode($page) . '.rel';
908         $ref_file = CACHE_DIR . encode($page) . '.ref';
909         if (file_exists($rel_file)) return;
910         if (file_exists($ref_file)) return;
911         $pattern = '/^((?:[0-9A-F]{2})+)' . '(\.ref|\.rel)' . '$/';
912
913         $dir = CACHE_DIR;
914         $dp = @opendir($dir) or die_message('CACHE_DIR/'. ' is not found or not readable.');
915         $rel_ref_ready = false;
916         $count = 0;
917         while (($file = readdir($dp)) !== FALSE) {
918                 if (preg_match($pattern, $file, $matches)) {
919                         if ($count++ > 5) {
920                                 $rel_ref_ready = true;
921                                 break;
922                         }
923                 }
924         }
925         closedir($dp);
926         if (!$rel_ref_ready) {
927                 if (count(get_existpages()) < 50) {
928                         // Make link files automatically only if page count < 50.
929                         // Because large number of update links will cause PHP timeout.
930                         links_init();
931                 }
932         }
933 }