]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/stdlib.php
Another refactor of the OOP HTML/XML generation code. (Sorry.)
[SourceForge/phpwiki.git] / lib / stdlib.php
1 <?php rcs_id('$Id: stdlib.php,v 1.94 2002-01-28 18:49:08 dairiki 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     LinkWikiWord($wikiword, $linktext)
9     LinkImage($url, $alt)
10
11     MakeWikiForm ($pagename, $args, $class, $button_text)
12     SplitQueryArgs ($query_args)
13     LinkPhpwikiURL($url, $text)
14     LinkBracketLink($bracketlink)
15     ExtractWikiPageLinks($content)
16
17     class Stack { push($item), pop(), cnt(), top() }
18
19     split_pagename ($page)
20     NoSuchRevision ($request, $page, $version)
21     TimezoneOffset ($time, $no_colon)
22     Iso8601DateTime ($time)
23     Rfc2822DateTime ($time)
24     CTime ($time)
25     __printf ($fmt)
26     __sprintf ($fmt)
27     __vsprintf ($fmt, $args)
28     better_srand($seed = '')
29
30   function: LinkInterWikiLink($link, $linktext)
31   moved to: lib/interwiki.php
32   function: linkExistingWikiWord($wikiword, $linktext, $version)
33   moved to: lib/Theme.php
34   function: LinkUnknownWikiWord($wikiword, $linktext)
35   moved to: lib/Theme.php
36   function: UpdateRecentChanges($dbi, $pagename, $isnewpage) 
37   gone see: lib/plugin/RecentChanges.php
38 */
39
40
41 function WikiURL($pagename, $args = '', $get_abs_url = false) {
42     if (is_object($pagename)) {
43         if (isa($pagename, 'WikiDB_Page')) {
44             $pagename = $pagename->getName();
45         }
46         elseif (isa($pagename, 'WikiDB_PageRevision')) {
47             $page = $pagename->getPage();
48             $args['version'] = $pagename->getVersion();
49             $pagename = $page->getName();
50         }
51     }
52     
53     if (is_array($args)) {
54         $enc_args = array();
55         foreach  ($args as $key => $val) {
56             $enc_args[] = urlencode($key) . '=' . urlencode($val);
57         }
58         $args = join('&', $enc_args);
59     }
60
61     if (USE_PATH_INFO) {
62         $url = $get_abs_url ? SERVER_URL . VIRTUAL_PATH . "/" : "";
63         $url .= preg_replace('/%2f/i', '/', rawurlencode($pagename));
64         if ($args)
65             $url .= "?$args";
66     }
67     else {
68         $url = $get_abs_url ? SERVER_URL . SCRIPT_NAME : basename(SCRIPT_NAME);
69         $url .= "?pagename=" . rawurlencode($pagename);
70         if ($args)
71             $url .= "&$args";
72     }
73     return $url;
74 }
75
76 function IconForLink($protocol_or_url) {
77     global $Theme;
78
79     list ($proto) = explode(':', $protocol_or_url, 2);
80     $src = $Theme->getLinkIconURL($proto);
81     if ($src)
82         return HTML::img(array('src' => $src, 'alt' => $proto, 'class' => 'linkicon'));
83     else
84         return false;
85 }
86
87 function LinkURL($url, $linktext = '') {
88     // FIXME: Is this needed (or sufficient?)
89     if(ereg("[<>\"]", $url)) {
90         $link = HTML::strong(HTML::u(array('class' => 'baduri'),
91                                      _("BAD URL -- remove all of <, >, \"")));
92     }
93     else {
94         $link = HTML::a(array('href' => $url),
95                         IconForLink($url),
96                         $linktext ? $linktext : $url);
97     }
98     $link->setAttr('class', $linktext ? 'namedurl' : 'rawurl');
99     return $link;
100 }
101
102 function LinkWikiWord($wikiword, $linktext = '', $version = false) {
103     global $request, $Theme;
104     $dbi = $request->getDbh();
105     if ($dbi->isWikiPage($wikiword))
106         $link = $Theme->linkExistingWikiWord($wikiword, $linktext, $version);
107     else
108         $link = $Theme->linkUnknownWikiWord($wikiword, $linktext);
109     return $link;
110 }
111
112 function LinkImage($url, $alt = '[External Image]') {
113     // FIXME: Is this needed (or sufficient?)
114     if(ereg("[<>\"]", $url)) {
115         $link = HTML::strong(HTML::u(array('class' => 'baduri'),
116                                      _("BAD URL -- remove all of <, >, \"")));
117     }
118     else {
119         $link = HTML::img(array('src' => $url, 'alt' => $alt));
120     }
121     $link->setAttr('class', 'inlineimage');
122     return $link;
123 }
124
125
126
127 class Stack {
128     var $items = array();
129     var $size = 0;
130     
131     function push($item) {
132         $this->items[$this->size] = $item;
133         $this->size++;
134         return true;
135     }  
136     
137     function pop() {
138         if ($this->size == 0) {
139             return false; // stack is empty
140         }  
141         $this->size--;
142         return $this->items[$this->size];
143     }  
144     
145     function cnt() {
146         return $this->size;
147     }  
148     
149     function top() {
150         if($this->size)
151             return $this->items[$this->size - 1];
152         else
153             return '';
154     }
155     
156 }  
157 // end class definition
158
159
160 function MakeWikiForm ($pagename, $args, $class, $button_text = '') {
161     $form = HTML::form(array('action' => USE_PATH_INFO ? WikiURL($pagename) : SCRIPT_NAME,
162                              'method' => 'get',
163                              'class'  => $class,
164                              'accept-charset' => CHARSET));
165     $td = HTML::td();
166     
167     while (list($key, $val) = each($args)) {
168         $i = HTML::input(array('name' => $key, 'value' => $val, 'type' => 'hidden'));
169         
170         if (preg_match('/^ (\d*) \( (.*) \) ((upload)?) $/xi', $val, $m)) {
171             $i->setAttr('size', $m[1] ? $m[1] : 30);
172             $i->setAttr('value', $m[2]);
173             if (!$m[3]) {
174                 $i->setAttr('type', 'text');
175             }
176             else {
177                 $i->setAttr('type', 'file');
178                 $form->setAttr('enctype', 'multipart/form-data');
179                 $form->pushContent(HTML::input(array('name'  => 'MAX_FILE_SIZE',
180                                                      'value' =>  MAX_UPLOAD_SIZE,
181                                                      'type'  => 'hidden')));
182                 $form->setAttr('method', 'post');
183             }
184             $td->pushContent($i);
185         }
186         else
187             $form->pushContent($i);
188     }
189     
190     $tr = HTML::tr($td);
191     
192     if (!empty($button_text))
193         $tr->pushContent(HTML::td(HTML::input(array('type'   => 'submit',
194                                                      'class' => 'button',
195                                                      'value' => $button_text))));
196     $form->pushContent(HTML::table(array('cellspacing' => 0,
197                                          'cellpadding' => 2,
198                                          'border'      => 0),
199                                    $tr));
200     return $form;
201 }
202
203 function SplitQueryArgs ($query_args = '') 
204 {
205     $split_args = split('&', $query_args);
206     $args = array();
207     while (list($key, $val) = each($split_args))
208         if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
209             $args[$m[1]] = $m[2];
210     return $args;
211 }
212
213 function LinkPhpwikiURL($url, $text = '') {
214     $args = array();
215     
216     if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m)) {
217         return HTML::strong(array('class' => 'rawurl'),
218                             HTML::u(array('class' => 'baduri'),
219                                     _("BAD phpwiki: URL")));
220     }
221
222     if ($m[1])
223         $pagename = urldecode($m[1]);
224     $qargs = $m[2];
225     
226     if (empty($pagename) &&
227         preg_match('/^(diff|edit|links|info)=([^&]+)$/', $qargs, $m)) {
228         // Convert old style links (to not break diff links in
229         // RecentChanges).
230         $pagename = urldecode($m[2]);
231         $args = array("action" => $m[1]);
232     }
233     else {
234         $args = SplitQueryArgs($qargs);
235     }
236
237     if (empty($pagename))
238         $pagename = $GLOBALS['request']->getArg('pagename');
239
240     if (isset($args['action']) && $args['action'] == 'browse')
241         unset($args['action']);
242     
243     /*FIXME:
244       if (empty($args['action']))
245       $class = 'wikilink';
246       else if (is_safe_action($args['action']))
247       $class = 'wikiaction';
248     */
249     if (empty($args['action']) || is_safe_action($args['action']))
250         $class = 'wikiaction';
251     else {
252         // Don't allow administrative links on unlocked pages.
253         $page = $GLOBALS['request']->getPage();
254         if (!$page->get('locked'))
255             return HTML::span(array('class' => 'wikiunsafe'),
256                               HTML::u(_("Lock page to enable link")));
257         $class = 'wikiadmin';
258     }
259     
260     // FIXME: ug, don't like this
261     if (preg_match('/=\d*\(/', $qargs))
262         return MakeWikiForm($pagename, $args, $class, $text);
263     if (!$text)
264         $text = HTML::span(array('class' => 'rawurl'), $url);
265
266     return HTML::a(array('href'  => WikiURL($pagename, $args),
267                          'class' => $class),
268                    $text);
269 }
270
271 function LinkBracketLink($bracketlink) {
272     global $request, $AllowedProtocols, $InlineImages;
273     global $InterWikiLinkRegexp, $Theme;
274
275     
276     // $bracketlink will start and end with brackets; in between will
277     // be either a page name, a URL or both separated by a pipe.
278     
279     // strip brackets and leading space
280     preg_match("/(\[\s*)(.+?)(\s*\])/", $bracketlink, $match);
281     // match the contents 
282     preg_match("/([^|]+)(\|)?([^|]+)?/", $match[2], $matches);
283     
284     if (isset($matches[3])) {
285         // named link of the form  "[some link name | http://blippy.com/]"
286         $URL = trim($matches[3]);
287         $linkname = trim($matches[1]);
288     } else {
289         // unnamed link of the form "[http://blippy.com/] or [wiki page]"
290         $URL = trim($matches[1]);
291         $linkname = false;
292     }
293
294     $dbi = $request->getDbh();
295     if ($dbi->isWikiPage($URL))
296         return $Theme->linkExistingWikiWord($URL, $linkname);
297     elseif (preg_match("#^($AllowedProtocols):#", $URL)) {
298         // if it's an image, embed it; otherwise, it's a regular link
299         if (preg_match("/($InlineImages)$/i", $URL))
300             return LinkImage($URL, $linkname);
301         else
302             return LinkURL($URL, $linkname);
303     }
304     elseif (preg_match("/^phpwiki:/", $URL))
305         return LinkPhpwikiURL($URL, $linkname);
306     elseif (function_exists('LinkInterWikiLink')
307             && preg_match("/^$InterWikiLinkRegexp:/", $URL))
308         return LinkInterWikiLink($URL, $linkname);
309     else {
310         return $Theme->linkUnknownWikiWord($URL, $linkname);
311     }
312     
313 }
314
315 /* FIXME: this should be done by the transform code */
316 function ExtractWikiPageLinks($content) {
317     global $WikiNameRegexp;
318     
319     if (is_string($content))
320         $content = explode("\n", $content);
321     
322     $wikilinks = array();
323     foreach ($content as $line) {
324         // remove plugin code
325         $line = preg_replace('/<\?plugin\s+\w.*?\?>/', '', $line);
326         // remove escaped '['
327         $line = str_replace('[[', ' ', $line);
328         // remove footnotes
329         $line = preg_replace('/[\d+]/', ' ', $line);
330         
331         // bracket links (only type wiki-* is of interest)
332         $numBracketLinks = preg_match_all("/\[\s*([^\]|]+\|)?\s*(\S.*?)\s*\]/",
333                                           $line, $brktlinks);
334         for ($i = 0; $i < $numBracketLinks; $i++) {
335             $link = LinkBracketLink($brktlinks[0][$i]);
336             if (preg_match('/^(named-)?wiki(unknown)?$/', $link->getAttr('class')))
337                 $wikilinks[$brktlinks[2][$i]] = 1;
338             
339             $brktlink = preg_quote($brktlinks[0][$i]);
340             $line = preg_replace("|$brktlink|", '', $line);
341         }
342         
343         // BumpyText old-style wiki links
344         if (preg_match_all("/!?$WikiNameRegexp/", $line, $link)) {
345             for ($i = 0; isset($link[0][$i]); $i++) {
346                 if($link[0][$i][0] <> '!')
347                     $wikilinks[$link[0][$i]] = 1;
348             }
349         }
350     }
351     return array_keys($wikilinks);
352 }      
353
354 /**
355  * Split WikiWords in page names.
356  *
357  * It has been deemed useful to split WikiWords (into "Wiki Words") in
358  * places like page titles. This is rumored to help search engines
359  * quite a bit.
360  *
361  * @param $page string The page name.
362  *
363  * @return string The split name.
364  */
365 function split_pagename ($page) {
366     
367     if (preg_match("/\s/", $page))
368         return $page;           // Already split --- don't split any more.
369     
370     // FIXME: this algorithm is Anglo-centric.
371     static $RE;
372     if (!isset($RE)) {
373         // This mess splits between a lower-case letter followed by
374         // either an upper-case or a numeral; except that it wont
375         // split the prefixes 'Mc', 'De', or 'Di' off of their tails.
376         $RE[] = '/([[:lower:]])((?<!Mc|De|Di)[[:upper:]]|\d)/';
377         // This the single-letter words 'I' and 'A' from any following
378         // capitalized words.
379         $RE[] = '/(?: |^)([AI])([[:upper:]][[:lower:]])/';
380         // Split numerals from following letters.
381         $RE[] = '/(\d)([[:alpha:]])/';
382         
383         foreach ($RE as $key => $val)
384             $RE[$key] = pcre_fix_posix_classes($val);
385     }
386     
387     foreach ($RE as $regexp)
388         $page = preg_replace($regexp, '\\1 \\2', $page);
389     return $page;
390 }
391
392 function NoSuchRevision (&$request, $page, $version) {
393     $html = HTML(HTML::h2(_("Revision Not Found")),
394                  HTML::p(fmt("I'm sorry.  Version %d of %s is not in my database.",
395                              $version, LinkWikiWord($page->getName()))));
396     include_once('lib/Template.php');
397     GeneratePage($html, _("Bad Version"), $page->getCurrentRevision());
398     $request->finish();
399 }
400
401
402 /**
403  * Get time offset for local time zone.
404  *
405  * @param $time time_t Get offset for this time. Default: now.
406  * @param $no_colon boolean Don't put colon between hours and minutes.
407  * @return string Offset as a string in the format +HH:MM.
408  */
409 function TimezoneOffset ($time = false, $no_colon = false) {
410     if ($time === false)
411         $time = time();
412     $secs = date('Z', $time);
413     if ($secs < 0) {
414         $sign = '-';
415         $secs = -$secs;
416     }
417     else {
418         $sign = '+';
419     }
420     $colon = $no_colon ? '' : ':';
421     $mins = intval(($secs + 30) / 60);
422     return sprintf("%s%02d%s%02d",
423                    $sign, $mins / 60, $colon, $mins % 60);
424 }
425
426 /**
427  * Format time in ISO-8601 format.
428  *
429  * @param $time time_t Time.  Default: now.
430  * @return string Date and time in ISO-8601 format.
431  */
432 function Iso8601DateTime ($time = false) {
433     if ($time === false)
434         $time = time();
435     $tzoff = TimezoneOffset($time);
436     $date  = date('Y-m-d', $time);
437     $time  = date('H:i:s', $time);
438     return $date . 'T' . $time . $tzoff;
439 }
440
441 /**
442  * Format time in RFC-2822 format.
443  *
444  * @param $time time_t Time.  Default: now.
445  * @return string Date and time in RFC-2822 format.
446  */
447 function Rfc2822DateTime ($time = false) {
448     if ($time === false)
449         $time = time();
450     return date('D, j M Y H:i:s ', $time) . TimezoneOffset($time, 'no colon');
451 }
452
453 /**
454  * Format time to standard 'ctime' format.
455  *
456  * @param $time time_t Time.  Default: now.
457  * @return string Date and time in RFC-2822 format.
458  */
459 function CTime ($time = false)
460 {
461     if ($time === false)
462         $time = time();
463     return date("D M j H:i:s Y", $time);
464 }
465
466
467
468 /**
469  * Internationalized printf.
470  *
471  * This is essentially the same as PHP's built-in printf
472  * with the following exceptions:
473  * <ol>
474  * <li> It passes the format string through gettext().
475  * <li> It supports the argument reordering extensions.
476  * </ol>
477  *
478  * Example:
479  *
480  * In php code, use:
481  * <pre>
482  *    __printf("Differences between versions %s and %s of %s",
483  *             $new_link, $old_link, $page_link);
484  * </pre>
485  *
486  * Then in locale/po/de.po, one can reorder the printf arguments:
487  *
488  * <pre>
489  *    msgid "Differences between %s and %s of %s."
490  *    msgstr "Der Unterschiedsergebnis von %3$s, zwischen %1$s und %2$s."
491  * </pre>
492  *
493  * (Note that while PHP tries to expand $vars within double-quotes,
494  * the values in msgstr undergo no such expansion, so the '$'s
495  * okay...)
496  *
497  * One shouldn't use reordered arguments in the default format string.
498  * Backslashes in the default string would be necessary to escape the
499  * '$'s, and they'll cause all kinds of trouble....
500  */ 
501 function __printf ($fmt) {
502     $args = func_get_args();
503     array_shift($args);
504     echo __vsprintf($fmt, $args);
505 }
506
507 /**
508  * Internationalized sprintf.
509  *
510  * This is essentially the same as PHP's built-in printf with the
511  * following exceptions:
512  *
513  * <ol>
514  * <li> It passes the format string through gettext().
515  * <li> It supports the argument reordering extensions.
516  * </ol>
517  *
518  * @see __printf
519  */ 
520 function __sprintf ($fmt) {
521     $args = func_get_args();
522     array_shift($args);
523     return __vsprintf($fmt, $args);
524 }
525
526 /**
527  * Internationalized vsprintf.
528  *
529  * This is essentially the same as PHP's built-in printf with the
530  * following exceptions:
531  *
532  * <ol>
533  * <li> It passes the format string through gettext().
534  * <li> It supports the argument reordering extensions.
535  * </ol>
536  *
537  * @see __printf
538  */ 
539 function __vsprintf ($fmt, $args) {
540     $fmt = gettext($fmt);
541     // PHP's sprintf doesn't support variable with specifiers,
542     // like sprintf("%*s", 10, "x"); --- so we won't either.
543     
544     if (preg_match_all('/(?<!%)%(\d+)\$/x', $fmt, $m)) {
545         // Format string has '%2$s' style argument reordering.
546         // PHP doesn't support this.
547         if (preg_match('/(?<!%)%[- ]?\d*[^- \d$]/x', $fmt))
548             // literal variable name substitution only to keep locale
549             // strings uncluttered
550             trigger_error(sprintf(_("Can't mix '%s' with '%s' type format strings"),
551                                   '%1\$s','%s'), E_USER_WARNING); //php+locale error
552         
553         $fmt = preg_replace('/(?<!%)%\d+\$/x', '%', $fmt);
554         $newargs = array();
555         
556         // Reorder arguments appropriately.
557         foreach($m[1] as $argnum) {
558             if ($argnum < 1 || $argnum > count($args))
559                 trigger_error(sprintf(_("%s: argument index out of range"), 
560                                       $argnum), E_USER_WARNING);
561             $newargs[] = $args[$argnum - 1];
562         }
563         $args = $newargs;
564     }
565     
566     // Not all PHP's have vsprintf, so...
567     array_unshift($args, $fmt);
568     return call_user_func_array('sprintf', $args);
569 }
570
571
572 class fileSet {
573     /**
574      * Build an array in $this->_fileList of files from $dirname.
575      * Subdirectories are not traversed.
576      *
577      * (This was a function LoadDir in lib/loadsave.php)
578      * See also http://www.php.net/manual/en/function.readdir.php
579      */
580     function getFiles() {
581         return $this->_fileList;
582     }
583
584     function _filenameSelector($filename) {
585         // Default selects all filenames, override as needed.
586         return true;
587     }
588
589     function fileSet($directory) {
590         $this->_fileList = array();
591
592         if (empty($directory)) {
593             trigger_error(sprintf(_("%s is empty."), 'directoryname'),
594                           E_USER_NOTICE);
595             return; // early return
596         }
597
598         @ $dir_handle = opendir($dir=$directory);
599         if (empty($dir_handle)) {
600             trigger_error(sprintf(_("Unable to open directory '%s' for reading"),
601                                   $dir), E_USER_NOTICE);
602             return; // early return
603         }
604
605         while ($filename = readdir($dir_handle)) {
606             if ($filename[0] == '.' || filetype("$dir/$filename") != 'file')
607                 continue;
608             if ($this->_filenameSelector($filename)) {
609                 array_push($this->_fileList, "$filename");
610                 //trigger_error(sprintf(_("found file %s"), $filename),
611                 //                      E_USER_NOTICE); //debugging
612             }
613         }
614         closedir($dir_handle);
615     }
616 };
617
618
619 // Class introspections
620
621 /** Determine whether object is of a specified type.
622  *
623  * @param $object object An object.
624  * @param $class string Class name.
625  * @return bool True iff $object is a $class
626  * or a sub-type of $class. 
627  */
628 function isa ($object, $class) 
629 {
630     $lclass = strtolower($class);
631
632     return is_object($object)
633         && ( get_class($object) == strtolower($lclass)
634              || is_subclass_of($object, $lclass) );
635 }
636
637 /** Determine whether (possible) object has method.
638  *
639  * @param $object mixed Object
640  * @param $method string Method name
641  * @return bool True iff $object is an object with has method $method.
642  */
643 function can ($object, $method) 
644 {
645     return is_object($object) && method_exists($object, strtolower($method));
646 }
647
648 /**
649  * Seed the random number generator.
650  *
651  * better_srand() ensures the randomizer is seeded only once.
652  * 
653  * How random do you want it? See:
654  * http://www.php.net/manual/en/function.srand.php
655  * http://www.php.net/manual/en/function.mt-srand.php
656  */
657 function better_srand($seed = '') {
658     static $wascalled = FALSE;
659     if (!$wascalled) {
660         $seed = $seed === '' ? (double) microtime() * 1000000 : $seed;
661         srand($seed);
662         $wascalled = TRUE;
663         //trigger_error("new random seed", E_USER_NOTICE); //debugging
664     }
665 }
666
667 // (c-file-style: "gnu")
668 // Local Variables:
669 // mode: php
670 // tab-width: 8
671 // c-basic-offset: 4
672 // c-hanging-comment-ender-p: nil
673 // indent-tabs-mode: nil
674 // End:   
675 ?>