]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/stdlib.php
gettext --> __
[SourceForge/phpwiki.git] / lib / stdlib.php
1 <?php
2 /*
3  * Copyright 1999-2008 $ThePhpWikiProgrammingTeam
4  * Copyright 2008-2009 Marc-Etienne Vargenau, Alcatel-Lucent
5  *
6  * This file is part of PhpWiki.
7  *
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.
12  *
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.
17  *
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.
21  */
22
23 /*
24   Standard functions for Wiki functionality
25     WikiURL ($pagename, $args, $get_abs_url)
26     AbsoluteURL ($url)
27     IconForLink ($protocol_or_url)
28     PossiblyGlueIconToText($proto_or_url, $text)
29     IsSafeURL($url)
30     LinkURL ($url, $linktext)
31     LinkImage ($url, $alt)
32     ImgObject ($img, $url)
33
34     SplitQueryArgs ($query_args)
35     LinkPhpwikiURL ($url, $text, $basepage)
36     ConvertOldMarkup ($content, $markup_type = "block")
37     MangleXmlIdentifier($str)
38     UnMangleXmlIdentifier($str)
39
40     class Stack { push($item), pop(), cnt(), top() }
41     class Alert { show() }
42     class WikiPageName {getParent(),isValid(),getWarnings() }
43
44     expand_tabs($str, $tab_width = 8)
45     SplitPagename ($page)
46     NoSuchRevision ($request, $page, $version)
47     TimezoneOffset ($time, $no_colon)
48     Iso8601DateTime ($time)
49     Rfc2822DateTime ($time)
50     ParseRfc1123DateTime ($timestr)
51     CTime ($time)
52     ByteFormatter ($bytes = 0, $longformat = false)
53     __printf ($fmt)
54     __sprintf ($fmt)
55     __vsprintf ($fmt, $args)
56
57     file_mtime ($filename)
58     sort_file_mtime ($a, $b)
59     class fileSet {fileSet($directory, $filepattern = false),
60                    getFiles($exclude='', $sortby='', $limit='') }
61     class ListRegexExpand { listMatchCallback($item, $key),
62                             expandRegex ($index, &$pages) }
63
64     glob_to_pcre ($glob)
65     glob_match ($glob, $against, $case_sensitive = true)
66     explodeList ($input, $allnames, $glob_style = true, $case_sensitive = true)
67     explodePageList ($input, $perm = false)
68     isa ($object, $class)
69     can ($object, $method)
70     function_usable ($function_name)
71     wikihash ($x)
72     better_srand ($seed = '')
73     count_all ($arg)
74     isSubPage ($pagename)
75     subPageSlice ($pagename, $pos)
76     isActionPage ($filename)
77
78     phpwiki_version ()
79     isWikiWord ($word)
80     obj2hash ($obj, $exclude = false, $fields = false)
81     isUtf8String ($s)
82     fixTitleEncoding ($s)
83     url_get_contents ($uri)
84     GenerateId ($name)
85     firstNWordsOfContent ($n, $content)
86     extractSection ($section, $content, $page, $quiet = false, $sectionhead = false)
87     isExternalReferrer()
88
89     charset_convert($from, $to, $data)
90     string_starts_with($string, $prefix)
91     string_ends_with($string, $suffix)
92     array_remove($arr,$value)
93     longer_timeout($secs=30)
94     printSimpleTrace($bt)
95     getMemoryUsage()
96     binary_search($needle, $haystack)
97     is_localhost()
98     javascript_quote_string($s)
99     isSerialized($s)
100     is_whole_number($var)
101     parse_attributes($line)
102     is_image ($filename)
103     is_video ($filename)
104
105   function: linkExistingWikiWord($wikiword, $linktext, $version)
106   moved to: lib/WikiTheme.php
107 */
108 if (defined('_PHPWIKI_STDLIB_LOADED')) return;
109 else define('_PHPWIKI_STDLIB_LOADED', true);
110
111 if (!defined('MAX_PAGENAME_LENGTH')) {
112     define('MAX_PAGENAME_LENGTH', 100);
113 }
114
115 /**
116  * Convert string to a valid XML identifier.
117  *
118  * XML 1.0 identifiers are of the form: [A-Za-z][A-Za-z0-9:_.-]*
119  *
120  * We would like to have, e.g. named anchors within wiki pages
121  * names like "Table of Contents" --- clearly not a valid XML
122  * fragment identifier.
123  *
124  * This function implements a one-to-one map from {any string}
125  * to {valid XML identifiers}.
126  *
127  * It does this by
128  * converting all bytes not in [A-Za-z0-9:_-],
129  * and any leading byte not in [A-Za-z] to 'xbb.',
130  * where 'bb' is the hexadecimal representation of the
131  * character.
132  *
133  * As a special case, the empty string is converted to 'empty.'
134  *
135  * @param string $str
136  * @return string
137  */
138 function MangleXmlIdentifier($str)
139 {
140     if (!$str)
141         return 'empty.';
142
143     return preg_replace('/[^-_:A-Za-z0-9]|(?<=^)[^A-Za-z]/e',
144         "'x' . sprintf('%02x', ord('\\0')) . '.'",
145         $str);
146 }
147
148 function UnMangleXmlIdentifier($str)
149 {
150     if ($str == 'empty.')
151         return '';
152     return preg_replace('/x(\w\w)\./e',
153         "sprintf('%c', hex('\\0'))",
154         $str);
155 }
156
157 /**
158  * Returns a name for the WIKI_ID cookie that should be unique on the host.
159  * But for it to be unique you must have set a unique WIKI_NAME in your
160  * configuration file.
161  * @return string The name of the WIKI_ID cookie to use for this wiki.
162  */
163 function getCookieName()
164 {
165     return preg_replace("/[^\d\w]/", "_", WIKI_NAME) . "_WIKI_ID";
166 }
167
168 /**
169  * Generates a valid URL for a given Wiki pagename.
170  * @param mixed $pagename If a string this will be the name of the Wiki page to link to.
171  *               If a WikiDB_Page object function will extract the name to link to.
172  *               If a WikiDB_PageRevision object function will extract the name to link to.
173  * @param array $args
174  * @param boolean $get_abs_url Default value is false.
175  * @return string The absolute URL to the page passed as $pagename.
176  */
177 function WikiURL($pagename, $args = '', $get_abs_url = false)
178 {
179     global $request, $WikiTheme;
180     $anchor = false;
181
182     if (is_object($pagename)) {
183         if (isa($pagename, 'WikiDB_Page')) {
184             $pagename = $pagename->getName();
185         } elseif (isa($pagename, 'WikiDB_PageRevision')) {
186             $page = $pagename->getPage();
187             $args['version'] = $pagename->getVersion();
188             $pagename = $page->getName();
189         } elseif (isa($pagename, 'WikiPageName')) {
190             $anchor = $pagename->anchor;
191             $pagename = $pagename->name;
192         } else { // php5
193             $anchor = $pagename->anchor;
194             $pagename = $pagename->name;
195         }
196     }
197     if (!$get_abs_url and DEBUG and $request->getArg('start_debug')) {
198         if (!$args)
199             $args = 'start_debug=' . $request->getArg('start_debug');
200         elseif (is_array($args))
201             $args['start_debug'] = $request->getArg('start_debug'); else
202             $args .= '&start_debug=' . $request->getArg('start_debug');
203     }
204     if (is_array($args)) {
205         $enc_args = array();
206         foreach ($args as $key => $val) {
207             // avoid default args
208             if (USE_PATH_INFO and $key == 'pagename')
209                 ;
210             elseif ($key == 'action' and $val == 'browse')
211                 ; elseif (!is_array($val)) // ugly hack for getURLtoSelf() which also takes POST vars
212                 $enc_args[] = urlencode($key) . '=' . urlencode($val);
213         }
214         $args = join('&', $enc_args);
215     }
216
217     if (USE_PATH_INFO or !empty($WikiTheme->HTML_DUMP_SUFFIX)) {
218         $url = $get_abs_url ? (SERVER_URL . VIRTUAL_PATH . "/") : "";
219         $base = preg_replace('/%2f/i', '/', rawurlencode($pagename));
220         $url .= $base;
221         if (!empty($WikiTheme->HTML_DUMP_SUFFIX)) {
222             if (!empty($WikiTheme->VALID_LINKS) and $request->getArg('action') == 'pdf') {
223                 if (!in_array($pagename, $WikiTheme->VALID_LINKS))
224                     $url = '';
225                 else
226                     $url = $base . $WikiTheme->HTML_DUMP_SUFFIX;
227             } else {
228                 $url .= $WikiTheme->HTML_DUMP_SUFFIX;
229                 if ($args)
230                     $url .= "?$args";
231             }
232         } else {
233             if ($args)
234                 $url .= "?$args";
235         }
236     } else {
237         $url = $get_abs_url ? SERVER_URL . SCRIPT_NAME : basename(SCRIPT_NAME);
238         $url .= "?pagename=" . rawurlencode($pagename);
239         if ($args)
240             $url .= "&$args";
241     }
242     if ($anchor)
243         $url .= "#" . MangleXmlIdentifier($anchor);
244     return $url;
245 }
246
247 /** Convert relative URL to absolute URL.
248  *
249  * This converts a relative URL to one of PhpWiki's support files
250  * to an absolute one.
251  *
252  * @param string $url
253  * @return string Absolute URL
254  */
255 function AbsoluteURL($url)
256 {
257     if (preg_match('/^https?:/', $url))
258         return $url;
259     if ($url[0] != '/') {
260         $base = USE_PATH_INFO ? VIRTUAL_PATH : dirname(SCRIPT_NAME);
261         while ($base != '/' and substr($url, 0, 3) == "../") {
262             $url = substr($url, 3);
263             $base = dirname($base);
264         }
265         if ($base != '/')
266             $base .= '/';
267         $url = $base . $url;
268     }
269     return SERVER_URL . $url;
270 }
271
272 function DataURL($url)
273 {
274     if (preg_match('/^https?:/', $url))
275         return $url;
276     $url = NormalizeWebFileName($url);
277     if (DEBUG and $GLOBALS['request']->getArg('start_debug') and substr($url, -4, 4) == '.php')
278         $url .= "?start_debug=1"; // XMLRPC and SOAP debugging helper.
279     return AbsoluteURL($url);
280 }
281
282 /**
283  * Generates icon in front of links.
284  *
285  * @param string $protocol_or_url URL or protocol to determine which icon to use.
286  *
287  * @return HtmlElement HtmlElement object that contains data to create img link to
288  * icon for use with url or protocol passed to the function. False if no img to be
289  * displayed.
290  */
291 function IconForLink($protocol_or_url)
292 {
293     global $WikiTheme;
294     if (0 and $filename_suffix == false) {
295         // display apache style icon for file type instead of protocol icon
296         // - archive: unix:gz,bz2,tgz,tar,z; mac:dmg,dmgz,bin,img,cpt,sit; pc:zip;
297         // - document: html, htm, text, txt, rtf, pdf, doc
298         // - non-inlined image: jpg,jpeg,png,gif,tiff,tif,swf,pict,psd,eps,ps
299         // - audio: mp3,mp2,aiff,aif,au
300         // - multimedia: mpeg,mpg,mov,qt
301     } else {
302         list ($proto) = explode(':', $protocol_or_url, 2);
303         $src = $WikiTheme->getLinkIconURL($proto);
304         if ($src)
305             return HTML::img(array('src' => $src, 'alt' => "", 'class' => 'linkicon'));
306         else
307             return false;
308     }
309 }
310
311 /**
312  * Glue icon in front of or after text.
313  * Pref: 'noLinkIcons'      - ignore icon if set
314  * WikiTheme: 'LinkIcons'   - 'yes'   at front
315  *                          - 'no'    display no icon
316  *                          - 'front' display at left
317  *                          - 'after' display at right
318  *
319  * @param string $protocol_or_url Protocol or URL.  Used to determine the
320  * proper icon.
321  * @param string $text The text.
322  * @return XmlContent.
323  */
324 function PossiblyGlueIconToText($proto_or_url, $text)
325 {
326     global $request, $WikiTheme;
327     if ($request->getPref('noLinkIcons'))
328         return $text;
329     $icon = IconForLink($proto_or_url);
330     if (!$icon)
331         return $text;
332     if ($where = $WikiTheme->getLinkIconAttr()) {
333         if ($where == 'no') return $text;
334         if ($where != 'after') $where = 'front';
335     } else {
336         $where = 'front';
337     }
338     if ($where == 'after') {
339         // span the icon only to the last word (tie them together),
340         // to let the previous words wrap on line breaks.
341         if (!is_object($text)) {
342             preg_match('/^(\s*\S*)(\s*)$/', $text, $m);
343             list (, $prefix, $last_word) = $m;
344         } else {
345             $last_word = $text;
346             $prefix = false;
347         }
348         $text = HTML::span(array('style' => 'white-space: nowrap'),
349             $last_word, HTML::Raw('&nbsp;'), $icon);
350         if ($prefix)
351             $text = HTML($prefix, $text);
352         return $text;
353     }
354     // span the icon only to the first word (tie them together),
355     // to let the next words wrap on line breaks
356     if (!is_object($text)) {
357         preg_match('/^\s*(\S*)(.*?)\s*$/', $text, $m);
358         list (, $first_word, $tail) = $m;
359     } else {
360         $first_word = $text;
361         $tail = false;
362     }
363     $text = HTML::span(array('style' => 'white-space: nowrap'),
364         $icon, $first_word);
365     if ($tail)
366         $text = HTML($text, $tail);
367     return $text;
368 }
369
370 /**
371  * Determines if the url passed to function is safe, by detecting if the characters
372  * '<', '>', or '"' are present.
373  * Check against their urlencoded values also.
374  *
375  * @param string $url URL to check for unsafe characters.
376  * @return boolean True if same, false else.
377  */
378 function IsSafeURL($url)
379 {
380     return !preg_match('/([<>"])|(%3C)|(%3E)|(%22)/', $url);
381 }
382
383 /**
384  * Generates an HtmlElement object to store data for a link.
385  *
386  * @param string $url URL that the link will point to.
387  * @param string $linktext Text to be displayed as link.
388  * @return HtmlElement HtmlElement object that contains data to construct an html link.
389  */
390 function LinkURL($url, $linktext = '')
391 {
392     // FIXME: Is this needed (or sufficient?)
393     if (!IsSafeURL($url)) {
394         $link = HTML::span(array('class' => 'error'), _('Bad URL -- remove all of <, >, "'));
395         return $link;
396     } else {
397         if (!$linktext)
398             $linktext = preg_replace("/mailto:/A", "", $url);
399         $args = array('href' => $url);
400         if (defined('EXTERNAL_LINK_TARGET')) // can also be set in the css
401             $args['target'] = (is_string(EXTERNAL_LINK_TARGET) and (EXTERNAL_LINK_TARGET != "")) ? EXTERNAL_LINK_TARGET : "_blank";
402         $link = HTML::a($args, PossiblyGlueIconToText($url, $linktext));
403     }
404     $link->setAttr('class', $linktext ? 'namedurl' : 'rawurl');
405     return $link;
406 }
407
408 /**
409  * Inline Images
410  *
411  * Syntax: [image.png size=50% border=n align= hspace= vspace= width= height=]
412  * Disallows sizes which are too small.
413  * Spammers may use such (typically invisible) image attributes to raise their GoogleRank.
414  *
415  * Handle embeddable objects, like svg, class, vrml, swf, svgz, pdf, avi, wmv especially.
416  */
417 function LinkImage($url, $alt = "")
418 {
419     $force_img = "png|jpg|gif|jpeg|bmp|pl|cgi";
420     // Disallow tags in img src urls. Typical CSS attacks.
421     // FIXME: Is this needed (or sufficient?)
422     // FIXED: This was broken for moniker:TP30 test/image.png => url="moniker:TP30" attr="test/image.png"
423     $ori_url = $url;
424     // support new syntax: [prefix/image.jpg size=50% border=n]
425     if (empty($alt)) {
426         $alt = "";
427     }
428     if (!IsSafeURL($url)) {
429         $link = HTML::span(array('class' => 'error'), _('Bad URL for image -- remove all of <, >, "'));
430         return $link;
431     }
432     // spaces in inline images must be %20 encoded!
433     $link = HTML::img(array('src' => $url));
434
435     // Extract attributes and shorten url
436     $arr = parse_attributes(strstr($url, " "));
437     foreach ($arr as $attr => $value) {
438         // strip attr=... url suffix
439         $link->setAttr('src', $url);
440         $i = strpos($url, $attr);
441         $url = substr($url, 0, $i - 1);
442         // These attributes take strings: lang, id, title, alt
443         if (($attr == "lang")
444             || ($attr == "id")
445             || ($attr == "title")
446             || ($attr == "alt")
447         ) {
448             $link->setAttr($attr, $value);
449         } // align = bottom|middle|top|left|right
450         // we allow "center" as synonym for "middle"
451         elseif (($attr == "align")
452             && (($value == "bottom")
453                 || ($value == "middle")
454                 || ($value == "center")
455                 || ($value == "top")
456                 || ($value == "left")
457                 || ($value == "right"))
458         ) {
459             if ($value == "center") {
460                 $value = "middle";
461             }
462             $link->setAttr($attr, $value);
463         } // These attributes take a number (pixels): border, hspace, vspace
464         elseif ((($attr == "border") || ($attr == "hspace") || ($attr == "vspace"))
465             && (is_numeric($value))
466         ) {
467             $link->setAttr($attr, (int)$value);
468         } // These attributes take a number (pixels) or a percentage: height, width
469         elseif ((($attr == "height") || ($attr == "width"))
470             && (preg_match('/\d+[%p]?x?/', $value))
471         ) {
472             $link->setAttr($attr, $value);
473         } // We allow size=50% and size=20x30
474         // We replace this with "width" and "height" HTML attributes
475         elseif ($attr == "size") {
476             if (preg_match('/(\d+%)/', $value, $m)) {
477                 $link->setAttr('width', $m[1]);
478                 $link->setAttr('height', $m[1]);
479             } elseif (preg_match('/(\d+)x(\d+)/', $value, $m)) {
480                 $link->setAttr('width', $m[1]);
481                 $link->setAttr('height', $m[2]);
482             }
483         } else {
484             $url = substr(strrchr($ori_url, "/"), 1);
485             $link = HTML::span(array('class' => 'error'),
486                 sprintf(_("Invalid attribute %s=%s for image %s"),
487                     $attr, $value, $url));
488             return $link;
489         }
490     }
491     // Correct silently the most common error
492     if (strstr($ori_url, " ") and !preg_match("/^http/", $url)) {
493         // space belongs to the path
494         $file = NormalizeLocalFileName($ori_url);
495         if (file_exists($file)) {
496             $link = HTML::img(array('src' => $ori_url));
497             trigger_error(
498                 sprintf(_("Invalid image link fixed %s => %s. Spaces must be quoted with %%20."),
499                     $url, $ori_url), E_USER_WARNING);
500         } elseif (string_starts_with($ori_url, getUploadDataPath())) {
501             $file = substr($file, strlen(getUploadDataPath()));
502             $path = getUploadFilePath() . $file;
503             if (file_exists($path)) {
504                 trigger_error(sprintf(_("Invalid image link fixed \"%s\" => \"%s\".\n Spaces must be quoted with %%20."),
505                     $url, $ori_url), E_USER_WARNING);
506                 $link->setAttr('src', getUploadDataPath() . $file);
507                 $url = $ori_url;
508             }
509         }
510     }
511     if (!$link->getAttr('alt')) {
512         $link->setAttr('alt', $alt);
513     }
514     // Check width and height as spam countermeasure
515     if (($width = $link->getAttr('width')) and ($height = $link->getAttr('height'))) {
516         //$width  = (int) $width; // px or % or other suffix
517         //$height = (int) $height;
518         if (($width < 3 and $height < 10) or
519             ($height < 3 and $width < 20) or
520             ($height < 7 and $width < 7)
521         ) {
522             $link = HTML::span(array('class' => 'error'),
523                 _("Invalid image size"));
524             return $link;
525         }
526     } else {
527         $size = 0;
528         // Prepare for getimagesize($url)
529         // $url only valid for external urls, otherwise local path
530         if (DISABLE_GETIMAGESIZE)
531             ;
532         elseif (!preg_match("/\.$force_img$/i", $url))
533             ; // only valid image extensions or scripts assumed to generate images
534         elseif (preg_match("/^http/", $url)) { // external url
535             $size = @getimagesize($url);
536         } else { // local file
537             if (file_exists($file = NormalizeLocalFileName($url))) { // here
538                 $size = @getimagesize($file);
539             } elseif (file_exists(NormalizeLocalFileName(urldecode($url)))) {
540                 $size = @getimagesize($file);
541                 $link->setAttr('src', rawurldecode($url));
542             } elseif (string_starts_with($url, getUploadDataPath())) { // there
543                 $file = substr($file, strlen(getUploadDataPath()));
544                 $path = getUploadFilePath() . rawurldecode($file);
545                 $size = @getimagesize($path);
546                 $link->setAttr('src', getUploadDataPath() . rawurldecode($file));
547             } else { // elsewhere
548                 global $request;
549                 $size = @getimagesize($request->get('DOCUMENT_ROOT') . urldecode($url));
550             }
551         }
552         if ($size) {
553             $width = $size[0];
554             $height = $size[1];
555             if (($width < 3 and $height < 10)
556                 or ($height < 3 and $width < 20)
557                 or ($height < 7 and $width < 7)
558             ) {
559                 $link = HTML::span(array('class' => 'error'),
560                     _("Invalid image size"));
561                 return $link;
562             }
563         }
564     }
565     $link->setAttr('class', 'inlineimage');
566
567     /* Check for inlined objects. Everything allowed in INLINE_IMAGES besides
568      * png|jpg|gif|jpeg|bmp|pl|cgi.  If no image it is an object to embed.
569      * Note: Allow cgi's (pl,cgi) returning images.
570      */
571     if (!preg_match("/\.(" . $force_img . ")/i", $ori_url)) {
572         // HTML::img(array('src' => $url, 'alt' => $alt, 'title' => $alt));
573         // => HTML::object(array('src' => $url)) ...;
574         return ImgObject($link, $ori_url);
575     }
576     return $link;
577 }
578
579 /**
580  * <object> / <embed> tags instead of <img> for all non-image extensions
581  * in INLINE_IMAGES.
582  * Called by LinkImage(), not directly.
583  * Syntax:  [image.svg size=50% alt=image.gif border=n align= hspace= vspace= width= height=]
584  * Samples: [Upload:song.mp3 type=audio/mpeg width=200 height=10]
585  *   $alt may be an alternate img
586  * TODO: Need to unify with WikiPluginCached::embedObject()
587  *
588  * Note that Safari 1.0 will crash with <object>, so use only <embed>
589  *   http://www.alleged.org.uk/pdc/2002/svg-object.html
590  *
591  * Allowed object tags:
592  *   ID
593  *   DATA=URI (object data)
594  *   CLASSID=URI (location of implementation)
595  *   ARCHIVE=CDATA (archive files)
596  *   CODEBASE=URI (base URI for CLASSID, DATA, ARCHIVE)
597  *   WIDTH=Length (object width)
598  *   HEIGHT=Length (object height)
599  *   NAME=CDATA (name for form submission)
600  *   USEMAP=URI (client-side image map)
601  *   TYPE=ContentType (content-type of object)
602  *   CODETYPE=ContentType (content-type of code)
603  *   STANDBY=Text (message to show while loading)
604  *   TABINDEX=NUMBER (position in tabbing order)
605  *   DECLARE (do not instantiate object)
606  * The rest is added as <param name="" value="" /> tags
607  */
608 function ImgObject($img, $url)
609 {
610     // get the url args: data="sample.svgz" type="image/svg+xml" width="400" height="300"
611     $params = explode(",", "id,width,height,data,classid,archive,codebase,name,usemap,type," .
612         "codetype,standby,tabindex,declare");
613     if (is_array($url)) {
614         $args = $url;
615         $found = array();
616         foreach ($args as $attr => $value) {
617             foreach ($params as $param) {
618                 if ($param == $attr) {
619                     $img->setAttr($param, $value);
620                     if (isset($found[$param])) $found[$param]++;
621                     else $found[$param] = 1;
622                     break;
623                 }
624             }
625         }
626         // now all remaining args are added as <param> to the object
627         $params = array();
628         foreach ($args as $attr => $value) {
629             if (!isset($found[$attr])) {
630                 $params[] = HTML::param(array('name' => $attr,
631                     'value' => $value));
632             }
633         }
634         $url = $img->getAttr('src');
635         $force_img = "png|jpg|gif|jpeg|bmp";
636         if (!preg_match("/\.(" . $force_img . ")/i", $url)) {
637             $img->setAttr('src', false);
638         }
639     } else {
640         $args = explode(' ', $url);
641         if (count($args) >= 1) {
642             $url = array_shift($args);
643             $found = array();
644             foreach ($args as $attr) {
645                 foreach ($params as $param) {
646                     if (preg_match("/^$param=(\S+)$/i", $attr, $m)) {
647                         $img->setAttr($param, $m[1]);
648                         if (isset($found[$param])) $found[$param]++;
649                         else $found[$param] = 1;
650                         break;
651                     }
652                 }
653             }
654             // now all remaining args are added as <param> to the object
655             $params = array();
656             foreach ($args as $attr) {
657                 if (!isset($found[$attr]) and preg_match("/^(\S+)=(\S+)$/i", $attr, $m)) {
658                     $params[] = HTML::param(array('name' => $m[1],
659                         'value' => $m[2]));
660                 }
661             }
662         }
663     }
664     $type = $img->getAttr('type');
665     if (!$type) {
666         if (function_exists('mime_content_type') && file_exists($url)) {
667             $type = mime_content_type($url);
668         }
669     }
670     $object = HTML::object(array_merge($img->_attr,
671             array('type' => $type)), //'src' => $url
672         $img->_content);
673     $object->setAttr('class', 'inlineobject');
674     if ($params) {
675         foreach ($params as $param) $object->pushContent($param);
676     }
677     if (isBrowserSafari() and !isBrowserSafari(532)) { // recent chrome can do OBJECT
678         return HTML::embed($object->_attr, $object->_content);
679     }
680     $object->pushContent(HTML::embed($object->_attr));
681     return $object;
682 }
683
684 class Stack
685 {
686
687     // var in php5 deprecated
688     function Stack()
689     {
690         $this->items = array();
691         $this->size = 0;
692     }
693
694     function push($item)
695     {
696         $this->items[$this->size] = $item;
697         $this->size++;
698         return true;
699     }
700
701     function pop()
702     {
703         if ($this->size == 0) {
704             return false; // stack is empty
705         }
706         $this->size--;
707         return $this->items[$this->size];
708     }
709
710     function cnt()
711     {
712         return $this->size;
713     }
714
715     function top()
716     {
717         if ($this->size)
718             return $this->items[$this->size - 1];
719         else
720             return '';
721     }
722
723 }
724
725 // end class definition
726
727 function SplitQueryArgs($query_args = '')
728 {
729     // FIXME: use the arg-seperator which might not be &
730     $split_args = explode('&', $query_args);
731     $args = array();
732     while (list($key, $val) = each($split_args))
733         if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
734             $args[$m[1]] = $m[2];
735     return $args;
736 }
737
738 function LinkPhpwikiURL($url, $text = '', $basepage = false)
739 {
740     $args = array();
741
742     if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m)) {
743         return HTML::span(array('class' => 'error'), _("BAD phpwiki: URL"));
744     }
745
746     if ($m[1])
747         $pagename = urldecode($m[1]);
748     $qargs = $m[2];
749
750     if (empty($pagename) &&
751         preg_match('/^(diff|edit|links|info)=([^&]+)$/', $qargs, $m)
752     ) {
753         // Convert old style links (to not break diff links in
754         // RecentChanges).
755         $pagename = urldecode($m[2]);
756         $args = array("action" => $m[1]);
757     } else {
758         $args = SplitQueryArgs($qargs);
759     }
760
761     if (empty($pagename))
762         $pagename = $GLOBALS['request']->getArg('pagename');
763
764     if (isset($args['action']) && $args['action'] == 'browse')
765         unset($args['action']);
766
767     /*FIXME:
768       if (empty($args['action']))
769       $class = 'wikilink';
770       else if (is_safe_action($args['action']))
771       $class = 'wikiaction';
772     */
773     if (empty($args['action']) || is_safe_action($args['action']))
774         $class = 'wikiaction';
775     else {
776         // Don't allow administrative links on unlocked pages.
777         $dbi = $GLOBALS['request']->getDbh();
778         $page = $dbi->getPage($basepage ? $basepage : $pagename);
779         if (!$page->get('locked'))
780             return HTML::span(array('class' => 'wikiunsafe'),
781                 HTML::u(_("Lock page to enable link")));
782         $class = 'wikiadmin';
783     }
784
785     if (!$text)
786         $text = HTML::span(array('class' => 'rawurl'), $url);
787
788     $wikipage = new WikiPageName($pagename);
789     if (!$wikipage->isValid()) {
790         global $WikiTheme;
791         return $WikiTheme->linkBadWikiWord($wikipage, $url);
792     }
793
794     return HTML::a(array('href' => WikiURL($pagename, $args),
795             'class' => $class),
796         $text);
797 }
798
799 /**
800  * A class to assist in parsing wiki pagenames.
801  *
802  * Now with subpages and anchors, parsing and passing around
803  * pagenames is more complicated.  This should help.
804  */
805 class WikiPageName
806 {
807     /** Short name for page.
808      *
809      * This is the value of $name passed to the constructor.
810      * (For use, e.g. as a default label for links to the page.)
811      */
812     //var $shortName;
813
814     /** The full page name.
815      *
816      * This is the full name of the page (without anchor).
817      */
818     //var $name;
819
820     /** The anchor.
821      *
822      * This is the referenced anchor within the page, or the empty string.
823      */
824     //var $anchor;
825
826     /** Constructor
827      *
828      * @param mixed $name Page name.
829      * WikiDB_Page, WikiDB_PageRevision, or string.
830      * This can be a relative subpage name (like '/SubPage'),
831      * or can be the empty string to refer to the $basename.
832      *
833      * @param string $anchor For links to anchors in page.
834      *
835      * @param mixed $basename Page name from which to interpret
836      * relative or other non-fully-specified page names.
837      */
838     function WikiPageName($name, $basename = false, $anchor = false)
839     {
840         if (is_string($name)) {
841             $this->shortName = $name;
842             if (strstr($name, ':')) {
843                 list($moniker, $shortName) = explode(":", $name, 2);
844                 $map = getInterwikiMap(); // allow overrides to custom maps
845                 if (isset($map->_map[$moniker])) {
846                     $url = $map->_map[$moniker];
847                     if (strstr($url, '%s'))
848                         $url = sprintf($url, $shortName);
849                     else
850                         $url .= $shortName;
851                     $this->url = $url;
852                     // expand Talk or User, but not to absolute urls!
853                     if (strstr($url, '//')) {
854                         if ($moniker == 'Talk')
855                             $name = $name . SUBPAGE_SEPARATOR . _("Discussion");
856                         elseif ($moniker == 'User')
857                             $name = $name;
858                     } else {
859                         $name = $url;
860                     }
861                     if (strstr($shortName, '?')) {
862                         list($shortName, $dummy) = explode("\?", $shortName, 2);
863                     }
864                     $this->shortName = $shortName;
865                 }
866             }
867             // FIXME: We should really fix the cause for "/PageName" in the WikiDB
868             if ($name == '' or $name[0] == SUBPAGE_SEPARATOR) {
869                 if ($basename)
870                     $name = $this->_pagename($basename) . $name;
871                 else {
872                     $name = $this->_normalize_bad_pagename($name);
873                     $this->shortName = $name;
874                 }
875             }
876         } else {
877             $name = $this->_pagename($name);
878             $this->shortName = $name;
879         }
880
881         $this->name = $this->_check($name);
882         $this->anchor = (string)$anchor;
883     }
884
885     function getName()
886     {
887         return $this->name;
888     }
889
890     function getParent()
891     {
892         $name = $this->name;
893         if (!($tail = strrchr($name, SUBPAGE_SEPARATOR)))
894             return false;
895         return substr($name, 0, -strlen($tail));
896     }
897
898     function isValid($strict = false)
899     {
900         if ($strict)
901             return !isset($this->_errors);
902         return (is_string($this->name) and $this->name != '');
903     }
904
905     function getWarnings()
906     {
907         $warnings = array();
908         if (isset($this->_warnings))
909             $warnings = array_merge($warnings, $this->_warnings);
910         if (isset($this->_errors))
911             $warnings = array_merge($warnings, $this->_errors);
912         if (!$warnings)
913             return false;
914
915         return sprintf(_("'%s': Bad page name: %s"),
916             $this->shortName, join(', ', $warnings));
917     }
918
919     function _pagename($page)
920     {
921         if (isa($page, 'WikiDB_Page'))
922             return $page->getName();
923         elseif (isa($page, 'WikiDB_PageRevision'))
924             return $page->getPageName(); elseif (isa($page, 'WikiPageName'))
925             return $page->name;
926         // '0' or e.g. '1984' should be allowed though
927         if (!is_string($page) and !is_integer($page)) {
928             trigger_error(sprintf("Non-string pagename '%s' (%s)(%s)",
929                     $page, gettype($page), get_class($page)),
930                 E_USER_NOTICE);
931         }
932         //assert(is_string($page));
933         return $page;
934     }
935
936     function _normalize_bad_pagename($name)
937     {
938         trigger_error("Bad pagename: " . $name, E_USER_WARNING);
939
940         // Punt...  You really shouldn't get here.
941         if (empty($name)) {
942             global $request;
943             return $request->getArg('pagename');
944         }
945         assert($name[0] == SUBPAGE_SEPARATOR);
946         $this->_errors[] = sprintf(_("Leading %s not allowed"), SUBPAGE_SEPARATOR);
947         return substr($name, 1);
948     }
949
950     /**
951      * Compress internal white-space to single space character.
952      *
953      * This leads to problems with loading a foreign charset pagename,
954      * which cannot be deleted anymore, because unknown chars are compressed.
955      * So BEFORE importing a file _check must be done !!!
956      */
957     function _check($pagename)
958     {
959         // Compress internal white-space to single space character.
960         $pagename = preg_replace('/[\s\xa0]+/', ' ', $orig = $pagename);
961         if ($pagename != $orig)
962             $this->_warnings[] = _("White space converted to single space");
963
964         // Delete any control characters.
965         if (DATABASE_TYPE == 'cvs' or DATABASE_TYPE == 'file' or DATABASE_TYPE == 'flatfile') {
966             $pagename = preg_replace('/[\x00-\x1f\x7f\x80-\x9f]/', '', $orig = $pagename);
967             if ($pagename != $orig)
968                 $this->_errors[] = _("Control characters not allowed");
969         }
970
971         // Strip leading and trailing white-space.
972         $pagename = trim($pagename);
973
974         $orig = $pagename;
975         while ($pagename and $pagename[0] == SUBPAGE_SEPARATOR)
976             $pagename = substr($pagename, 1);
977         if ($pagename != $orig)
978             $this->_errors[] = sprintf(_("Leading %s not allowed"), SUBPAGE_SEPARATOR);
979
980         // ";" is urlencoded, so safe from php arg-delim problems
981         /*if (strstr($pagename, ';')) {
982             $this->_warnings[] = _("';' is deprecated");
983             $pagename = str_replace(';', '', $pagename);
984         }*/
985
986         // not only for SQL, also to restrict url length
987         if (strlen($pagename) > MAX_PAGENAME_LENGTH) {
988             $pagename = substr($pagename, 0, MAX_PAGENAME_LENGTH);
989             $this->_errors[] = _("Page name too long");
990         }
991
992         // disallow some chars only on file and cvs
993         if ((DATABASE_TYPE == 'cvs'
994             or DATABASE_TYPE == 'file'
995             or DATABASE_TYPE == 'flatfile')
996             and preg_match('/(:|\.\.)/', $pagename, $m)
997         ) {
998             $this->_warnings[] = sprintf(_("Illegal chars %s removed"), $m[1]);
999             $pagename = str_replace('..', '', $pagename);
1000             $pagename = str_replace(':', '', $pagename);
1001         }
1002
1003         return $pagename;
1004     }
1005 }
1006
1007 /**
1008  * Convert old page markup to new-style markup.
1009  *
1010  * @param string $text Old-style wiki markup.
1011  *
1012  * @param string $markup_type
1013  * One of: <dl>
1014  * <dt><code>"block"</code>  <dd>Convert all markup.
1015  * <dt><code>"inline"</code> <dd>Convert only inline markup.
1016  * <dt><code>"links"</code>  <dd>Convert only link markup.
1017  * </dl>
1018  *
1019  * @return string New-style wiki markup.
1020  *
1021  * @bugs Footnotes don't work quite as before (esp if there are
1022  *   multiple references to the same footnote.  But close enough,
1023  *   probably for now....
1024  * @bugs  Apache2 and IIS crash with OldTextFormattingRules or
1025  *   AnciennesR%E8glesDeFormatage. (at the 2nd attempt to do the anchored block regex)
1026  *   It only crashes with CreateToc so far, but other pages (not in pgsrc) are
1027  *   also known to crash, even with Apache1.
1028  */
1029 function ConvertOldMarkup($text, $markup_type = "block")
1030 {
1031
1032     static $subs;
1033     static $block_re;
1034
1035     // FIXME:
1036     // Trying to detect why the 2nd paragraph of OldTextFormattingRules or
1037     // AnciennesR%E8glesDeFormatage crashes.
1038     // It only crashes with CreateToc so far, but other pages (not in pgsrc) are
1039     // also known to crash, even with Apache1.
1040     $debug_skip = false;
1041     // I suspect this only to crash with Apache2 and IIS.
1042     if (in_array(php_sapi_name(), array('apache2handler', 'apache2filter', 'isapi'))
1043         and preg_match("/plugin CreateToc/", $text)
1044     ) {
1045         trigger_error(_("The CreateTocPlugin is not yet old markup compatible! ")
1046             . _("Please remove the CreateToc line to be able to reformat this page to old markup. ")
1047             . _("Skipped."), E_USER_WARNING);
1048         $debug_skip = true;
1049         //if (!DEBUG) return $text;
1050         return $text;
1051     }
1052
1053     if (empty($subs)) {
1054         /*****************************************************************
1055          * Conversions for inline markup:
1056          */
1057
1058         // escape tilde's
1059         $orig[] = '/~/';
1060         $repl[] = '~~';
1061
1062         // escape escaped brackets
1063         $orig[] = '/\[\[/';
1064         $repl[] = '~[';
1065
1066         // change ! escapes to ~'s.
1067         global $WikiNameRegexp, $request;
1068         $bang_esc[] = "(?:" . ALLOWED_PROTOCOLS . "):[^\s<>\[\]\"'()]*[^\s<>\[\]\"'(),.?]";
1069         // before 4.3.9 pcre had a memory release bug, which might hit us here. so be safe.
1070         $map = getInterwikiMap();
1071         if ($map_regex = $map->getRegexp())
1072             $bang_esc[] = $map_regex . ":[^\\s.,;?()]+"; // FIXME: is this really needed?
1073         $bang_esc[] = $WikiNameRegexp;
1074         $orig[] = '/!((?:' . join(')|(', $bang_esc) . '))/';
1075         $repl[] = '~\\1';
1076
1077         $subs["links"] = array($orig, $repl);
1078
1079         // Temporarily URL-encode pairs of underscores in links to hide
1080         // them from the re for bold markup.
1081         $orig[] = '/\[[^\[\]]*?__[^\[\]]*?\]/e';
1082         $repl[] = 'str_replace(\'__\', \'%5F%5F\', \'\\0\')';
1083
1084         // Escape '<'s
1085         //$orig[] = '/<(?!\?plugin)|(?<!^)</m';
1086         //$repl[] = '~<';
1087
1088         // Convert footnote references.
1089         $orig[] = '/(?<=.)(?<!~)\[\s*(\d+)\s*\]/m';
1090         $repl[] = '#[|ftnt_ref_\\1]<sup>~[[\\1|#ftnt_\\1]~]</sup>';
1091
1092         // Convert old style emphases to HTML style emphasis.
1093         $orig[] = '/__(.*?)__/';
1094         $repl[] = '<strong>\\1</strong>';
1095         $orig[] = "/''(.*?)''/";
1096         $repl[] = '<em>\\1</em>';
1097
1098         // Escape nestled markup.
1099         $orig[] = '/^(?<=^|\s)[=_](?=\S)|(?<=\S)[=_*](?=\s|$)/m';
1100         $repl[] = '~\\0';
1101
1102         // in old markup headings only allowed at beginning of line
1103         $orig[] = '/!/';
1104         $repl[] = '~!';
1105
1106         // Convert URL-encoded pairs of underscores in links back to
1107         // real underscores after bold markup has been converted.
1108         $orig = '/\[[^\[\]]*?%5F%5F[^\[\]]*?\]/e';
1109         $repl = 'str_replace(\'%5F%5F\', \'__\', \'\\0\')';
1110
1111         $subs["inline"] = array($orig, $repl);
1112
1113         /*****************************************************************
1114          * Patterns which match block markup constructs which take
1115          * special handling...
1116          */
1117
1118         // Indented blocks
1119         $blockpats[] = '[ \t]+\S(?:.*\s*\n[ \t]+\S)*';
1120         // Tables
1121         $blockpats[] = '\|(?:.*\n\|)*';
1122
1123         // List items
1124         $blockpats[] = '[#*;]*(?:[*#]|;.*?:)';
1125
1126         // Footnote definitions
1127         $blockpats[] = '\[\s*(\d+)\s*\]';
1128
1129         if (!$debug_skip) {
1130             // Plugins
1131             $blockpats[] = '<\?plugin(?:-form)?\b.*\?>\s*$';
1132         }
1133
1134         // Section Title
1135         $blockpats[] = '!{1,3}[^!]';
1136         /*
1137     removed .|\n in the anchor not to crash on /m because with /m "." already includes \n
1138     this breaks headings but it doesn't crash anymore (crash on non-cgi, non-cli only)
1139     */
1140         $block_re = ('/\A((?:.|\n)*?)(^(?:'
1141             . join("|", $blockpats)
1142             . ').*$)\n?/m');
1143
1144     }
1145
1146     if ($markup_type != "block") {
1147         list ($orig, $repl) = $subs[$markup_type];
1148         return preg_replace($orig, $repl, $text);
1149     } else {
1150         list ($orig, $repl) = $subs['inline'];
1151         $out = '';
1152         //FIXME:
1153         // php crashes here in the 2nd paragraph of OldTextFormattingRules,
1154         // AnciennesR%E8glesDeFormatage and more
1155         // See http://www.pcre.org/pcre.txt LIMITATIONS
1156         while (preg_match($block_re, $text, $m)) {
1157             $text = substr($text, strlen($m[0]));
1158             list (, $leading_text, $block) = $m;
1159             $suffix = "\n";
1160
1161             if (strchr(" \t", $block[0])) {
1162                 // Indented block
1163                 $prefix = "<pre>\n";
1164                 $suffix = "\n</pre>\n";
1165             } elseif ($block[0] == '|') {
1166                 // Old-style table
1167                 $prefix = "<?plugin OldStyleTable\n";
1168                 $suffix = "\n?>\n";
1169             } elseif (strchr("#*;", $block[0])) {
1170                 // Old-style list item
1171                 preg_match('/^([#*;]*)([*#]|;.*?:) */', $block, $m);
1172                 list (, $ind, $bullet) = $m;
1173                 $block = substr($block, strlen($m[0]));
1174
1175                 $indent = str_repeat('     ', strlen($ind));
1176                 if ($bullet[0] == ';') {
1177                     //$term = ltrim(substr($bullet, 1));
1178                     //return $indent . $term . "\n" . $indent . '     ';
1179                     $prefix = $ind . $bullet;
1180                 } else
1181                     $prefix = $indent . $bullet . ' ';
1182             } elseif ($block[0] == '[') {
1183                 // Footnote definition
1184                 preg_match('/^\[\s*(\d+)\s*\]/', $block, $m);
1185                 $footnum = $m[1];
1186                 $block = substr($block, strlen($m[0]));
1187                 $prefix = "#[|ftnt_" . ${footnum} . "]~[[" . ${footnum} . "|#ftnt_ref_" . ${footnum} . "]~] ";
1188             } elseif ($block[0] == '<') {
1189                 // Plugin.
1190                 // HACK: no inline markup...
1191                 $prefix = $block;
1192                 $block = '';
1193             } elseif ($block[0] == '!') {
1194                 // Section heading
1195                 preg_match('/^!{1,3}/', $block, $m);
1196                 $prefix = $m[0];
1197                 $block = substr($block, strlen($m[0]));
1198             } else {
1199                 // AAck!
1200                 assert(0);
1201             }
1202             if ($leading_text) $leading_text = preg_replace($orig, $repl, $leading_text);
1203             if ($block) $block = preg_replace($orig, $repl, $block);
1204             $out .= $leading_text;
1205             $out .= $prefix;
1206             $out .= $block;
1207             $out .= $suffix;
1208         }
1209         return $out . preg_replace($orig, $repl, $text);
1210     }
1211 }
1212
1213
1214 /**
1215  * Expand tabs in string.
1216  *
1217  * Converts all tabs to (the appropriate number of) spaces.
1218  *
1219  * @param string $str
1220  * @param integer $tab_width
1221  * @return string
1222  */
1223 function expand_tabs($str, $tab_width = 8)
1224 {
1225     $split = explode("\t", $str);
1226     $tail = array_pop($split);
1227     $expanded = "\n";
1228     foreach ($split as $hunk) {
1229         $expanded .= $hunk;
1230         $pos = strlen(strrchr($expanded, "\n")) - 1;
1231         $expanded .= str_repeat(" ", ($tab_width - $pos % $tab_width));
1232     }
1233     return substr($expanded, 1) . $tail;
1234 }
1235
1236 /**
1237  * Split WikiWords in page names.
1238  *
1239  * It has been deemed useful to split WikiWords (into "Wiki Words") in
1240  * places like page titles. This is rumored to help search engines
1241  * quite a bit.
1242  *
1243  * @param $page string The page name.
1244  *
1245  * @return string The split name.
1246  */
1247 function SplitPagename($page)
1248 {
1249
1250     if (preg_match("/\s/", $page))
1251         return $page; // Already split --- don't split any more.
1252
1253     // This algorithm is specialized for several languages.
1254     // (Thanks to Pierrick MEIGNEN)
1255     // Improvements for other languages welcome.
1256     static $RE;
1257     if (!isset($RE)) {
1258         // This mess splits between a lower-case letter followed by
1259         // either an upper-case or a numeral; except that it wont
1260         // split the prefixes 'Mc', 'De', or 'Di' off of their tails.
1261         switch ($GLOBALS['LANG']) {
1262             case 'en':
1263             case 'it':
1264             case 'es':
1265             case 'de':
1266                 $RE[] = '/([[:lower:]])((?<!Mc|De|Di)[[:upper:]]|\d)/';
1267                 break;
1268             case 'fr':
1269                 $RE[] = '/([[:lower:]])((?<!Mc|Di)[[:upper:]]|\d)/';
1270                 break;
1271         }
1272         $sep = preg_quote(SUBPAGE_SEPARATOR, '/');
1273         // This the single-letter words 'I' and 'A' from any following
1274         // capitalized words.
1275         switch ($GLOBALS['LANG']) {
1276             case 'en':
1277                 $RE[] = "/(?<= |${sep}|^)([AI])([[:upper:]][[:lower:]])/";
1278                 break;
1279             case 'fr':
1280                 $RE[] = "/(?<= |${sep}|^)([À])([[:upper:]][[:lower:]])/";
1281                 break;
1282         }
1283         // Split at underscore
1284         $RE[] = '/(_)([[:alpha:]])/';
1285         $RE[] = '/([[:alpha:]])(_)/';
1286         // Split numerals from following letters.
1287         $RE[] = '/(\d)([[:alpha:]])/';
1288         // Split at subpage seperators. TBD in WikiTheme.php
1289         $RE[] = "/([^${sep}]+)(${sep})/";
1290         $RE[] = "/(${sep})([^${sep}]+)/";
1291
1292         foreach ($RE as $key)
1293             $RE[$key] = $key;
1294     }
1295
1296     foreach ($RE as $regexp) {
1297         $page = preg_replace($regexp, '\\1 \\2', $page);
1298     }
1299     return $page;
1300 }
1301
1302 function NoSuchRevision(&$request, $page, $version)
1303 {
1304     $html = HTML(HTML::h2(_("Revision Not Found")),
1305         HTML::p(fmt("I'm sorry.  Version %d of %s is not in the database.",
1306             $version, WikiLink($page, 'auto'))));
1307     include_once 'lib/Template.php';
1308     GeneratePage($html, _("Bad Version"), $page->getCurrentRevision());
1309     $request->finish();
1310 }
1311
1312 /**
1313  * Get time offset for local time zone.
1314  *
1315  * @param $time time_t Get offset for this time. Default: now.
1316  * @param $no_colon boolean Don't put colon between hours and minutes.
1317  * @return string Offset as a string in the format +HH:MM.
1318  */
1319 function TimezoneOffset($time = false, $no_colon = false)
1320 {
1321     if ($time === false)
1322         $time = time();
1323     $secs = date('Z', $time);
1324
1325     if ($secs < 0) {
1326         $sign = '-';
1327         $secs = -$secs;
1328     } else {
1329         $sign = '+';
1330     }
1331     $colon = $no_colon ? '' : ':';
1332     $mins = intval(($secs + 30) / 60);
1333     return sprintf("%s%02d%s%02d",
1334         $sign, $mins / 60, $colon, $mins % 60);
1335 }
1336
1337
1338 /**
1339  * Format time in ISO-8601 format.
1340  *
1341  * @param $time time_t Time.  Default: now.
1342  * @return string Date and time in ISO-8601 format.
1343  */
1344 function Iso8601DateTime($time = false)
1345 {
1346     if ($time === false)
1347         $time = time();
1348     $tzoff = TimezoneOffset($time);
1349     $date = date('Y-m-d', $time);
1350     $time = date('H:i:s', $time);
1351     return $date . 'T' . $time . $tzoff;
1352 }
1353
1354 /**
1355  * Format time in RFC-2822 format.
1356  *
1357  * @param $time time_t Time.  Default: now.
1358  * @return string Date and time in RFC-2822 format.
1359  */
1360 function Rfc2822DateTime($time = false)
1361 {
1362     if ($time === false)
1363         $time = time();
1364     return date('D, j M Y H:i:s ', $time) . TimezoneOffset($time, 'no colon');
1365 }
1366
1367 /**
1368  * Format time in RFC-1123 format.
1369  *
1370  * @param $time time_t Time.  Default: now.
1371  * @return string Date and time in RFC-1123 format.
1372  */
1373 function Rfc1123DateTime($time = false)
1374 {
1375     if ($time === false)
1376         $time = time();
1377     return gmdate('D, d M Y H:i:s \G\M\T', $time);
1378 }
1379
1380 /** Parse date in RFC-1123 format.
1381  *
1382  * According to RFC 1123 we must accept dates in the following
1383  * formats:
1384  *
1385  *   Sun, 06 Nov 1994 08:49:37 GMT  ; RFC 822, updated by RFC 1123
1386  *   Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
1387  *   Sun Nov  6 08:49:37 1994       ; ANSI C's asctime() format
1388  *
1389  * (Though we're only allowed to generate dates in the first format.)
1390  */
1391 function ParseRfc1123DateTime($timestr)
1392 {
1393     $timestr = trim($timestr);
1394     if (preg_match('/^ \w{3},\s* (\d{1,2}) \s* (\w{3}) \s* (\d{4}) \s*'
1395             . '(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
1396         $timestr, $m)
1397     ) {
1398         list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
1399     } elseif (preg_match('/^ \w+,\s* (\d{1,2})-(\w{3})-(\d{2}|\d{4}) \s*'
1400             . '(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
1401         $timestr, $m)
1402     ) {
1403         list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
1404         if ($year < 70) $year += 2000;
1405         elseif ($year < 100) $year += 1900;
1406     } elseif (preg_match('/^\w+\s* (\w{3}) \s* (\d{1,2}) \s*'
1407             . '(\d\d):(\d\d):(\d\d) \s* (\d{4})$/ix',
1408         $timestr, $m)
1409     ) {
1410         list(, $mon, $mday, $hh, $mm, $ss, $year) = $m;
1411     } else {
1412         // Parse failed.
1413         return false;
1414     }
1415
1416     $time = strtotime("$mday $mon $year ${hh}:${mm}:${ss} GMT");
1417     if ($time == -1)
1418         return false; // failed
1419     return $time;
1420 }
1421
1422 /**
1423  * Format time to standard 'ctime' format.
1424  *
1425  * @param $time time_t Time.  Default: now.
1426  * @return string Date and time.
1427  */
1428 function CTime($time = false)
1429 {
1430     if ($time === false)
1431         $time = time();
1432     return date("D M j H:i:s Y", $time);
1433 }
1434
1435
1436 /**
1437  * Format number as kibibytes or bytes.
1438  * Short format is used for PageList
1439  * Long format is used in PageInfo
1440  *
1441  * @param $bytes       int.  Default: 0.
1442  * @param $longformat  bool. Default: false.
1443  * @return class FormattedText (XmlElement.php).
1444  */
1445 function ByteFormatter($bytes = 0, $longformat = false)
1446 {
1447     if ($bytes < 0)
1448         return fmt("-???");
1449     if ($bytes < 1024) {
1450         if (!$longformat)
1451             $size = fmt("%s B", $bytes);
1452         else
1453             $size = fmt("%s bytes", $bytes);
1454     } else {
1455         $kb = round($bytes / 1024, 1);
1456         if (!$longformat)
1457             $size = fmt("%s KiB", $kb);
1458         else
1459             $size = fmt("%s KiB (%s bytes)", $kb, $bytes);
1460     }
1461     return $size;
1462 }
1463
1464 /**
1465  * Internationalized printf.
1466  *
1467  * This is essentially the same as PHP's built-in printf
1468  * with the following exceptions:
1469  * <ol>
1470  * <li> It passes the format string through gettext().
1471  * <li> It supports the argument reordering extensions.
1472  * </ol>
1473  *
1474  * Example:
1475  *
1476  * In php code, use:
1477  * <pre>
1478  *    __printf("Differences between versions %s and %s of %s",
1479  *             $new_link, $old_link, $page_link);
1480  * </pre>
1481  *
1482  * Then in locale/po/de.po, one can reorder the printf arguments:
1483  *
1484  * <pre>
1485  *    msgid "Differences between %s and %s of %s."
1486  *    msgstr "Der Unterschiedsergebnis von %3$s, zwischen %1$s und %2$s."
1487  * </pre>
1488  *
1489  * (Note that while PHP tries to expand $vars within double-quotes,
1490  * the values in msgstr undergo no such expansion, so the '$'s
1491  * okay...)
1492  *
1493  * One shouldn't use reordered arguments in the default format string.
1494  * Backslashes in the default string would be necessary to escape the
1495  * '$'s, and they'll cause all kinds of trouble....
1496  */
1497 function __printf($fmt)
1498 {
1499     $args = func_get_args();
1500     array_shift($args);
1501     echo __vsprintf($fmt, $args);
1502 }
1503
1504 /**
1505  * Internationalized sprintf.
1506  *
1507  * This is essentially the same as PHP's built-in printf with the
1508  * following exceptions:
1509  *
1510  * <ol>
1511  * <li> It passes the format string through gettext().
1512  * <li> It supports the argument reordering extensions.
1513  * </ol>
1514  *
1515  * @see __printf
1516  */
1517 function __sprintf($fmt)
1518 {
1519     $args = func_get_args();
1520     array_shift($args);
1521     return __vsprintf($fmt, $args);
1522 }
1523
1524 /**
1525  * Internationalized vsprintf.
1526  *
1527  * This is essentially the same as PHP's built-in printf with the
1528  * following exceptions:
1529  *
1530  * <ol>
1531  * <li> It passes the format string through gettext().
1532  * <li> It supports the argument reordering extensions.
1533  * </ol>
1534  *
1535  * @see __printf
1536  */
1537 function __vsprintf($fmt, $args)
1538 {
1539     $fmt = gettext($fmt);
1540     // PHP's sprintf doesn't support variable with specifiers,
1541     // like sprintf("%*s", 10, "x"); --- so we won't either.
1542
1543     if (preg_match_all('/(?<!%)%(\d+)\$/x', $fmt, $m)) {
1544         // Format string has '%2$s' style argument reordering.
1545         // PHP doesn't support this.
1546         if (preg_match('/(?<!%)%[- ]?\d*[^- \d$]/x', $fmt))
1547             // literal variable name substitution only to keep locale
1548             // strings uncluttered
1549             trigger_error(sprintf(_("Can't mix '%s' with '%s' type format strings"),
1550                 '%1\$s', '%s'), E_USER_WARNING); //php+locale error
1551
1552         $fmt = preg_replace('/(?<!%)%\d+\$/x', '%', $fmt);
1553         $newargs = array();
1554
1555         // Reorder arguments appropriately.
1556         foreach ($m[1] as $argnum) {
1557             if ($argnum < 1 || $argnum > count($args))
1558                 trigger_error(sprintf(_("%s: argument index out of range"),
1559                     $argnum), E_USER_WARNING);
1560             $newargs[] = $args[$argnum - 1];
1561         }
1562         $args = $newargs;
1563     }
1564
1565     // Not all PHP's have vsprintf, so...
1566     array_unshift($args, $fmt);
1567     return call_user_func_array('sprintf', $args);
1568 }
1569
1570 function file_mtime($filename)
1571 {
1572     if ($stat = @stat($filename))
1573         return $stat[9];
1574     else
1575         return false;
1576 }
1577
1578 function sort_file_mtime($a, $b)
1579 {
1580     $ma = file_mtime($a);
1581     $mb = file_mtime($b);
1582     if (!$ma or !$mb or $ma == $mb) return 0;
1583     return ($ma > $mb) ? -1 : 1;
1584 }
1585
1586 class fileSet
1587 {
1588     /**
1589      * Build an array in $this->_fileList of files from $dirname.
1590      * Subdirectories are not traversed.
1591      *
1592      * (This was a function LoadDir in lib/loadsave.php)
1593      * See also http://www.php.net/manual/en/function.readdir.php
1594      */
1595     function getFiles($exclude = '', $sortby = '', $limit = '')
1596     {
1597         $list = $this->_fileList;
1598
1599         if ($sortby) {
1600             require_once 'lib/PageList.php';
1601             switch (Pagelist::sortby($sortby, 'db')) {
1602                 case 'pagename ASC':
1603                     break;
1604                 case 'pagename DESC':
1605                     $list = array_reverse($list);
1606                     break;
1607                 case 'mtime ASC':
1608                     usort($list, 'sort_file_mtime');
1609                     break;
1610                 case 'mtime DESC':
1611                     usort($list, 'sort_file_mtime');
1612                     $list = array_reverse($list);
1613                     break;
1614             }
1615         }
1616         if ($limit)
1617             return array_splice($list, 0, $limit);
1618         return $list;
1619     }
1620
1621     function _filenameSelector($filename)
1622     {
1623         if (!$this->_pattern)
1624             return true;
1625         else {
1626             if (!$this->_pcre_pattern)
1627                 $this->_pcre_pattern = glob_to_pcre($this->_pattern);
1628             return preg_match('/' . $this->_pcre_pattern . ($this->_case ? '/' : '/i'),
1629                 $filename);
1630         }
1631     }
1632
1633     function fileSet($directory, $filepattern = false)
1634     {
1635         $this->_fileList = array();
1636         $this->_pattern = $filepattern;
1637         if ($filepattern) {
1638             $this->_pcre_pattern = glob_to_pcre($this->_pattern);
1639         }
1640         $this->_case = !isWindows();
1641         $this->_pathsep = '/';
1642
1643         if (empty($directory)) {
1644             trigger_error(sprintf(_("%s is empty."), 'directoryname'),
1645                 E_USER_NOTICE);
1646             return; // early return
1647         }
1648
1649         @ $dir_handle = opendir($dir = $directory);
1650         if (empty($dir_handle)) {
1651             trigger_error(sprintf(_("Unable to open directory '%s' for reading"),
1652                 $dir), E_USER_NOTICE);
1653             return; // early return
1654         }
1655
1656         while ($filename = readdir($dir_handle)) {
1657             if ($filename[0] == '.' || filetype($dir . $this->_pathsep . $filename) != 'file')
1658                 continue;
1659             if ($this->_filenameSelector($filename)) {
1660                 array_push($this->_fileList, "$filename");
1661                 //trigger_error(sprintf(_("found file %s"), $filename),
1662                 //                      E_USER_NOTICE); //debugging
1663             }
1664         }
1665         closedir($dir_handle);
1666     }
1667 }
1668
1669
1670
1671 // File globbing
1672
1673 // expands a list containing regex's to its matching entries
1674 class ListRegexExpand
1675 {
1676     //var $match, $list, $index, $case_sensitive;
1677     function ListRegexExpand(&$list, $match, $case_sensitive = true)
1678     {
1679         $this->match = $match;
1680         $this->list = &$list;
1681         $this->case_sensitive = $case_sensitive;
1682         //$this->index = false;
1683     }
1684
1685     function listMatchCallback($item, $key)
1686     {
1687         $quoted = str_replace('/', '\/', $item);
1688         if (preg_match('/' . $this->match . ($this->case_sensitive ? '/' : '/i'),
1689             $quoted)
1690         ) {
1691             unset($this->list[$this->index]);
1692             $this->list[] = $item;
1693         }
1694     }
1695
1696     function expandRegex($index, &$pages)
1697     {
1698         $this->index = $index;
1699         array_walk($pages, array($this, 'listMatchCallback'));
1700         return $this->list;
1701     }
1702 }
1703
1704 // Convert fileglob to regex style:
1705 // Convert some wildcards to pcre style, escape the rest
1706 // Escape . \\ + * ? [ ^ ] $ ( ) { } = ! < > | : /
1707 // Fixed bug #994994: "/" in $glob.
1708 function glob_to_pcre($glob)
1709 {
1710     // check simple case: no need to escape
1711     $escape = '\[](){}=!<>|:/';
1712     if (strcspn($glob, $escape . ".+*?^$") == strlen($glob))
1713         return $glob;
1714     // preg_replace cannot handle "\\\\\\2" so convert \\ to \xff
1715     $glob = strtr($glob, "\\", "\xff");
1716     $glob = str_replace("/", "\\/", $glob);
1717     // first convert some unescaped expressions to pcre style: . => \.
1718     $special = '.^$';
1719     $re = preg_replace('/([^\xff])?([' . preg_quote($special) . '])/',
1720         "\\1\xff\\2", $glob);
1721
1722     // * => .*, ? => .
1723     $re = preg_replace('/([^\xff])?\*/', '$1.*', $re);
1724     $re = preg_replace('/([^\xff])?\?/', '$1.', $re);
1725     if (!preg_match('/^[\?\*]/', $glob))
1726         $re = '^' . $re;
1727     if (!preg_match('/[\?\*]$/', $glob))
1728         $re = $re . '$';
1729
1730     // Fixes Bug 1182997
1731     // .*? handled above, now escape the rest
1732     //while (strcspn($re, $escape) != strlen($re)) // loop strangely needed
1733     $re = preg_replace('/([^\xff])([' . preg_quote($escape, "/") . '])/',
1734         "\\1\xff\\2", $re);
1735     // Problem with 'Date/Time' => 'Date\/Time' => 'Date\xff\/Time' => 'Date\/Time'
1736     // 'plugin/*.php'
1737     $re = preg_replace('/\xff/', '', $re);
1738     return $re;
1739 }
1740
1741 function glob_match($glob, $against, $case_sensitive = true)
1742 {
1743     return preg_match('/' . glob_to_pcre($glob) . ($case_sensitive ? '/' : '/i'),
1744         $against);
1745 }
1746
1747 function explodeList($input, $allnames, $glob_style = true, $case_sensitive = true)
1748 {
1749     $list = explode(',', $input);
1750     // expand wildcards from list of $allnames
1751     if (preg_match('/[\?\*]/', $input)) {
1752         // Optimizing loop invariants:
1753         // http://phplens.com/lens/php-book/optimizing-debugging-php.php
1754         for ($i = 0, $max = sizeof($list); $i < $max; $i++) {
1755             $f = $list[$i];
1756             if (preg_match('/[\?\*]/', $f)) {
1757                 reset($allnames);
1758                 $expand = new ListRegexExpand($list,
1759                     $glob_style ? glob_to_pcre($f) : $f, $case_sensitive);
1760                 $expand->expandRegex($i, $allnames);
1761             }
1762         }
1763     }
1764     return $list;
1765 }
1766
1767 // echo implode(":",explodeList("Test*",array("xx","Test1","Test2")));
1768 function explodePageList($input, $include_empty = false, $sortby = 'pagename',
1769                          $limit = '', $exclude = '')
1770 {
1771     include_once 'lib/PageList.php';
1772     return PageList::explodePageList($input, $include_empty, $sortby, $limit, $exclude);
1773 }
1774
1775 // Class introspections
1776
1777 /**
1778  * Determine whether object is of a specified type.
1779  * In PHP builtin since 4.2.0 as is_a()
1780  * is_a() deprecated in PHP 5, in favor of instanceof operator
1781  * @param $object object An object.
1782  * @param $class string Class name.
1783  * @return bool True iff $object is a $class
1784  * or a sub-type of $class.
1785  */
1786 function isa($object, $class)
1787 {
1788     //if (check_php_version(5))
1789     //    return $object instanceof $class;
1790     if (!check_php_version(5))
1791         return is_a($object, $class);
1792
1793     $lclass = check_php_version(5) ? $class : strtolower($class);
1794     return is_object($object)
1795         && (strtolower(get_class($object)) == strtolower($class)
1796             || is_subclass_of($object, $lclass));
1797 }
1798
1799 /** Determine whether a function is okay to use.
1800  *
1801  * Some providers (e.g. Lycos) disable some of PHP functions for
1802  * "security reasons."  This makes those functions, of course,
1803  * unusable, despite the fact the function_exists() says they
1804  * exist.
1805  *
1806  * This function test to see if a function exists and is not
1807  * disallowed by PHP's disable_functions config setting.
1808  *
1809  * @param string $function_name  Function name
1810  * @return bool  True iff function can be used.
1811  */
1812 function function_usable($function_name)
1813 {
1814     static $disabled;
1815     if (!is_array($disabled)) {
1816         $disabled = array();
1817         // Use get_cfg_var since ini_get() is one of the disabled functions
1818         // (on Lycos, at least.)
1819         $split = preg_split('/\s*,\s*/', trim(get_cfg_var('disable_functions')));
1820         foreach ($split as $f)
1821             $disabled[strtolower($f)] = true;
1822     }
1823
1824     return (function_exists($function_name)
1825         and !isset($disabled[strtolower($function_name)])
1826     );
1827 }
1828
1829
1830 /** Hash a value.
1831  *
1832  * This is used for generating ETags.
1833  */
1834 function wikihash($x)
1835 {
1836     if (is_scalar($x)) {
1837         return $x;
1838     } elseif (is_array($x)) {
1839         ksort($x);
1840         return md5(serialize($x));
1841     } elseif (is_object($x)) {
1842         return $x->hash();
1843     }
1844     trigger_error("Can't hash $x", E_USER_ERROR);
1845 }
1846
1847
1848 /**
1849  * Seed the random number generator.
1850  *
1851  * better_srand() ensures the randomizer is seeded only once.
1852  *
1853  * How random do you want it? See:
1854  * http://www.php.net/manual/en/function.srand.php
1855  * http://www.php.net/manual/en/function.mt-srand.php
1856  */
1857 function better_srand($seed = '')
1858 {
1859     static $wascalled = FALSE;
1860     if (!$wascalled) {
1861         $seed = $seed === '' ? (double)microtime() * 1000000 : $seed;
1862         function_exists('mt_srand') ? mt_srand($seed) : srand($seed);
1863         $wascalled = TRUE;
1864         //trigger_error("new random seed", E_USER_NOTICE); //debugging
1865     }
1866 }
1867
1868 function rand_ascii($length = 1)
1869 {
1870     better_srand();
1871     $s = "";
1872     for ($i = 1; $i <= $length; $i++) {
1873         // return only typeable 7 bit ascii, avoid quotes
1874         if (function_exists('mt_rand'))
1875             $s .= chr(mt_rand(40, 126));
1876         else
1877             // the usually bad glibc srand()
1878             $s .= chr(rand(40, 126));
1879     }
1880     return $s;
1881 }
1882
1883 /* by Dan Frankowski.
1884  */
1885 function rand_ascii_readable($length = 6)
1886 {
1887     // Pick a few random letters or numbers
1888     $word = "";
1889     better_srand();
1890     // Don't use 1lI0O, because they're hard to read
1891     $letters = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789";
1892     $letter_len = strlen($letters);
1893     for ($i = 0; $i < $length; $i++) {
1894         if (function_exists('mt_rand'))
1895             $word .= $letters[mt_rand(0, $letter_len - 1)];
1896         else
1897             $word .= $letters[rand(0, $letter_len - 1)];
1898     }
1899     return $word;
1900 }
1901
1902 /**
1903  * Recursively count all non-empty elements
1904  * in array of any dimension or mixed - i.e.
1905  * array('1' => 2, '2' => array('1' => 3, '2' => 4))
1906  * See http://www.php.net/manual/en/function.count.php
1907  */
1908 function count_all($arg)
1909 {
1910     // skip if argument is empty
1911     if ($arg) {
1912         //print_r($arg); //debugging
1913         $count = 0;
1914         // not an array, return 1 (base case)
1915         if (!is_array($arg))
1916             return 1;
1917         // else call recursively for all elements $arg
1918         foreach ($arg as $key => $val)
1919             $count += count_all($val);
1920         return $count;
1921     }
1922 }
1923
1924 function isSubPage($pagename)
1925 {
1926     return (strstr($pagename, SUBPAGE_SEPARATOR));
1927 }
1928
1929 function subPageSlice($pagename, $pos)
1930 {
1931     $pages = explode(SUBPAGE_SEPARATOR, $pagename);
1932     $pages = array_slice($pages, $pos, 1);
1933     return $pages[0];
1934 }
1935
1936 function isActionPage($filename)
1937 {
1938
1939     global $AllActionPages;
1940
1941     $localizedAllActionPages = array_map("__", $AllActionPages);
1942
1943     return (in_array($filename, $localizedAllActionPages));
1944 }
1945
1946 /**
1947  * Alert
1948  *
1949  * Class for "popping up" and alert box.  (Except that right now, it doesn't
1950  * pop up...)
1951  *
1952  * FIXME:
1953  * This is a hackish and needs to be refactored.  However it would be nice to
1954  * unify all the different methods we use for showing Alerts and Dialogs.
1955  * (E.g. "Page deleted", login form, ...)
1956  */
1957 class Alert
1958 {
1959     /** Constructor
1960      *
1961      * @param object $request
1962      * @param mixed  $head    Header ("title") for alert box.
1963      * @param mixed  $body    The text in the alert box.
1964      * @param hash   $buttons An array mapping button labels to URLs.
1965      *    The default is a single "Okay" button pointing to $request->getURLtoSelf().
1966      */
1967     function Alert($head, $body, $buttons = false)
1968     {
1969         if ($buttons === false)
1970             $buttons = array();
1971
1972         if (is_array($body)) {
1973             $html = HTML::ol();
1974             foreach ($body as $li) {
1975                 $html->pushContent(HTML::li($li));
1976             }
1977             $body = $html;
1978         }
1979         $this->_tokens = array('HEADER' => $head, 'CONTENT' => $body);
1980         $this->_buttons = $buttons;
1981     }
1982
1983     /**
1984      * Show the alert box.
1985      */
1986     function show()
1987     {
1988         global $request;
1989
1990         $tokens = $this->_tokens;
1991         $tokens['BUTTONS'] = $this->_getButtons();
1992
1993         $request->discardOutput();
1994         $tmpl = new Template('dialog', $request, $tokens);
1995         $tmpl->printXML();
1996         $request->finish();
1997     }
1998
1999
2000     function _getButtons()
2001     {
2002         global $request;
2003
2004         $buttons = $this->_buttons;
2005         if (!$buttons)
2006             $buttons = array(_("OK") => $request->getURLtoSelf());
2007
2008         global $WikiTheme;
2009         foreach ($buttons as $label => $url)
2010             print "$label $url\n";
2011         $out[] = $WikiTheme->makeButton($label, $url, 'wikiaction');
2012         return new XmlContent($out);
2013     }
2014 }
2015
2016 // 1.3.8     => 1030.08
2017 // 1.3.9-p1  => 1030.091
2018 // 1.3.10pre => 1030.099
2019 // 1.3.11pre-20041120 => 1030.1120041120
2020 // 1.3.12-rc1 => 1030.119
2021 function phpwiki_version()
2022 {
2023     static $PHPWIKI_VERSION;
2024     if (!isset($PHPWIKI_VERSION)) {
2025         $arr = explode('.', preg_replace('/\D+$/', '', PHPWIKI_VERSION)); // remove the pre
2026         $arr[2] = preg_replace('/\.+/', '.', preg_replace('/\D/', '.', $arr[2]));
2027         $PHPWIKI_VERSION = $arr[0] * 1000 + $arr[1] * 10 + 0.01 * $arr[2];
2028         if (strstr(PHPWIKI_VERSION, 'pre') or strstr(PHPWIKI_VERSION, 'rc'))
2029             $PHPWIKI_VERSION -= 0.01;
2030     }
2031     return $PHPWIKI_VERSION;
2032 }
2033
2034 function phpwiki_gzhandler($ob)
2035 {
2036     if (function_exists('gzencode'))
2037         $ob = gzencode($ob);
2038     $GLOBALS['request']->_ob_get_length = strlen($ob);
2039     if (!headers_sent()) {
2040         header(sprintf("Content-Length: %d", $GLOBALS['request']->_ob_get_length));
2041     }
2042     return $ob;
2043 }
2044
2045 function isWikiWord($word)
2046 {
2047     global $WikiNameRegexp;
2048     //or preg_match('/\A' . $WikiNameRegexp . '\z/', $word) ??
2049     return preg_match("/^$WikiNameRegexp\$/", $word);
2050 }
2051
2052 // needed to store serialized objects-values only (perm, pref)
2053 function obj2hash($obj, $exclude = false, $fields = false)
2054 {
2055     $a = array();
2056     if (!$fields) $fields = get_object_vars($obj);
2057     foreach ($fields as $key => $val) {
2058         if (is_array($exclude)) {
2059             if (in_array($key, $exclude)) continue;
2060         }
2061         $a[$key] = $val;
2062     }
2063     return $a;
2064 }
2065
2066 /**
2067  * isAsciiString($string)
2068  */
2069 function isAsciiString($s)
2070 {
2071     $ptrASCII = '[\x00-\x7F]';
2072     return preg_match("/^($ptrASCII)*$/s", $s);
2073 }
2074
2075 /**
2076  * isUtf8String($string) - cheap utf-8 detection
2077  *
2078  * segfaults for strings longer than 10kb!
2079  * Use http://www.phpdiscuss.com/article.php?id=565&group=php.i18n or
2080  * checkTitleEncoding() at http://cvs.sourceforge.net/viewcvs.py/wikipedia/phase3/languages/Language.php
2081  */
2082 function isUtf8String($s)
2083 {
2084     $ptrASCII = '[\x00-\x7F]';
2085     $ptr2Octet = '[\xC2-\xDF][\x80-\xBF]';
2086     $ptr3Octet = '[\xE0-\xEF][\x80-\xBF]{2}';
2087     $ptr4Octet = '[\xF0-\xF4][\x80-\xBF]{3}';
2088     $ptr5Octet = '[\xF8-\xFB][\x80-\xBF]{4}';
2089     $ptr6Octet = '[\xFC-\xFD][\x80-\xBF]{5}';
2090     return preg_match("/^($ptrASCII|$ptr2Octet|$ptr3Octet|$ptr4Octet|$ptr5Octet|$ptr6Octet)*$/s", $s);
2091 }
2092
2093 /**
2094  * Check for UTF-8 URLs; Internet Explorer produces these if you
2095  * type non-ASCII chars in the URL bar or follow unescaped links.
2096  * Requires urldecoded pagename.
2097  * Fixes sf.net bug #953949
2098  *
2099  * src: languages/Language.php:checkTitleEncoding() from mediawiki
2100  */
2101 function fixTitleEncoding($s)
2102 {
2103     global $charset;
2104
2105     $s = trim($s);
2106     // print a warning?
2107     if (empty($s)) return $s;
2108
2109     $ishigh = preg_match('/[\x80-\xff]/', $s);
2110     /*
2111     $isutf = ($ishigh ? preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2112                                     '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s ) : true );
2113     */
2114     $isutf = ($ishigh ? isUtf8String($s) : true);
2115     $locharset = strtolower($charset);
2116
2117     if ($locharset != "utf-8" and $ishigh and $isutf)
2118         $s = charset_convert('UTF-8', $locharset, $s);
2119     if ($locharset == "utf-8" and $ishigh and !$isutf)
2120         return utf8_encode($s);
2121
2122     // Other languages can safely leave this function, or replace
2123     // it with one to detect and convert another legacy encoding.
2124     return $s;
2125 }
2126
2127 /**
2128  * MySQL fulltext index doesn't grok utf-8, so we
2129  * need to fold cases and convert to hex.
2130  * src: languages/Language.php:stripForSearch() from mediawiki
2131  */
2132 /*
2133 function stripForSearch( $string ) {
2134     global $wikiLowerChars;
2135     // '/(?:[a-z]|\xc3[\x9f-\xbf]|\xc4[\x81\x83\x85\x87])/' => "a-z\xdf-\xf6\xf8-\xff"
2136     return preg_replace(
2137                         "/([\\xc0-\\xff][\\x80-\\xbf]*)/e",
2138                         "'U8' . bin2hex( strtr( \"\$1\", \$wikiLowerChars ) )",
2139                         $string );
2140 }
2141 */
2142
2143 /**
2144  * Workaround for allow_url_fopen, to get the content of an external URI.
2145  * It returns the contents in one slurp. Parsers might want to check for allow_url_fopen
2146  * and use fopen, fread chunkwise. (see lib/XmlParser.php)
2147  */
2148 function url_get_contents($uri)
2149 {
2150     if (get_cfg_var('allow_url_fopen')) { // was ini_get('allow_url_fopen'))
2151         return @file_get_contents($uri);
2152     } else {
2153         require_once 'lib/HttpClient.php';
2154         $bits = parse_url($uri);
2155         $host = $bits['host'];
2156         $port = isset($bits['port']) ? $bits['port'] : 80;
2157         $path = isset($bits['path']) ? $bits['path'] : '/';
2158         if (isset($bits['query'])) {
2159             $path .= '?' . $bits['query'];
2160         }
2161         $client = new HttpClient($host, $port);
2162         $client->use_gzip = false;
2163         if (!$client->get($path)) {
2164             return false;
2165         } else {
2166             return $client->getContent();
2167         }
2168     }
2169 }
2170
2171 /**
2172  * Generate consecutively named strings:
2173  *   Name, Name2, Name3, ...
2174  */
2175 function GenerateId($name)
2176 {
2177     static $ids = array();
2178     if (empty($ids[$name])) {
2179         $ids[$name] = 1;
2180         return $name;
2181     } else {
2182         $ids[$name]++;
2183         return $name . $ids[$name];
2184     }
2185 }
2186
2187 // from IncludePage. To be of general use.
2188 // content: string or array of strings
2189 function firstNWordsOfContent($n, $content)
2190 {
2191     if ($content and $n > 0) {
2192         if (is_array($content)) {
2193             // fixme: return a list of lines then?
2194             //$content = join("\n", $content);
2195             //$return_array = true;
2196             $wordcount = 0;
2197             foreach ($content as $line) {
2198                 $words = explode(' ', $line);
2199                 if ($wordcount + count($words) > $n) {
2200                     $new[] = implode(' ', array_slice($words, 0, $n - $wordcount))
2201                         . sprintf(_("... (first %s words)"), $n);
2202                     return $new;
2203                 } else {
2204                     $wordcount += count($words);
2205                     $new[] = $line;
2206                 }
2207             }
2208             return $new;
2209         } else {
2210             // fixme: use better whitespace/word seperators
2211             $words = explode(' ', $content);
2212             if (count($words) > $n) {
2213                 return join(' ', array_slice($words, 0, $n))
2214                     . sprintf(_("... (first %s words)"), $n);
2215             } else {
2216                 return $content;
2217             }
2218         }
2219     } else {
2220         return '';
2221     }
2222 }
2223
2224 // moved from lib/plugin/IncludePage.php
2225 function extractSection($section, $content, $page, $quiet = false, $sectionhead = false)
2226 {
2227     $qsection = preg_replace('/\s+/', '\s+', preg_quote($section, '/'));
2228
2229     if (preg_match("/ ^(!{1,}|={2,})\\s*$qsection\s*=*" // section header
2230             . "  \\s*$\\n?" // possible blank lines
2231             . "  ( (?: ^.*\\n? )*? )" // some lines
2232             . "  (?= ^\\1 | \\Z)/xm", // sec header (same or higher level) (or EOF)
2233         implode("\n", $content),
2234         $match)
2235     ) {
2236         // Strip trailing blanks lines and ---- <hr>s
2237         $text = preg_replace("/\\s*^-{4,}\\s*$/m", "", $match[2]);
2238         if ($sectionhead)
2239             $text = $match[1] . $section . "\n" . $text;
2240         return explode("\n", $text);
2241     }
2242     if ($quiet)
2243         $mesg = $page . " " . $section;
2244     else
2245         $mesg = $section;
2246     return array(sprintf(_("<%s: no such section>"), $mesg));
2247 }
2248
2249 // Extract the first $sections sections of the page
2250 function extractSections($sections, $content, $page, $quiet = false, $sectionhead = false)
2251 {
2252
2253     $mycontent = $content;
2254     $result = "";
2255
2256     while ($sections > 0) {
2257
2258         if (preg_match("/ ^(!{1,}|={2,})\\s*(.*)\\n" // section header
2259                 . "  \\s*$\\n?" // possible blank lines
2260                 . "  ( (?: ^.*\\n? )*? )" // some lines
2261                 . "  ( ^\\1 (.|\\n)* | \\Z)/xm", // sec header (same or higher level) (or EOF)
2262             implode("\n", $mycontent),
2263             $match)
2264         ) {
2265             $section = $match[2];
2266             // Strip trailing blanks lines and ---- <hr>s
2267             $text = preg_replace("/\\s*^-{4,}\\s*$/m", "", $match[3]);
2268             if ($sectionhead)
2269                 $text = $match[1] . $section . "\n" . $text;
2270             $result .= $text;
2271
2272             $mycontent = explode("\n", $match[4]);
2273             $sections--;
2274             if ($sections === 0) {
2275                 return explode("\n", $result);
2276             }
2277         }
2278     }
2279 }
2280
2281 // use this faster version: only load ExternalReferrer if we came from an external referrer
2282 function isExternalReferrer(&$request)
2283 {
2284     if ($referrer = $request->get('HTTP_REFERER')) {
2285         $home = SERVER_URL; // SERVER_URL or SCRIPT_NAME, if we want to check sister wiki's also
2286         if (string_starts_with(strtolower($referrer), strtolower($home))) return false;
2287         require_once 'lib/ExternalReferrer.php';
2288         $se = new SearchEngines();
2289         return $se->parseSearchQuery($referrer);
2290     }
2291     //if (DEBUG) return array('query' => 'wiki');
2292     return false;
2293 }
2294
2295 /**
2296  * Useful for PECL overrides: cvsclient, ldap, soap, xmlrpc, pdo, pdo_<driver>
2297  */
2298 function loadPhpExtension($extension)
2299 {
2300     if (!extension_loaded($extension)) {
2301         $isWindows = (substr(PHP_OS, 0, 3) == 'WIN');
2302         $soname = ($isWindows ? 'php_' : '')
2303             . $extension
2304             . ($isWindows ? '.dll' : '.so');
2305         if (!@dl($soname))
2306             return false;
2307     }
2308     return extension_loaded($extension);
2309 }
2310
2311 function charset_convert($from, $to, $data)
2312 {
2313     //global $CHARSET;
2314     //$wikicharset = strtolower($CHARSET);
2315     //$systemcharset = strtolower(get_cfg_var('iconv.internal_encoding')); // 'iso-8859-1';
2316     if (strtolower($from) == 'utf-8' and strtolower($to) == 'iso-8859-1')
2317         return utf8_decode($data);
2318     if (strtolower($to) == 'utf-8' and strtolower($from) == 'iso-8859-1')
2319         return utf8_encode($data);
2320
2321     if (loadPhpExtension("iconv")) {
2322         $tmpdata = iconv($from, $to, $data);
2323         if (!$tmpdata)
2324             trigger_error("charset conversion $from => $to failed. Wrong source charset?", E_USER_WARNING);
2325         else
2326             $data = $tmpdata;
2327     } else {
2328         trigger_error("The iconv extension cannot be loaded", E_USER_WARNING);
2329     }
2330     return $data;
2331 }
2332
2333 function string_starts_with($string, $prefix)
2334 {
2335     return (substr($string, 0, strlen($prefix)) == $prefix);
2336 }
2337
2338 function string_ends_with($string, $suffix)
2339 {
2340     return (substr($string, -strlen($suffix)) == $suffix);
2341 }
2342
2343 function array_remove($arr, $value)
2344 {
2345     return array_values(array_diff($arr, array($value)));
2346 }
2347
2348 /**
2349  * Ensure that the script will have another $secs time left.
2350  * Works only if safe_mode is off.
2351  * For example not to timeout on waiting socket connections.
2352  *   Use the socket timeout as arg.
2353  */
2354 function longer_timeout($secs = 30)
2355 {
2356     $timeout = @ini_get("max_execution_time") ? ini_get("max_execution_time") : 30;
2357     $timeleft = $timeout - $GLOBALS['RUNTIMER']->getTime();
2358     if ($timeleft < $secs)
2359         @set_time_limit(max($timeout, (integer)($secs + $timeleft)));
2360 }
2361
2362 function printSimpleTrace($bt)
2363 {
2364     //print_r($bt);
2365     echo "\nTraceback:\n";
2366     if (function_exists('debug_print_backtrace')) { // >= 5
2367         debug_print_backtrace();
2368     } else {
2369         foreach ($bt as $i => $elem) {
2370             if (!array_key_exists('file', $elem)) {
2371                 continue;
2372             }
2373             //echo join(" ",array_values($elem)),"\n";
2374             echo "  ", $elem['file'], ':', $elem['line'], " ", $elem['function'], "\n";
2375         }
2376     }
2377 }
2378
2379 /**
2380  * Return the used process memory, in bytes.
2381  * Enable the section which will work for you. They are very slow.
2382  * Special quirks for Windows: Requires cygwin.
2383  */
2384 function getMemoryUsage()
2385 {
2386     //if (!(DEBUG & _DEBUG_VERBOSE)) return;
2387     if (function_exists('memory_get_usage') and memory_get_usage()) {
2388         return memory_get_usage();
2389     } elseif (function_exists('getrusage') and ($u = @getrusage()) and !empty($u['ru_maxrss'])) {
2390         $mem = $u['ru_maxrss'];
2391     } elseif (substr(PHP_OS, 0, 3) == 'WIN') { // may require a newer cygwin
2392         // what we want is the process memory only: apache or php (if CGI)
2393         $pid = getmypid();
2394         $memstr = '';
2395         // win32_ps_stat_proc, win32_ps_stat_mem
2396         if (function_exists('win32_ps_list_procs')) {
2397             $info = win32_ps_stat_proc($pid);
2398             $memstr = $info['mem']['working_set_size'];
2399         } elseif (0) {
2400             // This works only if it's a cygwin process (apache or php).
2401             // Requires a newer cygwin
2402             $memstr = exec("cat /proc/$pid/statm |cut -f1");
2403
2404             // if it's native windows use something like this:
2405             //   (requires pslist from sysinternals.com, grep, sed and perl)
2406             //$memstr = exec("pslist $pid|grep -A1 Mem|sed 1d|perl -ane\"print \$"."F[5]\"");
2407         }
2408         return (integer)trim($memstr);
2409     } elseif (1) {
2410         $pid = getmypid();
2411         //%MEM: Percentage of total memory in use by this process
2412         //VSZ: Total virtual memory size, in 1K blocks.
2413         //RSS: Real Set Size, the actual amount of physical memory allocated to this process.
2414         //CPU time used by process since it started.
2415         //echo "%",`ps -o%mem,vsz,rss,time -p $pid|sed 1d`,"\n";
2416         $memstr = exec("ps -orss -p $pid|sed 1d");
2417         return (integer)trim($memstr);
2418     }
2419 }
2420
2421 /**
2422  * @param var $needle
2423  * @param array $haystack one-dimensional numeric array only, no hash
2424  * @return integer
2425  * @desc Feed a sorted array to $haystack and a value to search for to $needle.
2426 It will return false if not found or the index where it was found.
2427 From dennis.decoene@moveit.be http://www.php.net/array_search
2428  */
2429 function binary_search($needle, $haystack)
2430 {
2431     $high = count($haystack);
2432     $low = 0;
2433
2434     while (($high - $low) > 1) {
2435         $probe = floor(($high + $low) / 2);
2436         if ($haystack[$probe] < $needle) {
2437             $low = $probe;
2438         } elseif ($haystack[$probe] == $needle) {
2439             $high = $low = $probe;
2440         } else {
2441             $high = $probe;
2442         }
2443     }
2444
2445     if ($high == count($haystack) || $haystack[$high] != $needle) {
2446         return false;
2447     } else {
2448         return $high;
2449     }
2450 }
2451
2452 function is_localhost()
2453 {
2454     return $_SERVER['SERVER_ADDR'] == '127.0.0.1';
2455 }
2456
2457 /**
2458  * Take a string and quote it sufficiently to be passed as a Javascript
2459  * string between ''s
2460  */
2461 function javascript_quote_string($s)
2462 {
2463     return str_replace("'", "\'", $s);
2464 }
2465
2466 function isSerialized($s)
2467 {
2468     return (!empty($s) and (strlen($s) > 3) and (substr($s, 1, 1) == ':'));
2469 }
2470
2471 /**
2472  * Determine if a variable represents a whole number
2473  */
2474
2475 function is_whole_number($var)
2476 {
2477     return (is_numeric($var) && (intval($var) == floatval($var)));
2478 }
2479
2480 /**
2481  * Take a string and return an array of pairs (attribute name, attribute value)
2482  *
2483  * We allow attributes with or without double quotes (")
2484  * Attribute-value pairs may be separated by space or comma
2485  * Space is normal HTML attributes, comma is for RichTable compatibility
2486  * border=1, cellpadding="5"
2487  * border=1 cellpadding="5"
2488  * style="font-family: sans-serif; border-top:1px solid #dddddd;"
2489  * style="font-family: Verdana, Arial, Helvetica, sans-serif"
2490  */
2491 function parse_attributes($line)
2492 {
2493
2494     $options = array();
2495
2496     if (empty($line)) return $options;
2497     $line = trim($line);
2498     if (empty($line)) return $options;
2499     $line = trim($line, ",");
2500     if (empty($line)) return $options;
2501
2502     // First we have an attribute name.
2503     $attribute = "";
2504     $value = "";
2505
2506     $i = 0;
2507     while (($i < strlen($line)) && ($line[$i] != '=')) {
2508         $i++;
2509     }
2510     $attribute = substr($line, 0, $i);
2511     $attribute = strtolower($attribute);
2512
2513     $line = substr($line, $i + 1);
2514     $line = trim($line);
2515     $line = trim($line, "=");
2516     $line = trim($line);
2517
2518     if (empty($line)) return $options;
2519
2520     // Then we have the attribute value.
2521
2522     $i = 0;
2523     // Attribute value might be between double quotes
2524     // In that case we have to find the closing double quote
2525     if ($line[0] == '"') {
2526         $i++; // skip first '"'
2527         while (($i < strlen($line)) && ($line[$i] != '"')) {
2528             $i++;
2529         }
2530         $value = substr($line, 0, $i);
2531         $value = trim($value, '"');
2532         $value = trim($value);
2533
2534         // If there are no double quotes, we have to find the next space or comma
2535     } else {
2536         while (($i < strlen($line)) && (($line[$i] != ' ') && ($line[$i] != ','))) {
2537             $i++;
2538         }
2539         $value = substr($line, 0, $i);
2540         $value = trim($value);
2541         $value = trim($value, ",");
2542         $value = trim($value);
2543     }
2544
2545     $options[$attribute] = $value;
2546
2547     $line = substr($line, $i + 1);
2548     $line = trim($line);
2549     $line = trim($line, ",");
2550     $line = trim($line);
2551
2552     return $options + parse_attributes($line);
2553 }
2554
2555 /**
2556  * Returns true if the filename ends with an image suffix.
2557  * Uses INLINE_IMAGES if defined, else "png|jpg|jpeg|gif"
2558  */
2559 function is_image($filename)
2560 {
2561
2562     if (defined('INLINE_IMAGES')) {
2563         $inline_images = INLINE_IMAGES;
2564     } else {
2565         $inline_images = "png|jpg|jpeg|gif";
2566     }
2567
2568     foreach (explode("|", $inline_images) as $suffix) {
2569         if (string_ends_with(strtolower($filename), "." . $suffix)) {
2570             return true;
2571         }
2572     }
2573     return false;
2574 }
2575
2576 /**
2577  * Returns true if the filename ends with an video suffix.
2578  * Currently only FLV and OGG
2579  */
2580 function is_video($filename)
2581 {
2582
2583     return string_ends_with(strtolower($filename), ".flv")
2584         or string_ends_with(strtolower($filename), ".ogg");
2585 }
2586
2587 /**
2588  * Remove accents from given text.
2589  */
2590 function strip_accents($text)
2591 {
2592     $res = utf8_decode($text);
2593     $res = strtr($res,
2594         utf8_decode('àáâãäçèéêëìíîïñòóôõöùúûüýÿÀÁÂÃÄÇÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜÝ'),
2595         'aaaaaceeeeiiiinooooouuuuyyAAAAACEEEEIIIINOOOOOUUUUY');
2596     return utf8_encode($res);
2597 }
2598
2599 // Local Variables:
2600 // mode: php
2601 // tab-width: 8
2602 // c-basic-offset: 4
2603 // c-hanging-comment-ender-p: nil
2604 // indent-tabs-mode: nil
2605 // End: