OSDN Git Service

BugTrack2/106: Inserted BugTrack no to the comments
[pukiwiki/pukiwiki.git] / lib / file.php
1 <?php
2 // PukiWiki - Yet another WikiWikiWeb clone.
3 // $Id: file.php,v 1.40 2005/10/04 13:41:03 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, $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 $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                 if ($dir == DATA_DIR && file_exists($file)) {
166                         // File deletion
167                         unlink($file);
168                         add_recent($page, $whatsdeleted, '', $maxshow_deleted); // RecentDeleted
169                 }
170         } else {
171                 // File replacement (Edit)
172                 $str = rtrim(preg_replace('/' . "\r" . '/', '', $str)) . "\n";
173
174                 if ($notimestamp && file_exists($file))
175                         $timestamp = filemtime($file) - LOCALZONE;
176
177                 $fp = fopen($file, 'a') or die('fopen() failed: ' .
178                         htmlspecialchars(basename($dir) . '/' . encode($page) . '.txt') .       
179                         '<br />' . "\n" .
180                         'Maybe permission is not writable or filename is too long');
181                 set_file_buffer($fp, 0);
182
183                 flock($fp, LOCK_EX);
184
185                 // Write
186                 ftruncate($fp, 0);
187                 rewind($fp);
188                 fputs($fp, $str);
189
190                 flock($fp, LOCK_UN);
191
192                 fclose($fp);
193
194                 if ($timestamp) pkwk_touch_file($file, $timestamp + LOCALZONE);
195         }
196
197         // Clear is_page() cache
198         is_page($page, TRUE);
199
200         if (! $timestamp && $dir == DATA_DIR)
201                 put_lastmodified();
202
203         // Execute $update_exec here
204         if ($update_exec && $dir == DATA_DIR)
205                 system($update_exec . ' > /dev/null &');
206
207         if ($notify && $dir == DIFF_DIR) {
208                 if ($notify_diff_only) $str = preg_replace('/^[^-+].*\n/m', '', $str);
209
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;
215
216                 pkwk_mail_notify($notify_subject, $str, $footer) or
217                         die('pkwk_mail_notify(): Failed');
218         }
219 }
220
221 // Update RecentDeleted
222 function add_recent($page, $recentpage, $subject = '', $limit = 0)
223 {
224         if (PKWK_READONLY || $limit == 0 || $page == '' || $recentpage == '') return;
225
226         // Load
227         $lines = $matches = array();
228         foreach (get_source($recentpage) as $line)
229                 if (preg_match('/^-(.+) - (\[\[.+\]\])$/', $line, $matches))
230                         $lines[$matches[2]] = $line;
231
232         $_page = '[[' . $page . ']]';
233
234         // Remove a report about the same page
235         if (isset($lines[$_page])) unset($lines[$_page]);
236
237         // Add
238         array_unshift($lines, '-' . format_date(UTIME) . ' - ' . $_page .
239                 htmlspecialchars($subject) . "\n");
240
241         // Get latest $limit reports
242         $lines = array_splice($lines, 0, $limit);
243
244         // Update
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);
250         flock($fp, LOCK_EX);
251         rewind($fp);
252         fputs($fp, '#freeze'    . "\n");
253         fputs($fp, '#norelated' . "\n"); // :)
254         fputs($fp, join('', $lines));
255         flock($fp, LOCK_UN);
256         fclose($fp);
257 }
258
259 // Update RecentChanges
260 function put_lastmodified()
261 {
262         global $maxshow, $whatsnew, $non_list, $autolink;
263
264         if (PKWK_READONLY) return; // Do nothing
265
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);
272
273         // Sort decending order of last-modification date
274         arsort($recent_pages, SORT_NUMERIC);
275
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');
281
282         set_file_buffer($fp, 0);
283         flock($fp, LOCK_EX);
284         rewind($fp);
285         foreach ($recent_pages as $page=>$time)
286                 fputs($fp, $time . "\t" . $page . "\n");
287         flock($fp, LOCK_UN);
288         fclose($fp);
289
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');
295
296         set_file_buffer($fp, 0);
297         flock($fp, LOCK_EX);
298         rewind($fp);
299
300         // BugTrack2/106: Only variables can be passed by reference from PHP 5.0.5
301         $tmp_array = array_keys($recent_pages); // with array_splice()
302
303         foreach (array_splice($tmp_array, 0, $maxshow) as $page) {
304                 $time      = $recent_pages[$page];
305                 $s_lastmod = htmlspecialchars(format_date($time));
306                 $s_page    = htmlspecialchars($page);
307                 fputs($fp, '-' . $s_lastmod . ' - [[' . $s_page . ']]' . "\n");
308         }
309         fputs($fp, '#norelated' . "\n"); // :)
310         flock($fp, LOCK_UN);
311         fclose($fp);
312
313         // For AutoLink
314         if ($autolink) {
315                 list($pattern, $pattern_a, $forceignorelist) =
316                         get_autolink_pattern($pages);
317
318                 $fp = fopen(CACHE_DIR . 'autolink.dat', 'w') or
319                         die_message('Cannot write autolink file ' .
320                         CACHE_DIR . '/autolink.dat' .
321                         '<br />Maybe permission is not writable');
322                 set_file_buffer($fp, 0);
323                 flock($fp, LOCK_EX);
324                 rewind($fp);
325                 fputs($fp, $pattern   . "\n");
326                 fputs($fp, $pattern_a . "\n");
327                 fputs($fp, join("\t", $forceignorelist) . "\n");
328                 flock($fp, LOCK_UN);
329                 fclose($fp);
330         }
331 }
332
333 // Get elapsed date of the pate
334 function get_pg_passage($page, $sw = TRUE)
335 {
336         global $show_passage;
337         if (! $show_passage) return '';
338
339         $time = get_filetime($page);
340         $pg_passage = ($time != 0) ? get_passage($time) : '';
341
342         return $sw ? '<small>' . $pg_passage . '</small>' : ' ' . $pg_passage;
343 }
344
345 // Last-Modified header
346 function header_lastmod($page = NULL)
347 {
348         global $lastmod;
349
350         if ($lastmod && is_page($page)) {
351                 pkwk_headers_sent();
352                 header('Last-Modified: ' .
353                         date('D, d M Y H:i:s', get_filetime($page)) . ' GMT');
354         }
355 }
356
357 // Get a page list of this wiki
358 function get_existpages($dir = DATA_DIR, $ext = '.txt')
359 {
360         $aryret = array();
361
362         $pattern = '((?:[0-9A-F]{2})+)';
363         if ($ext != '') $ext = preg_quote($ext, '/');
364         $pattern = '/^' . $pattern . $ext . '$/';
365
366         $dp = @opendir($dir) or
367                 die_message($dir . ' is not found or not readable.');
368         $matches = array();
369         while ($file = readdir($dp))
370                 if (preg_match($pattern, $file, $matches))
371                         $aryret[$file] = decode($matches[1]);
372         closedir($dp);
373
374         return $aryret;
375 }
376
377 // Get PageReading(pronounce-annotated) data in an array()
378 function get_readings()
379 {
380         global $pagereading_enable, $pagereading_kanji2kana_converter;
381         global $pagereading_kanji2kana_encoding, $pagereading_chasen_path;
382         global $pagereading_kakasi_path, $pagereading_config_page;
383         global $pagereading_config_dict;
384
385         $pages = get_existpages();
386
387         $readings = array();
388         foreach ($pages as $page) 
389                 $readings[$page] = '';
390
391         $deletedPage = FALSE;
392         $matches = array();
393         foreach (get_source($pagereading_config_page) as $line) {
394                 $line = chop($line);
395                 if(preg_match('/^-\[\[([^]]+)\]\]\s+(.+)$/', $line, $matches)) {
396                         if(isset($readings[$matches[1]])) {
397                                 // This page is not clear how to be pronounced
398                                 $readings[$matches[1]] = $matches[2];
399                         } else {
400                                 // This page seems deleted
401                                 $deletedPage = TRUE;
402                         }
403                 }
404         }
405
406         // If enabled ChaSen/KAKASI execution
407         if($pagereading_enable) {
408
409                 // Check there's non-clear-pronouncing page
410                 $unknownPage = FALSE;
411                 foreach ($readings as $page => $reading) {
412                         if($reading == '') {
413                                 $unknownPage = TRUE;
414                                 break;
415                         }
416                 }
417
418                 // Execute ChaSen/KAKASI, and get annotation
419                 if($unknownPage) {
420                         switch(strtolower($pagereading_kanji2kana_converter)) {
421                         case 'chasen':
422                                 if(! file_exists($pagereading_chasen_path))
423                                         die_message('ChaSen not found: ' . $pagereading_chasen_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                                 $chasen = "$pagereading_chasen_path -F %y $tmpfname";
436                                 $fp     = popen($chasen, 'r');
437                                 if($fp === FALSE) {
438                                         unlink($tmpfname);
439                                         die_message('ChaSen execution failed: ' . $chasen);
440                                 }
441                                 foreach ($readings as $page => $reading) {
442                                         if($reading != '') continue;
443
444                                         $line = fgets($fp);
445                                         $line = mb_convert_encoding($line, SOURCE_ENCODING,
446                                                 $pagereading_kanji2kana_encoding);
447                                         $line = chop($line);
448                                         $readings[$page] = $line;
449                                 }
450                                 pclose($fp);
451
452                                 unlink($tmpfname) or
453                                         die_message('Temporary file can not be removed: ' . $tmpfname);
454                                 break;
455
456                         case 'kakasi':  /*FALLTHROUGH*/
457                         case 'kakashi':
458                                 if(! file_exists($pagereading_kakasi_path))
459                                         die_message('KAKASI not found: ' . $pagereading_kakasi_path);
460
461                                 $tmpfname = tempnam(CACHE_DIR, 'PageReading');
462                                 $fp       = fopen($tmpfname, 'w') or
463                                         die_message('Cannot write temporary file "' . $tmpfname . '".' . "\n");
464                                 foreach ($readings as $page => $reading) {
465                                         if($reading != '') continue;
466                                         fputs($fp, mb_convert_encoding($page . "\n",
467                                                 $pagereading_kanji2kana_encoding, SOURCE_ENCODING));
468                                 }
469                                 fclose($fp);
470
471                                 $kakasi = "$pagereading_kakasi_path -kK -HK -JK < $tmpfname";
472                                 $fp     = popen($kakasi, 'r');
473                                 if($fp === FALSE) {
474                                         unlink($tmpfname);
475                                         die_message('KAKASI execution failed: ' . $kakasi);
476                                 }
477
478                                 foreach ($readings as $page => $reading) {
479                                         if($reading != '') continue;
480
481                                         $line = fgets($fp);
482                                         $line = mb_convert_encoding($line, SOURCE_ENCODING,
483                                                 $pagereading_kanji2kana_encoding);
484                                         $line = chop($line);
485                                         $readings[$page] = $line;
486                                 }
487                                 pclose($fp);
488
489                                 unlink($tmpfname) or
490                                         die_message('Temporary file can not be removed: ' . $tmpfname);
491                                 break;
492
493                         case 'none':
494                                 $patterns = $replacements = $matches = array();
495                                 foreach (get_source($pagereading_config_dict) as $line) {
496                                         $line = chop($line);
497                                         if(preg_match('|^ /([^/]+)/,\s*(.+)$|', $line, $matches)) {
498                                                 $patterns[]     = $matches[1];
499                                                 $replacements[] = $matches[2];
500                                         }
501                                 }
502                                 foreach ($readings as $page => $reading) {
503                                         if($reading != '') continue;
504
505                                         $readings[$page] = $page;
506                                         foreach ($patterns as $no => $pattern)
507                                                 $readings[$page] = mb_convert_kana(mb_ereg_replace($pattern,
508                                                         $replacements[$no], $readings[$page]), 'aKCV');
509                                 }
510                                 break;
511
512                         default:
513                                 die_message('Unknown kanji-kana converter: ' . $pagereading_kanji2kana_converter . '.');
514                                 break;
515                         }
516                 }
517
518                 if($unknownPage || $deletedPage) {
519
520                         asort($readings); // Sort by pronouncing(alphabetical/reading) order
521                         $body = '';
522                         foreach ($readings as $page => $reading)
523                                 $body .= '-[[' . $page . ']] ' . $reading . "\n";
524
525                         page_write($pagereading_config_page, $body);
526                 }
527         }
528
529         // Pages that are not prounouncing-clear, return pagenames of themselves
530         foreach ($pages as $page) {
531                 if($readings[$page] == '')
532                         $readings[$page] = $page;
533         }
534
535         return $readings;
536 }
537
538 // Get a list of encoded files (must specify a directory and a suffix)
539 function get_existfiles($dir, $ext)
540 {
541         $pattern = '/^(?:[0-9A-F]{2})+' . preg_quote($ext, '/') . '$/';
542         $aryret = array();
543         $dp = @opendir($dir) or die_message($dir . ' is not found or not readable.');
544         while ($file = readdir($dp))
545                 if (preg_match($pattern, $file))
546                         $aryret[] = $dir . $file;
547         closedir($dp);
548         return $aryret;
549 }
550
551 // Get a list of related pages of the page
552 function links_get_related($page)
553 {
554         global $vars, $related;
555         static $links = array();
556
557         if (isset($links[$page])) return $links[$page];
558
559         // If possible, merge related pages generated by make_link()
560         $links[$page] = ($page == $vars['page']) ? $related : array();
561
562         // Get repated pages from DB
563         $links[$page] += links_get_related_db($vars['page']);
564
565         return $links[$page];
566 }
567
568 // _If needed_, re-create the file to change/correct ownership into PHP's
569 // NOTE: Not works for Windows
570 function pkwk_chown($filename, $preserve_time = TRUE)
571 {
572         static $php_uid; // PHP's UID
573
574         if (! isset($php_uid)) {
575                 if (extension_loaded('posix')) {
576                         $php_uid = posix_getuid(); // Unix
577                 } else {
578                         $php_uid = 0; // Windows
579                 }
580         }
581
582         // Lock for pkwk_chown()
583         $lockfile = CACHE_DIR . 'pkwk_chown.lock';
584         $flock = fopen($lockfile, 'a') or
585                 die('pkwk_chown(): fopen() failed for: CACHEDIR/' .
586                         basename(htmlspecialchars($lockfile)));
587         flock($flock, LOCK_EX) or die('pkwk_chown(): flock() failed for lock');
588
589         // Check owner
590         $stat = stat($filename) or
591                 die('pkwk_chown(): stat() failed for: '  . basename(htmlspecialchars($filename)));
592         if ($stat[4] === $php_uid) {
593                 // NOTE: Windows always here
594                 $result = TRUE; // Seems the same UID. Nothing to do
595         } else {
596                 $tmp = $filename . '.' . getmypid() . '.tmp';
597
598                 // Lock source $filename to avoid file corruption
599                 // NOTE: Not 'r+'. Don't check write permission here
600                 $ffile = fopen($filename, 'r') or
601                         die('pkwk_chown(): fopen() failed for: ' .
602                                 basename(htmlspecialchars($filename)));
603
604                 // Try to chown by re-creating files
605                 // NOTE:
606                 //   * touch() before copy() is for 'rw-r--r--' instead of 'rwxr-xr-x' (with umask 022).
607                 //   * (PHP 4 < PHP 4.2.0) touch() with the third argument is not implemented and retuns NULL and Warn.
608                 //   * @unlink() before rename() is for Windows but here's for Unix only
609                 flock($ffile, LOCK_EX) or die('pkwk_chown(): flock() failed');
610                 $result = touch($tmp) && copy($filename, $tmp) &&
611                         ($preserve_time ? (touch($tmp, $stat[9], $stat[8]) || touch($tmp, $stat[9])) : TRUE) &&
612                         rename($tmp, $filename);
613                 flock($ffile, LOCK_UN) or die('pkwk_chown(): flock() failed');
614
615                 fclose($ffile) or die('pkwk_chown(): fclose() failed');
616
617                 if ($result === FALSE) @unlink($tmp);
618         }
619
620         // Unlock for pkwk_chown()
621         flock($flock, LOCK_UN) or die('pkwk_chown(): flock() failed for lock');
622         fclose($flock) or die('pkwk_chown(): fclose() failed for lock');
623
624         return $result;
625 }
626
627 // touch() with trying pkwk_chown()
628 function pkwk_touch_file($filename, $time = FALSE, $atime = FALSE)
629 {
630         // Is the owner incorrected and unable to correct?
631         if (! file_exists($filename) || pkwk_chown($filename)) {
632                 if ($time === FALSE) {
633                         $result = touch($filename);
634                 } else if ($atime === FALSE) {
635                         $result = touch($filename, $time);
636                 } else {
637                         $result = touch($filename, $time, $atime);
638                 }
639                 return $result;
640         } else {
641                 die('pkwk_touch_file(): Invalid UID and (not writable for the directory or not a flie): ' .
642                         htmlspecialchars(basename($filename)));
643         }
644 }
645 ?>