OSDN Git Service

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