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