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