OSDN Git Service

BugTrack/2401 Locked file_get_contents/file_put_contents on bugtrack
[pukiwiki/pukiwiki.git] / lib / file.php
index 748b069..b90a2f8 100644 (file)
@@ -1,8 +1,8 @@
 <?php
 // PukiWiki - Yet another WikiWikiWeb clone.
-// $Id: file.php,v 1.65 2006/04/29 02:32:49 henoheno Exp $
+// file.php
 // Copyright (C)
-//   2002-2006 PukiWiki Developers Team
+//   2002-2016 PukiWiki Development Team
 //   2001-2002 Originally written by yu-ji
 // License: GPL v2 or (at your option) any later version
 //
@@ -16,26 +16,45 @@ define('PKWK_MAXSHOW_CACHE', 'recent.dat');
 define('PKWK_AUTOLINK_REGEX_CACHE', 'autolink.dat');
 
 // Get source(wiki text) data of the page
+// Returns FALSE if error occurerd
 function get_source($page = NULL, $lock = TRUE, $join = FALSE)
 {
+       //$result = NULL;       // File is not found
        $result = $join ? '' : array();
+               // Compat for "implode('', get_source($file))",
+               //      -- this is slower than "get_source($file, TRUE, TRUE)"
+               // Compat for foreach(get_source($file) as $line) {} not to warns
 
-       if (is_page($page)) {
-               $path  = get_filename($page);
+       $path = get_filename($page);
+       if (file_exists($path)) {
 
                if ($lock) {
                        $fp = @fopen($path, 'r');
-                       if ($fp == FALSE) return $result;
+                       if ($fp === FALSE) return FALSE;
                        flock($fp, LOCK_SH);
                }
 
                if ($join) {
                        // Returns a value
-                       $result = str_replace("\r", '', fread($fp, filesize($path)));
+                       $size = filesize($path);
+                       if ($size === FALSE) {
+                               $result = FALSE;
+                       } else if ($size == 0) {
+                               $result = '';
+                       } else {
+                               $result = fread($fp, $size);
+                               if ($result !== FALSE) {
+                                       // Removing Carriage-Return
+                                       $result = str_replace("\r", '', $result);
+                               }
+                       }
                } else {
                        // Returns an array
-                       // Removing line-feeds: Because file() doesn't remove them.
-                       $result = str_replace("\r", '', file($path));
+                       $result = file($path);
+                       if ($result !== FALSE) {
+                               // Removing Carriage-Return
+                               $result = str_replace("\r", '', $result);
+                       }
                }
 
                if ($lock) {
@@ -62,30 +81,29 @@ function get_filename($page)
 // 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);
+       $text_without_author = remove_author_info($postdata);
+       $postdata = add_author_info($text_without_author);
+       $is_delete = empty($text_without_author);
 
-       // Create and write diff
+       // Do nothing when it has no changes
        $oldpostdata = is_page($page) ? join('', get_source($page)) : '';
+       $oldtext_without_author = remove_author_info($oldpostdata);
+       if ($text_without_author === $oldtext_without_author) {
+               // Do nothing on updating with unchanged content
+               return;
+       }
+       // Create and write diff
        $diffdata    = do_diff($oldpostdata, $postdata);
        file_write(DIFF_DIR, $page, $diffdata);
 
        // Create backup
-       make_backup($page, $postdata == ''); // Is $postdata null?
+       make_backup($page, $is_delete, $postdata); // Is $postdata null?
 
        // Create wiki text
-       file_write(DATA_DIR, $page, $postdata, $notimestamp);
-
-       if ($trackback) {
-               // TrackBack Ping
-               $_diff = explode("\n", $diffdata);
-               $plus  = join("\n", preg_replace('/^\+/', '', preg_grep('/^\+/', $_diff)));
-               $minus = join("\n", preg_replace('/^-/',  '', preg_grep('/^-/',  $_diff)));
-               tb_send($page, $plus, $minus);
-       }
+       file_write(DATA_DIR, $page, $postdata, $notimestamp, $is_delete);
 
        links_update($page);
 }
@@ -149,6 +167,38 @@ function make_str_rules($source)
        return implode("\n", $lines);
 }
 
+function add_author_info($wikitext)
+{
+       global $auth_user, $auth_user_fullname;
+       $author = preg_replace('/"/', '', $auth_user);
+       $fullname = $auth_user_fullname;
+       if (!$fullname && $author) {
+               // Fullname is empty, use $author as its fullname
+               $fullname = preg_replace('/^[^:]*:/', '', $author);
+       }
+       $displayname = preg_replace('/"/', '', $fullname);
+       $user_prefix = get_auth_user_prefix();
+       $author_text = sprintf('#author("%s","%s","%s")',
+               get_date_atom(UTIME + LOCALZONE),
+               ($author ? $user_prefix . $author : ''),
+               $displayname) . "\n";
+       return $author_text . $wikitext;
+}
+
+function remove_author_info($wikitext)
+{
+       return preg_replace('/^\s*#author\([^\n]*(\n|$)/m', '', $wikitext);
+}
+
+function get_date_atom($timestamp)
+{
+       // Compatible with DATE_ATOM format
+       // return date(DATE_ATOM, $timestamp);
+       $zmin = abs(LOCALZONE / 60);
+       return date('Y-m-d\TH:i:s', $timestamp) . sprintf('%s%02d:%02d',
+               (LOCALZONE < 0 ? '-' : '+') , $zmin / 60, $zmin % 60);
+}
+
 // Generate ID
 function generate_fixed_heading_anchor_id($seed)
 {
@@ -182,9 +232,9 @@ function file_head($file, $count = 1, $lock = TRUE, $buffer = 8192)
 }
 
 // Output to a file
-function file_write($dir, $page, $str, $notimestamp = FALSE)
+function file_write($dir, $page, $str, $notimestamp = FALSE, $is_delete = FALSE)
 {
-       global $update_exec, $_msg_invalidiwn, $notify, $notify_diff_only, $notify_subject;
+       global $_msg_invalidiwn, $notify, $notify_diff_only, $notify_subject;
        global $whatsdeleted, $maxshow_deleted;
 
        if (PKWK_READONLY) return; // Do nothing
@@ -197,17 +247,18 @@ function file_write($dir, $page, $str, $notimestamp = FALSE)
        // ----
        // Delete?
 
-       if ($dir == DATA_DIR && $str === '') {
+       if ($dir == DATA_DIR && $is_delete) {
                // Page deletion
                if (! $file_exists) return; // Ignore null posting for DATA_DIR
 
                // Update RecentDeleted (Add the $page)
                add_recent($page, $whatsdeleted, '', $maxshow_deleted);
 
+               // Remove the page
                unlink($file);
 
-               // Update RecentChanges (Remove the $page from RecentChanges)
-               put_lastmodified();
+               // Update RecentDeleted, and remove the page from RecentChanges
+               lastmodified_add($whatsdeleted, $page);
 
                // Clear is_page() cache
                is_page($page, TRUE);
@@ -222,14 +273,14 @@ function file_write($dir, $page, $str, $notimestamp = FALSE)
        // File replacement (Edit)
 
        if (! is_pagename($page))
-               die_message(str_replace('$1', htmlspecialchars($page),
+               die_message(str_replace('$1', htmlsc($page),
                            str_replace('$2', 'WikiName', $_msg_invalidiwn)));
 
        $str = rtrim(preg_replace('/' . "\r" . '/', '', $str)) . "\n";
        $timestamp = ($file_exists && $notimestamp) ? filemtime($file) : FALSE;
 
        $fp = fopen($file, 'a') or die('fopen() failed: ' .
-               htmlspecialchars(basename($dir) . '/' . encode($page) . '.txt') .       
+               htmlsc(basename($dir) . '/' . encode($page) . '.txt') . 
                '<br />' . "\n" .
                'Maybe permission is not writable or filename is too long');
        set_file_buffer($fp, 0);
@@ -247,14 +298,15 @@ function file_write($dir, $page, $str, $notimestamp = FALSE)
                // Update RecentChanges (Add or renew the $page)
                if ($timestamp === FALSE) lastmodified_add($page);
 
-               // Execute $update_exec here
-               if ($update_exec) system($update_exec . ' > /dev/null &');
+               // Command execution per update
+               if (defined('PKWK_UPDATE_EXEC') && PKWK_UPDATE_EXEC)
+                       system(PKWK_UPDATE_EXEC . ' > /dev/null &');
 
        } else if ($dir == DIFF_DIR && $notify) {
                if ($notify_diff_only) $str = preg_replace('/^[^-+].*\n/m', '', $str);
                $footer['ACTION'] = 'Page update';
                $footer['PAGE']   = & $page;
-               $footer['URI']    = get_script_uri() . '?' . rawurlencode($page);
+               $footer['URI']    = get_script_uri() . '?' . pagename_urlencode($page);
                $footer['USER_AGENT']  = TRUE;
                $footer['REMOTE_ADDR'] = TRUE;
                pkwk_mail_notify($notify_subject, $str, $footer) or
@@ -283,7 +335,7 @@ function add_recent($page, $recentpage, $subject = '', $limit = 0)
 
        // Add
        array_unshift($lines, '-' . format_date(UTIME) . ' - ' . $_page .
-               htmlspecialchars($subject) . "\n");
+               htmlsc($subject) . "\n");
 
        // Get latest $limit reports
        $lines = array_splice($lines, 0, $limit);
@@ -291,7 +343,7 @@ function add_recent($page, $recentpage, $subject = '', $limit = 0)
        // Update
        $fp = fopen(get_filename($recentpage), 'w') or
                die_message('Cannot write page file ' .
-               htmlspecialchars($recentpage) .
+               htmlsc($recentpage) .
                '<br />Maybe permission is not writable or filename is too long');
        set_file_buffer($fp, 0);
        flock($fp, LOCK_EX);
@@ -305,7 +357,7 @@ function add_recent($page, $recentpage, $subject = '', $limit = 0)
 
 // Update PKWK_MAXSHOW_CACHE itself (Add or renew about the $page) (Light)
 // Use without $autolink
-function lastmodified_add($page = '')
+function lastmodified_add($update = '', $remove = '')
 {
        global $maxshow, $whatsnew, $autolink;
 
@@ -315,7 +367,8 @@ function lastmodified_add($page = '')
                return;
        }
 
-       if (check_non_list($page)) return; // No need
+       if (($update == '' || check_non_list($update)) && $remove == '')
+               return; // No need
 
        $file = CACHE_DIR . PKWK_MAXSHOW_CACHE;
        if (! file_exists($file)) {
@@ -337,20 +390,33 @@ function lastmodified_add($page = '')
                        $recent_pages[$matches[2]] = $matches[1];
 
        // Remove if it exists inside
-       if (isset($recent_pages[$page])) unset($recent_pages[$page]);
+       if (isset($recent_pages[$update])) unset($recent_pages[$update]);
+       if (isset($recent_pages[$remove])) unset($recent_pages[$remove]);
 
        // Add to the top: like array_unshift()
-       $recent_pages = array($page => get_filetime($page)) + $recent_pages;
+       if ($update != '')
+               $recent_pages = array($update => get_filetime($update)) + $recent_pages;
 
-       // Write
-       ftruncate($fp, 0);
-       rewind($fp);
-       foreach ($recent_pages as $_page=>$time)
-               fputs($fp, $time . "\t" . $_page . "\n");
+       // Check
+       $abort = count($recent_pages) < $maxshow;
+
+       if (! $abort) {
+               // Write
+               ftruncate($fp, 0);
+               rewind($fp);
+               foreach ($recent_pages as $_page=>$time)
+                       fputs($fp, $time . "\t" . $_page . "\n");
+       }
 
        flock($fp, LOCK_UN);
        fclose($fp);
 
+       if ($abort) {
+               put_lastmodified(); // Try to (re)create ALL
+               return;
+       }
+
+
 
        // ----
        // Update the page 'RecentChanges'
@@ -361,7 +427,7 @@ function lastmodified_add($page = '')
        // Open
        pkwk_touch_file($file);
        $fp = fopen($file, 'r+') or
-               die_message('Cannot open ' . htmlspecialchars($whatsnew));
+               die_message('Cannot open ' . htmlsc($whatsnew));
        set_file_buffer($fp, 0);
        flock($fp, LOCK_EX);
 
@@ -369,8 +435,8 @@ function lastmodified_add($page = '')
        ftruncate($fp, 0);
        rewind($fp);
        foreach ($recent_pages as $_page=>$time)
-               fputs($fp, '-' . htmlspecialchars(format_date($time)) .
-                       ' - ' . '[[' . htmlspecialchars($_page) . ']]' . "\n");
+               fputs($fp, '-' . htmlsc(format_date($time)) .
+                       ' - ' . '[[' . htmlsc($_page) . ']]' . "\n");
        fputs($fp, '#norelated' . "\n"); // :)
 
        flock($fp, LOCK_UN);
@@ -390,14 +456,22 @@ function put_lastmodified()
        // Check ALL filetime
        $recent_pages = array();
        foreach($pages as $page)
-               if ($page != $whatsnew && ! check_non_list($page))
+               if ($page !== $whatsnew && ! check_non_list($page))
                        $recent_pages[$page] = get_filetime($page);
 
        // Sort decending order of last-modification date
        arsort($recent_pages, SORT_NUMERIC);
 
        // Cut unused lines
-       $recent_pages = array_splice($recent_pages, 0, $maxshow + PKWK_MAXSHOW_ALLOWANCE);
+       // BugTrack2/179: array_splice() will break integer keys in hashtable
+       $count   = $maxshow + PKWK_MAXSHOW_ALLOWANCE;
+       $_recent = array();
+       foreach($recent_pages as $key=>$value) {
+               unset($recent_pages[$key]);
+               $_recent[$key] = $value;
+               if (--$count < 1) break;
+       }
+       $recent_pages = & $_recent;
 
        // Re-create PKWK_MAXSHOW_CACHE
        $file = CACHE_DIR . PKWK_MAXSHOW_CACHE;
@@ -417,15 +491,15 @@ function put_lastmodified()
        $file = get_filename($whatsnew);
        pkwk_touch_file($file);
        $fp = fopen($file, 'r+') or
-               die_message('Cannot open ' . htmlspecialchars($whatsnew));
+               die_message('Cannot open ' . htmlsc($whatsnew));
        set_file_buffer($fp, 0);
        flock($fp, LOCK_EX);
        ftruncate($fp, 0);
        rewind($fp);
        foreach (array_keys($recent_pages) as $page) {
                $time      = $recent_pages[$page];
-               $s_lastmod = htmlspecialchars(format_date($time));
-               $s_page    = htmlspecialchars($page);
+               $s_lastmod = htmlsc(format_date($time));
+               $s_page    = htmlsc($page);
                fputs($fp, '-' . $s_lastmod . ' - [[' . $s_page . ']]' . "\n");
        }
        fputs($fp, '#norelated' . "\n"); // :)
@@ -477,21 +551,36 @@ function header_lastmod($page = NULL)
        }
 }
 
+// Get a list of encoded files (must specify a directory and a suffix)
+function get_existfiles($dir = DATA_DIR, $ext = '.txt')
+{
+       $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)) !== FALSE) {
+               if (preg_match($pattern, $file)) {
+                       $aryret[] = $dir . $file;
+               }
+       }
+       closedir($dp);
+
+       return $aryret;
+}
+
 // Get a page list of this wiki
 function get_existpages($dir = DATA_DIR, $ext = '.txt')
 {
        $aryret = array();
+       $pattern = '/^((?:[0-9A-F]{2})+)' . 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.');
+       $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)) !== FALSE) {
+               if (preg_match($pattern, $file, $matches)) {
                        $aryret[$file] = decode($matches[1]);
+               }
+       }
        closedir($dp);
 
        return $aryret;
@@ -640,7 +729,7 @@ function get_readings()
 
                if($unknownPage || $deletedPage) {
 
-                       asort($readings); // Sort by pronouncing(alphabetical/reading) order
+                       asort($readings, SORT_STRING); // Sort by pronouncing(alphabetical/reading) order
                        $body = '';
                        foreach ($readings as $page => $reading)
                                $body .= '-[[' . $page . ']] ' . $reading . "\n";
@@ -658,19 +747,6 @@ 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();
-       $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)
 {
@@ -680,7 +756,7 @@ function links_get_related($page)
        if (isset($links[$page])) return $links[$page];
 
        // If possible, merge related pages generated by make_link()
-       $links[$page] = ($page == $vars['page']) ? $related : array();
+       $links[$page] = ($page === $vars['page']) ? $related : array();
 
        // Get repated pages from DB
        $links[$page] += links_get_related_db($vars['page']);
@@ -706,12 +782,12 @@ function pkwk_chown($filename, $preserve_time = TRUE)
        $lockfile = CACHE_DIR . 'pkwk_chown.lock';
        $flock = fopen($lockfile, 'a') or
                die('pkwk_chown(): fopen() failed for: CACHEDIR/' .
-                       basename(htmlspecialchars($lockfile)));
+                       basename(htmlsc($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)));
+               die('pkwk_chown(): stat() failed for: '  . basename(htmlsc($filename)));
        if ($stat[4] === $php_uid) {
                // NOTE: Windows always here
                $result = TRUE; // Seems the same UID. Nothing to do
@@ -722,7 +798,7 @@ function pkwk_chown($filename, $preserve_time = TRUE)
                // NOTE: Not 'r+'. Don't check write permission here
                $ffile = fopen($filename, 'r') or
                        die('pkwk_chown(): fopen() failed for: ' .
-                               basename(htmlspecialchars($filename)));
+                               basename(htmlsc($filename)));
 
                // Try to chown by re-creating files
                // NOTE:
@@ -762,7 +838,22 @@ function pkwk_touch_file($filename, $time = FALSE, $atime = FALSE)
                return $result;
        } else {
                die('pkwk_touch_file(): Invalid UID and (not writable for the directory or not a flie): ' .
-                       htmlspecialchars(basename($filename)));
+                       htmlsc(basename($filename)));
        }
 }
-?>
+
+/**
+ * Lock-enabled file_get_contents
+ *
+ * Require: PHP5+
+ */
+function pkwk_file_get_contents($filename) {
+       if (! file_exists($filename)) {
+               return false;
+       }
+       $fp   = fopen($filename, 'rb');
+       flock($fp, LOCK_SH);
+       $file = file_get_contents($filename);
+       flock($fp, LOCK_UN);
+       return $file;
+}