OSDN Git Service

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