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