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