OSDN Git Service

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