3 * Copyright 1999-2008 $ThePhpWikiProgrammingTeam
4 * Copyright 2008-2009 Marc-Etienne Vargenau, Alcatel-Lucent
6 * This file is part of PhpWiki.
8 * PhpWiki is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * PhpWiki is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License along
19 * with PhpWiki; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24 Standard functions for Wiki functionality
25 WikiURL ($pagename, $args, $get_abs_url)
27 IconForLink ($protocol_or_url)
28 PossiblyGlueIconToText($proto_or_url, $text)
30 LinkURL ($url, $linktext)
31 LinkImage ($url, $alt)
32 ImgObject ($img, $url)
34 SplitQueryArgs ($query_args)
35 LinkPhpwikiURL ($url, $text, $basepage)
36 ConvertOldMarkup ($content, $markup_type = "block")
37 MangleXmlIdentifier($str)
39 class Stack { push($item), pop(), cnt(), top() }
40 class Alert { show() }
41 class WikiPageName {getParent(),isValid(),getWarnings() }
43 expand_tabs($str, $tab_width = 8)
45 NoSuchRevision ($request, $page, $version)
46 TimezoneOffset ($time, $no_colon)
47 Iso8601DateTime ($time)
48 Rfc2822DateTime ($time)
49 ParseRfc1123DateTime ($timestr)
51 ByteFormatter ($bytes = 0, $longformat = false)
54 __vsprintf ($fmt, $args)
56 file_mtime ($filename)
57 sort_file_mtime ($a, $b)
58 class fileSet {fileSet($directory, $filepattern = false),
59 getFiles($exclude='', $sortby='', $limit='') }
60 class ListRegexExpand { listMatchCallback($item, $key),
61 expandRegex ($index, &$pages) }
64 glob_match ($glob, $against, $case_sensitive = true)
65 explodeList ($input, $allnames, $glob_style = true, $case_sensitive = true)
66 explodePageList ($input, $perm = false)
68 can ($object, $method)
69 function_usable ($function_name)
71 better_srand ($seed = '')
74 subPageSlice ($pagename, $pos)
75 isActionPage ($filename)
79 obj2hash ($obj, $exclude = false, $fields = false)
82 url_get_contents ($uri)
84 firstNWordsOfContent ($n, $content)
85 extractSection ($section, $content, $page, $quiet = false, $sectionhead = false)
88 charset_convert($from, $to, $data)
89 string_starts_with($string, $prefix)
90 string_ends_with($string, $suffix)
91 array_remove($arr,$value)
92 longer_timeout($secs=30)
95 binary_search($needle, $haystack)
97 javascript_quote_string($s)
100 parse_attributes($line)
104 function: linkExistingWikiWord($wikiword, $linktext, $version)
105 moved to: lib/WikiTheme.php
107 if (defined('_PHPWIKI_STDLIB_LOADED')) return;
108 else define('_PHPWIKI_STDLIB_LOADED', true);
110 if (!defined('MAX_PAGENAME_LENGTH')) {
111 define('MAX_PAGENAME_LENGTH', 100);
115 * Convert string to a valid XML identifier.
117 * XML 1.0 identifiers are of the form: [A-Za-z][A-Za-z0-9:_.-]*
119 * We would like to have, e.g. named anchors within wiki pages
120 * names like "Table of Contents" --- clearly not a valid XML
121 * fragment identifier.
123 * This function implements a one-to-one map from {any string}
124 * to {valid XML identifiers}.
127 * converting all bytes not in [A-Za-z0-9:_-],
128 * and any leading byte not in [A-Za-z] to 'xbb.',
129 * where 'bb' is the hexadecimal representation of the
132 * As a special case, the empty string is converted to 'empty.'
137 function MangleXmlIdentifier($str)
142 return preg_replace('/[^-_:A-Za-z0-9]|(?<=^)[^A-Za-z]/e',
143 "'x' . sprintf('%02x', ord('\\0')) . '.'",
148 * Returns a name for the WIKI_ID cookie that should be unique on the host.
149 * But for it to be unique you must have set a unique WIKI_NAME in your
150 * configuration file.
151 * @return string The name of the WIKI_ID cookie to use for this wiki.
153 function getCookieName()
155 return preg_replace("/[^\d\w]/", "_", WIKI_NAME) . "_WIKI_ID";
159 * Generates a valid URL for a given Wiki pagename.
160 * @param mixed $pagename If a string this will be the name of the Wiki page to link to.
161 * If a WikiDB_Page object function will extract the name to link to.
162 * If a WikiDB_PageRevision object function will extract the name to link to.
164 * @param boolean $get_abs_url Default value is false.
165 * @return string The absolute URL to the page passed as $pagename.
167 function WikiURL($pagename, $args = '', $get_abs_url = false)
169 global $request, $WikiTheme;
172 if (is_object($pagename)) {
173 if (isa($pagename, 'WikiDB_Page')) {
174 $pagename = $pagename->getName();
175 } elseif (isa($pagename, 'WikiDB_PageRevision')) {
176 $page = $pagename->getPage();
177 $args['version'] = $pagename->getVersion();
178 $pagename = $page->getName();
179 } elseif (isa($pagename, 'WikiPageName')) {
180 $anchor = $pagename->anchor;
181 $pagename = $pagename->name;
183 $anchor = $pagename->anchor;
184 $pagename = $pagename->name;
187 if (!$get_abs_url and DEBUG and $request->getArg('start_debug')) {
189 $args = 'start_debug=' . $request->getArg('start_debug');
190 elseif (is_array($args))
191 $args['start_debug'] = $request->getArg('start_debug'); else
192 $args .= '&start_debug=' . $request->getArg('start_debug');
194 if (is_array($args)) {
196 foreach ($args as $key => $val) {
197 // avoid default args
198 if (USE_PATH_INFO and $key == 'pagename')
200 elseif ($key == 'action' and $val == 'browse')
201 ; elseif (!is_array($val)) // ugly hack for getURLtoSelf() which also takes POST vars
202 $enc_args[] = urlencode($key) . '=' . urlencode($val);
204 $args = join('&', $enc_args);
207 if (USE_PATH_INFO or !empty($WikiTheme->HTML_DUMP_SUFFIX)) {
208 $url = $get_abs_url ? (SERVER_URL . VIRTUAL_PATH . "/") : "";
209 $base = preg_replace('/%2f/i', '/', rawurlencode($pagename));
211 if (!empty($WikiTheme->HTML_DUMP_SUFFIX)) {
212 if (!empty($WikiTheme->VALID_LINKS) and $request->getArg('action') == 'pdf') {
213 if (!in_array($pagename, $WikiTheme->VALID_LINKS))
216 $url = $base . $WikiTheme->HTML_DUMP_SUFFIX;
218 $url .= $WikiTheme->HTML_DUMP_SUFFIX;
227 $url = $get_abs_url ? SERVER_URL . SCRIPT_NAME : basename(SCRIPT_NAME);
228 $url .= "?pagename=" . rawurlencode($pagename);
233 $url .= "#" . MangleXmlIdentifier($anchor);
237 /** Convert relative URL to absolute URL.
239 * This converts a relative URL to one of PhpWiki's support files
240 * to an absolute one.
243 * @return string Absolute URL
245 function AbsoluteURL($url)
247 if (preg_match('/^https?:/', $url))
249 if ($url[0] != '/') {
250 $base = USE_PATH_INFO ? VIRTUAL_PATH : dirname(SCRIPT_NAME);
251 while ($base != '/' and substr($url, 0, 3) == "../") {
252 $url = substr($url, 3);
253 $base = dirname($base);
259 return SERVER_URL . $url;
262 function DataURL($url)
264 if (preg_match('/^https?:/', $url))
266 $url = NormalizeWebFileName($url);
267 if (DEBUG and $GLOBALS['request']->getArg('start_debug') and substr($url, -4, 4) == '.php')
268 $url .= "?start_debug=1"; // XMLRPC and SOAP debugging helper.
269 return AbsoluteURL($url);
273 * Generates icon in front of links.
275 * @param string $protocol_or_url URL or protocol to determine which icon to use.
277 * @return HtmlElement HtmlElement object that contains data to create img link to
278 * icon for use with url or protocol passed to the function. False if no img to be
281 function IconForLink($protocol_or_url)
284 if (0 and $filename_suffix == false) {
285 // display apache style icon for file type instead of protocol icon
286 // - archive: unix:gz,bz2,tgz,tar,z; mac:dmg,dmgz,bin,img,cpt,sit; pc:zip;
287 // - document: html, htm, text, txt, rtf, pdf, doc
288 // - non-inlined image: jpg,jpeg,png,gif,tiff,tif,swf,pict,psd,eps,ps
289 // - audio: mp3,mp2,aiff,aif,au
290 // - multimedia: mpeg,mpg,mov,qt
292 list ($proto) = explode(':', $protocol_or_url, 2);
293 $src = $WikiTheme->getLinkIconURL($proto);
295 return HTML::img(array('src' => $src, 'alt' => "", 'class' => 'linkicon'));
302 * Glue icon in front of or after text.
303 * Pref: 'noLinkIcons' - ignore icon if set
304 * WikiTheme: 'LinkIcons' - 'yes' at front
305 * - 'no' display no icon
306 * - 'front' display at left
307 * - 'after' display at right
309 * @param string $protocol_or_url Protocol or URL. Used to determine the
311 * @param string $text The text.
312 * @return XmlContent.
314 function PossiblyGlueIconToText($proto_or_url, $text)
316 global $request, $WikiTheme;
317 if ($request->getPref('noLinkIcons'))
319 $icon = IconForLink($proto_or_url);
322 if ($where = $WikiTheme->getLinkIconAttr()) {
323 if ($where == 'no') return $text;
324 if ($where != 'after') $where = 'front';
328 if ($where == 'after') {
329 // span the icon only to the last word (tie them together),
330 // to let the previous words wrap on line breaks.
331 if (!is_object($text)) {
332 preg_match('/^(\s*\S*)(\s*)$/', $text, $m);
333 list (, $prefix, $last_word) = $m;
338 $text = HTML::span(array('style' => 'white-space: nowrap'),
339 $last_word, HTML::Raw(' '), $icon);
341 $text = HTML($prefix, $text);
344 // span the icon only to the first word (tie them together),
345 // to let the next words wrap on line breaks
346 if (!is_object($text)) {
347 preg_match('/^\s*(\S*)(.*?)\s*$/', $text, $m);
348 list (, $first_word, $tail) = $m;
353 $text = HTML::span(array('style' => 'white-space: nowrap'),
356 $text = HTML($text, $tail);
361 * Determines if the url passed to function is safe, by detecting if the characters
362 * '<', '>', or '"' are present.
363 * Check against their urlencoded values also.
365 * @param string $url URL to check for unsafe characters.
366 * @return boolean True if same, false else.
368 function IsSafeURL($url)
370 return !preg_match('/([<>"])|(%3C)|(%3E)|(%22)/', $url);
374 * Generates an HtmlElement object to store data for a link.
376 * @param string $url URL that the link will point to.
377 * @param string $linktext Text to be displayed as link.
378 * @return HtmlElement HtmlElement object that contains data to construct an html link.
380 function LinkURL($url, $linktext = '')
382 // FIXME: Is this needed (or sufficient?)
383 if (!IsSafeURL($url)) {
384 $link = HTML::span(array('class' => 'error'), _('Bad URL -- remove all of <, >, "'));
388 $linktext = preg_replace("/mailto:/A", "", $url);
389 $args = array('href' => $url);
390 if (defined('EXTERNAL_LINK_TARGET')) // can also be set in the css
391 $args['target'] = (is_string(EXTERNAL_LINK_TARGET) and (EXTERNAL_LINK_TARGET != "")) ? EXTERNAL_LINK_TARGET : "_blank";
392 $link = HTML::a($args, PossiblyGlueIconToText($url, $linktext));
394 $link->setAttr('class', $linktext ? 'namedurl' : 'rawurl');
401 * Syntax: [image.png size=50% border=n align= hspace= vspace= width= height=]
402 * Disallows sizes which are too small.
403 * Spammers may use such (typically invisible) image attributes to raise their GoogleRank.
405 * Handle embeddable objects, like svg, class, vrml, swf, svgz, pdf, avi, wmv especially.
407 function LinkImage($url, $alt = "")
409 $force_img = "png|jpg|gif|jpeg|bmp|pl|cgi";
410 // Disallow tags in img src urls. Typical CSS attacks.
411 // FIXME: Is this needed (or sufficient?)
412 // FIXED: This was broken for moniker:TP30 test/image.png => url="moniker:TP30" attr="test/image.png"
414 // support new syntax: [prefix/image.jpg size=50% border=n]
419 $arr = explode(' ', $url);
420 if (!empty($arr)) $url = $arr[0];
421 if (!IsSafeURL($url)) {
422 $link = HTML::span(array('class' => 'error'), _('Bad URL for image -- remove all of <, >, "'));
425 // spaces in inline images must be %20 encoded!
426 $link = HTML::img(array('src' => $url));
428 // Extract attributes
429 $arr = parse_attributes(strstr($ori_url, " "));
430 foreach ($arr as $attr => $value) {
431 // These attributes take strings: lang, id, title, alt
432 if (($attr == "lang")
434 || ($attr == "title")
437 $link->setAttr($attr, $value);
438 } // align = bottom|middle|top|left|right
439 // we allow "center" as synonym for "middle"
440 elseif (($attr == "align")
441 && (($value == "bottom")
442 || ($value == "middle")
443 || ($value == "center")
445 || ($value == "left")
446 || ($value == "right"))
448 if ($value == "center") {
451 $link->setAttr($attr, $value);
452 } // These attributes take a number (pixels): border, hspace, vspace
453 elseif ((($attr == "border") || ($attr == "hspace") || ($attr == "vspace"))
454 && (is_numeric($value))
456 $link->setAttr($attr, (int)$value);
457 } // These attributes take a number (pixels) or a percentage: height, width
458 elseif ((($attr == "height") || ($attr == "width"))
459 && (preg_match('/\d+[%p]?x?/', $value))
461 $link->setAttr($attr, $value);
462 } // We allow size=50% and size=20x30
463 // We replace this with "width" and "height" HTML attributes
464 elseif ($attr == "size") {
465 if (preg_match('/(\d+%)/', $value, $m)) {
466 $link->setAttr('width', $m[1]);
467 $link->setAttr('height', $m[1]);
468 } elseif (preg_match('/(\d+)x(\d+)/', $value, $m)) {
469 $link->setAttr('width', $m[1]);
470 $link->setAttr('height', $m[2]);
473 $url = substr(strrchr($ori_url, "/"), 1);
474 $link = HTML::span(array('class' => 'error'),
475 sprintf(_("Invalid attribute %s=%s for image %s"),
476 $attr, $value, $url));
480 // Correct silently the most common error
481 if ($url != $ori_url and empty($arr) and !preg_match("/^http/", $url)) {
482 // space belongs to the path
483 $file = NormalizeLocalFileName($ori_url);
484 if (file_exists($file)) {
485 $link = HTML::img(array('src' => $ori_url));
487 sprintf(_("Invalid image link fixed %s => %s. Spaces must be quoted with %%20."),
488 $url, $ori_url), E_USER_WARNING);
489 } elseif (string_starts_with($ori_url, getUploadDataPath())) {
490 $file = substr($file, strlen(getUploadDataPath()));
491 $path = getUploadFilePath() . $file;
492 if (file_exists($path)) {
493 trigger_error(sprintf(_("Invalid image link fixed \"%s\" => \"%s\".\n Spaces must be quoted with %%20."),
494 $url, $ori_url), E_USER_WARNING);
495 $link->setAttr('src', getUploadDataPath() . $file);
500 if (!$link->getAttr('alt')) {
501 $link->setAttr('alt', $alt);
503 // Check width and height as spam countermeasure
504 if (($width = $link->getAttr('width')) and ($height = $link->getAttr('height'))) {
505 //$width = (int) $width; // px or % or other suffix
506 //$height = (int) $height;
507 if (($width < 3 and $height < 10) or
508 ($height < 3 and $width < 20) or
509 ($height < 7 and $width < 7)
511 $link = HTML::span(array('class' => 'error'),
512 _("Invalid image size"));
517 // Prepare for getimagesize($url)
518 // $url only valid for external urls, otherwise local path
519 if (DISABLE_GETIMAGESIZE)
521 elseif (!preg_match("/\.$force_img$/i", $url))
522 ; // only valid image extensions or scripts assumed to generate images
523 elseif (preg_match("/^http/", $url)) { // external url
524 $size = @getimagesize($url);
525 } else { // local file
526 if (file_exists($file = NormalizeLocalFileName($url))) { // here
527 $size = @getimagesize($file);
528 } elseif (file_exists(NormalizeLocalFileName(urldecode($url)))) {
529 $size = @getimagesize($file);
530 $link->setAttr('src', rawurldecode($url));
531 } elseif (string_starts_with($url, getUploadDataPath())) { // there
532 $file = substr($file, strlen(getUploadDataPath()));
533 $path = getUploadFilePath() . rawurldecode($file);
534 $size = @getimagesize($path);
535 $link->setAttr('src', getUploadDataPath() . rawurldecode($file));
536 } else { // elsewhere
538 $size = @getimagesize($request->get('DOCUMENT_ROOT') . urldecode($url));
544 if (($width < 3 and $height < 10)
545 or ($height < 3 and $width < 20)
546 or ($height < 7 and $width < 7)
548 $link = HTML::span(array('class' => 'error'),
549 _("Invalid image size"));
554 $link->setAttr('class', 'inlineimage');
556 /* Check for inlined objects. Everything allowed in INLINE_IMAGES besides
557 * png|jpg|gif|jpeg|bmp|pl|cgi. If no image it is an object to embed.
558 * Note: Allow cgi's (pl,cgi) returning images.
560 if (!preg_match("/\.(" . $force_img . ")/i", $ori_url)) {
561 // HTML::img(array('src' => $url, 'alt' => $alt, 'title' => $alt));
562 // => HTML::object(array('src' => $url)) ...;
563 return ImgObject($link, $ori_url);
569 * <object> / <embed> tags instead of <img> for all non-image extensions
571 * Called by LinkImage(), not directly.
572 * Syntax: [image.svg size=50% alt=image.gif border=n align= hspace= vspace= width= height=]
573 * Samples: [Upload:song.mp3 type=audio/mpeg width=200 height=10]
574 * $alt may be an alternate img
575 * TODO: Need to unify with WikiPluginCached::embedObject()
577 * Note that Safari 1.0 will crash with <object>, so use only <embed>
578 * http://www.alleged.org.uk/pdc/2002/svg-object.html
580 * Allowed object tags:
582 * DATA=URI (object data)
583 * CLASSID=URI (location of implementation)
584 * ARCHIVE=CDATA (archive files)
585 * CODEBASE=URI (base URI for CLASSID, DATA, ARCHIVE)
586 * WIDTH=Length (object width)
587 * HEIGHT=Length (object height)
588 * NAME=CDATA (name for form submission)
589 * USEMAP=URI (client-side image map)
590 * TYPE=ContentType (content-type of object)
591 * CODETYPE=ContentType (content-type of code)
592 * STANDBY=Text (message to show while loading)
593 * TABINDEX=NUMBER (position in tabbing order)
594 * DECLARE (do not instantiate object)
595 * The rest is added as <param name="" value="" /> tags
597 function ImgObject($img, $url)
599 // get the url args: data="sample.svgz" type="image/svg+xml" width="400" height="300"
600 $params = explode(",", "id,width,height,data,classid,archive,codebase,name,usemap,type," .
601 "codetype,standby,tabindex,declare");
602 if (is_array($url)) {
605 foreach ($args as $attr => $value) {
606 foreach ($params as $param) {
607 if ($param == $attr) {
608 $img->setAttr($param, $value);
609 if (isset($found[$param])) $found[$param]++;
610 else $found[$param] = 1;
615 // now all remaining args are added as <param> to the object
617 foreach ($args as $attr => $value) {
618 if (!isset($found[$attr])) {
619 $params[] = HTML::param(array('name' => $attr,
623 $url = $img->getAttr('src');
624 $force_img = "png|jpg|gif|jpeg|bmp";
625 if (!preg_match("/\.(" . $force_img . ")/i", $url)) {
626 $img->setAttr('src', false);
629 $args = explode(' ', $url);
630 if (count($args) >= 1) {
631 $url = array_shift($args);
633 foreach ($args as $attr) {
634 foreach ($params as $param) {
635 if (preg_match("/^$param=(\S+)$/i", $attr, $m)) {
636 $img->setAttr($param, $m[1]);
637 if (isset($found[$param])) $found[$param]++;
638 else $found[$param] = 1;
643 // now all remaining args are added as <param> to the object
645 foreach ($args as $attr) {
646 if (!isset($found[$attr]) and preg_match("/^(\S+)=(\S+)$/i", $attr, $m)) {
647 $params[] = HTML::param(array('name' => $m[1],
653 $type = $img->getAttr('type');
655 if (function_exists('mime_content_type') && file_exists($url)) {
656 $type = mime_content_type($url);
659 $object = HTML::object(array_merge($img->_attr,
660 array('type' => $type)), //'src' => $url
662 $object->setAttr('class', 'inlineobject');
664 foreach ($params as $param) $object->pushContent($param);
666 if (isBrowserSafari() and !isBrowserSafari(532)) { // recent chrome can do OBJECT
667 return HTML::embed($object->_attr, $object->_content);
669 $object->pushContent(HTML::embed($object->_attr));
677 $this->items = array();
683 $this->items[$this->size] = $item;
690 if ($this->size == 0) {
691 return false; // stack is empty
694 return $this->items[$this->size];
705 return $this->items[$this->size - 1];
712 // end class definition
714 function SplitQueryArgs($query_args = '')
716 // FIXME: use the arg-seperator which might not be &
717 $split_args = explode('&', $query_args);
719 while (list($key, $val) = each($split_args))
720 if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
721 $args[$m[1]] = $m[2];
725 function LinkPhpwikiURL($url, $text = '', $basepage = false)
729 if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m)) {
730 return HTML::span(array('class' => 'error'), _("BAD phpwiki: URL"));
734 $pagename = urldecode($m[1]);
737 if (empty($pagename) &&
738 preg_match('/^(diff|edit|links|info)=([^&]+)$/', $qargs, $m)
740 // Convert old style links (to not break diff links in
742 $pagename = urldecode($m[2]);
743 $args = array("action" => $m[1]);
745 $args = SplitQueryArgs($qargs);
748 if (empty($pagename))
749 $pagename = $GLOBALS['request']->getArg('pagename');
751 if (isset($args['action']) && $args['action'] == 'browse')
752 unset($args['action']);
755 if (empty($args['action']))
757 else if (is_safe_action($args['action']))
758 $class = 'wikiaction';
760 if (empty($args['action']) || is_safe_action($args['action']))
761 $class = 'wikiaction';
763 // Don't allow administrative links on unlocked pages.
764 $dbi = $GLOBALS['request']->getDbh();
765 $page = $dbi->getPage($basepage ? $basepage : $pagename);
766 if (!$page->get('locked'))
767 return HTML::span(array('class' => 'wikiunsafe'),
768 HTML::u(_("Lock page to enable link")));
769 $class = 'wikiadmin';
773 $text = HTML::span(array('class' => 'rawurl'), $url);
775 $wikipage = new WikiPageName($pagename);
776 if (!$wikipage->isValid()) {
778 return $WikiTheme->linkBadWikiWord($wikipage, $url);
781 return HTML::a(array('href' => WikiURL($pagename, $args),
787 * A class to assist in parsing wiki pagenames.
789 * Now with subpages and anchors, parsing and passing around
790 * pagenames is more complicated. This should help.
794 /** Short name for page.
796 * This is the value of $name passed to the constructor.
797 * (For use, e.g. as a default label for links to the page.)
801 /** The full page name.
803 * This is the full name of the page (without anchor).
809 * This is the referenced anchor within the page, or the empty string.
815 * @param mixed $name Page name.
816 * WikiDB_Page, WikiDB_PageRevision, or string.
817 * This can be a relative subpage name (like '/SubPage'),
818 * or can be the empty string to refer to the $basename.
820 * @param string $anchor For links to anchors in page.
822 * @param mixed $basename Page name from which to interpret
823 * relative or other non-fully-specified page names.
825 function WikiPageName($name, $basename = false, $anchor = false)
827 if (is_string($name)) {
828 $this->shortName = $name;
829 if (strstr($name, ':')) {
830 list($moniker, $shortName) = explode(":", $name, 2);
831 $map = getInterwikiMap(); // allow overrides to custom maps
832 if (isset($map->_map[$moniker])) {
833 $url = $map->_map[$moniker];
834 if (strstr($url, '%s'))
835 $url = sprintf($url, $shortName);
839 // expand Talk or User, but not to absolute urls!
840 if (strstr($url, '//')) {
841 if ($moniker == 'Talk')
842 $name = $name . SUBPAGE_SEPARATOR . _("Discussion");
843 elseif ($moniker == 'User')
848 $this->shortName = $shortName;
851 // FIXME: We should really fix the cause for "/PageName" in the WikiDB
852 if ($name == '' or $name[0] == SUBPAGE_SEPARATOR) {
854 $name = $this->_pagename($basename) . $name;
856 $name = $this->_normalize_bad_pagename($name);
857 $this->shortName = $name;
861 $name = $this->_pagename($name);
862 $this->shortName = $name;
865 $this->name = $this->_check($name);
866 $this->anchor = (string)$anchor;
877 if (!($tail = strrchr($name, SUBPAGE_SEPARATOR)))
879 return substr($name, 0, -strlen($tail));
882 function isValid($strict = false)
885 return !isset($this->_errors);
886 return (is_string($this->name) and $this->name != '');
889 function getWarnings()
892 if (isset($this->_warnings))
893 $warnings = array_merge($warnings, $this->_warnings);
894 if (isset($this->_errors))
895 $warnings = array_merge($warnings, $this->_errors);
899 return sprintf(_("“%s”: Bad page name: %s"),
900 $this->shortName, join(', ', $warnings));
903 function _pagename($page)
905 if (isa($page, 'WikiDB_Page'))
906 return $page->getName();
907 elseif (isa($page, 'WikiDB_PageRevision'))
908 return $page->getPageName(); elseif (isa($page, 'WikiPageName'))
910 // '0' or e.g. '1984' should be allowed though
911 if (!is_string($page) and !is_integer($page)) {
912 trigger_error(sprintf("Non-string pagename “%s” (%s)(%s)",
913 $page, gettype($page), get_class($page)),
916 //assert(is_string($page));
920 function _normalize_bad_pagename($name)
922 trigger_error("Bad pagename: " . $name, E_USER_WARNING);
924 // Punt... You really shouldn't get here.
927 return $request->getArg('pagename');
929 assert($name[0] == SUBPAGE_SEPARATOR);
930 $this->_errors[] = sprintf(_("Leading %s not allowed"), SUBPAGE_SEPARATOR);
931 return substr($name, 1);
935 * Compress internal white-space to single space character.
937 * This leads to problems with loading a foreign charset pagename,
938 * which cannot be deleted anymore, because unknown chars are compressed.
939 * So BEFORE importing a file _check must be done !!!
941 function _check($pagename)
943 // Compress internal white-space to single space character.
944 $pagename = preg_replace('/[\s\xa0]+/', ' ', $orig = $pagename);
945 if ($pagename != $orig)
946 $this->_warnings[] = _("White space converted to single space");
948 // Delete any control characters.
949 if (DATABASE_TYPE == 'cvs' or DATABASE_TYPE == 'file' or DATABASE_TYPE == 'flatfile') {
950 $pagename = preg_replace('/[\x00-\x1f\x7f\x80-\x9f]/', '', $orig = $pagename);
951 if ($pagename != $orig)
952 $this->_errors[] = _("Control characters not allowed");
955 // Strip leading and trailing white-space.
956 $pagename = trim($pagename);
959 while ($pagename and $pagename[0] == SUBPAGE_SEPARATOR)
960 $pagename = substr($pagename, 1);
961 if ($pagename != $orig)
962 $this->_errors[] = sprintf(_("Leading %s not allowed"), SUBPAGE_SEPARATOR);
964 // ";" is urlencoded, so safe from php arg-delim problems
965 /*if (strstr($pagename, ';')) {
966 $this->_warnings[] = _("';' is deprecated");
967 $pagename = str_replace(';', '', $pagename);
970 // not only for SQL, also to restrict url length
971 if (strlen($pagename) > MAX_PAGENAME_LENGTH) {
972 $pagename = substr($pagename, 0, MAX_PAGENAME_LENGTH);
973 $this->_errors[] = _("Page name too long");
976 // disallow some chars only on file and cvs
977 if ((DATABASE_TYPE == 'cvs'
978 or DATABASE_TYPE == 'file'
979 or DATABASE_TYPE == 'flatfile')
980 and preg_match('/(:|\.\.)/', $pagename, $m)
982 $this->_warnings[] = sprintf(_("Illegal chars %s removed"), $m[1]);
983 $pagename = str_replace('..', '', $pagename);
984 $pagename = str_replace(':', '', $pagename);
992 * Convert old page markup to new-style markup.
994 * @param string $text Old-style wiki markup.
996 * @param string $markup_type
998 * <dt><code>"block"</code> <dd>Convert all markup.
999 * <dt><code>"inline"</code> <dd>Convert only inline markup.
1000 * <dt><code>"links"</code> <dd>Convert only link markup.
1003 * @return string New-style wiki markup.
1005 * @bugs Footnotes don't work quite as before (esp if there are
1006 * multiple references to the same footnote. But close enough,
1007 * probably for now....
1008 * @bugs Apache2 and IIS crash with OldTextFormattingRules or
1009 * AnciennesR%E8glesDeFormatage. (at the 2nd attempt to do the anchored block regex)
1010 * It only crashes with CreateToc so far, but other pages (not in pgsrc) are
1011 * also known to crash, even with Apache1.
1013 function ConvertOldMarkup($text, $markup_type = "block")
1020 // Trying to detect why the 2nd paragraph of OldTextFormattingRules or
1021 // AnciennesR%E8glesDeFormatage crashes.
1022 // It only crashes with CreateToc so far, but other pages (not in pgsrc) are
1023 // also known to crash, even with Apache1.
1024 $debug_skip = false;
1025 // I suspect this only to crash with Apache2 and IIS.
1026 if (in_array(php_sapi_name(), array('apache2handler', 'apache2filter', 'isapi'))
1027 and preg_match("/plugin CreateToc/", $text)
1029 trigger_error(_("The CreateTocPlugin is not yet old markup compatible! ")
1030 . _("Please remove the CreateToc line to be able to reformat this page to old markup. ")
1031 . _("Skipped."), E_USER_WARNING);
1033 //if (!DEBUG) return $text;
1038 /*****************************************************************
1039 * Conversions for inline markup:
1046 // escape escaped brackets
1050 // change ! escapes to ~'s.
1051 global $WikiNameRegexp, $request;
1052 $bang_esc[] = "(?:" . ALLOWED_PROTOCOLS . "):[^\s<>\[\]\"'()]*[^\s<>\[\]\"'(),.?]";
1053 // before 4.3.9 pcre had a memory release bug, which might hit us here. so be safe.
1054 $map = getInterwikiMap();
1055 if ($map_regex = $map->getRegexp())
1056 $bang_esc[] = $map_regex . ":[^\\s.,;?()]+"; // FIXME: is this really needed?
1057 $bang_esc[] = $WikiNameRegexp;
1058 $orig[] = '/!((?:' . join(')|(', $bang_esc) . '))/';
1061 $subs["links"] = array($orig, $repl);
1063 // Temporarily URL-encode pairs of underscores in links to hide
1064 // them from the re for bold markup.
1065 $orig[] = '/\[[^\[\]]*?__[^\[\]]*?\]/e';
1066 $repl[] = 'str_replace(\'__\', \'%5F%5F\', \'\\0\')';
1069 //$orig[] = '/<(?!\?plugin)|(?<!^)</m';
1072 // Convert footnote references.
1073 $orig[] = '/(?<=.)(?<!~)\[\s*(\d+)\s*\]/m';
1074 $repl[] = '#[|ftnt_ref_\\1]<sup>~[[\\1|#ftnt_\\1]~]</sup>';
1076 // Convert old style emphases to HTML style emphasis.
1077 $orig[] = '/__(.*?)__/';
1078 $repl[] = '<strong>\\1</strong>';
1079 $orig[] = "/''(.*?)''/";
1080 $repl[] = '<em>\\1</em>';
1082 // Escape nestled markup.
1083 $orig[] = '/^(?<=^|\s)[=_](?=\S)|(?<=\S)[=_*](?=\s|$)/m';
1086 // in old markup headings only allowed at beginning of line
1090 // Convert URL-encoded pairs of underscores in links back to
1091 // real underscores after bold markup has been converted.
1092 $orig = '/\[[^\[\]]*?%5F%5F[^\[\]]*?\]/e';
1093 $repl = 'str_replace(\'%5F%5F\', \'__\', \'\\0\')';
1095 $subs["inline"] = array($orig, $repl);
1097 /*****************************************************************
1098 * Patterns which match block markup constructs which take
1099 * special handling...
1103 $blockpats[] = '[ \t]+\S(?:.*\s*\n[ \t]+\S)*';
1105 $blockpats[] = '\|(?:.*\n\|)*';
1108 $blockpats[] = '[#*;]*(?:[*#]|;.*?:)';
1110 // Footnote definitions
1111 $blockpats[] = '\[\s*(\d+)\s*\]';
1115 $blockpats[] = '<\?plugin(?:-form)?\b.*\?>\s*$';
1119 $blockpats[] = '!{1,3}[^!]';
1121 removed .|\n in the anchor not to crash on /m because with /m "." already includes \n
1122 this breaks headings but it doesn't crash anymore (crash on non-cgi, non-cli only)
1124 $block_re = ('/\A((?:.|\n)*?)(^(?:'
1125 . join("|", $blockpats)
1130 if ($markup_type != "block") {
1131 list ($orig, $repl) = $subs[$markup_type];
1132 return preg_replace($orig, $repl, $text);
1134 list ($orig, $repl) = $subs['inline'];
1137 // php crashes here in the 2nd paragraph of OldTextFormattingRules,
1138 // AnciennesR%E8glesDeFormatage and more
1139 // See http://www.pcre.org/pcre.txt LIMITATIONS
1140 while (preg_match($block_re, $text, $m)) {
1141 $text = substr($text, strlen($m[0]));
1142 list (, $leading_text, $block) = $m;
1145 if (strchr(" \t", $block[0])) {
1147 $prefix = "<pre>\n";
1148 $suffix = "\n</pre>\n";
1149 } elseif ($block[0] == '|') {
1151 $prefix = "<?plugin OldStyleTable\n";
1153 } elseif (strchr("#*;", $block[0])) {
1154 // Old-style list item
1155 preg_match('/^([#*;]*)([*#]|;.*?:) */', $block, $m);
1156 list (, $ind, $bullet) = $m;
1157 $block = substr($block, strlen($m[0]));
1159 $indent = str_repeat(' ', strlen($ind));
1160 if ($bullet[0] == ';') {
1161 //$term = ltrim(substr($bullet, 1));
1162 //return $indent . $term . "\n" . $indent . ' ';
1163 $prefix = $ind . $bullet;
1165 $prefix = $indent . $bullet . ' ';
1166 } elseif ($block[0] == '[') {
1167 // Footnote definition
1168 preg_match('/^\[\s*(\d+)\s*\]/', $block, $m);
1170 $block = substr($block, strlen($m[0]));
1171 $prefix = "#[|ftnt_" . ${footnum} . "]~[[" . ${footnum} . "|#ftnt_ref_" . ${footnum} . "]~] ";
1172 } elseif ($block[0] == '<') {
1174 // HACK: no inline markup...
1177 } elseif ($block[0] == '!') {
1179 preg_match('/^!{1,3}/', $block, $m);
1181 $block = substr($block, strlen($m[0]));
1186 if ($leading_text) $leading_text = preg_replace($orig, $repl, $leading_text);
1187 if ($block) $block = preg_replace($orig, $repl, $block);
1188 $out .= $leading_text;
1193 return $out . preg_replace($orig, $repl, $text);
1198 * Expand tabs in string.
1200 * Converts all tabs to (the appropriate number of) spaces.
1202 * @param string $str
1203 * @param integer $tab_width
1206 function expand_tabs($str, $tab_width = 8)
1208 $split = explode("\t", $str);
1209 $tail = array_pop($split);
1211 foreach ($split as $hunk) {
1213 $pos = strlen(strrchr($expanded, "\n")) - 1;
1214 $expanded .= str_repeat(" ", ($tab_width - $pos % $tab_width));
1216 return substr($expanded, 1) . $tail;
1220 * Split WikiWords in page names.
1222 * It has been deemed useful to split WikiWords (into "Wiki Words") in
1223 * places like page titles. This is rumored to help search engines
1226 * @param $page string The page name.
1228 * @return string The split name.
1230 function SplitPagename($page)
1233 if (preg_match("/\s/", $page))
1234 return $page; // Already split --- don't split any more.
1236 // This algorithm is specialized for several languages.
1237 // (Thanks to Pierrick MEIGNEN)
1238 // Improvements for other languages welcome.
1241 // This mess splits between a lower-case letter followed by
1242 // either an upper-case or a numeral; except that it wont
1243 // split the prefixes 'Mc', 'De', or 'Di' off of their tails.
1244 switch ($GLOBALS['LANG']) {
1249 $RE[] = '/([[:lower:]])((?<!Mc|De|Di)[[:upper:]]|\d)/';
1252 $RE[] = '/([[:lower:]])((?<!Mc|Di)[[:upper:]]|\d)/';
1255 $sep = preg_quote(SUBPAGE_SEPARATOR, '/');
1256 // This the single-letter words 'I' and 'A' from any following
1257 // capitalized words.
1258 switch ($GLOBALS['LANG']) {
1260 $RE[] = "/(?<= |${sep}|^)([AI])([[:upper:]][[:lower:]])/";
1263 $RE[] = "/(?<= |${sep}|^)([À])([[:upper:]][[:lower:]])/";
1266 // Split at underscore
1267 $RE[] = '/(_)([[:alpha:]])/';
1268 $RE[] = '/([[:alpha:]])(_)/';
1269 // Split numerals from following letters.
1270 $RE[] = '/(\d)([[:alpha:]])/';
1271 // Split at subpage seperators. TBD in WikiTheme.php
1272 $RE[] = "/([^${sep}]+)(${sep})/";
1273 $RE[] = "/(${sep})([^${sep}]+)/";
1275 foreach ($RE as $key)
1279 foreach ($RE as $regexp) {
1280 $page = preg_replace($regexp, '\\1 \\2', $page);
1285 function NoSuchRevision(&$request, $page, $version)
1287 $html = HTML(HTML::h2(_("Revision Not Found")),
1288 HTML::p(fmt("I'm sorry. Version %d of %s is not in the database.",
1289 $version, WikiLink($page, 'auto'))));
1290 include_once 'lib/Template.php';
1291 GeneratePage($html, _("Bad Version"), $page->getCurrentRevision());
1296 * Get time offset for local time zone.
1298 * @param $time time_t Get offset for this time. Default: now.
1299 * @param $no_colon boolean Don't put colon between hours and minutes.
1300 * @return string Offset as a string in the format +HH:MM.
1302 function TimezoneOffset($time = false, $no_colon = false)
1304 if ($time === false)
1306 $secs = date('Z', $time);
1314 $colon = $no_colon ? '' : ':';
1315 $mins = intval(($secs + 30) / 60);
1316 return sprintf("%s%02d%s%02d",
1317 $sign, $mins / 60, $colon, $mins % 60);
1321 * Format time in ISO-8601 format.
1323 * @param $time time_t Time. Default: now.
1324 * @return string Date and time in ISO-8601 format.
1326 function Iso8601DateTime($time = false)
1328 if ($time === false)
1330 $tzoff = TimezoneOffset($time);
1331 $date = date('Y-m-d', $time);
1332 $time = date('H:i:s', $time);
1333 return $date . 'T' . $time . $tzoff;
1337 * Format time in RFC-2822 format.
1339 * @param $time time_t Time. Default: now.
1340 * @return string Date and time in RFC-2822 format.
1342 function Rfc2822DateTime($time = false)
1344 if ($time === false)
1346 return date('D, j M Y H:i:s ', $time) . TimezoneOffset($time, 'no colon');
1350 * Format time in RFC-1123 format.
1352 * @param $time time_t Time. Default: now.
1353 * @return string Date and time in RFC-1123 format.
1355 function Rfc1123DateTime($time = false)
1357 if ($time === false)
1359 return gmdate('D, d M Y H:i:s \G\M\T', $time);
1362 /** Parse date in RFC-1123 format.
1364 * According to RFC 1123 we must accept dates in the following
1367 * Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123
1368 * Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
1369 * Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format
1371 * (Though we're only allowed to generate dates in the first format.)
1373 function ParseRfc1123DateTime($timestr)
1375 $timestr = trim($timestr);
1376 if (preg_match('/^ \w{3},\s* (\d{1,2}) \s* (\w{3}) \s* (\d{4}) \s*'
1377 . '(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
1380 list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
1381 } elseif (preg_match('/^ \w+,\s* (\d{1,2})-(\w{3})-(\d{2}|\d{4}) \s*'
1382 . '(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
1385 list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
1386 if ($year < 70) $year += 2000;
1387 elseif ($year < 100) $year += 1900;
1388 } elseif (preg_match('/^\w+\s* (\w{3}) \s* (\d{1,2}) \s*'
1389 . '(\d\d):(\d\d):(\d\d) \s* (\d{4})$/ix',
1392 list(, $mon, $mday, $hh, $mm, $ss, $year) = $m;
1398 $time = strtotime("$mday $mon $year ${hh}:${mm}:${ss} GMT");
1400 return false; // failed
1405 * Format time to standard 'ctime' format.
1407 * @param $time time_t Time. Default: now.
1408 * @return string Date and time.
1410 function CTime($time = false)
1412 if ($time === false)
1414 return date("D M j H:i:s Y", $time);
1418 * Format number as kibibytes or bytes.
1419 * Short format is used for PageList
1420 * Long format is used in PageInfo
1422 * @param $bytes int. Default: 0.
1423 * @param $longformat bool. Default: false.
1424 * @return class FormattedText (XmlElement.php).
1426 function ByteFormatter($bytes = 0, $longformat = false)
1430 if ($bytes < 1024) {
1432 $size = fmt("%s B", $bytes);
1434 $size = fmt("%s bytes", $bytes);
1436 $kb = round($bytes / 1024, 1);
1438 $size = fmt("%s KiB", $kb);
1440 $size = fmt("%s KiB (%s bytes)", $kb, $bytes);
1446 * Internationalized printf.
1448 * This is essentially the same as PHP's built-in printf
1449 * with the following exceptions:
1451 * <li> It passes the format string through gettext().
1452 * <li> It supports the argument reordering extensions.
1459 * __printf("Differences between versions %s and %s of %s",
1460 * $new_link, $old_link, $page_link);
1463 * Then in locale/po/de.po, one can reorder the printf arguments:
1466 * msgid "Differences between %s and %s of %s."
1467 * msgstr "Der Unterschiedsergebnis von %3$s, zwischen %1$s und %2$s."
1470 * (Note that while PHP tries to expand $vars within double-quotes,
1471 * the values in msgstr undergo no such expansion, so the '$'s
1474 * One shouldn't use reordered arguments in the default format string.
1475 * Backslashes in the default string would be necessary to escape the
1476 * '$'s, and they'll cause all kinds of trouble....
1478 function __printf($fmt)
1480 $args = func_get_args();
1482 echo __vsprintf($fmt, $args);
1486 * Internationalized sprintf.
1488 * This is essentially the same as PHP's built-in printf with the
1489 * following exceptions:
1492 * <li> It passes the format string through gettext().
1493 * <li> It supports the argument reordering extensions.
1498 function __sprintf($fmt)
1500 $args = func_get_args();
1502 return __vsprintf($fmt, $args);
1506 * Internationalized vsprintf.
1508 * This is essentially the same as PHP's built-in printf with the
1509 * following exceptions:
1512 * <li> It passes the format string through gettext().
1513 * <li> It supports the argument reordering extensions.
1518 function __vsprintf($fmt, $args)
1520 $fmt = gettext($fmt);
1521 // PHP's sprintf doesn't support variable with specifiers,
1522 // like sprintf("%*s", 10, "x"); --- so we won't either.
1524 if (preg_match_all('/(?<!%)%(\d+)\$/x', $fmt, $m)) {
1525 // Format string has '%2$s' style argument reordering.
1526 // PHP doesn't support this.
1527 if (preg_match('/(?<!%)%[- ]?\d*[^- \d$]/x', $fmt))
1528 // literal variable name substitution only to keep locale
1529 // strings uncluttered
1530 trigger_error(sprintf(_("Can't mix “%s” with “%s” type format strings"),
1531 '%1\$s', '%s'), E_USER_WARNING); //php+locale error
1533 $fmt = preg_replace('/(?<!%)%\d+\$/x', '%', $fmt);
1536 // Reorder arguments appropriately.
1537 foreach ($m[1] as $argnum) {
1538 if ($argnum < 1 || $argnum > count($args))
1539 trigger_error(sprintf(_("%s: argument index out of range"),
1540 $argnum), E_USER_WARNING);
1541 $newargs[] = $args[$argnum - 1];
1546 // Not all PHP's have vsprintf, so...
1547 array_unshift($args, $fmt);
1548 return call_user_func_array('sprintf', $args);
1551 function file_mtime($filename)
1553 if ($stat = @stat($filename))
1559 function sort_file_mtime($a, $b)
1561 $ma = file_mtime($a);
1562 $mb = file_mtime($b);
1563 if (!$ma or !$mb or $ma == $mb) return 0;
1564 return ($ma > $mb) ? -1 : 1;
1570 * Build an array in $this->_fileList of files from $dirname.
1571 * Subdirectories are not traversed.
1573 * (This was a function LoadDir in lib/loadsave.php)
1574 * See also http://www.php.net/manual/en/function.readdir.php
1576 function getFiles($exclude = '', $sortby = '', $limit = '')
1578 $list = $this->_fileList;
1581 require_once 'lib/PageList.php';
1582 switch (Pagelist::sortby($sortby, 'db')) {
1583 case 'pagename ASC':
1585 case 'pagename DESC':
1586 $list = array_reverse($list);
1589 usort($list, 'sort_file_mtime');
1592 usort($list, 'sort_file_mtime');
1593 $list = array_reverse($list);
1598 return array_splice($list, 0, $limit);
1602 function _filenameSelector($filename)
1604 if (!$this->_pattern)
1607 if (!$this->_pcre_pattern)
1608 $this->_pcre_pattern = glob_to_pcre($this->_pattern);
1609 return preg_match('/' . $this->_pcre_pattern . ($this->_case ? '/' : '/i'),
1614 function fileSet($directory, $filepattern = false)
1616 $this->_fileList = array();
1617 $this->_pattern = $filepattern;
1619 $this->_pcre_pattern = glob_to_pcre($this->_pattern);
1621 $this->_case = !isWindows();
1622 $this->_pathsep = '/';
1624 if (empty($directory)) {
1625 trigger_error(sprintf(_("%s is empty."), 'directoryname'),
1627 return; // early return
1630 @ $dir_handle = opendir($dir = $directory);
1631 if (empty($dir_handle)) {
1632 trigger_error(sprintf(_("Unable to open directory “%s” for reading"),
1633 $dir), E_USER_NOTICE);
1634 return; // early return
1637 while ($filename = readdir($dir_handle)) {
1638 if ($filename[0] == '.' || filetype($dir . $this->_pathsep . $filename) != 'file')
1640 if ($this->_filenameSelector($filename)) {
1641 array_push($this->_fileList, "$filename");
1642 //trigger_error(sprintf(_("found file %s"), $filename),
1643 // E_USER_NOTICE); //debugging
1646 closedir($dir_handle);
1652 // expands a list containing regex's to its matching entries
1653 class ListRegexExpand
1655 public $match, $list, $index, $case_sensitive;
1656 function ListRegexExpand(&$list, $match, $case_sensitive = true)
1658 $this->match = $match;
1659 $this->list = &$list;
1660 $this->case_sensitive = $case_sensitive;
1661 //$this->index = false;
1664 function listMatchCallback($item, $key)
1666 $quoted = str_replace('/', '\/', $item);
1667 if (preg_match('/' . $this->match . ($this->case_sensitive ? '/' : '/i'),
1670 unset($this->list[$this->index]);
1671 $this->list[] = $item;
1675 function expandRegex($index, &$pages)
1677 $this->index = $index;
1678 array_walk($pages, array($this, 'listMatchCallback'));
1683 // Convert fileglob to regex style:
1684 // Convert some wildcards to pcre style, escape the rest
1685 // Escape . \\ + * ? [ ^ ] $ ( ) { } = ! < > | : /
1686 // Fixed bug #994994: "/" in $glob.
1687 function glob_to_pcre($glob)
1689 // check simple case: no need to escape
1690 $escape = '\[](){}=!<>|:/';
1691 if (strcspn($glob, $escape . ".+*?^$") == strlen($glob))
1693 // preg_replace cannot handle "\\\\\\2" so convert \\ to \xff
1694 $glob = strtr($glob, "\\", "\xff");
1695 $glob = str_replace("/", "\\/", $glob);
1696 // first convert some unescaped expressions to pcre style: . => \.
1698 $re = preg_replace('/([^\xff])?([' . preg_quote($special) . '])/',
1699 "\\1\xff\\2", $glob);
1702 $re = preg_replace('/([^\xff])?\*/', '$1.*', $re);
1703 $re = preg_replace('/([^\xff])?\?/', '$1.', $re);
1704 if (!preg_match('/^[\?\*]/', $glob))
1706 if (!preg_match('/[\?\*]$/', $glob))
1709 // Fixes Bug 1182997
1710 // .*? handled above, now escape the rest
1711 //while (strcspn($re, $escape) != strlen($re)) // loop strangely needed
1712 $re = preg_replace('/([^\xff])([' . preg_quote($escape, "/") . '])/',
1714 // Problem with 'Date/Time' => 'Date\/Time' => 'Date\xff\/Time' => 'Date\/Time'
1716 $re = preg_replace('/\xff/', '', $re);
1720 function glob_match($glob, $against, $case_sensitive = true)
1722 return preg_match('/' . glob_to_pcre($glob) . ($case_sensitive ? '/' : '/i'),
1726 function explodeList($input, $allnames, $glob_style = true, $case_sensitive = true)
1728 $list = explode(',', $input);
1729 // expand wildcards from list of $allnames
1730 if (preg_match('/[\?\*]/', $input)) {
1731 // Optimizing loop invariants:
1732 // http://phplens.com/lens/php-book/optimizing-debugging-php.php
1733 for ($i = 0, $max = sizeof($list); $i < $max; $i++) {
1735 if (preg_match('/[\?\*]/', $f)) {
1737 $expand = new ListRegexExpand($list,
1738 $glob_style ? glob_to_pcre($f) : $f, $case_sensitive);
1739 $expand->expandRegex($i, $allnames);
1746 // echo implode(":",explodeList("Test*",array("xx","Test1","Test2")));
1747 function explodePageList($input, $include_empty = false, $sortby = 'pagename',
1748 $limit = '', $exclude = '')
1750 include_once 'lib/PageList.php';
1751 return PageList::explodePageList($input, $include_empty, $sortby, $limit, $exclude);
1754 // Class introspections
1757 * Determine whether object is of a specified type.
1758 * In PHP builtin since 4.2.0 as is_a()
1759 * is_a() deprecated in PHP 5, in favor of instanceof operator
1760 * @param $object object An object.
1761 * @param $class string Class name.
1762 * @return bool True iff $object is a $class
1763 * or a sub-type of $class.
1765 function isa($object, $class)
1768 return is_object($object)
1769 && (strtolower(get_class($object)) == strtolower($class)
1770 || is_subclass_of($object, $lclass));
1773 /** Determine whether a function is okay to use.
1775 * Some providers (e.g. Lycos) disable some of PHP functions for
1776 * "security reasons." This makes those functions, of course,
1777 * unusable, despite the fact the function_exists() says they
1780 * This function test to see if a function exists and is not
1781 * disallowed by PHP's disable_functions config setting.
1783 * @param string $function_name Function name
1784 * @return bool True iff function can be used.
1786 function function_usable($function_name)
1789 if (!is_array($disabled)) {
1790 $disabled = array();
1791 // Use get_cfg_var since ini_get() is one of the disabled functions
1792 // (on Lycos, at least.)
1793 $split = preg_split('/\s*,\s*/', trim(get_cfg_var('disable_functions')));
1794 foreach ($split as $f)
1795 $disabled[strtolower($f)] = true;
1798 return (function_exists($function_name)
1799 and !isset($disabled[strtolower($function_name)])
1805 * This is used for generating ETags.
1807 function wikihash($x)
1809 if (is_scalar($x)) {
1811 } elseif (is_array($x)) {
1813 return md5(serialize($x));
1814 } elseif (is_object($x)) {
1817 trigger_error("Can't hash $x", E_USER_ERROR);
1821 * Seed the random number generator.
1823 * better_srand() ensures the randomizer is seeded only once.
1825 * How random do you want it? See:
1826 * http://www.php.net/manual/en/function.srand.php
1827 * http://www.php.net/manual/en/function.mt-srand.php
1829 function better_srand($seed = '')
1831 static $wascalled = FALSE;
1833 $seed = $seed === '' ? (double)microtime() * 1000000 : $seed;
1834 function_exists('mt_srand') ? mt_srand($seed) : srand($seed);
1836 //trigger_error("new random seed", E_USER_NOTICE); //debugging
1840 function rand_ascii($length = 1)
1844 for ($i = 1; $i <= $length; $i++) {
1845 // return only typeable 7 bit ascii, avoid quotes
1846 if (function_exists('mt_rand'))
1847 $s .= chr(mt_rand(40, 126));
1849 // the usually bad glibc srand()
1850 $s .= chr(rand(40, 126));
1855 /* by Dan Frankowski.
1857 function rand_ascii_readable($length = 6)
1859 // Pick a few random letters or numbers
1862 // Don't use 1lI0O, because they're hard to read
1863 $letters = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789";
1864 $letter_len = strlen($letters);
1865 for ($i = 0; $i < $length; $i++) {
1866 if (function_exists('mt_rand'))
1867 $word .= $letters[mt_rand(0, $letter_len - 1)];
1869 $word .= $letters[rand(0, $letter_len - 1)];
1875 * Recursively count all non-empty elements
1876 * in array of any dimension or mixed - i.e.
1877 * array('1' => 2, '2' => array('1' => 3, '2' => 4))
1878 * See http://www.php.net/manual/en/function.count.php
1880 function count_all($arg)
1882 // skip if argument is empty
1884 //print_r($arg); //debugging
1886 // not an array, return 1 (base case)
1887 if (!is_array($arg))
1889 // else call recursively for all elements $arg
1890 foreach ($arg as $key => $val)
1891 $count += count_all($val);
1896 function isSubPage($pagename)
1898 return (strstr($pagename, SUBPAGE_SEPARATOR));
1901 function subPageSlice($pagename, $pos)
1903 $pages = explode(SUBPAGE_SEPARATOR, $pagename);
1904 $pages = array_slice($pages, $pos, 1);
1908 function isActionPage($filename)
1911 global $AllActionPages;
1913 $localizedAllActionPages = array_map("__", $AllActionPages);
1915 return (in_array($filename, $localizedAllActionPages));
1921 * Class for "popping up" and alert box. (Except that right now, it doesn't
1925 * This is a hackish and needs to be refactored. However it would be nice to
1926 * unify all the different methods we use for showing Alerts and Dialogs.
1927 * (E.g. "Page deleted", login form, ...)
1933 * @param object $request
1934 * @param mixed $head Header ("title") for alert box.
1935 * @param mixed $body The text in the alert box.
1936 * @param hash $buttons An array mapping button labels to URLs.
1937 * The default is a single "Okay" button pointing to $request->getURLtoSelf().
1939 function Alert($head, $body, $buttons = false)
1941 if ($buttons === false)
1944 if (is_array($body)) {
1946 foreach ($body as $li) {
1947 $html->pushContent(HTML::li($li));
1951 $this->_tokens = array('HEADER' => $head, 'CONTENT' => $body);
1952 $this->_buttons = $buttons;
1956 * Show the alert box.
1962 $tokens = $this->_tokens;
1963 $tokens['BUTTONS'] = $this->_getButtons();
1965 $request->discardOutput();
1966 $tmpl = new Template('dialog', $request, $tokens);
1971 function _getButtons()
1975 $buttons = $this->_buttons;
1977 $buttons = array(_("OK") => $request->getURLtoSelf());
1980 foreach ($buttons as $label => $url)
1981 print "$label $url\n";
1982 $out[] = $WikiTheme->makeButton($label, $url, 'wikiaction');
1983 return new XmlContent($out);
1988 // 1.3.9-p1 => 1030.091
1989 // 1.3.10pre => 1030.099
1990 // 1.3.11pre-20041120 => 1030.1120041120
1991 // 1.3.12-rc1 => 1030.119
1992 function phpwiki_version()
1994 static $PHPWIKI_VERSION;
1995 if (!isset($PHPWIKI_VERSION)) {
1996 $arr = explode('.', preg_replace('/\D+$/', '', PHPWIKI_VERSION)); // remove the pre
1997 $arr[2] = preg_replace('/\.+/', '.', preg_replace('/\D/', '.', $arr[2]));
1998 $PHPWIKI_VERSION = $arr[0] * 1000 + $arr[1] * 10 + 0.01 * $arr[2];
1999 if (strstr(PHPWIKI_VERSION, 'pre') or strstr(PHPWIKI_VERSION, 'rc'))
2000 $PHPWIKI_VERSION -= 0.01;
2002 return $PHPWIKI_VERSION;
2005 function phpwiki_gzhandler($ob)
2007 if (function_exists('gzencode'))
2008 $ob = gzencode($ob);
2009 $GLOBALS['request']->_ob_get_length = strlen($ob);
2010 if (!headers_sent()) {
2011 header(sprintf("Content-Length: %d", $GLOBALS['request']->_ob_get_length));
2016 function isWikiWord($word)
2018 global $WikiNameRegexp;
2019 //or preg_match('/\A' . $WikiNameRegexp . '\z/', $word) ??
2020 return preg_match("/^$WikiNameRegexp\$/", $word);
2023 // needed to store serialized objects-values only (perm, pref)
2024 function obj2hash($obj, $exclude = false, $fields = false)
2027 if (!$fields) $fields = get_object_vars($obj);
2028 foreach ($fields as $key => $val) {
2029 if (is_array($exclude)) {
2030 if (in_array($key, $exclude)) continue;
2038 * isAsciiString($string)
2040 function isAsciiString($s)
2042 $ptrASCII = '[\x00-\x7F]';
2043 return preg_match("/^($ptrASCII)*$/s", $s);
2047 * isUtf8String($string) - cheap utf-8 detection
2049 * segfaults for strings longer than 10kb!
2050 * Use http://www.phpdiscuss.com/article.php?id=565&group=php.i18n or
2051 * checkTitleEncoding() at http://cvs.sourceforge.net/viewcvs.py/wikipedia/phase3/languages/Language.php
2053 function isUtf8String($s)
2055 $ptrASCII = '[\x00-\x7F]';
2056 $ptr2Octet = '[\xC2-\xDF][\x80-\xBF]';
2057 $ptr3Octet = '[\xE0-\xEF][\x80-\xBF]{2}';
2058 $ptr4Octet = '[\xF0-\xF4][\x80-\xBF]{3}';
2059 $ptr5Octet = '[\xF8-\xFB][\x80-\xBF]{4}';
2060 $ptr6Octet = '[\xFC-\xFD][\x80-\xBF]{5}';
2061 return preg_match("/^($ptrASCII|$ptr2Octet|$ptr3Octet|$ptr4Octet|$ptr5Octet|$ptr6Octet)*$/s", $s);
2065 * Check for UTF-8 URLs; Internet Explorer produces these if you
2066 * type non-ASCII chars in the URL bar or follow unescaped links.
2067 * Requires urldecoded pagename.
2068 * Fixes sf.net bug #953949
2070 * src: languages/Language.php:checkTitleEncoding() from mediawiki
2072 function fixTitleEncoding($s)
2078 * Workaround for allow_url_fopen, to get the content of an external URI.
2079 * It returns the contents in one slurp. Parsers might want to check for allow_url_fopen
2080 * and use fopen, fread chunkwise. (see lib/XmlParser.php)
2082 function url_get_contents($uri)
2084 if (get_cfg_var('allow_url_fopen')) { // was ini_get('allow_url_fopen'))
2085 return @file_get_contents($uri);
2087 require_once 'lib/HttpClient.php';
2088 $bits = parse_url($uri);
2089 $host = $bits['host'];
2090 $port = isset($bits['port']) ? $bits['port'] : 80;
2091 $path = isset($bits['path']) ? $bits['path'] : '/';
2092 if (isset($bits['query'])) {
2093 $path .= '?' . $bits['query'];
2095 $client = new HttpClient($host, $port);
2096 $client->use_gzip = false;
2097 if (!$client->get($path)) {
2100 return $client->getContent();
2106 * Generate consecutively named strings:
2107 * Name, Name2, Name3, ...
2109 function GenerateId($name)
2111 static $ids = array();
2112 if (empty($ids[$name])) {
2117 return $name . $ids[$name];
2121 // from IncludePage. To be of general use.
2122 // content: string or array of strings
2123 function firstNWordsOfContent($n, $content)
2125 if ($content and $n > 0) {
2126 if (is_array($content)) {
2127 // fixme: return a list of lines then?
2128 //$content = join("\n", $content);
2129 //$return_array = true;
2131 foreach ($content as $line) {
2132 $words = explode(' ', $line);
2133 if ($wordcount + count($words) > $n) {
2134 $new[] = implode(' ', array_slice($words, 0, $n - $wordcount))
2135 . sprintf(_("... (first %s words)"), $n);
2138 $wordcount += count($words);
2144 // fixme: use better whitespace/word seperators
2145 $words = explode(' ', $content);
2146 if (count($words) > $n) {
2147 return join(' ', array_slice($words, 0, $n))
2148 . sprintf(_("... (first %s words)"), $n);
2158 // moved from lib/plugin/IncludePage.php
2159 function extractSection($section, $content, $page, $quiet = false, $sectionhead = false)
2161 $qsection = preg_replace('/\s+/', '\s+', preg_quote($section, '/'));
2163 if (preg_match("/ ^(!{1,}|={2,})\\s*$qsection\s*=*" // section header
2164 . " \\s*$\\n?" // possible blank lines
2165 . " ( (?: ^.*\\n? )*? )" // some lines
2166 . " (?= ^\\1 | \\Z)/xm", // sec header (same or higher level) (or EOF)
2167 implode("\n", $content),
2170 // Strip trailing blanks lines and ---- <hr>s
2171 $text = preg_replace("/\\s*^-{4,}\\s*$/m", "", $match[2]);
2173 $text = $match[1] . $section . "\n" . $text;
2174 return explode("\n", $text);
2177 $mesg = $page . " " . $section;
2180 return array(sprintf(_("<%s: no such section>"), $mesg));
2183 // Extract the first $sections sections of the page
2184 function extractSections($sections, $content, $page, $quiet = false, $sectionhead = false)
2187 $mycontent = $content;
2190 while ($sections > 0) {
2192 if (preg_match("/ ^(!{1,}|={2,})\\s*(.*)\\n" // section header
2193 . " \\s*$\\n?" // possible blank lines
2194 . " ( (?: ^.*\\n? )*? )" // some lines
2195 . " ( ^\\1 (.|\\n)* | \\Z)/xm", // sec header (same or higher level) (or EOF)
2196 implode("\n", $mycontent),
2199 $section = $match[2];
2200 // Strip trailing blanks lines and ---- <hr>s
2201 $text = preg_replace("/\\s*^-{4,}\\s*$/m", "", $match[3]);
2203 $text = $match[1] . $section . "\n" . $text;
2206 $mycontent = explode("\n", $match[4]);
2208 if ($sections === 0) {
2209 return explode("\n", $result);
2215 // use this faster version: only load ExternalReferrer if we came from an external referrer
2216 function isExternalReferrer(&$request)
2218 if ($referrer = $request->get('HTTP_REFERER')) {
2219 $home = SERVER_URL; // SERVER_URL or SCRIPT_NAME, if we want to check sister wiki's also
2220 if (string_starts_with(strtolower($referrer), strtolower($home))) return false;
2221 require_once 'lib/ExternalReferrer.php';
2222 $se = new SearchEngines();
2223 return $se->parseSearchQuery($referrer);
2225 //if (DEBUG) return array('query' => 'wiki');
2230 * Useful for PECL overrides: cvsclient, ldap, soap, xmlrpc, pdo, pdo_<driver>
2232 function loadPhpExtension($extension)
2234 if (!extension_loaded($extension)) {
2235 $isWindows = (substr(PHP_OS, 0, 3) == 'WIN');
2236 $soname = ($isWindows ? 'php_' : '')
2238 . ($isWindows ? '.dll' : '.so');
2242 return extension_loaded($extension);
2245 function charset_convert($from, $to, $data)
2247 if (strtolower($from) == 'utf-8' and strtolower($to) == 'iso-8859-1')
2248 return utf8_decode($data);
2249 if (strtolower($to) == 'utf-8' and strtolower($from) == 'iso-8859-1')
2250 return utf8_encode($data);
2252 if (loadPhpExtension("iconv")) {
2253 $tmpdata = iconv($from, $to, $data);
2255 trigger_error("charset conversion $from => $to failed. Wrong source charset?", E_USER_WARNING);
2259 trigger_error("The iconv extension cannot be loaded", E_USER_WARNING);
2264 function string_starts_with($string, $prefix)
2266 return (substr($string, 0, strlen($prefix)) == $prefix);
2269 function string_ends_with($string, $suffix)
2271 return (substr($string, -strlen($suffix)) == $suffix);
2274 function array_remove($arr, $value)
2276 return array_values(array_diff($arr, array($value)));
2280 * Ensure that the script will have another $secs time left.
2281 * Works only if safe_mode is off.
2282 * For example not to timeout on waiting socket connections.
2283 * Use the socket timeout as arg.
2285 function longer_timeout($secs = 30)
2287 $timeout = @ini_get("max_execution_time") ? ini_get("max_execution_time") : 30;
2288 $timeleft = $timeout - $GLOBALS['RUNTIMER']->getTime();
2289 if ($timeleft < $secs)
2290 @set_time_limit(max($timeout, (integer)($secs + $timeleft)));
2293 function printSimpleTrace($bt)
2296 echo "\nTraceback:\n";
2297 if (function_exists('debug_print_backtrace')) { // >= 5
2298 debug_print_backtrace();
2300 foreach ($bt as $i => $elem) {
2301 if (!array_key_exists('file', $elem)) {
2304 //echo join(" ",array_values($elem)),"\n";
2305 echo " ", $elem['file'], ':', $elem['line'], " ", $elem['function'], "\n";
2311 * Return the used process memory, in bytes.
2312 * Enable the section which will work for you. They are very slow.
2313 * Special quirks for Windows: Requires cygwin.
2315 function getMemoryUsage()
2317 //if (!(DEBUG & _DEBUG_VERBOSE)) return;
2318 if (function_exists('memory_get_usage') and memory_get_usage()) {
2319 return memory_get_usage();
2320 } elseif (function_exists('getrusage') and ($u = @getrusage()) and !empty($u['ru_maxrss'])) {
2321 $mem = $u['ru_maxrss'];
2322 } elseif (substr(PHP_OS, 0, 3) == 'WIN') { // may require a newer cygwin
2323 // what we want is the process memory only: apache or php (if CGI)
2326 // win32_ps_stat_proc, win32_ps_stat_mem
2327 if (function_exists('win32_ps_list_procs')) {
2328 $info = win32_ps_stat_proc($pid);
2329 $memstr = $info['mem']['working_set_size'];
2331 // This works only if it's a cygwin process (apache or php).
2332 // Requires a newer cygwin
2333 $memstr = exec("cat /proc/$pid/statm |cut -f1");
2335 // if it's native windows use something like this:
2336 // (requires pslist from sysinternals.com, grep, sed and perl)
2337 //$memstr = exec("pslist $pid|grep -A1 Mem|sed 1d|perl -ane\"print \$"."F[5]\"");
2339 return (integer)trim($memstr);
2342 //%MEM: Percentage of total memory in use by this process
2343 //VSZ: Total virtual memory size, in 1K blocks.
2344 //RSS: Real Set Size, the actual amount of physical memory allocated to this process.
2345 //CPU time used by process since it started.
2346 //echo "%",`ps -o%mem,vsz,rss,time -p $pid|sed 1d`,"\n";
2347 $memstr = exec("ps -orss -p $pid|sed 1d");
2348 return (integer)trim($memstr);
2353 * @param var $needle
2354 * @param array $haystack one-dimensional numeric array only, no hash
2356 * @desc Feed a sorted array to $haystack and a value to search for to $needle.
2357 It will return false if not found or the index where it was found.
2358 From dennis.decoene@moveit.be http://www.php.net/array_search
2360 function binary_search($needle, $haystack)
2362 $high = count($haystack);
2365 while (($high - $low) > 1) {
2366 $probe = floor(($high + $low) / 2);
2367 if ($haystack[$probe] < $needle) {
2369 } elseif ($haystack[$probe] == $needle) {
2370 $high = $low = $probe;
2376 if ($high == count($haystack) || $haystack[$high] != $needle) {
2383 function is_localhost()
2385 return $_SERVER['SERVER_ADDR'] == '127.0.0.1';
2389 * Take a string and quote it sufficiently to be passed as a Javascript
2390 * string between ''s
2392 function javascript_quote_string($s)
2394 return str_replace("'", "\'", $s);
2397 function isSerialized($s)
2399 return (!empty($s) and (strlen($s) > 3) and (substr($s, 1, 1) == ':'));
2403 * Determine if a variable represents a whole number
2406 function is_whole_number($var)
2408 return (is_numeric($var) && (intval($var) == floatval($var)));
2412 * Take a string and return an array of pairs (attribute name, attribute value)
2414 * We allow attributes with or without double quotes (")
2415 * Attribute-value pairs may be separated by space or comma
2416 * Space is normal HTML attributes, comma is for RichTable compatibility
2417 * border=1, cellpadding="5"
2418 * border=1 cellpadding="5"
2419 * style="font-family: sans-serif; border-top:1px solid #dddddd;"
2420 * style="font-family: Verdana, Arial, Helvetica, sans-serif"
2422 function parse_attributes($line)
2427 if (empty($line)) return $options;
2428 $line = trim($line);
2429 if (empty($line)) return $options;
2430 $line = trim($line, ",");
2431 if (empty($line)) return $options;
2433 // First we have an attribute name.
2438 while (($i < strlen($line)) && ($line[$i] != '=')) {
2441 $attribute = substr($line, 0, $i);
2442 $attribute = strtolower($attribute);
2444 $line = substr($line, $i + 1);
2445 $line = trim($line);
2446 $line = trim($line, "=");
2447 $line = trim($line);
2449 if (empty($line)) return $options;
2451 // Then we have the attribute value.
2454 // Attribute value might be between double quotes
2455 // In that case we have to find the closing double quote
2456 if ($line[0] == '"') {
2457 $i++; // skip first '"'
2458 while (($i < strlen($line)) && ($line[$i] != '"')) {
2461 $value = substr($line, 0, $i);
2462 $value = trim($value, '"');
2463 $value = trim($value);
2465 // If there are no double quotes, we have to find the next space or comma
2467 while (($i < strlen($line)) && (($line[$i] != ' ') && ($line[$i] != ','))) {
2470 $value = substr($line, 0, $i);
2471 $value = trim($value);
2472 $value = trim($value, ",");
2473 $value = trim($value);
2476 $options[$attribute] = $value;
2478 $line = substr($line, $i + 1);
2479 $line = trim($line);
2480 $line = trim($line, ",");
2481 $line = trim($line);
2483 return $options + parse_attributes($line);
2487 * Returns true if the filename ends with an image suffix.
2488 * Uses INLINE_IMAGES if defined, else "png|jpg|jpeg|gif|swf"
2490 function is_image($filename)
2493 if (defined('INLINE_IMAGES')) {
2494 $inline_images = INLINE_IMAGES;
2496 $inline_images = "png|jpg|jpeg|gif|swf";
2499 foreach (explode("|", $inline_images) as $suffix) {
2500 if (string_ends_with(strtolower($filename), "." . $suffix)) {
2508 * Returns true if the filename ends with an video suffix.
2509 * Currently only FLV and OGG
2511 function is_video($filename)
2514 return string_ends_with(strtolower($filename), ".flv")
2515 or string_ends_with(strtolower($filename), ".ogg");
2519 * Remove accents from given text.
2521 function strip_accents($text)
2523 $res = utf8_decode($text);
2525 utf8_decode('àáâãäçèéêëìíîïñòóôõöùúûüýÿÀÁÂÃÄÇÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜÝ'),
2526 'aaaaaceeeeiiiinooooouuuuyyAAAAACEEEEIIIINOOOOOUUUUY');
2527 return utf8_encode($res);
2533 // c-basic-offset: 4
2534 // c-hanging-comment-ender-p: nil
2535 // indent-tabs-mode: nil