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