OSDN Git Service

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