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