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