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