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