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