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