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