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