]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/stdlib.php
Valid HTML: escape ampersand
[SourceForge/phpwiki.git] / lib / stdlib.php
1 <?php //rcs_id('$Id: stdlib.php,v 1.270 2008-01-31 20:21:12 vargenau 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 .= '&amp;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 ($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         $this->_case = !isWindows();
1456         $this->_pathsep = '/';
1457
1458         if (empty($directory)) {
1459             trigger_error(sprintf(_("%s is empty."), 'directoryname'),
1460                           E_USER_NOTICE);
1461             return; // early return
1462         }
1463
1464         @ $dir_handle = opendir($dir=$directory);
1465         if (empty($dir_handle)) {
1466             trigger_error(sprintf(_("Unable to open directory '%s' for reading"),
1467                                   $dir), E_USER_NOTICE);
1468             return; // early return
1469         }
1470
1471         while ($filename = readdir($dir_handle)) {
1472             if ($filename[0] == '.' || filetype($dir . $this->_pathsep . $filename) != 'file')
1473                 continue;
1474             if ($this->_filenameSelector($filename)) {
1475                 array_push($this->_fileList, "$filename");
1476                 //trigger_error(sprintf(_("found file %s"), $filename),
1477                 //                      E_USER_NOTICE); //debugging
1478             }
1479         }
1480         closedir($dir_handle);
1481     }
1482 };
1483
1484 // File globbing
1485
1486 // expands a list containing regex's to its matching entries
1487 class ListRegexExpand {
1488     //var $match, $list, $index, $case_sensitive;
1489     function ListRegexExpand (&$list, $match, $case_sensitive = true) {
1490         $this->match = $match;
1491         $this->list = &$list;
1492         $this->case_sensitive = $case_sensitive;        
1493         //$this->index = false;
1494     }
1495     function listMatchCallback ($item, $key) {
1496         $quoted = str_replace('/','\/',$item);
1497         if (preg_match('/' . $this->match . ($this->case_sensitive ? '/' : '/i'), 
1498                        $quoted)) {
1499             unset($this->list[$this->index]);
1500             $this->list[] = $item;
1501         }
1502     }
1503     function expandRegex ($index, &$pages) {
1504         $this->index = $index;
1505         array_walk($pages, array($this, 'listMatchCallback'));
1506         return $this->list;
1507     }
1508 }
1509
1510 // Convert fileglob to regex style:
1511 // Convert some wildcards to pcre style, escape the rest
1512 // Escape . \\ + * ? [ ^ ] $ ( ) { } = ! < > | : /
1513 // Fixed bug #994994: "/" in $glob.
1514 function glob_to_pcre ($glob) {
1515     // check simple case: no need to escape
1516     $escape = '\[](){}=!<>|:/';
1517     if (strcspn($glob, $escape . ".+*?^$") == strlen($glob))
1518         return $glob;
1519     // preg_replace cannot handle "\\\\\\2" so convert \\ to \xff
1520     $glob = strtr($glob, "\\", "\xff");
1521     $glob = str_replace("/", "\\/", $glob);
1522     // first convert some unescaped expressions to pcre style: . => \.
1523     $special = ".^$";
1524     $re = preg_replace('/([^\xff])?(['.preg_quote($special).'])/', 
1525                        "\\1\xff\\2", $glob);
1526
1527     // * => .*, ? => .
1528     $re = preg_replace('/([^\xff])?\*/', '$1.*', $re);
1529     $re = preg_replace('/([^\xff])?\?/', '$1.', $re);
1530     if (!preg_match('/^[\?\*]/', $glob))
1531         $re = '^' . $re;
1532     if (!preg_match('/[\?\*]$/', $glob))
1533         $re = $re . '$';
1534
1535     // Fixes Bug 1182997
1536     // .*? handled above, now escape the rest
1537     //while (strcspn($re, $escape) != strlen($re)) // loop strangely needed
1538     $re = preg_replace('/([^\xff])(['.preg_quote($escape, "/").'])/', 
1539                        "\\1\xff\\2", $re);
1540     return strtr($re, "\xff", "");
1541 }
1542
1543 function glob_match ($glob, $against, $case_sensitive = true) {
1544     return preg_match('/' . glob_to_pcre($glob) . ($case_sensitive ? '/' : '/i'), 
1545                       $against);
1546 }
1547
1548 function explodeList($input, $allnames, $glob_style = true, $case_sensitive = true) {
1549     $list = explode(',',$input);
1550     // expand wildcards from list of $allnames
1551     if (preg_match('/[\?\*]/',$input)) {
1552         // Optimizing loop invariants:
1553         // http://phplens.com/lens/php-book/optimizing-debugging-php.php
1554         for ($i = 0, $max = sizeof($list); $i < $max; $i++) {
1555             $f = $list[$i];
1556             if (preg_match('/[\?\*]/',$f)) {
1557                 reset($allnames);
1558                 $expand = new ListRegexExpand($list, 
1559                     $glob_style ? glob_to_pcre($f) : $f, $case_sensitive);
1560                 $expand->expandRegex($i, $allnames);
1561             }
1562         }
1563     }
1564     return $list;
1565 }
1566
1567 // echo implode(":",explodeList("Test*",array("xx","Test1","Test2")));
1568 function explodePageList($input, $include_empty=false, $sortby='pagename', 
1569                          $limit='', $exclude='') {
1570     include_once("lib/PageList.php");
1571     return PageList::explodePageList($input, $include_empty, $sortby, $limit, $exclude);
1572 }
1573
1574 // Class introspections
1575
1576 /** 
1577  * Determine whether object is of a specified type.
1578  * In PHP builtin since 4.2.0 as is_a()
1579  * is_a() deprecated in PHP 5, in favor of instanceof operator
1580
1581  * @param $object object An object.
1582  * @param $class string Class name.
1583  * @return bool True iff $object is a $class
1584  * or a sub-type of $class. 
1585  */
1586 function isa ($object, $class) {
1587     //if (check_php_version(5)) 
1588     //    return $object instanceof $class;
1589     if (check_php_version(4,2) and !check_php_version(5)) 
1590         return is_a($object, $class);
1591
1592     $lclass = check_php_version(5) ? $class : strtolower($class);
1593     return is_object($object)
1594         && ( strtolower(get_class($object)) == strtolower($class)
1595              || is_subclass_of($object, $lclass) );
1596 }
1597
1598 /** Determine whether (possible) object has method.
1599  *
1600  * @param $object mixed Object
1601  * @param $method string Method name
1602  * @return bool True iff $object is an object with has method $method.
1603  */
1604 function can ($object, $method) {
1605     return is_object($object) && method_exists($object, strtolower($method));
1606 }
1607
1608 /** Determine whether a function is okay to use.
1609  *
1610  * Some providers (e.g. Lycos) disable some of PHP functions for
1611  * "security reasons."  This makes those functions, of course,
1612  * unusable, despite the fact the function_exists() says they
1613  * exist.
1614  *
1615  * This function test to see if a function exists and is not
1616  * disallowed by PHP's disable_functions config setting.
1617  *
1618  * @param string $function_name  Function name
1619  * @return bool  True iff function can be used.
1620  */
1621 function function_usable($function_name) {
1622     static $disabled;
1623     if (!is_array($disabled)) {
1624         $disabled = array();
1625         // Use get_cfg_var since ini_get() is one of the disabled functions
1626         // (on Lycos, at least.)
1627         $split = preg_split('/\s*,\s*/', trim(get_cfg_var('disable_functions')));
1628         foreach ($split as $f)
1629             $disabled[strtolower($f)] = true;
1630     }
1631
1632     return ( function_exists($function_name)
1633              and ! isset($disabled[strtolower($function_name)])
1634              );
1635 }
1636     
1637     
1638 /** Hash a value.
1639  *
1640  * This is used for generating ETags.
1641  */
1642 function wikihash ($x) {
1643     if (is_scalar($x)) {
1644         return $x;
1645     }
1646     elseif (is_array($x)) {            
1647         ksort($x);
1648         return md5(serialize($x));
1649     }
1650     elseif (is_object($x)) {
1651         return $x->hash();
1652     }
1653     trigger_error("Can't hash $x", E_USER_ERROR);
1654 }
1655
1656
1657 /**
1658  * Seed the random number generator.
1659  *
1660  * better_srand() ensures the randomizer is seeded only once.
1661  * 
1662  * How random do you want it? See:
1663  * http://www.php.net/manual/en/function.srand.php
1664  * http://www.php.net/manual/en/function.mt-srand.php
1665  */
1666 function better_srand($seed = '') {
1667     static $wascalled = FALSE;
1668     if (!$wascalled) {
1669         $seed = $seed === '' ? (double) microtime() * 1000000 : $seed;
1670         function_exists('mt_srand') ? mt_srand($seed) : srand($seed);
1671         $wascalled = TRUE;
1672         //trigger_error("new random seed", E_USER_NOTICE); //debugging
1673     }
1674 }
1675
1676 function rand_ascii($length = 1) {
1677     better_srand();
1678     $s = "";
1679     for ($i = 1; $i <= $length; $i++) {
1680         // return only typeable 7 bit ascii, avoid quotes
1681         if (function_exists('mt_rand'))
1682             $s .= chr(mt_rand(40, 126)); 
1683         else
1684             // the usually bad glibc srand()
1685             $s .= chr(rand(40, 126));
1686     }
1687     return $s;
1688 }
1689
1690 /* by Dan Frankowski.
1691  */
1692 function rand_ascii_readable ($length = 6) {
1693     // Pick a few random letters or numbers
1694     $word = "";
1695     better_srand();
1696     // Don't use 1lI0O, because they're hard to read
1697     $letters = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789";
1698     $letter_len = strlen($letters);
1699     for ($i=0; $i < $length; $i++) {
1700         if (function_exists('mt_rand'))
1701             $word .= $letters[mt_rand(0, $letter_len-1)];
1702         else
1703             $word .= $letters[rand(0, $letter_len-1)];
1704     }
1705     return $word;
1706 }
1707
1708 /**
1709  * Recursively count all non-empty elements 
1710  * in array of any dimension or mixed - i.e. 
1711  * array('1' => 2, '2' => array('1' => 3, '2' => 4))
1712  * See http://www.php.net/manual/en/function.count.php
1713  */
1714 function count_all($arg) {
1715     // skip if argument is empty
1716     if ($arg) {
1717         //print_r($arg); //debugging
1718         $count = 0;
1719         // not an array, return 1 (base case) 
1720         if(!is_array($arg))
1721             return 1;
1722         // else call recursively for all elements $arg
1723         foreach($arg as $key => $val)
1724             $count += count_all($val);
1725         return $count;
1726     }
1727 }
1728
1729 function isSubPage($pagename) {
1730     return (strstr($pagename, SUBPAGE_SEPARATOR));
1731 }
1732
1733 function subPageSlice($pagename, $pos) {
1734     $pages = explode(SUBPAGE_SEPARATOR,$pagename);
1735     $pages = array_slice($pages,$pos,1);
1736     return $pages[0];
1737 }
1738
1739 /**
1740  * Alert
1741  *
1742  * Class for "popping up" and alert box.  (Except that right now, it doesn't
1743  * pop up...)
1744  *
1745  * FIXME:
1746  * This is a hackish and needs to be refactored.  However it would be nice to
1747  * unify all the different methods we use for showing Alerts and Dialogs.
1748  * (E.g. "Page deleted", login form, ...)
1749  */
1750 class Alert {
1751     /** Constructor
1752      *
1753      * @param object $request
1754      * @param mixed $head  Header ("title") for alert box.
1755      * @param mixed $body  The text in the alert box.
1756      * @param hash $buttons  An array mapping button labels to URLs.
1757      *    The default is a single "Okay" button pointing to $request->getURLtoSelf().
1758      */
1759     function Alert($head, $body, $buttons=false) {
1760         if ($buttons === false)
1761             $buttons = array();
1762
1763         if (is_array($body)) {
1764             $html = HTML::ol();
1765             foreach ($body as $li) {
1766                 $html->pushContent(HTML::li($li));
1767             }
1768             $body = $html;
1769         }
1770         $this->_tokens = array('HEADER' => $head, 'CONTENT' => $body);
1771         $this->_buttons = $buttons;
1772     }
1773
1774     /**
1775      * Show the alert box.
1776      */
1777     function show() {
1778         global $request;
1779
1780         $tokens = $this->_tokens;
1781         $tokens['BUTTONS'] = $this->_getButtons();
1782         
1783         $request->discardOutput();
1784         $tmpl = new Template('dialog', $request, $tokens);
1785         $tmpl->printXML();
1786         $request->finish();
1787     }
1788
1789
1790     function _getButtons() {
1791         global $request;
1792
1793         $buttons = $this->_buttons;
1794         if (!$buttons)
1795             $buttons = array(_("Okay") => $request->getURLtoSelf());
1796         
1797         global $WikiTheme;
1798         foreach ($buttons as $label => $url)
1799             print "$label $url\n";
1800             $out[] = $WikiTheme->makeButton($label, $url, 'wikiaction');
1801         return new XmlContent($out);
1802     }
1803 }
1804
1805 // 1.3.8     => 1030.08
1806 // 1.3.9-p1  => 1030.091
1807 // 1.3.10pre => 1030.099
1808 // 1.3.11pre-20041120 => 1030.1120041120
1809 // 1.3.12-rc1 => 1030.119
1810 function phpwiki_version() {
1811     static $PHPWIKI_VERSION;
1812     if (!isset($PHPWIKI_VERSION)) {
1813         $arr = explode('.',preg_replace('/\D+$/','', PHPWIKI_VERSION)); // remove the pre
1814         $arr[2] = preg_replace('/\.+/','.',preg_replace('/\D/','.',$arr[2]));
1815         $PHPWIKI_VERSION = $arr[0]*1000 + $arr[1]*10 + 0.01*$arr[2];
1816         if (strstr(PHPWIKI_VERSION, 'pre') or strstr(PHPWIKI_VERSION, 'rc'))
1817             $PHPWIKI_VERSION -= 0.01;
1818     }
1819     return $PHPWIKI_VERSION;
1820 }
1821
1822 function phpwiki_gzhandler($ob) {
1823     if (function_exists('gzencode'))
1824         $ob = gzencode($ob);
1825         $GLOBALS['request']->_ob_get_length = strlen($ob);
1826     if (!headers_sent()) {
1827         header(sprintf("Content-Length: %d", $GLOBALS['request']->_ob_get_length));
1828     }
1829     return $ob;
1830 }
1831
1832 function isWikiWord($word) {
1833     global $WikiNameRegexp;
1834     //or preg_match('/\A' . $WikiNameRegexp . '\z/', $word) ??
1835     return preg_match("/^$WikiNameRegexp\$/",$word);
1836 }
1837
1838 // needed to store serialized objects-values only (perm, pref)
1839 function obj2hash ($obj, $exclude = false, $fields = false) {
1840     $a = array();
1841     if (! $fields ) $fields = get_object_vars($obj);
1842     foreach ($fields as $key => $val) {
1843         if (is_array($exclude)) {
1844             if (in_array($key, $exclude)) continue;
1845         }
1846         $a[$key] = $val;
1847     }
1848     return $a;
1849 }
1850
1851 /**
1852  * isUtf8String($string) - cheap utf-8 detection
1853  *
1854  * segfaults for strings longer than 10kb!
1855  * Use http://www.phpdiscuss.com/article.php?id=565&group=php.i18n or
1856  * checkTitleEncoding() at http://cvs.sourceforge.net/viewcvs.py/wikipedia/phase3/languages/Language.php
1857  */
1858 function isUtf8String( $s ) {
1859     $ptrASCII  = '[\x00-\x7F]';
1860     $ptr2Octet = '[\xC2-\xDF][\x80-\xBF]';
1861     $ptr3Octet = '[\xE0-\xEF][\x80-\xBF]{2}';
1862     $ptr4Octet = '[\xF0-\xF4][\x80-\xBF]{3}';
1863     $ptr5Octet = '[\xF8-\xFB][\x80-\xBF]{4}';
1864     $ptr6Octet = '[\xFC-\xFD][\x80-\xBF]{5}';
1865     return preg_match("/^($ptrASCII|$ptr2Octet|$ptr3Octet|$ptr4Octet|$ptr5Octet|$ptr6Octet)*$/s", $s);
1866 }
1867
1868 /** 
1869  * Check for UTF-8 URLs; Internet Explorer produces these if you
1870  * type non-ASCII chars in the URL bar or follow unescaped links.
1871  * Requires urldecoded pagename.
1872  * Fixes sf.net bug #953949
1873  *
1874  * src: languages/Language.php:checkTitleEncoding() from mediawiki
1875  */
1876 function fixTitleEncoding( $s ) {
1877     global $charset;
1878
1879     $s = trim($s);
1880     // print a warning?
1881     if (empty($s)) return $s;
1882
1883     $ishigh = preg_match( '/[\x80-\xff]/', $s);
1884     /*
1885     $isutf = ($ishigh ? preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
1886                                     '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s ) : true );
1887     */
1888     $isutf = ($ishigh ? isUtf8String($s) : true);
1889     $locharset = strtolower($charset);
1890
1891     if( $locharset != "utf-8" and $ishigh and $isutf )
1892         $s = charset_convert('UTF-8', $locharset, $s);
1893     if ($locharset == "utf-8" and $ishigh and !$isutf )
1894         return utf8_encode( $s );
1895
1896     // Other languages can safely leave this function, or replace
1897     // it with one to detect and convert another legacy encoding.
1898     return $s;
1899 }
1900
1901 /** 
1902  * MySQL fulltext index doesn't grok utf-8, so we
1903  * need to fold cases and convert to hex.
1904  * src: languages/Language.php:stripForSearch() from mediawiki
1905  */
1906 /*
1907 function stripForSearch( $string ) {
1908     global $wikiLowerChars; 
1909     // '/(?:[a-z]|\xc3[\x9f-\xbf]|\xc4[\x81\x83\x85\x87])/' => "a-z\xdf-\xf6\xf8-\xff"
1910     return preg_replace(
1911                         "/([\\xc0-\\xff][\\x80-\\xbf]*)/e",
1912                         "'U8' . bin2hex( strtr( \"\$1\", \$wikiLowerChars ) )",
1913                         $string );
1914 }
1915 */
1916
1917 /** 
1918  * Workaround for allow_url_fopen, to get the content of an external URI.
1919  * It returns the contents in one slurp. Parsers might want to check for allow_url_fopen
1920  * and use fopen, fread chunkwise. (see lib/XmlParser.php)
1921  */
1922 function url_get_contents( $uri ) {
1923     if (get_cfg_var('allow_url_fopen')) { // was ini_get('allow_url_fopen'))
1924         return @file_get_contents($uri);
1925     } else {
1926         require_once("lib/HttpClient.php");
1927         $bits = parse_url($uri);
1928         $host = $bits['host'];
1929         $port = isset($bits['port']) ? $bits['port'] : 80;
1930         $path = isset($bits['path']) ? $bits['path'] : '/';
1931         if (isset($bits['query'])) {
1932             $path .= '?'.$bits['query'];
1933         }
1934         $client = new HttpClient($host, $port);
1935         $client->use_gzip = false;
1936         if (!$client->get($path)) {
1937             return false;
1938         } else {
1939             return $client->getContent();
1940         }
1941     }
1942 }
1943
1944 /**
1945  * Generate consecutively named strings:
1946  *   Name, Name2, Name3, ...
1947  */
1948 function GenerateId($name) {
1949     static $ids = array();
1950     if (empty($ids[$name])) {
1951         $ids[$name] = 1;
1952         return $name;
1953     } else {
1954         $ids[$name]++;
1955         return $name . $ids[$name];
1956     }
1957 }
1958
1959 // from IncludePage. To be of general use.
1960 // content: string or array of strings
1961 function firstNWordsOfContent( $n, $content ) {
1962     if ($content and $n > 0) {
1963         if (is_array($content)) {
1964             // fixme: return a list of lines then?
1965             //$content = join("\n", $content);
1966             //$return_array = true;
1967             $wordcount = 0;
1968             foreach ($content as $line) {
1969                 $words = explode(' ', $line);
1970                 if ($wordcount + count($words) > $n) {
1971                     $new[] = implode(' ', array_slice($words, 0, $n - $wordcount))
1972                            . sprintf(_("... (first %s words)"), $n);
1973                     return $new;
1974                 } else {
1975                     $wordcount += count($words);
1976                     $new[] = $line;
1977                 }
1978             }
1979             return $new;
1980         } else {
1981             // fixme: use better whitespace/word seperators
1982             $words = explode(' ', $content);
1983             if (count($words) > $n) {
1984                 return join(' ', array_slice($words, 0, $n))
1985                        . sprintf(_("... (first %s words)"), $n);
1986             } else {
1987                 return $content;
1988             }
1989         }
1990     } else {
1991         return '';
1992     }
1993 }
1994
1995 // moved from lib/plugin/IncludePage.php
1996 function extractSection ($section, $content, $page, $quiet = false, $sectionhead = false) {
1997     $qsection = preg_replace('/\s+/', '\s+', preg_quote($section, '/'));
1998
1999     if (preg_match("/ ^(!{1,})\\s*$qsection" // section header
2000                    . "  \\s*$\\n?"           // possible blank lines
2001                    . "  ( (?: ^.*\\n? )*? )" // some lines
2002                    . "  (?= ^\\1 | \\Z)/xm", // sec header (same or higher level) (or EOF)
2003                    implode("\n", $content),
2004                    $match)) {
2005         // Strip trailing blanks lines and ---- <hr>s
2006         $text = preg_replace("/\\s*^-{4,}\\s*$/m", "", $match[2]);
2007         if ($sectionhead)
2008             $text = $match[1] . $section ."\n". $text;
2009         return explode("\n", $text);
2010     }
2011     if ($quiet)
2012         $mesg = $page ." ". $section;
2013     else
2014         $mesg = $section;
2015     return array(sprintf(_("<%s: no such section>"), $mesg));
2016 }
2017
2018 // use this faster version: only load ExternalReferrer if we came from an external referrer
2019 function isExternalReferrer(&$request) {
2020     if ($referrer = $request->get('HTTP_REFERER')) {
2021         $home = SERVER_URL; // SERVER_URL or SCRIPT_NAME, if we want to check sister wiki's also
2022         if (string_starts_with(strtolower($referrer), strtolower($home))) return false;
2023         require_once("lib/ExternalReferrer.php");
2024         $se = new SearchEngines();
2025         return $se->parseSearchQuery($referrer);
2026     }
2027     //if (DEBUG) return array('query' => 'wiki');
2028     return false;
2029 }
2030
2031 /**
2032  * Useful for PECL overrides: cvsclient, ldap, soap, xmlrpc, pdo, pdo_<driver>
2033  */
2034 function loadPhpExtension($extension) {
2035     if (!extension_loaded($extension)) {
2036         $isWindows = (substr(PHP_OS,0,3) == 'WIN');
2037         $soname = ($isWindows ? 'php_' : '') 
2038                 . $extension 
2039                 . ($isWindows ? '.dll' : '.so');
2040         if (!@dl($soname))
2041             return false;
2042     }
2043     return extension_loaded($extension);
2044 }
2045
2046 function charset_convert($from, $to, $data) {
2047     //global $CHARSET;
2048     //$wikicharset = strtolower($CHARSET);
2049     //$systemcharset = strtolower(get_cfg_var('iconv.internal_encoding')); // 'iso-8859-1';
2050     if (strtolower($from) == 'utf-8' and strtolower($to) == 'iso-8859-1')
2051         return utf8_decode($data);
2052     if (strtolower($to) == 'utf-8' and strtolower($from) == 'iso-8859-1')
2053         return utf8_encode($data);
2054
2055     if (loadPhpExtension("iconv")) {
2056         $tmpdata = iconv($from, $to, $data);
2057         if (!$tmpdata)
2058             trigger_error("charset conversion $from => $to failed. Wrong source charset?", E_USER_WARNING);
2059         else
2060             $data = $tmpdata;
2061     } else {
2062         trigger_error("The iconv extension cannot be loaded", E_USER_WARNING);
2063     }
2064     return $data;
2065 }
2066
2067 function string_starts_with($string, $prefix) {
2068     return (substr($string, 0, strlen($prefix)) == $prefix);
2069 }
2070 function string_ends_with($string, $suffix) {
2071     return (substr($string, -strlen($suffix)) == $suffix);
2072 }
2073 function array_remove($arr,$value) {
2074    return array_values(array_diff($arr,array($value)));
2075 }
2076
2077 /** 
2078  * Ensure that the script will have another $secs time left. 
2079  * Works only if safe_mode is off.
2080  * For example not to timeout on waiting socket connections.
2081  *   Use the socket timeout as arg.
2082  */
2083 function longer_timeout($secs = 30) {
2084     $timeout = @ini_get("max_execution_time") ? ini_get("max_execution_time") : 30;
2085     $timeleft = $timeout - $GLOBALS['RUNTIMER']->getTime();
2086     if ($timeleft < $secs)
2087         @set_time_limit(max($timeout,(integer)($secs + $timeleft)));
2088 }
2089
2090 function printSimpleTrace($bt) {
2091     //print_r($bt);
2092     echo "\nTraceback:\n";
2093     if (function_exists('debug_print_backtrace')) { // >= 5
2094         debug_print_backtrace();
2095     } else {
2096         foreach ($bt as $i => $elem) {
2097             if (!array_key_exists('file', $elem)) {
2098                 continue;
2099             }
2100             //echo join(" ",array_values($elem)),"\n";
2101             echo "  ",$elem['file'],':',$elem['line']," ",$elem['function'],"\n";
2102         }
2103     }
2104 }
2105
2106 /**
2107  * Return the used process memory, in bytes.
2108  * Enable the section which will work for you. They are very slow.
2109  * Special quirks for Windows: Requires cygwin.
2110  */
2111 function getMemoryUsage() {
2112     //if (!(DEBUG & _DEBUG_VERBOSE)) return;
2113     if (function_exists('memory_get_usage') and memory_get_usage()) {
2114         return memory_get_usage();
2115     } elseif (function_exists('getrusage') and ($u = @getrusage()) and !empty($u['ru_maxrss'])) {
2116         $mem = $u['ru_maxrss'];
2117     } elseif (substr(PHP_OS,0,3) == 'WIN') { // may require a newer cygwin
2118         // what we want is the process memory only: apache or php (if CGI)
2119         $pid = getmypid();
2120         $memstr = '';
2121         // win32_ps_stat_proc, win32_ps_stat_mem
2122         if (function_exists('win32_ps_list_procs')) {
2123             $info = win32_ps_stat_proc($pid);
2124             $memstr = $info['mem']['working_set_size'];
2125         } elseif(0) {
2126             // This works only if it's a cygwin process (apache or php).
2127             // Requires a newer cygwin
2128             $memstr = exec("cat /proc/$pid/statm |cut -f1");
2129
2130             // if it's native windows use something like this: 
2131             //   (requires pslist from sysinternals.com, grep, sed and perl)
2132             //$memstr = exec("pslist $pid|grep -A1 Mem|sed 1d|perl -ane\"print \$"."F[5]\"");
2133         }
2134         return (integer) trim($memstr);
2135     } elseif (1) {
2136         $pid = getmypid();
2137         //%MEM: Percentage of total memory in use by this process
2138         //VSZ: Total virtual memory size, in 1K blocks.
2139         //RSS: Real Set Size, the actual amount of physical memory allocated to this process.
2140         //CPU time used by process since it started.
2141         //echo "%",`ps -o%mem,vsz,rss,time -p $pid|sed 1d`,"\n";
2142         $memstr = exec("ps -orss -p $pid|sed 1d");
2143         return (integer) trim($memstr);
2144     }
2145 }
2146
2147 /**
2148  * @param var $needle
2149  * @param array $haystack one-dimensional numeric array only, no hash
2150  * @return integer
2151  * @desc Feed a sorted array to $haystack and a value to search for to $needle.
2152              It will return false if not found or the index where it was found.
2153   From dennis.decoene@moveit.be http://www.php.net/array_search
2154 */
2155 function binary_search($needle, $haystack) {
2156     $high = count($haystack);
2157     $low = 0;
2158    
2159     while (($high - $low) > 1) {
2160         $probe = floor(($high + $low) / 2);
2161         if ($haystack[$probe] < $needle) {
2162             $low = $probe;
2163         } elseif ($haystack[$probe] == $needle) {
2164             $high = $low = $probe;
2165         } else {
2166             $high = $probe;
2167         }
2168     }
2169
2170     if ($high == count($haystack) || $haystack[$high] != $needle) {
2171         return false;
2172     } else {
2173         return $high;
2174     }
2175 }
2176
2177 function is_localhost($url = false) {
2178     if (!$url) {
2179         global $HTTP_SERVER_VARS;
2180         return $HTTP_SERVER_VARS['SERVER_ADDR'] == '127.0.0.1';
2181     }
2182 }
2183
2184 /**
2185  * Take a string and quote it sufficiently to be passed as a Javascript
2186  * string between ''s
2187  */
2188 function javascript_quote_string($s) {
2189     return str_replace("'", "\'", $s);
2190 }
2191
2192
2193 // $Log: not supported by cvs2svn $
2194 // Revision 1.269  2008/01/24 19:17:03  rurban
2195 // add javascript_quote_string for Theme
2196 //
2197 // Revision 1.268  2007/09/15 12:28:46  rurban
2198 // Improve multi-page format handling: abstract _DumpHtmlToDir. get rid of non-external pdf, non-global VALID_LINKS
2199 //
2200 // Revision 1.267  2007/09/12 19:32:29  rurban
2201 // link only VALID_LINKS with pagelist HTML_DUMP
2202 //
2203 // Revision 1.266  2007/09/01 13:24:23  rurban
2204 // add INSECURE_ACTIONS_LOCALHOST_ONLY. advanced security settings
2205 //
2206 // Revision 1.265  2007/08/08 18:47:14  rurban
2207 // * Fix EmailNotify for Subpages: Unknown modifier ? at any page save.
2208 //   Quoting error on glob_match.
2209 // * Fix binary_search
2210 //
2211 // Revision 1.264  2007/07/15 17:39:42  rurban
2212 // add binary_search. enable memory ps calls
2213 //
2214 // Revision 1.263  2007/07/14 12:05:29  rurban
2215 // add url field to WikiPageName for interwiki expansion
2216 //
2217 // Revision 1.262  2007/06/07 17:02:01  rurban
2218 // fix display of pagenames containing ":" in certain lists
2219 //
2220 // Revision 1.261  2007/06/01 06:37:53  rurban
2221 // use native debug_print_backtrace
2222 //
2223 // Revision 1.260  2007/02/17 14:15:21  rurban
2224 // fix ImgLink params: $ori_url
2225 //
2226 // Revision 1.259  2007/01/20 11:41:38  rurban
2227 // WikiPagename::_check: add flatfile support
2228 //
2229 // Revision 1.258  2007/01/07 18:43:51  rurban
2230 // Remove FileFinder dependency for loadPhpExtension()
2231 //
2232 // Revision 1.257  2007/01/03 21:24:56  rurban
2233 // Disable noisy ps subprocess on DEBUG. Turn it on explicitly on memory debugging. Add convert_charset helper. Use convert_charset().
2234 //
2235 // Revision 1.256  2007/01/02 13:23:49  rurban
2236 // ftnt_${footnum}: do not confuse old php string definition parsers. Clarify API: sortby,limit and exclude are strings.
2237 //
2238 // Revision 1.255  2006/12/22 16:53:38  rurban
2239 // Try to dl() load the iconv extension, if not already loaded
2240 //
2241 // Revision 1.254  2006/12/02 19:53:05  rurban
2242 // Simplify DISABLE_MARKUP_WIKIWORD handling by adding the new function
2243 // stdlib: array_remove(). Hopefully PHP will not add this natively sooner
2244 // or later.
2245 //
2246 // Revision 1.253  2006/08/25 22:20:52  rurban
2247 // better split subpages at sep
2248 //
2249 // Revision 1.252  2006/06/18 11:03:36  rurban
2250 // support rc version
2251 //
2252 // Revision 1.251  2006/03/19 15:01:00  rurban
2253 // sf.net patch #1333957 by Matt Brown: Authentication cookie identical across all wikis on a host
2254 //
2255 // Revision 1.250  2006/03/07 20:45:44  rurban
2256 // wikihash for php-5.1
2257 //
2258 // Revision 1.249  2005/10/30 14:24:33  rurban
2259 // move rand_ascii_readable from Captcha to stdlib
2260 //
2261 // Revision 1.248  2005/10/29 14:18:30  uckelman
2262 // Added is_a() deprecation note.
2263 //
2264 // Revision 1.247  2005/10/10 20:31:21  rurban
2265 // fix win32ps call
2266 //
2267 // Revision 1.246  2005/10/10 19:38:48  rurban
2268 // add win32ps
2269 //
2270 // Revision 1.245  2005/09/18 16:01:09  rurban
2271 // trick to send the correct gzipped Content-Length
2272 //
2273 // Revision 1.244  2005/09/11 13:24:33  rurban
2274 // fix shortname, dont quote twice in ListRegexExpand
2275 //
2276 // Revision 1.243  2005/08/06 15:01:38  rurban
2277 // workaround php VBASIC alike limitation: allow integer pagenames
2278 //
2279 // Revision 1.242  2005/08/06 13:07:04  rurban
2280 // quote paths correctly (not the best method though)
2281 //
2282 // Revision 1.241  2005/05/06 16:54:19  rurban
2283 // support optional EXTERNAL_LINK_TARGET, default: _blank
2284 //
2285 // Revision 1.240  2005/04/23 11:15:49  rurban
2286 // handle allowed inlined objects within INLINE_IMAGES
2287 //
2288 // Revision 1.239  2005/04/01 16:11:42  rurban
2289 // just whitespace
2290 //
2291 // Revision 1.238  2005/03/04 16:29:14  rurban
2292 // Fixed bug #994994 (escape / in glob)
2293 // Optimized glob_to_pcre within fileSet() matching.
2294 //
2295 // Revision 1.237  2005/02/12 17:22:18  rurban
2296 // locale update: missing . : fixed. unified strings
2297 // proper linebreaks
2298 //
2299 // Revision 1.236  2005/02/08 13:41:32  rurban
2300 // add rand_ascii
2301 //
2302 // Revision 1.235  2005/02/04 11:54:48  rurban
2303 // fix Talk: names
2304 //
2305 // Revision 1.234  2005/02/03 05:09:25  rurban
2306 // Talk: + User: fix
2307 //
2308 // Revision 1.233  2005/02/02 20:40:12  rurban
2309 // fix Talk: and User: names and links
2310 //
2311 // Revision 1.232  2005/02/02 19:34:09  rurban
2312 // more maps: Talk, User
2313 //
2314 // Revision 1.231  2005/01/30 19:48:52  rurban
2315 // enable ps memory on unix
2316 //
2317 // Revision 1.230  2005/01/25 07:10:51  rurban
2318 // add getMemoryUsage to stdlib
2319 //
2320 // Revision 1.229  2005/01/21 11:51:22  rurban
2321 // changed (c)
2322 //
2323 // Revision 1.228  2005/01/17 20:28:30  rurban
2324 // Allow more pagename chars: Limit only on certain backends.
2325 // Re-Allow : and ; and control chars on non-file backends.
2326 //
2327 // Revision 1.227  2005/01/14 18:32:08  uckelman
2328 // ConvertOldMarkup did not properly handle links containing pairs of pairs
2329 // of underscores. (E.g., [http://example.com/foo__bar__.html] would be
2330 // munged by the regex for bold text.) Now '__' in links are hidden prior to
2331 // conversion of '__' into '<strong>', and then unhidden afterwards.
2332 //
2333 // Revision 1.226  2004/12/26 17:12:06  rurban
2334 // avoid stdargs in url, php5 fixes
2335 //
2336 // Revision 1.225  2004/12/22 19:02:29  rurban
2337 // fix glob for starting * or ?
2338 //
2339 // Revision 1.224  2004/12/20 12:11:50  rurban
2340 // fix "lib/stdlib.php:1348: Warning[2]: Compilation failed: unmatched parentheses at offset 2"
2341 //   not reproducable other than on sf.net, but this seems to fix it.
2342 //
2343 // Revision 1.223  2004/12/18 16:49:29  rurban
2344 // fix RPC for !USE_PATH_INFO, add debugging helper
2345 //
2346 // Revision 1.222  2004/12/17 16:40:45  rurban
2347 // add not yet used url helper
2348 //
2349 // Revision 1.221  2004/12/06 19:49:58  rurban
2350 // enable action=remove which is undoable and seeable in RecentChanges: ADODB ony for now.
2351 // renamed delete_page to purge_page.
2352 // enable action=edit&version=-1 to force creation of a new version.
2353 // added BABYCART_PATH config
2354 // fixed magiqc in adodb.inc.php
2355 // and some more docs
2356 //
2357 // Revision 1.220  2004/11/30 17:47:41  rurban
2358 // added mt_srand, check for native isa
2359 //
2360 // Revision 1.219  2004/11/26 18:39:02  rurban
2361 // new regex search parser and SQL backends (90% complete, glob and pcre backends missing)
2362 //
2363 // Revision 1.218  2004/11/25 08:28:48  rurban
2364 // support exclude
2365 //
2366 // Revision 1.217  2004/11/16 17:31:03  rurban
2367 // re-enable old block markup conversion
2368 //
2369 // Revision 1.216  2004/11/11 18:31:26  rurban
2370 // add simple backtrace on such general failures to get at least an idea where
2371 //
2372 // Revision 1.215  2004/11/11 14:34:12  rurban
2373 // minor clarifications
2374 //
2375 // Revision 1.214  2004/11/11 11:01:20  rurban
2376 // fix loadPhpExtension
2377 //
2378 // Revision 1.213  2004/11/01 10:43:57  rurban
2379 // seperate PassUser methods into seperate dir (memory usage)
2380 // fix WikiUser (old) overlarge data session
2381 // remove wikidb arg from various page class methods, use global ->_dbi instead
2382 // ...
2383 //
2384 // Revision 1.212  2004/10/22 09:15:39  rurban
2385 // Alert::show has no arg anymore
2386 //
2387 // Revision 1.211  2004/10/22 09:05:11  rurban
2388 // added longer_timeout (HttpClient)
2389 // fixed warning
2390 //
2391 // Revision 1.210  2004/10/14 21:06:02  rurban
2392 // fix dumphtml with USE_PATH_INFO (again). fix some PageList refs
2393 //
2394 // Revision 1.209  2004/10/14 19:19:34  rurban
2395 // loadsave: check if the dumped file will be accessible from outside.
2396 // and some other minor fixes. (cvsclient native not yet ready)
2397 //
2398 // Revision 1.208  2004/10/12 13:13:20  rurban
2399 // php5 compatibility (5.0.1 ok)
2400 //
2401 // Revision 1.207  2004/09/26 12:21:40  rurban
2402 // removed old log entries.
2403 // added persistent start_debug on internal links and DEBUG
2404 // added isExternalReferrer (not yet used)
2405 //
2406 // Revision 1.206  2004/09/25 16:28:36  rurban
2407 // added to TOC, firstNWordsOfContent is now plugin compatible, added extractSection
2408 //
2409 // Revision 1.205  2004/09/23 13:59:35  rurban
2410 // Before removing a page display a sample of 100 words.
2411 //
2412 // Revision 1.204  2004/09/17 13:19:15  rurban
2413 // fix LinkPhpwikiURL bug reported in http://phpwiki.sourceforge.net/phpwiki/KnownBugs
2414 // by SteveBennett.
2415 //
2416 // Revision 1.203  2004/09/16 08:00:52  rurban
2417 // just some comments
2418 //
2419 // Revision 1.202  2004/09/14 10:11:44  rurban
2420 // start 2nd Id with ...Plugin2
2421 //
2422 // Revision 1.201  2004/09/14 10:06:42  rurban
2423 // generate iterated plugin ids, set plugin span id also
2424 //
2425 // Revision 1.200  2004/08/05 17:34:26  rurban
2426 // move require to sortby branch
2427 //
2428 // Revision 1.199  2004/08/05 10:38:15  rurban
2429 // fix Bug #993692:  Making Snapshots or Backups doesn't work anymore
2430 // in CVS version.
2431 //
2432 // Revision 1.198  2004/07/02 10:30:36  rurban
2433 // always disable getimagesize for < php-4.3 with external png's
2434 //
2435 // Revision 1.197  2004/07/02 09:55:58  rurban
2436 // more stability fixes: new DISABLE_GETIMAGESIZE if your php crashes when loading LinkIcons: failing getimagesize in old phps; blockparser stabilized
2437 //
2438 // Revision 1.196  2004/07/01 08:51:22  rurban
2439 // dumphtml: added exclude, print pagename before processing
2440 //
2441 // Revision 1.195  2004/06/29 08:52:22  rurban
2442 // Use ...version() $need_content argument in WikiDB also:
2443 // To reduce the memory footprint for larger sets of pagelists,
2444 // we don't cache the content (only true or false) and
2445 // we purge the pagedata (_cached_html) also.
2446 // _cached_html is only cached for the current pagename.
2447 // => Vastly improved page existance check, ACL check, ...
2448 //
2449 // Now only PagedList info=content or size needs the whole content, esp. if sortable.
2450 //
2451 // Revision 1.194  2004/06/29 06:48:04  rurban
2452 // Improve LDAP auth and GROUP_LDAP membership:
2453 //   no error message on false password,
2454 //   added two new config vars: LDAP_OU_USERS and LDAP_OU_GROUP with GROUP_METHOD=LDAP
2455 //   fixed two group queries (this -> user)
2456 // stdlib: ConvertOldMarkup still flawed
2457 //
2458 // Revision 1.193  2004/06/28 13:27:03  rurban
2459 // CreateToc disabled for old markup and Apache2 only
2460 //
2461 // Revision 1.192  2004/06/28 12:47:43  rurban
2462 // skip if non-DEBUG and old markup with CreateToc
2463 //
2464 // Revision 1.191  2004/06/25 14:31:56  rurban
2465 // avoid debug_skip warning
2466 //
2467 // Revision 1.190  2004/06/25 14:29:20  rurban
2468 // WikiGroup refactoring:
2469 //   global group attached to user, code for not_current user.
2470 //   improved helpers for special groups (avoid double invocations)
2471 // new experimental config option ENABLE_XHTML_XML (fails with IE, and document.write())
2472 // fixed a XHTML validation error on userprefs.tmpl
2473 //
2474 // Revision 1.189  2004/06/20 09:45:35  rurban
2475 // php5 isa fix (wrong strtolower)
2476 //
2477 // Revision 1.188  2004/06/16 10:38:58  rurban
2478 // Disallow refernces in calls if the declaration is a reference
2479 // ("allow_call_time_pass_reference clean").
2480 //   PhpWiki is now allow_call_time_pass_reference = Off clean,
2481 //   but several external libraries may not.
2482 //   In detail these libs look to be affected (not tested):
2483 //   * Pear_DB odbc
2484 //   * adodb oracle
2485 //
2486 // Revision 1.187  2004/06/14 11:31:37  rurban
2487 // renamed global $Theme to $WikiTheme (gforge nameclash)
2488 // inherit PageList default options from PageList
2489 //   default sortby=pagename
2490 // use options in PageList_Selectable (limit, sortby, ...)
2491 // added action revert, with button at action=diff
2492 // added option regex to WikiAdminSearchReplace
2493 //
2494 // Revision 1.186  2004/06/13 13:54:25  rurban
2495 // Catch fatals on the four dump calls (as file and zip, as html and mimified)
2496 // FoafViewer: Check against external requirements, instead of fatal.
2497 // Change output for xhtmldumps: using file:// urls to the local fs.
2498 // Catch SOAP fatal by checking for GOOGLE_LICENSE_KEY
2499 // Import GOOGLE_LICENSE_KEY and FORTUNE_DIR from config.ini.
2500 //
2501 // Revision 1.185  2004/06/11 09:07:30  rurban
2502 // support theme-specific LinkIconAttr: front or after or none
2503 //
2504 // Revision 1.184  2004/06/04 20:32:53  rurban
2505 // Several locale related improvements suggested by Pierrick Meignen
2506 // LDAP fix by John Cole
2507 // reanable admin check without ENABLE_PAGEPERM in the admin plugins
2508 //
2509 // Revision 1.183  2004/06/01 10:22:56  rurban
2510 // added url_get_contents() used in XmlParser and elsewhere
2511 //
2512 // Revision 1.182  2004/05/25 12:40:48  rurban
2513 // trim the pagename
2514 //
2515 // Revision 1.181  2004/05/25 10:18:44  rurban
2516 // Check for UTF-8 URLs; Internet Explorer produces these if you
2517 // type non-ASCII chars in the URL bar or follow unescaped links.
2518 // Fixes sf.net bug #953949
2519 // src: languages/Language.php:checkTitleEncoding() from mediawiki
2520 //
2521 // Revision 1.180  2004/05/18 16:23:39  rurban
2522 // rename split_pagename to SplitPagename
2523 //
2524 // Revision 1.179  2004/05/18 16:18:37  rurban
2525 // AutoSplit at subpage seperators
2526 // RssFeed stability fix for empty feeds or broken connections
2527 //
2528 // Revision 1.178  2004/05/12 10:49:55  rurban
2529 // require_once fix for those libs which are loaded before FileFinder and
2530 //   its automatic include_path fix, and where require_once doesn't grok
2531 //   dirname(__FILE__) != './lib'
2532 // upgrade fix with PearDB
2533 // navbar.tmpl: remove spaces for IE &nbsp; button alignment
2534 //
2535 // Revision 1.177  2004/05/08 14:06:12  rurban
2536 // new support for inlined image attributes: [image.jpg size=50x30 align=right]
2537 // minor stability and portability fixes
2538 //
2539 // Revision 1.176  2004/05/08 11:25:15  rurban
2540 // php-4.0.4 fixes
2541 //
2542 // Revision 1.175  2004/05/06 17:30:38  rurban
2543 // CategoryGroup: oops, dos2unix eol
2544 // improved phpwiki_version:
2545 //   pre -= .0001 (1.3.10pre: 1030.099)
2546 //   -p1 += .001 (1.3.9-p1: 1030.091)
2547 // improved InstallTable for mysql and generic SQL versions and all newer tables so far.
2548 // abstracted more ADODB/PearDB methods for action=upgrade stuff:
2549 //   backend->backendType(), backend->database(),
2550 //   backend->listOfFields(),
2551 //   backend->listOfTables(),
2552 //
2553 // Revision 1.174  2004/05/06 12:02:05  rurban
2554 // fix sf.net bug#949002: [ Link | ] assertion
2555 //
2556 // Revision 1.173  2004/05/03 15:00:31  rurban
2557 // added more database upgrading: session.sess_ip, page.id autp_increment
2558 //
2559 // Revision 1.172  2004/04/26 20:44:34  rurban
2560 // locking table specific for better databases
2561 //
2562 // Revision 1.171  2004/04/19 23:13:03  zorloc
2563 // Connect the rest of PhpWiki to the IniConfig system.  Also the keyword regular expression is not a config setting
2564 //
2565 // Revision 1.170  2004/04/19 18:27:45  rurban
2566 // Prevent from some PHP5 warnings (ref args, no :: object init)
2567 //   php5 runs now through, just one wrong XmlElement object init missing
2568 // Removed unneccesary UpgradeUser lines
2569 // Changed WikiLink to omit version if current (RecentChanges)
2570 //
2571 // Revision 1.169  2004/04/15 21:29:48  rurban
2572 // allow [0] with new markup: link to page "0"
2573 //
2574 // Revision 1.168  2004/04/10 02:30:49  rurban
2575 // Fixed gettext problem with VIRTUAL_PATH scripts (Windows only probably)
2576 // Fixed "cannot setlocale..." (sf.net problem)
2577 //
2578 // Revision 1.167  2004/04/02 15:06:55  rurban
2579 // fixed a nasty ADODB_mysql session update bug
2580 // improved UserPreferences layout (tabled hints)
2581 // fixed UserPreferences auth handling
2582 // improved auth stability
2583 // improved old cookie handling: fixed deletion of old cookies with paths
2584 //
2585 // Revision 1.166  2004/04/01 15:57:10  rurban
2586 // simplified Sidebar theme: table, not absolute css positioning
2587 // added the new box methods.
2588 // remaining problems: large left margin, how to override _autosplitWikiWords in Template only
2589 //
2590 // Revision 1.165  2004/03/24 19:39:03  rurban
2591 // php5 workaround code (plus some interim debugging code in XmlElement)
2592 //   php5 doesn't work yet with the current XmlElement class constructors,
2593 //   WikiUserNew does work better than php4.
2594 // rewrote WikiUserNew user upgrading to ease php5 update
2595 // fixed pref handling in WikiUserNew
2596 // added Email Notification
2597 // added simple Email verification
2598 // removed emailVerify userpref subclass: just a email property
2599 // changed pref binary storage layout: numarray => hash of non default values
2600 // print optimize message only if really done.
2601 // forced new cookie policy: delete pref cookies, use only WIKI_ID as plain string.
2602 //   prefs should be stored in db or homepage, besides the current session.
2603 //
2604 // Revision 1.164  2004/03/18 21:41:09  rurban
2605 // fixed sqlite support
2606 // WikiUserNew: PHP5 fixes: don't assign $this (untested)
2607 //
2608 // Revision 1.163  2004/03/17 18:41:49  rurban
2609 // just reformatting
2610 //
2611 // Revision 1.162  2004/03/16 15:43:08  rurban
2612 // make fileSet sortable to please PageList
2613 //
2614 // Revision 1.161  2004/03/12 15:48:07  rurban
2615 // fixed explodePageList: wrong sortby argument order in UnfoldSubpages
2616 // simplified lib/stdlib.php:explodePageList
2617 //
2618 // Revision 1.160  2004/02/28 21:14:08  rurban
2619 // generally more PHPDOC docs
2620 //   see http://xarch.tu-graz.ac.at/home/rurban/phpwiki/xref/
2621 // fxied WikiUserNew pref handling: empty theme not stored, save only
2622 //   changed prefs, sql prefs improved, fixed password update,
2623 //   removed REPLACE sql (dangerous)
2624 // moved gettext init after the locale was guessed
2625 // + some minor changes
2626 //
2627
2628 // (c-file-style: "gnu")
2629 // Local Variables:
2630 // mode: php
2631 // tab-width: 8
2632 // c-basic-offset: 4
2633 // c-hanging-comment-ender-p: nil
2634 // indent-tabs-mode: nil
2635 // End:   
2636 ?>