OSDN Git Service

BugTrack/84 Limit page name length: 115 bytes(soft); 125 bytes(hard)
[pukiwiki/pukiwiki.git] / lib / func.php
index 69a6ef2..ec1e3da 100644 (file)
@@ -2,7 +2,7 @@
 // PukiWiki - Yet another WikiWikiWeb clone.
 // func.php
 // Copyright
-//   2002-2017 PukiWiki Development Team
+//   2002-2022 PukiWiki Development Team
 //   2001-2002 Originally written by yu-ji
 // License: GPL v2 or (at your option) any later version
 //
@@ -16,6 +16,11 @@ define('PKWK_URI_ROOT', 1);
 /** Absolute URI. */
 define('PKWK_URI_ABSOLUTE', 2);
 
+/** New page name - its length is need to be within the soft limit. */
+define('PKWK_PAGENAME_BYTES_SOFT_LIMIT', 115);
+/** Page name - its length is need to be within the hard limit. */
+define('PKWK_PAGENAME_BYTES_HARD_LIMIT', 125);
+
 function pkwk_log($message)
 {
        $log_filepath = 'log/error.log.php';
@@ -144,6 +149,32 @@ function is_page($page, $clearcache = FALSE)
        return file_exists(get_filename($page));
 }
 
+function is_pagename_bytes_within_soft_limit($page)
+{
+       return strlen($page) <= PKWK_PAGENAME_BYTES_SOFT_LIMIT;
+}
+
+function is_pagename_bytes_within_hard_limit($page)
+{
+       return strlen($page) <= PKWK_PAGENAME_BYTES_SOFT_LIMIT;
+}
+
+function page_exists_in_history($page)
+{
+       if (is_page($page)) {
+               return true;
+       }
+       $diff_file = DIFF_DIR . encode($page) . '.txt';
+       if (file_exists($diff_file)) {
+               return true;
+       }
+       $backup_file = BACKUP_DIR . encode($page) . BACKUP_EXT;
+       if (file_exists($backup_file)) {
+               return true;
+       }
+       return false;
+}
+
 function is_editable($page)
 {
        global $cantedit;
@@ -230,6 +261,13 @@ function auto_template($page)
        return $body;
 }
 
+function _mb_convert_kana__enable($str, $option) {
+       return mb_convert_kana($str, $option, SOURCE_ENCODING);
+}
+function _mb_convert_kana__none($str, $option) {
+       return $str;
+}
+
 // Expand all search-words to regexes and push them into an array
 function get_search_words($words = array(), $do_escape = FALSE)
 {
@@ -238,11 +276,9 @@ function get_search_words($words = array(), $do_escape = FALSE)
        if (! isset($init)) {
                // function: mb_convert_kana() is for Japanese code only
                if (LANG == 'ja' && function_exists('mb_convert_kana')) {
-                       $mb_convert_kana = create_function('$str, $option',
-                               'return mb_convert_kana($str, $option, SOURCE_ENCODING);');
+                       $mb_convert_kana = '_mb_convert_kana__enable';
                } else {
-                       $mb_convert_kana = create_function('$str, $option',
-                               'return $str;');
+                       $mb_convert_kana = '_mb_convert_kana__none';
                }
                if (SOURCE_ENCODING == 'EUC-JP') {
                        // Perl memo - Correct pattern-matching with EUC-JP
@@ -298,6 +334,74 @@ function get_search_words($words = array(), $do_escape = FALSE)
        return $regex; // For all words
 }
 
+function get_passage_date_html_span($date_atom)
+{
+       return '<span class="page_passage" data-mtime="' . $date_atom . '"></span>';
+}
+
+function get_passage_mtime_html_span($mtime)
+{
+       $date_atom = get_date_atom($mtime);
+       return get_passage_date_html_span($date_atom);
+}
+
+/**
+ * Get passage span html
+ *
+ * @param $page
+ */
+function get_passage_html_span($page)
+{
+       $date_atom = get_page_date_atom($page);
+       return get_passage_date_html_span($date_atom);
+}
+
+function get_link_passage_class() {
+       return 'link_page_passage';
+}
+
+/**
+ * Get page link general attributes
+ * @param $page
+ * @return array('data_mtime' => page mtime or null, 'class' => additinal classes)
+ */
+function get_page_link_a_attrs($page)
+{
+       global $show_passage;
+       if ($show_passage) {
+               $pagemtime = get_page_date_atom($page);
+               return array(
+                       'data_mtime' => $pagemtime,
+                       'class' => get_link_passage_class(),
+               );
+       }
+       return array(
+               'data_mtime' => '',
+               'class' => ''
+       );
+}
+
+/**
+ * Get page link general attributes from filetime
+ * @param $filetime
+ * @return array('data_mtime' => page mtime or null, 'class' => additinal classes)
+ */
+function get_filetime_a_attrs($filetime)
+{
+       global $show_passage;
+       if ($show_passage) {
+               $pagemtime = get_date_atom($filetime + LOCALZONE);
+               return array(
+                       'data_mtime' => $pagemtime,
+                       'class' => get_link_passage_class(),
+               );
+       }
+       return array(
+               'data_mtime' => '',
+               'class' => ''
+       );
+}
+
 // 'Search' main function
 function do_search($word, $type = 'AND', $non_format = FALSE, $base = '')
 {
@@ -341,11 +445,13 @@ function do_search($word, $type = 'AND', $non_format = FALSE, $base = '')
                if ($search_auth && ! check_readable($page, false, false)) {
                        unset($pages[$page]);
                        --$count;
+                       continue;
                }
 
                // Search for page contents
                foreach ($keys as $key) {
-                       $b_match = preg_match($key, get_source($page, TRUE, TRUE));
+                       $body = get_source($page, TRUE, TRUE, TRUE);
+                       $b_match = preg_match($key, remove_author_header($body));
                        if ($b_type xor $b_match) break; // OR
                }
                if ($b_match) continue;
@@ -357,7 +463,7 @@ function do_search($word, $type = 'AND', $non_format = FALSE, $base = '')
        $r_word = rawurlencode($word);
        $s_word = htmlsc($word);
        if (empty($pages))
-               return str_replace('$1', $s_word, $_msg_notfoundresult);
+               return str_replace('$1', $s_word, str_replace('$3', $count, $_msg_notfoundresult));
 
        ksort($pages, SORT_STRING);
 
@@ -365,7 +471,7 @@ function do_search($word, $type = 'AND', $non_format = FALSE, $base = '')
        foreach (array_keys($pages) as $page) {
                $r_page  = rawurlencode($page);
                $s_page  = htmlsc($page);
-               $passage = $show_passage ? ' ' . get_passage(get_filetime($page)) : '';
+               $passage = $show_passage ? ' ' . get_passage_html_span($page) : '';
                $retval .= ' <li><a href="' . get_base_uri() . '?cmd=read&amp;page=' .
                        $r_page . '&amp;word=' . $r_word . '">' . $s_page .
                        '</a>' . $passage . '</li>' . "\n";
@@ -387,7 +493,7 @@ function arg_check($str)
 
 function _pagename_urlencode_callback($matches)
 {
-       return rawurlencode($matches[0]);
+       return urlencode($matches[0]);
 }
 
 function pagename_urlencode($page)
@@ -449,24 +555,18 @@ function page_list($pages, $cmd = 'read', $withfilename = FALSE)
                mb_regex_encoding(SOURCE_ENCODING);
                $readings = get_readings($pages);
        }
-
        $list = $matches = array();
-
-       // Shrink URI for read
-       if ($cmd == 'read') {
-               $href = $script . '?';
-       } else {
-               $href = $script . '?cmd=' . $cmd . '&amp;page=';
-       }
-
+       uasort($pages, 'strnatcmp');
        foreach($pages as $file=>$page) {
-               $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;
-
+               // Shrink URI for read
+               if ($cmd == 'read') {
+                       $href = get_page_uri($page);
+               } else {
+                       $href = $script . '?cmd=' . $cmd . '&amp;page=' . rawurlencode($page);
+               }
+               $str = '   <li><a href="' . $href . '">' .
+                       $s_page . '</a> ' . get_pg_passage($page);
                if ($withfilename) {
                        $s_file = htmlsc($file);
                        $str .= "\n" . '    <ul><li>' . $s_file . '</li></ul>' .
@@ -489,15 +589,14 @@ function page_list($pages, $cmd = 'read', $withfilename = FALSE)
                        $head = (preg_match('/^([A-Za-z])/', $page, $matches)) ? strtoupper($matches[1]) :
                                (preg_match('/^([ -~])/', $page) ? $symbol : $other);
                }
-
                $list[$head][$page] = $str;
        }
-       uksort($pages, 'strnatcmp');
+       uksort($list, 'strnatcmp');
 
        $cnt = 0;
        $arr_index = array();
        $retval .= '<ul>' . "\n";
-       foreach ($list as $head=>$pages) {
+       foreach ($list as $head=>$sub_pages) {
                if ($head === $symbol) {
                        $head = $_msg_symbol;
                } else if ($head === $other) {
@@ -513,8 +612,7 @@ function page_list($pages, $cmd = 'read', $withfilename = FALSE)
                                '"><strong>' . $head . '</strong></a>' . "\n" .
                                '  <ul>' . "\n";
                }
-               ksort($pages, SORT_STRING);
-               $retval .= join("\n", $pages);
+               $retval .= join("\n", $sub_pages);
                if ($list_index)
                        $retval .= "\n  </ul>\n </li>\n";
        }
@@ -577,6 +675,21 @@ EOD;
        exit;
 }
 
+function die_invalid_pagename() {
+       $title = 'Error';
+       $page = 'Error: Invlid page name';
+       $body = <<<EOD
+<h3>Error</h3>
+<strong>Error message: Invalid page name</strong>
+EOD;
+
+       pkwk_common_headers();
+       header('HTTP/1.0 400 Bad request');
+       catbody($title, $page, $body);
+       exit;
+}
+
+
 // Have the time (as microtime)
 function getmicrotime()
 {
@@ -617,6 +730,18 @@ function format_date($val, $paren = FALSE)
        return $paren ? '(' . $date . ')' : $date;
 }
 
+/**
+ * Format date in DATE_ATOM format.
+ */
+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);
+}
+
 // Get short string of the passage, 'N seconds/minutes/hours/days/years ago'
 function get_passage($time, $paren = TRUE)
 {
@@ -641,9 +766,9 @@ function drop_submit($str)
 }
 
 // Generate AutoLink patterns (thx to hirofummy)
-function get_autolink_pattern(& $pages)
+function get_autolink_pattern($pages, $min_length)
 {
-       global $WikiName, $autolink, $nowikiname;
+       global $WikiName, $nowikiname;
 
        $config = new Config('AutoLink');
        $config->read();
@@ -652,13 +777,14 @@ function get_autolink_pattern(& $pages)
        unset($config);
        $auto_pages = array_merge($ignorepages, $forceignorepages);
 
-       foreach ($pages as $page)
+       foreach ($pages as $page) {
                if (preg_match('/^' . $WikiName . '$/', $page) ?
-                   $nowikiname : strlen($page) >= $autolink)
+                   $nowikiname : strlen($page) >= $min_length) {
                        $auto_pages[] = $page;
-
+               }
+       }
        if (empty($auto_pages)) {
-               $result = $result_a = $nowikiname ? '(?!)' : $WikiName;
+               $result = $result_a = '(?!)';
        } else {
                $auto_pages = array_unique($auto_pages);
                sort($auto_pages, SORT_STRING);
@@ -672,7 +798,7 @@ function get_autolink_pattern(& $pages)
        return array($result, $result_a, $forceignorepages);
 }
 
-function get_autolink_pattern_sub($pages, $start, $end, $pos)
+function get_autolink_pattern_sub($pages, $start, $end, $pos)
 {
        if ($end == 0) return '(?!)';
 
@@ -701,6 +827,52 @@ function get_autolink_pattern_sub(& $pages, $start, $end, $pos)
        return $result;
 }
 
+// Get AutoAlias value
+function get_autoalias_right_link($alias_name)
+{
+       $pairs = get_autoaliases();
+       // A string: Seek the pair
+       if (isset($pairs[$alias_name])) {
+               return $pairs[$alias_name];
+       }
+       return '';
+}
+
+// Load setting pairs from AutoAliasName
+function get_autoaliases()
+{
+       global $aliaspage, $autoalias_max_words;
+       static $pairs;
+       $preg_u = get_preg_u();
+
+       if (! isset($pairs)) {
+               $pairs = array();
+               $pattern = <<<EOD
+\[\[                # open bracket
+((?:(?!\]\]).)+)>   # (1) alias name
+((?:(?!\]\]).)+)    # (2) alias link
+\]\]                # close bracket
+EOD;
+               $postdata = join('', get_source($aliaspage));
+               $matches  = array();
+               $count = 0;
+               $max   = max($autoalias_max_words, 0);
+               if (preg_match_all('/' . $pattern . '/x' . get_preg_u(), $postdata,
+                       $matches, PREG_SET_ORDER)) {
+                       foreach($matches as $key => $value) {
+                               if ($count ==  $max) break;
+                               $name = trim($value[1]);
+                               if (! isset($pairs[$name])) {
+                                       ++$count;
+                                        $pairs[$name] = trim($value[2]);
+                               }
+                               unset($matches[$key]);
+                       }
+               }
+       }
+       return $pairs;
+}
+
 /**
  * Get propery URI of this script
  *
@@ -709,7 +881,9 @@ function get_autolink_pattern_sub(& $pages, $start, $end, $pos)
  */
 function get_base_uri($uri_type = PKWK_URI_RELATIVE)
 {
-       switch ($uri_type) {
+       $base_type = pkwk_base_uri_type_stack_peek();
+       $type = max($base_type, $uri_type);
+       switch ($type) {
        case PKWK_URI_RELATIVE:
                return pkwk_script_uri_base(PKWK_URI_RELATIVE);
        case PKWK_URI_ROOT:
@@ -730,7 +904,11 @@ function get_base_uri($uri_type = PKWK_URI_RELATIVE)
  */
 function get_page_uri($page, $uri_type = PKWK_URI_RELATIVE)
 {
-       return get_base_uri($uri_type) . '?' . pagename_urlencode($page);
+       global $page_uri_handler, $defaultpage;
+       if ($page === $defaultpage) {
+               return get_base_uri($uri_type);
+       }
+       return get_base_uri($uri_type) . $page_uri_handler->get_page_uri_virtual_query($page);
 }
 
 // Get absolute-URI of this script
@@ -747,7 +925,7 @@ function get_script_uri()
  * @param $initialize true if you initialize URI
  * @param $uri_set URI set manually
  */
-function pkwk_script_uri_base($uri_type, $initialize, $uri_set)
+function pkwk_script_uri_base($uri_type, $initialize = null, $uri_set = null)
 {
        global $script_directory_index;
        static $initialized = false;
@@ -797,6 +975,80 @@ function pkwk_script_uri_base($uri_type, $initialize, $uri_set)
 }
 
 /**
+ * Create uri_type context
+ *
+ * @param $uri_type relative or absolute option
+ *        PKWK_URI_RELATIVE, PKWK_URI_ROOT or PKWK_URI_ABSOLUTE
+ */
+function pkwk_base_uri_type_stack_push($uri_type)
+{
+       _pkwk_base_uri_type_stack(false, true, $uri_type);
+}
+
+/**
+ * Stop current active uri_type context
+ */
+function pkwk_base_uri_type_stack_pop()
+{
+       _pkwk_base_uri_type_stack(false, false);
+}
+
+/**
+ * Get current active uri_type status
+ */
+function pkwk_base_uri_type_stack_peek()
+{
+       $type = _pkwk_base_uri_type_stack(true, false);
+       if (is_null($type)) {
+               return PKWK_URI_RELATIVE;
+       } elseif ($type === PKWK_URI_ABSOLUTE) {
+               return PKWK_URI_ABSOLUTE;
+       } elseif ($type === PKWK_URI_ROOT) {
+               return PKWK_URI_ROOT;
+       } else {
+               return PKWK_URI_RELATIVE;
+       }
+}
+
+/**
+ * uri_type context internal function
+ *
+ * @param $peek is peek action or not
+ * @param $push push(true) or pop(false) on not peeking
+ * @param $uri_type uri_type on push and non-peeking
+ * @return $uri_type uri_type for peeking
+ */
+function _pkwk_base_uri_type_stack($peek, $push, $uri_type = null)
+{
+       static $uri_types = array();
+       if ($peek) {
+               // Peek: get latest value
+               if (count($uri_types) === 0) {
+                       return null;
+               } else {
+                       return $uri_types[0];
+               }
+       } else {
+               if ($push) {
+                       // Push $uri_type
+                       if (count($uri_types) === 0) {
+                               array_unshift($uri_types, $uri_type);
+                       } else {
+                               $prev_type = $uri_types[0];
+                               if ($uri_type >= $prev_type) {
+                                       array_unshift($uri_types, $uri_type);
+                               } else {
+                                       array_unshift($uri_types, $prev_type);
+                               }
+                       }
+               } else {
+                       // Pop $uri_type
+                       return array_shift($uri_types);
+               }
+       }
+}
+
+/**
  * Guess Script Absolute URI.
  *
  * SERVER_PORT: $_SERVER['SERVER_PORT'] converted in init.php
@@ -805,8 +1057,7 @@ function pkwk_script_uri_base($uri_type, $initialize, $uri_set)
 function guess_script_absolute_uri()
 {
        $port = SERVER_PORT;
-       $is_ssl = (SERVER_PORT == 443) ||
-               (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ||
+       $is_ssl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ||
                (isset($_SERVER['REQUEST_SCHEME']) && $_SERVER['REQUEST_SCHEME'] === 'https');
        if ($is_ssl) {
                $host = 'https://' . SERVER_NAME .
@@ -831,9 +1082,14 @@ function guess_script_absolute_uri()
 function input_filter($param)
 {
        static $magic_quotes_gpc = NULL;
-       if ($magic_quotes_gpc === NULL)
-           $magic_quotes_gpc = get_magic_quotes_gpc();
-
+       if ($magic_quotes_gpc === NULL) {
+               if (function_exists('get_magic_quotes_gpc')) {
+                       // No 'get_magic_quotes_gpc' function in PHP8
+                       $magic_quotes_gpc = get_magic_quotes_gpc();
+               } else {
+                       $magic_quotes_gpc = 0;
+               }
+       }
        if (is_array($param)) {
                return array_map('input_filter', $param);
        } else {
@@ -860,7 +1116,7 @@ function csv_explode($separator, $string)
 
        foreach ($matches[1] as $str) {
                $len = strlen($str);
-               if ($len > 1 && $str{0} == '"' && $str{$len - 1} == '"')
+               if ($len > 1 && $str[0] == '"' && $str[$len - 1] == '"')
                        $str = str_replace('""', '"', substr($str, 1, -1));
                $retval[] = $str;
        }
@@ -870,7 +1126,7 @@ function csv_explode($separator, $string)
 // Implode an array with CSV data format (escape double quotes)
 function csv_implode($glue, $pieces)
 {
-       $_glue = ($glue != '') ? '\\' . $glue{0} : '';
+       $_glue = ($glue != '') ? '\\' . $glue[0] : '';
        $arr = array();
        foreach ($pieces as $str) {
                if (preg_match('/[' . '"' . "\n\r" . $_glue . ']/', $str))
@@ -887,6 +1143,21 @@ function htmlsc($string = '', $flags = ENT_COMPAT, $charset = CONTENT_CHARSET)
 }
 
 /**
+ * Get JSON string with htmlspecialchars().
+ */
+function htmlsc_json($obj)
+{
+       // json_encode: PHP 5.2+
+       // JSON_UNESCAPED_UNICODE: PHP 5.4+
+       // JSON_UNESCAPED_SLASHES: PHP 5.4+
+       if (defined('JSON_UNESCAPED_UNICODE')) {
+               return htmlsc(json_encode($obj,
+                       JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
+       }
+       return '';
+}
+
+/**
  * Get redirect page name on Page Redirect Rules
  *
  * This function returns exactly false if it doesn't need redirection.
@@ -936,6 +1207,50 @@ function manage_page_redirect() {
        return FALSE;
 }
 
+/**
+ * Return 'u' (PCRE_UTF8) if PHP7+ and UTF-8.
+ */
+function get_preg_u() {
+       static $utf8u; // 'u'(PCRE_UTF8) or ''
+       if (! isset($utf8u)) {
+               if (version_compare('7.0.0', PHP_VERSION, '<=')
+                       && defined('PKWK_UTF8_ENABLE')) {
+                       $utf8u = 'u';
+               } else {
+                       $utf8u = '';
+               }
+       }
+       return $utf8u;
+}
+
+// Default Page name - URI mapping handler
+class PukiWikiStandardPageURIHandler {
+       function filter_raw_query_string($query_string) {
+               return $query_string;
+       }
+
+       function get_page_uri_virtual_query($page) {
+               return '?' . pagename_urlencode($page);
+       }
+
+       function get_page_from_query_string($query_string) {
+               $param1st = preg_replace("#^([^&]*)&.*$#", "$1", $query_string);
+               if ($param1st == '') {
+                       return null; // default page
+               }
+               if (strpos($param1st, '=') !== FALSE) {
+                       // Found '/?key=value' (Top page with additional query params)
+                       return null; // default page
+               }
+               $page = urldecode($param1st);
+               $page2 = input_filter($page);
+               if ($page !== $page2) {
+                       return FALSE; // Error page
+               }
+               return $page2;
+       }
+}
+
 //// Compat ////
 
 // is_a --  Returns TRUE if the object is of this class or has this class as one of its parents