OSDN Git Service

BugTrack/2438 Fasten get_existpages() for ls2 and calendar_viewer
[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 /**
689  * Get/Set pagelist cache enabled for get_existpages()
690  *
691  * @param $newvalue Set true when the system can cache the page list
692  * @return true if can use page list cache
693  */
694 function is_pagelist_cache_enabled($newvalue = null) {
695         static $cache_enabled = null;
696
697         if (!is_null($newvalue)) {
698                 $cache_enabled = $newvalue;
699                 return; // Return nothing on setting newvalue call
700         }
701         if (is_null($cache_enabled)) {
702                 return false;
703         }
704         return $cache_enabled;
705 }
706
707 // Get a page list of this wiki
708 function get_existpages($dir = DATA_DIR, $ext = '.txt')
709 {
710         static $cached_list = null; // Cached wikitext page list
711         $use_cache = false;
712
713         if ($dir === DATA_DIR && $ext === '.txt' && is_pagelist_cache_enabled()) {
714                 // Use pagelist cache for "wiki/*.txt" files
715                 if (!is_null($cached_list)) {
716                         return $cached_list;
717                 }
718                 $use_cache = true;
719         }
720         $aryret = array();
721         $pattern = '/^((?:[0-9A-F]{2})+)' . preg_quote($ext, '/') . '$/';
722         $dp = @opendir($dir) or die_message($dir . ' is not found or not readable.');
723         $matches = array();
724         while (($file = readdir($dp)) !== FALSE) {
725                 if (preg_match($pattern, $file, $matches)) {
726                         $aryret[$file] = decode($matches[1]);
727                 }
728         }
729         closedir($dp);
730         if ($use_cache) {
731                 $cached_list = $aryret;
732         }
733         return $aryret;
734 }
735
736 // Get PageReading(pronounce-annotated) data in an array()
737 function get_readings()
738 {
739         global $pagereading_enable, $pagereading_kanji2kana_converter;
740         global $pagereading_kanji2kana_encoding, $pagereading_chasen_path;
741         global $pagereading_kakasi_path, $pagereading_config_page;
742         global $pagereading_config_dict;
743
744         $pages = get_existpages();
745
746         $readings = array();
747         foreach ($pages as $page) 
748                 $readings[$page] = '';
749
750         $deletedPage = FALSE;
751         $matches = array();
752         foreach (get_source($pagereading_config_page) as $line) {
753                 $line = chop($line);
754                 if(preg_match('/^-\[\[([^]]+)\]\]\s+(.+)$/', $line, $matches)) {
755                         if(isset($readings[$matches[1]])) {
756                                 // This page is not clear how to be pronounced
757                                 $readings[$matches[1]] = $matches[2];
758                         } else {
759                                 // This page seems deleted
760                                 $deletedPage = TRUE;
761                         }
762                 }
763         }
764
765         // If enabled ChaSen/KAKASI execution
766         if($pagereading_enable) {
767
768                 // Check there's non-clear-pronouncing page
769                 $unknownPage = FALSE;
770                 foreach ($readings as $page => $reading) {
771                         if($reading == '') {
772                                 $unknownPage = TRUE;
773                                 break;
774                         }
775                 }
776
777                 // Execute ChaSen/KAKASI, and get annotation
778                 if($unknownPage) {
779                         switch(strtolower($pagereading_kanji2kana_converter)) {
780                         case 'chasen':
781                                 if(! file_exists($pagereading_chasen_path))
782                                         die_message('ChaSen not found: ' . $pagereading_chasen_path);
783
784                                 $tmpfname = tempnam(realpath(CACHE_DIR), 'PageReading');
785                                 $fp = fopen($tmpfname, 'w') or
786                                         die_message('Cannot write temporary file "' . $tmpfname . '".' . "\n");
787                                 foreach ($readings as $page => $reading) {
788                                         if($reading != '') continue;
789                                         fputs($fp, mb_convert_encoding($page . "\n",
790                                                 $pagereading_kanji2kana_encoding, SOURCE_ENCODING));
791                                 }
792                                 fclose($fp);
793
794                                 $chasen = "$pagereading_chasen_path -F %y $tmpfname";
795                                 $fp     = popen($chasen, 'r');
796                                 if($fp === FALSE) {
797                                         unlink($tmpfname);
798                                         die_message('ChaSen execution failed: ' . $chasen);
799                                 }
800                                 foreach ($readings as $page => $reading) {
801                                         if($reading != '') continue;
802
803                                         $line = fgets($fp);
804                                         $line = mb_convert_encoding($line, SOURCE_ENCODING,
805                                                 $pagereading_kanji2kana_encoding);
806                                         $line = chop($line);
807                                         $readings[$page] = $line;
808                                 }
809                                 pclose($fp);
810
811                                 unlink($tmpfname) or
812                                         die_message('Temporary file can not be removed: ' . $tmpfname);
813                                 break;
814
815                         case 'kakasi':  /*FALLTHROUGH*/
816                         case 'kakashi':
817                                 if(! file_exists($pagereading_kakasi_path))
818                                         die_message('KAKASI not found: ' . $pagereading_kakasi_path);
819
820                                 $tmpfname = tempnam(realpath(CACHE_DIR), 'PageReading');
821                                 $fp       = fopen($tmpfname, 'w') or
822                                         die_message('Cannot write temporary file "' . $tmpfname . '".' . "\n");
823                                 foreach ($readings as $page => $reading) {
824                                         if($reading != '') continue;
825                                         fputs($fp, mb_convert_encoding($page . "\n",
826                                                 $pagereading_kanji2kana_encoding, SOURCE_ENCODING));
827                                 }
828                                 fclose($fp);
829
830                                 $kakasi = "$pagereading_kakasi_path -kK -HK -JK < $tmpfname";
831                                 $fp     = popen($kakasi, 'r');
832                                 if($fp === FALSE) {
833                                         unlink($tmpfname);
834                                         die_message('KAKASI execution failed: ' . $kakasi);
835                                 }
836
837                                 foreach ($readings as $page => $reading) {
838                                         if($reading != '') continue;
839
840                                         $line = fgets($fp);
841                                         $line = mb_convert_encoding($line, SOURCE_ENCODING,
842                                                 $pagereading_kanji2kana_encoding);
843                                         $line = chop($line);
844                                         $readings[$page] = $line;
845                                 }
846                                 pclose($fp);
847
848                                 unlink($tmpfname) or
849                                         die_message('Temporary file can not be removed: ' . $tmpfname);
850                                 break;
851
852                         case 'none':
853                                 $patterns = $replacements = $matches = array();
854                                 foreach (get_source($pagereading_config_dict) as $line) {
855                                         $line = chop($line);
856                                         if(preg_match('|^ /([^/]+)/,\s*(.+)$|', $line, $matches)) {
857                                                 $patterns[]     = $matches[1];
858                                                 $replacements[] = $matches[2];
859                                         }
860                                 }
861                                 foreach ($readings as $page => $reading) {
862                                         if($reading != '') continue;
863
864                                         $readings[$page] = $page;
865                                         foreach ($patterns as $no => $pattern)
866                                                 $readings[$page] = mb_convert_kana(mb_ereg_replace($pattern,
867                                                         $replacements[$no], $readings[$page]), 'aKCV');
868                                 }
869                                 break;
870
871                         default:
872                                 die_message('Unknown kanji-kana converter: ' . $pagereading_kanji2kana_converter . '.');
873                                 break;
874                         }
875                 }
876
877                 if($unknownPage || $deletedPage) {
878
879                         asort($readings, SORT_STRING); // Sort by pronouncing(alphabetical/reading) order
880                         $body = '';
881                         foreach ($readings as $page => $reading)
882                                 $body .= '-[[' . $page . ']] ' . $reading . "\n";
883
884                         page_write($pagereading_config_page, $body);
885                 }
886         }
887
888         // Pages that are not prounouncing-clear, return pagenames of themselves
889         foreach ($pages as $page) {
890                 if($readings[$page] == '')
891                         $readings[$page] = $page;
892         }
893
894         return $readings;
895 }
896
897 // Get a list of related pages of the page
898 function links_get_related($page)
899 {
900         global $vars, $related;
901         static $links = array();
902
903         if (isset($links[$page])) return $links[$page];
904
905         // If possible, merge related pages generated by make_link()
906         $links[$page] = ($page === $vars['page']) ? $related : array();
907
908         // Get repated pages from DB
909         $links[$page] += links_get_related_db($vars['page']);
910
911         return $links[$page];
912 }
913
914 // _If needed_, re-create the file to change/correct ownership into PHP's
915 // NOTE: Not works for Windows
916 function pkwk_chown($filename, $preserve_time = TRUE)
917 {
918         static $php_uid; // PHP's UID
919
920         if (! isset($php_uid)) {
921                 if (extension_loaded('posix')) {
922                         $php_uid = posix_getuid(); // Unix
923                 } else {
924                         $php_uid = 0; // Windows
925                 }
926         }
927
928         // Lock for pkwk_chown()
929         $lockfile = CACHE_DIR . 'pkwk_chown.lock';
930         $flock = fopen($lockfile, 'a') or
931                 die('pkwk_chown(): fopen() failed for: CACHEDIR/' .
932                         basename(htmlsc($lockfile)));
933         flock($flock, LOCK_EX) or die('pkwk_chown(): flock() failed for lock');
934
935         // Check owner
936         $stat = stat($filename) or
937                 die('pkwk_chown(): stat() failed for: '  . basename(htmlsc($filename)));
938         if ($stat[4] === $php_uid) {
939                 // NOTE: Windows always here
940                 $result = TRUE; // Seems the same UID. Nothing to do
941         } else {
942                 $tmp = $filename . '.' . getmypid() . '.tmp';
943
944                 // Lock source $filename to avoid file corruption
945                 // NOTE: Not 'r+'. Don't check write permission here
946                 $ffile = fopen($filename, 'r') or
947                         die('pkwk_chown(): fopen() failed for: ' .
948                                 basename(htmlsc($filename)));
949
950                 // Try to chown by re-creating files
951                 // NOTE:
952                 //   * touch() before copy() is for 'rw-r--r--' instead of 'rwxr-xr-x' (with umask 022).
953                 //   * (PHP 4 < PHP 4.2.0) touch() with the third argument is not implemented and retuns NULL and Warn.
954                 //   * @unlink() before rename() is for Windows but here's for Unix only
955                 flock($ffile, LOCK_EX) or die('pkwk_chown(): flock() failed');
956                 $result = touch($tmp) && copy($filename, $tmp) &&
957                         ($preserve_time ? (touch($tmp, $stat[9], $stat[8]) || touch($tmp, $stat[9])) : TRUE) &&
958                         rename($tmp, $filename);
959                 flock($ffile, LOCK_UN) or die('pkwk_chown(): flock() failed');
960
961                 fclose($ffile) or die('pkwk_chown(): fclose() failed');
962
963                 if ($result === FALSE) @unlink($tmp);
964         }
965
966         // Unlock for pkwk_chown()
967         flock($flock, LOCK_UN) or die('pkwk_chown(): flock() failed for lock');
968         fclose($flock) or die('pkwk_chown(): fclose() failed for lock');
969
970         return $result;
971 }
972
973 // touch() with trying pkwk_chown()
974 function pkwk_touch_file($filename, $time = FALSE, $atime = FALSE)
975 {
976         // Is the owner incorrected and unable to correct?
977         if (! file_exists($filename) || pkwk_chown($filename)) {
978                 if ($time === FALSE) {
979                         $result = touch($filename);
980                 } else if ($atime === FALSE) {
981                         $result = touch($filename, $time);
982                 } else {
983                         $result = touch($filename, $time, $atime);
984                 }
985                 return $result;
986         } else {
987                 die('pkwk_touch_file(): Invalid UID and (not writable for the directory or not a flie): ' .
988                         htmlsc(basename($filename)));
989         }
990 }
991
992 /**
993  * Lock-enabled file_get_contents
994  *
995  * Require: PHP5+
996  */
997 function pkwk_file_get_contents($filename) {
998         if (! file_exists($filename)) {
999                 return false;
1000         }
1001         $fp   = fopen($filename, 'rb');
1002         flock($fp, LOCK_SH);
1003         $file = file_get_contents($filename);
1004         flock($fp, LOCK_UN);
1005         return $file;
1006 }
1007
1008 /**
1009  * Prepare some cache files for convert_html()
1010  *
1011  * * Make cache/autolink.dat if needed
1012  */
1013 function prepare_display_materials() {
1014         global $autolink;
1015         if ($autolink) {
1016                 // Make sure 'cache/autolink.dat'
1017                 $file = CACHE_DIR . PKWK_AUTOLINK_REGEX_CACHE;
1018                 if (!file_exists($file)) {
1019                         // Re-create autolink.dat
1020                         put_lastmodified();
1021                 }
1022         }
1023 }
1024
1025 /**
1026  * Prepare page related links and references for links_get_related()
1027  */
1028 function prepare_links_related($page) {
1029         $enc_name = encode($page);
1030         $rel_file = CACHE_DIR . encode($page) . '.rel';
1031         $ref_file = CACHE_DIR . encode($page) . '.ref';
1032         if (file_exists($rel_file)) return;
1033         if (file_exists($ref_file)) return;
1034         $pattern = '/^((?:[0-9A-F]{2})+)' . '(\.ref|\.rel)' . '$/';
1035
1036         $dir = CACHE_DIR;
1037         $dp = @opendir($dir) or die_message('CACHE_DIR/'. ' is not found or not readable.');
1038         $rel_ref_ready = false;
1039         $count = 0;
1040         while (($file = readdir($dp)) !== FALSE) {
1041                 if (preg_match($pattern, $file, $matches)) {
1042                         if ($count++ > 5) {
1043                                 $rel_ref_ready = true;
1044                                 break;
1045                         }
1046                 }
1047         }
1048         closedir($dp);
1049         if (!$rel_ref_ready) {
1050                 if (count(get_existpages()) < 50) {
1051                         // Make link files automatically only if page count < 50.
1052                         // Because large number of update links will cause PHP timeout.
1053                         links_init();
1054                 }
1055         }
1056 }