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