]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/stdlib.php
function better_srand() moved from themes/Hawaiian/lib/random.php to stdlib.php
[SourceForge/phpwiki.git] / lib / stdlib.php
1 <?php rcs_id('$Id: stdlib.php,v 1.93 2002-01-28 15:52:40 carstenklapp 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::p(fmt("I'm sorry.  Version %d of %s is not in my database.",
394                           $version, LinkWikiWord($page->getName())));
395     include_once('lib/Template.php');
396     GeneratePage($html, _("Bad Version"), $page->getCurrentRevision());
397     $request->finish();
398 }
399
400
401 /**
402  * Get time offset for local time zone.
403  *
404  * @param $time time_t Get offset for this time. Default: now.
405  * @param $no_colon boolean Don't put colon between hours and minutes.
406  * @return string Offset as a string in the format +HH:MM.
407  */
408 function TimezoneOffset ($time = false, $no_colon = false) {
409     if ($time === false)
410         $time = time();
411     $secs = date('Z', $time);
412     if ($secs < 0) {
413         $sign = '-';
414         $secs = -$secs;
415     }
416     else {
417         $sign = '+';
418     }
419     $colon = $no_colon ? '' : ':';
420     $mins = intval(($secs + 30) / 60);
421     return sprintf("%s%02d%s%02d",
422                    $sign, $mins / 60, $colon, $mins % 60);
423 }
424
425 /**
426  * Format time in ISO-8601 format.
427  *
428  * @param $time time_t Time.  Default: now.
429  * @return string Date and time in ISO-8601 format.
430  */
431 function Iso8601DateTime ($time = false) {
432     if ($time === false)
433         $time = time();
434     $tzoff = TimezoneOffset($time);
435     $date  = date('Y-m-d', $time);
436     $time  = date('H:i:s', $time);
437     return $date . 'T' . $time . $tzoff;
438 }
439
440 /**
441  * Format time in RFC-2822 format.
442  *
443  * @param $time time_t Time.  Default: now.
444  * @return string Date and time in RFC-2822 format.
445  */
446 function Rfc2822DateTime ($time = false) {
447     if ($time === false)
448         $time = time();
449     return date('D, j M Y H:i:s ', $time) . TimezoneOffset($time, 'no colon');
450 }
451
452 /**
453  * Format time to standard 'ctime' format.
454  *
455  * @param $time time_t Time.  Default: now.
456  * @return string Date and time in RFC-2822 format.
457  */
458 function CTime ($time = false)
459 {
460     if ($time === false)
461         $time = time();
462     return date("D M j H:i:s Y", $time);
463 }
464
465
466
467 /**
468  * Internationalized printf.
469  *
470  * This is essentially the same as PHP's built-in printf
471  * with the following exceptions:
472  * <ol>
473  * <li> It passes the format string through gettext().
474  * <li> It supports the argument reordering extensions.
475  * </ol>
476  *
477  * Example:
478  *
479  * In php code, use:
480  * <pre>
481  *    __printf("Differences between versions %s and %s of %s",
482  *             $new_link, $old_link, $page_link);
483  * </pre>
484  *
485  * Then in locale/po/de.po, one can reorder the printf arguments:
486  *
487  * <pre>
488  *    msgid "Differences between %s and %s of %s."
489  *    msgstr "Der Unterschiedsergebnis von %3$s, zwischen %1$s und %2$s."
490  * </pre>
491  *
492  * (Note that while PHP tries to expand $vars within double-quotes,
493  * the values in msgstr undergo no such expansion, so the '$'s
494  * okay...)
495  *
496  * One shouldn't use reordered arguments in the default format string.
497  * Backslashes in the default string would be necessary to escape the
498  * '$'s, and they'll cause all kinds of trouble....
499  */ 
500 function __printf ($fmt) {
501     $args = func_get_args();
502     array_shift($args);
503     echo __vsprintf($fmt, $args);
504 }
505
506 /**
507  * Internationalized sprintf.
508  *
509  * This is essentially the same as PHP's built-in printf with the
510  * following exceptions:
511  *
512  * <ol>
513  * <li> It passes the format string through gettext().
514  * <li> It supports the argument reordering extensions.
515  * </ol>
516  *
517  * @see __printf
518  */ 
519 function __sprintf ($fmt) {
520     $args = func_get_args();
521     array_shift($args);
522     return __vsprintf($fmt, $args);
523 }
524
525 /**
526  * Internationalized vsprintf.
527  *
528  * This is essentially the same as PHP's built-in printf with the
529  * following exceptions:
530  *
531  * <ol>
532  * <li> It passes the format string through gettext().
533  * <li> It supports the argument reordering extensions.
534  * </ol>
535  *
536  * @see __printf
537  */ 
538 function __vsprintf ($fmt, $args) {
539     $fmt = gettext($fmt);
540     // PHP's sprintf doesn't support variable with specifiers,
541     // like sprintf("%*s", 10, "x"); --- so we won't either.
542     
543     if (preg_match_all('/(?<!%)%(\d+)\$/x', $fmt, $m)) {
544         // Format string has '%2$s' style argument reordering.
545         // PHP doesn't support this.
546         if (preg_match('/(?<!%)%[- ]?\d*[^- \d$]/x', $fmt))
547             // literal variable name substitution only to keep locale
548             // strings uncluttered
549             trigger_error(sprintf(_("Can't mix '%s' with '%s' type format strings"),
550                                   '%1\$s','%s'), E_USER_WARNING); //php+locale error
551         
552         $fmt = preg_replace('/(?<!%)%\d+\$/x', '%', $fmt);
553         $newargs = array();
554         
555         // Reorder arguments appropriately.
556         foreach($m[1] as $argnum) {
557             if ($argnum < 1 || $argnum > count($args))
558                 trigger_error(sprintf(_("%s: argument index out of range"), 
559                                       $argnum), E_USER_WARNING);
560             $newargs[] = $args[$argnum - 1];
561         }
562         $args = $newargs;
563     }
564     
565     // Not all PHP's have vsprintf, so...
566     array_unshift($args, $fmt);
567     return call_user_func_array('sprintf', $args);
568 }
569
570
571 class fileSet {
572     /**
573      * Build an array in $this->_fileList of files from $dirname.
574      * Subdirectories are not traversed.
575      *
576      * (This was a function LoadDir in lib/loadsave.php)
577      * See also http://www.php.net/manual/en/function.readdir.php
578      */
579     function getFiles() {
580         return $this->_fileList;
581     }
582
583     function _filenameSelector($filename) {
584         // Default selects all filenames, override as needed.
585         return true;
586     }
587
588     function fileSet($directory) {
589         $this->_fileList = array();
590
591         if (empty($directory)) {
592             trigger_error(sprintf(_("%s is empty."), 'directoryname'),
593                           E_USER_NOTICE);
594             return; // early return
595         }
596
597         @ $dir_handle = opendir($dir=$directory);
598         if (empty($dir_handle)) {
599             trigger_error(sprintf(_("Unable to open directory '%s' for reading"),
600                                   $dir), E_USER_NOTICE);
601             return; // early return
602         }
603
604         while ($filename = readdir($dir_handle)) {
605             if ($filename[0] == '.' || filetype("$dir/$filename") != 'file')
606                 continue;
607             if ($this->_filenameSelector($filename)) {
608                 array_push($this->_fileList, "$filename");
609                 //trigger_error(sprintf(_("found file %s"), $filename),
610                 //                      E_USER_NOTICE); //debugging
611             }
612         }
613         closedir($dir_handle);
614     }
615 };
616
617
618 // Class introspections
619
620 /** Determine whether object is of a specified type.
621  *
622  * @param $object object An object.
623  * @param $class string Class name.
624  * @return bool True iff $object is a $class
625  * or a sub-type of $class. 
626  */
627 function isa ($object, $class) 
628 {
629     $lclass = strtolower($class);
630
631     return is_object($object)
632         && ( get_class($object) == strtolower($lclass)
633              || is_subclass_of($object, $lclass) );
634 }
635
636 /** Determine whether (possible) object has method.
637  *
638  * @param $object mixed Object
639  * @param $method string Method name
640  * @return bool True iff $object is an object with has method $method.
641  */
642 function can ($object, $method) 
643 {
644     return is_object($object) && method_exists($object, strtolower($method));
645 }
646
647 /**
648  * Seed the random number generator.
649  *
650  * better_srand() ensures the randomizer is seeded only once.
651  * 
652  * How random do you want it? See:
653  * http://www.php.net/manual/en/function.srand.php
654  * http://www.php.net/manual/en/function.mt-srand.php
655  */
656 function better_srand($seed = '') {
657     static $wascalled = FALSE;
658     if (!$wascalled) {
659         $seed = $seed === '' ? (double) microtime() * 1000000 : $seed;
660         srand($seed);
661         $wascalled = TRUE;
662         //trigger_error("new random seed", E_USER_NOTICE); //debugging
663     }
664 }
665
666 // (c-file-style: "gnu")
667 // Local Variables:
668 // mode: php
669 // tab-width: 8
670 // c-basic-offset: 4
671 // c-hanging-comment-ender-p: nil
672 // indent-tabs-mode: nil
673 // End:   
674 ?>