<?php
// PukiWiki - Yet another WikiWikiWeb clone.
-// $Id: file.php,v 1.17 2005/04/16 04:56:49 henoheno Exp $
+// $Id: file.php,v 1.56 2006/04/10 14:41:10 henoheno Exp $
+// Copyright (C)
+// 2002-2006 PukiWiki Developers Team
+// 2001-2002 Originally written by yu-ji
+// License: GPL v2 or (at your option) any later version
//
// File related functions
+define('PKWK_MAXSHOW_CACHE', 'recent.dat');
+define('PKWK_AUTOLINK_REGEX_CACHE', 'autolink.dat');
+
// Get source(wiki text) data of the page
-function get_source($page = NULL)
+function get_source($page = NULL, $lock = TRUE)
{
- // Removing line-feeds: Because file() doesn't remove them.
- return is_page($page) ? str_replace("\r", '', file(get_filename($page))) : array();
+ $array = array();
+
+ if (is_page($page)) {
+ $path = get_filename($page);
+
+ if ($lock) {
+ $fp = @fopen($path, 'r');
+ if ($fp == FALSE) return $array;
+ flock($fp, LOCK_SH);
+ }
+
+ // Removing line-feeds: Because file() doesn't remove them.
+ $array = str_replace("\r", '', file($path));
+
+ if ($lock) {
+ flock($fp, LOCK_UN);
+ @fclose($fp);
+ }
+ }
+
+ return $array;
}
// Get last-modified filetime of the page
links_update($page);
}
-// User-defined rules (replace the source)
-function make_str_rules($str)
+// Modify original text with user-defined / system-defined rules
+function make_str_rules($source)
{
global $str_rules, $fixed_heading_anchor;
- $arr = explode("\n", $str);
+ $lines = explode("\n", $source);
+ $count = count($lines);
+
+ $modify = TRUE;
+ $multiline = 0;
+ $matches = array();
+ for ($i = 0; $i < $count; $i++) {
+ $line = & $lines[$i]; // Modify directly
+
+ // Ignore null string and preformatted texts
+ if ($line == '' || $line{0} == ' ' || $line{0} == "\t") continue;
+
+ // Modify this line?
+ if ($modify) {
+ if (! PKWKEXP_DISABLE_MULTILINE_PLUGIN_HACK &&
+ $multiline == 0 &&
+ preg_match('/#[^{]*(\{\{+)\s*$/', $line, $matches)) {
+ // Multiline convert plugin start
+ $modify = FALSE;
+ $multiline = strlen($matches[1]); // Set specific number
+ }
+ } else {
+ if (! PKWKEXP_DISABLE_MULTILINE_PLUGIN_HACK &&
+ $multiline != 0 &&
+ preg_match('/^\}{' . $multiline . '}\s*$/', $line)) {
+ // Multiline convert plugin end
+ $modify = TRUE;
+ $multiline = 0;
+ }
+ }
+ if ($modify === FALSE) continue;
- $retvars = $matches = array();
- foreach ($arr as $str) {
- if ($str != '' && $str{0} != ' ' && $str{0} != "\t")
- foreach ($str_rules as $rule => $replace)
- $str = preg_replace('/' . $rule . '/', $replace, $str);
+ // Replace with $str_rules
+ foreach ($str_rules as $pattern => $replacement)
+ $line = preg_replace('/' . $pattern . '/', $replacement, $line);
// Adding fixed anchor into headings
if ($fixed_heading_anchor &&
- preg_match('/^(\*{1,3}(.(?!\[#[A-Za-z][\w-]+\]))+)$/', $str, $matches))
- {
- // 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 . ']';
+ preg_match('/^(\*{1,3}.*?)(?:\[#([A-Za-z][\w-]*)\]\s*)?$/', $line, $matches) &&
+ (! isset($matches[2]) || $matches[2] == '')) {
+ // Generate unique id
+ $anchor = generate_fixed_heading_anchor_id($matches[1]);
+ $line = rtrim($matches[1]) . ' [#' . $anchor . ']';
}
- $retvars[] = $str;
}
- return join("\n", $retvars);
+ // Multiline part has no stopper
+ if (! PKWKEXP_DISABLE_MULTILINE_PLUGIN_HACK &&
+ $modify === FALSE && $multiline != 0)
+ $lines[] = str_repeat('}', $multiline);
+
+ return implode("\n", $lines);
+}
+
+// Generate ID
+function generate_fixed_heading_anchor_id($seed)
+{
+ // A random alphabetic letter + 7 letters of random strings from md()
+ return chr(mt_rand(ord('a'), ord('z'))) .
+ substr(md5(uniqid(substr($seed, 0, 100), TRUE)),
+ mt_rand(0, 24), 7);
+}
+
+// Read top N lines as an array
+// (Use PHP file() function if you want to get ALL lines)
+function file_head($file, $count = 1, $buffer = 8192, $lock = TRUE)
+{
+ $index = 0;
+ $array = array();
+
+ $fp = @fopen($file, 'r');
+ if ($fp === FALSE) return FALSE;
+ set_file_buffer($fp, 0);
+
+ if ($lock) flock($fp, LOCK_SH);
+ while (! feof($fp)) {
+ $line = fgets($fp, $buffer);
+ if ($line != FALSE) $array[] = $line;
+ if (++$index >= $count) break;
+ }
+ if ($lock) flock($fp, LOCK_UN);
+
+ if(! fclose($fp)) return FALSE;
+
+ return $array;
}
// Output to a file
function file_write($dir, $page, $str, $notimestamp = FALSE)
{
- global $update_exec, $_msg_invalidiwn;
- global $notify, $notify_diff_only, $notify_to, $notify_subject, $notify_header;
- global $smtp_server, $smtp_auth;
+ global $update_exec, $_msg_invalidiwn, $notify, $notify_diff_only, $notify_subject;
global $whatsdeleted, $maxshow_deleted;
if (PKWK_READONLY) return; // Do nothing
+ if ($dir != DATA_DIR && $dir != DIFF_DIR) die('file_write(): Invalid directory');
- if (! is_pagename($page))
- die_message(str_replace('$1', htmlspecialchars($page),
- str_replace('$2', 'WikiName', $_msg_invalidiwn)));
+ $page = strip_bracket($page);
+ $file = $dir . encode($page) . '.txt';
+ $file_exists = file_exists($file);
- $page = strip_bracket($page);
- $timestamp = FALSE;
- $file = $dir . encode($page) . '.txt';
+ // ----
+ // Delete?
- if ($dir == DATA_DIR && $str == '' && file_exists($file)) {
- unlink($file);
- add_recent($page, $whatsdeleted, '', $maxshow_deleted); // RecentDeleted
- }
+ if ($dir == DATA_DIR && $str === '') {
+ // Page deletion
+ if (! $file_exists) return; // Ignore null posting for DATA_DIR
- if ($str != '') {
- $str = preg_replace('/' . "\r" . '/', '', $str);
- $str = rtrim($str) . "\n";
+ // Update RecentDeleted (Add the $page)
+ add_recent($page, $whatsdeleted, '', $maxshow_deleted);
- if ($notimestamp && file_exists($file))
- $timestamp = filemtime($file) - LOCALZONE;
+ unlink($file);
- $fp = fopen($file, 'w') or
- die_message('Cannot write page file or diff file or other ' .
- htmlspecialchars($page) .
- '<br />Maybe permission is not writable or filename is too long');
+ // Update RecentChanges (Remove the $page from RecentChanges)
+ put_lastmodified();
- set_file_buffer($fp, 0);
- flock($fp, LOCK_EX);
- rewind($fp);
- fputs($fp, $str);
- flock($fp, LOCK_UN);
- fclose($fp);
+ // Clear is_page() cache
+ is_page($page, TRUE);
- if ($timestamp) pkwk_touch_file($file, $timestamp + LOCALZONE);
+ return;
+
+ } else if ($dir == DIFF_DIR && $str === " \n") {
+ return; // Ignore null posting for DIFF_DIR
}
- // Clear is_page() cache
- is_page($page, TRUE);
+ // ----
+ // File replacement (Edit)
- if (! $timestamp && $dir == DATA_DIR)
- put_lastmodified();
+ if (! is_pagename($page))
+ die_message(str_replace('$1', htmlspecialchars($page),
+ str_replace('$2', 'WikiName', $_msg_invalidiwn)));
- // Execute $update_exec here
- if ($update_exec && $dir == DATA_DIR)
- system($update_exec . ' > /dev/null &');
+ $str = rtrim(preg_replace('/' . "\r" . '/', '', $str)) . "\n";
+ $timestamp = ($file_exists && $notimestamp) ? filemtime($file) : FALSE;
- if ($notify && $dir == DIFF_DIR) {
- 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";
+ $fp = fopen($file, 'a') or die('fopen() failed: ' .
+ htmlspecialchars(basename($dir) . '/' . encode($page) . '.txt') .
+ '<br />' . "\n" .
+ 'Maybe permission is not writable or filename is too long');
+ set_file_buffer($fp, 0);
+ flock($fp, LOCK_EX);
+ ftruncate($fp, 0);
+ rewind($fp);
+ fputs($fp, $str);
+ flock($fp, LOCK_UN);
+ fclose($fp);
- $subject = str_replace('$page', $page, $notify_subject);
- ini_set('SMTP', $smtp_server);
- mb_language(LANG);
+ if ($timestamp) pkwk_touch_file($file, $timestamp);
- if ($smtp_auth) pop_before_smtp();
- mb_send_mail($notify_to, $subject, $str, $notify_header);
+ // Optional actions
+ if ($dir == DATA_DIR) {
+ // Update RecentChanges (Add or renew the $page)
+ if ($timestamp === FALSE) put_lastmodified();
+
+ // Execute $update_exec here
+ if ($update_exec) system($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['USER_AGENT'] = TRUE;
+ $footer['REMOTE_ADDR'] = TRUE;
+ pkwk_mail_notify($notify_subject, $str, $footer) or
+ die('pkwk_mail_notify(): Failed');
}
+
+ is_page($page, TRUE); // Clear is_page() cache
}
// Update RecentDeleted
function add_recent($page, $recentpage, $subject = '', $limit = 0)
{
- if (PKWK_READONLY || $limit == 0 || $page == '' || $recentpage == '') return;
+ if (PKWK_READONLY || $limit == 0 || $page == '' || $recentpage == '' ||
+ check_non_list($page)) return;
// Load
$lines = $matches = array();
fclose($fp);
}
-// Update RecentChanges
+// Re-create PKWK_MAXSHOW_CACHE
+
function put_lastmodified()
{
- global $maxshow, $whatsnew, $non_list, $autolink;
+ global $maxshow, $whatsnew, $autolink;
if (PKWK_READONLY) return; // Do nothing
+ // Get whole page list
$pages = get_existpages();
+
+ // Check ALL filetime
$recent_pages = array();
- $non_list_pattern = '/' . $non_list . '/';
foreach($pages as $page)
- if ($page != $whatsnew && ! preg_match($non_list_pattern, $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);
- // 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' .
- '<br />Maybe permission is not writable or filename is too long');
+ // Cut unused lines
+ $recent_pages = array_splice($recent_pages, 0, $maxshow);
+ // Re-create PKWK_MAXSHOW_CACHE
+ $fp = fopen(CACHE_DIR . PKWK_MAXSHOW_CACHE, 'w') or
+ die_message('Cannot write file ' .
+ 'CACHE_DIR/' . PKWK_MAXSHOW_CACHE . '<br />' . "\n" .
+ 'Maybe permission is not writable');
set_file_buffer($fp, 0);
flock($fp, LOCK_EX);
rewind($fp);
// Create RecentChanges
$fp = fopen(get_filename($whatsnew), 'w') or
- die_message('Cannot write page file ' .
- htmlspecialchars($whatsnew) .
- '<br />Maybe permission is not writable or filename is too long');
-
+ die_message('Cannot write file ' .
+ htmlspecialchars($whatsnew) . '<br />' . "\n" .
+ 'Maybe permission is not writable or filename is too long');
set_file_buffer($fp, 0);
flock($fp, LOCK_EX);
rewind($fp);
- foreach (array_splice(array_keys($recent_pages), 0, $maxshow) as $page) {
+ foreach (array_keys($recent_pages) as $page) {
$time = $recent_pages[$page];
$s_lastmod = htmlspecialchars(format_date($time));
$s_page = htmlspecialchars($page);
list($pattern, $pattern_a, $forceignorelist) =
get_autolink_pattern($pages);
- $fp = fopen(CACHE_DIR . 'autolink.dat', 'w') or
- die_message('Cannot write autolink file ' .
- CACHE_DIR . '/autolink.dat' .
- '<br />Maybe permission is not writable');
+ $fp = fopen(CACHE_DIR . PKWK_AUTOLINK_REGEX_CACHE, 'w') or
+ die_message('Cannot write file ' .
+ 'CACHE_DIR/' . PKWK_AUTOLINK_REGEX_CACHE . '<br />' . "\n" .
+ 'Maybe permission is not writable');
set_file_buffer($fp, 0);
flock($fp, LOCK_EX);
rewind($fp);
}
}
-// Get elapsed date of the pate
+// Get elapsed date of the page
function get_pg_passage($page, $sw = TRUE)
{
global $show_passage;
if(! file_exists($pagereading_chasen_path))
die_message('ChaSen not found: ' . $pagereading_chasen_path);
- $tmpfname = tempnam(CACHE_DIR, 'PageReading');
+ $tmpfname = tempnam(realpath(CACHE_DIR), 'PageReading');
$fp = fopen($tmpfname, 'w') or
die_message('Cannot write temporary file "' . $tmpfname . '".' . "\n");
foreach ($readings as $page => $reading) {
if(! file_exists($pagereading_kakasi_path))
die_message('KAKASI not found: ' . $pagereading_kakasi_path);
- $tmpfname = tempnam(CACHE_DIR, 'PageReading');
+ $tmpfname = tempnam(realpath(CACHE_DIR), 'PageReading');
$fp = fopen($tmpfname, 'w') or
die_message('Cannot write temporary file "' . $tmpfname . '".' . "\n");
foreach ($readings as $page => $reading) {
basename(htmlspecialchars($filename)));
// Try to chown by re-creating files
- // NOTE: @unlink() before rename() is for Windows but here's for Unix only
+ // 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 = copy($filename, $tmp) &&
- ($preserve_time ? touch($tmp, $stat[9], $stat[8]) : TRUE) &&
+ $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()
function pkwk_touch_file($filename, $time = FALSE, $atime = FALSE)
{
// Is the owner incorrected and unable to correct?
- if (pkwk_chown($filename)) {
+ if (! file_exists($filename) || pkwk_chown($filename)) {
if ($time === FALSE) {
$result = touch($filename);
} else if ($atime === FALSE) {