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