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