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