OSDN Git Service

a8bc474a70082214ad92640b2f4d5631f2ce24b1
[pukiwiki/pukiwiki.git] / lib / file.php
1 <?php
2 // PukiWiki - Yet another WikiWikiWeb clone.
3 // $Id: file.php,v 1.41 2005/12/09 17:52:20 teanan 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, $lock = TRUE)
13 {
14         $array = array();
15
16         if (is_page($page)) {
17                 $path  = get_filename($page);
18
19                 if ($lock) {
20                         $fp = @fopen($path, 'r');
21                         if ($fp == FALSE) return $array;
22                         flock($fp, LOCK_SH);
23                 }
24
25                 // Removing line-feeds: Because file() doesn't remove them.
26                 $array = str_replace("\r", '', file($path));
27
28                 if ($lock) {
29                         flock($fp, LOCK_UN);
30                         @fclose($fp);
31                 }
32         }
33
34         return $array;
35 }
36
37 // Get last-modified filetime of the page
38 function get_filetime($page)
39 {
40         return is_page($page) ? filemtime(get_filename($page)) - LOCALZONE : 0;
41 }
42
43 // Get physical file name of the page
44 function get_filename($page)
45 {
46         return DATA_DIR . encode($page) . '.txt';
47 }
48
49 // Put a data(wiki text) into a physical file(diff, backup, text)
50 function page_write($page, $postdata, $notimestamp = FALSE)
51 {
52         global $trackback;
53
54         if (PKWK_READONLY) return; // Do nothing
55
56         $postdata = make_str_rules($postdata);
57
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);
62
63         // Create backup
64         make_backup($page, $postdata == ''); // Is $postdata null?
65
66         // Create wiki text
67         file_write(DATA_DIR, $page, $postdata, $notimestamp);
68
69         if ($trackback) {
70                 // TrackBack Ping
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);
75         }
76
77         links_update($page);
78 }
79
80 // Modify ogirinal text with user-defined / system-defined rules
81 function make_str_rules($source)
82 {
83         global $str_rules, $fixed_heading_anchor;
84
85         $lines = explode("\n", $source);
86         $count = count($lines);
87
88         $modify    = TRUE;
89         $multiline = 0;
90         $matches   = array();
91         for ($i = 0; $i < $count; $i++) {
92                 $line = & $lines[$i]; // Modify directly
93
94                 // Ignore null string and preformatted texts
95                 if ($line == '' || $line{0} == ' ' || $line{0} == "\t") continue;
96
97                 // Modify this line?
98                 if ($modify) {
99                         if (! PKWKEXP_DISABLE_MULTILINE_PLUGIN_HACK &&
100                             $multiline == 0 &&
101                             preg_match('/#[^{]*(\{\{+)\s*$/', $line, $matches)) {
102                                 // Multiline convert plugin start
103                                 $modify    = FALSE;
104                                 $multiline = strlen($matches[1]); // Set specific number
105                         }
106                 } else {
107                         if (! PKWKEXP_DISABLE_MULTILINE_PLUGIN_HACK &&
108                             $multiline != 0 &&
109                             preg_match('/^\}{' . $multiline . '}\s*$/', $line)) {
110                                 // Multiline convert plugin end
111                                 $modify    = TRUE;
112                                 $multiline = 0;
113                         }
114                 }
115                 if ($modify === FALSE) continue;
116
117                 // Replace with $str_rules
118                 foreach ($str_rules as $pattern => $replacement)
119                         $line = preg_replace('/' . $pattern . '/', $replacement, $line);
120                 
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 . ']';
128                 }
129         }
130
131         // Multiline part has no stopper
132         if (! PKWKEXP_DISABLE_MULTILINE_PLUGIN_HACK &&
133             $modify === FALSE && $multiline != 0)
134                 $lines[] = str_repeat('}', $multiline);
135
136         return implode("\n", $lines);
137 }
138
139 // Generate ID
140 function generate_fixed_heading_anchor_id($seed)
141 {
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)),
145                 mt_rand(0, 24), 7);
146 }
147
148 // Output to a file
149 function file_write($dir, $page, $str, $notimestamp = FALSE)
150 {
151         global $update_exec, $_msg_invalidiwn, $notify, $notify_diff_only, $notify_subject;
152         global $non_list, $whatsdeleted, $maxshow_deleted;
153
154         if (PKWK_READONLY) return; // Do nothing
155
156         if (! is_pagename($page))
157                 die_message(str_replace('$1', htmlspecialchars($page),
158                             str_replace('$2', 'WikiName', $_msg_invalidiwn)));
159
160         $page      = strip_bracket($page);
161         $file      = $dir . encode($page) . '.txt';
162         $timestamp = FALSE;
163
164         if ($str === '') {
165                 $non_list_pattern = '/' . $non_list . '/';
166                 if ($dir == DATA_DIR && file_exists($file) && !preg_match($non_list_pattern, $page)) {
167                         // File deletion
168                         unlink($file);
169                         add_recent($page, $whatsdeleted, '', $maxshow_deleted); // RecentDeleted
170                 }
171         } else {
172                 // File replacement (Edit)
173                 $str = rtrim(preg_replace('/' . "\r" . '/', '', $str)) . "\n";
174
175                 if ($notimestamp && file_exists($file))
176                         $timestamp = filemtime($file) - LOCALZONE;
177
178                 $fp = fopen($file, 'a') or die('fopen() failed: ' .
179                         htmlspecialchars(basename($dir) . '/' . encode($page) . '.txt') .       
180                         '<br />' . "\n" .
181                         'Maybe permission is not writable or filename is too long');
182                 set_file_buffer($fp, 0);
183
184                 flock($fp, LOCK_EX);
185
186                 // Write
187                 ftruncate($fp, 0);
188                 rewind($fp);
189                 fputs($fp, $str);
190
191                 flock($fp, LOCK_UN);
192
193                 fclose($fp);
194
195                 if ($timestamp) pkwk_touch_file($file, $timestamp + LOCALZONE);
196         }
197
198         // Clear is_page() cache
199         is_page($page, TRUE);
200
201         if (! $timestamp && $dir == DATA_DIR)
202                 put_lastmodified();
203
204         // Execute $update_exec here
205         if ($update_exec && $dir == DATA_DIR)
206                 system($update_exec . ' > /dev/null &');
207
208         if ($notify && $dir == DIFF_DIR) {
209                 if ($notify_diff_only) $str = preg_replace('/^[^-+].*\n/m', '', $str);
210
211                 $footer['ACTION'] = 'Page update';
212                 $footer['PAGE']   = & $page;
213                 $footer['URI']    = get_script_uri() . '?' . rawurlencode($page);
214                 $footer['USER_AGENT']  = TRUE;
215                 $footer['REMOTE_ADDR'] = TRUE;
216
217                 pkwk_mail_notify($notify_subject, $str, $footer) or
218                         die('pkwk_mail_notify(): Failed');
219         }
220 }
221
222 // Update RecentDeleted
223 function add_recent($page, $recentpage, $subject = '', $limit = 0)
224 {
225         if (PKWK_READONLY || $limit == 0 || $page == '' || $recentpage == '') return;
226
227         // Load
228         $lines = $matches = array();
229         foreach (get_source($recentpage) as $line)
230                 if (preg_match('/^-(.+) - (\[\[.+\]\])$/', $line, $matches))
231                         $lines[$matches[2]] = $line;
232
233         $_page = '[[' . $page . ']]';
234
235         // Remove a report about the same page
236         if (isset($lines[$_page])) unset($lines[$_page]);
237
238         // Add
239         array_unshift($lines, '-' . format_date(UTIME) . ' - ' . $_page .
240                 htmlspecialchars($subject) . "\n");
241
242         // Get latest $limit reports
243         $lines = array_splice($lines, 0, $limit);
244
245         // Update
246         $fp = fopen(get_filename($recentpage), 'w') or
247                 die_message('Cannot write page file ' .
248                 htmlspecialchars($recentpage) .
249                 '<br />Maybe permission is not writable or filename is too long');
250         set_file_buffer($fp, 0);
251         flock($fp, LOCK_EX);
252         rewind($fp);
253         fputs($fp, '#freeze'    . "\n");
254         fputs($fp, '#norelated' . "\n"); // :)
255         fputs($fp, join('', $lines));
256         flock($fp, LOCK_UN);
257         fclose($fp);
258 }
259
260 // Update RecentChanges
261 function put_lastmodified()
262 {
263         global $maxshow, $whatsnew, $non_list, $autolink;
264
265         if (PKWK_READONLY) return; // Do nothing
266
267         $pages = get_existpages();
268         $recent_pages = array();
269         $non_list_pattern = '/' . $non_list . '/';
270         foreach($pages as $page)
271                 if ($page != $whatsnew && ! preg_match($non_list_pattern, $page))
272                         $recent_pages[$page] = get_filetime($page);
273
274         // Sort decending order of last-modification date
275         arsort($recent_pages, SORT_NUMERIC);
276
277         // Create recent.dat (for recent.inc.php)
278         $fp = fopen(CACHE_DIR . 'recent.dat', 'w') or
279                 die_message('Cannot write cache file ' .
280                 CACHE_DIR . 'recent.dat' .
281                 '<br />Maybe permission is not writable or filename is too long');
282
283         set_file_buffer($fp, 0);
284         flock($fp, LOCK_EX);
285         rewind($fp);
286         foreach ($recent_pages as $page=>$time)
287                 fputs($fp, $time . "\t" . $page . "\n");
288         flock($fp, LOCK_UN);
289         fclose($fp);
290
291         // Create RecentChanges
292         $fp = fopen(get_filename($whatsnew), 'w') or
293                 die_message('Cannot write page file ' .
294                 htmlspecialchars($whatsnew) .
295                 '<br />Maybe permission is not writable or filename is too long');
296
297         set_file_buffer($fp, 0);
298         flock($fp, LOCK_EX);
299         rewind($fp);
300
301         // BugTrack2/106: Only variables can be passed by reference from PHP 5.0.5
302         $tmp_array = array_keys($recent_pages); // with array_splice()
303
304         foreach (array_splice($tmp_array, 0, $maxshow) as $page) {
305                 $time      = $recent_pages[$page];
306                 $s_lastmod = htmlspecialchars(format_date($time));
307                 $s_page    = htmlspecialchars($page);
308                 fputs($fp, '-' . $s_lastmod . ' - [[' . $s_page . ']]' . "\n");
309         }
310         fputs($fp, '#norelated' . "\n"); // :)
311         flock($fp, LOCK_UN);
312         fclose($fp);
313
314         // For AutoLink
315         if ($autolink) {
316                 list($pattern, $pattern_a, $forceignorelist) =
317                         get_autolink_pattern($pages);
318
319                 $fp = fopen(CACHE_DIR . 'autolink.dat', 'w') or
320                         die_message('Cannot write autolink file ' .
321                         CACHE_DIR . '/autolink.dat' .
322                         '<br />Maybe permission is not writable');
323                 set_file_buffer($fp, 0);
324                 flock($fp, LOCK_EX);
325                 rewind($fp);
326                 fputs($fp, $pattern   . "\n");
327                 fputs($fp, $pattern_a . "\n");
328                 fputs($fp, join("\t", $forceignorelist) . "\n");
329                 flock($fp, LOCK_UN);
330                 fclose($fp);
331         }
332 }
333
334 // Get elapsed date of the pate
335 function get_pg_passage($page, $sw = TRUE)
336 {
337         global $show_passage;
338         if (! $show_passage) return '';
339
340         $time = get_filetime($page);
341         $pg_passage = ($time != 0) ? get_passage($time) : '';
342
343         return $sw ? '<small>' . $pg_passage . '</small>' : ' ' . $pg_passage;
344 }
345
346 // Last-Modified header
347 function header_lastmod($page = NULL)
348 {
349         global $lastmod;
350
351         if ($lastmod && is_page($page)) {
352                 pkwk_headers_sent();
353                 header('Last-Modified: ' .
354                         date('D, d M Y H:i:s', get_filetime($page)) . ' GMT');
355         }
356 }
357
358 // Get a page list of this wiki
359 function get_existpages($dir = DATA_DIR, $ext = '.txt')
360 {
361         $aryret = array();
362
363         $pattern = '((?:[0-9A-F]{2})+)';
364         if ($ext != '') $ext = preg_quote($ext, '/');
365         $pattern = '/^' . $pattern . $ext . '$/';
366
367         $dp = @opendir($dir) or
368                 die_message($dir . ' is not found or not readable.');
369         $matches = array();
370         while ($file = readdir($dp))
371                 if (preg_match($pattern, $file, $matches))
372                         $aryret[$file] = decode($matches[1]);
373         closedir($dp);
374
375         return $aryret;
376 }
377
378 // Get PageReading(pronounce-annotated) data in an array()
379 function get_readings()
380 {
381         global $pagereading_enable, $pagereading_kanji2kana_converter;
382         global $pagereading_kanji2kana_encoding, $pagereading_chasen_path;
383         global $pagereading_kakasi_path, $pagereading_config_page;
384         global $pagereading_config_dict;
385
386         $pages = get_existpages();
387
388         $readings = array();
389         foreach ($pages as $page) 
390                 $readings[$page] = '';
391
392         $deletedPage = FALSE;
393         $matches = array();
394         foreach (get_source($pagereading_config_page) as $line) {
395                 $line = chop($line);
396                 if(preg_match('/^-\[\[([^]]+)\]\]\s+(.+)$/', $line, $matches)) {
397                         if(isset($readings[$matches[1]])) {
398                                 // This page is not clear how to be pronounced
399                                 $readings[$matches[1]] = $matches[2];
400                         } else {
401                                 // This page seems deleted
402                                 $deletedPage = TRUE;
403                         }
404                 }
405         }
406
407         // If enabled ChaSen/KAKASI execution
408         if($pagereading_enable) {
409
410                 // Check there's non-clear-pronouncing page
411                 $unknownPage = FALSE;
412                 foreach ($readings as $page => $reading) {
413                         if($reading == '') {
414                                 $unknownPage = TRUE;
415                                 break;
416                         }
417                 }
418
419                 // Execute ChaSen/KAKASI, and get annotation
420                 if($unknownPage) {
421                         switch(strtolower($pagereading_kanji2kana_converter)) {
422                         case 'chasen':
423                                 if(! file_exists($pagereading_chasen_path))
424                                         die_message('ChaSen not found: ' . $pagereading_chasen_path);
425
426                                 $tmpfname = tempnam(CACHE_DIR, 'PageReading');
427                                 $fp = fopen($tmpfname, 'w') or
428                                         die_message('Cannot write temporary file "' . $tmpfname . '".' . "\n");
429                                 foreach ($readings as $page => $reading) {
430                                         if($reading != '') continue;
431                                         fputs($fp, mb_convert_encoding($page . "\n",
432                                                 $pagereading_kanji2kana_encoding, SOURCE_ENCODING));
433                                 }
434                                 fclose($fp);
435
436                                 $chasen = "$pagereading_chasen_path -F %y $tmpfname";
437                                 $fp     = popen($chasen, 'r');
438                                 if($fp === FALSE) {
439                                         unlink($tmpfname);
440                                         die_message('ChaSen execution failed: ' . $chasen);
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 'kakasi':  /*FALLTHROUGH*/
458                         case 'kakashi':
459                                 if(! file_exists($pagereading_kakasi_path))
460                                         die_message('KAKASI not found: ' . $pagereading_kakasi_path);
461
462                                 $tmpfname = tempnam(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));
469                                 }
470                                 fclose($fp);
471
472                                 $kakasi = "$pagereading_kakasi_path -kK -HK -JK < $tmpfname";
473                                 $fp     = popen($kakasi, 'r');
474                                 if($fp === FALSE) {
475                                         unlink($tmpfname);
476                                         die_message('KAKASI execution failed: ' . $kakasi);
477                                 }
478
479                                 foreach ($readings as $page => $reading) {
480                                         if($reading != '') continue;
481
482                                         $line = fgets($fp);
483                                         $line = mb_convert_encoding($line, SOURCE_ENCODING,
484                                                 $pagereading_kanji2kana_encoding);
485                                         $line = chop($line);
486                                         $readings[$page] = $line;
487                                 }
488                                 pclose($fp);
489
490                                 unlink($tmpfname) or
491                                         die_message('Temporary file can not be removed: ' . $tmpfname);
492                                 break;
493
494                         case 'none':
495                                 $patterns = $replacements = $matches = array();
496                                 foreach (get_source($pagereading_config_dict) as $line) {
497                                         $line = chop($line);
498                                         if(preg_match('|^ /([^/]+)/,\s*(.+)$|', $line, $matches)) {
499                                                 $patterns[]     = $matches[1];
500                                                 $replacements[] = $matches[2];
501                                         }
502                                 }
503                                 foreach ($readings as $page => $reading) {
504                                         if($reading != '') continue;
505
506                                         $readings[$page] = $page;
507                                         foreach ($patterns as $no => $pattern)
508                                                 $readings[$page] = mb_convert_kana(mb_ereg_replace($pattern,
509                                                         $replacements[$no], $readings[$page]), 'aKCV');
510                                 }
511                                 break;
512
513                         default:
514                                 die_message('Unknown kanji-kana converter: ' . $pagereading_kanji2kana_converter . '.');
515                                 break;
516                         }
517                 }
518
519                 if($unknownPage || $deletedPage) {
520
521                         asort($readings); // Sort by pronouncing(alphabetical/reading) order
522                         $body = '';
523                         foreach ($readings as $page => $reading)
524                                 $body .= '-[[' . $page . ']] ' . $reading . "\n";
525
526                         page_write($pagereading_config_page, $body);
527                 }
528         }
529
530         // Pages that are not prounouncing-clear, return pagenames of themselves
531         foreach ($pages as $page) {
532                 if($readings[$page] == '')
533                         $readings[$page] = $page;
534         }
535
536         return $readings;
537 }
538
539 // Get a list of encoded files (must specify a directory and a suffix)
540 function get_existfiles($dir, $ext)
541 {
542         $pattern = '/^(?:[0-9A-F]{2})+' . preg_quote($ext, '/') . '$/';
543         $aryret = array();
544         $dp = @opendir($dir) or die_message($dir . ' is not found or not readable.');
545         while ($file = readdir($dp))
546                 if (preg_match($pattern, $file))
547                         $aryret[] = $dir . $file;
548         closedir($dp);
549         return $aryret;
550 }
551
552 // Get a list of related pages of the page
553 function links_get_related($page)
554 {
555         global $vars, $related;
556         static $links = array();
557
558         if (isset($links[$page])) return $links[$page];
559
560         // If possible, merge related pages generated by make_link()
561         $links[$page] = ($page == $vars['page']) ? $related : array();
562
563         // Get repated pages from DB
564         $links[$page] += links_get_related_db($vars['page']);
565
566         return $links[$page];
567 }
568
569 // _If needed_, re-create the file to change/correct ownership into PHP's
570 // NOTE: Not works for Windows
571 function pkwk_chown($filename, $preserve_time = TRUE)
572 {
573         static $php_uid; // PHP's UID
574
575         if (! isset($php_uid)) {
576                 if (extension_loaded('posix')) {
577                         $php_uid = posix_getuid(); // Unix
578                 } else {
579                         $php_uid = 0; // Windows
580                 }
581         }
582
583         // Lock for pkwk_chown()
584         $lockfile = CACHE_DIR . 'pkwk_chown.lock';
585         $flock = fopen($lockfile, 'a') or
586                 die('pkwk_chown(): fopen() failed for: CACHEDIR/' .
587                         basename(htmlspecialchars($lockfile)));
588         flock($flock, LOCK_EX) or die('pkwk_chown(): flock() failed for lock');
589
590         // Check owner
591         $stat = stat($filename) or
592                 die('pkwk_chown(): stat() failed for: '  . basename(htmlspecialchars($filename)));
593         if ($stat[4] === $php_uid) {
594                 // NOTE: Windows always here
595                 $result = TRUE; // Seems the same UID. Nothing to do
596         } else {
597                 $tmp = $filename . '.' . getmypid() . '.tmp';
598
599                 // Lock source $filename to avoid file corruption
600                 // NOTE: Not 'r+'. Don't check write permission here
601                 $ffile = fopen($filename, 'r') or
602                         die('pkwk_chown(): fopen() failed for: ' .
603                                 basename(htmlspecialchars($filename)));
604
605                 // Try to chown by re-creating files
606                 // NOTE:
607                 //   * touch() before copy() is for 'rw-r--r--' instead of 'rwxr-xr-x' (with umask 022).
608                 //   * (PHP 4 < PHP 4.2.0) touch() with the third argument is not implemented and retuns NULL and Warn.
609                 //   * @unlink() before rename() is for Windows but here's for Unix only
610                 flock($ffile, LOCK_EX) or die('pkwk_chown(): flock() failed');
611                 $result = touch($tmp) && copy($filename, $tmp) &&
612                         ($preserve_time ? (touch($tmp, $stat[9], $stat[8]) || touch($tmp, $stat[9])) : TRUE) &&
613                         rename($tmp, $filename);
614                 flock($ffile, LOCK_UN) or die('pkwk_chown(): flock() failed');
615
616                 fclose($ffile) or die('pkwk_chown(): fclose() failed');
617
618                 if ($result === FALSE) @unlink($tmp);
619         }
620
621         // Unlock for pkwk_chown()
622         flock($flock, LOCK_UN) or die('pkwk_chown(): flock() failed for lock');
623         fclose($flock) or die('pkwk_chown(): fclose() failed for lock');
624
625         return $result;
626 }
627
628 // touch() with trying pkwk_chown()
629 function pkwk_touch_file($filename, $time = FALSE, $atime = FALSE)
630 {
631         // Is the owner incorrected and unable to correct?
632         if (! file_exists($filename) || pkwk_chown($filename)) {
633                 if ($time === FALSE) {
634                         $result = touch($filename);
635                 } else if ($atime === FALSE) {
636                         $result = touch($filename, $time);
637                 } else {
638                         $result = touch($filename, $time, $atime);
639                 }
640                 return $result;
641         } else {
642                 die('pkwk_touch_file(): Invalid UID and (not writable for the directory or not a flie): ' .
643                         htmlspecialchars(basename($filename)));
644         }
645 }
646 ?>