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