2 // PukiWiki - Yet another WikiWikiWeb clone.
3 // $Id: file.php,v 1.36 2005/08/01 15:04:29 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, $lock = TRUE)
17 $path = get_filename($page);
20 $fp = @fopen($path, 'r');
21 if ($fp == FALSE) return $array;
25 // Removing line-feeds: Because file() doesn't remove them.
26 $array = str_replace("\r", '', file($path));
37 // Get last-modified filetime of the page
38 function get_filetime($page)
40 return is_page($page) ? filemtime(get_filename($page)) - LOCALZONE : 0;
43 // Get physical file name of the page
44 function get_filename($page)
46 return DATA_DIR . encode($page) . '.txt';
49 // Put a data(wiki text) into a physical file(diff, backup, text)
50 function page_write($page, $postdata, $notimestamp = FALSE)
54 if (PKWK_READONLY) return; // Do nothing
56 $postdata = make_str_rules($postdata);
58 // Create and write diff
59 $oldpostdata = is_page($page) ? join('', get_source($page)) : '';
60 $diffdata = do_diff($oldpostdata, $postdata);
61 file_write(DIFF_DIR, $page, $diffdata);
64 make_backup($page, $postdata == ''); // Is $postdata null?
67 file_write(DATA_DIR, $page, $postdata, $notimestamp);
71 $_diff = explode("\n", $diffdata);
72 $plus = join("\n", preg_replace('/^\+/', '', preg_grep('/^\+/', $_diff)));
73 $minus = join("\n", preg_replace('/^-/', '', preg_grep('/^-/', $_diff)));
74 tb_send($page, $plus, $minus);
80 // Modify ogirinal text with user-defined / system-defined rules
81 function make_str_rules($source)
83 global $str_rules, $fixed_heading_anchor;
85 $lines = explode("\n", $source);
86 $count = count($lines);
91 for ($i = 0; $i < $count; $i++) {
92 $line = & $lines[$i]; // Modify directly
94 // Ignore null string and preformatted texts
95 if ($line == '' || $line{0} == ' ' || $line{0} == "\t") continue;
99 if (! PKWKEXP_DISABLE_MULTILINE_PLUGIN_HACK &&
101 preg_match('/#[^{]*(\{\{+)\s*$/', $line, $matches)) {
102 // Multiline convert plugin start
104 $multiline = strlen($matches[1]); // Set specific number
107 if (! PKWKEXP_DISABLE_MULTILINE_PLUGIN_HACK &&
109 preg_match('/^\}{' . $multiline . '}\s*$/', $line)) {
110 // Multiline convert plugin end
115 if ($modify === FALSE) continue;
117 // Replace with $str_rules
118 foreach ($str_rules as $pattern => $replacement)
119 $line = preg_replace('/' . $pattern . '/', $replacement, $line);
121 // Adding fixed anchor into headings
122 if ($fixed_heading_anchor &&
123 preg_match('/^(\*{1,3}.*?)(?:\[#([A-Za-z][\w-]*)\]\s*)?$/', $line, $matches) &&
124 (! isset($matches[2]) || $matches[2] == '')) {
125 // Generate unique id
126 $anchor = generate_fixed_heading_anchor_id($matches[1]);
127 $line = rtrim($matches[1]) . ' [#' . $anchor . ']';
131 // Multiline part has no stopper
132 if (! PKWKEXP_DISABLE_MULTILINE_PLUGIN_HACK &&
133 $modify === FALSE && $multiline != 0)
134 $lines[] = str_repeat('}', $multiline);
136 return implode("\n", $lines);
140 function generate_fixed_heading_anchor_id($seed)
142 // A random alphabetic letter + 7 letters of random strings from md()
143 return chr(mt_rand(ord('a'), ord('z'))) .
144 substr(md5(uniqid(substr($seed, 0, 100), TRUE)),
149 function file_write($dir, $page, $str, $notimestamp = FALSE)
151 global $update_exec, $_msg_invalidiwn, $notify, $notify_diff_only, $notify_subject;
152 global $whatsdeleted, $maxshow_deleted;
154 if (PKWK_READONLY) return; // Do nothing
156 if (! is_pagename($page))
157 die_message(str_replace('$1', htmlspecialchars($page),
158 str_replace('$2', 'WikiName', $_msg_invalidiwn)));
160 $page = strip_bracket($page);
161 $file = $dir . encode($page) . '.txt';
165 if ($dir == DATA_DIR && file_exists($file)) {
168 add_recent($page, $whatsdeleted, '', $maxshow_deleted); // RecentDeleted
171 // File replacement (Edit)
172 $str = rtrim(preg_replace('/' . "\r" . '/', '', $str)) . "\n";
174 if ($notimestamp && file_exists($file))
175 $timestamp = filemtime($file) - LOCALZONE;
177 $fp = fopen($file, 'r+') or die('fopen() failed: ' .
178 htmlspecialchars(basename($dir) . '/' . encode($page) . '.txt') .
180 'Maybe permission is not writable or filename is too long');
181 set_file_buffer($fp, 0);
186 if (! ftruncate($fp, 0)) return FALSE;
194 if ($timestamp) pkwk_touch_file($file, $timestamp + LOCALZONE);
197 // Clear is_page() cache
198 is_page($page, TRUE);
200 if (! $timestamp && $dir == DATA_DIR)
203 // Execute $update_exec here
204 if ($update_exec && $dir == DATA_DIR)
205 system($update_exec . ' > /dev/null &');
207 if ($notify && $dir == DIFF_DIR) {
208 if ($notify_diff_only) $str = preg_replace('/^[^-+].*\n/m', '', $str);
210 $footer['ACTION'] = 'Page update';
211 $footer['PAGE'] = & $page;
212 $footer['URI'] = get_script_uri() . '?' . rawurlencode($page);
213 $footer['USER_AGENT'] = TRUE;
214 $footer['REMOTE_ADDR'] = TRUE;
216 pkwk_mail_notify($notify_subject, $str, $footer) or
217 die('pkwk_mail_notify(): Failed');
221 // Update RecentDeleted
222 function add_recent($page, $recentpage, $subject = '', $limit = 0)
224 if (PKWK_READONLY || $limit == 0 || $page == '' || $recentpage == '') return;
227 $lines = $matches = array();
228 foreach (get_source($recentpage) as $line)
229 if (preg_match('/^-(.+) - (\[\[.+\]\])$/', $line, $matches))
230 $lines[$matches[2]] = $line;
232 $_page = '[[' . $page . ']]';
234 // Remove a report about the same page
235 if (isset($lines[$_page])) unset($lines[$_page]);
238 array_unshift($lines, '-' . format_date(UTIME) . ' - ' . $_page .
239 htmlspecialchars($subject) . "\n");
241 // Get latest $limit reports
242 $lines = array_splice($lines, 0, $limit);
245 $fp = fopen(get_filename($recentpage), 'w') or
246 die_message('Cannot write page file ' .
247 htmlspecialchars($recentpage) .
248 '<br />Maybe permission is not writable or filename is too long');
249 set_file_buffer($fp, 0);
252 fputs($fp, '#freeze' . "\n");
253 fputs($fp, '#norelated' . "\n"); // :)
254 fputs($fp, join('', $lines));
259 // Update RecentChanges
260 function put_lastmodified()
262 global $maxshow, $whatsnew, $non_list, $autolink;
264 if (PKWK_READONLY) return; // Do nothing
266 $pages = get_existpages();
267 $recent_pages = array();
268 $non_list_pattern = '/' . $non_list . '/';
269 foreach($pages as $page)
270 if ($page != $whatsnew && ! preg_match($non_list_pattern, $page))
271 $recent_pages[$page] = get_filetime($page);
273 // Sort decending order of last-modification date
274 arsort($recent_pages, SORT_NUMERIC);
276 // Create recent.dat (for recent.inc.php)
277 $fp = fopen(CACHE_DIR . 'recent.dat', 'w') or
278 die_message('Cannot write cache file ' .
279 CACHE_DIR . 'recent.dat' .
280 '<br />Maybe permission is not writable or filename is too long');
282 set_file_buffer($fp, 0);
285 foreach ($recent_pages as $page=>$time)
286 fputs($fp, $time . "\t" . $page . "\n");
290 // Create RecentChanges
291 $fp = fopen(get_filename($whatsnew), 'w') or
292 die_message('Cannot write page file ' .
293 htmlspecialchars($whatsnew) .
294 '<br />Maybe permission is not writable or filename is too long');
296 set_file_buffer($fp, 0);
299 foreach (array_splice(array_keys($recent_pages), 0, $maxshow) as $page) {
300 $time = $recent_pages[$page];
301 $s_lastmod = htmlspecialchars(format_date($time));
302 $s_page = htmlspecialchars($page);
303 fputs($fp, '-' . $s_lastmod . ' - [[' . $s_page . ']]' . "\n");
305 fputs($fp, '#norelated' . "\n"); // :)
311 list($pattern, $pattern_a, $forceignorelist) =
312 get_autolink_pattern($pages);
314 $fp = fopen(CACHE_DIR . 'autolink.dat', 'w') or
315 die_message('Cannot write autolink file ' .
316 CACHE_DIR . '/autolink.dat' .
317 '<br />Maybe permission is not writable');
318 set_file_buffer($fp, 0);
321 fputs($fp, $pattern . "\n");
322 fputs($fp, $pattern_a . "\n");
323 fputs($fp, join("\t", $forceignorelist) . "\n");
329 // Get elapsed date of the pate
330 function get_pg_passage($page, $sw = TRUE)
332 global $show_passage;
333 if (! $show_passage) return '';
335 $time = get_filetime($page);
336 $pg_passage = ($time != 0) ? get_passage($time) : '';
338 return $sw ? '<small>' . $pg_passage . '</small>' : ' ' . $pg_passage;
341 // Last-Modified header
342 function header_lastmod($page = NULL)
346 if ($lastmod && is_page($page)) {
348 header('Last-Modified: ' .
349 date('D, d M Y H:i:s', get_filetime($page)) . ' GMT');
353 // Get a page list of this wiki
354 function get_existpages($dir = DATA_DIR, $ext = '.txt')
358 $pattern = '((?:[0-9A-F]{2})+)';
359 if ($ext != '') $ext = preg_quote($ext, '/');
360 $pattern = '/^' . $pattern . $ext . '$/';
362 $dp = @opendir($dir) or
363 die_message($dir . ' is not found or not readable.');
365 while ($file = readdir($dp))
366 if (preg_match($pattern, $file, $matches))
367 $aryret[$file] = decode($matches[1]);
373 // Get PageReading(pronounce-annotated) data in an array()
374 function get_readings()
376 global $pagereading_enable, $pagereading_kanji2kana_converter;
377 global $pagereading_kanji2kana_encoding, $pagereading_chasen_path;
378 global $pagereading_kakasi_path, $pagereading_config_page;
379 global $pagereading_config_dict;
381 $pages = get_existpages();
384 foreach ($pages as $page)
385 $readings[$page] = '';
387 $deletedPage = FALSE;
389 foreach (get_source($pagereading_config_page) as $line) {
391 if(preg_match('/^-\[\[([^]]+)\]\]\s+(.+)$/', $line, $matches)) {
392 if(isset($readings[$matches[1]])) {
393 // This page is not clear how to be pronounced
394 $readings[$matches[1]] = $matches[2];
396 // This page seems deleted
402 // If enabled ChaSen/KAKASI execution
403 if($pagereading_enable) {
405 // Check there's non-clear-pronouncing page
406 $unknownPage = FALSE;
407 foreach ($readings as $page => $reading) {
414 // Execute ChaSen/KAKASI, and get annotation
416 switch(strtolower($pagereading_kanji2kana_converter)) {
418 if(! file_exists($pagereading_chasen_path))
419 die_message('ChaSen not found: ' . $pagereading_chasen_path);
421 $tmpfname = tempnam(CACHE_DIR, 'PageReading');
422 $fp = fopen($tmpfname, 'w') or
423 die_message('Cannot write temporary file "' . $tmpfname . '".' . "\n");
424 foreach ($readings as $page => $reading) {
425 if($reading != '') continue;
426 fputs($fp, mb_convert_encoding($page . "\n",
427 $pagereading_kanji2kana_encoding, SOURCE_ENCODING));
431 $chasen = "$pagereading_chasen_path -F %y $tmpfname";
432 $fp = popen($chasen, 'r');
435 die_message('ChaSen execution failed: ' . $chasen);
437 foreach ($readings as $page => $reading) {
438 if($reading != '') continue;
441 $line = mb_convert_encoding($line, SOURCE_ENCODING,
442 $pagereading_kanji2kana_encoding);
444 $readings[$page] = $line;
449 die_message('Temporary file can not be removed: ' . $tmpfname);
452 case 'kakasi': /*FALLTHROUGH*/
454 if(! file_exists($pagereading_kakasi_path))
455 die_message('KAKASI not found: ' . $pagereading_kakasi_path);
457 $tmpfname = tempnam(CACHE_DIR, 'PageReading');
458 $fp = fopen($tmpfname, 'w') or
459 die_message('Cannot write temporary file "' . $tmpfname . '".' . "\n");
460 foreach ($readings as $page => $reading) {
461 if($reading != '') continue;
462 fputs($fp, mb_convert_encoding($page . "\n",
463 $pagereading_kanji2kana_encoding, SOURCE_ENCODING));
467 $kakasi = "$pagereading_kakasi_path -kK -HK -JK < $tmpfname";
468 $fp = popen($kakasi, 'r');
471 die_message('KAKASI execution failed: ' . $kakasi);
474 foreach ($readings as $page => $reading) {
475 if($reading != '') continue;
478 $line = mb_convert_encoding($line, SOURCE_ENCODING,
479 $pagereading_kanji2kana_encoding);
481 $readings[$page] = $line;
486 die_message('Temporary file can not be removed: ' . $tmpfname);
490 $patterns = $replacements = $matches = array();
491 foreach (get_source($pagereading_config_dict) as $line) {
493 if(preg_match('|^ /([^/]+)/,\s*(.+)$|', $line, $matches)) {
494 $patterns[] = $matches[1];
495 $replacements[] = $matches[2];
498 foreach ($readings as $page => $reading) {
499 if($reading != '') continue;
501 $readings[$page] = $page;
502 foreach ($patterns as $no => $pattern)
503 $readings[$page] = mb_convert_kana(mb_ereg_replace($pattern,
504 $replacements[$no], $readings[$page]), 'aKCV');
509 die_message('Unknown kanji-kana converter: ' . $pagereading_kanji2kana_converter . '.');
514 if($unknownPage || $deletedPage) {
516 asort($readings); // Sort by pronouncing(alphabetical/reading) order
518 foreach ($readings as $page => $reading)
519 $body .= '-[[' . $page . ']] ' . $reading . "\n";
521 page_write($pagereading_config_page, $body);
525 // Pages that are not prounouncing-clear, return pagenames of themselves
526 foreach ($pages as $page) {
527 if($readings[$page] == '')
528 $readings[$page] = $page;
534 // Get a list of encoded files (must specify a directory and a suffix)
535 function get_existfiles($dir, $ext)
537 $pattern = '/^(?:[0-9A-F]{2})+' . preg_quote($ext, '/') . '$/';
539 $dp = @opendir($dir) or die_message($dir . ' is not found or not readable.');
540 while ($file = readdir($dp))
541 if (preg_match($pattern, $file))
542 $aryret[] = $dir . $file;
547 // Get a list of related pages of the page
548 function links_get_related($page)
550 global $vars, $related;
551 static $links = array();
553 if (isset($links[$page])) return $links[$page];
555 // If possible, merge related pages generated by make_link()
556 $links[$page] = ($page == $vars['page']) ? $related : array();
558 // Get repated pages from DB
559 $links[$page] += links_get_related_db($vars['page']);
561 return $links[$page];
564 // _If needed_, re-create the file to change/correct ownership into PHP's
565 // NOTE: Not works for Windows
566 function pkwk_chown($filename, $preserve_time = TRUE)
568 static $php_uid; // PHP's UID
570 if (! isset($php_uid)) {
571 if (extension_loaded('posix')) {
572 $php_uid = posix_getuid(); // Unix
574 $php_uid = 0; // Windows
578 // Lock for pkwk_chown()
579 $lockfile = CACHE_DIR . 'pkwk_chown.lock';
580 $flock = fopen($lockfile, 'a') or
581 die('pkwk_chown(): fopen() failed for: CACHEDIR/' .
582 basename(htmlspecialchars($lockfile)));
583 flock($flock, LOCK_EX) or die('pkwk_chown(): flock() failed for lock');
586 $stat = stat($filename) or
587 die('pkwk_chown(): stat() failed for: ' . basename(htmlspecialchars($filename)));
588 if ($stat[4] === $php_uid) {
589 // NOTE: Windows always here
590 $result = TRUE; // Seems the same UID. Nothing to do
592 $tmp = $filename . '.' . getmypid() . '.tmp';
594 // Lock source $filename to avoid file corruption
595 // NOTE: Not 'r+'. Don't check write permission here
596 $ffile = fopen($filename, 'r') or
597 die('pkwk_chown(): fopen() failed for: ' .
598 basename(htmlspecialchars($filename)));
600 // Try to chown by re-creating files
602 // * touch() before copy() is for 'rw-r--r--' instead of 'rwxr-xr-x' (with umask 022).
603 // * (PHP 4 < PHP 4.2.0) touch() with the third argument is not implemented and retuns NULL and Warn.
604 // * @unlink() before rename() is for Windows but here's for Unix only
605 flock($ffile, LOCK_EX) or die('pkwk_chown(): flock() failed');
606 $result = touch($tmp) && copy($filename, $tmp) &&
607 ($preserve_time ? (touch($tmp, $stat[9], $stat[8]) || touch($tmp, $stat[9])) : TRUE) &&
608 rename($tmp, $filename);
609 flock($ffile, LOCK_UN) or die('pkwk_chown(): flock() failed');
611 fclose($ffile) or die('pkwk_chown(): fclose() failed');
613 if ($result === FALSE) @unlink($tmp);
616 // Unlock for pkwk_chown()
617 flock($flock, LOCK_UN) or die('pkwk_chown(): flock() failed for lock');
618 fclose($flock) or die('pkwk_chown(): fclose() failed for lock');
623 // touch() with trying pkwk_chown()
624 function pkwk_touch_file($filename, $time = FALSE, $atime = FALSE)
626 // Is the owner incorrected and unable to correct?
627 if (! file_exists($filename) || pkwk_chown($filename)) {
628 if ($time === FALSE) {
629 $result = touch($filename);
630 } else if ($atime === FALSE) {
631 $result = touch($filename, $time);
633 $result = touch($filename, $time, $atime);
637 die('pkwk_touch_file(): Invalid UID and (not writable for the directory or not a flie): ' .
638 htmlspecialchars(basename($filename)));