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