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;
688 // Get a page list of this wiki
689 function get_existpages($dir = DATA_DIR, $ext = '.txt')
692 $pattern = '/^((?:[0-9A-F]{2})+)' . preg_quote($ext, '/') . '$/';
694 $dp = @opendir($dir) or die_message($dir . ' is not found or not readable.');
696 while (($file = readdir($dp)) !== FALSE) {
697 if (preg_match($pattern, $file, $matches)) {
698 $aryret[$file] = decode($matches[1]);
706 // Get PageReading(pronounce-annotated) data in an array()
707 function get_readings()
709 global $pagereading_enable, $pagereading_kanji2kana_converter;
710 global $pagereading_kanji2kana_encoding, $pagereading_chasen_path;
711 global $pagereading_kakasi_path, $pagereading_config_page;
712 global $pagereading_config_dict;
714 $pages = get_existpages();
717 foreach ($pages as $page)
718 $readings[$page] = '';
720 $deletedPage = FALSE;
722 foreach (get_source($pagereading_config_page) as $line) {
724 if(preg_match('/^-\[\[([^]]+)\]\]\s+(.+)$/', $line, $matches)) {
725 if(isset($readings[$matches[1]])) {
726 // This page is not clear how to be pronounced
727 $readings[$matches[1]] = $matches[2];
729 // This page seems deleted
735 // If enabled ChaSen/KAKASI execution
736 if($pagereading_enable) {
738 // Check there's non-clear-pronouncing page
739 $unknownPage = FALSE;
740 foreach ($readings as $page => $reading) {
747 // Execute ChaSen/KAKASI, and get annotation
749 switch(strtolower($pagereading_kanji2kana_converter)) {
751 if(! file_exists($pagereading_chasen_path))
752 die_message('ChaSen not found: ' . $pagereading_chasen_path);
754 $tmpfname = tempnam(realpath(CACHE_DIR), 'PageReading');
755 $fp = fopen($tmpfname, 'w') or
756 die_message('Cannot write temporary file "' . $tmpfname . '".' . "\n");
757 foreach ($readings as $page => $reading) {
758 if($reading != '') continue;
759 fputs($fp, mb_convert_encoding($page . "\n",
760 $pagereading_kanji2kana_encoding, SOURCE_ENCODING));
764 $chasen = "$pagereading_chasen_path -F %y $tmpfname";
765 $fp = popen($chasen, 'r');
768 die_message('ChaSen execution failed: ' . $chasen);
770 foreach ($readings as $page => $reading) {
771 if($reading != '') continue;
774 $line = mb_convert_encoding($line, SOURCE_ENCODING,
775 $pagereading_kanji2kana_encoding);
777 $readings[$page] = $line;
782 die_message('Temporary file can not be removed: ' . $tmpfname);
785 case 'kakasi': /*FALLTHROUGH*/
787 if(! file_exists($pagereading_kakasi_path))
788 die_message('KAKASI not found: ' . $pagereading_kakasi_path);
790 $tmpfname = tempnam(realpath(CACHE_DIR), 'PageReading');
791 $fp = fopen($tmpfname, 'w') or
792 die_message('Cannot write temporary file "' . $tmpfname . '".' . "\n");
793 foreach ($readings as $page => $reading) {
794 if($reading != '') continue;
795 fputs($fp, mb_convert_encoding($page . "\n",
796 $pagereading_kanji2kana_encoding, SOURCE_ENCODING));
800 $kakasi = "$pagereading_kakasi_path -kK -HK -JK < $tmpfname";
801 $fp = popen($kakasi, 'r');
804 die_message('KAKASI execution failed: ' . $kakasi);
807 foreach ($readings as $page => $reading) {
808 if($reading != '') continue;
811 $line = mb_convert_encoding($line, SOURCE_ENCODING,
812 $pagereading_kanji2kana_encoding);
814 $readings[$page] = $line;
819 die_message('Temporary file can not be removed: ' . $tmpfname);
823 $patterns = $replacements = $matches = array();
824 foreach (get_source($pagereading_config_dict) as $line) {
826 if(preg_match('|^ /([^/]+)/,\s*(.+)$|', $line, $matches)) {
827 $patterns[] = $matches[1];
828 $replacements[] = $matches[2];
831 foreach ($readings as $page => $reading) {
832 if($reading != '') continue;
834 $readings[$page] = $page;
835 foreach ($patterns as $no => $pattern)
836 $readings[$page] = mb_convert_kana(mb_ereg_replace($pattern,
837 $replacements[$no], $readings[$page]), 'aKCV');
842 die_message('Unknown kanji-kana converter: ' . $pagereading_kanji2kana_converter . '.');
847 if($unknownPage || $deletedPage) {
849 asort($readings, SORT_STRING); // Sort by pronouncing(alphabetical/reading) order
851 foreach ($readings as $page => $reading)
852 $body .= '-[[' . $page . ']] ' . $reading . "\n";
854 page_write($pagereading_config_page, $body);
858 // Pages that are not prounouncing-clear, return pagenames of themselves
859 foreach ($pages as $page) {
860 if($readings[$page] == '')
861 $readings[$page] = $page;
867 // Get a list of related pages of the page
868 function links_get_related($page)
870 global $vars, $related;
871 static $links = array();
873 if (isset($links[$page])) return $links[$page];
875 // If possible, merge related pages generated by make_link()
876 $links[$page] = ($page === $vars['page']) ? $related : array();
878 // Get repated pages from DB
879 $links[$page] += links_get_related_db($vars['page']);
881 return $links[$page];
884 // _If needed_, re-create the file to change/correct ownership into PHP's
885 // NOTE: Not works for Windows
886 function pkwk_chown($filename, $preserve_time = TRUE)
888 static $php_uid; // PHP's UID
890 if (! isset($php_uid)) {
891 if (extension_loaded('posix')) {
892 $php_uid = posix_getuid(); // Unix
894 $php_uid = 0; // Windows
898 // Lock for pkwk_chown()
899 $lockfile = CACHE_DIR . 'pkwk_chown.lock';
900 $flock = fopen($lockfile, 'a') or
901 die('pkwk_chown(): fopen() failed for: CACHEDIR/' .
902 basename(htmlsc($lockfile)));
903 flock($flock, LOCK_EX) or die('pkwk_chown(): flock() failed for lock');
906 $stat = stat($filename) or
907 die('pkwk_chown(): stat() failed for: ' . basename(htmlsc($filename)));
908 if ($stat[4] === $php_uid) {
909 // NOTE: Windows always here
910 $result = TRUE; // Seems the same UID. Nothing to do
912 $tmp = $filename . '.' . getmypid() . '.tmp';
914 // Lock source $filename to avoid file corruption
915 // NOTE: Not 'r+'. Don't check write permission here
916 $ffile = fopen($filename, 'r') or
917 die('pkwk_chown(): fopen() failed for: ' .
918 basename(htmlsc($filename)));
920 // Try to chown by re-creating files
922 // * touch() before copy() is for 'rw-r--r--' instead of 'rwxr-xr-x' (with umask 022).
923 // * (PHP 4 < PHP 4.2.0) touch() with the third argument is not implemented and retuns NULL and Warn.
924 // * @unlink() before rename() is for Windows but here's for Unix only
925 flock($ffile, LOCK_EX) or die('pkwk_chown(): flock() failed');
926 $result = touch($tmp) && copy($filename, $tmp) &&
927 ($preserve_time ? (touch($tmp, $stat[9], $stat[8]) || touch($tmp, $stat[9])) : TRUE) &&
928 rename($tmp, $filename);
929 flock($ffile, LOCK_UN) or die('pkwk_chown(): flock() failed');
931 fclose($ffile) or die('pkwk_chown(): fclose() failed');
933 if ($result === FALSE) @unlink($tmp);
936 // Unlock for pkwk_chown()
937 flock($flock, LOCK_UN) or die('pkwk_chown(): flock() failed for lock');
938 fclose($flock) or die('pkwk_chown(): fclose() failed for lock');
943 // touch() with trying pkwk_chown()
944 function pkwk_touch_file($filename, $time = FALSE, $atime = FALSE)
946 // Is the owner incorrected and unable to correct?
947 if (! file_exists($filename) || pkwk_chown($filename)) {
948 if ($time === FALSE) {
949 $result = touch($filename);
950 } else if ($atime === FALSE) {
951 $result = touch($filename, $time);
953 $result = touch($filename, $time, $atime);
957 die('pkwk_touch_file(): Invalid UID and (not writable for the directory or not a flie): ' .
958 htmlsc(basename($filename)));
963 * Lock-enabled file_get_contents
967 function pkwk_file_get_contents($filename) {
968 if (! file_exists($filename)) {
971 $fp = fopen($filename, 'rb');
973 $file = file_get_contents($filename);
979 * Prepare some cache files for convert_html()
981 * * Make cache/autolink.dat if needed
983 function prepare_display_materials() {
986 // Make sure 'cache/autolink.dat'
987 $file = CACHE_DIR . PKWK_AUTOLINK_REGEX_CACHE;
988 if (!file_exists($file)) {
989 // Re-create autolink.dat
996 * Prepare page related links and references for links_get_related()
998 function prepare_links_related($page) {
999 $enc_name = encode($page);
1000 $rel_file = CACHE_DIR . encode($page) . '.rel';
1001 $ref_file = CACHE_DIR . encode($page) . '.ref';
1002 if (file_exists($rel_file)) return;
1003 if (file_exists($ref_file)) return;
1004 $pattern = '/^((?:[0-9A-F]{2})+)' . '(\.ref|\.rel)' . '$/';
1007 $dp = @opendir($dir) or die_message('CACHE_DIR/'. ' is not found or not readable.');
1008 $rel_ref_ready = false;
1010 while (($file = readdir($dp)) !== FALSE) {
1011 if (preg_match($pattern, $file, $matches)) {
1013 $rel_ref_ready = true;
1019 if (!$rel_ref_ready) {
1020 if (count(get_existpages()) < 50) {
1021 // Make link files automatically only if page count < 50.
1022 // Because large number of update links will cause PHP timeout.