OSDN Git Service

BugTrack/2396 Stop page redirection when new_page = old_page
[pukiwiki/pukiwiki.git] / lib / func.php
index c0c4bb7..e061af8 100644 (file)
@@ -1,8 +1,8 @@
 <?php
 // PukiWiki - Yet another WikiWikiWeb clone.
-// $Id: func.php,v 1.58 2006/04/15 02:50:21 teanan Exp $
-// Copyright (C)
-//   2002-2006 PukiWiki Developers Team
+// func.php
+// Copyright
+//   2002-2016 PukiWiki Development Team
 //   2001-2002 Originally written by yu-ji
 // License: GPL v2 or (at your option) any later version
 //
@@ -80,12 +80,12 @@ function is_freeze($page, $clearcache = FALSE)
                return FALSE;
        } else {
                $fp = fopen(get_filename($page), 'rb') or
-                       die('is_freeze(): fopen() failed: ' . htmlspecialchars($page));
+                       die('is_freeze(): fopen() failed: ' . htmlsc($page));
                flock($fp, LOCK_SH) or die('is_freeze(): flock() failed');
                rewind($fp);
                $buffer = fgets($fp, 9);
                flock($fp, LOCK_UN) or die('is_freeze(): flock() failed');
-               fclose($fp) or die('is_freeze(): fclose() failed: ' . htmlspecialchars($page));
+               fclose($fp) or die('is_freeze(): fclose() failed: ' . htmlsc($page));
 
                $is_freeze[$page] = ($buffer != FALSE && rtrim($buffer, "\r\n") == '#freeze');
                return $is_freeze[$page];
@@ -182,7 +182,7 @@ function get_search_words($words = array(), $do_escape = FALSE)
                        $char = mb_substr($word_nm, $pos, 1, SOURCE_ENCODING);
 
                        // Just normalized one? (ASCII char or Zenkaku-Katakana?)
-                       $or = array(preg_quote($do_escape ? htmlspecialchars($char) : $char, $quote));
+                       $or = array(preg_quote($do_escape ? htmlsc($char) : $char, $quote));
                        if (strlen($char) == 1) {
                                // An ASCII (single-byte) character
                                foreach (array(strtoupper($char), strtolower($char)) as $_char) {
@@ -209,54 +209,71 @@ function get_search_words($words = array(), $do_escape = FALSE)
 // 'Search' main function
 function do_search($word, $type = 'AND', $non_format = FALSE, $base = '')
 {
-       global $script, $whatsnew, $search_non_list;
+       global $script, $whatsnew, $non_list, $search_non_list;
        global $_msg_andresult, $_msg_orresult, $_msg_notfoundresult;
-       global $search_auth;
+       global $search_auth, $show_passage;
 
        $retval = array();
 
        $b_type = ($type == 'AND'); // AND:TRUE OR:FALSE
        $keys = get_search_words(preg_split('/\s+/', $word, -1, PREG_SPLIT_NO_EMPTY));
+       foreach ($keys as $key=>$value)
+               $keys[$key] = '/' . $value . '/S';
 
-       $_pages = get_existpages();
+       $pages = get_existpages();
+
+       // Avoid
        if ($base != '') {
-               $_pages = preg_grep('/^' . $base . '/', $_pages);
+               $pages = preg_grep('/^' . preg_quote($base, '/') . '/S', $pages);
+       }
+       if (! $search_non_list) {
+               $pages = array_diff($pages, preg_grep('/' . $non_list . '/S', $pages));
        }
-       $pages = array();
+       $pages = array_flip($pages);
+       unset($pages[$whatsnew]);
 
-       foreach ($_pages as $page) {
-               if ($page == $whatsnew || (! $search_non_list && check_non_list($page)))
-                       continue;
+       $count = count($pages);
+       foreach (array_keys($pages) as $page) {
+               $b_match = FALSE;
 
-               // ¸¡º÷Âоݥڡ¼¥¸¤ÎÀ©¸Â¤ò¤«¤±¤ë¤«¤É¤¦¤« (¥Ú¡¼¥¸Ì¾¤ÏÀ©¸Â³°)
+               // Search for page name
+               if (! $non_format) {
+                       foreach ($keys as $key) {
+                               $b_match = preg_match($key, $page);
+                               if ($b_type xor $b_match) break; // OR
+                       }
+                       if ($b_match) continue;
+               }
+
+               // Search auth for page contents
                if ($search_auth && ! check_readable($page, false, false)) {
-                       $source = ''; // Empty
-               } else {
-                       $source = get_source($page, TRUE, TRUE);
+                       unset($pages[$page]);
+                       --$count;
                }
-               if (! $non_format)
-                       $source = $page . $source; // ¥Ú¡¼¥¸Ì¾¤â¸¡º÷ÂоݤË
 
-               $b_match = FALSE;
+               // Search for page contents
                foreach ($keys as $key) {
-                       $b_match = preg_match('/' . $key . '/', $source);
-                       if ($b_match xor $b_type) break;
+                       $b_match = preg_match($key, get_source($page, TRUE, TRUE));
+                       if ($b_type xor $b_match) break; // OR
                }
-               if ($b_match) $pages[$page] = get_filetime($page);
+               if ($b_match) continue;
+
+               unset($pages[$page]); // Miss
        }
        if ($non_format) return array_keys($pages);
 
        $r_word = rawurlencode($word);
-       $s_word = htmlspecialchars($word);
+       $s_word = htmlsc($word);
        if (empty($pages))
                return str_replace('$1', $s_word, $_msg_notfoundresult);
 
-       ksort($pages);
+       ksort($pages, SORT_STRING);
+
        $retval = '<ul>' . "\n";
-       foreach ($pages as $page=>$time) {
+       foreach (array_keys($pages) as $page) {
                $r_page  = rawurlencode($page);
-               $s_page  = htmlspecialchars($page);
-               $passage = get_passage($time);
+               $s_page  = htmlsc($page);
+               $passage = $show_passage ? ' ' . get_passage(get_filetime($page)) : '';
                $retval .= ' <li><a href="' . $script . '?cmd=read&amp;page=' .
                        $r_page . '&amp;word=' . $r_word . '">' . $s_page .
                        '</a>' . $passage . '</li>' . "\n";
@@ -264,7 +281,7 @@ function do_search($word, $type = 'AND', $non_format = FALSE, $base = '')
        $retval .= '</ul>' . "\n";
 
        $retval .= str_replace('$1', $s_word, str_replace('$2', count($pages),
-               str_replace('$3', count($_pages), $b_type ? $_msg_andresult : $_msg_orresult)));
+               str_replace('$3', $count, $b_type ? $_msg_andresult : $_msg_orresult)));
 
        return $retval;
 }
@@ -276,22 +293,33 @@ function arg_check($str)
        return isset($vars['cmd']) && (strpos($vars['cmd'], $str) === 0);
 }
 
+function _pagename_urlencode_callback($matches)
+{
+       return rawurlencode($matches[0]);
+}
+
+function pagename_urlencode($page)
+{
+       return preg_replace_callback('|[^/:]+|', '_pagename_urlencode_callback', $page);
+}
+
 // Encode page-name
-function encode($key)
+function encode($str)
 {
-       return ($key == '') ? '' : strtoupper(bin2hex($key));
+       $str = strval($str);
+       return ($str == '') ? '' : strtoupper(bin2hex($str));
        // Equal to strtoupper(join('', unpack('H*0', $key)));
        // But PHP 4.3.10 says 'Warning: unpack(): Type H: outside of string in ...'
 }
 
 // Decode page name
-function decode($key)
+function decode($str)
 {
-       return hex2bin($key);
+       return pkwk_hex2bin($str);
 }
 
 // Inversion of bin2hex()
-function hex2bin($hex_string)
+function pkwk_hex2bin($hex_string)
 {
        // preg_match : Avoid warning : pack(): Type H: illegal hex digit ...
        // (string)   : Always treat as string (not int etc). See BugTrack2/31
@@ -317,7 +345,7 @@ function page_list($pages, $cmd = 'read', $withfilename = FALSE)
        global $_msg_symbol, $_msg_other;
        global $pagereading_enable;
 
-       // ¥½¡¼¥È¥­¡¼¤ò·èÄꤹ¤ë¡£ ' ' < '[a-zA-Z]' < 'zz'¤È¤¤¤¦Á°Äó¡£
+       // ソートキーを決定する。 ' ' < '[a-zA-Z]' < 'zz'という前提。
        $symbol = ' ';
        $other = 'zz';
 
@@ -338,15 +366,15 @@ function page_list($pages, $cmd = 'read', $withfilename = FALSE)
        }
 
        foreach($pages as $file=>$page) {
-               $r_page  = rawurlencode($page);
-               $s_page  = htmlspecialchars($page, ENT_QUOTES);
+               $r_page  = pagename_urlencode($page);
+               $s_page  = htmlsc($page, ENT_QUOTES);
                $passage = get_pg_passage($page);
 
                $str = '   <li><a href="' . $href . $r_page . '">' .
                        $s_page . '</a>' . $passage;
 
                if ($withfilename) {
-                       $s_file = htmlspecialchars($file);
+                       $s_file = htmlsc($file);
                        $str .= "\n" . '    <ul><li>' . $s_file . '</li></ul>' .
                                "\n" . '   ';
                }
@@ -355,22 +383,22 @@ function page_list($pages, $cmd = 'read', $withfilename = FALSE)
                // WARNING: Japanese code hard-wired
                if($pagereading_enable) {
                        if(mb_ereg('^([A-Za-z])', mb_convert_kana($page, 'a'), $matches)) {
+                               $head = strtoupper($matches[1]);
+                       } elseif (isset($readings[$page]) && mb_ereg('^([ァ-ヶ])', $readings[$page], $matches)) { // here
                                $head = $matches[1];
-                       } elseif (isset($readings[$page]) && mb_ereg('^([¥¡-¥ö])', $readings[$page], $matches)) { // here
-                               $head = $matches[1];
-                       } elseif (mb_ereg('^[ -~]|[^¤¡-¤ó°¡-ô¦]', $page)) { // and here
+                       } elseif (mb_ereg('^[ -~]|[^ぁ-ん亜-熙]', $page)) { // and here
                                $head = $symbol;
                        } else {
                                $head = $other;
                        }
                } else {
-                       $head = (preg_match('/^([A-Za-z])/', $page, $matches)) ? $matches[1] :
-                               (preg_match('/^([ -~])/', $page, $matches) ? $symbol : $other);
+                       $head = (preg_match('/^([A-Za-z])/', $page, $matches)) ? strtoupper($matches[1]) :
+                               (preg_match('/^([ -~])/', $page) ? $symbol : $other);
                }
 
                $list[$head][$page] = $str;
        }
-       ksort($list);
+       uksort($pages, 'strnatcmp');
 
        $cnt = 0;
        $arr_index = array();
@@ -391,7 +419,7 @@ function page_list($pages, $cmd = 'read', $withfilename = FALSE)
                                '"><strong>' . $head . '</strong></a>' . "\n" .
                                '  <ul>' . "\n";
                }
-               ksort($pages);
+               ksort($pages, SORT_STRING);
                $retval .= join("\n", $pages);
                if ($list_index)
                        $retval .= "\n  </ul>\n </li>\n";
@@ -414,7 +442,7 @@ function catrule()
        global $rule_page;
 
        if (! is_page($rule_page)) {
-               return '<p>Sorry, page \'' . htmlspecialchars($rule_page) .
+               return '<p>Sorry, page \'' . htmlsc($rule_page) .
                        '\' unavailable.</p>';
        } else {
                return convert_html(get_source($rule_page));
@@ -434,13 +462,17 @@ EOD;
        if(defined('SKIN_FILE') && file_exists(SKIN_FILE) && is_readable(SKIN_FILE)) {
                catbody($title, $page, $body);
        } else {
-               header('Content-Type: text/html; charset=euc-jp');
+               $charset = 'utf-8';
+               if(defined('CONTENT_CHARSET')) {
+                       $charset = CONTENT_CHARSET;
+               }
+               header("Content-Type: text/html; charset=$charset");
                print <<<EOD
-<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
+<!DOCTYPE html>
 <html>
  <head>
+  <meta http-equiv="content-type" content="text/html; charset=$charset">
   <title>$title</title>
-  <meta http-equiv="content-type" content="text/html; charset=euc-jp">
  </head>
  <body>
  $body
@@ -458,6 +490,14 @@ function getmicrotime()
        return ((float)$sec + (float)$usec);
 }
 
+// Elapsed time by second
+//define('MUTIME', getmicrotime());
+function elapsedtime()
+{
+       $at_the_microtime = MUTIME;
+       return sprintf('%01.03f', getmicrotime() - $at_the_microtime);
+}
+
 // Get the date
 function get_date($format, $timestamp = NULL)
 {
@@ -511,7 +551,7 @@ function get_autolink_pattern(& $pages)
 {
        global $WikiName, $autolink, $nowikiname;
 
-       $config = &new Config('AutoLink');
+       $config = new Config('AutoLink');
        $config->read();
        $ignorepages      = $config->get('IgnoreList');
        $forceignorepages = $config->get('ForceIgnoreList');
@@ -584,13 +624,13 @@ function get_script_uri($init_uri = '')
                $script .= SERVER_NAME; // host
                $script .= (SERVER_PORT == 80 ? '' : ':' . SERVER_PORT);  // port
 
-               // SCRIPT_NAME ¤¬'/'¤Ç»Ï¤Þ¤Ã¤Æ¤¤¤Ê¤¤¾ì¹ç(cgi¤Ê¤É) REQUEST_URI¤ò»È¤Ã¤Æ¤ß¤ë
+               // SCRIPT_NAME が'/'で始まっていない場合(cgiなど) REQUEST_URIを使ってみる
                $path    = SCRIPT_NAME;
                if ($path{0} != '/') {
                        if (! isset($_SERVER['REQUEST_URI']) || $_SERVER['REQUEST_URI']{0} != '/')
                                die_message($msg);
 
-                       // REQUEST_URI¤ò¥Ñ¡¼¥¹¤·¡¢pathÉôʬ¤À¤±¤ò¼è¤ê½Ð¤¹
+                       // REQUEST_URIをパースし、path部分だけを取り出す
                        $parse_url = parse_url($script . $_SERVER['REQUEST_URI']);
                        if (! isset($parse_url['path']) || $parse_url['path']{0} != '/')
                                die_message($msg);
@@ -614,7 +654,7 @@ function get_script_uri($init_uri = '')
        if (isset($script_directory_index)) {
                if (! file_exists($script_directory_index))
                        die_message('Directory index file not found: ' .
-                               htmlspecialchars($script_directory_index));
+                               htmlsc($script_directory_index));
                $matches = array();
                if (preg_match('#^(.+/)' . preg_quote($script_directory_index, '#') . '$#',
                        $script, $matches)) $script = $matches[1];
@@ -629,8 +669,8 @@ function get_script_uri($init_uri = '')
 // [PHP-users 12736] null byte attack
 // http://ns1.php.gr.jp/pipermail/php-users/2003-January/012742.html
 //
-// 2003-05-16: magic quotes gpc¤ÎÉü¸µ½èÍý¤òÅý¹ç
-// 2003-05-21: Ï¢ÁÛÇÛÎó¤Î¥­¡¼¤Ïbinary safe
+// 2003-05-16: magic quotes gpcの復元処理を統合
+// 2003-05-21: 連想配列のキーはbinary safe
 //
 function input_filter($param)
 {
@@ -677,13 +717,45 @@ function csv_implode($glue, $pieces)
        $_glue = ($glue != '') ? '\\' . $glue{0} : '';
        $arr = array();
        foreach ($pieces as $str) {
-               if (ereg('[' . $_glue . '"' . "\n\r" . ']', $str))
+               if (preg_match('/[' . '"' . "\n\r" . $_glue . ']/', $str))
                        $str = '"' . str_replace('"', '""', $str) . '"';
                $arr[] = $str;
        }
        return join($glue, $arr);
 }
 
+// Sugar with default settings
+function htmlsc($string = '', $flags = ENT_COMPAT, $charset = CONTENT_CHARSET)
+{
+       return htmlspecialchars($string, $flags, $charset);     // htmlsc()
+}
+
+// Redirect from an old page to new page
+function manage_page_redirect() {
+       global $page_redirect_rules, $vars;
+       if (isset($vars['page'])) {
+               $page = $vars['page'];
+               foreach ($page_redirect_rules as $rule => $replace) {
+                       if (preg_match($rule, $page)) {
+                               if (is_string($replace)) {
+                                       $new_page = preg_replace($rule, $replace, $page);
+                               } elseif (is_object($replace) && is_callable($replace)) {
+                                       $new_page = preg_replace_callback($rule, $replace, $page);
+                               } else {
+                                       die_message('Invalid redirect rule: ' . $rule . '=>' . $replace);
+                               }
+                               if ($page !== $new_page) {
+                                       header('Location: ' . get_script_uri() . '?' .
+                                               pagename_urlencode($new_page));
+                                       return TRUE;
+                               }
+                       }
+               }
+       }
+       return FALSE;
+}
+
+
 //// Compat ////
 
 // is_a --  Returns TRUE if the object is of this class or has this class as one of its parents
@@ -739,11 +811,5 @@ if (! function_exists('sha1')) {
                {
                        return bin2hex(mhash(MHASH_SHA1, $str));
                }
-       } else {
-               function sha1($str, $raw_output = FALSE)
-               {
-                       die('Function sha1() not found and extension \'mhash\' not exists');
-               }
        }
 }
-?>