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