2 // PukiWiki - Yet another WikiWikiWeb clone.
3 // $Id: file.php,v 1.68 2006/05/02 01:22:56 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 $result = str_replace("\r", '', fread($fp, filesize($path)));
37 // Removing line-feeds: Because file() doesn't remove them.
38 $result = str_replace("\r", '', file($path));
50 // Get last-modified filetime of the page
51 function get_filetime($page)
53 return is_page($page) ? filemtime(get_filename($page)) - LOCALZONE : 0;
56 // Get physical file name of the page
57 function get_filename($page)
59 return DATA_DIR . encode($page) . '.txt';
62 // Put a data(wiki text) into a physical file(diff, backup, text)
63 function page_write($page, $postdata, $notimestamp = FALSE)
67 if (PKWK_READONLY) return; // Do nothing
69 $postdata = make_str_rules($postdata);
71 // Create and write diff
72 $oldpostdata = is_page($page) ? join('', get_source($page)) : '';
73 $diffdata = do_diff($oldpostdata, $postdata);
74 file_write(DIFF_DIR, $page, $diffdata);
77 make_backup($page, $postdata == ''); // Is $postdata null?
80 file_write(DATA_DIR, $page, $postdata, $notimestamp);
84 $_diff = explode("\n", $diffdata);
85 $plus = join("\n", preg_replace('/^\+/', '', preg_grep('/^\+/', $_diff)));
86 $minus = join("\n", preg_replace('/^-/', '', preg_grep('/^-/', $_diff)));
87 tb_send($page, $plus, $minus);
93 // Modify original text with user-defined / system-defined rules
94 function make_str_rules($source)
96 global $str_rules, $fixed_heading_anchor;
98 $lines = explode("\n", $source);
99 $count = count($lines);
104 for ($i = 0; $i < $count; $i++) {
105 $line = & $lines[$i]; // Modify directly
107 // Ignore null string and preformatted texts
108 if ($line == '' || $line{0} == ' ' || $line{0} == "\t") continue;
112 if (! PKWKEXP_DISABLE_MULTILINE_PLUGIN_HACK &&
114 preg_match('/#[^{]*(\{\{+)\s*$/', $line, $matches)) {
115 // Multiline convert plugin start
117 $multiline = strlen($matches[1]); // Set specific number
120 if (! PKWKEXP_DISABLE_MULTILINE_PLUGIN_HACK &&
122 preg_match('/^\}{' . $multiline . '}\s*$/', $line)) {
123 // Multiline convert plugin end
128 if ($modify === FALSE) continue;
130 // Replace with $str_rules
131 foreach ($str_rules as $pattern => $replacement)
132 $line = preg_replace('/' . $pattern . '/', $replacement, $line);
134 // Adding fixed anchor into headings
135 if ($fixed_heading_anchor &&
136 preg_match('/^(\*{1,3}.*?)(?:\[#([A-Za-z][\w-]*)\]\s*)?$/', $line, $matches) &&
137 (! isset($matches[2]) || $matches[2] == '')) {
138 // Generate unique id
139 $anchor = generate_fixed_heading_anchor_id($matches[1]);
140 $line = rtrim($matches[1]) . ' [#' . $anchor . ']';
144 // Multiline part has no stopper
145 if (! PKWKEXP_DISABLE_MULTILINE_PLUGIN_HACK &&
146 $modify === FALSE && $multiline != 0)
147 $lines[] = str_repeat('}', $multiline);
149 return implode("\n", $lines);
153 function generate_fixed_heading_anchor_id($seed)
155 // A random alphabetic letter + 7 letters of random strings from md()
156 return chr(mt_rand(ord('a'), ord('z'))) .
157 substr(md5(uniqid(substr($seed, 0, 100), TRUE)),
161 // Read top N lines as an array
162 // (Use PHP file() function if you want to get ALL lines)
163 function file_head($file, $count = 1, $lock = TRUE, $buffer = 8192)
167 $fp = @fopen($file, 'r');
168 if ($fp === FALSE) return FALSE;
169 set_file_buffer($fp, 0);
170 if ($lock) flock($fp, LOCK_SH);
173 while (! feof($fp)) {
174 $line = fgets($fp, $buffer);
175 if ($line != FALSE) $array[] = $line;
176 if (++$index >= $count) break;
178 if ($lock) flock($fp, LOCK_UN);
179 if (! fclose($fp)) return FALSE;
185 function file_write($dir, $page, $str, $notimestamp = FALSE)
187 global $_msg_invalidiwn, $notify, $notify_diff_only, $notify_subject;
188 global $whatsdeleted, $maxshow_deleted;
190 if (PKWK_READONLY) return; // Do nothing
191 if ($dir != DATA_DIR && $dir != DIFF_DIR) die('file_write(): Invalid directory');
193 $page = strip_bracket($page);
194 $file = $dir . encode($page) . '.txt';
195 $file_exists = file_exists($file);
200 if ($dir == DATA_DIR && $str === '') {
202 if (! $file_exists) return; // Ignore null posting for DATA_DIR
204 // Update RecentDeleted (Add the $page)
205 add_recent($page, $whatsdeleted, '', $maxshow_deleted);
210 // Update RecentDeleted, and remove the page from RecentChanges
211 lastmodified_add($whatsdeleted, $page);
213 // Clear is_page() cache
214 is_page($page, TRUE);
218 } else if ($dir == DIFF_DIR && $str === " \n") {
219 return; // Ignore null posting for DIFF_DIR
223 // File replacement (Edit)
225 if (! is_pagename($page))
226 die_message(str_replace('$1', htmlspecialchars($page),
227 str_replace('$2', 'WikiName', $_msg_invalidiwn)));
229 $str = rtrim(preg_replace('/' . "\r" . '/', '', $str)) . "\n";
230 $timestamp = ($file_exists && $notimestamp) ? filemtime($file) : FALSE;
232 $fp = fopen($file, 'a') or die('fopen() failed: ' .
233 htmlspecialchars(basename($dir) . '/' . encode($page) . '.txt') .
235 'Maybe permission is not writable or filename is too long');
236 set_file_buffer($fp, 0);
244 if ($timestamp) pkwk_touch_file($file, $timestamp);
247 if ($dir == DATA_DIR) {
248 // Update RecentChanges (Add or renew the $page)
249 if ($timestamp === FALSE) lastmodified_add($page);
251 // Command execution per update
252 if (defined(PKWK_UPDATE_EXEC))
253 system(PKWK_UPDATE_EXEC . ' > /dev/null &');
255 } else if ($dir == DIFF_DIR && $notify) {
256 if ($notify_diff_only) $str = preg_replace('/^[^-+].*\n/m', '', $str);
257 $footer['ACTION'] = 'Page update';
258 $footer['PAGE'] = & $page;
259 $footer['URI'] = get_script_uri() . '?' . rawurlencode($page);
260 $footer['USER_AGENT'] = TRUE;
261 $footer['REMOTE_ADDR'] = TRUE;
262 pkwk_mail_notify($notify_subject, $str, $footer) or
263 die('pkwk_mail_notify(): Failed');
266 is_page($page, TRUE); // Clear is_page() cache
269 // Update RecentDeleted
270 function add_recent($page, $recentpage, $subject = '', $limit = 0)
272 if (PKWK_READONLY || $limit == 0 || $page == '' || $recentpage == '' ||
273 check_non_list($page)) return;
276 $lines = $matches = array();
277 foreach (get_source($recentpage) as $line)
278 if (preg_match('/^-(.+) - (\[\[.+\]\])$/', $line, $matches))
279 $lines[$matches[2]] = $line;
281 $_page = '[[' . $page . ']]';
283 // Remove a report about the same page
284 if (isset($lines[$_page])) unset($lines[$_page]);
287 array_unshift($lines, '-' . format_date(UTIME) . ' - ' . $_page .
288 htmlspecialchars($subject) . "\n");
290 // Get latest $limit reports
291 $lines = array_splice($lines, 0, $limit);
294 $fp = fopen(get_filename($recentpage), 'w') or
295 die_message('Cannot write page file ' .
296 htmlspecialchars($recentpage) .
297 '<br />Maybe permission is not writable or filename is too long');
298 set_file_buffer($fp, 0);
301 fputs($fp, '#freeze' . "\n");
302 fputs($fp, '#norelated' . "\n"); // :)
303 fputs($fp, join('', $lines));
308 // Update PKWK_MAXSHOW_CACHE itself (Add or renew about the $page) (Light)
309 // Use without $autolink
310 function lastmodified_add($update = '', $remove = '')
312 global $maxshow, $whatsnew, $autolink;
314 // AutoLink implimentation needs everything, for now
316 put_lastmodified(); // Try to (re)create ALL
320 if (($update == '' || check_non_list($update)) && $remove == '')
323 $file = CACHE_DIR . PKWK_MAXSHOW_CACHE;
324 if (! file_exists($file)) {
325 put_lastmodified(); // Try to (re)create ALL
330 pkwk_touch_file($file);
331 $fp = fopen($file, 'r+') or
332 die_message('Cannot open ' . 'CACHE_DIR/' . PKWK_MAXSHOW_CACHE);
333 set_file_buffer($fp, 0);
336 // Read (keep the order of the lines)
337 $recent_pages = $matches = array();
338 foreach(file_head($file, $maxshow + PKWK_MAXSHOW_ALLOWANCE, FALSE) as $line)
339 if (preg_match('/^([0-9]+)\t(.+)/', $line, $matches))
340 $recent_pages[$matches[2]] = $matches[1];
342 // Remove if it exists inside
343 if (isset($recent_pages[$update])) unset($recent_pages[$update]);
344 if (isset($recent_pages[$remove])) unset($recent_pages[$remove]);
346 // Add to the top: like array_unshift()
348 $recent_pages = array($update => get_filetime($update)) + $recent_pages;
351 $abort = count($recent_pages) < $maxshow;
357 foreach ($recent_pages as $_page=>$time)
358 fputs($fp, $time . "\t" . $_page . "\n");
365 put_lastmodified(); // Try to (re)create ALL
372 // Update the page 'RecentChanges'
374 $recent_pages = array_splice($recent_pages, 0, $maxshow);
375 $file = get_filename($whatsnew);
378 pkwk_touch_file($file);
379 $fp = fopen($file, 'r+') or
380 die_message('Cannot open ' . htmlspecialchars($whatsnew));
381 set_file_buffer($fp, 0);
387 foreach ($recent_pages as $_page=>$time)
388 fputs($fp, '-' . htmlspecialchars(format_date($time)) .
389 ' - ' . '[[' . htmlspecialchars($_page) . ']]' . "\n");
390 fputs($fp, '#norelated' . "\n"); // :)
396 // Re-create PKWK_MAXSHOW_CACHE (Heavy)
397 function put_lastmodified()
399 global $maxshow, $whatsnew, $autolink;
401 if (PKWK_READONLY) return; // Do nothing
403 // Get WHOLE page list
404 $pages = get_existpages();
406 // Check ALL filetime
407 $recent_pages = array();
408 foreach($pages as $page)
409 if ($page != $whatsnew && ! check_non_list($page))
410 $recent_pages[$page] = get_filetime($page);
412 // Sort decending order of last-modification date
413 arsort($recent_pages, SORT_NUMERIC);
416 $recent_pages = array_splice($recent_pages, 0, $maxshow + PKWK_MAXSHOW_ALLOWANCE);
418 // Re-create PKWK_MAXSHOW_CACHE
419 $file = CACHE_DIR . PKWK_MAXSHOW_CACHE;
420 pkwk_touch_file($file);
421 $fp = fopen($file, 'r+') or
422 die_message('Cannot open' . 'CACHE_DIR/' . PKWK_MAXSHOW_CACHE);
423 set_file_buffer($fp, 0);
427 foreach ($recent_pages as $page=>$time)
428 fputs($fp, $time . "\t" . $page . "\n");
432 // Create RecentChanges
433 $file = get_filename($whatsnew);
434 pkwk_touch_file($file);
435 $fp = fopen($file, 'r+') or
436 die_message('Cannot open ' . htmlspecialchars($whatsnew));
437 set_file_buffer($fp, 0);
441 foreach (array_keys($recent_pages) as $page) {
442 $time = $recent_pages[$page];
443 $s_lastmod = htmlspecialchars(format_date($time));
444 $s_page = htmlspecialchars($page);
445 fputs($fp, '-' . $s_lastmod . ' - [[' . $s_page . ']]' . "\n");
447 fputs($fp, '#norelated' . "\n"); // :)
453 list($pattern, $pattern_a, $forceignorelist) =
454 get_autolink_pattern($pages);
456 $file = CACHE_DIR . PKWK_AUTOLINK_REGEX_CACHE;
457 pkwk_touch_file($file);
458 $fp = fopen($file, 'r+') or
459 die_message('Cannot open ' . 'CACHE_DIR/' . PKWK_AUTOLINK_REGEX_CACHE);
460 set_file_buffer($fp, 0);
464 fputs($fp, $pattern . "\n");
465 fputs($fp, $pattern_a . "\n");
466 fputs($fp, join("\t", $forceignorelist) . "\n");
472 // Get elapsed date of the page
473 function get_pg_passage($page, $sw = TRUE)
475 global $show_passage;
476 if (! $show_passage) return '';
478 $time = get_filetime($page);
479 $pg_passage = ($time != 0) ? get_passage($time) : '';
481 return $sw ? '<small>' . $pg_passage . '</small>' : ' ' . $pg_passage;
484 // Last-Modified header
485 function header_lastmod($page = NULL)
489 if ($lastmod && is_page($page)) {
491 header('Last-Modified: ' .
492 date('D, d M Y H:i:s', get_filetime($page)) . ' GMT');
496 // Get a page list of this wiki
497 function get_existpages($dir = DATA_DIR, $ext = '.txt')
501 $pattern = '((?:[0-9A-F]{2})+)';
502 if ($ext != '') $ext = preg_quote($ext, '/');
503 $pattern = '/^' . $pattern . $ext . '$/';
505 $dp = @opendir($dir) or
506 die_message($dir . ' is not found or not readable.');
508 while ($file = readdir($dp))
509 if (preg_match($pattern, $file, $matches))
510 $aryret[$file] = decode($matches[1]);
516 // Get PageReading(pronounce-annotated) data in an array()
517 function get_readings()
519 global $pagereading_enable, $pagereading_kanji2kana_converter;
520 global $pagereading_kanji2kana_encoding, $pagereading_chasen_path;
521 global $pagereading_kakasi_path, $pagereading_config_page;
522 global $pagereading_config_dict;
524 $pages = get_existpages();
527 foreach ($pages as $page)
528 $readings[$page] = '';
530 $deletedPage = FALSE;
532 foreach (get_source($pagereading_config_page) as $line) {
534 if(preg_match('/^-\[\[([^]]+)\]\]\s+(.+)$/', $line, $matches)) {
535 if(isset($readings[$matches[1]])) {
536 // This page is not clear how to be pronounced
537 $readings[$matches[1]] = $matches[2];
539 // This page seems deleted
545 // If enabled ChaSen/KAKASI execution
546 if($pagereading_enable) {
548 // Check there's non-clear-pronouncing page
549 $unknownPage = FALSE;
550 foreach ($readings as $page => $reading) {
557 // Execute ChaSen/KAKASI, and get annotation
559 switch(strtolower($pagereading_kanji2kana_converter)) {
561 if(! file_exists($pagereading_chasen_path))
562 die_message('ChaSen not found: ' . $pagereading_chasen_path);
564 $tmpfname = tempnam(realpath(CACHE_DIR), 'PageReading');
565 $fp = fopen($tmpfname, 'w') or
566 die_message('Cannot write temporary file "' . $tmpfname . '".' . "\n");
567 foreach ($readings as $page => $reading) {
568 if($reading != '') continue;
569 fputs($fp, mb_convert_encoding($page . "\n",
570 $pagereading_kanji2kana_encoding, SOURCE_ENCODING));
574 $chasen = "$pagereading_chasen_path -F %y $tmpfname";
575 $fp = popen($chasen, 'r');
578 die_message('ChaSen execution failed: ' . $chasen);
580 foreach ($readings as $page => $reading) {
581 if($reading != '') continue;
584 $line = mb_convert_encoding($line, SOURCE_ENCODING,
585 $pagereading_kanji2kana_encoding);
587 $readings[$page] = $line;
592 die_message('Temporary file can not be removed: ' . $tmpfname);
595 case 'kakasi': /*FALLTHROUGH*/
597 if(! file_exists($pagereading_kakasi_path))
598 die_message('KAKASI not found: ' . $pagereading_kakasi_path);
600 $tmpfname = tempnam(realpath(CACHE_DIR), 'PageReading');
601 $fp = fopen($tmpfname, 'w') or
602 die_message('Cannot write temporary file "' . $tmpfname . '".' . "\n");
603 foreach ($readings as $page => $reading) {
604 if($reading != '') continue;
605 fputs($fp, mb_convert_encoding($page . "\n",
606 $pagereading_kanji2kana_encoding, SOURCE_ENCODING));
610 $kakasi = "$pagereading_kakasi_path -kK -HK -JK < $tmpfname";
611 $fp = popen($kakasi, 'r');
614 die_message('KAKASI execution failed: ' . $kakasi);
617 foreach ($readings as $page => $reading) {
618 if($reading != '') continue;
621 $line = mb_convert_encoding($line, SOURCE_ENCODING,
622 $pagereading_kanji2kana_encoding);
624 $readings[$page] = $line;
629 die_message('Temporary file can not be removed: ' . $tmpfname);
633 $patterns = $replacements = $matches = array();
634 foreach (get_source($pagereading_config_dict) as $line) {
636 if(preg_match('|^ /([^/]+)/,\s*(.+)$|', $line, $matches)) {
637 $patterns[] = $matches[1];
638 $replacements[] = $matches[2];
641 foreach ($readings as $page => $reading) {
642 if($reading != '') continue;
644 $readings[$page] = $page;
645 foreach ($patterns as $no => $pattern)
646 $readings[$page] = mb_convert_kana(mb_ereg_replace($pattern,
647 $replacements[$no], $readings[$page]), 'aKCV');
652 die_message('Unknown kanji-kana converter: ' . $pagereading_kanji2kana_converter . '.');
657 if($unknownPage || $deletedPage) {
659 asort($readings); // Sort by pronouncing(alphabetical/reading) order
661 foreach ($readings as $page => $reading)
662 $body .= '-[[' . $page . ']] ' . $reading . "\n";
664 page_write($pagereading_config_page, $body);
668 // Pages that are not prounouncing-clear, return pagenames of themselves
669 foreach ($pages as $page) {
670 if($readings[$page] == '')
671 $readings[$page] = $page;
677 // Get a list of encoded files (must specify a directory and a suffix)
678 function get_existfiles($dir, $ext)
680 $pattern = '/^(?:[0-9A-F]{2})+' . preg_quote($ext, '/') . '$/';
682 $dp = @opendir($dir) or die_message($dir . ' is not found or not readable.');
683 while ($file = readdir($dp))
684 if (preg_match($pattern, $file))
685 $aryret[] = $dir . $file;
690 // Get a list of related pages of the page
691 function links_get_related($page)
693 global $vars, $related;
694 static $links = array();
696 if (isset($links[$page])) return $links[$page];
698 // If possible, merge related pages generated by make_link()
699 $links[$page] = ($page == $vars['page']) ? $related : array();
701 // Get repated pages from DB
702 $links[$page] += links_get_related_db($vars['page']);
704 return $links[$page];
707 // _If needed_, re-create the file to change/correct ownership into PHP's
708 // NOTE: Not works for Windows
709 function pkwk_chown($filename, $preserve_time = TRUE)
711 static $php_uid; // PHP's UID
713 if (! isset($php_uid)) {
714 if (extension_loaded('posix')) {
715 $php_uid = posix_getuid(); // Unix
717 $php_uid = 0; // Windows
721 // Lock for pkwk_chown()
722 $lockfile = CACHE_DIR . 'pkwk_chown.lock';
723 $flock = fopen($lockfile, 'a') or
724 die('pkwk_chown(): fopen() failed for: CACHEDIR/' .
725 basename(htmlspecialchars($lockfile)));
726 flock($flock, LOCK_EX) or die('pkwk_chown(): flock() failed for lock');
729 $stat = stat($filename) or
730 die('pkwk_chown(): stat() failed for: ' . basename(htmlspecialchars($filename)));
731 if ($stat[4] === $php_uid) {
732 // NOTE: Windows always here
733 $result = TRUE; // Seems the same UID. Nothing to do
735 $tmp = $filename . '.' . getmypid() . '.tmp';
737 // Lock source $filename to avoid file corruption
738 // NOTE: Not 'r+'. Don't check write permission here
739 $ffile = fopen($filename, 'r') or
740 die('pkwk_chown(): fopen() failed for: ' .
741 basename(htmlspecialchars($filename)));
743 // Try to chown by re-creating files
745 // * touch() before copy() is for 'rw-r--r--' instead of 'rwxr-xr-x' (with umask 022).
746 // * (PHP 4 < PHP 4.2.0) touch() with the third argument is not implemented and retuns NULL and Warn.
747 // * @unlink() before rename() is for Windows but here's for Unix only
748 flock($ffile, LOCK_EX) or die('pkwk_chown(): flock() failed');
749 $result = touch($tmp) && copy($filename, $tmp) &&
750 ($preserve_time ? (touch($tmp, $stat[9], $stat[8]) || touch($tmp, $stat[9])) : TRUE) &&
751 rename($tmp, $filename);
752 flock($ffile, LOCK_UN) or die('pkwk_chown(): flock() failed');
754 fclose($ffile) or die('pkwk_chown(): fclose() failed');
756 if ($result === FALSE) @unlink($tmp);
759 // Unlock for pkwk_chown()
760 flock($flock, LOCK_UN) or die('pkwk_chown(): flock() failed for lock');
761 fclose($flock) or die('pkwk_chown(): fclose() failed for lock');
766 // touch() with trying pkwk_chown()
767 function pkwk_touch_file($filename, $time = FALSE, $atime = FALSE)
769 // Is the owner incorrected and unable to correct?
770 if (! file_exists($filename) || pkwk_chown($filename)) {
771 if ($time === FALSE) {
772 $result = touch($filename);
773 } else if ($atime === FALSE) {
774 $result = touch($filename, $time);
776 $result = touch($filename, $time, $atime);
780 die('pkwk_touch_file(): Invalid UID and (not writable for the directory or not a flie): ' .
781 htmlspecialchars(basename($filename)));