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