OSDN Git Service

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