2 // PukiWiki - Yet another WikiWikiWeb clone.
3 // $Id: file.php,v 1.14 2005/04/05 14:40:43 henoheno Exp $
5 // File related functions
7 // Get source(wiki text) data of the page
8 function get_source($page = NULL)
10 // Removing line-feeds: Because file() doesn't remove them.
11 return is_page($page) ? str_replace("\r", '', file(get_filename($page))) : array();
14 // Get last-modified filetime of the page
15 function get_filetime($page)
17 return is_page($page) ? filemtime(get_filename($page)) - LOCALZONE : 0;
20 // Get physical file name of the page
21 function get_filename($page)
23 return DATA_DIR . encode($page) . '.txt';
26 // Put a data(wiki text) into a physical file(diff, backup, text)
27 function page_write($page, $postdata, $notimestamp = FALSE)
31 if (PKWK_READONLY) return; // Do nothing
33 $postdata = make_str_rules($postdata);
35 // Create and write diff
36 $oldpostdata = is_page($page) ? join('', get_source($page)) : '';
37 $diffdata = do_diff($oldpostdata, $postdata);
38 file_write(DIFF_DIR, $page, $diffdata);
41 make_backup($page, $postdata == ''); // Is $postdata null?
44 file_write(DATA_DIR, $page, $postdata, $notimestamp);
48 $_diff = explode("\n", $diffdata);
49 $plus = join("\n", preg_replace('/^\+/', '', preg_grep('/^\+/', $_diff)));
50 $minus = join("\n", preg_replace('/^-/', '', preg_grep('/^-/', $_diff)));
51 tb_send($page, $plus, $minus);
57 // User-defined rules (replace the source)
58 function make_str_rules($str)
60 global $str_rules, $fixed_heading_anchor;
62 $arr = explode("\n", $str);
64 $retvars = $matches = array();
65 foreach ($arr as $str) {
66 if ($str != '' && $str{0} != ' ' && $str{0} != "\t")
67 foreach ($str_rules as $rule => $replace)
68 $str = preg_replace('/' . $rule . '/', $replace, $str);
70 // Adding fixed anchor into headings
71 if ($fixed_heading_anchor &&
72 preg_match('/^(\*{1,3}(.(?!\[#[A-Za-z][\w-]+\]))+)$/', $str, $matches))
75 // A random alphabetic letter + 7 letters of random strings from md()
76 $anchor = chr(mt_rand(ord('a'), ord('z'))) .
77 substr(md5(uniqid(substr($matches[1], 0, 100), 1)), mt_rand(0, 24), 7);
78 $str = rtrim($matches[1]) . ' [#' . $anchor . ']';
83 return join("\n", $retvars);
87 function file_write($dir, $page, $str, $notimestamp = FALSE)
89 global $update_exec, $_msg_invalidiwn;
90 global $notify, $notify_diff_only, $notify_to, $notify_subject, $notify_header;
91 global $smtp_server, $smtp_auth;
92 global $whatsdeleted, $maxshow_deleted;
94 if (PKWK_READONLY) return; // Do nothing
96 if (! is_pagename($page))
97 die_message(str_replace('$1', htmlspecialchars($page),
98 str_replace('$2', 'WikiName', $_msg_invalidiwn)));
100 $page = strip_bracket($page);
102 $file = $dir . encode($page) . '.txt';
104 if ($dir == DATA_DIR && $str == '' && file_exists($file)) {
106 add_recent($page, $whatsdeleted, '', $maxshow_deleted); // RecentDeleted
110 $str = preg_replace('/' . "\r" . '/', '', $str);
111 $str = rtrim($str) . "\n";
113 if ($notimestamp && file_exists($file))
114 $timestamp = filemtime($file) - LOCALZONE;
116 $fp = fopen($file, 'w') or
117 die_message('Cannot write page file or diff file or other ' .
118 htmlspecialchars($page) .
119 '<br />Maybe permission is not writable or filename is too long');
121 set_file_buffer($fp, 0);
128 touch($file, $timestamp + LOCALZONE) or
129 die('Touch failed for: ' . htmlspecialchars(basename($file)));
130 // With safe_mode, touch() always check UID
133 // Clear is_page() cache
134 is_page($page, TRUE);
136 if (! $timestamp && $dir == DATA_DIR)
139 // Execute $update_exec here
140 if ($update_exec && $dir == DATA_DIR)
141 system($update_exec . ' > /dev/null &');
143 if ($notify && $dir == DIFF_DIR) {
144 if ($notify_diff_only) $str = preg_replace('/^[^-+].*\n/m', '', $str);
146 str_repeat('-', 30) . "\n" .
147 'URI: ' . get_script_uri() . '?' . rawurlencode($page) . "\n" .
148 'REMOTE_ADDR: ' . $_SERVER['REMOTE_ADDR'] . "\n";
150 $subject = str_replace('$page', $page, $notify_subject);
151 ini_set('SMTP', $smtp_server);
154 if ($smtp_auth) pop_before_smtp();
155 mb_send_mail($notify_to, $subject, $str, $notify_header);
159 // Update RecentDeleted
160 function add_recent($page, $recentpage, $subject = '', $limit = 0)
162 if (PKWK_READONLY || $limit == 0 || $page == '' || $recentpage == '') return;
165 $lines = $matches = array();
166 foreach (get_source($recentpage) as $line)
167 if (preg_match('/^-(.+) - (\[\[.+\]\])$/', $line, $matches))
168 $lines[$matches[2]] = $line;
170 $_page = '[[' . $page . ']]';
172 // Remove a report about the same page
173 if (isset($lines[$_page])) unset($lines[$_page]);
176 array_unshift($lines, '-' . format_date(UTIME) . ' - ' . $_page .
177 htmlspecialchars($subject) . "\n");
179 // Get latest $limit reports
180 $lines = array_splice($lines, 0, $limit);
183 $fp = fopen(get_filename($recentpage), 'w') or
184 die_message('Cannot write page file ' .
185 htmlspecialchars($recentpage) .
186 '<br />Maybe permission is not writable or filename is too long');
187 set_file_buffer($fp, 0);
190 fputs($fp, '#freeze' . "\n");
191 fputs($fp, '#norelated' . "\n"); // :)
192 fputs($fp, join('', $lines));
197 // Update RecentChanges
198 function put_lastmodified()
200 global $maxshow, $whatsnew, $non_list, $autolink;
202 if (PKWK_READONLY) return; // Do nothing
204 $pages = get_existpages();
205 $recent_pages = array();
206 $non_list_pattern = '/' . $non_list . '/';
207 foreach($pages as $page)
208 if ($page != $whatsnew && ! preg_match($non_list_pattern, $page))
209 $recent_pages[$page] = get_filetime($page);
211 // Sort decending order of last-modification date
212 arsort($recent_pages, SORT_NUMERIC);
214 // Create recent.dat (for recent.inc.php)
215 $fp = fopen(CACHE_DIR . 'recent.dat', 'w') or
216 die_message('Cannot write cache file ' .
217 CACHE_DIR . 'recent.dat' .
218 '<br />Maybe permission is not writable or filename is too long');
220 set_file_buffer($fp, 0);
223 foreach ($recent_pages as $page=>$time)
224 fputs($fp, $time . "\t" . $page . "\n");
228 // Create RecentChanges
229 $fp = fopen(get_filename($whatsnew), 'w') or
230 die_message('Cannot write page file ' .
231 htmlspecialchars($whatsnew) .
232 '<br />Maybe permission is not writable or filename is too long');
234 set_file_buffer($fp, 0);
237 foreach (array_splice(array_keys($recent_pages), 0, $maxshow) as $page) {
238 $time = $recent_pages[$page];
239 $s_lastmod = htmlspecialchars(format_date($time));
240 $s_page = htmlspecialchars($page);
241 fputs($fp, '-' . $s_lastmod . ' - [[' . $s_page . ']]' . "\n");
243 fputs($fp, '#norelated' . "\n"); // :)
249 list($pattern, $pattern_a, $forceignorelist) =
250 get_autolink_pattern($pages);
252 $fp = fopen(CACHE_DIR . 'autolink.dat', 'w') or
253 die_message('Cannot write autolink file ' .
254 CACHE_DIR . '/autolink.dat' .
255 '<br />Maybe permission is not writable');
256 set_file_buffer($fp, 0);
259 fputs($fp, $pattern . "\n");
260 fputs($fp, $pattern_a . "\n");
261 fputs($fp, join("\t", $forceignorelist) . "\n");
267 // Get elapsed date of the pate
268 function get_pg_passage($page, $sw = TRUE)
270 global $show_passage;
271 if (! $show_passage) return '';
273 $time = get_filetime($page);
274 $pg_passage = ($time != 0) ? get_passage($time) : '';
276 return $sw ? '<small>' . $pg_passage . '</small>' : ' ' . $pg_passage;
279 // Last-Modified header
280 function header_lastmod($page = NULL)
284 if ($lastmod && is_page($page)) {
286 header('Last-Modified: ' .
287 date('D, d M Y H:i:s', get_filetime($page)) . ' GMT');
291 // Get a page list of this wiki
292 function get_existpages($dir = DATA_DIR, $ext = '.txt')
296 $pattern = '((?:[0-9A-F]{2})+)';
297 if ($ext != '') $ext = preg_quote($ext, '/');
298 $pattern = '/^' . $pattern . $ext . '$/';
300 $dp = @opendir($dir) or
301 die_message($dir . ' is not found or not readable.');
303 while ($file = readdir($dp))
304 if (preg_match($pattern, $file, $matches))
305 $aryret[$file] = decode($matches[1]);
311 // Get PageReading(pronounce-annotated) data in an array()
312 function get_readings()
314 global $pagereading_enable, $pagereading_kanji2kana_converter;
315 global $pagereading_kanji2kana_encoding, $pagereading_chasen_path;
316 global $pagereading_kakasi_path, $pagereading_config_page;
317 global $pagereading_config_dict;
319 $pages = get_existpages();
322 foreach ($pages as $page)
323 $readings[$page] = '';
325 $deletedPage = FALSE;
327 foreach (get_source($pagereading_config_page) as $line) {
329 if(preg_match('/^-\[\[([^]]+)\]\]\s+(.+)$/', $line, $matches)) {
330 if(isset($readings[$matches[1]])) {
331 // This page is not clear how to be pronounced
332 $readings[$matches[1]] = $matches[2];
334 // This page seems deleted
340 // If enabled ChaSen/KAKASI execution
341 if($pagereading_enable) {
343 // Check there's non-clear-pronouncing page
344 $unknownPage = FALSE;
345 foreach ($readings as $page => $reading) {
352 // Execute ChaSen/KAKASI, and get annotation
354 switch(strtolower($pagereading_kanji2kana_converter)) {
356 if(! file_exists($pagereading_chasen_path))
357 die_message('ChaSen not found: ' . $pagereading_chasen_path);
359 $tmpfname = tempnam(CACHE_DIR, 'PageReading');
360 $fp = fopen($tmpfname, 'w') or
361 die_message('Cannot write temporary file "' . $tmpfname . '".' . "\n");
362 foreach ($readings as $page => $reading) {
363 if($reading != '') continue;
364 fputs($fp, mb_convert_encoding($page . "\n",
365 $pagereading_kanji2kana_encoding, SOURCE_ENCODING));
369 $chasen = "$pagereading_chasen_path -F %y $tmpfname";
370 $fp = popen($chasen, 'r');
373 die_message('ChaSen execution failed: ' . $chasen);
375 foreach ($readings as $page => $reading) {
376 if($reading != '') continue;
379 $line = mb_convert_encoding($line, SOURCE_ENCODING,
380 $pagereading_kanji2kana_encoding);
382 $readings[$page] = $line;
387 die_message('Temporary file can not be removed: ' . $tmpfname);
390 case 'kakasi': /*FALLTHROUGH*/
392 if(! file_exists($pagereading_kakasi_path))
393 die_message('KAKASI not found: ' . $pagereading_kakasi_path);
395 $tmpfname = tempnam(CACHE_DIR, 'PageReading');
396 $fp = fopen($tmpfname, 'w') or
397 die_message('Cannot write temporary file "' . $tmpfname . '".' . "\n");
398 foreach ($readings as $page => $reading) {
399 if($reading != '') continue;
400 fputs($fp, mb_convert_encoding($page . "\n",
401 $pagereading_kanji2kana_encoding, SOURCE_ENCODING));
405 $kakasi = "$pagereading_kakasi_path -kK -HK -JK < $tmpfname";
406 $fp = popen($kakasi, 'r');
409 die_message('KAKASI execution failed: ' . $kakasi);
412 foreach ($readings as $page => $reading) {
413 if($reading != '') continue;
416 $line = mb_convert_encoding($line, SOURCE_ENCODING,
417 $pagereading_kanji2kana_encoding);
419 $readings[$page] = $line;
424 die_message('Temporary file can not be removed: ' . $tmpfname);
428 $patterns = $replacements = $matches = array();
429 foreach (get_source($pagereading_config_dict) as $line) {
431 if(preg_match('|^ /([^/]+)/,\s*(.+)$|', $line, $matches)) {
432 $patterns[] = $matches[1];
433 $replacements[] = $matches[2];
436 foreach ($readings as $page => $reading) {
437 if($reading != '') continue;
439 $readings[$page] = $page;
440 foreach ($patterns as $no => $pattern)
441 $readings[$page] = mb_convert_kana(mb_ereg_replace($pattern,
442 $replacements[$no], $readings[$page]), 'aKCV');
447 die_message('Unknown kanji-kana converter: ' . $pagereading_kanji2kana_converter . '.');
452 if($unknownPage || $deletedPage) {
454 asort($readings); // Sort by pronouncing(alphabetical/reading) order
456 foreach ($readings as $page => $reading)
457 $body .= '-[[' . $page . ']] ' . $reading . "\n";
459 page_write($pagereading_config_page, $body);
463 // Pages that are not prounouncing-clear, return pagenames of themselves
464 foreach ($pages as $page) {
465 if($readings[$page] == '')
466 $readings[$page] = $page;
472 // Get a list of encoded files (must specify a directory and a suffix)
473 function get_existfiles($dir, $ext)
475 $pattern = '/^(?:[0-9A-F]{2})+' . preg_quote($ext, '/') . '$/';
477 $dp = @opendir($dir) or die_message($dir . ' is not found or not readable.');
478 while ($file = readdir($dp))
479 if (preg_match($pattern, $file))
480 $aryret[] = $dir . $file;
485 // Get a list of related pages of the page
486 function links_get_related($page)
488 global $vars, $related;
489 static $links = array();
491 if (isset($links[$page])) return $links[$page];
493 // If possible, merge related pages generated by make_link()
494 $links[$page] = ($page == $vars['page']) ? $related : array();
496 // Get repated pages from DB
497 $links[$page] += links_get_related_db($vars['page']);
499 return $links[$page];