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