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