]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/stdlib.php
Moved some time functions to stdlib and refactored.
[SourceForge/phpwiki.git] / lib / stdlib.php
1 <?php rcs_id('$Id: stdlib.php,v 1.98 2002-02-03 19:03:44 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 /**
440  * Format time in ISO-8601 format.
441  *
442  * @param $time time_t Time.  Default: now.
443  * @return string Date and time in ISO-8601 format.
444  */
445 function Iso8601DateTime ($time = false) {
446     if ($time === false)
447         $time = time();
448     $tzoff = TimezoneOffset($time);
449     $date  = date('Y-m-d', $time);
450     $time  = date('H:i:s', $time);
451     return $date . 'T' . $time . $tzoff;
452 }
453
454 /**
455  * Format time in RFC-2822 format.
456  *
457  * @param $time time_t Time.  Default: now.
458  * @return string Date and time in RFC-2822 format.
459  */
460 function Rfc2822DateTime ($time = false) {
461     if ($time === false)
462         $time = time();
463     return date('D, j M Y H:i:s ', $time) . TimezoneOffset($time, 'no colon');
464 }
465
466 /**
467  * Format time to standard 'ctime' format.
468  *
469  * @param $time time_t Time.  Default: now.
470  * @return string Date and time in RFC-2822 format.
471  */
472 function CTime ($time = false)
473 {
474     if ($time === false)
475         $time = time();
476     return date("D M j H:i:s Y", $time);
477 }
478
479
480
481 /**
482  * Internationalized printf.
483  *
484  * This is essentially the same as PHP's built-in printf
485  * with the following exceptions:
486  * <ol>
487  * <li> It passes the format string through gettext().
488  * <li> It supports the argument reordering extensions.
489  * </ol>
490  *
491  * Example:
492  *
493  * In php code, use:
494  * <pre>
495  *    __printf("Differences between versions %s and %s of %s",
496  *             $new_link, $old_link, $page_link);
497  * </pre>
498  *
499  * Then in locale/po/de.po, one can reorder the printf arguments:
500  *
501  * <pre>
502  *    msgid "Differences between %s and %s of %s."
503  *    msgstr "Der Unterschiedsergebnis von %3$s, zwischen %1$s und %2$s."
504  * </pre>
505  *
506  * (Note that while PHP tries to expand $vars within double-quotes,
507  * the values in msgstr undergo no such expansion, so the '$'s
508  * okay...)
509  *
510  * One shouldn't use reordered arguments in the default format string.
511  * Backslashes in the default string would be necessary to escape the
512  * '$'s, and they'll cause all kinds of trouble....
513  */ 
514 function __printf ($fmt) {
515     $args = func_get_args();
516     array_shift($args);
517     echo __vsprintf($fmt, $args);
518 }
519
520 /**
521  * Internationalized sprintf.
522  *
523  * This is essentially the same as PHP's built-in printf with the
524  * following exceptions:
525  *
526  * <ol>
527  * <li> It passes the format string through gettext().
528  * <li> It supports the argument reordering extensions.
529  * </ol>
530  *
531  * @see __printf
532  */ 
533 function __sprintf ($fmt) {
534     $args = func_get_args();
535     array_shift($args);
536     return __vsprintf($fmt, $args);
537 }
538
539 /**
540  * Internationalized vsprintf.
541  *
542  * This is essentially the same as PHP's built-in printf with the
543  * following exceptions:
544  *
545  * <ol>
546  * <li> It passes the format string through gettext().
547  * <li> It supports the argument reordering extensions.
548  * </ol>
549  *
550  * @see __printf
551  */ 
552 function __vsprintf ($fmt, $args) {
553     $fmt = gettext($fmt);
554     // PHP's sprintf doesn't support variable with specifiers,
555     // like sprintf("%*s", 10, "x"); --- so we won't either.
556     
557     if (preg_match_all('/(?<!%)%(\d+)\$/x', $fmt, $m)) {
558         // Format string has '%2$s' style argument reordering.
559         // PHP doesn't support this.
560         if (preg_match('/(?<!%)%[- ]?\d*[^- \d$]/x', $fmt))
561             // literal variable name substitution only to keep locale
562             // strings uncluttered
563             trigger_error(sprintf(_("Can't mix '%s' with '%s' type format strings"),
564                                   '%1\$s','%s'), E_USER_WARNING); //php+locale error
565         
566         $fmt = preg_replace('/(?<!%)%\d+\$/x', '%', $fmt);
567         $newargs = array();
568         
569         // Reorder arguments appropriately.
570         foreach($m[1] as $argnum) {
571             if ($argnum < 1 || $argnum > count($args))
572                 trigger_error(sprintf(_("%s: argument index out of range"), 
573                                       $argnum), E_USER_WARNING);
574             $newargs[] = $args[$argnum - 1];
575         }
576         $args = $newargs;
577     }
578     
579     // Not all PHP's have vsprintf, so...
580     array_unshift($args, $fmt);
581     return call_user_func_array('sprintf', $args);
582 }
583
584
585 class fileSet {
586     /**
587      * Build an array in $this->_fileList of files from $dirname.
588      * Subdirectories are not traversed.
589      *
590      * (This was a function LoadDir in lib/loadsave.php)
591      * See also http://www.php.net/manual/en/function.readdir.php
592      */
593     function getFiles() {
594         return $this->_fileList;
595     }
596
597     function _filenameSelector($filename) {
598         // Default selects all filenames, override as needed.
599         return true;
600     }
601
602     function fileSet($directory) {
603         $this->_fileList = array();
604
605         if (empty($directory)) {
606             trigger_error(sprintf(_("%s is empty."), 'directoryname'),
607                           E_USER_NOTICE);
608             return; // early return
609         }
610
611         @ $dir_handle = opendir($dir=$directory);
612         if (empty($dir_handle)) {
613             trigger_error(sprintf(_("Unable to open directory '%s' for reading"),
614                                   $dir), E_USER_NOTICE);
615             return; // early return
616         }
617
618         while ($filename = readdir($dir_handle)) {
619             if ($filename[0] == '.' || filetype("$dir/$filename") != 'file')
620                 continue;
621             if ($this->_filenameSelector($filename)) {
622                 array_push($this->_fileList, "$filename");
623                 //trigger_error(sprintf(_("found file %s"), $filename),
624                 //                      E_USER_NOTICE); //debugging
625             }
626         }
627         closedir($dir_handle);
628     }
629 };
630
631
632 // Class introspections
633
634 /** Determine whether object is of a specified type.
635  *
636  * @param $object object An object.
637  * @param $class string Class name.
638  * @return bool True iff $object is a $class
639  * or a sub-type of $class. 
640  */
641 function isa ($object, $class) 
642 {
643     $lclass = strtolower($class);
644
645     return is_object($object)
646         && ( get_class($object) == strtolower($lclass)
647              || is_subclass_of($object, $lclass) );
648 }
649
650 /** Determine whether (possible) object has method.
651  *
652  * @param $object mixed Object
653  * @param $method string Method name
654  * @return bool True iff $object is an object with has method $method.
655  */
656 function can ($object, $method) 
657 {
658     return is_object($object) && method_exists($object, strtolower($method));
659 }
660
661 /**
662  * Seed the random number generator.
663  *
664  * better_srand() ensures the randomizer is seeded only once.
665  * 
666  * How random do you want it? See:
667  * http://www.php.net/manual/en/function.srand.php
668  * http://www.php.net/manual/en/function.mt-srand.php
669  */
670 function better_srand($seed = '') {
671     static $wascalled = FALSE;
672     if (!$wascalled) {
673         $seed = $seed === '' ? (double) microtime() * 1000000 : $seed;
674         srand($seed);
675         $wascalled = TRUE;
676         //trigger_error("new random seed", E_USER_NOTICE); //debugging
677     }
678 }
679
680 // (c-file-style: "gnu")
681 // Local Variables:
682 // mode: php
683 // tab-width: 8
684 // c-basic-offset: 4
685 // c-hanging-comment-ender-p: nil
686 // indent-tabs-mode: nil
687 // End:   
688 ?>