2 // PukiWiki - Yet another WikiWikiWeb clone.
3 // $Id: file.php,v 1.58 2006/04/11 14:31:37 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
11 define('PKWK_MAXSHOW_CACHE', 'recent.dat');
12 define('PKWK_AUTOLINK_REGEX_CACHE', 'autolink.dat');
14 // Get source(wiki text) data of the page
15 function get_source($page = NULL, $lock = TRUE)
20 $path = get_filename($page);
23 $fp = @fopen($path, 'r');
24 if ($fp == FALSE) return $array;
28 // Removing line-feeds: Because file() doesn't remove them.
29 $array = str_replace("\r", '', file($path));
40 // Get last-modified filetime of the page
41 function get_filetime($page)
43 return is_page($page) ? filemtime(get_filename($page)) - LOCALZONE : 0;
46 // Get physical file name of the page
47 function get_filename($page)
49 return DATA_DIR . encode($page) . '.txt';
52 // Put a data(wiki text) into a physical file(diff, backup, text)
53 function page_write($page, $postdata, $notimestamp = FALSE)
57 if (PKWK_READONLY) return; // Do nothing
59 $postdata = make_str_rules($postdata);
61 // Create and write diff
62 $oldpostdata = is_page($page) ? join('', get_source($page)) : '';
63 $diffdata = do_diff($oldpostdata, $postdata);
64 file_write(DIFF_DIR, $page, $diffdata);
67 make_backup($page, $postdata == ''); // Is $postdata null?
70 file_write(DATA_DIR, $page, $postdata, $notimestamp);
74 $_diff = explode("\n", $diffdata);
75 $plus = join("\n", preg_replace('/^\+/', '', preg_grep('/^\+/', $_diff)));
76 $minus = join("\n", preg_replace('/^-/', '', preg_grep('/^-/', $_diff)));
77 tb_send($page, $plus, $minus);
83 // Modify original text with user-defined / system-defined rules
84 function make_str_rules($source)
86 global $str_rules, $fixed_heading_anchor;
88 $lines = explode("\n", $source);
89 $count = count($lines);
94 for ($i = 0; $i < $count; $i++) {
95 $line = & $lines[$i]; // Modify directly
97 // Ignore null string and preformatted texts
98 if ($line == '' || $line{0} == ' ' || $line{0} == "\t") continue;
102 if (! PKWKEXP_DISABLE_MULTILINE_PLUGIN_HACK &&
104 preg_match('/#[^{]*(\{\{+)\s*$/', $line, $matches)) {
105 // Multiline convert plugin start
107 $multiline = strlen($matches[1]); // Set specific number
110 if (! PKWKEXP_DISABLE_MULTILINE_PLUGIN_HACK &&
112 preg_match('/^\}{' . $multiline . '}\s*$/', $line)) {
113 // Multiline convert plugin end
118 if ($modify === FALSE) continue;
120 // Replace with $str_rules
121 foreach ($str_rules as $pattern => $replacement)
122 $line = preg_replace('/' . $pattern . '/', $replacement, $line);
124 // Adding fixed anchor into headings
125 if ($fixed_heading_anchor &&
126 preg_match('/^(\*{1,3}.*?)(?:\[#([A-Za-z][\w-]*)\]\s*)?$/', $line, $matches) &&
127 (! isset($matches[2]) || $matches[2] == '')) {
128 // Generate unique id
129 $anchor = generate_fixed_heading_anchor_id($matches[1]);
130 $line = rtrim($matches[1]) . ' [#' . $anchor . ']';
134 // Multiline part has no stopper
135 if (! PKWKEXP_DISABLE_MULTILINE_PLUGIN_HACK &&
136 $modify === FALSE && $multiline != 0)
137 $lines[] = str_repeat('}', $multiline);
139 return implode("\n", $lines);
143 function generate_fixed_heading_anchor_id($seed)
145 // A random alphabetic letter + 7 letters of random strings from md()
146 return chr(mt_rand(ord('a'), ord('z'))) .
147 substr(md5(uniqid(substr($seed, 0, 100), TRUE)),
151 // Read top N lines as an array
152 // (Use PHP file() function if you want to get ALL lines)
153 function file_head($file, $count = 1, $lock = TRUE, $buffer = 8192)
157 $fp = @fopen($file, 'r');
158 if ($fp === FALSE) return FALSE;
159 set_file_buffer($fp, 0);
160 if ($lock) flock($fp, LOCK_SH);
163 while (! feof($fp)) {
164 $line = fgets($fp, $buffer);
165 if ($line != FALSE) $array[] = $line;
166 if (++$index >= $count) break;
168 if ($lock) flock($fp, LOCK_UN);
169 if (! fclose($fp)) return FALSE;
175 function file_write($dir, $page, $str, $notimestamp = FALSE)
177 global $update_exec, $_msg_invalidiwn, $notify, $notify_diff_only, $notify_subject;
178 global $whatsdeleted, $maxshow_deleted;
180 if (PKWK_READONLY) return; // Do nothing
181 if ($dir != DATA_DIR && $dir != DIFF_DIR) die('file_write(): Invalid directory');
183 $page = strip_bracket($page);
184 $file = $dir . encode($page) . '.txt';
185 $file_exists = file_exists($file);
190 if ($dir == DATA_DIR && $str === '') {
192 if (! $file_exists) return; // Ignore null posting for DATA_DIR
194 // Update RecentDeleted (Add the $page)
195 add_recent($page, $whatsdeleted, '', $maxshow_deleted);
199 // Update RecentChanges (Remove the $page from RecentChanges)
202 // Clear is_page() cache
203 is_page($page, TRUE);
207 } else if ($dir == DIFF_DIR && $str === " \n") {
208 return; // Ignore null posting for DIFF_DIR
212 // File replacement (Edit)
214 if (! is_pagename($page))
215 die_message(str_replace('$1', htmlspecialchars($page),
216 str_replace('$2', 'WikiName', $_msg_invalidiwn)));
218 $str = rtrim(preg_replace('/' . "\r" . '/', '', $str)) . "\n";
219 $timestamp = ($file_exists && $notimestamp) ? filemtime($file) : FALSE;
221 $fp = fopen($file, 'a') or die('fopen() failed: ' .
222 htmlspecialchars(basename($dir) . '/' . encode($page) . '.txt') .
224 'Maybe permission is not writable or filename is too long');
225 set_file_buffer($fp, 0);
233 if ($timestamp) pkwk_touch_file($file, $timestamp);
236 if ($dir == DATA_DIR) {
237 // Update RecentChanges (Add or renew the $page)
238 if ($timestamp === FALSE) put_lastmodified();
240 // Execute $update_exec here
241 if ($update_exec) system($update_exec . ' > /dev/null &');
243 } else if ($dir == DIFF_DIR && $notify) {
244 if ($notify_diff_only) $str = preg_replace('/^[^-+].*\n/m', '', $str);
245 $footer['ACTION'] = 'Page update';
246 $footer['PAGE'] = & $page;
247 $footer['URI'] = get_script_uri() . '?' . rawurlencode($page);
248 $footer['USER_AGENT'] = TRUE;
249 $footer['REMOTE_ADDR'] = TRUE;
250 pkwk_mail_notify($notify_subject, $str, $footer) or
251 die('pkwk_mail_notify(): Failed');
254 is_page($page, TRUE); // Clear is_page() cache
257 // Update RecentDeleted
258 function add_recent($page, $recentpage, $subject = '', $limit = 0)
260 if (PKWK_READONLY || $limit == 0 || $page == '' || $recentpage == '' ||
261 check_non_list($page)) return;
264 $lines = $matches = array();
265 foreach (get_source($recentpage) as $line)
266 if (preg_match('/^-(.+) - (\[\[.+\]\])$/', $line, $matches))
267 $lines[$matches[2]] = $line;
269 $_page = '[[' . $page . ']]';
271 // Remove a report about the same page
272 if (isset($lines[$_page])) unset($lines[$_page]);
275 array_unshift($lines, '-' . format_date(UTIME) . ' - ' . $_page .
276 htmlspecialchars($subject) . "\n");
278 // Get latest $limit reports
279 $lines = array_splice($lines, 0, $limit);
282 $fp = fopen(get_filename($recentpage), 'w') or
283 die_message('Cannot write page file ' .
284 htmlspecialchars($recentpage) .
285 '<br />Maybe permission is not writable or filename is too long');
286 set_file_buffer($fp, 0);
289 fputs($fp, '#freeze' . "\n");
290 fputs($fp, '#norelated' . "\n"); // :)
291 fputs($fp, join('', $lines));
296 // Re-create PKWK_MAXSHOW_CACHE
298 function put_lastmodified()
300 global $maxshow, $whatsnew, $autolink;
302 if (PKWK_READONLY) return; // Do nothing
304 // Get whole page list
305 $pages = get_existpages();
307 // Check ALL filetime
308 $recent_pages = array();
309 foreach($pages as $page)
310 if ($page != $whatsnew && ! check_non_list($page))
311 $recent_pages[$page] = get_filetime($page);
313 // Sort decending order of last-modification date
314 arsort($recent_pages, SORT_NUMERIC);
317 $recent_pages = array_splice($recent_pages, 0, $maxshow);
319 // Re-create PKWK_MAXSHOW_CACHE
320 $fp = fopen(CACHE_DIR . PKWK_MAXSHOW_CACHE, 'w') or
321 die_message('Cannot write file ' .
322 'CACHE_DIR/' . PKWK_MAXSHOW_CACHE . '<br />' . "\n" .
323 'Maybe permission is not writable');
324 set_file_buffer($fp, 0);
327 foreach ($recent_pages as $page=>$time)
328 fputs($fp, $time . "\t" . $page . "\n");
332 // Create RecentChanges
333 $fp = fopen(get_filename($whatsnew), 'w') or
334 die_message('Cannot write file ' .
335 htmlspecialchars($whatsnew) . '<br />' . "\n" .
336 'Maybe permission is not writable or filename is too long');
337 set_file_buffer($fp, 0);
340 foreach (array_keys($recent_pages) as $page) {
341 $time = $recent_pages[$page];
342 $s_lastmod = htmlspecialchars(format_date($time));
343 $s_page = htmlspecialchars($page);
344 fputs($fp, '-' . $s_lastmod . ' - [[' . $s_page . ']]' . "\n");
346 fputs($fp, '#norelated' . "\n"); // :)
352 list($pattern, $pattern_a, $forceignorelist) =
353 get_autolink_pattern($pages);
355 $fp = fopen(CACHE_DIR . PKWK_AUTOLINK_REGEX_CACHE, 'w') or
356 die_message('Cannot write file ' .
357 'CACHE_DIR/' . PKWK_AUTOLINK_REGEX_CACHE . '<br />' . "\n" .
358 'Maybe permission is not writable');
359 set_file_buffer($fp, 0);
362 fputs($fp, $pattern . "\n");
363 fputs($fp, $pattern_a . "\n");
364 fputs($fp, join("\t", $forceignorelist) . "\n");
370 // Get elapsed date of the page
371 function get_pg_passage($page, $sw = TRUE)
373 global $show_passage;
374 if (! $show_passage) return '';
376 $time = get_filetime($page);
377 $pg_passage = ($time != 0) ? get_passage($time) : '';
379 return $sw ? '<small>' . $pg_passage . '</small>' : ' ' . $pg_passage;
382 // Last-Modified header
383 function header_lastmod($page = NULL)
387 if ($lastmod && is_page($page)) {
389 header('Last-Modified: ' .
390 date('D, d M Y H:i:s', get_filetime($page)) . ' GMT');
394 // Get a page list of this wiki
395 function get_existpages($dir = DATA_DIR, $ext = '.txt')
399 $pattern = '((?:[0-9A-F]{2})+)';
400 if ($ext != '') $ext = preg_quote($ext, '/');
401 $pattern = '/^' . $pattern . $ext . '$/';
403 $dp = @opendir($dir) or
404 die_message($dir . ' is not found or not readable.');
406 while ($file = readdir($dp))
407 if (preg_match($pattern, $file, $matches))
408 $aryret[$file] = decode($matches[1]);
414 // Get PageReading(pronounce-annotated) data in an array()
415 function get_readings()
417 global $pagereading_enable, $pagereading_kanji2kana_converter;
418 global $pagereading_kanji2kana_encoding, $pagereading_chasen_path;
419 global $pagereading_kakasi_path, $pagereading_config_page;
420 global $pagereading_config_dict;
422 $pages = get_existpages();
425 foreach ($pages as $page)
426 $readings[$page] = '';
428 $deletedPage = FALSE;
430 foreach (get_source($pagereading_config_page) as $line) {
432 if(preg_match('/^-\[\[([^]]+)\]\]\s+(.+)$/', $line, $matches)) {
433 if(isset($readings[$matches[1]])) {
434 // This page is not clear how to be pronounced
435 $readings[$matches[1]] = $matches[2];
437 // This page seems deleted
443 // If enabled ChaSen/KAKASI execution
444 if($pagereading_enable) {
446 // Check there's non-clear-pronouncing page
447 $unknownPage = FALSE;
448 foreach ($readings as $page => $reading) {
455 // Execute ChaSen/KAKASI, and get annotation
457 switch(strtolower($pagereading_kanji2kana_converter)) {
459 if(! file_exists($pagereading_chasen_path))
460 die_message('ChaSen not found: ' . $pagereading_chasen_path);
462 $tmpfname = tempnam(realpath(CACHE_DIR), 'PageReading');
463 $fp = fopen($tmpfname, 'w') or
464 die_message('Cannot write temporary file "' . $tmpfname . '".' . "\n");
465 foreach ($readings as $page => $reading) {
466 if($reading != '') continue;
467 fputs($fp, mb_convert_encoding($page . "\n",
468 $pagereading_kanji2kana_encoding, SOURCE_ENCODING));
472 $chasen = "$pagereading_chasen_path -F %y $tmpfname";
473 $fp = popen($chasen, 'r');
476 die_message('ChaSen execution failed: ' . $chasen);
478 foreach ($readings as $page => $reading) {
479 if($reading != '') continue;
482 $line = mb_convert_encoding($line, SOURCE_ENCODING,
483 $pagereading_kanji2kana_encoding);
485 $readings[$page] = $line;
490 die_message('Temporary file can not be removed: ' . $tmpfname);
493 case 'kakasi': /*FALLTHROUGH*/
495 if(! file_exists($pagereading_kakasi_path))
496 die_message('KAKASI not found: ' . $pagereading_kakasi_path);
498 $tmpfname = tempnam(realpath(CACHE_DIR), 'PageReading');
499 $fp = fopen($tmpfname, 'w') or
500 die_message('Cannot write temporary file "' . $tmpfname . '".' . "\n");
501 foreach ($readings as $page => $reading) {
502 if($reading != '') continue;
503 fputs($fp, mb_convert_encoding($page . "\n",
504 $pagereading_kanji2kana_encoding, SOURCE_ENCODING));
508 $kakasi = "$pagereading_kakasi_path -kK -HK -JK < $tmpfname";
509 $fp = popen($kakasi, 'r');
512 die_message('KAKASI execution failed: ' . $kakasi);
515 foreach ($readings as $page => $reading) {
516 if($reading != '') continue;
519 $line = mb_convert_encoding($line, SOURCE_ENCODING,
520 $pagereading_kanji2kana_encoding);
522 $readings[$page] = $line;
527 die_message('Temporary file can not be removed: ' . $tmpfname);
531 $patterns = $replacements = $matches = array();
532 foreach (get_source($pagereading_config_dict) as $line) {
534 if(preg_match('|^ /([^/]+)/,\s*(.+)$|', $line, $matches)) {
535 $patterns[] = $matches[1];
536 $replacements[] = $matches[2];
539 foreach ($readings as $page => $reading) {
540 if($reading != '') continue;
542 $readings[$page] = $page;
543 foreach ($patterns as $no => $pattern)
544 $readings[$page] = mb_convert_kana(mb_ereg_replace($pattern,
545 $replacements[$no], $readings[$page]), 'aKCV');
550 die_message('Unknown kanji-kana converter: ' . $pagereading_kanji2kana_converter . '.');
555 if($unknownPage || $deletedPage) {
557 asort($readings); // Sort by pronouncing(alphabetical/reading) order
559 foreach ($readings as $page => $reading)
560 $body .= '-[[' . $page . ']] ' . $reading . "\n";
562 page_write($pagereading_config_page, $body);
566 // Pages that are not prounouncing-clear, return pagenames of themselves
567 foreach ($pages as $page) {
568 if($readings[$page] == '')
569 $readings[$page] = $page;
575 // Get a list of encoded files (must specify a directory and a suffix)
576 function get_existfiles($dir, $ext)
578 $pattern = '/^(?:[0-9A-F]{2})+' . preg_quote($ext, '/') . '$/';
580 $dp = @opendir($dir) or die_message($dir . ' is not found or not readable.');
581 while ($file = readdir($dp))
582 if (preg_match($pattern, $file))
583 $aryret[] = $dir . $file;
588 // Get a list of related pages of the page
589 function links_get_related($page)
591 global $vars, $related;
592 static $links = array();
594 if (isset($links[$page])) return $links[$page];
596 // If possible, merge related pages generated by make_link()
597 $links[$page] = ($page == $vars['page']) ? $related : array();
599 // Get repated pages from DB
600 $links[$page] += links_get_related_db($vars['page']);
602 return $links[$page];
605 // _If needed_, re-create the file to change/correct ownership into PHP's
606 // NOTE: Not works for Windows
607 function pkwk_chown($filename, $preserve_time = TRUE)
609 static $php_uid; // PHP's UID
611 if (! isset($php_uid)) {
612 if (extension_loaded('posix')) {
613 $php_uid = posix_getuid(); // Unix
615 $php_uid = 0; // Windows
619 // Lock for pkwk_chown()
620 $lockfile = CACHE_DIR . 'pkwk_chown.lock';
621 $flock = fopen($lockfile, 'a') or
622 die('pkwk_chown(): fopen() failed for: CACHEDIR/' .
623 basename(htmlspecialchars($lockfile)));
624 flock($flock, LOCK_EX) or die('pkwk_chown(): flock() failed for lock');
627 $stat = stat($filename) or
628 die('pkwk_chown(): stat() failed for: ' . basename(htmlspecialchars($filename)));
629 if ($stat[4] === $php_uid) {
630 // NOTE: Windows always here
631 $result = TRUE; // Seems the same UID. Nothing to do
633 $tmp = $filename . '.' . getmypid() . '.tmp';
635 // Lock source $filename to avoid file corruption
636 // NOTE: Not 'r+'. Don't check write permission here
637 $ffile = fopen($filename, 'r') or
638 die('pkwk_chown(): fopen() failed for: ' .
639 basename(htmlspecialchars($filename)));
641 // Try to chown by re-creating files
643 // * touch() before copy() is for 'rw-r--r--' instead of 'rwxr-xr-x' (with umask 022).
644 // * (PHP 4 < PHP 4.2.0) touch() with the third argument is not implemented and retuns NULL and Warn.
645 // * @unlink() before rename() is for Windows but here's for Unix only
646 flock($ffile, LOCK_EX) or die('pkwk_chown(): flock() failed');
647 $result = touch($tmp) && copy($filename, $tmp) &&
648 ($preserve_time ? (touch($tmp, $stat[9], $stat[8]) || touch($tmp, $stat[9])) : TRUE) &&
649 rename($tmp, $filename);
650 flock($ffile, LOCK_UN) or die('pkwk_chown(): flock() failed');
652 fclose($ffile) or die('pkwk_chown(): fclose() failed');
654 if ($result === FALSE) @unlink($tmp);
657 // Unlock for pkwk_chown()
658 flock($flock, LOCK_UN) or die('pkwk_chown(): flock() failed for lock');
659 fclose($flock) or die('pkwk_chown(): fclose() failed for lock');
664 // touch() with trying pkwk_chown()
665 function pkwk_touch_file($filename, $time = FALSE, $atime = FALSE)
667 // Is the owner incorrected and unable to correct?
668 if (! file_exists($filename) || pkwk_chown($filename)) {
669 if ($time === FALSE) {
670 $result = touch($filename);
671 } else if ($atime === FALSE) {
672 $result = touch($filename, $time);
674 $result = touch($filename, $time, $atime);
678 die('pkwk_touch_file(): Invalid UID and (not writable for the directory or not a flie): ' .
679 htmlspecialchars(basename($filename)));