2 // PukiWiki - Yet another WikiWikiWeb clone.
3 // $Id: file.php,v 1.30 2005/07/03 14:16:23 henoheno Exp $
5 // 2002-2005 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 // Get source(wiki text) data of the page
12 function get_source($page = NULL)
14 // Removing line-feeds: Because file() doesn't remove them.
15 return is_page($page) ? str_replace("\r", '', file(get_filename($page))) : array();
18 // Get last-modified filetime of the page
19 function get_filetime($page)
21 return is_page($page) ? filemtime(get_filename($page)) - LOCALZONE : 0;
24 // Get physical file name of the page
25 function get_filename($page)
27 return DATA_DIR . encode($page) . '.txt';
30 // Put a data(wiki text) into a physical file(diff, backup, text)
31 function page_write($page, $postdata, $notimestamp = FALSE)
35 if (PKWK_READONLY) return; // Do nothing
37 $postdata = make_str_rules($postdata);
39 // Create and write diff
40 $oldpostdata = is_page($page) ? join('', get_source($page)) : '';
41 $diffdata = do_diff($oldpostdata, $postdata);
42 file_write(DIFF_DIR, $page, $diffdata);
45 make_backup($page, $postdata == ''); // Is $postdata null?
48 file_write(DATA_DIR, $page, $postdata, $notimestamp);
52 $_diff = explode("\n", $diffdata);
53 $plus = join("\n", preg_replace('/^\+/', '', preg_grep('/^\+/', $_diff)));
54 $minus = join("\n", preg_replace('/^-/', '', preg_grep('/^-/', $_diff)));
55 tb_send($page, $plus, $minus);
61 // Modify ogirinal text with user-defined / system-defined rules
62 function make_str_rules($source)
64 global $str_rules, $fixed_heading_anchor;
66 $lines = explode("\n", $source);
67 $count = count($lines);
72 for ($i = 0; $i < $count; $i++) {
73 $line = & $lines[$i]; // Modify directly
75 // Ignore null string and preformatted texts
76 if ($line == '' || $line{0} == ' ' || $line{0} == "\t") continue;
80 if (! PKWKEXP_DISABLE_MULTILINE_PLUGIN_HACK &&
82 preg_match('/#[^{]*(\{\{+)\s*$/', $line, $matches)) {
83 // Multiline convert plugin start
85 $multiline = strlen($matches[1]); // Set specific number
88 if (! PKWKEXP_DISABLE_MULTILINE_PLUGIN_HACK &&
90 preg_match('/^\}{' . $multiline . '}\s*$/', $line)) {
91 // Multiline convert plugin end
96 if ($modify === FALSE) continue;
98 // Replace with $str_rules
99 foreach ($str_rules as $pattern => $replacement)
100 $line = preg_replace('/' . $pattern . '/', $replacement, $line);
102 // Adding fixed anchor into headings
103 if ($fixed_heading_anchor &&
104 preg_match('/^(\*{1,3}(.(?!\[#[A-Za-z][\w-]+\]))+)$/', $line, $matches))
107 // A random alphabetic letter + 7 letters of random strings from md()
108 $anchor = chr(mt_rand(ord('a'), ord('z'))) .
109 substr(md5(uniqid(substr($matches[1], 0, 100), 1)), mt_rand(0, 24), 7);
110 $line = rtrim($matches[1]) . ' [#' . $anchor . ']';
114 // Multiline part has no stopper
115 if (! PKWKEXP_DISABLE_MULTILINE_PLUGIN_HACK &&
116 $modify === FALSE && $multiline != 0)
117 $lines[] = str_repeat('}', $multiline);
119 return implode("\n", $lines);
123 function file_write($dir, $page, $str, $notimestamp = FALSE)
125 global $update_exec, $_msg_invalidiwn, $notify, $notify_diff_only, $notify_subject;
126 global $whatsdeleted, $maxshow_deleted;
128 if (PKWK_READONLY) return; // Do nothing
130 if (! is_pagename($page))
131 die_message(str_replace('$1', htmlspecialchars($page),
132 str_replace('$2', 'WikiName', $_msg_invalidiwn)));
134 $page = strip_bracket($page);
136 $file = $dir . encode($page) . '.txt';
138 if ($dir == DATA_DIR && $str == '' && file_exists($file)) {
140 add_recent($page, $whatsdeleted, '', $maxshow_deleted); // RecentDeleted
144 $str = preg_replace('/' . "\r" . '/', '', $str);
145 $str = rtrim($str) . "\n";
147 if ($notimestamp && file_exists($file))
148 $timestamp = filemtime($file) - LOCALZONE;
150 $fp = fopen($file, 'w') or die('fopen() failed: ' .
151 htmlspecialchars(basename($dir) . '/' . encode($page) . '.txt') .
153 'Maybe permission is not writable or filename is too long');
155 set_file_buffer($fp, 0);
162 if ($timestamp) pkwk_touch_file($file, $timestamp + LOCALZONE);
165 // Clear is_page() cache
166 is_page($page, TRUE);
168 if (! $timestamp && $dir == DATA_DIR)
171 // Execute $update_exec here
172 if ($update_exec && $dir == DATA_DIR)
173 system($update_exec . ' > /dev/null &');
175 if ($notify && $dir == DIFF_DIR) {
176 if ($notify_diff_only) $str = preg_replace('/^[^-+].*\n/m', '', $str);
178 $footer['ACTION'] = 'Page update';
179 $footer['PAGE'] = & $page;
180 $footer['URI'] = get_script_uri() . '?' . rawurlencode($page);
181 $footer['USER_AGENT'] = TRUE;
182 $footer['REMOTE_ADDR'] = TRUE;
184 pkwk_mail_notify($notify_subject, $str, $footer) or
185 die('pkwk_mail_notify(): Failed');
189 // Update RecentDeleted
190 function add_recent($page, $recentpage, $subject = '', $limit = 0)
192 if (PKWK_READONLY || $limit == 0 || $page == '' || $recentpage == '') return;
195 $lines = $matches = array();
196 foreach (get_source($recentpage) as $line)
197 if (preg_match('/^-(.+) - (\[\[.+\]\])$/', $line, $matches))
198 $lines[$matches[2]] = $line;
200 $_page = '[[' . $page . ']]';
202 // Remove a report about the same page
203 if (isset($lines[$_page])) unset($lines[$_page]);
206 array_unshift($lines, '-' . format_date(UTIME) . ' - ' . $_page .
207 htmlspecialchars($subject) . "\n");
209 // Get latest $limit reports
210 $lines = array_splice($lines, 0, $limit);
213 $fp = fopen(get_filename($recentpage), 'w') or
214 die_message('Cannot write page file ' .
215 htmlspecialchars($recentpage) .
216 '<br />Maybe permission is not writable or filename is too long');
217 set_file_buffer($fp, 0);
220 fputs($fp, '#freeze' . "\n");
221 fputs($fp, '#norelated' . "\n"); // :)
222 fputs($fp, join('', $lines));
227 // Update RecentChanges
228 function put_lastmodified()
230 global $maxshow, $whatsnew, $non_list, $autolink;
232 if (PKWK_READONLY) return; // Do nothing
234 $pages = get_existpages();
235 $recent_pages = array();
236 $non_list_pattern = '/' . $non_list . '/';
237 foreach($pages as $page)
238 if ($page != $whatsnew && ! preg_match($non_list_pattern, $page))
239 $recent_pages[$page] = get_filetime($page);
241 // Sort decending order of last-modification date
242 arsort($recent_pages, SORT_NUMERIC);
244 // Create recent.dat (for recent.inc.php)
245 $fp = fopen(CACHE_DIR . 'recent.dat', 'w') or
246 die_message('Cannot write cache file ' .
247 CACHE_DIR . 'recent.dat' .
248 '<br />Maybe permission is not writable or filename is too long');
250 set_file_buffer($fp, 0);
253 foreach ($recent_pages as $page=>$time)
254 fputs($fp, $time . "\t" . $page . "\n");
258 // Create RecentChanges
259 $fp = fopen(get_filename($whatsnew), 'w') or
260 die_message('Cannot write page file ' .
261 htmlspecialchars($whatsnew) .
262 '<br />Maybe permission is not writable or filename is too long');
264 set_file_buffer($fp, 0);
267 foreach (array_splice(array_keys($recent_pages), 0, $maxshow) as $page) {
268 $time = $recent_pages[$page];
269 $s_lastmod = htmlspecialchars(format_date($time));
270 $s_page = htmlspecialchars($page);
271 fputs($fp, '-' . $s_lastmod . ' - [[' . $s_page . ']]' . "\n");
273 fputs($fp, '#norelated' . "\n"); // :)
279 list($pattern, $pattern_a, $forceignorelist) =
280 get_autolink_pattern($pages);
282 $fp = fopen(CACHE_DIR . 'autolink.dat', 'w') or
283 die_message('Cannot write autolink file ' .
284 CACHE_DIR . '/autolink.dat' .
285 '<br />Maybe permission is not writable');
286 set_file_buffer($fp, 0);
289 fputs($fp, $pattern . "\n");
290 fputs($fp, $pattern_a . "\n");
291 fputs($fp, join("\t", $forceignorelist) . "\n");
297 // Get elapsed date of the pate
298 function get_pg_passage($page, $sw = TRUE)
300 global $show_passage;
301 if (! $show_passage) return '';
303 $time = get_filetime($page);
304 $pg_passage = ($time != 0) ? get_passage($time) : '';
306 return $sw ? '<small>' . $pg_passage . '</small>' : ' ' . $pg_passage;
309 // Last-Modified header
310 function header_lastmod($page = NULL)
314 if ($lastmod && is_page($page)) {
316 header('Last-Modified: ' .
317 date('D, d M Y H:i:s', get_filetime($page)) . ' GMT');
321 // Get a page list of this wiki
322 function get_existpages($dir = DATA_DIR, $ext = '.txt')
326 $pattern = '((?:[0-9A-F]{2})+)';
327 if ($ext != '') $ext = preg_quote($ext, '/');
328 $pattern = '/^' . $pattern . $ext . '$/';
330 $dp = @opendir($dir) or
331 die_message($dir . ' is not found or not readable.');
333 while ($file = readdir($dp))
334 if (preg_match($pattern, $file, $matches))
335 $aryret[$file] = decode($matches[1]);
341 // Get PageReading(pronounce-annotated) data in an array()
342 function get_readings()
344 global $pagereading_enable, $pagereading_kanji2kana_converter;
345 global $pagereading_kanji2kana_encoding, $pagereading_chasen_path;
346 global $pagereading_kakasi_path, $pagereading_config_page;
347 global $pagereading_config_dict;
349 $pages = get_existpages();
352 foreach ($pages as $page)
353 $readings[$page] = '';
355 $deletedPage = FALSE;
357 foreach (get_source($pagereading_config_page) as $line) {
359 if(preg_match('/^-\[\[([^]]+)\]\]\s+(.+)$/', $line, $matches)) {
360 if(isset($readings[$matches[1]])) {
361 // This page is not clear how to be pronounced
362 $readings[$matches[1]] = $matches[2];
364 // This page seems deleted
370 // If enabled ChaSen/KAKASI execution
371 if($pagereading_enable) {
373 // Check there's non-clear-pronouncing page
374 $unknownPage = FALSE;
375 foreach ($readings as $page => $reading) {
382 // Execute ChaSen/KAKASI, and get annotation
384 switch(strtolower($pagereading_kanji2kana_converter)) {
386 if(! file_exists($pagereading_chasen_path))
387 die_message('ChaSen not found: ' . $pagereading_chasen_path);
389 $tmpfname = tempnam(CACHE_DIR, 'PageReading');
390 $fp = fopen($tmpfname, 'w') or
391 die_message('Cannot write temporary file "' . $tmpfname . '".' . "\n");
392 foreach ($readings as $page => $reading) {
393 if($reading != '') continue;
394 fputs($fp, mb_convert_encoding($page . "\n",
395 $pagereading_kanji2kana_encoding, SOURCE_ENCODING));
399 $chasen = "$pagereading_chasen_path -F %y $tmpfname";
400 $fp = popen($chasen, 'r');
403 die_message('ChaSen execution failed: ' . $chasen);
405 foreach ($readings as $page => $reading) {
406 if($reading != '') continue;
409 $line = mb_convert_encoding($line, SOURCE_ENCODING,
410 $pagereading_kanji2kana_encoding);
412 $readings[$page] = $line;
417 die_message('Temporary file can not be removed: ' . $tmpfname);
420 case 'kakasi': /*FALLTHROUGH*/
422 if(! file_exists($pagereading_kakasi_path))
423 die_message('KAKASI not found: ' . $pagereading_kakasi_path);
425 $tmpfname = tempnam(CACHE_DIR, 'PageReading');
426 $fp = fopen($tmpfname, 'w') or
427 die_message('Cannot write temporary file "' . $tmpfname . '".' . "\n");
428 foreach ($readings as $page => $reading) {
429 if($reading != '') continue;
430 fputs($fp, mb_convert_encoding($page . "\n",
431 $pagereading_kanji2kana_encoding, SOURCE_ENCODING));
435 $kakasi = "$pagereading_kakasi_path -kK -HK -JK < $tmpfname";
436 $fp = popen($kakasi, 'r');
439 die_message('KAKASI execution failed: ' . $kakasi);
442 foreach ($readings as $page => $reading) {
443 if($reading != '') continue;
446 $line = mb_convert_encoding($line, SOURCE_ENCODING,
447 $pagereading_kanji2kana_encoding);
449 $readings[$page] = $line;
454 die_message('Temporary file can not be removed: ' . $tmpfname);
458 $patterns = $replacements = $matches = array();
459 foreach (get_source($pagereading_config_dict) as $line) {
461 if(preg_match('|^ /([^/]+)/,\s*(.+)$|', $line, $matches)) {
462 $patterns[] = $matches[1];
463 $replacements[] = $matches[2];
466 foreach ($readings as $page => $reading) {
467 if($reading != '') continue;
469 $readings[$page] = $page;
470 foreach ($patterns as $no => $pattern)
471 $readings[$page] = mb_convert_kana(mb_ereg_replace($pattern,
472 $replacements[$no], $readings[$page]), 'aKCV');
477 die_message('Unknown kanji-kana converter: ' . $pagereading_kanji2kana_converter . '.');
482 if($unknownPage || $deletedPage) {
484 asort($readings); // Sort by pronouncing(alphabetical/reading) order
486 foreach ($readings as $page => $reading)
487 $body .= '-[[' . $page . ']] ' . $reading . "\n";
489 page_write($pagereading_config_page, $body);
493 // Pages that are not prounouncing-clear, return pagenames of themselves
494 foreach ($pages as $page) {
495 if($readings[$page] == '')
496 $readings[$page] = $page;
502 // Get a list of encoded files (must specify a directory and a suffix)
503 function get_existfiles($dir, $ext)
505 $pattern = '/^(?:[0-9A-F]{2})+' . preg_quote($ext, '/') . '$/';
507 $dp = @opendir($dir) or die_message($dir . ' is not found or not readable.');
508 while ($file = readdir($dp))
509 if (preg_match($pattern, $file))
510 $aryret[] = $dir . $file;
515 // Get a list of related pages of the page
516 function links_get_related($page)
518 global $vars, $related;
519 static $links = array();
521 if (isset($links[$page])) return $links[$page];
523 // If possible, merge related pages generated by make_link()
524 $links[$page] = ($page == $vars['page']) ? $related : array();
526 // Get repated pages from DB
527 $links[$page] += links_get_related_db($vars['page']);
529 return $links[$page];
532 // _If needed_, re-create the file to change/correct ownership into PHP's
533 // NOTE: Not works for Windows
534 function pkwk_chown($filename, $preserve_time = TRUE)
536 static $php_uid; // PHP's UID
538 if (! isset($php_uid)) {
539 if (extension_loaded('posix')) {
540 $php_uid = posix_getuid(); // Unix
542 $php_uid = 0; // Windows
546 // Lock for pkwk_chown()
547 $lockfile = CACHE_DIR . 'pkwk_chown.lock';
548 $flock = fopen($lockfile, 'a') or
549 die('pkwk_chown(): fopen() failed for: CACHEDIR/' .
550 basename(htmlspecialchars($lockfile)));
551 flock($flock, LOCK_EX) or die('pkwk_chown(): flock() failed for lock');
554 $stat = stat($filename) or
555 die('pkwk_chown(): stat() failed for: ' . basename(htmlspecialchars($filename)));
556 if ($stat[4] === $php_uid) {
557 // NOTE: Windows always here
558 $result = TRUE; // Seems the same UID. Nothing to do
560 $tmp = $filename . '.' . getmypid() . '.tmp';
562 // Lock source $filename to avoid file corruption
563 // NOTE: Not 'r+'. Don't check write permission here
564 $ffile = fopen($filename, 'r') or
565 die('pkwk_chown(): fopen() failed for: ' .
566 basename(htmlspecialchars($filename)));
568 // Try to chown by re-creating files
570 // * touch() before copy() is for 'rw-r--r--' instead of 'rwxr-xr-x' (with umask 022).
571 // * (PHP 4 < PHP 4.2.0) touch() with the third argument is not implemented and retuns NULL and Warn.
572 // * @unlink() before rename() is for Windows but here's for Unix only
573 flock($ffile, LOCK_EX) or die('pkwk_chown(): flock() failed');
574 $result = touch($tmp) && copy($filename, $tmp) &&
575 ($preserve_time ? (touch($tmp, $stat[9], $stat[8]) || touch($tmp, $stat[9])) : TRUE) &&
576 rename($tmp, $filename);
577 flock($ffile, LOCK_UN) or die('pkwk_chown(): flock() failed');
579 fclose($ffile) or die('pkwk_chown(): fclose() failed');
581 if ($result === FALSE) @unlink($tmp);
584 // Unlock for pkwk_chown()
585 flock($flock, LOCK_UN) or die('pkwk_chown(): flock() failed for lock');
586 fclose($flock) or die('pkwk_chown(): fclose() failed for lock');
591 // touch() with trying pkwk_chown()
592 function pkwk_touch_file($filename, $time = FALSE, $atime = FALSE)
594 // Is the owner incorrected and unable to correct?
595 if (! file_exists($filename) || pkwk_chown($filename)) {
596 if ($time === FALSE) {
597 $result = touch($filename);
598 } else if ($atime === FALSE) {
599 $result = touch($filename, $time);
601 $result = touch($filename, $time, $atime);
605 die('pkwk_touch_file(): Invalid UID and (not writable for the directory or not a flie): ' .
606 htmlspecialchars(basename($filename)));