OSDN Git Service

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