OSDN Git Service

BugTrack2/151: lastmodified_add() now treats page deletion
[pukiwiki/pukiwiki.git] / lib / file.php
1 <?php
2 // PukiWiki - Yet another WikiWikiWeb clone.
3 // $Id: file.php,v 1.67 2006/04/30 03:58:35 henoheno Exp $
4 // Copyright (C)
5 //   2002-2006 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 // RecentChanges
12 define('PKWK_MAXSHOW_ALLOWANCE', 10);
13 define('PKWK_MAXSHOW_CACHE', 'recent.dat');
14
15 // AutoLink
16 define('PKWK_AUTOLINK_REGEX_CACHE', 'autolink.dat');
17
18 // Get source(wiki text) data of the page
19 function get_source($page = NULL, $lock = TRUE, $join = FALSE)
20 {
21         $result = $join ? '' : array();
22
23         if (is_page($page)) {
24                 $path  = get_filename($page);
25
26                 if ($lock) {
27                         $fp = @fopen($path, 'r');
28                         if ($fp == FALSE) return $result;
29                         flock($fp, LOCK_SH);
30                 }
31
32                 if ($join) {
33                         // Returns a value
34                         $result = str_replace("\r", '', fread($fp, filesize($path)));
35                 } else {
36                         // Returns an array
37                         // Removing line-feeds: Because file() doesn't remove them.
38                         $result = str_replace("\r", '', file($path));
39                 }
40
41                 if ($lock) {
42                         flock($fp, LOCK_UN);
43                         @fclose($fp);
44                 }
45         }
46
47         return $result;
48 }
49
50 // Get last-modified filetime of the page
51 function get_filetime($page)
52 {
53         return is_page($page) ? filemtime(get_filename($page)) - LOCALZONE : 0;
54 }
55
56 // Get physical file name of the page
57 function get_filename($page)
58 {
59         return DATA_DIR . encode($page) . '.txt';
60 }
61
62 // Put a data(wiki text) into a physical file(diff, backup, text)
63 function page_write($page, $postdata, $notimestamp = FALSE)
64 {
65         global $trackback;
66
67         if (PKWK_READONLY) return; // Do nothing
68
69         $postdata = make_str_rules($postdata);
70
71         // Create and write diff
72         $oldpostdata = is_page($page) ? join('', get_source($page)) : '';
73         $diffdata    = do_diff($oldpostdata, $postdata);
74         file_write(DIFF_DIR, $page, $diffdata);
75
76         // Create backup
77         make_backup($page, $postdata == ''); // Is $postdata null?
78
79         // Create wiki text
80         file_write(DATA_DIR, $page, $postdata, $notimestamp);
81
82         if ($trackback) {
83                 // TrackBack Ping
84                 $_diff = explode("\n", $diffdata);
85                 $plus  = join("\n", preg_replace('/^\+/', '', preg_grep('/^\+/', $_diff)));
86                 $minus = join("\n", preg_replace('/^-/',  '', preg_grep('/^-/',  $_diff)));
87                 tb_send($page, $plus, $minus);
88         }
89
90         links_update($page);
91 }
92
93 // Modify original text with user-defined / system-defined rules
94 function make_str_rules($source)
95 {
96         global $str_rules, $fixed_heading_anchor;
97
98         $lines = explode("\n", $source);
99         $count = count($lines);
100
101         $modify    = TRUE;
102         $multiline = 0;
103         $matches   = array();
104         for ($i = 0; $i < $count; $i++) {
105                 $line = & $lines[$i]; // Modify directly
106
107                 // Ignore null string and preformatted texts
108                 if ($line == '' || $line{0} == ' ' || $line{0} == "\t") continue;
109
110                 // Modify this line?
111                 if ($modify) {
112                         if (! PKWKEXP_DISABLE_MULTILINE_PLUGIN_HACK &&
113                             $multiline == 0 &&
114                             preg_match('/#[^{]*(\{\{+)\s*$/', $line, $matches)) {
115                                 // Multiline convert plugin start
116                                 $modify    = FALSE;
117                                 $multiline = strlen($matches[1]); // Set specific number
118                         }
119                 } else {
120                         if (! PKWKEXP_DISABLE_MULTILINE_PLUGIN_HACK &&
121                             $multiline != 0 &&
122                             preg_match('/^\}{' . $multiline . '}\s*$/', $line)) {
123                                 // Multiline convert plugin end
124                                 $modify    = TRUE;
125                                 $multiline = 0;
126                         }
127                 }
128                 if ($modify === FALSE) continue;
129
130                 // Replace with $str_rules
131                 foreach ($str_rules as $pattern => $replacement)
132                         $line = preg_replace('/' . $pattern . '/', $replacement, $line);
133                 
134                 // Adding fixed anchor into headings
135                 if ($fixed_heading_anchor &&
136                     preg_match('/^(\*{1,3}.*?)(?:\[#([A-Za-z][\w-]*)\]\s*)?$/', $line, $matches) &&
137                     (! isset($matches[2]) || $matches[2] == '')) {
138                         // Generate unique id
139                         $anchor = generate_fixed_heading_anchor_id($matches[1]);
140                         $line = rtrim($matches[1]) . ' [#' . $anchor . ']';
141                 }
142         }
143
144         // Multiline part has no stopper
145         if (! PKWKEXP_DISABLE_MULTILINE_PLUGIN_HACK &&
146             $modify === FALSE && $multiline != 0)
147                 $lines[] = str_repeat('}', $multiline);
148
149         return implode("\n", $lines);
150 }
151
152 // Generate ID
153 function generate_fixed_heading_anchor_id($seed)
154 {
155         // A random alphabetic letter + 7 letters of random strings from md()
156         return chr(mt_rand(ord('a'), ord('z'))) .
157                 substr(md5(uniqid(substr($seed, 0, 100), TRUE)),
158                 mt_rand(0, 24), 7);
159 }
160
161 // Read top N lines as an array
162 // (Use PHP file() function if you want to get ALL lines)
163 function file_head($file, $count = 1, $lock = TRUE, $buffer = 8192)
164 {
165         $array = array();
166
167         $fp = @fopen($file, 'r');
168         if ($fp === FALSE) return FALSE;
169         set_file_buffer($fp, 0);
170         if ($lock) flock($fp, LOCK_SH);
171         rewind($fp);
172         $index = 0;
173         while (! feof($fp)) {
174                 $line = fgets($fp, $buffer);
175                 if ($line != FALSE) $array[] = $line;
176                 if (++$index >= $count) break;
177         }
178         if ($lock) flock($fp, LOCK_UN);
179         if (! fclose($fp)) return FALSE;
180
181         return $array;
182 }
183
184 // Output to a file
185 function file_write($dir, $page, $str, $notimestamp = FALSE)
186 {
187         global $update_exec, $_msg_invalidiwn, $notify, $notify_diff_only, $notify_subject;
188         global $whatsdeleted, $maxshow_deleted;
189
190         if (PKWK_READONLY) return; // Do nothing
191         if ($dir != DATA_DIR && $dir != DIFF_DIR) die('file_write(): Invalid directory');
192
193         $page = strip_bracket($page);
194         $file = $dir . encode($page) . '.txt';
195         $file_exists = file_exists($file);
196
197         // ----
198         // Delete?
199
200         if ($dir == DATA_DIR && $str === '') {
201                 // Page deletion
202                 if (! $file_exists) return; // Ignore null posting for DATA_DIR
203
204                 // Update RecentDeleted (Add the $page)
205                 add_recent($page, $whatsdeleted, '', $maxshow_deleted);
206
207                 // Remove the page
208                 unlink($file);
209
210                 // Update RecentDeleted, and remove the page from RecentChanges
211                 lastmodified_add($whatsdeleted, $page);
212
213                 // Clear is_page() cache
214                 is_page($page, TRUE);
215
216                 return;
217
218         } else if ($dir == DIFF_DIR && $str === " \n") {
219                 return; // Ignore null posting for DIFF_DIR
220         }
221
222         // ----
223         // File replacement (Edit)
224
225         if (! is_pagename($page))
226                 die_message(str_replace('$1', htmlspecialchars($page),
227                             str_replace('$2', 'WikiName', $_msg_invalidiwn)));
228
229         $str = rtrim(preg_replace('/' . "\r" . '/', '', $str)) . "\n";
230         $timestamp = ($file_exists && $notimestamp) ? filemtime($file) : FALSE;
231
232         $fp = fopen($file, 'a') or die('fopen() failed: ' .
233                 htmlspecialchars(basename($dir) . '/' . encode($page) . '.txt') .       
234                 '<br />' . "\n" .
235                 'Maybe permission is not writable or filename is too long');
236         set_file_buffer($fp, 0);
237         flock($fp, LOCK_EX);
238         ftruncate($fp, 0);
239         rewind($fp);
240         fputs($fp, $str);
241         flock($fp, LOCK_UN);
242         fclose($fp);
243
244         if ($timestamp) pkwk_touch_file($file, $timestamp);
245
246         // Optional actions
247         if ($dir == DATA_DIR) {
248                 // Update RecentChanges (Add or renew the $page)
249                 if ($timestamp === FALSE) lastmodified_add($page);
250
251                 // Execute $update_exec here
252                 if ($update_exec) system($update_exec . ' > /dev/null &');
253
254         } else if ($dir == DIFF_DIR && $notify) {
255                 if ($notify_diff_only) $str = preg_replace('/^[^-+].*\n/m', '', $str);
256                 $footer['ACTION'] = 'Page update';
257                 $footer['PAGE']   = & $page;
258                 $footer['URI']    = get_script_uri() . '?' . rawurlencode($page);
259                 $footer['USER_AGENT']  = TRUE;
260                 $footer['REMOTE_ADDR'] = TRUE;
261                 pkwk_mail_notify($notify_subject, $str, $footer) or
262                         die('pkwk_mail_notify(): Failed');
263         }
264
265         is_page($page, TRUE); // Clear is_page() cache
266 }
267
268 // Update RecentDeleted
269 function add_recent($page, $recentpage, $subject = '', $limit = 0)
270 {
271         if (PKWK_READONLY || $limit == 0 || $page == '' || $recentpage == '' ||
272             check_non_list($page)) return;
273
274         // Load
275         $lines = $matches = array();
276         foreach (get_source($recentpage) as $line)
277                 if (preg_match('/^-(.+) - (\[\[.+\]\])$/', $line, $matches))
278                         $lines[$matches[2]] = $line;
279
280         $_page = '[[' . $page . ']]';
281
282         // Remove a report about the same page
283         if (isset($lines[$_page])) unset($lines[$_page]);
284
285         // Add
286         array_unshift($lines, '-' . format_date(UTIME) . ' - ' . $_page .
287                 htmlspecialchars($subject) . "\n");
288
289         // Get latest $limit reports
290         $lines = array_splice($lines, 0, $limit);
291
292         // Update
293         $fp = fopen(get_filename($recentpage), 'w') or
294                 die_message('Cannot write page file ' .
295                 htmlspecialchars($recentpage) .
296                 '<br />Maybe permission is not writable or filename is too long');
297         set_file_buffer($fp, 0);
298         flock($fp, LOCK_EX);
299         rewind($fp);
300         fputs($fp, '#freeze'    . "\n");
301         fputs($fp, '#norelated' . "\n"); // :)
302         fputs($fp, join('', $lines));
303         flock($fp, LOCK_UN);
304         fclose($fp);
305 }
306
307 // Update PKWK_MAXSHOW_CACHE itself (Add or renew about the $page) (Light)
308 // Use without $autolink
309 function lastmodified_add($update = '', $remove = '')
310 {
311         global $maxshow, $whatsnew, $autolink;
312
313         // AutoLink implimentation needs everything, for now
314         if ($autolink) {
315                 put_lastmodified(); // Try to (re)create ALL
316                 return;
317         }
318
319         if (($update == '' || check_non_list($update)) && $remove == '')
320                 return; // No need
321
322         $file = CACHE_DIR . PKWK_MAXSHOW_CACHE;
323         if (! file_exists($file)) {
324                 put_lastmodified(); // Try to (re)create ALL
325                 return;
326         }
327
328         // Open
329         pkwk_touch_file($file);
330         $fp = fopen($file, 'r+') or
331                 die_message('Cannot open ' . 'CACHE_DIR/' . PKWK_MAXSHOW_CACHE);
332         set_file_buffer($fp, 0);
333         flock($fp, LOCK_EX);
334
335         // Read (keep the order of the lines)
336         $recent_pages = $matches = array();
337         foreach(file_head($file, $maxshow + PKWK_MAXSHOW_ALLOWANCE, FALSE) as $line)
338                 if (preg_match('/^([0-9]+)\t(.+)/', $line, $matches))
339                         $recent_pages[$matches[2]] = $matches[1];
340
341         // Remove if it exists inside
342         if (isset($recent_pages[$update])) unset($recent_pages[$update]);
343         if (isset($recent_pages[$remove])) unset($recent_pages[$remove]);
344
345         // Add to the top: like array_unshift()
346         if ($update != '')
347                 $recent_pages = array($update => get_filetime($update)) + $recent_pages;
348
349         // Check
350         $abort = count($recent_pages) < $maxshow;
351
352         if (! $abort) {
353                 // Write
354                 ftruncate($fp, 0);
355                 rewind($fp);
356                 foreach ($recent_pages as $_page=>$time)
357                         fputs($fp, $time . "\t" . $_page . "\n");
358         }
359
360         flock($fp, LOCK_UN);
361         fclose($fp);
362
363         if ($abort) {
364                 put_lastmodified(); // Try to (re)create ALL
365                 return;
366         }
367
368
369
370         // ----
371         // Update the page 'RecentChanges'
372
373         $recent_pages = array_splice($recent_pages, 0, $maxshow);
374         $file = get_filename($whatsnew);
375
376         // Open
377         pkwk_touch_file($file);
378         $fp = fopen($file, 'r+') or
379                 die_message('Cannot open ' . htmlspecialchars($whatsnew));
380         set_file_buffer($fp, 0);
381         flock($fp, LOCK_EX);
382
383         // Recreate
384         ftruncate($fp, 0);
385         rewind($fp);
386         foreach ($recent_pages as $_page=>$time)
387                 fputs($fp, '-' . htmlspecialchars(format_date($time)) .
388                         ' - ' . '[[' . htmlspecialchars($_page) . ']]' . "\n");
389         fputs($fp, '#norelated' . "\n"); // :)
390
391         flock($fp, LOCK_UN);
392         fclose($fp);
393 }
394
395 // Re-create PKWK_MAXSHOW_CACHE (Heavy)
396 function put_lastmodified()
397 {
398         global $maxshow, $whatsnew, $autolink;
399
400         if (PKWK_READONLY) return; // Do nothing
401
402         // Get WHOLE page list
403         $pages = get_existpages();
404
405         // Check ALL filetime
406         $recent_pages = array();
407         foreach($pages as $page)
408                 if ($page != $whatsnew && ! check_non_list($page))
409                         $recent_pages[$page] = get_filetime($page);
410
411         // Sort decending order of last-modification date
412         arsort($recent_pages, SORT_NUMERIC);
413
414         // Cut unused lines
415         $recent_pages = array_splice($recent_pages, 0, $maxshow + PKWK_MAXSHOW_ALLOWANCE);
416
417         // Re-create PKWK_MAXSHOW_CACHE
418         $file = CACHE_DIR . PKWK_MAXSHOW_CACHE;
419         pkwk_touch_file($file);
420         $fp = fopen($file, 'r+') or
421                 die_message('Cannot open' . 'CACHE_DIR/' . PKWK_MAXSHOW_CACHE);
422         set_file_buffer($fp, 0);
423         flock($fp, LOCK_EX);
424         ftruncate($fp, 0);
425         rewind($fp);
426         foreach ($recent_pages as $page=>$time)
427                 fputs($fp, $time . "\t" . $page . "\n");
428         flock($fp, LOCK_UN);
429         fclose($fp);
430
431         // Create RecentChanges
432         $file = get_filename($whatsnew);
433         pkwk_touch_file($file);
434         $fp = fopen($file, 'r+') or
435                 die_message('Cannot open ' . htmlspecialchars($whatsnew));
436         set_file_buffer($fp, 0);
437         flock($fp, LOCK_EX);
438         ftruncate($fp, 0);
439         rewind($fp);
440         foreach (array_keys($recent_pages) as $page) {
441                 $time      = $recent_pages[$page];
442                 $s_lastmod = htmlspecialchars(format_date($time));
443                 $s_page    = htmlspecialchars($page);
444                 fputs($fp, '-' . $s_lastmod . ' - [[' . $s_page . ']]' . "\n");
445         }
446         fputs($fp, '#norelated' . "\n"); // :)
447         flock($fp, LOCK_UN);
448         fclose($fp);
449
450         // For AutoLink
451         if ($autolink) {
452                 list($pattern, $pattern_a, $forceignorelist) =
453                         get_autolink_pattern($pages);
454
455                 $file = CACHE_DIR . PKWK_AUTOLINK_REGEX_CACHE;
456                 pkwk_touch_file($file);
457                 $fp = fopen($file, 'r+') or
458                         die_message('Cannot open ' . 'CACHE_DIR/' . PKWK_AUTOLINK_REGEX_CACHE);
459                 set_file_buffer($fp, 0);
460                 flock($fp, LOCK_EX);
461                 ftruncate($fp, 0);
462                 rewind($fp);
463                 fputs($fp, $pattern   . "\n");
464                 fputs($fp, $pattern_a . "\n");
465                 fputs($fp, join("\t", $forceignorelist) . "\n");
466                 flock($fp, LOCK_UN);
467                 fclose($fp);
468         }
469 }
470
471 // Get elapsed date of the page
472 function get_pg_passage($page, $sw = TRUE)
473 {
474         global $show_passage;
475         if (! $show_passage) return '';
476
477         $time = get_filetime($page);
478         $pg_passage = ($time != 0) ? get_passage($time) : '';
479
480         return $sw ? '<small>' . $pg_passage . '</small>' : ' ' . $pg_passage;
481 }
482
483 // Last-Modified header
484 function header_lastmod($page = NULL)
485 {
486         global $lastmod;
487
488         if ($lastmod && is_page($page)) {
489                 pkwk_headers_sent();
490                 header('Last-Modified: ' .
491                         date('D, d M Y H:i:s', get_filetime($page)) . ' GMT');
492         }
493 }
494
495 // Get a page list of this wiki
496 function get_existpages($dir = DATA_DIR, $ext = '.txt')
497 {
498         $aryret = array();
499
500         $pattern = '((?:[0-9A-F]{2})+)';
501         if ($ext != '') $ext = preg_quote($ext, '/');
502         $pattern = '/^' . $pattern . $ext . '$/';
503
504         $dp = @opendir($dir) or
505                 die_message($dir . ' is not found or not readable.');
506         $matches = array();
507         while ($file = readdir($dp))
508                 if (preg_match($pattern, $file, $matches))
509                         $aryret[$file] = decode($matches[1]);
510         closedir($dp);
511
512         return $aryret;
513 }
514
515 // Get PageReading(pronounce-annotated) data in an array()
516 function get_readings()
517 {
518         global $pagereading_enable, $pagereading_kanji2kana_converter;
519         global $pagereading_kanji2kana_encoding, $pagereading_chasen_path;
520         global $pagereading_kakasi_path, $pagereading_config_page;
521         global $pagereading_config_dict;
522
523         $pages = get_existpages();
524
525         $readings = array();
526         foreach ($pages as $page) 
527                 $readings[$page] = '';
528
529         $deletedPage = FALSE;
530         $matches = array();
531         foreach (get_source($pagereading_config_page) as $line) {
532                 $line = chop($line);
533                 if(preg_match('/^-\[\[([^]]+)\]\]\s+(.+)$/', $line, $matches)) {
534                         if(isset($readings[$matches[1]])) {
535                                 // This page is not clear how to be pronounced
536                                 $readings[$matches[1]] = $matches[2];
537                         } else {
538                                 // This page seems deleted
539                                 $deletedPage = TRUE;
540                         }
541                 }
542         }
543
544         // If enabled ChaSen/KAKASI execution
545         if($pagereading_enable) {
546
547                 // Check there's non-clear-pronouncing page
548                 $unknownPage = FALSE;
549                 foreach ($readings as $page => $reading) {
550                         if($reading == '') {
551                                 $unknownPage = TRUE;
552                                 break;
553                         }
554                 }
555
556                 // Execute ChaSen/KAKASI, and get annotation
557                 if($unknownPage) {
558                         switch(strtolower($pagereading_kanji2kana_converter)) {
559                         case 'chasen':
560                                 if(! file_exists($pagereading_chasen_path))
561                                         die_message('ChaSen not found: ' . $pagereading_chasen_path);
562
563                                 $tmpfname = tempnam(realpath(CACHE_DIR), 'PageReading');
564                                 $fp = fopen($tmpfname, 'w') or
565                                         die_message('Cannot write temporary file "' . $tmpfname . '".' . "\n");
566                                 foreach ($readings as $page => $reading) {
567                                         if($reading != '') continue;
568                                         fputs($fp, mb_convert_encoding($page . "\n",
569                                                 $pagereading_kanji2kana_encoding, SOURCE_ENCODING));
570                                 }
571                                 fclose($fp);
572
573                                 $chasen = "$pagereading_chasen_path -F %y $tmpfname";
574                                 $fp     = popen($chasen, 'r');
575                                 if($fp === FALSE) {
576                                         unlink($tmpfname);
577                                         die_message('ChaSen execution failed: ' . $chasen);
578                                 }
579                                 foreach ($readings as $page => $reading) {
580                                         if($reading != '') continue;
581
582                                         $line = fgets($fp);
583                                         $line = mb_convert_encoding($line, SOURCE_ENCODING,
584                                                 $pagereading_kanji2kana_encoding);
585                                         $line = chop($line);
586                                         $readings[$page] = $line;
587                                 }
588                                 pclose($fp);
589
590                                 unlink($tmpfname) or
591                                         die_message('Temporary file can not be removed: ' . $tmpfname);
592                                 break;
593
594                         case 'kakasi':  /*FALLTHROUGH*/
595                         case 'kakashi':
596                                 if(! file_exists($pagereading_kakasi_path))
597                                         die_message('KAKASI not found: ' . $pagereading_kakasi_path);
598
599                                 $tmpfname = tempnam(realpath(CACHE_DIR), 'PageReading');
600                                 $fp       = fopen($tmpfname, 'w') or
601                                         die_message('Cannot write temporary file "' . $tmpfname . '".' . "\n");
602                                 foreach ($readings as $page => $reading) {
603                                         if($reading != '') continue;
604                                         fputs($fp, mb_convert_encoding($page . "\n",
605                                                 $pagereading_kanji2kana_encoding, SOURCE_ENCODING));
606                                 }
607                                 fclose($fp);
608
609                                 $kakasi = "$pagereading_kakasi_path -kK -HK -JK < $tmpfname";
610                                 $fp     = popen($kakasi, 'r');
611                                 if($fp === FALSE) {
612                                         unlink($tmpfname);
613                                         die_message('KAKASI execution failed: ' . $kakasi);
614                                 }
615
616                                 foreach ($readings as $page => $reading) {
617                                         if($reading != '') continue;
618
619                                         $line = fgets($fp);
620                                         $line = mb_convert_encoding($line, SOURCE_ENCODING,
621                                                 $pagereading_kanji2kana_encoding);
622                                         $line = chop($line);
623                                         $readings[$page] = $line;
624                                 }
625                                 pclose($fp);
626
627                                 unlink($tmpfname) or
628                                         die_message('Temporary file can not be removed: ' . $tmpfname);
629                                 break;
630
631                         case 'none':
632                                 $patterns = $replacements = $matches = array();
633                                 foreach (get_source($pagereading_config_dict) as $line) {
634                                         $line = chop($line);
635                                         if(preg_match('|^ /([^/]+)/,\s*(.+)$|', $line, $matches)) {
636                                                 $patterns[]     = $matches[1];
637                                                 $replacements[] = $matches[2];
638                                         }
639                                 }
640                                 foreach ($readings as $page => $reading) {
641                                         if($reading != '') continue;
642
643                                         $readings[$page] = $page;
644                                         foreach ($patterns as $no => $pattern)
645                                                 $readings[$page] = mb_convert_kana(mb_ereg_replace($pattern,
646                                                         $replacements[$no], $readings[$page]), 'aKCV');
647                                 }
648                                 break;
649
650                         default:
651                                 die_message('Unknown kanji-kana converter: ' . $pagereading_kanji2kana_converter . '.');
652                                 break;
653                         }
654                 }
655
656                 if($unknownPage || $deletedPage) {
657
658                         asort($readings); // Sort by pronouncing(alphabetical/reading) order
659                         $body = '';
660                         foreach ($readings as $page => $reading)
661                                 $body .= '-[[' . $page . ']] ' . $reading . "\n";
662
663                         page_write($pagereading_config_page, $body);
664                 }
665         }
666
667         // Pages that are not prounouncing-clear, return pagenames of themselves
668         foreach ($pages as $page) {
669                 if($readings[$page] == '')
670                         $readings[$page] = $page;
671         }
672
673         return $readings;
674 }
675
676 // Get a list of encoded files (must specify a directory and a suffix)
677 function get_existfiles($dir, $ext)
678 {
679         $pattern = '/^(?:[0-9A-F]{2})+' . preg_quote($ext, '/') . '$/';
680         $aryret = array();
681         $dp = @opendir($dir) or die_message($dir . ' is not found or not readable.');
682         while ($file = readdir($dp))
683                 if (preg_match($pattern, $file))
684                         $aryret[] = $dir . $file;
685         closedir($dp);
686         return $aryret;
687 }
688
689 // Get a list of related pages of the page
690 function links_get_related($page)
691 {
692         global $vars, $related;
693         static $links = array();
694
695         if (isset($links[$page])) return $links[$page];
696
697         // If possible, merge related pages generated by make_link()
698         $links[$page] = ($page == $vars['page']) ? $related : array();
699
700         // Get repated pages from DB
701         $links[$page] += links_get_related_db($vars['page']);
702
703         return $links[$page];
704 }
705
706 // _If needed_, re-create the file to change/correct ownership into PHP's
707 // NOTE: Not works for Windows
708 function pkwk_chown($filename, $preserve_time = TRUE)
709 {
710         static $php_uid; // PHP's UID
711
712         if (! isset($php_uid)) {
713                 if (extension_loaded('posix')) {
714                         $php_uid = posix_getuid(); // Unix
715                 } else {
716                         $php_uid = 0; // Windows
717                 }
718         }
719
720         // Lock for pkwk_chown()
721         $lockfile = CACHE_DIR . 'pkwk_chown.lock';
722         $flock = fopen($lockfile, 'a') or
723                 die('pkwk_chown(): fopen() failed for: CACHEDIR/' .
724                         basename(htmlspecialchars($lockfile)));
725         flock($flock, LOCK_EX) or die('pkwk_chown(): flock() failed for lock');
726
727         // Check owner
728         $stat = stat($filename) or
729                 die('pkwk_chown(): stat() failed for: '  . basename(htmlspecialchars($filename)));
730         if ($stat[4] === $php_uid) {
731                 // NOTE: Windows always here
732                 $result = TRUE; // Seems the same UID. Nothing to do
733         } else {
734                 $tmp = $filename . '.' . getmypid() . '.tmp';
735
736                 // Lock source $filename to avoid file corruption
737                 // NOTE: Not 'r+'. Don't check write permission here
738                 $ffile = fopen($filename, 'r') or
739                         die('pkwk_chown(): fopen() failed for: ' .
740                                 basename(htmlspecialchars($filename)));
741
742                 // Try to chown by re-creating files
743                 // NOTE:
744                 //   * touch() before copy() is for 'rw-r--r--' instead of 'rwxr-xr-x' (with umask 022).
745                 //   * (PHP 4 < PHP 4.2.0) touch() with the third argument is not implemented and retuns NULL and Warn.
746                 //   * @unlink() before rename() is for Windows but here's for Unix only
747                 flock($ffile, LOCK_EX) or die('pkwk_chown(): flock() failed');
748                 $result = touch($tmp) && copy($filename, $tmp) &&
749                         ($preserve_time ? (touch($tmp, $stat[9], $stat[8]) || touch($tmp, $stat[9])) : TRUE) &&
750                         rename($tmp, $filename);
751                 flock($ffile, LOCK_UN) or die('pkwk_chown(): flock() failed');
752
753                 fclose($ffile) or die('pkwk_chown(): fclose() failed');
754
755                 if ($result === FALSE) @unlink($tmp);
756         }
757
758         // Unlock for pkwk_chown()
759         flock($flock, LOCK_UN) or die('pkwk_chown(): flock() failed for lock');
760         fclose($flock) or die('pkwk_chown(): fclose() failed for lock');
761
762         return $result;
763 }
764
765 // touch() with trying pkwk_chown()
766 function pkwk_touch_file($filename, $time = FALSE, $atime = FALSE)
767 {
768         // Is the owner incorrected and unable to correct?
769         if (! file_exists($filename) || pkwk_chown($filename)) {
770                 if ($time === FALSE) {
771                         $result = touch($filename);
772                 } else if ($atime === FALSE) {
773                         $result = touch($filename, $time);
774                 } else {
775                         $result = touch($filename, $time, $atime);
776                 }
777                 return $result;
778         } else {
779                 die('pkwk_touch_file(): Invalid UID and (not writable for the directory or not a flie): ' .
780                         htmlspecialchars(basename($filename)));
781         }
782 }
783 ?>