OSDN Git Service

Cleanup, shrink, added spaces and blank lines, simplify
[pukiwiki/pukiwiki.git] / lib / file.php
1 <?php
2 /////////////////////////////////////////////////
3 // PukiWiki - Yet another WikiWikiWeb clone.
4 //
5 // $Id: file.php,v 1.2 2004/08/01 13:00:01 henoheno Exp $
6 //
7
8 // ¥½¡¼¥¹¤ò¼èÆÀ
9 function get_source($page = NULL)
10 {
11         if (! is_page($page)) {
12                 return array();
13         } else {
14                 return str_replace("\r", '', file(get_filename($page)));
15         }
16 }
17
18 // ¥Ú¡¼¥¸¤Î¹¹¿·»þ¹ï¤òÆÀ¤ë
19 function get_filetime($page)
20 {
21         if (! is_page($page)) {
22                 return 0;
23         } else {
24                 return filemtime(get_filename($page)) - LOCALZONE;
25         }
26 }
27
28 // ¥Ú¡¼¥¸¤Î¥Õ¥¡¥¤¥ë̾¤òÆÀ¤ë
29 function get_filename($page)
30 {
31         return DATA_DIR . encode($page) . '.txt';
32 }
33
34 // ¥Ú¡¼¥¸¤Î½ÐÎÏ
35 function page_write($page, $postdata, $notimestamp = FALSE)
36 {
37         $postdata = make_str_rules($postdata);
38
39         // º¹Ê¬¥Õ¥¡¥¤¥ë¤ÎºîÀ®
40         $oldpostdata = is_page($page) ? join('', get_source($page)) : '';
41         $diffdata = do_diff($oldpostdata, $postdata);
42         file_write(DIFF_DIR, $page, $diffdata);
43
44         // ¥Ð¥Ã¥¯¥¢¥Ã¥×¤ÎºîÀ®
45         make_backup($page, $postdata == '');
46
47         // ¥Õ¥¡¥¤¥ë¤Î½ñ¤­¹þ¤ß
48         file_write(DATA_DIR, $page, $postdata, $notimestamp);
49
50         // TrackBack Ping ¤ÎÁ÷¿®
51         // ¡ÖÄɲá׹ԤòÃê½Ð
52         $lines = join("\n", preg_replace('/^\+/', '', preg_grep('/^\+/', explode("\n", $diffdata))));
53         tb_send($page, $lines);
54
55         // link¥Ç¡¼¥¿¥Ù¡¼¥¹¤ò¹¹¿·
56         links_update($page);
57 }
58
59 // ¥æ¡¼¥¶ÄêµÁ¥ë¡¼¥ë(¥½¡¼¥¹¤òÃÖ´¹¤¹¤ë)
60 function make_str_rules($str)
61 {
62         global $str_rules, $fixed_heading_anchor;
63
64         $arr = explode("\n", $str);
65
66         $retvars = $matches = array();
67         foreach ($arr as $str)
68         {
69                 if ($str != '' and $str{0} != ' ' and $str{0} != "\t")
70                 {
71                         foreach ($str_rules as $rule => $replace)
72                         {
73                                 $str = preg_replace("/$rule/", $replace, $str);
74                         }
75                 }
76                 // ¸«½Ð¤·¤Ë¸ÇÍ­ID¤òÉÕÍ¿¤¹¤ë
77                 if ($fixed_heading_anchor and
78                         preg_match('/^(\*{1,3}(.(?!\[#[A-Za-z][\w-]+\]))+)$/', $str, $matches))
79                 {
80                         // ¸ÇÍ­ID¤òÀ¸À®¤¹¤ë
81                         // ¥é¥ó¥À¥à¤Ê±Ñ»ú(1ʸ»ú)+md5¥Ï¥Ã¥·¥å¤Î¥é¥ó¥À¥à¤ÊÉôʬʸ»úÎó(7ʸ»ú)
82                         $anchor = chr(mt_rand(ord('a'), ord('z'))).
83                                 substr(md5(uniqid(substr($matches[1], 0, 100), 1)), mt_rand(0, 24), 7);
84                         $str = rtrim($matches[1]) . " [#$anchor]";
85                 }
86                 $retvars[] = $str;
87         }
88
89         return join("\n", $retvars);
90 }
91
92 // ¥Õ¥¡¥¤¥ë¤Ø¤Î½ÐÎÏ
93 function file_write($dir, $page, $str, $notimestamp = FALSE)
94 {
95         global $update_exec;
96         global $_msg_invalidiwn;
97         global $notify, $notify_diff_only, $notify_to, $notify_subject, $notify_header;
98         global $smtp_server, $smtp_auth;
99
100         if (! is_pagename($page))
101                 die_message(str_replace('$1', htmlspecialchars($page),
102                             str_replace('$2', 'WikiName', $_msg_invalidiwn))
103                 );
104
105         $page = strip_bracket($page);
106         $timestamp = FALSE;
107         $file = $dir . encode($page) . '.txt';
108
109         if ($dir == DATA_DIR and $str == '' and file_exists($file)) {
110                 unlink($file);
111                 put_recentdeleted($page);
112         }
113
114         if ($str != '') {
115                 $str = preg_replace("/\r/", '', $str);
116                 $str = rtrim($str) . "\n";
117
118                 if ($notimestamp and file_exists($file)) {
119                         $timestamp = filemtime($file) - LOCALZONE;
120                 }
121
122                 $fp = fopen($file, 'w') or
123                         die_message('Cannot write page file or diff file or other ' .
124                         htmlspecialchars($page) .
125                         '<br />Maybe permission is not writable or filename is too long');
126
127                 set_file_buffer($fp, 0);
128                 flock($fp, LOCK_EX);
129                 rewind($fp);
130                 fputs($fp, $str);
131                 flock($fp, LOCK_UN);
132                 fclose($fp);
133                 if ($timestamp) {
134                         touch($file, $timestamp + LOCALZONE);
135                 }
136         }
137
138         // is_page¤Î¥­¥ã¥Ã¥·¥å¤ò¥¯¥ê¥¢¤¹¤ë
139         is_page($page, TRUE);
140
141         if (! $timestamp and $dir == DATA_DIR) {
142                 put_lastmodified();
143         }
144
145         if ($update_exec and $dir == DATA_DIR) {
146                 system($update_exec . ' > /dev/null &');
147         }
148
149         if ($notify and $dir == DIFF_DIR) {
150                 if ($notify_diff_only) { // º¹Ê¬¤À¤±¤òÁ÷¿®¤¹¤ë
151                         $str = preg_replace('/^[^-+].*\n/m', '', $str);
152                 }
153                 if ($smtp_auth) {
154                         pop_before_smtp();
155                 }
156                 $subject = str_replace('$page', $page, $notify_subject);
157                 ini_set('SMTP', $smtp_server);
158                 mb_language(LANG);
159                 mb_send_mail($notify_to, $subject, $str, $notify_header);
160         }
161 }
162
163 // ºï½üÍúÎò¥Ú¡¼¥¸¤Î¹¹¿·
164 function put_recentdeleted($page)
165 {
166         global $whatsdeleted, $maxshow_deleted;
167
168         if ($maxshow_deleted == 0) return;
169
170         // Update RecentDeleted
171         $lines = $matches = array();
172         foreach (get_source($whatsdeleted) as $line) {
173                 if (preg_match('/^-(.+) - (\[\[.+\]\])$/', $line, $matches))
174                         $lines[$matches[2]] = $line;
175         }
176
177         $_page = "[[$page]]";
178         if (isset($lines[$_page])) unset($lines[$_page]);
179
180         array_unshift($lines, '-' . format_date(UTIME) . " - $_page\n");
181         $lines = array_splice($lines, 0, $maxshow_deleted);
182
183         $fp = fopen(get_filename($whatsdeleted), 'w') or
184                 die_message('Cannot write page file ' .
185                 htmlspecialchars($whatsdeleted) .
186                 '<br />Maybe permission is not writable or filename is too long');
187
188         set_file_buffer($fp, 0);
189         flock($fp, LOCK_EX);
190         rewind($fp);
191         fputs($fp, join('', $lines));
192         fputs($fp, "#norelated\n"); // :)
193         flock($fp, LOCK_UN);
194         fclose($fp);
195 }
196
197 // ºÇ½ª¹¹¿·¥Ú¡¼¥¸¤Î¹¹¿·
198 function put_lastmodified()
199 {
200         global $maxshow, $whatsnew, $non_list, $autolink;
201
202         $pages = get_existpages();
203         $recent_pages = array();
204         foreach($pages as $page) {
205                 if ($page != $whatsnew and ! preg_match("/$non_list/", $page))
206                         $recent_pages[$page] = get_filetime($page);
207         }
208
209         //»þ¹ï¹ß½ç¤Ç¥½¡¼¥È
210         arsort($recent_pages, SORT_NUMERIC);
211
212         // create recent.dat (for recent.inc.php)
213         $fp = fopen(CACHE_DIR . 'recent.dat', 'w') or
214                 die_message('Cannot write cache file ' .
215                 CACHE_DIR . 'recent.dat' .
216                 '<br />Maybe permission is not writable or filename is too long');
217
218         set_file_buffer($fp, 0);
219         flock($fp, LOCK_EX);
220         rewind($fp);
221         foreach ($recent_pages as $page=>$time) {
222                 fputs($fp, "$time\t$page\n");
223         }
224         flock($fp, LOCK_UN);
225         fclose($fp);
226
227         // create RecentChanges
228         $fp = fopen(get_filename($whatsnew), 'w') or
229                 die_message('Cannot write page file ' .
230                 htmlspecialchars($whatsnew) .
231                 '<br />Maybe permission is not writable or filename is too long');
232
233         set_file_buffer($fp, 0);
234         flock($fp, LOCK_EX);
235         rewind($fp);
236         foreach (array_splice(array_keys($recent_pages), 0, $maxshow) as $page) {
237                 $time = $recent_pages[$page];
238                 $s_lastmod = htmlspecialchars(format_date($time));
239                 $s_page = htmlspecialchars($page);
240                 fputs($fp, "-$s_lastmod - [[$s_page]]\n");
241         }
242         fputs($fp, "#norelated\n"); // :)
243         flock($fp, LOCK_UN);
244         fclose($fp);
245
246         // for autolink
247         if ($autolink) {
248                 list($pattern, $pattern_a, $forceignorelist) = get_autolink_pattern($pages);
249
250                 $fp = fopen(CACHE_DIR . 'autolink.dat', 'w') or
251                         die_message('Cannot write autolink file ' .
252                         CACHE_DIR . '/autolink.dat' .
253                         '<br />Maybe permission is not writable');
254                 set_file_buffer($fp, 0);
255                 flock($fp, LOCK_EX);
256                 rewind($fp);
257                 fputs($fp, $pattern   . "\n");
258                 fputs($fp, $pattern_a . "\n");
259                 fputs($fp, join("\t", $forceignorelist) . "\n");
260                 flock($fp, LOCK_UN);
261                 fclose($fp);
262         }
263 }
264
265 // »ØÄꤵ¤ì¤¿¥Ú¡¼¥¸¤Î·Ð²á»þ¹ï
266 function get_pg_passage($page, $sw = TRUE)
267 {
268         global $show_passage;
269         static $pg_passage = array();
270
271         if (! $show_passage) return '';
272
273         if (! array_key_exists($page, $pg_passage)) {
274                 $pg_passage[$page] = (is_page($page) and $time = get_filetime($page)) ?
275                         get_passage($time) : '';
276         }
277
278         return $sw ? "<small>{$pg_passage[$page]}</small>" : " {$pg_passage[$page]}";
279 }
280
281 // Last-Modified ¥Ø¥Ã¥À
282 function header_lastmod($page = NULL)
283 {
284         global $lastmod;
285
286         if ($lastmod and is_page($page)) {
287                 header('Last-Modified: ' .
288                         date('D, d M Y H:i:s', get_filetime($page)) . ' GMT');
289         }
290 }
291
292 // Á´¥Ú¡¼¥¸Ì¾¤òÇÛÎó¤Ë
293 function get_existpages($dir = DATA_DIR, $ext = '.txt')
294 {
295         $aryret = array();
296
297         $pattern = '^((?:[0-9A-F]{2})+)';
298         if ($ext != '')
299                 $pattern .= preg_quote($ext, '/') . '$';
300
301         $dp = @opendir($dir) or
302                 die_message($dir . ' is not found or not readable.');
303         $matches = array();
304         while ($file = readdir($dp)) {
305                 if (preg_match("/$pattern/", $file, $matches))
306                         $aryret[$file] = decode($matches[1]);
307         }
308         closedir($dp);
309
310         return $aryret;
311 }
312
313 // ¥Ú¡¼¥¸Ì¾¤ÎÆɤߤòÇÛÎó¤Ë
314 function get_readings()
315 {
316         global $pagereading_enable, $pagereading_kanji2kana_converter;
317         global $pagereading_kanji2kana_encoding, $pagereading_chasen_path;
318         global $pagereading_kakasi_path, $pagereading_config_page;
319         global $pagereading_config_dict;
320
321         $pages = get_existpages();
322
323         $readings = array();
324         foreach ($pages as $page) {
325                 $readings[$page] = '';
326         }
327
328         $deletedPage = FALSE;
329         $matches = array();
330         foreach (get_source($pagereading_config_page) as $line) {
331                 $line = chop($line);
332                 if(preg_match('/^-\[\[([^]]+)\]\]\s+(.+)$/', $line, $matches)) {
333                         if(isset($readings[$matches[1]])) {
334                                 // Æɤߤ¬ÉÔÌÀ¤Î¥Ú¡¼¥¸
335                                 $readings[$matches[1]] = $matches[2];
336                         } else {
337                                 // ºï½ü¤µ¤ì¤¿¥Ú¡¼¥¸
338                                 $deletedPage = TRUE;
339                         }
340                 }
341         }
342
343         // ChaSen/KAKASI ¸Æ¤Ó½Ð¤·¤¬Í­¸ú¤ËÀßÄꤵ¤ì¤Æ¤¤¤ë¾ì¹ç
344         if($pagereading_enable) {
345
346                 // Æɤߤ¬ÉÔÌÀ¤Î¥Ú¡¼¥¸¤¬¤¢¤ë¤«¥Á¥§¥Ã¥¯
347                 $unknownPage = FALSE;
348                 foreach ($readings as $page => $reading) {
349                         if($reading == '') {
350                                 $unknownPage = TRUE;
351                                 break;
352                         }
353                 }
354
355                 // Æɤߤ¬ÉÔÌÀ¤Î¥Ú¡¼¥¸¤¬¤¢¤ë¾ì¹ç¡¢ChaSen/KAKASI ¤ò¼Â¹Ô
356                 if($unknownPage) {
357                         switch(strtolower($pagereading_kanji2kana_converter)) {
358                         case 'chasen':
359                                 $tmpfname = tempnam(CACHE_DIR, 'PageReading');
360                                 $fp = fopen($tmpfname, "w") or
361                                         die_message("Cannot write temporary file '$tmpfname'.\n");
362                                 foreach ($readings as $page => $reading) {
363                                         if($reading == '') {
364                                                 fputs($fp, mb_convert_encoding("$page\n", $pagereading_kanji2kana_encoding, SOURCE_ENCODING));
365                                         }
366                                 }
367                                 fclose($fp);
368
369                                 if(! file_exists($pagereading_chasen_path)) {
370                                         unlink($tmpfname);
371                                         die_message("ChaSen not found: $pagereading_chasen_path");
372                                 }
373
374                                 $chasen = "$pagereading_chasen_path -F %y $tmpfname";
375                                 $fp = popen($chasen, "r");
376                                 if(! $fp) {
377                                         unlink($tmpfname);
378                                         die_message("ChaSen execution failed: $chasen");
379                                 }
380                                 foreach ($readings as $page => $reading) {
381                                         if($reading == '') {
382                                                 $line = fgets($fp);
383                                                 $line = mb_convert_encoding($line, SOURCE_ENCODING, $pagereading_kanji2kana_encoding);
384                                                 $line = chop($line);
385                                                 $readings[$page] = $line;
386                                         }
387                                 }
388                                 pclose($fp);
389
390                                 unlink($tmpfname) or die_message("Temporary file can not be removed: $tmpfname");
391                                 break;
392
393                         case 'kakasi':
394                         case 'kakashi':
395                                 $tmpfname = tempnam(CACHE_DIR, 'PageReading');
396                                 $fp = fopen($tmpfname, "w") or
397                                         die_message("Cannot write temporary file '$tmpfname'.\n");
398                                 foreach ($readings as $page => $reading) {
399                                         if($reading == '') {
400                                                 fputs($fp, mb_convert_encoding("$page\n", $pagereading_kanji2kana_encoding, SOURCE_ENCODING));
401                                         }
402                                 }
403                                 fclose($fp);
404
405                                 if(! file_exists($pagereading_kakasi_path)) {
406                                         unlink($tmpfname);
407                                         die_message("KAKASI not found: $pagereading_kakasi_path");
408                                 }
409
410                                 $kakasi = "$pagereading_kakasi_path -kK -HK -JK < $tmpfname";
411                                 $fp = popen($kakasi, "r");
412                                 if(!$fp) {
413                                         unlink($tmpfname);
414                                         die_message("KAKASI execution failed: $kakasi");
415                                 }
416                                 foreach ($readings as $page => $reading) {
417                                         if($reading == '') {
418                                                 $line = fgets($fp);
419                                                 $line = mb_convert_encoding($line, SOURCE_ENCODING, $pagereading_kanji2kana_encoding);
420                                                 $line = chop($line);
421                                                 $readings[$page] = $line;
422                                         }
423                                 }
424                                 pclose($fp);
425
426                                 unlink($tmpfname) or die_message("Temporary file can not be removed: $tmpfname");
427                                 break;
428
429                         case 'none':
430                                 $patterns = $replacements = $matches = array();
431                                 foreach (get_source($pagereading_config_dict) as $line) {
432                                         $line = chop($line);
433                                         if(preg_match('|^ /([^/]+)/,\s*(.+)$|', $line, $matches)) {
434                                                 $patterns[]     = $matches[1];
435                                                 $replacements[] = $matches[2];
436                                         }
437                                 }
438                                 foreach ($readings as $page => $reading) {
439                                         if($reading == '') {
440                                                 $readings[$page] = $page;
441                                                 foreach ($patterns as $no => $pattern) {
442                                                         $readings[$page] = mb_convert_kana(mb_ereg_replace($pattern, $replacements[$no], $readings[$page]), "aKCV");
443                                                 }
444                                         }
445                                 }
446                                 break;
447
448                         default:
449                                 die_message("Unknown kanji-kana converter: $pagereading_kanji2kana_converter.");
450                                 break;
451                         }
452                 }
453
454                 if($unknownPage or $deletedPage) {
455
456                         asort($readings); // Æɤߤǥ½¡¼¥È
457
458                         // ¥Ú¡¼¥¸¤ò½ñ¤­¹þ¤ß
459                         $body = '';
460                         foreach ($readings as $page => $reading) {
461                                 $body .= "-[[$page]] $reading\n";
462                         }
463                         page_write($pagereading_config_page, $body);
464                 }
465         }
466
467         // ÆɤßÉÔÌÀ¤Î¥Ú¡¼¥¸¤Ï¡¢¤½¤Î¤Þ¤Þ¥Ú¡¼¥¸Ì¾¤òÊÖ¤¹ (ChaSen/KAKASI ¸Æ
468         // ¤Ó½Ð¤·¤¬Ìµ¸ú¤ËÀßÄꤵ¤ì¤Æ¤¤¤ë¾ì¹ç¤ä¡¢ChaSen/KAKASI ¸Æ¤Ó½Ð¤·¤Ë
469         // ¼ºÇÔ¤·¤¿»þ¤Î°Ù)
470         foreach ($pages as $page) {
471                 if($readings[$page] == '') {
472                         $readings[$page] = $page;
473                 }
474         }
475
476         return $readings;
477 }
478
479 //¥Õ¥¡¥¤¥ë̾¤Î°ìÍ÷¤òÇÛÎó¤Ë(¥¨¥ó¥³¡¼¥ÉºÑ¤ß¡¢³ÈÄ¥»Ò¤ò»ØÄê)
480 function get_existfiles($dir, $ext)
481 {
482         $aryret = array();
483
484         $pattern = '^(?:[0-9A-F]{2})+' . preg_quote($ext, '/') . '$';
485         $dp = @opendir($dir) or
486                 die_message($dir . ' is not found or not readable.');
487         while ($file = readdir($dp)) {
488                 if (preg_match("/$pattern/", $file))
489                         $aryret[] = $dir . $file;
490         }
491         closedir($dp);
492         return $aryret;
493 }
494
495 //¤¢¤ë¥Ú¡¼¥¸¤Î´ØÏ¢¥Ú¡¼¥¸¤òÆÀ¤ë
496 function links_get_related($page)
497 {
498         global $vars, $related;
499         static $links = array();
500
501         if (isset($links[$page])) return $links[$page];
502
503         // ²Äǽ¤Ê¤émake_link()¤ÇÀ¸À®¤·¤¿´ØÏ¢¥Ú¡¼¥¸¤ò¼è¤ê¹þ¤à
504         $links[$page] = ($page == $vars['page']) ? $related : array();
505
506         // ¥Ç¡¼¥¿¥Ù¡¼¥¹¤«¤é´ØÏ¢¥Ú¡¼¥¸¤òÆÀ¤ë
507         $links[$page] += links_get_related_db($vars['page']);
508
509         return $links[$page];
510 }
511 ?>