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 '.bb',
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)
143 return preg_replace('/[^-_:A-Za-z0-9]|(?<=^)[^A-Za-z]/e',
144 "'.' . sprintf('%02x', ord('\\0'))",
149 * Returns a name for the WIKI_ID cookie that should be unique on the host.
150 * But for it to be unique you must have set a unique WIKI_NAME in your
151 * configuration file.
152 * @return string The name of the WIKI_ID cookie to use for this wiki.
154 function getCookieName()
156 return preg_replace("/[^\d\w]/", "_", WIKI_NAME) . "_WIKI_ID";
160 * Generates a valid URL for a given Wiki pagename.
161 * @param mixed $pagename If a string this will be the name of the Wiki page to link to.
162 * If a WikiDB_Page object function will extract the name to link to.
163 * If a WikiDB_PageRevision object function will extract the name to link to.
165 * @param boolean $get_abs_url Default value is false.
166 * @return string The absolute URL to the page passed as $pagename.
168 function WikiURL($pagename, $args = '', $get_abs_url = false)
170 global $request, $WikiTheme;
173 if (is_object($pagename)) {
174 if (isa($pagename, 'WikiDB_Page')) {
175 $pagename = $pagename->getName();
176 } elseif (isa($pagename, 'WikiDB_PageRevision')) {
177 $page = $pagename->getPage();
178 $args['version'] = $pagename->getVersion();
179 $pagename = $page->getName();
180 } elseif (isa($pagename, 'WikiPageName')) {
181 $anchor = $pagename->anchor;
182 $pagename = $pagename->name;
184 $anchor = $pagename->anchor;
185 $pagename = $pagename->name;
188 if (!$get_abs_url and DEBUG and $request->getArg('start_debug')) {
190 $args = 'start_debug=' . $request->getArg('start_debug');
191 elseif (is_array($args))
192 $args['start_debug'] = $request->getArg('start_debug'); else
193 $args .= '&start_debug=' . $request->getArg('start_debug');
195 if (is_array($args)) {
197 foreach ($args as $key => $val) {
198 // avoid default args
199 if (USE_PATH_INFO and $key == 'pagename')
201 elseif ($key == 'action' and $val == 'browse')
202 ; elseif (!is_array($val)) // ugly hack for getURLtoSelf() which also takes POST vars
203 $enc_args[] = urlencode($key) . '=' . urlencode($val);
205 $args = join('&', $enc_args);
208 if (USE_PATH_INFO or !empty($WikiTheme->HTML_DUMP_SUFFIX)) {
209 $url = $get_abs_url ? (SERVER_URL . VIRTUAL_PATH . "/") : "";
210 $base = preg_replace('/%2f/i', '/', rawurlencode($pagename));
212 if (!empty($WikiTheme->HTML_DUMP_SUFFIX)) {
213 if (!empty($WikiTheme->VALID_LINKS) and $request->getArg('action') == 'pdf') {
214 if (!in_array($pagename, $WikiTheme->VALID_LINKS))
217 $url = $base . $WikiTheme->HTML_DUMP_SUFFIX;
219 $url .= $WikiTheme->HTML_DUMP_SUFFIX;
228 $url = $get_abs_url ? SERVER_URL . SCRIPT_NAME : basename(SCRIPT_NAME);
229 $url .= "?pagename=" . rawurlencode($pagename);
234 $url .= "#" . MangleXmlIdentifier($anchor);
238 /** Convert relative URL to absolute URL.
240 * This converts a relative URL to one of PhpWiki's support files
241 * to an absolute one.
244 * @return string Absolute URL
246 function AbsoluteURL($url)
248 if (preg_match('/^https?:/', $url))
250 if ($url[0] != '/') {
251 $base = USE_PATH_INFO ? VIRTUAL_PATH : dirname(SCRIPT_NAME);
252 while ($base != '/' and substr($url, 0, 3) == "../") {
253 $url = substr($url, 3);
254 $base = dirname($base);
260 return SERVER_URL . $url;
263 function DataURL($url)
265 if (preg_match('/^https?:/', $url))
267 $url = NormalizeWebFileName($url);
268 if (DEBUG and $GLOBALS['request']->getArg('start_debug') and substr($url, -4, 4) == '.php')
269 $url .= "?start_debug=1"; // XMLRPC and SOAP debugging helper.
270 return AbsoluteURL($url);
274 * Generates icon in front of links.
276 * @param string $protocol_or_url URL or protocol to determine which icon to use.
278 * @return HtmlElement HtmlElement object that contains data to create img link to
279 * icon for use with url or protocol passed to the function. False if no img to be
282 function IconForLink($protocol_or_url)
285 if (0 and $filename_suffix == false) {
286 // display apache style icon for file type instead of protocol icon
287 // - archive: unix:gz,bz2,tgz,tar,z; mac:dmg,dmgz,bin,img,cpt,sit; pc:zip;
288 // - document: html, htm, text, txt, rtf, pdf, doc
289 // - non-inlined image: jpg,jpeg,png,gif,tiff,tif,swf,pict,psd,eps,ps
290 // - audio: mp3,mp2,aiff,aif,au
291 // - multimedia: mpeg,mpg,mov,qt
293 list ($proto) = explode(':', $protocol_or_url, 2);
294 $src = $WikiTheme->getLinkIconURL($proto);
296 return HTML::img(array('src' => $src, 'alt' => "", 'class' => 'linkicon'));
303 * Glue icon in front of or after text.
304 * Pref: 'noLinkIcons' - ignore icon if set
305 * WikiTheme: 'LinkIcons' - 'yes' at front
306 * - 'no' display no icon
307 * - 'front' display at left
308 * - 'after' display at right
310 * @param string $protocol_or_url Protocol or URL. Used to determine the
312 * @param string $text The text.
313 * @return XmlContent.
315 function PossiblyGlueIconToText($proto_or_url, $text)
317 global $request, $WikiTheme;
318 if ($request->getPref('noLinkIcons'))
320 $icon = IconForLink($proto_or_url);
323 if ($where = $WikiTheme->getLinkIconAttr()) {
324 if ($where == 'no') return $text;
325 if ($where != 'after') $where = 'front';
329 if ($where == 'after') {
330 // span the icon only to the last word (tie them together),
331 // to let the previous words wrap on line breaks.
332 if (!is_object($text)) {
333 preg_match('/^(\s*\S*)(\s*)$/', $text, $m);
334 list (, $prefix, $last_word) = $m;
339 $text = HTML::span(array('style' => 'white-space: nowrap'),
340 $last_word, HTML::Raw(' '), $icon);
342 $text = HTML($prefix, $text);
345 // span the icon only to the first word (tie them together),
346 // to let the next words wrap on line breaks
347 if (!is_object($text)) {
348 preg_match('/^\s*(\S*)(.*?)\s*$/', $text, $m);
349 list (, $first_word, $tail) = $m;
354 $text = HTML::span(array('style' => 'white-space: nowrap'),
357 $text = HTML($text, $tail);
362 * Determines if the url passed to function is safe, by detecting if the characters
363 * '<', '>', or '"' are present.
364 * Check against their urlencoded values also.
366 * @param string $url URL to check for unsafe characters.
367 * @return boolean True if same, false else.
369 function IsSafeURL($url)
371 return !preg_match('/([<>"])|(%3C)|(%3E)|(%22)/', $url);
375 * Generates an HtmlElement object to store data for a link.
377 * @param string $url URL that the link will point to.
378 * @param string $linktext Text to be displayed as link.
379 * @return HtmlElement HtmlElement object that contains data to construct an html link.
381 function LinkURL($url, $linktext = '')
383 // FIXME: Is this needed (or sufficient?)
384 if (!IsSafeURL($url)) {
385 $link = HTML::span(array('class' => 'error'), _('Bad URL -- remove all of <, >, "'));
389 $linktext = preg_replace("/mailto:/A", "", $url);
390 $args = array('href' => $url);
391 if (defined('EXTERNAL_LINK_TARGET')) // can also be set in the css
392 $args['target'] = (is_string(EXTERNAL_LINK_TARGET) and (EXTERNAL_LINK_TARGET != "")) ? EXTERNAL_LINK_TARGET : "_blank";
393 $link = HTML::a($args, PossiblyGlueIconToText($url, $linktext));
395 $link->setAttr('class', $linktext ? 'namedurl' : 'rawurl');
402 * Syntax: [image.png size=50% border=n align= hspace= vspace= width= height=]
403 * Disallows sizes which are too small.
404 * Spammers may use such (typically invisible) image attributes to raise their GoogleRank.
406 * Handle embeddable objects, like svg, class, vrml, swf, svgz, pdf, avi, wmv especially.
408 function LinkImage($url, $alt = "")
410 $force_img = "png|jpg|gif|jpeg|bmp|pl|cgi";
411 // Disallow tags in img src urls. Typical CSS attacks.
412 // FIXME: Is this needed (or sufficient?)
413 // FIXED: This was broken for moniker:TP30 test/image.png => url="moniker:TP30" attr="test/image.png"
415 // support new syntax: [prefix/image.jpg size=50% border=n]
420 $arr = explode(' ', $url);
421 if (!empty($arr)) $url = $arr[0];
422 if (!IsSafeURL($url)) {
423 $link = HTML::span(array('class' => 'error'), _('Bad URL for image -- remove all of <, >, "'));
426 // spaces in inline images must be %20 encoded!
427 $link = HTML::img(array('src' => $url));
429 // Extract attributes
430 $arr = parse_attributes(strstr($ori_url, " "));
431 foreach ($arr as $attr => $value) {
432 // These attributes take strings: lang, id, title, alt
433 if (($attr == "lang")
435 || ($attr == "title")
438 $link->setAttr($attr, $value);
439 } // align = bottom|middle|top|left|right
440 // we allow "center" as synonym for "middle"
441 elseif (($attr == "align")
442 && (($value == "bottom")
443 || ($value == "middle")
444 || ($value == "center")
446 || ($value == "left")
447 || ($value == "right"))
449 if ($value == "center") {
452 $link->setAttr($attr, $value);
453 } // These attributes take a number (pixels): border, hspace, vspace
454 elseif ((($attr == "border") || ($attr == "hspace") || ($attr == "vspace"))
455 && (is_numeric($value))
457 $link->setAttr($attr, (int)$value);
458 } // These attributes take a number (pixels) or a percentage: height, width
459 elseif ((($attr == "height") || ($attr == "width"))
460 && (preg_match('/\d+[%p]?x?/', $value))
462 $link->setAttr($attr, $value);
463 } // We allow size=50% and size=20x30
464 // We replace this with "width" and "height" HTML attributes
465 elseif ($attr == "size") {
466 if (preg_match('/(\d+%)/', $value, $m)) {
467 $link->setAttr('width', $m[1]);
468 $link->setAttr('height', $m[1]);
469 } elseif (preg_match('/(\d+)x(\d+)/', $value, $m)) {
470 $link->setAttr('width', $m[1]);
471 $link->setAttr('height', $m[2]);
474 $url = substr(strrchr($ori_url, "/"), 1);
475 $link = HTML::span(array('class' => 'error'),
476 sprintf(_("Invalid attribute %s=%s for image %s"),
477 $attr, $value, $url));
481 // Correct silently the most common error
482 if ($url != $ori_url and empty($arr) and !preg_match("/^http/", $url)) {
483 // space belongs to the path
484 $file = NormalizeLocalFileName($ori_url);
485 if (file_exists($file)) {
486 $link = HTML::img(array('src' => $ori_url));
488 sprintf(_("Invalid image link fixed %s => %s. Spaces must be quoted with %%20."),
489 $url, $ori_url), E_USER_WARNING);
490 } elseif (string_starts_with($ori_url, getUploadDataPath())) {
491 $file = substr($file, strlen(getUploadDataPath()));
492 $path = getUploadFilePath() . $file;
493 if (file_exists($path)) {
494 trigger_error(sprintf(_("Invalid image link fixed \"%s\" => \"%s\".\n Spaces must be quoted with %%20."),
495 $url, $ori_url), E_USER_WARNING);
496 $link->setAttr('src', getUploadDataPath() . $file);
501 if (!$link->getAttr('alt')) {
502 $link->setAttr('alt', $alt);
504 // Check width and height as spam countermeasure
505 if (($width = $link->getAttr('width')) and ($height = $link->getAttr('height'))) {
506 //$width = (int) $width; // px or % or other suffix
507 //$height = (int) $height;
508 if (($width < 3 and $height < 10) or
509 ($height < 3 and $width < 20) or
510 ($height < 7 and $width < 7)
512 $link = HTML::span(array('class' => 'error'),
513 _("Invalid image size"));
518 // Prepare for getimagesize($url)
519 // $url only valid for external urls, otherwise local path
520 if (DISABLE_GETIMAGESIZE)
522 elseif (!preg_match("/\.$force_img$/i", $url))
523 ; // only valid image extensions or scripts assumed to generate images
524 elseif (preg_match("/^http/", $url)) { // external url
525 $size = @getimagesize($url);
526 } else { // local file
527 if (file_exists($file = NormalizeLocalFileName($url))) { // here
528 $size = @getimagesize($file);
529 } elseif (file_exists(NormalizeLocalFileName(urldecode($url)))) {
530 $size = @getimagesize($file);
531 $link->setAttr('src', rawurldecode($url));
532 } elseif (string_starts_with($url, getUploadDataPath())) { // there
533 $file = substr($file, strlen(getUploadDataPath()));
534 $path = getUploadFilePath() . rawurldecode($file);
535 $size = @getimagesize($path);
536 $link->setAttr('src', getUploadDataPath() . rawurldecode($file));
537 } else { // elsewhere
539 $size = @getimagesize($request->get('DOCUMENT_ROOT') . urldecode($url));
545 if (($width < 3 and $height < 10)
546 or ($height < 3 and $width < 20)
547 or ($height < 7 and $width < 7)
549 $link = HTML::span(array('class' => 'error'),
550 _("Invalid image size"));
555 $link->setAttr('class', 'inlineimage');
557 /* Check for inlined objects. Everything allowed in INLINE_IMAGES besides
558 * png|jpg|gif|jpeg|bmp|pl|cgi. If no image it is an object to embed.
559 * Note: Allow cgi's (pl,cgi) returning images.
561 if (!preg_match("/\.(" . $force_img . ")/i", $ori_url)) {
562 // HTML::img(array('src' => $url, 'alt' => $alt, 'title' => $alt));
563 // => HTML::object(array('src' => $url)) ...;
564 return ImgObject($link, $ori_url);
570 * <object> / <embed> tags instead of <img> for all non-image extensions
572 * Called by LinkImage(), not directly.
573 * Syntax: [image.svg size=50% alt=image.gif border=n align= hspace= vspace= width= height=]
574 * Samples: [Upload:song.mp3 type=audio/mpeg width=200 height=10]
575 * $alt may be an alternate img
576 * TODO: Need to unify with WikiPluginCached::embedObject()
578 * Note that Safari 1.0 will crash with <object>, so use only <embed>
579 * http://www.alleged.org.uk/pdc/2002/svg-object.html
581 * Allowed object tags:
583 * DATA=URI (object data)
584 * CLASSID=URI (location of implementation)
585 * ARCHIVE=CDATA (archive files)
586 * CODEBASE=URI (base URI for CLASSID, DATA, ARCHIVE)
587 * WIDTH=Length (object width)
588 * HEIGHT=Length (object height)
589 * NAME=CDATA (name for form submission)
590 * USEMAP=URI (client-side image map)
591 * TYPE=ContentType (content-type of object)
592 * CODETYPE=ContentType (content-type of code)
593 * STANDBY=Text (message to show while loading)
594 * TABINDEX=NUMBER (position in tabbing order)
595 * DECLARE (do not instantiate object)
596 * The rest is added as <param name="" value="" /> tags
598 function ImgObject($img, $url)
600 // get the url args: data="sample.svgz" type="image/svg+xml" width="400" height="300"
601 $params = explode(",", "id,width,height,data,classid,archive,codebase,name,usemap,type," .
602 "codetype,standby,tabindex,declare");
603 if (is_array($url)) {
606 foreach ($args as $attr => $value) {
607 foreach ($params as $param) {
608 if ($param == $attr) {
609 $img->setAttr($param, $value);
610 if (isset($found[$param])) $found[$param]++;
611 else $found[$param] = 1;
616 // now all remaining args are added as <param> to the object
618 foreach ($args as $attr => $value) {
619 if (!isset($found[$attr])) {
620 $params[] = HTML::param(array('name' => $attr,
624 $url = $img->getAttr('src');
625 $force_img = "png|jpg|gif|jpeg|bmp";
626 if (!preg_match("/\.(" . $force_img . ")/i", $url)) {
627 $img->setAttr('src', false);
630 $args = explode(' ', $url);
631 if (count($args) >= 1) {
632 $url = array_shift($args);
634 foreach ($args as $attr) {
635 foreach ($params as $param) {
636 if (preg_match("/^$param=(\S+)$/i", $attr, $m)) {
637 $img->setAttr($param, $m[1]);
638 if (isset($found[$param])) $found[$param]++;
639 else $found[$param] = 1;
644 // now all remaining args are added as <param> to the object
646 foreach ($args as $attr) {
647 if (!isset($found[$attr]) and preg_match("/^(\S+)=(\S+)$/i", $attr, $m)) {
648 $params[] = HTML::param(array('name' => $m[1],
654 $type = $img->getAttr('type');
656 if (function_exists('mime_content_type') && file_exists($url)) {
657 $type = mime_content_type($url);
660 $object = HTML::object(array_merge($img->_attr,
661 array('type' => $type)), //'src' => $url
663 $object->setAttr('class', 'inlineobject');
665 foreach ($params as $param) $object->pushContent($param);
667 if (isBrowserSafari() and !isBrowserSafari(532)) { // recent chrome can do OBJECT
668 return HTML::embed($object->_attr, $object->_content);
670 $object->pushContent(HTML::embed($object->_attr));
678 $this->items = array();
684 $this->items[$this->size] = $item;
691 if ($this->size == 0) {
692 return false; // stack is empty
695 return $this->items[$this->size];
706 return $this->items[$this->size - 1];
713 // end class definition
715 function SplitQueryArgs($query_args = '')
717 // FIXME: use the arg-seperator which might not be &
718 $split_args = explode('&', $query_args);
720 while (list($key, $val) = each($split_args))
721 if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
722 $args[$m[1]] = $m[2];
726 function LinkPhpwikiURL($url, $text = '', $basepage = false)
730 if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m)) {
731 return HTML::span(array('class' => 'error'), _("BAD phpwiki: URL"));
735 $pagename = urldecode($m[1]);
738 if (empty($pagename) &&
739 preg_match('/^(diff|edit|links|info)=([^&]+)$/', $qargs, $m)
741 // Convert old style links (to not break diff links in
743 $pagename = urldecode($m[2]);
744 $args = array("action" => $m[1]);
746 $args = SplitQueryArgs($qargs);
749 if (empty($pagename))
750 $pagename = $GLOBALS['request']->getArg('pagename');
752 if (isset($args['action']) && $args['action'] == 'browse')
753 unset($args['action']);
756 if (empty($args['action']))
758 else if (is_safe_action($args['action']))
759 $class = 'wikiaction';
761 if (empty($args['action']) || is_safe_action($args['action']))
762 $class = 'wikiaction';
764 // Don't allow administrative links on unlocked pages.
765 $dbi = $GLOBALS['request']->getDbh();
766 $page = $dbi->getPage($basepage ? $basepage : $pagename);
767 if (!$page->get('locked'))
768 return HTML::span(array('class' => 'wikiunsafe'),
769 HTML::u(_("Lock page to enable link")));
770 $class = 'wikiadmin';
774 $text = HTML::span(array('class' => 'rawurl'), $url);
776 $wikipage = new WikiPageName($pagename);
777 if (!$wikipage->isValid()) {
779 return $WikiTheme->linkBadWikiWord($wikipage, $url);
782 return HTML::a(array('href' => WikiURL($pagename, $args),
788 * A class to assist in parsing wiki pagenames.
790 * Now with subpages and anchors, parsing and passing around
791 * pagenames is more complicated. This should help.
795 /** Short name for page.
797 * This is the value of $name passed to the constructor.
798 * (For use, e.g. as a default label for links to the page.)
802 /** The full page name.
804 * This is the full name of the page (without anchor).
810 * This is the referenced anchor within the page, or the empty string.
816 * @param mixed $name Page name.
817 * WikiDB_Page, WikiDB_PageRevision, or string.
818 * This can be a relative subpage name (like '/SubPage'),
819 * or can be the empty string to refer to the $basename.
821 * @param string $anchor For links to anchors in page.
823 * @param mixed $basename Page name from which to interpret
824 * relative or other non-fully-specified page names.
826 function WikiPageName($name, $basename = false, $anchor = false)
828 if (is_string($name)) {
829 $this->shortName = $name;
830 if (strstr($name, ':')) {
831 list($moniker, $shortName) = explode(":", $name, 2);
832 $map = getInterwikiMap(); // allow overrides to custom maps
833 if (isset($map->_map[$moniker])) {
834 $url = $map->_map[$moniker];
835 if (strstr($url, '%s'))
836 $url = sprintf($url, $shortName);
840 // expand Talk or User, but not to absolute urls!
841 if (strstr($url, '//')) {
842 if ($moniker == 'Talk')
843 $name = $name . SUBPAGE_SEPARATOR . _("Discussion");
844 elseif ($moniker == 'User')
849 $this->shortName = $shortName;
852 // FIXME: We should really fix the cause for "/PageName" in the WikiDB
853 if ($name == '' or $name[0] == SUBPAGE_SEPARATOR) {
855 $name = $this->_pagename($basename) . $name;
857 $name = $this->_normalize_bad_pagename($name);
858 $this->shortName = $name;
862 $name = $this->_pagename($name);
863 $this->shortName = $name;
866 $this->name = $this->_check($name);
867 $this->anchor = (string)$anchor;
878 if (!($tail = strrchr($name, SUBPAGE_SEPARATOR)))
880 return substr($name, 0, -strlen($tail));
883 function isValid($strict = false)
886 return !isset($this->_errors);
887 return (is_string($this->name) and $this->name != '');
890 function getWarnings()
893 if (isset($this->_warnings))
894 $warnings = array_merge($warnings, $this->_warnings);
895 if (isset($this->_errors))
896 $warnings = array_merge($warnings, $this->_errors);
900 return sprintf(_("“%s”: Bad page name: %s"),
901 $this->shortName, join(', ', $warnings));
904 function _pagename($page)
906 if (isa($page, 'WikiDB_Page'))
907 return $page->getName();
908 elseif (isa($page, 'WikiDB_PageRevision'))
909 return $page->getPageName(); elseif (isa($page, 'WikiPageName'))
911 // '0' or e.g. '1984' should be allowed though
912 if (!is_string($page) and !is_integer($page)) {
913 trigger_error(sprintf("Non-string pagename “%s” (%s)(%s)",
914 $page, gettype($page), get_class($page)),
917 //assert(is_string($page));
921 function _normalize_bad_pagename($name)
923 trigger_error("Bad pagename: " . $name, E_USER_WARNING);
925 // Punt... You really shouldn't get here.
928 return $request->getArg('pagename');
930 assert($name[0] == SUBPAGE_SEPARATOR);
931 $this->_errors[] = sprintf(_("Leading %s not allowed"), SUBPAGE_SEPARATOR);
932 return substr($name, 1);
936 * Compress internal white-space to single space character.
938 * This leads to problems with loading a foreign charset pagename,
939 * which cannot be deleted anymore, because unknown chars are compressed.
940 * So BEFORE importing a file _check must be done !!!
942 function _check($pagename)
944 // Compress internal white-space to single space character.
945 $pagename = preg_replace('/[\s\xa0]+/', ' ', $orig = $pagename);
946 if ($pagename != $orig)
947 $this->_warnings[] = _("White space converted to single space");
949 // Delete any control characters.
950 if (DATABASE_TYPE == 'cvs' or DATABASE_TYPE == 'file' or DATABASE_TYPE == 'flatfile') {
951 $pagename = preg_replace('/[\x00-\x1f\x7f\x80-\x9f]/', '', $orig = $pagename);
952 if ($pagename != $orig)
953 $this->_errors[] = _("Control characters not allowed");
956 // Strip leading and trailing white-space.
957 $pagename = trim($pagename);
960 while ($pagename and $pagename[0] == SUBPAGE_SEPARATOR)
961 $pagename = substr($pagename, 1);
962 if ($pagename != $orig)
963 $this->_errors[] = sprintf(_("Leading %s not allowed"), SUBPAGE_SEPARATOR);
965 // ";" is urlencoded, so safe from php arg-delim problems
966 /*if (strstr($pagename, ';')) {
967 $this->_warnings[] = _("';' is deprecated");
968 $pagename = str_replace(';', '', $pagename);
971 // not only for SQL, also to restrict url length
972 if (strlen($pagename) > MAX_PAGENAME_LENGTH) {
973 $pagename = substr($pagename, 0, MAX_PAGENAME_LENGTH);
974 $this->_errors[] = _("Page name too long");
977 // disallow some chars only on file and cvs
978 if ((DATABASE_TYPE == 'cvs'
979 or DATABASE_TYPE == 'file'
980 or DATABASE_TYPE == 'flatfile')
981 and preg_match('/(:|\.\.)/', $pagename, $m)
983 $this->_warnings[] = sprintf(_("Illegal chars %s removed"), $m[1]);
984 $pagename = str_replace('..', '', $pagename);
985 $pagename = str_replace(':', '', $pagename);
993 * Convert old page markup to new-style markup.
995 * @param string $text Old-style wiki markup.
997 * @param string $markup_type
999 * <dt><code>"block"</code> <dd>Convert all markup.
1000 * <dt><code>"inline"</code> <dd>Convert only inline markup.
1001 * <dt><code>"links"</code> <dd>Convert only link markup.
1004 * @return string New-style wiki markup.
1006 * @bugs Footnotes don't work quite as before (esp if there are
1007 * multiple references to the same footnote. But close enough,
1008 * probably for now....
1009 * @bugs Apache2 and IIS crash with OldTextFormattingRules or
1010 * AnciennesR%E8glesDeFormatage. (at the 2nd attempt to do the anchored block regex)
1011 * It only crashes with CreateToc so far, but other pages (not in pgsrc) are
1012 * also known to crash, even with Apache1.
1014 function ConvertOldMarkup($text, $markup_type = "block")
1021 // Trying to detect why the 2nd paragraph of OldTextFormattingRules or
1022 // AnciennesR%E8glesDeFormatage crashes.
1023 // It only crashes with CreateToc so far, but other pages (not in pgsrc) are
1024 // also known to crash, even with Apache1.
1025 $debug_skip = false;
1026 // I suspect this only to crash with Apache2 and IIS.
1027 if (in_array(php_sapi_name(), array('apache2handler', 'apache2filter', 'isapi'))
1028 and preg_match("/plugin CreateToc/", $text)
1030 trigger_error(_("The CreateTocPlugin is not yet old markup compatible! ")
1031 . _("Please remove the CreateToc line to be able to reformat this page to old markup. ")
1032 . _("Skipped."), E_USER_WARNING);
1034 //if (!DEBUG) return $text;
1039 /*****************************************************************
1040 * Conversions for inline markup:
1047 // escape escaped brackets
1051 // change ! escapes to ~'s.
1052 global $WikiNameRegexp, $request;
1053 $bang_esc[] = "(?:" . ALLOWED_PROTOCOLS . "):[^\s<>\[\]\"'()]*[^\s<>\[\]\"'(),.?]";
1054 // before 4.3.9 pcre had a memory release bug, which might hit us here. so be safe.
1055 $map = getInterwikiMap();
1056 if ($map_regex = $map->getRegexp())
1057 $bang_esc[] = $map_regex . ":[^\\s.,;?()]+"; // FIXME: is this really needed?
1058 $bang_esc[] = $WikiNameRegexp;
1059 $orig[] = '/!((?:' . join(')|(', $bang_esc) . '))/';
1062 $subs["links"] = array($orig, $repl);
1064 // Temporarily URL-encode pairs of underscores in links to hide
1065 // them from the re for bold markup.
1066 $orig[] = '/\[[^\[\]]*?__[^\[\]]*?\]/e';
1067 $repl[] = 'str_replace(\'__\', \'%5F%5F\', \'\\0\')';
1070 //$orig[] = '/<(?!\?plugin)|(?<!^)</m';
1073 // Convert footnote references.
1074 $orig[] = '/(?<=.)(?<!~)\[\s*(\d+)\s*\]/m';
1075 $repl[] = '#[|ftnt_ref_\\1]<sup>~[[\\1|#ftnt_\\1]~]</sup>';
1077 // Convert old style emphases to HTML style emphasis.
1078 $orig[] = '/__(.*?)__/';
1079 $repl[] = '<strong>\\1</strong>';
1080 $orig[] = "/''(.*?)''/";
1081 $repl[] = '<em>\\1</em>';
1083 // Escape nestled markup.
1084 $orig[] = '/^(?<=^|\s)[=_](?=\S)|(?<=\S)[=_*](?=\s|$)/m';
1087 // in old markup headings only allowed at beginning of line
1091 // Convert URL-encoded pairs of underscores in links back to
1092 // real underscores after bold markup has been converted.
1093 $orig = '/\[[^\[\]]*?%5F%5F[^\[\]]*?\]/e';
1094 $repl = 'str_replace(\'%5F%5F\', \'__\', \'\\0\')';
1096 $subs["inline"] = array($orig, $repl);
1098 /*****************************************************************
1099 * Patterns which match block markup constructs which take
1100 * special handling...
1104 $blockpats[] = '[ \t]+\S(?:.*\s*\n[ \t]+\S)*';
1106 $blockpats[] = '\|(?:.*\n\|)*';
1109 $blockpats[] = '[#*;]*(?:[*#]|;.*?:)';
1111 // Footnote definitions
1112 $blockpats[] = '\[\s*(\d+)\s*\]';
1116 $blockpats[] = '<\?plugin(?:-form)?\b.*\?>\s*$';
1120 $blockpats[] = '!{1,3}[^!]';
1122 removed .|\n in the anchor not to crash on /m because with /m "." already includes \n
1123 this breaks headings but it doesn't crash anymore (crash on non-cgi, non-cli only)
1125 $block_re = ('/\A((?:.|\n)*?)(^(?:'
1126 . join("|", $blockpats)
1131 if ($markup_type != "block") {
1132 list ($orig, $repl) = $subs[$markup_type];
1133 return preg_replace($orig, $repl, $text);
1135 list ($orig, $repl) = $subs['inline'];
1138 // php crashes here in the 2nd paragraph of OldTextFormattingRules,
1139 // AnciennesR%E8glesDeFormatage and more
1140 // See http://www.pcre.org/pcre.txt LIMITATIONS
1141 while (preg_match($block_re, $text, $m)) {
1142 $text = substr($text, strlen($m[0]));
1143 list (, $leading_text, $block) = $m;
1146 if (strchr(" \t", $block[0])) {
1148 $prefix = "<pre>\n";
1149 $suffix = "\n</pre>\n";
1150 } elseif ($block[0] == '|') {
1152 $prefix = "<?plugin OldStyleTable\n";
1154 } elseif (strchr("#*;", $block[0])) {
1155 // Old-style list item
1156 preg_match('/^([#*;]*)([*#]|;.*?:) */', $block, $m);
1157 list (, $ind, $bullet) = $m;
1158 $block = substr($block, strlen($m[0]));
1160 $indent = str_repeat(' ', strlen($ind));
1161 if ($bullet[0] == ';') {
1162 //$term = ltrim(substr($bullet, 1));
1163 //return $indent . $term . "\n" . $indent . ' ';
1164 $prefix = $ind . $bullet;
1166 $prefix = $indent . $bullet . ' ';
1167 } elseif ($block[0] == '[') {
1168 // Footnote definition
1169 preg_match('/^\[\s*(\d+)\s*\]/', $block, $m);
1171 $block = substr($block, strlen($m[0]));
1172 $prefix = "#[|ftnt_" . ${footnum} . "]~[[" . ${footnum} . "|#ftnt_ref_" . ${footnum} . "]~] ";
1173 } elseif ($block[0] == '<') {
1175 // HACK: no inline markup...
1178 } elseif ($block[0] == '!') {
1180 preg_match('/^!{1,3}/', $block, $m);
1182 $block = substr($block, strlen($m[0]));
1187 if ($leading_text) $leading_text = preg_replace($orig, $repl, $leading_text);
1188 if ($block) $block = preg_replace($orig, $repl, $block);
1189 $out .= $leading_text;
1194 return $out . preg_replace($orig, $repl, $text);
1199 * Expand tabs in string.
1201 * Converts all tabs to (the appropriate number of) spaces.
1203 * @param string $str
1204 * @param integer $tab_width
1207 function expand_tabs($str, $tab_width = 8)
1209 $split = explode("\t", $str);
1210 $tail = array_pop($split);
1212 foreach ($split as $hunk) {
1214 $pos = strlen(strrchr($expanded, "\n")) - 1;
1215 $expanded .= str_repeat(" ", ($tab_width - $pos % $tab_width));
1217 return substr($expanded, 1) . $tail;
1221 * Split WikiWords in page names.
1223 * It has been deemed useful to split WikiWords (into "Wiki Words") in
1224 * places like page titles. This is rumored to help search engines
1227 * @param $page string The page name.
1229 * @return string The split name.
1231 function SplitPagename($page)
1234 if (preg_match("/\s/", $page))
1235 return $page; // Already split --- don't split any more.
1237 // This algorithm is specialized for several languages.
1238 // (Thanks to Pierrick MEIGNEN)
1239 // Improvements for other languages welcome.
1242 // This mess splits between a lower-case letter followed by
1243 // either an upper-case or a numeral; except that it wont
1244 // split the prefixes 'Mc', 'De', or 'Di' off of their tails.
1245 switch ($GLOBALS['LANG']) {
1250 $RE[] = '/([[:lower:]])((?<!Mc|De|Di)[[:upper:]]|\d)/';
1253 $RE[] = '/([[:lower:]])((?<!Mc|Di)[[:upper:]]|\d)/';
1256 $sep = preg_quote(SUBPAGE_SEPARATOR, '/');
1257 // This the single-letter words 'I' and 'A' from any following
1258 // capitalized words.
1259 switch ($GLOBALS['LANG']) {
1261 $RE[] = "/(?<= |${sep}|^)([AI])([[:upper:]][[:lower:]])/";
1264 $RE[] = "/(?<= |${sep}|^)([À])([[:upper:]][[:lower:]])/";
1267 // Split at underscore
1268 $RE[] = '/(_)([[:alpha:]])/';
1269 $RE[] = '/([[:alpha:]])(_)/';
1270 // Split numerals from following letters.
1271 $RE[] = '/(\d)([[:alpha:]])/';
1272 // Split at subpage seperators. TBD in WikiTheme.php
1273 $RE[] = "/([^${sep}]+)(${sep})/";
1274 $RE[] = "/(${sep})([^${sep}]+)/";
1276 foreach ($RE as $key)
1280 foreach ($RE as $regexp) {
1281 $page = preg_replace($regexp, '\\1 \\2', $page);
1286 function NoSuchRevision(&$request, $page, $version)
1288 $html = HTML(HTML::h2(_("Revision Not Found")),
1289 HTML::p(fmt("I'm sorry. Version %d of %s is not in the database.",
1290 $version, WikiLink($page, 'auto'))));
1291 include_once 'lib/Template.php';
1292 GeneratePage($html, _("Bad Version"), $page->getCurrentRevision());
1297 * Get time offset for local time zone.
1299 * @param $time time_t Get offset for this time. Default: now.
1300 * @param $no_colon boolean Don't put colon between hours and minutes.
1301 * @return string Offset as a string in the format +HH:MM.
1303 function TimezoneOffset($time = false, $no_colon = false)
1305 if ($time === false)
1307 $secs = date('Z', $time);
1315 $colon = $no_colon ? '' : ':';
1316 $mins = intval(($secs + 30) / 60);
1317 return sprintf("%s%02d%s%02d",
1318 $sign, $mins / 60, $colon, $mins % 60);
1322 * Format time in ISO-8601 format.
1324 * @param $time time_t Time. Default: now.
1325 * @return string Date and time in ISO-8601 format.
1327 function Iso8601DateTime($time = false)
1329 if ($time === false)
1331 $tzoff = TimezoneOffset($time);
1332 $date = date('Y-m-d', $time);
1333 $time = date('H:i:s', $time);
1334 return $date . 'T' . $time . $tzoff;
1338 * Format time in RFC-2822 format.
1340 * @param $time time_t Time. Default: now.
1341 * @return string Date and time in RFC-2822 format.
1343 function Rfc2822DateTime($time = false)
1345 if ($time === false)
1347 return date('D, j M Y H:i:s ', $time) . TimezoneOffset($time, 'no colon');
1351 * Format time in RFC-1123 format.
1353 * @param $time time_t Time. Default: now.
1354 * @return string Date and time in RFC-1123 format.
1356 function Rfc1123DateTime($time = false)
1358 if ($time === false)
1360 return gmdate('D, d M Y H:i:s \G\M\T', $time);
1363 /** Parse date in RFC-1123 format.
1365 * According to RFC 1123 we must accept dates in the following
1368 * Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123
1369 * Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
1370 * Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format
1372 * (Though we're only allowed to generate dates in the first format.)
1374 function ParseRfc1123DateTime($timestr)
1376 $timestr = trim($timestr);
1377 if (preg_match('/^ \w{3},\s* (\d{1,2}) \s* (\w{3}) \s* (\d{4}) \s*'
1378 . '(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
1381 list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
1382 } elseif (preg_match('/^ \w+,\s* (\d{1,2})-(\w{3})-(\d{2}|\d{4}) \s*'
1383 . '(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
1386 list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
1387 if ($year < 70) $year += 2000;
1388 elseif ($year < 100) $year += 1900;
1389 } elseif (preg_match('/^\w+\s* (\w{3}) \s* (\d{1,2}) \s*'
1390 . '(\d\d):(\d\d):(\d\d) \s* (\d{4})$/ix',
1393 list(, $mon, $mday, $hh, $mm, $ss, $year) = $m;
1399 $time = strtotime("$mday $mon $year ${hh}:${mm}:${ss} GMT");
1401 return false; // failed
1406 * Format time to standard 'ctime' format.
1408 * @param $time time_t Time. Default: now.
1409 * @return string Date and time.
1411 function CTime($time = false)
1413 if ($time === false)
1415 return date("D M j H:i:s Y", $time);
1419 * Format number as kibibytes or bytes.
1420 * Short format is used for PageList
1421 * Long format is used in PageInfo
1423 * @param $bytes int. Default: 0.
1424 * @param $longformat bool. Default: false.
1425 * @return class FormattedText (XmlElement.php).
1427 function ByteFormatter($bytes = 0, $longformat = false)
1431 if ($bytes < 1024) {
1433 $size = fmt("%s B", $bytes);
1435 $size = fmt("%s bytes", $bytes);
1437 $kb = round($bytes / 1024, 1);
1439 $size = fmt("%s KiB", $kb);
1441 $size = fmt("%s KiB (%s bytes)", $kb, $bytes);
1447 * Internationalized printf.
1449 * This is essentially the same as PHP's built-in printf
1450 * with the following exceptions:
1452 * <li> It passes the format string through gettext().
1453 * <li> It supports the argument reordering extensions.
1460 * __printf("Differences between versions %s and %s of %s",
1461 * $new_link, $old_link, $page_link);
1464 * Then in locale/po/de.po, one can reorder the printf arguments:
1467 * msgid "Differences between %s and %s of %s."
1468 * msgstr "Der Unterschiedsergebnis von %3$s, zwischen %1$s und %2$s."
1471 * (Note that while PHP tries to expand $vars within double-quotes,
1472 * the values in msgstr undergo no such expansion, so the '$'s
1475 * One shouldn't use reordered arguments in the default format string.
1476 * Backslashes in the default string would be necessary to escape the
1477 * '$'s, and they'll cause all kinds of trouble....
1479 function __printf($fmt)
1481 $args = func_get_args();
1483 echo __vsprintf($fmt, $args);
1487 * Internationalized sprintf.
1489 * This is essentially the same as PHP's built-in printf with the
1490 * following exceptions:
1493 * <li> It passes the format string through gettext().
1494 * <li> It supports the argument reordering extensions.
1499 function __sprintf($fmt)
1501 $args = func_get_args();
1503 return __vsprintf($fmt, $args);
1507 * Internationalized vsprintf.
1509 * This is essentially the same as PHP's built-in printf with the
1510 * following exceptions:
1513 * <li> It passes the format string through gettext().
1514 * <li> It supports the argument reordering extensions.
1519 function __vsprintf($fmt, $args)
1521 $fmt = gettext($fmt);
1522 // PHP's sprintf doesn't support variable with specifiers,
1523 // like sprintf("%*s", 10, "x"); --- so we won't either.
1525 if (preg_match_all('/(?<!%)%(\d+)\$/x', $fmt, $m)) {
1526 // Format string has '%2$s' style argument reordering.
1527 // PHP doesn't support this.
1528 if (preg_match('/(?<!%)%[- ]?\d*[^- \d$]/x', $fmt))
1529 // literal variable name substitution only to keep locale
1530 // strings uncluttered
1531 trigger_error(sprintf(_("Can't mix “%s” with “%s” type format strings"),
1532 '%1\$s', '%s'), E_USER_WARNING); //php+locale error
1534 $fmt = preg_replace('/(?<!%)%\d+\$/x', '%', $fmt);
1537 // Reorder arguments appropriately.
1538 foreach ($m[1] as $argnum) {
1539 if ($argnum < 1 || $argnum > count($args))
1540 trigger_error(sprintf(_("%s: argument index out of range"),
1541 $argnum), E_USER_WARNING);
1542 $newargs[] = $args[$argnum - 1];
1547 // Not all PHP's have vsprintf, so...
1548 array_unshift($args, $fmt);
1549 return call_user_func_array('sprintf', $args);
1552 function file_mtime($filename)
1554 if ($stat = @stat($filename))
1560 function sort_file_mtime($a, $b)
1562 $ma = file_mtime($a);
1563 $mb = file_mtime($b);
1564 if (!$ma or !$mb or $ma == $mb) return 0;
1565 return ($ma > $mb) ? -1 : 1;
1571 * Build an array in $this->_fileList of files from $dirname.
1572 * Subdirectories are not traversed.
1574 * (This was a function LoadDir in lib/loadsave.php)
1575 * See also http://www.php.net/manual/en/function.readdir.php
1577 function getFiles($exclude = '', $sortby = '', $limit = '')
1579 $list = $this->_fileList;
1582 require_once 'lib/PageList.php';
1583 switch (Pagelist::sortby($sortby, 'db')) {
1584 case 'pagename ASC':
1586 case 'pagename DESC':
1587 $list = array_reverse($list);
1590 usort($list, 'sort_file_mtime');
1593 usort($list, 'sort_file_mtime');
1594 $list = array_reverse($list);
1599 return array_splice($list, 0, $limit);
1603 function _filenameSelector($filename)
1605 if (!$this->_pattern)
1608 if (!$this->_pcre_pattern)
1609 $this->_pcre_pattern = glob_to_pcre($this->_pattern);
1610 return preg_match('/' . $this->_pcre_pattern . ($this->_case ? '/' : '/i'),
1615 function fileSet($directory, $filepattern = false)
1617 $this->_fileList = array();
1618 $this->_pattern = $filepattern;
1620 $this->_pcre_pattern = glob_to_pcre($this->_pattern);
1622 $this->_case = !isWindows();
1623 $this->_pathsep = '/';
1625 if (empty($directory)) {
1626 trigger_error(sprintf(_("%s is empty."), 'directoryname'),
1628 return; // early return
1631 @ $dir_handle = opendir($dir = $directory);
1632 if (empty($dir_handle)) {
1633 trigger_error(sprintf(_("Unable to open directory “%s” for reading"),
1634 $dir), E_USER_NOTICE);
1635 return; // early return
1638 while ($filename = readdir($dir_handle)) {
1639 if ($filename[0] == '.' || filetype($dir . $this->_pathsep . $filename) != 'file')
1641 if ($this->_filenameSelector($filename)) {
1642 array_push($this->_fileList, "$filename");
1643 //trigger_error(sprintf(_("found file %s"), $filename),
1644 // E_USER_NOTICE); //debugging
1647 closedir($dir_handle);
1653 // expands a list containing regex's to its matching entries
1654 class ListRegexExpand
1656 public $match, $list, $index, $case_sensitive;
1657 function ListRegexExpand(&$list, $match, $case_sensitive = true)
1659 $this->match = $match;
1660 $this->list = &$list;
1661 $this->case_sensitive = $case_sensitive;
1662 //$this->index = false;
1665 function listMatchCallback($item, $key)
1667 $quoted = str_replace('/', '\/', $item);
1668 if (preg_match('/' . $this->match . ($this->case_sensitive ? '/' : '/i'),
1671 unset($this->list[$this->index]);
1672 $this->list[] = $item;
1676 function expandRegex($index, &$pages)
1678 $this->index = $index;
1679 array_walk($pages, array($this, 'listMatchCallback'));
1684 // Convert fileglob to regex style:
1685 // Convert some wildcards to pcre style, escape the rest
1686 // Escape . \\ + * ? [ ^ ] $ ( ) { } = ! < > | : /
1687 // Fixed bug #994994: "/" in $glob.
1688 function glob_to_pcre($glob)
1690 // check simple case: no need to escape
1691 $escape = '\[](){}=!<>|:/';
1692 if (strcspn($glob, $escape . ".+*?^$") == strlen($glob))
1694 // preg_replace cannot handle "\\\\\\2" so convert \\ to \xff
1695 $glob = strtr($glob, "\\", "\xff");
1696 $glob = str_replace("/", "\\/", $glob);
1697 // first convert some unescaped expressions to pcre style: . => \.
1699 $re = preg_replace('/([^\xff])?([' . preg_quote($special) . '])/',
1700 "\\1\xff\\2", $glob);
1703 $re = preg_replace('/([^\xff])?\*/', '$1.*', $re);
1704 $re = preg_replace('/([^\xff])?\?/', '$1.', $re);
1705 if (!preg_match('/^[\?\*]/', $glob))
1707 if (!preg_match('/[\?\*]$/', $glob))
1710 // Fixes Bug 1182997
1711 // .*? handled above, now escape the rest
1712 //while (strcspn($re, $escape) != strlen($re)) // loop strangely needed
1713 $re = preg_replace('/([^\xff])([' . preg_quote($escape, "/") . '])/',
1715 // Problem with 'Date/Time' => 'Date\/Time' => 'Date\xff\/Time' => 'Date\/Time'
1717 $re = preg_replace('/\xff/', '', $re);
1721 function glob_match($glob, $against, $case_sensitive = true)
1723 return preg_match('/' . glob_to_pcre($glob) . ($case_sensitive ? '/' : '/i'),
1727 function explodeList($input, $allnames, $glob_style = true, $case_sensitive = true)
1729 $list = explode(',', $input);
1730 // expand wildcards from list of $allnames
1731 if (preg_match('/[\?\*]/', $input)) {
1732 // Optimizing loop invariants:
1733 // http://phplens.com/lens/php-book/optimizing-debugging-php.php
1734 for ($i = 0, $max = sizeof($list); $i < $max; $i++) {
1736 if (preg_match('/[\?\*]/', $f)) {
1738 $expand = new ListRegexExpand($list,
1739 $glob_style ? glob_to_pcre($f) : $f, $case_sensitive);
1740 $expand->expandRegex($i, $allnames);
1747 // echo implode(":",explodeList("Test*",array("xx","Test1","Test2")));
1748 function explodePageList($input, $include_empty = false, $sortby = 'pagename',
1749 $limit = '', $exclude = '')
1751 include_once 'lib/PageList.php';
1752 return PageList::explodePageList($input, $include_empty, $sortby, $limit, $exclude);
1755 // Class introspections
1758 * Determine whether object is of a specified type.
1759 * In PHP builtin since 4.2.0 as is_a()
1760 * is_a() deprecated in PHP 5, in favor of instanceof operator
1761 * @param $object object An object.
1762 * @param $class string Class name.
1763 * @return bool True iff $object is a $class
1764 * or a sub-type of $class.
1766 function isa($object, $class)
1769 return is_object($object)
1770 && (strtolower(get_class($object)) == strtolower($class)
1771 || is_subclass_of($object, $lclass));
1774 /** Determine whether a function is okay to use.
1776 * Some providers (e.g. Lycos) disable some of PHP functions for
1777 * "security reasons." This makes those functions, of course,
1778 * unusable, despite the fact the function_exists() says they
1781 * This function test to see if a function exists and is not
1782 * disallowed by PHP's disable_functions config setting.
1784 * @param string $function_name Function name
1785 * @return bool True iff function can be used.
1787 function function_usable($function_name)
1790 if (!is_array($disabled)) {
1791 $disabled = array();
1792 // Use get_cfg_var since ini_get() is one of the disabled functions
1793 // (on Lycos, at least.)
1794 $split = preg_split('/\s*,\s*/', trim(get_cfg_var('disable_functions')));
1795 foreach ($split as $f)
1796 $disabled[strtolower($f)] = true;
1799 return (function_exists($function_name)
1800 and !isset($disabled[strtolower($function_name)])
1806 * This is used for generating ETags.
1808 function wikihash($x)
1810 if (is_scalar($x)) {
1812 } elseif (is_array($x)) {
1814 return md5(serialize($x));
1815 } elseif (is_object($x)) {
1818 trigger_error("Can't hash $x", E_USER_ERROR);
1822 * Seed the random number generator.
1824 * better_srand() ensures the randomizer is seeded only once.
1826 * How random do you want it? See:
1827 * http://www.php.net/manual/en/function.srand.php
1828 * http://www.php.net/manual/en/function.mt-srand.php
1830 function better_srand($seed = '')
1832 static $wascalled = FALSE;
1834 $seed = $seed === '' ? (double)microtime() * 1000000 : $seed;
1835 function_exists('mt_srand') ? mt_srand($seed) : srand($seed);
1837 //trigger_error("new random seed", E_USER_NOTICE); //debugging
1841 function rand_ascii($length = 1)
1845 for ($i = 1; $i <= $length; $i++) {
1846 // return only typeable 7 bit ascii, avoid quotes
1847 if (function_exists('mt_rand'))
1848 $s .= chr(mt_rand(40, 126));
1850 // the usually bad glibc srand()
1851 $s .= chr(rand(40, 126));
1856 /* by Dan Frankowski.
1858 function rand_ascii_readable($length = 6)
1860 // Pick a few random letters or numbers
1863 // Don't use 1lI0O, because they're hard to read
1864 $letters = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789";
1865 $letter_len = strlen($letters);
1866 for ($i = 0; $i < $length; $i++) {
1867 if (function_exists('mt_rand'))
1868 $word .= $letters[mt_rand(0, $letter_len - 1)];
1870 $word .= $letters[rand(0, $letter_len - 1)];
1876 * Recursively count all non-empty elements
1877 * in array of any dimension or mixed - i.e.
1878 * array('1' => 2, '2' => array('1' => 3, '2' => 4))
1879 * See http://www.php.net/manual/en/function.count.php
1881 function count_all($arg)
1883 // skip if argument is empty
1885 //print_r($arg); //debugging
1887 // not an array, return 1 (base case)
1888 if (!is_array($arg))
1890 // else call recursively for all elements $arg
1891 foreach ($arg as $key => $val)
1892 $count += count_all($val);
1897 function isSubPage($pagename)
1899 return (strstr($pagename, SUBPAGE_SEPARATOR));
1902 function subPageSlice($pagename, $pos)
1904 $pages = explode(SUBPAGE_SEPARATOR, $pagename);
1905 $pages = array_slice($pages, $pos, 1);
1909 function isActionPage($filename)
1912 global $AllActionPages;
1914 $localizedAllActionPages = array_map("__", $AllActionPages);
1916 return (in_array($filename, $localizedAllActionPages));
1922 * Class for "popping up" and alert box. (Except that right now, it doesn't
1926 * This is a hackish and needs to be refactored. However it would be nice to
1927 * unify all the different methods we use for showing Alerts and Dialogs.
1928 * (E.g. "Page deleted", login form, ...)
1934 * @param object $request
1935 * @param mixed $head Header ("title") for alert box.
1936 * @param mixed $body The text in the alert box.
1937 * @param hash $buttons An array mapping button labels to URLs.
1938 * The default is a single "Okay" button pointing to $request->getURLtoSelf().
1940 function Alert($head, $body, $buttons = false)
1942 if ($buttons === false)
1945 if (is_array($body)) {
1947 foreach ($body as $li) {
1948 $html->pushContent(HTML::li($li));
1952 $this->_tokens = array('HEADER' => $head, 'CONTENT' => $body);
1953 $this->_buttons = $buttons;
1957 * Show the alert box.
1963 $tokens = $this->_tokens;
1964 $tokens['BUTTONS'] = $this->_getButtons();
1966 $request->discardOutput();
1967 $tmpl = new Template('dialog', $request, $tokens);
1972 function _getButtons()
1976 $buttons = $this->_buttons;
1978 $buttons = array(_("OK") => $request->getURLtoSelf());
1981 foreach ($buttons as $label => $url)
1982 print "$label $url\n";
1983 $out[] = $WikiTheme->makeButton($label, $url, 'wikiaction');
1984 return new XmlContent($out);
1989 // 1.3.9-p1 => 1030.091
1990 // 1.3.10pre => 1030.099
1991 // 1.3.11pre-20041120 => 1030.1120041120
1992 // 1.3.12-rc1 => 1030.119
1993 function phpwiki_version()
1995 static $PHPWIKI_VERSION;
1996 if (!isset($PHPWIKI_VERSION)) {
1997 $arr = explode('.', preg_replace('/\D+$/', '', PHPWIKI_VERSION)); // remove the pre
1998 $arr[2] = preg_replace('/\.+/', '.', preg_replace('/\D/', '.', $arr[2]));
1999 $PHPWIKI_VERSION = $arr[0] * 1000 + $arr[1] * 10 + 0.01 * $arr[2];
2000 if (strstr(PHPWIKI_VERSION, 'pre') or strstr(PHPWIKI_VERSION, 'rc'))
2001 $PHPWIKI_VERSION -= 0.01;
2003 return $PHPWIKI_VERSION;
2006 function phpwiki_gzhandler($ob)
2008 if (function_exists('gzencode'))
2009 $ob = gzencode($ob);
2010 $GLOBALS['request']->_ob_get_length = strlen($ob);
2011 if (!headers_sent()) {
2012 header(sprintf("Content-Length: %d", $GLOBALS['request']->_ob_get_length));
2017 function isWikiWord($word)
2019 global $WikiNameRegexp;
2020 //or preg_match('/\A' . $WikiNameRegexp . '\z/', $word) ??
2021 return preg_match("/^$WikiNameRegexp\$/", $word);
2024 // needed to store serialized objects-values only (perm, pref)
2025 function obj2hash($obj, $exclude = false, $fields = false)
2028 if (!$fields) $fields = get_object_vars($obj);
2029 foreach ($fields as $key => $val) {
2030 if (is_array($exclude)) {
2031 if (in_array($key, $exclude)) continue;
2039 * isAsciiString($string)
2041 function isAsciiString($s)
2043 $ptrASCII = '[\x00-\x7F]';
2044 return preg_match("/^($ptrASCII)*$/s", $s);
2048 * isUtf8String($string) - cheap utf-8 detection
2050 * segfaults for strings longer than 10kb!
2051 * Use http://www.phpdiscuss.com/article.php?id=565&group=php.i18n or
2052 * checkTitleEncoding() at http://cvs.sourceforge.net/viewcvs.py/wikipedia/phase3/languages/Language.php
2054 function isUtf8String($s)
2056 $ptrASCII = '[\x00-\x7F]';
2057 $ptr2Octet = '[\xC2-\xDF][\x80-\xBF]';
2058 $ptr3Octet = '[\xE0-\xEF][\x80-\xBF]{2}';
2059 $ptr4Octet = '[\xF0-\xF4][\x80-\xBF]{3}';
2060 $ptr5Octet = '[\xF8-\xFB][\x80-\xBF]{4}';
2061 $ptr6Octet = '[\xFC-\xFD][\x80-\xBF]{5}';
2062 return preg_match("/^($ptrASCII|$ptr2Octet|$ptr3Octet|$ptr4Octet|$ptr5Octet|$ptr6Octet)*$/s", $s);
2066 * Check for UTF-8 URLs; Internet Explorer produces these if you
2067 * type non-ASCII chars in the URL bar or follow unescaped links.
2068 * Requires urldecoded pagename.
2069 * Fixes sf.net bug #953949
2071 * src: languages/Language.php:checkTitleEncoding() from mediawiki
2073 function fixTitleEncoding($s)
2079 * Workaround for allow_url_fopen, to get the content of an external URI.
2080 * It returns the contents in one slurp. Parsers might want to check for allow_url_fopen
2081 * and use fopen, fread chunkwise. (see lib/XmlParser.php)
2083 function url_get_contents($uri)
2085 if (get_cfg_var('allow_url_fopen')) { // was ini_get('allow_url_fopen'))
2086 return @file_get_contents($uri);
2088 require_once 'lib/HttpClient.php';
2089 $bits = parse_url($uri);
2090 $host = $bits['host'];
2091 $port = isset($bits['port']) ? $bits['port'] : 80;
2092 $path = isset($bits['path']) ? $bits['path'] : '/';
2093 if (isset($bits['query'])) {
2094 $path .= '?' . $bits['query'];
2096 $client = new HttpClient($host, $port);
2097 $client->use_gzip = false;
2098 if (!$client->get($path)) {
2101 return $client->getContent();
2107 * Generate consecutively named strings:
2108 * Name, Name2, Name3, ...
2110 function GenerateId($name)
2112 static $ids = array();
2113 if (empty($ids[$name])) {
2118 return $name . $ids[$name];
2122 // from IncludePage. To be of general use.
2123 // content: string or array of strings
2124 function firstNWordsOfContent($n, $content)
2126 if ($content and $n > 0) {
2127 if (is_array($content)) {
2128 // fixme: return a list of lines then?
2129 //$content = join("\n", $content);
2130 //$return_array = true;
2132 foreach ($content as $line) {
2133 $words = explode(' ', $line);
2134 if ($wordcount + count($words) > $n) {
2135 $new[] = implode(' ', array_slice($words, 0, $n - $wordcount))
2136 . sprintf(_("... (first %s words)"), $n);
2139 $wordcount += count($words);
2145 // fixme: use better whitespace/word seperators
2146 $words = explode(' ', $content);
2147 if (count($words) > $n) {
2148 return join(' ', array_slice($words, 0, $n))
2149 . sprintf(_("... (first %s words)"), $n);
2159 // moved from lib/plugin/IncludePage.php
2160 function extractSection($section, $content, $page, $quiet = false, $sectionhead = false)
2162 $qsection = preg_replace('/\s+/', '\s+', preg_quote($section, '/'));
2164 if (preg_match("/ ^(!{1,}|={2,})\\s*$qsection\s*=*" // section header
2165 . " \\s*$\\n?" // possible blank lines
2166 . " ( (?: ^.*\\n? )*? )" // some lines
2167 . " (?= ^\\1 | \\Z)/xm", // sec header (same or higher level) (or EOF)
2168 implode("\n", $content),
2171 // Strip trailing blanks lines and ---- <hr>s
2172 $text = preg_replace("/\\s*^-{4,}\\s*$/m", "", $match[2]);
2174 $text = $match[1] . $section . "\n" . $text;
2175 return explode("\n", $text);
2178 $mesg = $page . " " . $section;
2181 return array(sprintf(_("<%s: no such section>"), $mesg));
2184 // Extract the first $sections sections of the page
2185 function extractSections($sections, $content, $page, $quiet = false, $sectionhead = false)
2188 $mycontent = $content;
2191 while ($sections > 0) {
2193 if (preg_match("/ ^(!{1,}|={2,})\\s*(.*)\\n" // section header
2194 . " \\s*$\\n?" // possible blank lines
2195 . " ( (?: ^.*\\n? )*? )" // some lines
2196 . " ( ^\\1 (.|\\n)* | \\Z)/xm", // sec header (same or higher level) (or EOF)
2197 implode("\n", $mycontent),
2200 $section = $match[2];
2201 // Strip trailing blanks lines and ---- <hr>s
2202 $text = preg_replace("/\\s*^-{4,}\\s*$/m", "", $match[3]);
2204 $text = $match[1] . $section . "\n" . $text;
2207 $mycontent = explode("\n", $match[4]);
2209 if ($sections === 0) {
2210 return explode("\n", $result);
2216 // use this faster version: only load ExternalReferrer if we came from an external referrer
2217 function isExternalReferrer(&$request)
2219 if ($referrer = $request->get('HTTP_REFERER')) {
2220 $home = SERVER_URL; // SERVER_URL or SCRIPT_NAME, if we want to check sister wiki's also
2221 if (string_starts_with(strtolower($referrer), strtolower($home))) return false;
2222 require_once 'lib/ExternalReferrer.php';
2223 $se = new SearchEngines();
2224 return $se->parseSearchQuery($referrer);
2226 //if (DEBUG) return array('query' => 'wiki');
2231 * Useful for PECL overrides: cvsclient, ldap, soap, xmlrpc, pdo, pdo_<driver>
2233 function loadPhpExtension($extension)
2235 if (!extension_loaded($extension)) {
2236 $isWindows = (substr(PHP_OS, 0, 3) == 'WIN');
2237 $soname = ($isWindows ? 'php_' : '')
2239 . ($isWindows ? '.dll' : '.so');
2243 return extension_loaded($extension);
2246 function charset_convert($from, $to, $data)
2248 if (strtolower($from) == 'utf-8' and strtolower($to) == 'iso-8859-1')
2249 return utf8_decode($data);
2250 if (strtolower($to) == 'utf-8' and strtolower($from) == 'iso-8859-1')
2251 return utf8_encode($data);
2253 if (loadPhpExtension("iconv")) {
2254 $tmpdata = iconv($from, $to, $data);
2256 trigger_error("charset conversion $from => $to failed. Wrong source charset?", E_USER_WARNING);
2260 trigger_error("The iconv extension cannot be loaded", E_USER_WARNING);
2265 function string_starts_with($string, $prefix)
2267 return (substr($string, 0, strlen($prefix)) == $prefix);
2270 function string_ends_with($string, $suffix)
2272 return (substr($string, -strlen($suffix)) == $suffix);
2275 function array_remove($arr, $value)
2277 return array_values(array_diff($arr, array($value)));
2281 * Ensure that the script will have another $secs time left.
2282 * Works only if safe_mode is off.
2283 * For example not to timeout on waiting socket connections.
2284 * Use the socket timeout as arg.
2286 function longer_timeout($secs = 30)
2288 $timeout = @ini_get("max_execution_time") ? ini_get("max_execution_time") : 30;
2289 $timeleft = $timeout - $GLOBALS['RUNTIMER']->getTime();
2290 if ($timeleft < $secs)
2291 @set_time_limit(max($timeout, (integer)($secs + $timeleft)));
2294 function printSimpleTrace($bt)
2297 echo "\nTraceback:\n";
2298 if (function_exists('debug_print_backtrace')) { // >= 5
2299 debug_print_backtrace();
2301 foreach ($bt as $i => $elem) {
2302 if (!array_key_exists('file', $elem)) {
2305 //echo join(" ",array_values($elem)),"\n";
2306 echo " ", $elem['file'], ':', $elem['line'], " ", $elem['function'], "\n";
2312 * Return the used process memory, in bytes.
2313 * Enable the section which will work for you. They are very slow.
2314 * Special quirks for Windows: Requires cygwin.
2316 function getMemoryUsage()
2318 //if (!(DEBUG & _DEBUG_VERBOSE)) return;
2319 if (function_exists('memory_get_usage') and memory_get_usage()) {
2320 return memory_get_usage();
2321 } elseif (function_exists('getrusage') and ($u = @getrusage()) and !empty($u['ru_maxrss'])) {
2322 $mem = $u['ru_maxrss'];
2323 } elseif (substr(PHP_OS, 0, 3) == 'WIN') { // may require a newer cygwin
2324 // what we want is the process memory only: apache or php (if CGI)
2327 // win32_ps_stat_proc, win32_ps_stat_mem
2328 if (function_exists('win32_ps_list_procs')) {
2329 $info = win32_ps_stat_proc($pid);
2330 $memstr = $info['mem']['working_set_size'];
2332 // This works only if it's a cygwin process (apache or php).
2333 // Requires a newer cygwin
2334 $memstr = exec("cat /proc/$pid/statm |cut -f1");
2336 // if it's native windows use something like this:
2337 // (requires pslist from sysinternals.com, grep, sed and perl)
2338 //$memstr = exec("pslist $pid|grep -A1 Mem|sed 1d|perl -ane\"print \$"."F[5]\"");
2340 return (integer)trim($memstr);
2343 //%MEM: Percentage of total memory in use by this process
2344 //VSZ: Total virtual memory size, in 1K blocks.
2345 //RSS: Real Set Size, the actual amount of physical memory allocated to this process.
2346 //CPU time used by process since it started.
2347 //echo "%",`ps -o%mem,vsz,rss,time -p $pid|sed 1d`,"\n";
2348 $memstr = exec("ps -orss -p $pid|sed 1d");
2349 return (integer)trim($memstr);
2354 * @param var $needle
2355 * @param array $haystack one-dimensional numeric array only, no hash
2357 * @desc Feed a sorted array to $haystack and a value to search for to $needle.
2358 It will return false if not found or the index where it was found.
2359 From dennis.decoene@moveit.be http://www.php.net/array_search
2361 function binary_search($needle, $haystack)
2363 $high = count($haystack);
2366 while (($high - $low) > 1) {
2367 $probe = floor(($high + $low) / 2);
2368 if ($haystack[$probe] < $needle) {
2370 } elseif ($haystack[$probe] == $needle) {
2371 $high = $low = $probe;
2377 if ($high == count($haystack) || $haystack[$high] != $needle) {
2384 function is_localhost()
2386 return $_SERVER['SERVER_ADDR'] == '127.0.0.1';
2390 * Take a string and quote it sufficiently to be passed as a Javascript
2391 * string between ''s
2393 function javascript_quote_string($s)
2395 return str_replace("'", "\'", $s);
2398 function isSerialized($s)
2400 return (!empty($s) and (strlen($s) > 3) and (substr($s, 1, 1) == ':'));
2404 * Determine if a variable represents a whole number
2407 function is_whole_number($var)
2409 return (is_numeric($var) && (intval($var) == floatval($var)));
2413 * Take a string and return an array of pairs (attribute name, attribute value)
2415 * We allow attributes with or without double quotes (")
2416 * Attribute-value pairs may be separated by space or comma
2417 * Space is normal HTML attributes, comma is for RichTable compatibility
2418 * border=1, cellpadding="5"
2419 * border=1 cellpadding="5"
2420 * style="font-family: sans-serif; border-top:1px solid #dddddd;"
2421 * style="font-family: Verdana, Arial, Helvetica, sans-serif"
2423 function parse_attributes($line)
2428 if (empty($line)) return $options;
2429 $line = trim($line);
2430 if (empty($line)) return $options;
2431 $line = trim($line, ",");
2432 if (empty($line)) return $options;
2434 // First we have an attribute name.
2439 while (($i < strlen($line)) && ($line[$i] != '=')) {
2442 $attribute = substr($line, 0, $i);
2443 $attribute = strtolower($attribute);
2445 $line = substr($line, $i + 1);
2446 $line = trim($line);
2447 $line = trim($line, "=");
2448 $line = trim($line);
2450 if (empty($line)) return $options;
2452 // Then we have the attribute value.
2455 // Attribute value might be between double quotes
2456 // In that case we have to find the closing double quote
2457 if ($line[0] == '"') {
2458 $i++; // skip first '"'
2459 while (($i < strlen($line)) && ($line[$i] != '"')) {
2462 $value = substr($line, 0, $i);
2463 $value = trim($value, '"');
2464 $value = trim($value);
2466 // If there are no double quotes, we have to find the next space or comma
2468 while (($i < strlen($line)) && (($line[$i] != ' ') && ($line[$i] != ','))) {
2471 $value = substr($line, 0, $i);
2472 $value = trim($value);
2473 $value = trim($value, ",");
2474 $value = trim($value);
2477 $options[$attribute] = $value;
2479 $line = substr($line, $i + 1);
2480 $line = trim($line);
2481 $line = trim($line, ",");
2482 $line = trim($line);
2484 return $options + parse_attributes($line);
2488 * Returns true if the filename ends with an image suffix.
2489 * Uses INLINE_IMAGES if defined, else "png|jpg|jpeg|gif|swf"
2491 function is_image($filename)
2494 if (defined('INLINE_IMAGES')) {
2495 $inline_images = INLINE_IMAGES;
2497 $inline_images = "png|jpg|jpeg|gif|swf";
2500 foreach (explode("|", $inline_images) as $suffix) {
2501 if (string_ends_with(strtolower($filename), "." . $suffix)) {
2509 * Returns true if the filename ends with an video suffix.
2510 * Currently only FLV and OGG
2512 function is_video($filename)
2515 return string_ends_with(strtolower($filename), ".flv")
2516 or string_ends_with(strtolower($filename), ".ogg");
2520 * Remove accents from given text.
2522 function strip_accents($text)
2524 $res = utf8_decode($text);
2526 utf8_decode('àáâãäçèéêëìíîïñòóôõöùúûüýÿÀÁÂÃÄÇÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜÝ'),
2527 'aaaaaceeeeiiiinooooouuuuyyAAAAACEEEEIIIINOOOOOUUUUY');
2528 return utf8_encode($res);
2534 // c-basic-offset: 4
2535 // c-hanging-comment-ender-p: nil
2536 // indent-tabs-mode: nil