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