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