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