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