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;
86 * Get last-modified filemtime (plain value) of the page.
90 function get_page_date_atom($page)
93 return get_date_atom(filemtime(get_filename($page)));
98 // Get physical file name of the page
99 function get_filename($page)
101 return DATA_DIR . encode($page) . '.txt';
104 // Put a data(wiki text) into a physical file(diff, backup, text)
105 function page_write($page, $postdata, $notimestamp = FALSE)
107 if (PKWK_READONLY) return; // Do nothing
109 $postdata = make_str_rules($postdata);
110 $timestamp_to_keep = null;
112 $timestamp_to_keep = get_filetime($page);
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);
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
125 // Create and write diff
126 $diffdata = do_diff($oldpostdata, $postdata);
127 file_write(DIFF_DIR, $page, $diffdata);
130 make_backup($page, $is_delete, $postdata); // Is $postdata null?
133 file_write(DATA_DIR, $page, $postdata, $notimestamp, $is_delete);
138 // Modify original text with user-defined / system-defined rules
139 function make_str_rules($source)
141 global $str_rules, $fixed_heading_anchor;
143 $lines = explode("\n", $source);
144 $count = count($lines);
149 for ($i = 0; $i < $count; $i++) {
150 $line = & $lines[$i]; // Modify directly
152 // Ignore null string and preformatted texts
153 if ($line == '' || $line{0} == ' ' || $line{0} == "\t") continue;
157 if (! PKWKEXP_DISABLE_MULTILINE_PLUGIN_HACK &&
159 preg_match('/#[^{]*(\{\{+)\s*$/', $line, $matches)) {
160 // Multiline convert plugin start
162 $multiline = strlen($matches[1]); // Set specific number
165 if (! PKWKEXP_DISABLE_MULTILINE_PLUGIN_HACK &&
167 preg_match('/^\}{' . $multiline . '}\s*$/', $line)) {
168 // Multiline convert plugin end
173 if ($modify === FALSE) continue;
175 // Replace with $str_rules
176 foreach ($str_rules as $pattern => $replacement)
177 $line = preg_replace('/' . $pattern . '/', $replacement, $line);
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 . ']';
189 // Multiline part has no stopper
190 if (! PKWKEXP_DISABLE_MULTILINE_PLUGIN_HACK &&
191 $modify === FALSE && $multiline != 0)
192 $lines[] = str_repeat('}', $multiline);
194 return implode("\n", $lines);
198 * Add author plugin text for wiki text body
200 * @param string $wikitext
201 * @param integer $timestamp_to_keep Set null when not to keep timestamp
203 function add_author_info($wikitext, $timestamp_to_keep)
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);
212 $datetime_to_keep = '';
213 if (!is_null($timestamp_to_keep)) {
214 $datetime_to_keep .= ';' . get_date_atom($timestamp_to_keep + LOCALZONE);
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;
225 function remove_author_info($wikitext)
227 return preg_replace('/^\s*#author\([^\n]*(\n|$)/m', '', $wikitext);
231 * Remove author line from wikitext
233 function remove_author_header($wikitext)
236 while (($pos = strpos($wikitext, "\n", $start)) != false) {
237 $line = substr($wikitext, $start, $pos);
239 if (preg_match('/^#author\(/', $line, $m)) {
240 // fond #author line, Remove this line only
242 return substr($wikitext, $pos + 1);
244 return substr($wikitext, 0, $start - 1) .
245 substr($wikitext, $pos + 1);
247 } else if (preg_match('/^#freeze(\W|$)/', $line, $m)) {
248 // Found #freeze still in header
250 // other line, #author not found
259 * Get author info from wikitext
261 function get_author_info($wikitext)
264 while (($pos = strpos($wikitext, "\n", $start)) != false) {
265 $line = substr($wikitext, $start, $pos);
267 if (preg_match('/^#author\(/', $line, $m)) {
269 } else if (preg_match('/^#freeze(\W|$)/', $line, $m)) {
270 // Found #freeze still in header
272 // other line, #author not found
281 * Get updated datetime from author
283 function get_update_datetime_from_author($author_line) {
285 if (preg_match('/^#author\(\"([^\";]+)(?:;([^\";]+))?/', $author_line, $m)) {
296 function generate_fixed_heading_anchor_id($seed)
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)),
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)
310 $fp = @fopen($file, 'r');
311 if ($fp === FALSE) return FALSE;
312 set_file_buffer($fp, 0);
313 if ($lock) flock($fp, LOCK_SH);
316 while (! feof($fp)) {
317 $line = fgets($fp, $buffer);
318 if ($line != FALSE) $array[] = $line;
319 if (++$index >= $count) break;
321 if ($lock) flock($fp, LOCK_UN);
322 if (! fclose($fp)) return FALSE;
328 function file_write($dir, $page, $str, $notimestamp = FALSE, $is_delete = FALSE)
330 global $_msg_invalidiwn, $notify, $notify_diff_only, $notify_subject;
331 global $whatsdeleted, $maxshow_deleted;
333 if (PKWK_READONLY) return; // Do nothing
334 if ($dir != DATA_DIR && $dir != DIFF_DIR) die('file_write(): Invalid directory');
336 $page = strip_bracket($page);
337 $file = $dir . encode($page) . '.txt';
338 $file_exists = file_exists($file);
343 if ($dir == DATA_DIR && $is_delete) {
345 if (! $file_exists) return; // Ignore null posting for DATA_DIR
347 // Update RecentDeleted (Add the $page)
348 add_recent($page, $whatsdeleted, '', $maxshow_deleted);
353 // Update RecentDeleted, and remove the page from RecentChanges
354 lastmodified_add($whatsdeleted, $page);
356 // Clear is_page() cache
357 is_page($page, TRUE);
361 } else if ($dir == DIFF_DIR && $str === " \n") {
362 return; // Ignore null posting for DIFF_DIR
366 // File replacement (Edit)
368 if (! is_pagename($page))
369 die_message(str_replace('$1', htmlsc($page),
370 str_replace('$2', 'WikiName', $_msg_invalidiwn)));
372 $str = rtrim(preg_replace('/' . "\r" . '/', '', $str)) . "\n";
373 $timestamp = ($file_exists && $notimestamp) ? filemtime($file) : FALSE;
375 $fp = fopen($file, 'a') or die('fopen() failed: ' .
376 htmlsc(basename($dir) . '/' . encode($page) . '.txt') .
378 'Maybe permission is not writable or filename is too long');
379 set_file_buffer($fp, 0);
387 if ($timestamp) pkwk_touch_file($file, $timestamp);
390 if ($dir == DATA_DIR) {
391 // Update RecentChanges (Add or renew the $page)
392 if ($timestamp === FALSE) lastmodified_add($page);
394 // Command execution per update
395 if (defined('PKWK_UPDATE_EXEC') && PKWK_UPDATE_EXEC)
396 system(PKWK_UPDATE_EXEC . ' > /dev/null &');
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');
408 if ($dir === DIFF_DIR) {
409 pkwk_log_updates($page, $str);
411 is_page($page, TRUE); // Clear is_page() cache
414 // Update RecentDeleted
415 function add_recent($page, $recentpage, $subject = '', $limit = 0)
417 if (PKWK_READONLY || $limit == 0 || $page == '' || $recentpage == '' ||
418 check_non_list($page)) return;
421 $lines = $matches = array();
422 foreach (get_source($recentpage) as $line)
423 if (preg_match('/^-(.+) - (\[\[.+\]\])$/', $line, $matches))
424 $lines[$matches[2]] = $line;
426 $_page = '[[' . $page . ']]';
428 // Remove a report about the same page
429 if (isset($lines[$_page])) unset($lines[$_page]);
432 array_unshift($lines, '-' . format_date(UTIME) . ' - ' . $_page .
433 htmlsc($subject) . "\n");
435 // Get latest $limit reports
436 $lines = array_splice($lines, 0, $limit);
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);
446 fputs($fp, '#freeze' . "\n");
447 fputs($fp, '#norelated' . "\n"); // :)
448 fputs($fp, join('', $lines));
453 // Update PKWK_MAXSHOW_CACHE itself (Add or renew about the $page) (Light)
454 // Use without $autolink
455 function lastmodified_add($update = '', $remove = '')
457 global $maxshow, $whatsnew, $autolink;
459 // AutoLink implimentation needs everything, for now
461 put_lastmodified(); // Try to (re)create ALL
465 if (($update == '' || check_non_list($update)) && $remove == '')
468 $file = CACHE_DIR . PKWK_MAXSHOW_CACHE;
469 if (! file_exists($file)) {
470 put_lastmodified(); // Try to (re)create ALL
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);
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];
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]);
491 // Add to the top: like array_unshift()
493 $recent_pages = array($update => get_filetime($update)) + $recent_pages;
496 $abort = count($recent_pages) < $maxshow;
502 foreach ($recent_pages as $_page=>$time)
503 fputs($fp, $time . "\t" . $_page . "\n");
510 put_lastmodified(); // Try to (re)create ALL
517 // Update the page 'RecentChanges'
519 $recent_pages = array_splice($recent_pages, 0, $maxshow);
520 $file = get_filename($whatsnew);
523 pkwk_touch_file($file);
524 $fp = fopen($file, 'r+') or
525 die_message('Cannot open ' . htmlsc($whatsnew));
526 set_file_buffer($fp, 0);
532 foreach ($recent_pages as $_page=>$time)
533 fputs($fp, '-' . htmlsc(format_date($time)) .
534 ' - ' . '[[' . htmlsc($_page) . ']]' . "\n");
535 fputs($fp, '#norelated' . "\n"); // :)
541 // Re-create PKWK_MAXSHOW_CACHE (Heavy)
542 function put_lastmodified()
544 global $maxshow, $whatsnew, $autolink;
546 if (PKWK_READONLY) return; // Do nothing
548 // Get WHOLE page list
549 $pages = get_existpages();
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);
557 // Sort decending order of last-modification date
558 arsort($recent_pages, SORT_NUMERIC);
561 // BugTrack2/179: array_splice() will break integer keys in hashtable
562 $count = $maxshow + PKWK_MAXSHOW_ALLOWANCE;
564 foreach($recent_pages as $key=>$value) {
565 unset($recent_pages[$key]);
566 $_recent[$key] = $value;
567 if (--$count < 1) break;
569 $recent_pages = & $_recent;
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);
580 foreach ($recent_pages as $page=>$time)
581 fputs($fp, $time . "\t" . $page . "\n");
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);
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");
600 fputs($fp, '#norelated' . "\n"); // :)
606 list($pattern, $pattern_a, $forceignorelist) =
607 get_autolink_pattern($pages);
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);
617 fputs($fp, $pattern . "\n");
618 fputs($fp, $pattern_a . "\n");
619 fputs($fp, join("\t", $forceignorelist) . "\n");
628 * @return Array of (file => time)
630 function get_recent_files()
632 $recentfile = CACHE_DIR . PKWK_MAXSHOW_CACHE;
633 $lines = file($recentfile);
634 if (!$lines) return array();
636 foreach ($lines as $line) {
637 list ($time, $file) = explode("\t", rtrim($line));
638 $files[$file] = $time;
644 * Update RecentChanges page / Invalidate recent.dat
646 function delete_recent_changes_cache() {
647 $file = CACHE_DIR . PKWK_MAXSHOW_CACHE;
651 // Get elapsed date of the page
652 function get_pg_passage($page, $sw = TRUE)
654 global $show_passage;
655 if (! $show_passage) return '';
657 $time = get_filetime($page);
658 $pg_passage = ($time != 0) ? get_passage($time) : '';
660 return $sw ? '<small>' . $pg_passage . '</small>' : ' ' . $pg_passage;
663 // Last-Modified header
664 function header_lastmod($page = NULL)
668 if ($lastmod && is_page($page)) {
670 header('Last-Modified: ' .
671 date('D, d M Y H:i:s', get_filetime($page)) . ' GMT');
675 // Get a list of encoded files (must specify a directory and a suffix)
676 function get_existfiles($dir = DATA_DIR, $ext = '.txt')
679 $pattern = '/^(?:[0-9A-F]{2})+' . preg_quote($ext, '/') . '$/';
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;
693 * Get/Set pagelist cache enabled for get_existpages()
695 * @param $newvalue Set true when the system can cache the page list
696 * @return true if can use page list cache
698 function is_pagelist_cache_enabled($newvalue = null)
700 static $cache_enabled = null;
702 if (!is_null($newvalue)) {
703 $cache_enabled = $newvalue;
704 return; // Return nothing on setting newvalue call
706 if (is_null($cache_enabled)) {
709 return $cache_enabled;
712 // Get a page list of this wiki
713 function get_existpages($dir = DATA_DIR, $ext = '.txt')
715 static $cached_list = null; // Cached wikitext page list
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)) {
726 $pattern = '/^((?:[0-9A-F]{2})+)' . preg_quote($ext, '/') . '$/';
727 $dp = @opendir($dir) or die_message($dir . ' is not found or not readable.');
729 while (($file = readdir($dp)) !== FALSE) {
730 if (preg_match($pattern, $file, $matches)) {
731 $aryret[$file] = decode($matches[1]);
736 $cached_list = $aryret;
741 // Get PageReading(pronounce-annotated) data in an array()
742 function get_readings()
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;
749 $pages = get_existpages();
752 foreach ($pages as $page)
753 $readings[$page] = '';
755 $deletedPage = FALSE;
757 foreach (get_source($pagereading_config_page) as $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];
764 // This page seems deleted
770 // If enabled ChaSen/KAKASI execution
771 if($pagereading_enable) {
773 // Check there's non-clear-pronouncing page
774 $unknownPage = FALSE;
775 foreach ($readings as $page => $reading) {
782 // Execute ChaSen/KAKASI, and get annotation
784 switch(strtolower($pagereading_kanji2kana_converter)) {
786 if(! file_exists($pagereading_chasen_path))
787 die_message('ChaSen not found: ' . $pagereading_chasen_path);
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));
799 $chasen = "$pagereading_chasen_path -F %y $tmpfname";
800 $fp = popen($chasen, 'r');
803 die_message('ChaSen execution failed: ' . $chasen);
805 foreach ($readings as $page => $reading) {
806 if($reading != '') continue;
809 $line = mb_convert_encoding($line, SOURCE_ENCODING,
810 $pagereading_kanji2kana_encoding);
812 $readings[$page] = $line;
817 die_message('Temporary file can not be removed: ' . $tmpfname);
820 case 'kakasi': /*FALLTHROUGH*/
822 if(! file_exists($pagereading_kakasi_path))
823 die_message('KAKASI not found: ' . $pagereading_kakasi_path);
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));
835 $kakasi = "$pagereading_kakasi_path -kK -HK -JK < $tmpfname";
836 $fp = popen($kakasi, 'r');
839 die_message('KAKASI execution failed: ' . $kakasi);
842 foreach ($readings as $page => $reading) {
843 if($reading != '') continue;
846 $line = mb_convert_encoding($line, SOURCE_ENCODING,
847 $pagereading_kanji2kana_encoding);
849 $readings[$page] = $line;
854 die_message('Temporary file can not be removed: ' . $tmpfname);
858 $patterns = $replacements = $matches = array();
859 foreach (get_source($pagereading_config_dict) as $line) {
861 if(preg_match('|^ /([^/]+)/,\s*(.+)$|', $line, $matches)) {
862 $patterns[] = $matches[1];
863 $replacements[] = $matches[2];
866 foreach ($readings as $page => $reading) {
867 if($reading != '') continue;
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');
877 die_message('Unknown kanji-kana converter: ' . $pagereading_kanji2kana_converter . '.');
882 if($unknownPage || $deletedPage) {
884 asort($readings, SORT_STRING); // Sort by pronouncing(alphabetical/reading) order
886 foreach ($readings as $page => $reading)
887 $body .= '-[[' . $page . ']] ' . $reading . "\n";
889 page_write($pagereading_config_page, $body);
893 // Pages that are not prounouncing-clear, return pagenames of themselves
894 foreach ($pages as $page) {
895 if($readings[$page] == '')
896 $readings[$page] = $page;
902 // Get a list of related pages of the page
903 function links_get_related($page)
905 global $vars, $related;
906 static $links = array();
908 if (isset($links[$page])) return $links[$page];
910 // If possible, merge related pages generated by make_link()
911 $links[$page] = ($page === $vars['page']) ? $related : array();
913 // Get repated pages from DB
914 $links[$page] += links_get_related_db($vars['page']);
916 return $links[$page];
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)
923 static $php_uid; // PHP's UID
925 if (! isset($php_uid)) {
926 if (extension_loaded('posix')) {
927 $php_uid = posix_getuid(); // Unix
929 $php_uid = 0; // Windows
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');
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
947 $tmp = $filename . '.' . getmypid() . '.tmp';
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)));
955 // Try to chown by re-creating files
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');
966 fclose($ffile) or die('pkwk_chown(): fclose() failed');
968 if ($result === FALSE) @unlink($tmp);
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');
978 // touch() with trying pkwk_chown()
979 function pkwk_touch_file($filename, $time = FALSE, $atime = FALSE)
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);
988 $result = touch($filename, $time, $atime);
992 die('pkwk_touch_file(): Invalid UID and (not writable for the directory or not a flie): ' .
993 htmlsc(basename($filename)));
998 * Lock-enabled file_get_contents
1002 function pkwk_file_get_contents($filename) {
1003 if (! file_exists($filename)) {
1006 $fp = fopen($filename, 'rb');
1007 flock($fp, LOCK_SH);
1008 $file = file_get_contents($filename);
1009 flock($fp, LOCK_UN);
1014 * Prepare some cache files for convert_html()
1016 * * Make cache/autolink.dat if needed
1018 function prepare_display_materials() {
1021 // Make sure 'cache/autolink.dat'
1022 $file = CACHE_DIR . PKWK_AUTOLINK_REGEX_CACHE;
1023 if (!file_exists($file)) {
1024 // Re-create autolink.dat
1031 * Prepare page related links and references for links_get_related()
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)' . '$/';
1042 $dp = @opendir($dir) or die_message('CACHE_DIR/'. ' is not found or not readable.');
1043 $rel_ref_ready = false;
1045 while (($file = readdir($dp)) !== FALSE) {
1046 if (preg_match($pattern, $file, $matches)) {
1048 $rel_ref_ready = true;
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.