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