2 // PukiWiki - Yet another WikiWikiWeb clone.
3 // $Id: file.php,v 1.95 2011/01/25 15:01:01 henoheno Exp $
5 // 2002-2006 PukiWiki Developers 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');
18 // Get source(wiki text) data of the page
19 function get_source($page = NULL, $lock = TRUE, $join = FALSE)
21 $result = $join ? '' : array();
24 $path = get_filename($page);
27 $fp = @fopen($path, 'r');
28 if ($fp == FALSE) return $result;
34 $size = filesize($path);
36 $result = str_replace("\r", '', fread($fp, filesize($path)));
42 // Removing line-feeds: Because file() doesn't remove them.
43 $result = str_replace("\r", '', file($path));
55 // Get last-modified filetime of the page
56 function get_filetime($page)
58 return is_page($page) ? filemtime(get_filename($page)) - LOCALZONE : 0;
61 // Get physical file name of the page
62 function get_filename($page)
64 return DATA_DIR . encode($page) . '.txt';
67 // Put a data(wiki text) into a physical file(diff, backup, text)
68 function page_write($page, $postdata, $notimestamp = FALSE)
70 if (PKWK_READONLY) return; // Do nothing
72 $postdata = make_str_rules($postdata);
74 // Create and write diff
75 $oldpostdata = is_page($page) ? join('', get_source($page)) : '';
76 $diffdata = do_diff($oldpostdata, $postdata);
77 file_write(DIFF_DIR, $page, $diffdata);
80 make_backup($page, $postdata == ''); // Is $postdata null?
83 file_write(DATA_DIR, $page, $postdata, $notimestamp);
88 // Modify original text with user-defined / system-defined rules
89 function make_str_rules($source)
91 global $str_rules, $fixed_heading_anchor;
93 $lines = explode("\n", $source);
94 $count = count($lines);
99 for ($i = 0; $i < $count; $i++) {
100 $line = & $lines[$i]; // Modify directly
102 // Ignore null string and preformatted texts
103 if ($line == '' || $line{0} == ' ' || $line{0} == "\t") continue;
107 if (! PKWKEXP_DISABLE_MULTILINE_PLUGIN_HACK &&
109 preg_match('/#[^{]*(\{\{+)\s*$/', $line, $matches)) {
110 // Multiline convert plugin start
112 $multiline = strlen($matches[1]); // Set specific number
115 if (! PKWKEXP_DISABLE_MULTILINE_PLUGIN_HACK &&
117 preg_match('/^\}{' . $multiline . '}\s*$/', $line)) {
118 // Multiline convert plugin end
123 if ($modify === FALSE) continue;
125 // Replace with $str_rules
126 foreach ($str_rules as $pattern => $replacement)
127 $line = preg_replace('/' . $pattern . '/', $replacement, $line);
129 // Adding fixed anchor into headings
130 if ($fixed_heading_anchor &&
131 preg_match('/^(\*{1,3}.*?)(?:\[#([A-Za-z][\w-]*)\]\s*)?$/', $line, $matches) &&
132 (! isset($matches[2]) || $matches[2] == '')) {
133 // Generate unique id
134 $anchor = generate_fixed_heading_anchor_id($matches[1]);
135 $line = rtrim($matches[1]) . ' [#' . $anchor . ']';
139 // Multiline part has no stopper
140 if (! PKWKEXP_DISABLE_MULTILINE_PLUGIN_HACK &&
141 $modify === FALSE && $multiline != 0)
142 $lines[] = str_repeat('}', $multiline);
144 return implode("\n", $lines);
148 function generate_fixed_heading_anchor_id($seed)
150 // A random alphabetic letter + 7 letters of random strings from md()
151 return chr(mt_rand(ord('a'), ord('z'))) .
152 substr(md5(uniqid(substr($seed, 0, 100), TRUE)),
156 // Read top N lines as an array
157 // (Use PHP file() function if you want to get ALL lines)
158 function file_head($file, $count = 1, $lock = TRUE, $buffer = 8192)
162 $fp = @fopen($file, 'r');
163 if ($fp === FALSE) return FALSE;
164 set_file_buffer($fp, 0);
165 if ($lock) flock($fp, LOCK_SH);
168 while (! feof($fp)) {
169 $line = fgets($fp, $buffer);
170 if ($line != FALSE) $array[] = $line;
171 if (++$index >= $count) break;
173 if ($lock) flock($fp, LOCK_UN);
174 if (! fclose($fp)) return FALSE;
180 function file_write($dir, $page, $str, $notimestamp = FALSE)
182 global $_msg_invalidiwn, $notify, $notify_diff_only, $notify_subject;
183 global $whatsdeleted, $maxshow_deleted;
185 if (PKWK_READONLY) return; // Do nothing
186 if ($dir != DATA_DIR && $dir != DIFF_DIR) die('file_write(): Invalid directory');
188 $page = strip_bracket($page);
189 $file = $dir . encode($page) . '.txt';
190 $file_exists = file_exists($file);
195 if ($dir == DATA_DIR && $str === '') {
197 if (! $file_exists) return; // Ignore null posting for DATA_DIR
199 // Update RecentDeleted (Add the $page)
200 add_recent($page, $whatsdeleted, '', $maxshow_deleted);
205 // Update RecentDeleted, and remove the page from RecentChanges
206 lastmodified_add($whatsdeleted, $page);
208 // Clear is_page() cache
209 is_page($page, TRUE);
213 } else if ($dir == DIFF_DIR && $str === " \n") {
214 return; // Ignore null posting for DIFF_DIR
218 // File replacement (Edit)
220 if (! is_pagename($page))
221 die_message(str_replace('$1', htmlsc($page),
222 str_replace('$2', 'WikiName', $_msg_invalidiwn)));
224 $str = rtrim(preg_replace('/' . "\r" . '/', '', $str)) . "\n";
225 $timestamp = ($file_exists && $notimestamp) ? filemtime($file) : FALSE;
227 $fp = fopen($file, 'a') or die('fopen() failed: ' .
228 htmlsc(basename($dir) . '/' . encode($page) . '.txt') .
230 'Maybe permission is not writable or filename is too long');
231 set_file_buffer($fp, 0);
239 if ($timestamp) pkwk_touch_file($file, $timestamp);
242 if ($dir == DATA_DIR) {
243 // Update RecentChanges (Add or renew the $page)
244 if ($timestamp === FALSE) lastmodified_add($page);
246 // Command execution per update
247 if (defined('PKWK_UPDATE_EXEC') && PKWK_UPDATE_EXEC)
248 system(PKWK_UPDATE_EXEC . ' > /dev/null &');
250 } else if ($dir == DIFF_DIR && $notify) {
251 if ($notify_diff_only) $str = preg_replace('/^[^-+].*\n/m', '', $str);
252 $footer['ACTION'] = 'Page update';
253 $footer['PAGE'] = & $page;
254 $footer['URI'] = get_script_uri() . '?' . rawurlencode($page);
255 $footer['USER_AGENT'] = TRUE;
256 $footer['REMOTE_ADDR'] = TRUE;
257 pkwk_mail_notify($notify_subject, $str, $footer) or
258 die('pkwk_mail_notify(): Failed');
261 is_page($page, TRUE); // Clear is_page() cache
264 // Update RecentDeleted
265 function add_recent($page, $recentpage, $subject = '', $limit = 0)
267 if (PKWK_READONLY || $limit == 0 || $page == '' || $recentpage == '' ||
268 check_non_list($page)) return;
271 $lines = $matches = array();
272 foreach (get_source($recentpage) as $line)
273 if (preg_match('/^-(.+) - (\[\[.+\]\])$/', $line, $matches))
274 $lines[$matches[2]] = $line;
276 $_page = '[[' . $page . ']]';
278 // Remove a report about the same page
279 if (isset($lines[$_page])) unset($lines[$_page]);
282 array_unshift($lines, '-' . format_date(UTIME) . ' - ' . $_page .
283 htmlsc($subject) . "\n");
285 // Get latest $limit reports
286 $lines = array_splice($lines, 0, $limit);
289 $fp = fopen(get_filename($recentpage), 'w') or
290 die_message('Cannot write page file ' .
291 htmlsc($recentpage) .
292 '<br />Maybe permission is not writable or filename is too long');
293 set_file_buffer($fp, 0);
296 fputs($fp, '#freeze' . "\n");
297 fputs($fp, '#norelated' . "\n"); // :)
298 fputs($fp, join('', $lines));
303 // Update PKWK_MAXSHOW_CACHE itself (Add or renew about the $page) (Light)
304 // Use without $autolink
305 function lastmodified_add($update = '', $remove = '')
307 global $maxshow, $whatsnew, $autolink;
309 // AutoLink implimentation needs everything, for now
311 put_lastmodified(); // Try to (re)create ALL
315 if (($update == '' || check_non_list($update)) && $remove == '')
318 $file = CACHE_DIR . PKWK_MAXSHOW_CACHE;
319 if (! file_exists($file)) {
320 put_lastmodified(); // Try to (re)create ALL
325 pkwk_touch_file($file);
326 $fp = fopen($file, 'r+') or
327 die_message('Cannot open ' . 'CACHE_DIR/' . PKWK_MAXSHOW_CACHE);
328 set_file_buffer($fp, 0);
331 // Read (keep the order of the lines)
332 $recent_pages = $matches = array();
333 foreach(file_head($file, $maxshow + PKWK_MAXSHOW_ALLOWANCE, FALSE) as $line)
334 if (preg_match('/^([0-9]+)\t(.+)/', $line, $matches))
335 $recent_pages[$matches[2]] = $matches[1];
337 // Remove if it exists inside
338 if (isset($recent_pages[$update])) unset($recent_pages[$update]);
339 if (isset($recent_pages[$remove])) unset($recent_pages[$remove]);
341 // Add to the top: like array_unshift()
343 $recent_pages = array($update => get_filetime($update)) + $recent_pages;
346 $abort = count($recent_pages) < $maxshow;
352 foreach ($recent_pages as $_page=>$time)
353 fputs($fp, $time . "\t" . $_page . "\n");
360 put_lastmodified(); // Try to (re)create ALL
367 // Update the page 'RecentChanges'
369 $recent_pages = array_splice($recent_pages, 0, $maxshow);
370 $file = get_filename($whatsnew);
373 pkwk_touch_file($file);
374 $fp = fopen($file, 'r+') or
375 die_message('Cannot open ' . htmlsc($whatsnew));
376 set_file_buffer($fp, 0);
382 foreach ($recent_pages as $_page=>$time)
383 fputs($fp, '-' . htmlsc(format_date($time)) .
384 ' - ' . '[[' . htmlsc($_page) . ']]' . "\n");
385 fputs($fp, '#norelated' . "\n"); // :)
391 // Re-create PKWK_MAXSHOW_CACHE (Heavy)
392 function put_lastmodified()
394 global $maxshow, $whatsnew, $autolink;
396 if (PKWK_READONLY) return; // Do nothing
398 // Get WHOLE page list
399 $pages = get_existpages();
401 // Check ALL filetime
402 $recent_pages = array();
403 foreach($pages as $page)
404 if ($page != $whatsnew && ! check_non_list($page))
405 $recent_pages[$page] = get_filetime($page);
407 // Sort decending order of last-modification date
408 arsort($recent_pages, SORT_NUMERIC);
411 // BugTrack2/179: array_splice() will break integer keys in hashtable
412 $count = $maxshow + PKWK_MAXSHOW_ALLOWANCE;
414 foreach($recent_pages as $key=>$value) {
415 unset($recent_pages[$key]);
416 $_recent[$key] = $value;
417 if (--$count < 1) break;
419 $recent_pages = & $_recent;
421 // Re-create PKWK_MAXSHOW_CACHE
422 $file = CACHE_DIR . PKWK_MAXSHOW_CACHE;
423 pkwk_touch_file($file);
424 $fp = fopen($file, 'r+') or
425 die_message('Cannot open' . 'CACHE_DIR/' . PKWK_MAXSHOW_CACHE);
426 set_file_buffer($fp, 0);
430 foreach ($recent_pages as $page=>$time)
431 fputs($fp, $time . "\t" . $page . "\n");
435 // Create RecentChanges
436 $file = get_filename($whatsnew);
437 pkwk_touch_file($file);
438 $fp = fopen($file, 'r+') or
439 die_message('Cannot open ' . htmlsc($whatsnew));
440 set_file_buffer($fp, 0);
444 foreach (array_keys($recent_pages) as $page) {
445 $time = $recent_pages[$page];
446 $s_lastmod = htmlsc(format_date($time));
447 $s_page = htmlsc($page);
448 fputs($fp, '-' . $s_lastmod . ' - [[' . $s_page . ']]' . "\n");
450 fputs($fp, '#norelated' . "\n"); // :)
456 list($pattern, $pattern_a, $forceignorelist) =
457 get_autolink_pattern($pages);
459 $file = CACHE_DIR . PKWK_AUTOLINK_REGEX_CACHE;
460 pkwk_touch_file($file);
461 $fp = fopen($file, 'r+') or
462 die_message('Cannot open ' . 'CACHE_DIR/' . PKWK_AUTOLINK_REGEX_CACHE);
463 set_file_buffer($fp, 0);
467 fputs($fp, $pattern . "\n");
468 fputs($fp, $pattern_a . "\n");
469 fputs($fp, join("\t", $forceignorelist) . "\n");
475 // Get elapsed date of the page
476 function get_pg_passage($page, $sw = TRUE)
478 global $show_passage;
479 if (! $show_passage) return '';
481 $time = get_filetime($page);
482 $pg_passage = ($time != 0) ? get_passage($time) : '';
484 return $sw ? '<small>' . $pg_passage . '</small>' : ' ' . $pg_passage;
487 // Last-Modified header
488 function header_lastmod($page = NULL)
492 if ($lastmod && is_page($page)) {
494 header('Last-Modified: ' .
495 date('D, d M Y H:i:s', get_filetime($page)) . ' GMT');
499 // Get a page list of this wiki
500 function get_existpages($dir = DATA_DIR, $ext = '.txt')
504 $pattern = '((?:[0-9A-F]{2})+)';
505 if ($ext != '') $ext = preg_quote($ext, '/');
506 $pattern = '/^' . $pattern . $ext . '$/';
508 $dp = @opendir($dir) or
509 die_message($dir . ' is not found or not readable.');
511 while ($file = readdir($dp))
512 if (preg_match($pattern, $file, $matches))
513 $aryret[$file] = decode($matches[1]);
519 // Get PageReading(pronounce-annotated) data in an array()
520 function get_readings()
522 global $pagereading_enable, $pagereading_kanji2kana_converter;
523 global $pagereading_kanji2kana_encoding, $pagereading_chasen_path;
524 global $pagereading_kakasi_path, $pagereading_config_page;
525 global $pagereading_config_dict;
527 $pages = get_existpages();
530 foreach ($pages as $page)
531 $readings[$page] = '';
533 $deletedPage = FALSE;
535 foreach (get_source($pagereading_config_page) as $line) {
537 if(preg_match('/^-\[\[([^]]+)\]\]\s+(.+)$/', $line, $matches)) {
538 if(isset($readings[$matches[1]])) {
539 // This page is not clear how to be pronounced
540 $readings[$matches[1]] = $matches[2];
542 // This page seems deleted
548 // If enabled ChaSen/KAKASI execution
549 if($pagereading_enable) {
551 // Check there's non-clear-pronouncing page
552 $unknownPage = FALSE;
553 foreach ($readings as $page => $reading) {
560 // Execute ChaSen/KAKASI, and get annotation
562 switch(strtolower($pagereading_kanji2kana_converter)) {
564 if(! file_exists($pagereading_chasen_path))
565 die_message('ChaSen not found: ' . $pagereading_chasen_path);
567 $tmpfname = tempnam(realpath(CACHE_DIR), 'PageReading');
568 $fp = fopen($tmpfname, 'w') or
569 die_message('Cannot write temporary file "' . $tmpfname . '".' . "\n");
570 foreach ($readings as $page => $reading) {
571 if($reading != '') continue;
572 fputs($fp, mb_convert_encoding($page . "\n",
573 $pagereading_kanji2kana_encoding, SOURCE_ENCODING));
577 $chasen = "$pagereading_chasen_path -F %y $tmpfname";
578 $fp = popen($chasen, 'r');
581 die_message('ChaSen execution failed: ' . $chasen);
583 foreach ($readings as $page => $reading) {
584 if($reading != '') continue;
587 $line = mb_convert_encoding($line, SOURCE_ENCODING,
588 $pagereading_kanji2kana_encoding);
590 $readings[$page] = $line;
595 die_message('Temporary file can not be removed: ' . $tmpfname);
598 case 'kakasi': /*FALLTHROUGH*/
600 if(! file_exists($pagereading_kakasi_path))
601 die_message('KAKASI not found: ' . $pagereading_kakasi_path);
603 $tmpfname = tempnam(realpath(CACHE_DIR), 'PageReading');
604 $fp = fopen($tmpfname, 'w') or
605 die_message('Cannot write temporary file "' . $tmpfname . '".' . "\n");
606 foreach ($readings as $page => $reading) {
607 if($reading != '') continue;
608 fputs($fp, mb_convert_encoding($page . "\n",
609 $pagereading_kanji2kana_encoding, SOURCE_ENCODING));
613 $kakasi = "$pagereading_kakasi_path -kK -HK -JK < $tmpfname";
614 $fp = popen($kakasi, 'r');
617 die_message('KAKASI execution failed: ' . $kakasi);
620 foreach ($readings as $page => $reading) {
621 if($reading != '') continue;
624 $line = mb_convert_encoding($line, SOURCE_ENCODING,
625 $pagereading_kanji2kana_encoding);
627 $readings[$page] = $line;
632 die_message('Temporary file can not be removed: ' . $tmpfname);
636 $patterns = $replacements = $matches = array();
637 foreach (get_source($pagereading_config_dict) as $line) {
639 if(preg_match('|^ /([^/]+)/,\s*(.+)$|', $line, $matches)) {
640 $patterns[] = $matches[1];
641 $replacements[] = $matches[2];
644 foreach ($readings as $page => $reading) {
645 if($reading != '') continue;
647 $readings[$page] = $page;
648 foreach ($patterns as $no => $pattern)
649 $readings[$page] = mb_convert_kana(mb_ereg_replace($pattern,
650 $replacements[$no], $readings[$page]), 'aKCV');
655 die_message('Unknown kanji-kana converter: ' . $pagereading_kanji2kana_converter . '.');
660 if($unknownPage || $deletedPage) {
662 asort($readings, SORT_STRING); // Sort by pronouncing(alphabetical/reading) order
664 foreach ($readings as $page => $reading)
665 $body .= '-[[' . $page . ']] ' . $reading . "\n";
667 page_write($pagereading_config_page, $body);
671 // Pages that are not prounouncing-clear, return pagenames of themselves
672 foreach ($pages as $page) {
673 if($readings[$page] == '')
674 $readings[$page] = $page;
680 // Get a list of encoded files (must specify a directory and a suffix)
681 function get_existfiles($dir, $ext)
683 $pattern = '/^(?:[0-9A-F]{2})+' . preg_quote($ext, '/') . '$/';
685 $dp = @opendir($dir) or die_message($dir . ' is not found or not readable.');
686 while ($file = readdir($dp))
687 if (preg_match($pattern, $file))
688 $aryret[] = $dir . $file;
693 // Get a list of related pages of the page
694 function links_get_related($page)
696 global $vars, $related;
697 static $links = array();
699 if (isset($links[$page])) return $links[$page];
701 // If possible, merge related pages generated by make_link()
702 $links[$page] = ($page == $vars['page']) ? $related : array();
704 // Get repated pages from DB
705 $links[$page] += links_get_related_db($vars['page']);
707 return $links[$page];
710 // _If needed_, re-create the file to change/correct ownership into PHP's
711 // NOTE: Not works for Windows
712 function pkwk_chown($filename, $preserve_time = TRUE)
714 static $php_uid; // PHP's UID
716 if (! isset($php_uid)) {
717 if (extension_loaded('posix')) {
718 $php_uid = posix_getuid(); // Unix
720 $php_uid = 0; // Windows
724 // Lock for pkwk_chown()
725 $lockfile = CACHE_DIR . 'pkwk_chown.lock';
726 $flock = fopen($lockfile, 'a') or
727 die('pkwk_chown(): fopen() failed for: CACHEDIR/' .
728 basename(htmlsc($lockfile)));
729 flock($flock, LOCK_EX) or die('pkwk_chown(): flock() failed for lock');
732 $stat = stat($filename) or
733 die('pkwk_chown(): stat() failed for: ' . basename(htmlsc($filename)));
734 if ($stat[4] === $php_uid) {
735 // NOTE: Windows always here
736 $result = TRUE; // Seems the same UID. Nothing to do
738 $tmp = $filename . '.' . getmypid() . '.tmp';
740 // Lock source $filename to avoid file corruption
741 // NOTE: Not 'r+'. Don't check write permission here
742 $ffile = fopen($filename, 'r') or
743 die('pkwk_chown(): fopen() failed for: ' .
744 basename(htmlsc($filename)));
746 // Try to chown by re-creating files
748 // * touch() before copy() is for 'rw-r--r--' instead of 'rwxr-xr-x' (with umask 022).
749 // * (PHP 4 < PHP 4.2.0) touch() with the third argument is not implemented and retuns NULL and Warn.
750 // * @unlink() before rename() is for Windows but here's for Unix only
751 flock($ffile, LOCK_EX) or die('pkwk_chown(): flock() failed');
752 $result = touch($tmp) && copy($filename, $tmp) &&
753 ($preserve_time ? (touch($tmp, $stat[9], $stat[8]) || touch($tmp, $stat[9])) : TRUE) &&
754 rename($tmp, $filename);
755 flock($ffile, LOCK_UN) or die('pkwk_chown(): flock() failed');
757 fclose($ffile) or die('pkwk_chown(): fclose() failed');
759 if ($result === FALSE) @unlink($tmp);
762 // Unlock for pkwk_chown()
763 flock($flock, LOCK_UN) or die('pkwk_chown(): flock() failed for lock');
764 fclose($flock) or die('pkwk_chown(): fclose() failed for lock');
769 // touch() with trying pkwk_chown()
770 function pkwk_touch_file($filename, $time = FALSE, $atime = FALSE)
772 // Is the owner incorrected and unable to correct?
773 if (! file_exists($filename) || pkwk_chown($filename)) {
774 if ($time === FALSE) {
775 $result = touch($filename);
776 } else if ($atime === FALSE) {
777 $result = touch($filename, $time);
779 $result = touch($filename, $time, $atime);
783 die('pkwk_touch_file(): Invalid UID and (not writable for the directory or not a flie): ' .
784 htmlsc(basename($filename)));