OSDN Git Service

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