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