2 // PukiWiki - Yet another WikiWikiWeb clone.
3 // $Id: file.php,v 1.61 2006/04/14 18:30:37 teanan 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 $result = fread($fp, filesize($path));
36 // Removing line-feeds: Because file() doesn't remove them.
37 $result = str_replace("\r", '', file($path));
49 // Get last-modified filetime of the page
50 function get_filetime($page)
52 return is_page($page) ? filemtime(get_filename($page)) - LOCALZONE : 0;
55 // Get physical file name of the page
56 function get_filename($page)
58 return DATA_DIR . encode($page) . '.txt';
61 // Put a data(wiki text) into a physical file(diff, backup, text)
62 function page_write($page, $postdata, $notimestamp = FALSE)
66 if (PKWK_READONLY) return; // Do nothing
68 $postdata = make_str_rules($postdata);
70 // Create and write diff
71 $oldpostdata = is_page($page) ? join('', get_source($page)) : '';
72 $diffdata = do_diff($oldpostdata, $postdata);
73 file_write(DIFF_DIR, $page, $diffdata);
76 make_backup($page, $postdata == ''); // Is $postdata null?
79 file_write(DATA_DIR, $page, $postdata, $notimestamp);
83 $_diff = explode("\n", $diffdata);
84 $plus = join("\n", preg_replace('/^\+/', '', preg_grep('/^\+/', $_diff)));
85 $minus = join("\n", preg_replace('/^-/', '', preg_grep('/^-/', $_diff)));
86 tb_send($page, $plus, $minus);
92 // Modify original text with user-defined / system-defined rules
93 function make_str_rules($source)
95 global $str_rules, $fixed_heading_anchor;
97 $lines = explode("\n", $source);
98 $count = count($lines);
103 for ($i = 0; $i < $count; $i++) {
104 $line = & $lines[$i]; // Modify directly
106 // Ignore null string and preformatted texts
107 if ($line == '' || $line{0} == ' ' || $line{0} == "\t") continue;
111 if (! PKWKEXP_DISABLE_MULTILINE_PLUGIN_HACK &&
113 preg_match('/#[^{]*(\{\{+)\s*$/', $line, $matches)) {
114 // Multiline convert plugin start
116 $multiline = strlen($matches[1]); // Set specific number
119 if (! PKWKEXP_DISABLE_MULTILINE_PLUGIN_HACK &&
121 preg_match('/^\}{' . $multiline . '}\s*$/', $line)) {
122 // Multiline convert plugin end
127 if ($modify === FALSE) continue;
129 // Replace with $str_rules
130 foreach ($str_rules as $pattern => $replacement)
131 $line = preg_replace('/' . $pattern . '/', $replacement, $line);
133 // Adding fixed anchor into headings
134 if ($fixed_heading_anchor &&
135 preg_match('/^(\*{1,3}.*?)(?:\[#([A-Za-z][\w-]*)\]\s*)?$/', $line, $matches) &&
136 (! isset($matches[2]) || $matches[2] == '')) {
137 // Generate unique id
138 $anchor = generate_fixed_heading_anchor_id($matches[1]);
139 $line = rtrim($matches[1]) . ' [#' . $anchor . ']';
143 // Multiline part has no stopper
144 if (! PKWKEXP_DISABLE_MULTILINE_PLUGIN_HACK &&
145 $modify === FALSE && $multiline != 0)
146 $lines[] = str_repeat('}', $multiline);
148 return implode("\n", $lines);
152 function generate_fixed_heading_anchor_id($seed)
154 // A random alphabetic letter + 7 letters of random strings from md()
155 return chr(mt_rand(ord('a'), ord('z'))) .
156 substr(md5(uniqid(substr($seed, 0, 100), TRUE)),
160 // Read top N lines as an array
161 // (Use PHP file() function if you want to get ALL lines)
162 function file_head($file, $count = 1, $lock = TRUE, $buffer = 8192)
166 $fp = @fopen($file, 'r');
167 if ($fp === FALSE) return FALSE;
168 set_file_buffer($fp, 0);
169 if ($lock) flock($fp, LOCK_SH);
172 while (! feof($fp)) {
173 $line = fgets($fp, $buffer);
174 if ($line != FALSE) $array[] = $line;
175 if (++$index >= $count) break;
177 if ($lock) flock($fp, LOCK_UN);
178 if (! fclose($fp)) return FALSE;
184 function file_write($dir, $page, $str, $notimestamp = FALSE)
186 global $update_exec, $_msg_invalidiwn, $notify, $notify_diff_only, $notify_subject;
187 global $whatsdeleted, $maxshow_deleted;
189 if (PKWK_READONLY) return; // Do nothing
190 if ($dir != DATA_DIR && $dir != DIFF_DIR) die('file_write(): Invalid directory');
192 $page = strip_bracket($page);
193 $file = $dir . encode($page) . '.txt';
194 $file_exists = file_exists($file);
199 if ($dir == DATA_DIR && $str === '') {
201 if (! $file_exists) return; // Ignore null posting for DATA_DIR
203 // Update RecentDeleted (Add the $page)
204 add_recent($page, $whatsdeleted, '', $maxshow_deleted);
208 // Update RecentChanges (Remove the $page from RecentChanges)
211 // Clear is_page() cache
212 is_page($page, TRUE);
216 } else if ($dir == DIFF_DIR && $str === " \n") {
217 return; // Ignore null posting for DIFF_DIR
221 // File replacement (Edit)
223 if (! is_pagename($page))
224 die_message(str_replace('$1', htmlspecialchars($page),
225 str_replace('$2', 'WikiName', $_msg_invalidiwn)));
227 $str = rtrim(preg_replace('/' . "\r" . '/', '', $str)) . "\n";
228 $timestamp = ($file_exists && $notimestamp) ? filemtime($file) : FALSE;
230 $fp = fopen($file, 'a') or die('fopen() failed: ' .
231 htmlspecialchars(basename($dir) . '/' . encode($page) . '.txt') .
233 'Maybe permission is not writable or filename is too long');
234 set_file_buffer($fp, 0);
242 if ($timestamp) pkwk_touch_file($file, $timestamp);
245 if ($dir == DATA_DIR) {
246 // Update RecentChanges (Add or renew the $page)
247 if ($timestamp === FALSE) lastmodified_add($page);
249 // Execute $update_exec here
250 if ($update_exec) system($update_exec . ' > /dev/null &');
252 } else if ($dir == DIFF_DIR && $notify) {
253 if ($notify_diff_only) $str = preg_replace('/^[^-+].*\n/m', '', $str);
254 $footer['ACTION'] = 'Page update';
255 $footer['PAGE'] = & $page;
256 $footer['URI'] = get_script_uri() . '?' . rawurlencode($page);
257 $footer['USER_AGENT'] = TRUE;
258 $footer['REMOTE_ADDR'] = TRUE;
259 pkwk_mail_notify($notify_subject, $str, $footer) or
260 die('pkwk_mail_notify(): Failed');
263 is_page($page, TRUE); // Clear is_page() cache
266 // Update RecentDeleted
267 function add_recent($page, $recentpage, $subject = '', $limit = 0)
269 if (PKWK_READONLY || $limit == 0 || $page == '' || $recentpage == '' ||
270 check_non_list($page)) return;
273 $lines = $matches = array();
274 foreach (get_source($recentpage) as $line)
275 if (preg_match('/^-(.+) - (\[\[.+\]\])$/', $line, $matches))
276 $lines[$matches[2]] = $line;
278 $_page = '[[' . $page . ']]';
280 // Remove a report about the same page
281 if (isset($lines[$_page])) unset($lines[$_page]);
284 array_unshift($lines, '-' . format_date(UTIME) . ' - ' . $_page .
285 htmlspecialchars($subject) . "\n");
287 // Get latest $limit reports
288 $lines = array_splice($lines, 0, $limit);
291 $fp = fopen(get_filename($recentpage), 'w') or
292 die_message('Cannot write page file ' .
293 htmlspecialchars($recentpage) .
294 '<br />Maybe permission is not writable or filename is too long');
295 set_file_buffer($fp, 0);
298 fputs($fp, '#freeze' . "\n");
299 fputs($fp, '#norelated' . "\n"); // :)
300 fputs($fp, join('', $lines));
305 // Update PKWK_MAXSHOW_CACHE itself (Add or renew about the $page) (Light)
306 // Use without $autolink
307 function lastmodified_add($page = '')
309 global $maxshow, $whatsnew, $autolink;
311 $file = CACHE_DIR . PKWK_MAXSHOW_CACHE;
312 if ($autolink || ! file_exists($file)) {
313 put_lastmodified(); // Try to (re)create ALL
318 pkwk_touch_file($file);
319 $fp = fopen($file, 'r+') or
320 die_message('Cannot open ' . 'CACHE_DIR/' . PKWK_MAXSHOW_CACHE);
321 set_file_buffer($fp, 0);
325 $recent_pages = $matches = array();
326 foreach(file_head($file, $maxshow + PKWK_MAXSHOW_ALLOWANCE, FALSE) as $line)
327 if (preg_match('/^([0-9]+)\t(.+)/', $line, $matches))
328 $recent_pages[$matches[2]] = $matches[1];
331 if (isset($recent_pages[$page])) unset($recent_pages[$page]);
333 // Add: array_unshift()
334 $recent_pages = array($page => get_filetime($page)) + $recent_pages;
339 foreach ($recent_pages as $_page=>$time)
340 fputs($fp, $time . "\t" . $_page . "\n");
347 // Update the page 'RecentChanges'
349 $recent_pages = array_splice($recent_pages, 0, $maxshow);
350 $file = get_filename($whatsnew);
353 pkwk_touch_file($file);
354 $fp = fopen($file, 'r+') or
355 die_message('Cannot open ' . htmlspecialchars($whatsnew));
356 set_file_buffer($fp, 0);
362 foreach ($recent_pages as $_page=>$time)
363 fputs($fp, '-' . htmlspecialchars(format_date($time)) .
364 ' - ' . '[[' . htmlspecialchars($_page) . ']]' . "\n");
365 fputs($fp, '#norelated' . "\n"); // :)
371 // Re-create PKWK_MAXSHOW_CACHE (Heavy)
372 function put_lastmodified()
374 global $maxshow, $whatsnew, $autolink;
376 if (PKWK_READONLY) return; // Do nothing
378 // Get WHOLE page list
379 $pages = get_existpages();
381 // Check ALL filetime
382 $recent_pages = array();
383 foreach($pages as $page)
384 if ($page != $whatsnew && ! check_non_list($page))
385 $recent_pages[$page] = get_filetime($page);
387 // Sort decending order of last-modification date
388 arsort($recent_pages, SORT_NUMERIC);
391 $recent_pages = array_splice($recent_pages, 0, $maxshow + PKWK_MAXSHOW_ALLOWANCE);
393 // Re-create PKWK_MAXSHOW_CACHE
394 $file = CACHE_DIR . PKWK_MAXSHOW_CACHE;
395 pkwk_touch_file($file);
396 $fp = fopen($file, 'r+') or
397 die_message('Cannot open' . 'CACHE_DIR/' . PKWK_MAXSHOW_CACHE);
398 set_file_buffer($fp, 0);
402 foreach ($recent_pages as $page=>$time)
403 fputs($fp, $time . "\t" . $page . "\n");
407 // Create RecentChanges
408 $file = get_filename($whatsnew);
409 pkwk_touch_file($file);
410 $fp = fopen($file, 'r+') or
411 die_message('Cannot open ' . htmlspecialchars($whatsnew));
412 set_file_buffer($fp, 0);
416 foreach (array_keys($recent_pages) as $page) {
417 $time = $recent_pages[$page];
418 $s_lastmod = htmlspecialchars(format_date($time));
419 $s_page = htmlspecialchars($page);
420 fputs($fp, '-' . $s_lastmod . ' - [[' . $s_page . ']]' . "\n");
422 fputs($fp, '#norelated' . "\n"); // :)
428 list($pattern, $pattern_a, $forceignorelist) =
429 get_autolink_pattern($pages);
431 $file = CACHE_DIR . PKWK_AUTOLINK_REGEX_CACHE;
432 pkwk_touch_file($file);
433 $fp = fopen($file, 'r+') or
434 die_message('Cannot open ' . 'CACHE_DIR/' . PKWK_AUTOLINK_REGEX_CACHE);
435 set_file_buffer($fp, 0);
439 fputs($fp, $pattern . "\n");
440 fputs($fp, $pattern_a . "\n");
441 fputs($fp, join("\t", $forceignorelist) . "\n");
447 // Get elapsed date of the page
448 function get_pg_passage($page, $sw = TRUE)
450 global $show_passage;
451 if (! $show_passage) return '';
453 $time = get_filetime($page);
454 $pg_passage = ($time != 0) ? get_passage($time) : '';
456 return $sw ? '<small>' . $pg_passage . '</small>' : ' ' . $pg_passage;
459 // Last-Modified header
460 function header_lastmod($page = NULL)
464 if ($lastmod && is_page($page)) {
466 header('Last-Modified: ' .
467 date('D, d M Y H:i:s', get_filetime($page)) . ' GMT');
471 // Get a page list of this wiki
472 function get_existpages($dir = DATA_DIR, $ext = '.txt')
476 $pattern = '((?:[0-9A-F]{2})+)';
477 if ($ext != '') $ext = preg_quote($ext, '/');
478 $pattern = '/^' . $pattern . $ext . '$/';
480 $dp = @opendir($dir) or
481 die_message($dir . ' is not found or not readable.');
483 while ($file = readdir($dp))
484 if (preg_match($pattern, $file, $matches))
485 $aryret[$file] = decode($matches[1]);
491 // Get PageReading(pronounce-annotated) data in an array()
492 function get_readings()
494 global $pagereading_enable, $pagereading_kanji2kana_converter;
495 global $pagereading_kanji2kana_encoding, $pagereading_chasen_path;
496 global $pagereading_kakasi_path, $pagereading_config_page;
497 global $pagereading_config_dict;
499 $pages = get_existpages();
502 foreach ($pages as $page)
503 $readings[$page] = '';
505 $deletedPage = FALSE;
507 foreach (get_source($pagereading_config_page) as $line) {
509 if(preg_match('/^-\[\[([^]]+)\]\]\s+(.+)$/', $line, $matches)) {
510 if(isset($readings[$matches[1]])) {
511 // This page is not clear how to be pronounced
512 $readings[$matches[1]] = $matches[2];
514 // This page seems deleted
520 // If enabled ChaSen/KAKASI execution
521 if($pagereading_enable) {
523 // Check there's non-clear-pronouncing page
524 $unknownPage = FALSE;
525 foreach ($readings as $page => $reading) {
532 // Execute ChaSen/KAKASI, and get annotation
534 switch(strtolower($pagereading_kanji2kana_converter)) {
536 if(! file_exists($pagereading_chasen_path))
537 die_message('ChaSen not found: ' . $pagereading_chasen_path);
539 $tmpfname = tempnam(realpath(CACHE_DIR), 'PageReading');
540 $fp = fopen($tmpfname, 'w') or
541 die_message('Cannot write temporary file "' . $tmpfname . '".' . "\n");
542 foreach ($readings as $page => $reading) {
543 if($reading != '') continue;
544 fputs($fp, mb_convert_encoding($page . "\n",
545 $pagereading_kanji2kana_encoding, SOURCE_ENCODING));
549 $chasen = "$pagereading_chasen_path -F %y $tmpfname";
550 $fp = popen($chasen, 'r');
553 die_message('ChaSen execution failed: ' . $chasen);
555 foreach ($readings as $page => $reading) {
556 if($reading != '') continue;
559 $line = mb_convert_encoding($line, SOURCE_ENCODING,
560 $pagereading_kanji2kana_encoding);
562 $readings[$page] = $line;
567 die_message('Temporary file can not be removed: ' . $tmpfname);
570 case 'kakasi': /*FALLTHROUGH*/
572 if(! file_exists($pagereading_kakasi_path))
573 die_message('KAKASI not found: ' . $pagereading_kakasi_path);
575 $tmpfname = tempnam(realpath(CACHE_DIR), 'PageReading');
576 $fp = fopen($tmpfname, 'w') or
577 die_message('Cannot write temporary file "' . $tmpfname . '".' . "\n");
578 foreach ($readings as $page => $reading) {
579 if($reading != '') continue;
580 fputs($fp, mb_convert_encoding($page . "\n",
581 $pagereading_kanji2kana_encoding, SOURCE_ENCODING));
585 $kakasi = "$pagereading_kakasi_path -kK -HK -JK < $tmpfname";
586 $fp = popen($kakasi, 'r');
589 die_message('KAKASI execution failed: ' . $kakasi);
592 foreach ($readings as $page => $reading) {
593 if($reading != '') continue;
596 $line = mb_convert_encoding($line, SOURCE_ENCODING,
597 $pagereading_kanji2kana_encoding);
599 $readings[$page] = $line;
604 die_message('Temporary file can not be removed: ' . $tmpfname);
608 $patterns = $replacements = $matches = array();
609 foreach (get_source($pagereading_config_dict) as $line) {
611 if(preg_match('|^ /([^/]+)/,\s*(.+)$|', $line, $matches)) {
612 $patterns[] = $matches[1];
613 $replacements[] = $matches[2];
616 foreach ($readings as $page => $reading) {
617 if($reading != '') continue;
619 $readings[$page] = $page;
620 foreach ($patterns as $no => $pattern)
621 $readings[$page] = mb_convert_kana(mb_ereg_replace($pattern,
622 $replacements[$no], $readings[$page]), 'aKCV');
627 die_message('Unknown kanji-kana converter: ' . $pagereading_kanji2kana_converter . '.');
632 if($unknownPage || $deletedPage) {
634 asort($readings); // Sort by pronouncing(alphabetical/reading) order
636 foreach ($readings as $page => $reading)
637 $body .= '-[[' . $page . ']] ' . $reading . "\n";
639 page_write($pagereading_config_page, $body);
643 // Pages that are not prounouncing-clear, return pagenames of themselves
644 foreach ($pages as $page) {
645 if($readings[$page] == '')
646 $readings[$page] = $page;
652 // Get a list of encoded files (must specify a directory and a suffix)
653 function get_existfiles($dir, $ext)
655 $pattern = '/^(?:[0-9A-F]{2})+' . preg_quote($ext, '/') . '$/';
657 $dp = @opendir($dir) or die_message($dir . ' is not found or not readable.');
658 while ($file = readdir($dp))
659 if (preg_match($pattern, $file))
660 $aryret[] = $dir . $file;
665 // Get a list of related pages of the page
666 function links_get_related($page)
668 global $vars, $related;
669 static $links = array();
671 if (isset($links[$page])) return $links[$page];
673 // If possible, merge related pages generated by make_link()
674 $links[$page] = ($page == $vars['page']) ? $related : array();
676 // Get repated pages from DB
677 $links[$page] += links_get_related_db($vars['page']);
679 return $links[$page];
682 // _If needed_, re-create the file to change/correct ownership into PHP's
683 // NOTE: Not works for Windows
684 function pkwk_chown($filename, $preserve_time = TRUE)
686 static $php_uid; // PHP's UID
688 if (! isset($php_uid)) {
689 if (extension_loaded('posix')) {
690 $php_uid = posix_getuid(); // Unix
692 $php_uid = 0; // Windows
696 // Lock for pkwk_chown()
697 $lockfile = CACHE_DIR . 'pkwk_chown.lock';
698 $flock = fopen($lockfile, 'a') or
699 die('pkwk_chown(): fopen() failed for: CACHEDIR/' .
700 basename(htmlspecialchars($lockfile)));
701 flock($flock, LOCK_EX) or die('pkwk_chown(): flock() failed for lock');
704 $stat = stat($filename) or
705 die('pkwk_chown(): stat() failed for: ' . basename(htmlspecialchars($filename)));
706 if ($stat[4] === $php_uid) {
707 // NOTE: Windows always here
708 $result = TRUE; // Seems the same UID. Nothing to do
710 $tmp = $filename . '.' . getmypid() . '.tmp';
712 // Lock source $filename to avoid file corruption
713 // NOTE: Not 'r+'. Don't check write permission here
714 $ffile = fopen($filename, 'r') or
715 die('pkwk_chown(): fopen() failed for: ' .
716 basename(htmlspecialchars($filename)));
718 // Try to chown by re-creating files
720 // * touch() before copy() is for 'rw-r--r--' instead of 'rwxr-xr-x' (with umask 022).
721 // * (PHP 4 < PHP 4.2.0) touch() with the third argument is not implemented and retuns NULL and Warn.
722 // * @unlink() before rename() is for Windows but here's for Unix only
723 flock($ffile, LOCK_EX) or die('pkwk_chown(): flock() failed');
724 $result = touch($tmp) && copy($filename, $tmp) &&
725 ($preserve_time ? (touch($tmp, $stat[9], $stat[8]) || touch($tmp, $stat[9])) : TRUE) &&
726 rename($tmp, $filename);
727 flock($ffile, LOCK_UN) or die('pkwk_chown(): flock() failed');
729 fclose($ffile) or die('pkwk_chown(): fclose() failed');
731 if ($result === FALSE) @unlink($tmp);
734 // Unlock for pkwk_chown()
735 flock($flock, LOCK_UN) or die('pkwk_chown(): flock() failed for lock');
736 fclose($flock) or die('pkwk_chown(): fclose() failed for lock');
741 // touch() with trying pkwk_chown()
742 function pkwk_touch_file($filename, $time = FALSE, $atime = FALSE)
744 // Is the owner incorrected and unable to correct?
745 if (! file_exists($filename) || pkwk_chown($filename)) {
746 if ($time === FALSE) {
747 $result = touch($filename);
748 } else if ($atime === FALSE) {
749 $result = touch($filename, $time);
751 $result = touch($filename, $time, $atime);
755 die('pkwk_touch_file(): Invalid UID and (not writable for the directory or not a flie): ' .
756 htmlspecialchars(basename($filename)));