OSDN Git Service

9ad23f9d2e8f96024a25ca4ebb8a0ee73316b192
[pukiwiki/pukiwiki.git] / lib / file.php
1 <?php
2 // PukiWiki - Yet another WikiWikiWeb clone.
3 // $Id: file.php,v 1.30 2005/07/03 14:16:23 henoheno Exp $
4 // Copyright (C)
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
8 //
9 // File related functions
10
11 // Get source(wiki text) data of the page
12 function get_source($page = NULL)
13 {
14         // Removing line-feeds: Because file() doesn't remove them.
15         return is_page($page) ? str_replace("\r", '', file(get_filename($page))) : array();
16 }
17
18 // Get last-modified filetime of the page
19 function get_filetime($page)
20 {
21         return is_page($page) ? filemtime(get_filename($page)) - LOCALZONE : 0;
22 }
23
24 // Get physical file name of the page
25 function get_filename($page)
26 {
27         return DATA_DIR . encode($page) . '.txt';
28 }
29
30 // Put a data(wiki text) into a physical file(diff, backup, text)
31 function page_write($page, $postdata, $notimestamp = FALSE)
32 {
33         global $trackback;
34
35         if (PKWK_READONLY) return; // Do nothing
36
37         $postdata = make_str_rules($postdata);
38
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);
43
44         // Create backup
45         make_backup($page, $postdata == ''); // Is $postdata null?
46
47         // Create wiki text
48         file_write(DATA_DIR, $page, $postdata, $notimestamp);
49
50         if ($trackback) {
51                 // TrackBack Ping
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);
56         }
57
58         links_update($page);
59 }
60
61 // Modify ogirinal text with user-defined / system-defined rules
62 function make_str_rules($source)
63 {
64         global $str_rules, $fixed_heading_anchor;
65
66         $lines = explode("\n", $source);
67         $count = count($lines);
68
69         $modify    = TRUE;
70         $multiline = 0;
71         $matches   = array();
72         for ($i = 0; $i < $count; $i++) {
73                 $line = & $lines[$i]; // Modify directly
74
75                 // Ignore null string and preformatted texts
76                 if ($line == '' || $line{0} == ' ' || $line{0} == "\t") continue;
77
78                 // Modify this line?
79                 if ($modify) {
80                         if (! PKWKEXP_DISABLE_MULTILINE_PLUGIN_HACK &&
81                             $multiline == 0 &&
82                             preg_match('/#[^{]*(\{\{+)\s*$/', $line, $matches)) {
83                                 // Multiline convert plugin start
84                                 $modify    = FALSE;
85                                 $multiline = strlen($matches[1]); // Set specific number
86                         }
87                 } else {
88                         if (! PKWKEXP_DISABLE_MULTILINE_PLUGIN_HACK &&
89                             $multiline != 0 &&
90                             preg_match('/^\}{' . $multiline . '}\s*$/', $line)) {
91                                 // Multiline convert plugin end
92                                 $modify    = TRUE;
93                                 $multiline = 0;
94                         }
95                 }
96                 if ($modify === FALSE) continue;
97
98                 // Replace with $str_rules
99                 foreach ($str_rules as $pattern => $replacement)
100                         $line = preg_replace('/' . $pattern . '/', $replacement, $line);
101                 
102                 // Adding fixed anchor into headings
103                 if ($fixed_heading_anchor &&
104                         preg_match('/^(\*{1,3}(.(?!\[#[A-Za-z][\w-]+\]))+)$/', $line, $matches))
105                 {
106                         // Generate ID:
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 . ']';
111                 }
112         }
113
114         // Multiline part has no stopper
115         if (! PKWKEXP_DISABLE_MULTILINE_PLUGIN_HACK &&
116             $modify === FALSE && $multiline != 0)
117                 $lines[] = str_repeat('}', $multiline);
118
119         return implode("\n", $lines);
120 }
121
122 // Output to a file
123 function file_write($dir, $page, $str, $notimestamp = FALSE)
124 {
125         global $update_exec, $_msg_invalidiwn, $notify, $notify_diff_only, $notify_subject;
126         global $whatsdeleted, $maxshow_deleted;
127
128         if (PKWK_READONLY) return; // Do nothing
129
130         if (! is_pagename($page))
131                 die_message(str_replace('$1', htmlspecialchars($page),
132                             str_replace('$2', 'WikiName', $_msg_invalidiwn)));
133
134         $page      = strip_bracket($page);
135         $timestamp = FALSE;
136         $file      = $dir . encode($page) . '.txt';
137
138         if ($dir == DATA_DIR && $str == '' && file_exists($file)) {
139                 unlink($file);
140                 add_recent($page, $whatsdeleted, '', $maxshow_deleted); // RecentDeleted
141         }
142
143         if ($str != '') {
144                 $str = preg_replace('/' . "\r" . '/', '', $str);
145                 $str = rtrim($str) . "\n";
146
147                 if ($notimestamp && file_exists($file))
148                         $timestamp = filemtime($file) - LOCALZONE;
149
150                 $fp = fopen($file, 'w') or die('fopen() failed: ' .
151                         htmlspecialchars(basename($dir) . '/' . encode($page) . '.txt') .       
152                         '<br />' . "\n" .
153                         'Maybe permission is not writable or filename is too long');
154
155                 set_file_buffer($fp, 0);
156                 flock($fp, LOCK_EX);
157                 rewind($fp);
158                 fputs($fp, $str);
159                 flock($fp, LOCK_UN);
160                 fclose($fp);
161
162                 if ($timestamp) pkwk_touch_file($file, $timestamp + LOCALZONE);
163         }
164
165         // Clear is_page() cache
166         is_page($page, TRUE);
167
168         if (! $timestamp && $dir == DATA_DIR)
169                 put_lastmodified();
170
171         // Execute $update_exec here
172         if ($update_exec && $dir == DATA_DIR)
173                 system($update_exec . ' > /dev/null &');
174
175         if ($notify && $dir == DIFF_DIR) {
176                 if ($notify_diff_only) $str = preg_replace('/^[^-+].*\n/m', '', $str);
177
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;
183
184                 pkwk_mail_notify($notify_subject, $str, $footer) or
185                         die('pkwk_mail_notify(): Failed');
186         }
187 }
188
189 // Update RecentDeleted
190 function add_recent($page, $recentpage, $subject = '', $limit = 0)
191 {
192         if (PKWK_READONLY || $limit == 0 || $page == '' || $recentpage == '') return;
193
194         // Load
195         $lines = $matches = array();
196         foreach (get_source($recentpage) as $line)
197                 if (preg_match('/^-(.+) - (\[\[.+\]\])$/', $line, $matches))
198                         $lines[$matches[2]] = $line;
199
200         $_page = '[[' . $page . ']]';
201
202         // Remove a report about the same page
203         if (isset($lines[$_page])) unset($lines[$_page]);
204
205         // Add
206         array_unshift($lines, '-' . format_date(UTIME) . ' - ' . $_page .
207                 htmlspecialchars($subject) . "\n");
208
209         // Get latest $limit reports
210         $lines = array_splice($lines, 0, $limit);
211
212         // Update
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);
218         flock($fp, LOCK_EX);
219         rewind($fp);
220         fputs($fp, '#freeze'    . "\n");
221         fputs($fp, '#norelated' . "\n"); // :)
222         fputs($fp, join('', $lines));
223         flock($fp, LOCK_UN);
224         fclose($fp);
225 }
226
227 // Update RecentChanges
228 function put_lastmodified()
229 {
230         global $maxshow, $whatsnew, $non_list, $autolink;
231
232         if (PKWK_READONLY) return; // Do nothing
233
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);
240
241         // Sort decending order of last-modification date
242         arsort($recent_pages, SORT_NUMERIC);
243
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');
249
250         set_file_buffer($fp, 0);
251         flock($fp, LOCK_EX);
252         rewind($fp);
253         foreach ($recent_pages as $page=>$time)
254                 fputs($fp, $time . "\t" . $page . "\n");
255         flock($fp, LOCK_UN);
256         fclose($fp);
257
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');
263
264         set_file_buffer($fp, 0);
265         flock($fp, LOCK_EX);
266         rewind($fp);
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");
272         }
273         fputs($fp, '#norelated' . "\n"); // :)
274         flock($fp, LOCK_UN);
275         fclose($fp);
276
277         // For AutoLink
278         if ($autolink) {
279                 list($pattern, $pattern_a, $forceignorelist) =
280                         get_autolink_pattern($pages);
281
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);
287                 flock($fp, LOCK_EX);
288                 rewind($fp);
289                 fputs($fp, $pattern   . "\n");
290                 fputs($fp, $pattern_a . "\n");
291                 fputs($fp, join("\t", $forceignorelist) . "\n");
292                 flock($fp, LOCK_UN);
293                 fclose($fp);
294         }
295 }
296
297 // Get elapsed date of the pate
298 function get_pg_passage($page, $sw = TRUE)
299 {
300         global $show_passage;
301         if (! $show_passage) return '';
302
303         $time = get_filetime($page);
304         $pg_passage = ($time != 0) ? get_passage($time) : '';
305
306         return $sw ? '<small>' . $pg_passage . '</small>' : ' ' . $pg_passage;
307 }
308
309 // Last-Modified header
310 function header_lastmod($page = NULL)
311 {
312         global $lastmod;
313
314         if ($lastmod && is_page($page)) {
315                 pkwk_headers_sent();
316                 header('Last-Modified: ' .
317                         date('D, d M Y H:i:s', get_filetime($page)) . ' GMT');
318         }
319 }
320
321 // Get a page list of this wiki
322 function get_existpages($dir = DATA_DIR, $ext = '.txt')
323 {
324         $aryret = array();
325
326         $pattern = '((?:[0-9A-F]{2})+)';
327         if ($ext != '') $ext = preg_quote($ext, '/');
328         $pattern = '/^' . $pattern . $ext . '$/';
329
330         $dp = @opendir($dir) or
331                 die_message($dir . ' is not found or not readable.');
332         $matches = array();
333         while ($file = readdir($dp))
334                 if (preg_match($pattern, $file, $matches))
335                         $aryret[$file] = decode($matches[1]);
336         closedir($dp);
337
338         return $aryret;
339 }
340
341 // Get PageReading(pronounce-annotated) data in an array()
342 function get_readings()
343 {
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;
348
349         $pages = get_existpages();
350
351         $readings = array();
352         foreach ($pages as $page) 
353                 $readings[$page] = '';
354
355         $deletedPage = FALSE;
356         $matches = array();
357         foreach (get_source($pagereading_config_page) as $line) {
358                 $line = chop($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];
363                         } else {
364                                 // This page seems deleted
365                                 $deletedPage = TRUE;
366                         }
367                 }
368         }
369
370         // If enabled ChaSen/KAKASI execution
371         if($pagereading_enable) {
372
373                 // Check there's non-clear-pronouncing page
374                 $unknownPage = FALSE;
375                 foreach ($readings as $page => $reading) {
376                         if($reading == '') {
377                                 $unknownPage = TRUE;
378                                 break;
379                         }
380                 }
381
382                 // Execute ChaSen/KAKASI, and get annotation
383                 if($unknownPage) {
384                         switch(strtolower($pagereading_kanji2kana_converter)) {
385                         case 'chasen':
386                                 if(! file_exists($pagereading_chasen_path))
387                                         die_message('ChaSen not found: ' . $pagereading_chasen_path);
388
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));
396                                 }
397                                 fclose($fp);
398
399                                 $chasen = "$pagereading_chasen_path -F %y $tmpfname";
400                                 $fp     = popen($chasen, 'r');
401                                 if($fp === FALSE) {
402                                         unlink($tmpfname);
403                                         die_message('ChaSen execution failed: ' . $chasen);
404                                 }
405                                 foreach ($readings as $page => $reading) {
406                                         if($reading != '') continue;
407
408                                         $line = fgets($fp);
409                                         $line = mb_convert_encoding($line, SOURCE_ENCODING,
410                                                 $pagereading_kanji2kana_encoding);
411                                         $line = chop($line);
412                                         $readings[$page] = $line;
413                                 }
414                                 pclose($fp);
415
416                                 unlink($tmpfname) or
417                                         die_message('Temporary file can not be removed: ' . $tmpfname);
418                                 break;
419
420                         case 'kakasi':  /*FALLTHROUGH*/
421                         case 'kakashi':
422                                 if(! file_exists($pagereading_kakasi_path))
423                                         die_message('KAKASI not found: ' . $pagereading_kakasi_path);
424
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));
432                                 }
433                                 fclose($fp);
434
435                                 $kakasi = "$pagereading_kakasi_path -kK -HK -JK < $tmpfname";
436                                 $fp     = popen($kakasi, 'r');
437                                 if($fp === FALSE) {
438                                         unlink($tmpfname);
439                                         die_message('KAKASI execution failed: ' . $kakasi);
440                                 }
441
442                                 foreach ($readings as $page => $reading) {
443                                         if($reading != '') continue;
444
445                                         $line = fgets($fp);
446                                         $line = mb_convert_encoding($line, SOURCE_ENCODING,
447                                                 $pagereading_kanji2kana_encoding);
448                                         $line = chop($line);
449                                         $readings[$page] = $line;
450                                 }
451                                 pclose($fp);
452
453                                 unlink($tmpfname) or
454                                         die_message('Temporary file can not be removed: ' . $tmpfname);
455                                 break;
456
457                         case 'none':
458                                 $patterns = $replacements = $matches = array();
459                                 foreach (get_source($pagereading_config_dict) as $line) {
460                                         $line = chop($line);
461                                         if(preg_match('|^ /([^/]+)/,\s*(.+)$|', $line, $matches)) {
462                                                 $patterns[]     = $matches[1];
463                                                 $replacements[] = $matches[2];
464                                         }
465                                 }
466                                 foreach ($readings as $page => $reading) {
467                                         if($reading != '') continue;
468
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');
473                                 }
474                                 break;
475
476                         default:
477                                 die_message('Unknown kanji-kana converter: ' . $pagereading_kanji2kana_converter . '.');
478                                 break;
479                         }
480                 }
481
482                 if($unknownPage || $deletedPage) {
483
484                         asort($readings); // Sort by pronouncing(alphabetical/reading) order
485                         $body = '';
486                         foreach ($readings as $page => $reading)
487                                 $body .= '-[[' . $page . ']] ' . $reading . "\n";
488
489                         page_write($pagereading_config_page, $body);
490                 }
491         }
492
493         // Pages that are not prounouncing-clear, return pagenames of themselves
494         foreach ($pages as $page) {
495                 if($readings[$page] == '')
496                         $readings[$page] = $page;
497         }
498
499         return $readings;
500 }
501
502 // Get a list of encoded files (must specify a directory and a suffix)
503 function get_existfiles($dir, $ext)
504 {
505         $pattern = '/^(?:[0-9A-F]{2})+' . preg_quote($ext, '/') . '$/';
506         $aryret = array();
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;
511         closedir($dp);
512         return $aryret;
513 }
514
515 // Get a list of related pages of the page
516 function links_get_related($page)
517 {
518         global $vars, $related;
519         static $links = array();
520
521         if (isset($links[$page])) return $links[$page];
522
523         // If possible, merge related pages generated by make_link()
524         $links[$page] = ($page == $vars['page']) ? $related : array();
525
526         // Get repated pages from DB
527         $links[$page] += links_get_related_db($vars['page']);
528
529         return $links[$page];
530 }
531
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)
535 {
536         static $php_uid; // PHP's UID
537
538         if (! isset($php_uid)) {
539                 if (extension_loaded('posix')) {
540                         $php_uid = posix_getuid(); // Unix
541                 } else {
542                         $php_uid = 0; // Windows
543                 }
544         }
545
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');
552
553         // Check owner
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
559         } else {
560                 $tmp = $filename . '.' . getmypid() . '.tmp';
561
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)));
567
568                 // Try to chown by re-creating files
569                 // NOTE:
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');
578
579                 fclose($ffile) or die('pkwk_chown(): fclose() failed');
580
581                 if ($result === FALSE) @unlink($tmp);
582         }
583
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');
587
588         return $result;
589 }
590
591 // touch() with trying pkwk_chown()
592 function pkwk_touch_file($filename, $time = FALSE, $atime = FALSE)
593 {
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);
600                 } else {
601                         $result = touch($filename, $time, $atime);
602                 }
603                 return $result;
604         } else {
605                 die('pkwk_touch_file(): Invalid UID and (not writable for the directory or not a flie): ' .
606                         htmlspecialchars(basename($filename)));
607         }
608 }
609 ?>