2 // PukiWiki - Yet another WikiWikiWeb clone.
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
9 // File related functions
12 define('PKWK_MAXSHOW_ALLOWANCE', 10);
13 define('PKWK_MAXSHOW_CACHE', 'recent.dat');
16 define('PKWK_AUTOLINK_REGEX_CACHE', 'autolink.dat');
19 * Get source(wiki text) data of the page
21 * @param $page page name
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
27 function get_source($page = NULL, $lock = TRUE, $join = FALSE, $raw = FALSE)
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
35 $path = get_filename($page);
36 if (file_exists($path)) {
39 $fp = @fopen($path, 'r');
40 if ($fp === FALSE) return FALSE;
46 $size = filesize($path);
47 if ($size === FALSE) {
49 } else if ($size == 0) {
52 $result = fread($fp, $size);
53 if ($result !== FALSE) {
57 // Removing Carriage-Return
58 $result = str_replace("\r", '', $result);
63 $result = file($path);
64 if ($result !== FALSE) {
65 // Removing Carriage-Return
66 $result = str_replace("\r", '', $result);
79 // Get last-modified filetime of the page
80 function get_filetime($page)
82 return is_page($page) ? filemtime(get_filename($page)) - LOCALZONE : 0;
85 // Get physical file name of the page
86 function get_filename($page)
88 return DATA_DIR . encode($page) . '.txt';
91 // Put a data(wiki text) into a physical file(diff, backup, text)
92 function page_write($page, $postdata, $notimestamp = FALSE)
94 if (PKWK_READONLY) return; // Do nothing
96 $postdata = make_str_rules($postdata);
97 $timestamp_to_keep = null;
99 $timestamp_to_keep = get_filetime($page);
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);
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
112 // Create and write diff
113 $diffdata = do_diff($oldpostdata, $postdata);
114 file_write(DIFF_DIR, $page, $diffdata);
117 make_backup($page, $is_delete, $postdata); // Is $postdata null?
120 file_write(DATA_DIR, $page, $postdata, $notimestamp, $is_delete);
125 // Modify original text with user-defined / system-defined rules
126 function make_str_rules($source)
128 global $str_rules, $fixed_heading_anchor;
130 $lines = explode("\n", $source);
131 $count = count($lines);
136 for ($i = 0; $i < $count; $i++) {
137 $line = & $lines[$i]; // Modify directly
139 // Ignore null string and preformatted texts
140 if ($line == '' || $line{0} == ' ' || $line{0} == "\t") continue;
144 if (! PKWKEXP_DISABLE_MULTILINE_PLUGIN_HACK &&
146 preg_match('/#[^{]*(\{\{+)\s*$/', $line, $matches)) {
147 // Multiline convert plugin start
149 $multiline = strlen($matches[1]); // Set specific number
152 if (! PKWKEXP_DISABLE_MULTILINE_PLUGIN_HACK &&
154 preg_match('/^\}{' . $multiline . '}\s*$/', $line)) {
155 // Multiline convert plugin end
160 if ($modify === FALSE) continue;
162 // Replace with $str_rules
163 foreach ($str_rules as $pattern => $replacement)
164 $line = preg_replace('/' . $pattern . '/', $replacement, $line);
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 . ']';
176 // Multiline part has no stopper
177 if (! PKWKEXP_DISABLE_MULTILINE_PLUGIN_HACK &&
178 $modify === FALSE && $multiline != 0)
179 $lines[] = str_repeat('}', $multiline);
181 return implode("\n", $lines);
185 * Add author plugin text for wiki text body
187 * @param string $wikitext
188 * @param integer $timestamp_to_keep Set null when not to keep timestamp
190 function add_author_info($wikitext, $timestamp_to_keep)
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);
199 $datetime_to_keep = '';
200 if (!is_null($timestamp_to_keep)) {
201 $datetime_to_keep .= ';' . get_date_atom($timestamp_to_keep + LOCALZONE);
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;
212 function remove_author_info($wikitext)
214 return preg_replace('/^\s*#author\([^\n]*(\n|$)/m', '', $wikitext);
218 * Remove author line from wikitext
220 function remove_author_header($wikitext)
223 while (($pos = strpos($wikitext, "\n", $start)) != false) {
224 $line = substr($wikitext, $start, $pos);
226 if (preg_match('/^#author\(/', $line, $m)) {
227 // fond #author line, Remove this line only
229 return substr($wikitext, $pos + 1);
231 return substr($wikitext, 0, $start - 1) .
232 substr($wikitext, $pos + 1);
234 } else if (preg_match('/^#freeze(\W|$)/', $line, $m)) {
235 // Found #freeze still in header
237 // other line, #author not found
246 * Get author info from wikitext
248 function get_author_info($wikitext)
251 while (($pos = strpos($wikitext, "\n", $start)) != false) {
252 $line = substr($wikitext, $start, $pos);
254 if (preg_match('/^#author\(/', $line, $m)) {
256 } else if (preg_match('/^#freeze(\W|$)/', $line, $m)) {
257 // Found #freeze still in header
259 // other line, #author not found
268 * Get updated datetime from author
270 function get_update_datetime_from_author($author_line) {
272 if (preg_match('/^#author\(\"([^\";]+)(?:;([^\";]+))?/', $author_line, $m)) {
282 function get_date_atom($timestamp)
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);
292 function generate_fixed_heading_anchor_id($seed)
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)),
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)
306 $fp = @fopen($file, 'r');
307 if ($fp === FALSE) return FALSE;
308 set_file_buffer($fp, 0);
309 if ($lock) flock($fp, LOCK_SH);
312 while (! feof($fp)) {
313 $line = fgets($fp, $buffer);
314 if ($line != FALSE) $array[] = $line;
315 if (++$index >= $count) break;
317 if ($lock) flock($fp, LOCK_UN);
318 if (! fclose($fp)) return FALSE;
324 function file_write($dir, $page, $str, $notimestamp = FALSE, $is_delete = FALSE)
326 global $_msg_invalidiwn, $notify, $notify_diff_only, $notify_subject;
327 global $whatsdeleted, $maxshow_deleted;
329 if (PKWK_READONLY) return; // Do nothing
330 if ($dir != DATA_DIR && $dir != DIFF_DIR) die('file_write(): Invalid directory');
332 $page = strip_bracket($page);
333 $file = $dir . encode($page) . '.txt';
334 $file_exists = file_exists($file);
339 if ($dir == DATA_DIR && $is_delete) {
341 if (! $file_exists) return; // Ignore null posting for DATA_DIR
343 // Update RecentDeleted (Add the $page)
344 add_recent($page, $whatsdeleted, '', $maxshow_deleted);
349 // Update RecentDeleted, and remove the page from RecentChanges
350 lastmodified_add($whatsdeleted, $page);
352 // Clear is_page() cache
353 is_page($page, TRUE);
357 } else if ($dir == DIFF_DIR && $str === " \n") {
358 return; // Ignore null posting for DIFF_DIR
362 // File replacement (Edit)
364 if (! is_pagename($page))
365 die_message(str_replace('$1', htmlsc($page),
366 str_replace('$2', 'WikiName', $_msg_invalidiwn)));
368 $str = rtrim(preg_replace('/' . "\r" . '/', '', $str)) . "\n";
369 $timestamp = ($file_exists && $notimestamp) ? filemtime($file) : FALSE;
371 $fp = fopen($file, 'a') or die('fopen() failed: ' .
372 htmlsc(basename($dir) . '/' . encode($page) . '.txt') .
374 'Maybe permission is not writable or filename is too long');
375 set_file_buffer($fp, 0);
383 if ($timestamp) pkwk_touch_file($file, $timestamp);
386 if ($dir == DATA_DIR) {
387 // Update RecentChanges (Add or renew the $page)
388 if ($timestamp === FALSE) lastmodified_add($page);
390 // Command execution per update
391 if (defined('PKWK_UPDATE_EXEC') && PKWK_UPDATE_EXEC)
392 system(PKWK_UPDATE_EXEC . ' > /dev/null &');
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');
404 if ($dir === DIFF_DIR) {
405 pkwk_log_updates($page, $str);
407 is_page($page, TRUE); // Clear is_page() cache
410 // Update RecentDeleted
411 function add_recent($page, $recentpage, $subject = '', $limit = 0)
413 if (PKWK_READONLY || $limit == 0 || $page == '' || $recentpage == '' ||
414 check_non_list($page)) return;
417 $lines = $matches = array();
418 foreach (get_source($recentpage) as $line)
419 if (preg_match('/^-(.+) - (\[\[.+\]\])$/', $line, $matches))
420 $lines[$matches[2]] = $line;
422 $_page = '[[' . $page . ']]';
424 // Remove a report about the same page
425 if (isset($lines[$_page])) unset($lines[$_page]);
428 array_unshift($lines, '-' . format_date(UTIME) . ' - ' . $_page .
429 htmlsc($subject) . "\n");
431 // Get latest $limit reports
432 $lines = array_splice($lines, 0, $limit);
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);
442 fputs($fp, '#freeze' . "\n");
443 fputs($fp, '#norelated' . "\n"); // :)
444 fputs($fp, join('', $lines));
449 // Update PKWK_MAXSHOW_CACHE itself (Add or renew about the $page) (Light)
450 // Use without $autolink
451 function lastmodified_add($update = '', $remove = '')
453 global $maxshow, $whatsnew, $autolink;
455 // AutoLink implimentation needs everything, for now
457 put_lastmodified(); // Try to (re)create ALL
461 if (($update == '' || check_non_list($update)) && $remove == '')
464 $file = CACHE_DIR . PKWK_MAXSHOW_CACHE;
465 if (! file_exists($file)) {
466 put_lastmodified(); // Try to (re)create ALL
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);
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];
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]);
487 // Add to the top: like array_unshift()
489 $recent_pages = array($update => get_filetime($update)) + $recent_pages;
492 $abort = count($recent_pages) < $maxshow;
498 foreach ($recent_pages as $_page=>$time)
499 fputs($fp, $time . "\t" . $_page . "\n");
506 put_lastmodified(); // Try to (re)create ALL
513 // Update the page 'RecentChanges'
515 $recent_pages = array_splice($recent_pages, 0, $maxshow);
516 $file = get_filename($whatsnew);
519 pkwk_touch_file($file);
520 $fp = fopen($file, 'r+') or
521 die_message('Cannot open ' . htmlsc($whatsnew));
522 set_file_buffer($fp, 0);
528 foreach ($recent_pages as $_page=>$time)
529 fputs($fp, '-' . htmlsc(format_date($time)) .
530 ' - ' . '[[' . htmlsc($_page) . ']]' . "\n");
531 fputs($fp, '#norelated' . "\n"); // :)
537 // Re-create PKWK_MAXSHOW_CACHE (Heavy)
538 function put_lastmodified()
540 global $maxshow, $whatsnew, $autolink;
542 if (PKWK_READONLY) return; // Do nothing
544 // Get WHOLE page list
545 $pages = get_existpages();
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);
553 // Sort decending order of last-modification date
554 arsort($recent_pages, SORT_NUMERIC);
557 // BugTrack2/179: array_splice() will break integer keys in hashtable
558 $count = $maxshow + PKWK_MAXSHOW_ALLOWANCE;
560 foreach($recent_pages as $key=>$value) {
561 unset($recent_pages[$key]);
562 $_recent[$key] = $value;
563 if (--$count < 1) break;
565 $recent_pages = & $_recent;
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);
576 foreach ($recent_pages as $page=>$time)
577 fputs($fp, $time . "\t" . $page . "\n");
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);
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");
596 fputs($fp, '#norelated' . "\n"); // :)
602 list($pattern, $pattern_a, $forceignorelist) =
603 get_autolink_pattern($pages);
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);
613 fputs($fp, $pattern . "\n");
614 fputs($fp, $pattern_a . "\n");
615 fputs($fp, join("\t", $forceignorelist) . "\n");
624 * @return Array of (file => time)
626 function get_recent_files()
628 $recentfile = CACHE_DIR . PKWK_MAXSHOW_CACHE;
629 $lines = file($recentfile);
630 if (!$lines) return array();
632 foreach ($lines as $line) {
633 list ($time, $file) = explode("\t", rtrim($line));
634 $files[$file] = $time;
640 * Update RecentChanges page / Invalidate recent.dat
642 function delete_recent_changes_cache() {
643 $file = CACHE_DIR . PKWK_MAXSHOW_CACHE;
647 // Get elapsed date of the page
648 function get_pg_passage($page, $sw = TRUE)
650 global $show_passage;
651 if (! $show_passage) return '';
653 $time = get_filetime($page);
654 $pg_passage = ($time != 0) ? get_passage($time) : '';
656 return $sw ? '<small>' . $pg_passage . '</small>' : ' ' . $pg_passage;
659 // Last-Modified header
660 function header_lastmod($page = NULL)
664 if ($lastmod && is_page($page)) {
666 header('Last-Modified: ' .
667 date('D, d M Y H:i:s', get_filetime($page)) . ' GMT');
671 // Get a list of encoded files (must specify a directory and a suffix)
672 function get_existfiles($dir = DATA_DIR, $ext = '.txt')
675 $pattern = '/^(?:[0-9A-F]{2})+' . preg_quote($ext, '/') . '$/';
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;
689 * Get/Set pagelist cache enabled for get_existpages()
691 * @param $newvalue Set true when the system can cache the page list
692 * @return true if can use page list cache
694 function is_pagelist_cache_enabled($newvalue = null) {
695 static $cache_enabled = null;
697 if (!is_null($newvalue)) {
698 $cache_enabled = $newvalue;
699 return; // Return nothing on setting newvalue call
701 if (is_null($cache_enabled)) {
704 return $cache_enabled;
707 // Get a page list of this wiki
708 function get_existpages($dir = DATA_DIR, $ext = '.txt')
710 static $cached_list = null; // Cached wikitext page list
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)) {
721 $pattern = '/^((?:[0-9A-F]{2})+)' . preg_quote($ext, '/') . '$/';
722 $dp = @opendir($dir) or die_message($dir . ' is not found or not readable.');
724 while (($file = readdir($dp)) !== FALSE) {
725 if (preg_match($pattern, $file, $matches)) {
726 $aryret[$file] = decode($matches[1]);
731 $cached_list = $aryret;
736 // Get PageReading(pronounce-annotated) data in an array()
737 function get_readings()
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;
744 $pages = get_existpages();
747 foreach ($pages as $page)
748 $readings[$page] = '';
750 $deletedPage = FALSE;
752 foreach (get_source($pagereading_config_page) as $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];
759 // This page seems deleted
765 // If enabled ChaSen/KAKASI execution
766 if($pagereading_enable) {
768 // Check there's non-clear-pronouncing page
769 $unknownPage = FALSE;
770 foreach ($readings as $page => $reading) {
777 // Execute ChaSen/KAKASI, and get annotation
779 switch(strtolower($pagereading_kanji2kana_converter)) {
781 if(! file_exists($pagereading_chasen_path))
782 die_message('ChaSen not found: ' . $pagereading_chasen_path);
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));
794 $chasen = "$pagereading_chasen_path -F %y $tmpfname";
795 $fp = popen($chasen, 'r');
798 die_message('ChaSen execution failed: ' . $chasen);
800 foreach ($readings as $page => $reading) {
801 if($reading != '') continue;
804 $line = mb_convert_encoding($line, SOURCE_ENCODING,
805 $pagereading_kanji2kana_encoding);
807 $readings[$page] = $line;
812 die_message('Temporary file can not be removed: ' . $tmpfname);
815 case 'kakasi': /*FALLTHROUGH*/
817 if(! file_exists($pagereading_kakasi_path))
818 die_message('KAKASI not found: ' . $pagereading_kakasi_path);
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));
830 $kakasi = "$pagereading_kakasi_path -kK -HK -JK < $tmpfname";
831 $fp = popen($kakasi, 'r');
834 die_message('KAKASI execution failed: ' . $kakasi);
837 foreach ($readings as $page => $reading) {
838 if($reading != '') continue;
841 $line = mb_convert_encoding($line, SOURCE_ENCODING,
842 $pagereading_kanji2kana_encoding);
844 $readings[$page] = $line;
849 die_message('Temporary file can not be removed: ' . $tmpfname);
853 $patterns = $replacements = $matches = array();
854 foreach (get_source($pagereading_config_dict) as $line) {
856 if(preg_match('|^ /([^/]+)/,\s*(.+)$|', $line, $matches)) {
857 $patterns[] = $matches[1];
858 $replacements[] = $matches[2];
861 foreach ($readings as $page => $reading) {
862 if($reading != '') continue;
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');
872 die_message('Unknown kanji-kana converter: ' . $pagereading_kanji2kana_converter . '.');
877 if($unknownPage || $deletedPage) {
879 asort($readings, SORT_STRING); // Sort by pronouncing(alphabetical/reading) order
881 foreach ($readings as $page => $reading)
882 $body .= '-[[' . $page . ']] ' . $reading . "\n";
884 page_write($pagereading_config_page, $body);
888 // Pages that are not prounouncing-clear, return pagenames of themselves
889 foreach ($pages as $page) {
890 if($readings[$page] == '')
891 $readings[$page] = $page;
897 // Get a list of related pages of the page
898 function links_get_related($page)
900 global $vars, $related;
901 static $links = array();
903 if (isset($links[$page])) return $links[$page];
905 // If possible, merge related pages generated by make_link()
906 $links[$page] = ($page === $vars['page']) ? $related : array();
908 // Get repated pages from DB
909 $links[$page] += links_get_related_db($vars['page']);
911 return $links[$page];
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)
918 static $php_uid; // PHP's UID
920 if (! isset($php_uid)) {
921 if (extension_loaded('posix')) {
922 $php_uid = posix_getuid(); // Unix
924 $php_uid = 0; // Windows
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');
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
942 $tmp = $filename . '.' . getmypid() . '.tmp';
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)));
950 // Try to chown by re-creating files
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');
961 fclose($ffile) or die('pkwk_chown(): fclose() failed');
963 if ($result === FALSE) @unlink($tmp);
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');
973 // touch() with trying pkwk_chown()
974 function pkwk_touch_file($filename, $time = FALSE, $atime = FALSE)
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);
983 $result = touch($filename, $time, $atime);
987 die('pkwk_touch_file(): Invalid UID and (not writable for the directory or not a flie): ' .
988 htmlsc(basename($filename)));
993 * Lock-enabled file_get_contents
997 function pkwk_file_get_contents($filename) {
998 if (! file_exists($filename)) {
1001 $fp = fopen($filename, 'rb');
1002 flock($fp, LOCK_SH);
1003 $file = file_get_contents($filename);
1004 flock($fp, LOCK_UN);
1009 * Prepare some cache files for convert_html()
1011 * * Make cache/autolink.dat if needed
1013 function prepare_display_materials() {
1016 // Make sure 'cache/autolink.dat'
1017 $file = CACHE_DIR . PKWK_AUTOLINK_REGEX_CACHE;
1018 if (!file_exists($file)) {
1019 // Re-create autolink.dat
1026 * Prepare page related links and references for links_get_related()
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)' . '$/';
1037 $dp = @opendir($dir) or die_message('CACHE_DIR/'. ' is not found or not readable.');
1038 $rel_ref_ready = false;
1040 while (($file = readdir($dp)) !== FALSE) {
1041 if (preg_match($pattern, $file, $matches)) {
1043 $rel_ref_ready = true;
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.