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