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