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