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