OSDN Git Service

BugTrack2/55: touch() before copy() is for 'rw-r--r--' instead of 'rwxr-xr-x' (with...
[pukiwiki/pukiwiki.git] / lib / file.php
index 6b15ada..852ad94 100644 (file)
@@ -1,44 +1,46 @@
 <?php
-/////////////////////////////////////////////////
 // PukiWiki - Yet another WikiWikiWeb clone.
+// $Id: file.php,v 1.21 2005/04/17 06:42:26 henoheno Exp $
 //
-// $Id: file.php,v 1.9 2004/12/11 15:44:45 henoheno Exp $
-//
+// File related functions
 
-// ¥½¡¼¥¹¤ò¼èÆÀ
+// Get source(wiki text) data of the page
 function get_source($page = NULL)
 {
+       // Removing line-feeds: Because file() doesn't remove them.
        return is_page($page) ? str_replace("\r", '', file(get_filename($page))) : array();
 }
 
-// ¥Ú¡¼¥¸¤Î¹¹¿·»þ¹ï¤òÆÀ¤ë
+// Get last-modified filetime of the page
 function get_filetime($page)
 {
        return is_page($page) ? filemtime(get_filename($page)) - LOCALZONE : 0;
 }
 
-// ¥Ú¡¼¥¸¤Î¥Õ¥¡¥¤¥ë̾¤òÆÀ¤ë
+// Get physical file name of the page
 function get_filename($page)
 {
        return DATA_DIR . encode($page) . '.txt';
 }
 
-// ¥Ú¡¼¥¸¤Î½ÐÎÏ
+// Put a data(wiki text) into a physical file(diff, backup, text)
 function page_write($page, $postdata, $notimestamp = FALSE)
 {
        global $trackback;
 
+       if (PKWK_READONLY) return; // Do nothing
+
        $postdata = make_str_rules($postdata);
 
-       // º¹Ê¬¥Õ¥¡¥¤¥ë¤ÎºîÀ®
+       // Create and write diff
        $oldpostdata = is_page($page) ? join('', get_source($page)) : '';
        $diffdata    = do_diff($oldpostdata, $postdata);
        file_write(DIFF_DIR, $page, $diffdata);
 
-       // ¥Ð¥Ã¥¯¥¢¥Ã¥×¤ÎºîÀ®
+       // Create backup
        make_backup($page, $postdata == ''); // Is $postdata null?
 
-       // ¥Õ¥¡¥¤¥ë¤Î½ñ¤­¹þ¤ß
+       // Create wiki text
        file_write(DATA_DIR, $page, $postdata, $notimestamp);
 
        if ($trackback) {
@@ -52,7 +54,7 @@ function page_write($page, $postdata, $notimestamp = FALSE)
        links_update($page);
 }
 
-// ¥æ¡¼¥¶ÄêµÁ¥ë¡¼¥ë(¥½¡¼¥¹¤òÃÖ´¹¤¹¤ë)
+// User-defined rules (replace the source)
 function make_str_rules($str)
 {
        global $str_rules, $fixed_heading_anchor;
@@ -61,20 +63,19 @@ function make_str_rules($str)
 
        $retvars = $matches = array();
        foreach ($arr as $str) {
-               if ($str != '' && $str{0} != ' ' && $str{0} != "\t") {
+               if ($str != '' && $str{0} != ' ' && $str{0} != "\t")
                        foreach ($str_rules as $rule => $replace)
-                               $str = preg_replace("/$rule/", $replace, $str);
-               }
+                               $str = preg_replace('/' . $rule . '/', $replace, $str);
                
-               // ¸«½Ð¤·¤Ë¸ÇÍ­ID¤òÉÕÍ¿¤¹¤ë
+               // Adding fixed anchor into headings
                if ($fixed_heading_anchor &&
                        preg_match('/^(\*{1,3}(.(?!\[#[A-Za-z][\w-]+\]))+)$/', $str, $matches))
                {
-                       // ¸ÇÍ­ID¤òÀ¸À®¤¹¤ë
-                       // ¥é¥ó¥À¥à¤Ê±Ñ»ú(1ʸ»ú) + md5¥Ï¥Ã¥·¥å¤Î¥é¥ó¥À¥à¤ÊÉôʬʸ»úÎó(7ʸ»ú)
+                       // Generate ID:
+                       // A random alphabetic letter + 7 letters of random strings from md()
                        $anchor = chr(mt_rand(ord('a'), ord('z'))) .
                                substr(md5(uniqid(substr($matches[1], 0, 100), 1)), mt_rand(0, 24), 7);
-                       $str = rtrim($matches[1]) . " [#$anchor]";
+                       $str = rtrim($matches[1]) . ' [#' . $anchor . ']';
                }
                $retvars[] = $str;
        }
@@ -82,18 +83,19 @@ function make_str_rules($str)
        return join("\n", $retvars);
 }
 
-// ¥Õ¥¡¥¤¥ë¤Ø¤Î½ÐÎÏ
+// Output to a file
 function file_write($dir, $page, $str, $notimestamp = FALSE)
 {
-       global $update_exec;
-       global $_msg_invalidiwn;
+       global $update_exec, $_msg_invalidiwn;
        global $notify, $notify_diff_only, $notify_to, $notify_subject, $notify_header;
        global $smtp_server, $smtp_auth;
+       global $whatsdeleted, $maxshow_deleted;
+
+       if (PKWK_READONLY) return; // Do nothing
 
        if (! is_pagename($page))
                die_message(str_replace('$1', htmlspecialchars($page),
-                           str_replace('$2', 'WikiName', $_msg_invalidiwn))
-               );
+                           str_replace('$2', 'WikiName', $_msg_invalidiwn)));
 
        $page      = strip_bracket($page);
        $timestamp = FALSE;
@@ -101,11 +103,11 @@ function file_write($dir, $page, $str, $notimestamp = FALSE)
 
        if ($dir == DATA_DIR && $str == '' && file_exists($file)) {
                unlink($file);
-               put_recentdeleted($page);
+               add_recent($page, $whatsdeleted, '', $maxshow_deleted); // RecentDeleted
        }
 
        if ($str != '') {
-               $str = preg_replace("/\r/", '', $str);
+               $str = preg_replace('/' . "\r" . '/', '', $str);
                $str = rtrim($str) . "\n";
 
                if ($notimestamp && file_exists($file))
@@ -122,81 +124,92 @@ function file_write($dir, $page, $str, $notimestamp = FALSE)
                fputs($fp, $str);
                flock($fp, LOCK_UN);
                fclose($fp);
-               if ($timestamp) 
-                       touch($file, $timestamp + LOCALZONE);
+
+               if ($timestamp) pkwk_touch_file($file, $timestamp + LOCALZONE);
        }
 
-       // is_page¤Î¥­¥ã¥Ã¥·¥å¤ò¥¯¥ê¥¢¤¹¤ë
+       // Clear is_page() cache
        is_page($page, TRUE);
 
        if (! $timestamp && $dir == DATA_DIR)
                put_lastmodified();
 
+       // Execute $update_exec here
        if ($update_exec && $dir == DATA_DIR)
                system($update_exec . ' > /dev/null &');
 
        if ($notify && $dir == DIFF_DIR) {
-               if ($notify_diff_only) // º¹Ê¬¤À¤±¤òÁ÷¿®¤¹¤ë
-                       $str = preg_replace('/^[^-+].*\n/m', '', $str);
-               if ($smtp_auth)
-                       pop_before_smtp();
+               if ($notify_diff_only) $str = preg_replace('/^[^-+].*\n/m', '', $str);
+               $str .= "\n" .
+                       str_repeat('-', 30) . "\n" .
+                       'URI: ' . get_script_uri() . '?' . rawurlencode($page) . "\n" .
+                       'REMOTE_ADDR: ' . $_SERVER['REMOTE_ADDR'] . "\n";
+
                $subject = str_replace('$page', $page, $notify_subject);
                ini_set('SMTP', $smtp_server);
                mb_language(LANG);
+
+               if ($smtp_auth) pop_before_smtp();
                mb_send_mail($notify_to, $subject, $str, $notify_header);
        }
 }
 
-// ºï½üÍúÎò¥Ú¡¼¥¸¤Î¹¹¿·
-function put_recentdeleted($page)
+// Update RecentDeleted
+function add_recent($page, $recentpage, $subject = '', $limit = 0)
 {
-       global $whatsdeleted, $maxshow_deleted;
+       if (PKWK_READONLY || $limit == 0 || $page == '' || $recentpage == '') return;
 
-       if ($maxshow_deleted == 0) return;
-
-       // Update RecentDeleted
+       // Load
        $lines = $matches = array();
-       foreach (get_source($whatsdeleted) as $line) {
+       foreach (get_source($recentpage) as $line)
                if (preg_match('/^-(.+) - (\[\[.+\]\])$/', $line, $matches))
                        $lines[$matches[2]] = $line;
-       }
 
-       $_page = "[[$page]]";
+       $_page = '[[' . $page . ']]';
+
+       // Remove a report about the same page
        if (isset($lines[$_page])) unset($lines[$_page]);
 
-       array_unshift($lines, '-' . format_date(UTIME) . " - $_page\n");
-       $lines = array_splice($lines, 0, $maxshow_deleted);
+       // Add
+       array_unshift($lines, '-' . format_date(UTIME) . ' - ' . $_page .
+               htmlspecialchars($subject) . "\n");
 
-       $fp = fopen(get_filename($whatsdeleted), 'w') or
+       // Get latest $limit reports
+       $lines = array_splice($lines, 0, $limit);
+
+       // Update
+       $fp = fopen(get_filename($recentpage), 'w') or
                die_message('Cannot write page file ' .
-               htmlspecialchars($whatsdeleted) .
+               htmlspecialchars($recentpage) .
                '<br />Maybe permission is not writable or filename is too long');
-
        set_file_buffer($fp, 0);
        flock($fp, LOCK_EX);
        rewind($fp);
+       fputs($fp, '#freeze'    . "\n");
+       fputs($fp, '#norelated' . "\n"); // :)
        fputs($fp, join('', $lines));
-       fputs($fp, "#norelated\n"); // :)
        flock($fp, LOCK_UN);
        fclose($fp);
 }
 
-// ºÇ½ª¹¹¿·¥Ú¡¼¥¸¤Î¹¹¿·
+// Update RecentChanges
 function put_lastmodified()
 {
        global $maxshow, $whatsnew, $non_list, $autolink;
 
+       if (PKWK_READONLY) return; // Do nothing
+
        $pages = get_existpages();
        $recent_pages = array();
-       foreach($pages as $page) {
-               if ($page != $whatsnew && ! preg_match("/$non_list/", $page))
+       $non_list_pattern = '/' . $non_list . '/';
+       foreach($pages as $page)
+               if ($page != $whatsnew && ! preg_match($non_list_pattern, $page))
                        $recent_pages[$page] = get_filetime($page);
-       }
 
-       //»þ¹ï¹ß½ç¤Ç¥½¡¼¥È
+       // Sort decending order of last-modification date
        arsort($recent_pages, SORT_NUMERIC);
 
-       // create recent.dat (for recent.inc.php)
+       // Create recent.dat (for recent.inc.php)
        $fp = fopen(CACHE_DIR . 'recent.dat', 'w') or
                die_message('Cannot write cache file ' .
                CACHE_DIR . 'recent.dat' .
@@ -206,11 +219,11 @@ function put_lastmodified()
        flock($fp, LOCK_EX);
        rewind($fp);
        foreach ($recent_pages as $page=>$time)
-               fputs($fp, "$time\t$page\n");
+               fputs($fp, $time . "\t" . $page . "\n");
        flock($fp, LOCK_UN);
        fclose($fp);
 
-       // create RecentChanges
+       // Create RecentChanges
        $fp = fopen(get_filename($whatsnew), 'w') or
                die_message('Cannot write page file ' .
                htmlspecialchars($whatsnew) .
@@ -223,13 +236,13 @@ function put_lastmodified()
                $time      = $recent_pages[$page];
                $s_lastmod = htmlspecialchars(format_date($time));
                $s_page    = htmlspecialchars($page);
-               fputs($fp, "-$s_lastmod - [[$s_page]]\n");
+               fputs($fp, '-' . $s_lastmod . ' - [[' . $s_page . ']]' . "\n");
        }
-       fputs($fp, "#norelated\n"); // :)
+       fputs($fp, '#norelated' . "\n"); // :)
        flock($fp, LOCK_UN);
        fclose($fp);
 
-       // for autolink
+       // For AutoLink
        if ($autolink) {
                list($pattern, $pattern_a, $forceignorelist) =
                        get_autolink_pattern($pages);
@@ -249,7 +262,7 @@ function put_lastmodified()
        }
 }
 
-// »ØÄꤵ¤ì¤¿¥Ú¡¼¥¸¤Î·Ð²á»þ¹ï
+// Get elapsed date of the pate
 function get_pg_passage($page, $sw = TRUE)
 {
        global $show_passage;
@@ -258,10 +271,10 @@ function get_pg_passage($page, $sw = TRUE)
        $time = get_filetime($page);
        $pg_passage = ($time != 0) ? get_passage($time) : '';
 
-       return $sw ? "<small>$pg_passage</small>" : " $pg_passage";
+       return $sw ? '<small>' . $pg_passage . '</small>' : ' ' . $pg_passage;
 }
 
-// Last-Modified ¥Ø¥Ã¥À
+// Last-Modified header
 function header_lastmod($page = NULL)
 {
        global $lastmod;
@@ -273,28 +286,27 @@ function header_lastmod($page = NULL)
        }
 }
 
-// Á´¥Ú¡¼¥¸Ì¾¤òÇÛÎó¤Ë
+// Get a page list of this wiki
 function get_existpages($dir = DATA_DIR, $ext = '.txt')
 {
        $aryret = array();
 
-       $pattern = '^((?:[0-9A-F]{2})+)';
-       if ($ext != '')
-               $pattern .= preg_quote($ext, '/') . '$';
+       $pattern = '((?:[0-9A-F]{2})+)';
+       if ($ext != '') $ext = preg_quote($ext, '/');
+       $pattern = '/^' . $pattern . $ext . '$/';
 
        $dp = @opendir($dir) or
                die_message($dir . ' is not found or not readable.');
        $matches = array();
-       while ($file = readdir($dp)) {
-               if (preg_match("/$pattern/", $file, $matches))
+       while ($file = readdir($dp))
+               if (preg_match($pattern, $file, $matches))
                        $aryret[$file] = decode($matches[1]);
-       }
        closedir($dp);
 
        return $aryret;
 }
 
-// ¥Ú¡¼¥¸Ì¾¤ÎÆɤߤòÇÛÎó¤Ë
+// Get PageReading(pronounce-annotated) data in an array()
 function get_readings()
 {
        global $pagereading_enable, $pagereading_kanji2kana_converter;
@@ -314,19 +326,19 @@ function get_readings()
                $line = chop($line);
                if(preg_match('/^-\[\[([^]]+)\]\]\s+(.+)$/', $line, $matches)) {
                        if(isset($readings[$matches[1]])) {
-                               // Æɤߤ¬ÉÔÌÀ¤Î¥Ú¡¼¥¸
+                               // This page is not clear how to be pronounced
                                $readings[$matches[1]] = $matches[2];
                        } else {
-                               // ºï½ü¤µ¤ì¤¿¥Ú¡¼¥¸
+                               // This page seems deleted
                                $deletedPage = TRUE;
                        }
                }
        }
 
-       // ChaSen/KAKASI ¸Æ¤Ó½Ð¤·¤¬Í­¸ú¤ËÀßÄꤵ¤ì¤Æ¤¤¤ë¾ì¹ç
+       // If enabled ChaSen/KAKASI execution
        if($pagereading_enable) {
 
-               // Æɤߤ¬ÉÔÌÀ¤Î¥Ú¡¼¥¸¤¬¤¢¤ë¤«¥Á¥§¥Ã¥¯
+               // Check there's non-clear-pronouncing page
                $unknownPage = FALSE;
                foreach ($readings as $page => $reading) {
                        if($reading == '') {
@@ -335,19 +347,19 @@ function get_readings()
                        }
                }
 
-               // Æɤߤ¬ÉÔÌÀ¤Î¥Ú¡¼¥¸¤¬¤¢¤ë¾ì¹ç¡¢ChaSen/KAKASI ¤ò¼Â¹Ô
+               // Execute ChaSen/KAKASI, and get annotation
                if($unknownPage) {
                        switch(strtolower($pagereading_kanji2kana_converter)) {
                        case 'chasen':
                                if(! file_exists($pagereading_chasen_path))
-                                       die_message("ChaSen not found: $pagereading_chasen_path");
+                                       die_message('ChaSen not found: ' . $pagereading_chasen_path);
 
                                $tmpfname = tempnam(CACHE_DIR, 'PageReading');
-                               $fp = fopen($tmpfname, "w") or
-                                       die_message("Cannot write temporary file '$tmpfname'.\n");
+                               $fp = fopen($tmpfname, 'w') or
+                                       die_message('Cannot write temporary file "' . $tmpfname . '".' . "\n");
                                foreach ($readings as $page => $reading) {
                                        if($reading != '') continue;
-                                       fputs($fp, mb_convert_encoding("$page\n",
+                                       fputs($fp, mb_convert_encoding($page . "\n",
                                                $pagereading_kanji2kana_encoding, SOURCE_ENCODING));
                                }
                                fclose($fp);
@@ -356,7 +368,7 @@ function get_readings()
                                $fp     = popen($chasen, 'r');
                                if($fp === FALSE) {
                                        unlink($tmpfname);
-                                       die_message("ChaSen execution failed: $chasen");
+                                       die_message('ChaSen execution failed: ' . $chasen);
                                }
                                foreach ($readings as $page => $reading) {
                                        if($reading != '') continue;
@@ -370,20 +382,20 @@ function get_readings()
                                pclose($fp);
 
                                unlink($tmpfname) or
-                                       die_message("Temporary file can not be removed: $tmpfname");
+                                       die_message('Temporary file can not be removed: ' . $tmpfname);
                                break;
 
-                       case 'kakasi':
+                       case 'kakasi':  /*FALLTHROUGH*/
                        case 'kakashi':
                                if(! file_exists($pagereading_kakasi_path))
-                                       die_message("KAKASI not found: $pagereading_kakasi_path");
+                                       die_message('KAKASI not found: ' . $pagereading_kakasi_path);
 
                                $tmpfname = tempnam(CACHE_DIR, 'PageReading');
                                $fp       = fopen($tmpfname, 'w') or
-                                       die_message("Cannot write temporary file '$tmpfname'.\n");
+                                       die_message('Cannot write temporary file "' . $tmpfname . '".' . "\n");
                                foreach ($readings as $page => $reading) {
                                        if($reading != '') continue;
-                                       fputs($fp, mb_convert_encoding("$page\n",
+                                       fputs($fp, mb_convert_encoding($page . "\n",
                                                $pagereading_kanji2kana_encoding, SOURCE_ENCODING));
                                }
                                fclose($fp);
@@ -392,7 +404,7 @@ function get_readings()
                                $fp     = popen($kakasi, 'r');
                                if($fp === FALSE) {
                                        unlink($tmpfname);
-                                       die_message("KAKASI execution failed: $kakasi");
+                                       die_message('KAKASI execution failed: ' . $kakasi);
                                }
 
                                foreach ($readings as $page => $reading) {
@@ -407,7 +419,7 @@ function get_readings()
                                pclose($fp);
 
                                unlink($tmpfname) or
-                                       die_message("Temporary file can not be removed: $tmpfname");
+                                       die_message('Temporary file can not be removed: ' . $tmpfname);
                                break;
 
                        case 'none':
@@ -425,31 +437,28 @@ function get_readings()
                                        $readings[$page] = $page;
                                        foreach ($patterns as $no => $pattern)
                                                $readings[$page] = mb_convert_kana(mb_ereg_replace($pattern,
-                                                       $replacements[$no], $readings[$page]), "aKCV");
+                                                       $replacements[$no], $readings[$page]), 'aKCV');
                                }
                                break;
 
                        default:
-                               die_message("Unknown kanji-kana converter: $pagereading_kanji2kana_converter.");
+                               die_message('Unknown kanji-kana converter: ' . $pagereading_kanji2kana_converter . '.');
                                break;
                        }
                }
 
                if($unknownPage || $deletedPage) {
 
-                       asort($readings); // Æɤߤǥ½¡¼¥È
+                       asort($readings); // Sort by pronouncing(alphabetical/reading) order
                        $body = '';
                        foreach ($readings as $page => $reading)
-                               $body .= "-[[$page]] $reading\n";
+                               $body .= '-[[' . $page . ']] ' . $reading . "\n";
 
-                       // ¥Ú¡¼¥¸¤ò½ñ¤­¹þ¤ß
                        page_write($pagereading_config_page, $body);
                }
        }
 
-       // ÆɤßÉÔÌÀ¤Î¥Ú¡¼¥¸¤Ï¡¢¤½¤Î¤Þ¤Þ¥Ú¡¼¥¸Ì¾¤òÊÖ¤¹ (ChaSen/KAKASI ¸Æ
-       // ¤Ó½Ð¤·¤¬Ìµ¸ú¤ËÀßÄꤵ¤ì¤Æ¤¤¤ë¾ì¹ç¤ä¡¢ChaSen/KAKASI ¸Æ¤Ó½Ð¤·¤Ë
-       // ¼ºÇÔ¤·¤¿»þ¤Î°Ù)
+       // Pages that are not prounouncing-clear, return pagenames of themselves
        foreach ($pages as $page) {
                if($readings[$page] == '')
                        $readings[$page] = $page;
@@ -458,23 +467,20 @@ function get_readings()
        return $readings;
 }
 
-//¥Õ¥¡¥¤¥ë̾¤Î°ìÍ÷¤òÇÛÎó¤Ë(¥¨¥ó¥³¡¼¥ÉºÑ¤ß¡¢³ÈÄ¥»Ò¤ò»ØÄê)
+// Get a list of encoded files (must specify a directory and a suffix)
 function get_existfiles($dir, $ext)
 {
+       $pattern = '/^(?:[0-9A-F]{2})+' . preg_quote($ext, '/') . '$/';
        $aryret = array();
-
-       $pattern = '^(?:[0-9A-F]{2})+' . preg_quote($ext, '/') . '$';
-       $dp = @opendir($dir) or
-               die_message($dir . ' is not found or not readable.');
-       while ($file = readdir($dp)) {
-               if (preg_match("/$pattern/", $file))
+       $dp = @opendir($dir) or die_message($dir . ' is not found or not readable.');
+       while ($file = readdir($dp))
+               if (preg_match($pattern, $file))
                        $aryret[] = $dir . $file;
-       }
        closedir($dp);
        return $aryret;
 }
 
-//¤¢¤ë¥Ú¡¼¥¸¤Î´ØÏ¢¥Ú¡¼¥¸¤òÆÀ¤ë
+// Get a list of related pages of the page
 function links_get_related($page)
 {
        global $vars, $related;
@@ -482,12 +488,90 @@ function links_get_related($page)
 
        if (isset($links[$page])) return $links[$page];
 
-       // ²Äǽ¤Ê¤émake_link()¤ÇÀ¸À®¤·¤¿´ØÏ¢¥Ú¡¼¥¸¤ò¼è¤ê¹þ¤à
+       // If possible, merge related pages generated by make_link()
        $links[$page] = ($page == $vars['page']) ? $related : array();
 
-       // ¥Ç¡¼¥¿¥Ù¡¼¥¹¤«¤é´ØÏ¢¥Ú¡¼¥¸¤òÆÀ¤ë
+       // Get repated pages from DB
        $links[$page] += links_get_related_db($vars['page']);
 
        return $links[$page];
 }
+
+// _If needed_, re-create the file to change/correct ownership into PHP's
+// NOTE: Not works for Windows
+function pkwk_chown($filename, $preserve_time = TRUE)
+{
+       static $php_uid; // PHP's UID
+
+       if (! isset($php_uid)) {
+               if (extension_loaded('posix')) {
+                       $php_uid = posix_getuid(); // Unix
+               } else {
+                       $php_uid = 0; // Windows
+               }
+       }
+
+       // Lock for pkwk_chown()
+       $lockfile = CACHE_DIR . 'pkwk_chown.lock';
+       $flock = fopen($lockfile, 'a') or
+               die('pkwk_chown(): fopen() failed for: CACHEDIR/' .
+                       basename(htmlspecialchars($lockfile)));
+       flock($flock, LOCK_EX) or die('pkwk_chown(): flock() failed for lock');
+
+       // Check owner
+       $stat = stat($filename) or
+               die('pkwk_chown(): stat() failed for: '  . basename(htmlspecialchars($filename)));
+       if ($stat[4] === $php_uid) {
+               // NOTE: Windows always here
+               $result = TRUE; // Seems the same UID. Nothing to do
+       } else {
+               $tmp = $filename . '.' . getmypid() . '.tmp';
+
+               // Lock source $filename to avoid file corruption
+               // NOTE: Not 'r+'. Don't check write permission here
+               $ffile = fopen($filename, 'r') or
+                       die('pkwk_chown(): fopen() failed for: ' .
+                               basename(htmlspecialchars($filename)));
+
+               // Try to chown by re-creating files
+               // NOTE:
+               //   * touch() before copy() is for 'rw-r--r--' instead of 'rwxr-xr-x' (with umask 022).
+               //   * (PHP 4 < PHP 4.2.0) touch() with the third argument is not implemented and retuns NULL and Warn.
+               //   * @unlink() before rename() is for Windows but here's for Unix only
+               flock($ffile, LOCK_EX) or die('pkwk_chown(): flock() failed');
+               $result = touch($tmp) && copy($filename, $tmp) &&
+                       ($preserve_time ? (touch($tmp, $stat[9], $stat[8]) || touch($tmp, $stat[9])) : TRUE) &&
+                       rename($tmp, $filename);
+               flock($ffile, LOCK_UN) or die('pkwk_chown(): flock() failed');
+
+               fclose($ffile) or die('pkwk_chown(): fclose() failed');
+
+               if ($result === FALSE) @unlink($tmp);
+       }
+
+       // Unlock for pkwk_chown()
+       flock($flock, LOCK_UN) or die('pkwk_chown(): flock() failed for lock');
+       fclose($flock) or die('pkwk_chown(): fclose() failed for lock');
+
+       return $result;
+}
+
+// touch() with trying pkwk_chown()
+function pkwk_touch_file($filename, $time = FALSE, $atime = FALSE)
+{
+       // Is the owner incorrected and unable to correct?
+       if (! file_exists($filename) || pkwk_chown($filename)) {
+               if ($time === FALSE) {
+                       $result = touch($filename);
+               } else if ($atime === FALSE) {
+                       $result = touch($filename, $time);
+               } else {
+                       $result = touch($filename, $time, $atime);
+               }
+               return $result;
+       } else {
+               die('pkwk_touch_file(): Invalid UID and (not writable for the directory or not a flie): ' .
+                       htmlspecialchars(basename($filename)));
+       }
+}
 ?>