]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/stdlib.php
//define("USE_LINK_ICONS", 1) this turns on url indicator icons, inserted before...
[SourceForge/phpwiki.git] / lib / stdlib.php
1 <?php rcs_id('$Id: stdlib.php,v 1.49 2001-12-02 03:33:50 carstenklapp Exp $');
2
3    /*
4       Standard functions for Wiki functionality
5          WikiURL($pagename, $args, $abs)
6          LinkWikiWord($wikiword, $linktext) 
7          LinkExistingWikiWord($wikiword, $linktext) 
8          LinkUnknownWikiWord($wikiword, $linktext) 
9          LinkURL($url, $linktext)
10          LinkImage($url, $alt)
11          LinkInterWikiLink($link, $linktext)
12          CookSpaces($pagearray) 
13          class Stack (push(), pop(), cnt(), top())
14          UpdateRecentChanges($dbi, $pagename, $isnewpage) 
15          ParseAndLink($bracketlink)
16          ExtractWikiPageLinks($content)
17          LinkRelatedPages($dbi, $pagename)
18    */
19
20
21    function DataURL($url) {
22       if (preg_match('@^(\w+:|/)@', $url))
23          return $url;
24       return SERVER_URL . DATA_PATH . "/$url";
25       // Beginnings of theme support by Carsten Klapp:
26       /*
27       global $theme;
28       return SERVER_URL . DATA_PATH . "/templates/$theme/$url";
29       */
30    }
31           
32 function WikiURL($pagename, $args = '', $get_abs_url = false) {
33     if (is_array($args)) {
34         $enc_args = array();
35         foreach  ($args as $key => $val) {
36             $enc_args[] = urlencode($key) . '=' . urlencode($val);
37         }
38         $args = join('&', $enc_args);
39     }
40
41     if (USE_PATH_INFO) {
42         $url = $get_abs_url ? SERVER_URL . VIRTUAL_PATH . "/" : '';
43         $url .= rawurlencode($pagename);
44         if ($args)
45             $url .= "?$args";
46     }
47     else {
48         $url = $get_abs_url ? SERVER_URL . SCRIPT_NAME : basename(SCRIPT_NAME);
49         $url .= "?pagename=" . rawurlencode($pagename);
50         if ($args)
51             $url .= "&$args";
52     }
53
54     return $url;
55 }
56
57 define('NO_END_TAG_PAT',
58        '/^' . join('|', array('area', 'base', 'basefont',
59                               'br', 'col', 'frame',
60                               'hr', 'img', 'input',
61                               'isindex', 'link', 'meta',
62                               'param')) . '$/i');
63
64 function StartTag($tag, $args = '')
65 {
66    $s = "<$tag";
67    if (is_array($args))
68    {
69       while (list($key, $val) = each($args))
70       {
71          if (is_string($val) || is_numeric($val))
72             $s .= sprintf(' %s="%s"', $key, htmlspecialchars($val));
73          else if ($val)
74             $s .= " $key=\"$key\"";
75       }
76    }
77    return "$s>";
78 }
79
80    
81 function Element($tag, $args = '', $content = '')
82 {
83     $html = "<$tag";
84     if (!is_array($args)) {
85         $content = $args;
86         $args = false;
87     }
88     $html = StartTag($tag, $args);
89     if (preg_match(NO_END_TAG_PAT, $tag)) {
90         assert(! $content);
91         return preg_replace('/>$/', " />", $html);
92     } else {
93         $html .= $content;
94         $html .= "</$tag>";//FIXME: newline might not always be desired.
95     }
96     return $html;
97 }
98
99 function QElement($tag, $args = '', $content = '')
100 {
101     if (is_array($args))
102         return Element($tag, $args, htmlspecialchars($content));
103     else {
104         $content = $args;
105         return Element($tag, htmlspecialchars($content));
106     }
107 }
108    
109    function LinkURL($url, $linktext='') {
110       // FIXME: Is this needed (or sufficient?)
111       if(ereg("[<>\"]", $url)) {
112           return Element('strong',
113                          QElement('u', array('class' => 'baduri'),
114                                   'BAD URL -- remove all of <, >, "'));
115       }
116
117       if (empty($linktext)) {
118           $linktext = $url;
119           $class = 'rawurl';
120       }
121       else {
122           $class = 'namedurl';
123       }
124
125       return QElement('a',
126                       array('href' => $url, 'class' => $class),
127                       $linktext);
128    }
129
130 function LinkWikiWord($wikiword, $linktext='') {
131     global $dbi;
132     if ($dbi->isWikiPage($wikiword))
133         return LinkExistingWikiWord($wikiword, $linktext);
134     else
135         return LinkUnknownWikiWord($wikiword, $linktext);
136 }
137
138     
139    function LinkExistingWikiWord($wikiword, $linktext='') {
140       if (empty($linktext)) {
141           $linktext = $wikiword;
142           $class = 'wiki';
143       }
144       else
145           $class = 'named-wiki';
146       
147       return QElement('a', array('href' => WikiURL($wikiword),
148                                  'class' => $class),
149                      $linktext);
150    }
151
152    function LinkUnknownWikiWord($wikiword, $linktext='') {
153       if (empty($linktext)) {
154           $linktext = $wikiword;
155           $class = 'wikiunknown';
156       }
157       else {
158           $class = 'named-wikiunknown';
159       }
160
161       return Element('span', array('class' => $class),
162                      QElement('a',
163                               array('href' => WikiURL($wikiword, array('action' => 'edit'))),
164                               '?')
165                      . Element('u', $linktext));
166    }
167
168    function LinkImage($url, $alt='[External Image]') {
169       // FIXME: Is this needed (or sufficient?)
170       //  As long as the src in htmlspecialchars()ed I think it's safe.
171       if(ereg('[<>"]', $url)) {
172          return Element('strong',
173                         QElement('u', array('class' => 'baduri'),
174                                  'BAD URL -- remove all of <, >, "'));
175       }
176       return Element('img', array('src' => $url, 'alt' => $alt));
177    }
178
179    // converts spaces to tabs
180    function CookSpaces($pagearray) {
181       return preg_replace("/ {3,8}/", "\t", $pagearray);
182    }
183
184
185    class Stack {
186       var $items = array();
187       var $size = 0;
188
189       function push($item) {
190          $this->items[$this->size] = $item;
191          $this->size++;
192          return true;
193       }  
194    
195       function pop() {
196          if ($this->size == 0) {
197             return false; // stack is empty
198          }  
199          $this->size--;
200          return $this->items[$this->size];
201       }  
202    
203       function cnt() {
204          return $this->size;
205       }  
206
207       function top() {
208          if($this->size)
209             return $this->items[$this->size - 1];
210          else
211             return '';
212       }  
213
214    }  
215    // end class definition
216
217
218    function MakeWikiForm ($pagename, $args, $class, $button_text = '')
219    {
220       $formargs['action'] = USE_PATH_INFO ? WikiURL($pagename) : SCRIPT_NAME;
221       $formargs['method'] = 'get';
222       $formargs['class'] = $class;
223       
224       $contents = '';
225       $input_seen = 0;
226       
227       while (list($key, $val) = each($args))
228       {
229          $a = array('name' => $key, 'value' => $val, 'type' => 'hidden');
230          
231          if (preg_match('/^ (\d*) \( (.*) \) ((upload)?) $/xi', $val, $m))
232          {
233             $input_seen++;
234             $a['type'] = 'text';
235             $a['size'] = $m[1] ? $m[1] : 30;
236             $a['value'] = $m[2];
237             if ($m[3])
238             {
239                $a['type'] = 'file';
240                $formargs['enctype'] = 'multipart/form-data';
241                $contents .= Element('input',
242                                     array('name' => 'MAX_FILE_SIZE',
243                                           'value' => MAX_UPLOAD_SIZE,
244                                           'type' => 'hidden'));
245                $formargs['method'] = 'post';
246             }
247          }
248
249          $contents .= Element('input', $a);
250       }
251
252       $row = Element('td', $contents);
253       
254       if (!empty($button_text)) {
255          $row .= Element('td', Element('input', array('type' => 'submit',
256                                                       'class' => 'button',
257                                                       'value' => $button_text)));
258       }
259
260       return Element('form', $formargs,
261                      Element('table', array('cellspacing' => 0, 'cellpadding' => 2, 'border' => 0),
262                              Element('tr', $row)));
263    }
264
265    function SplitQueryArgs ($query_args = '') 
266    {
267       $split_args = split('&', $query_args);
268       $args = array();
269       while (list($key, $val) = each($split_args))
270          if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
271             $args[$m[1]] = $m[2];
272       return $args;
273    }
274    
275 function LinkPhpwikiURL($url, $text = '') {
276         $args = array();
277
278         if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m))
279             return Element('strong',
280                            QElement('u', array('class' => 'baduri'),
281                                     'BAD phpwiki: URL'));
282         if ($m[1])
283                 $pagename = urldecode($m[1]);
284         $qargs = $m[2];
285       
286         if (empty($pagename) && preg_match('/^(diff|edit|links|info)=([^&]+)$/', $qargs, $m)) {
287                 // Convert old style links (to not break diff links in 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                                                         gettext('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
338       // will 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         if (!defined("USE_LINK_ICONS")) {
370            $link['link'] = LinkURL($URL, $linkname);
371         } else {
372            //preg_split((.*?):(.*)$, $URL, $matches);
373            //preg_split("[:]", $URL, $matches);
374            //$protoc = $matches[0] . "-" . $matches[1];
375            $protoc = substr($URL, 0, strrpos($URL, ":"));
376            if ($protoc == "mailto") {
377                $link['link'] = "<img src=\"" . DATA_PATH . "/images/mailto.png\"> " . LinkURL($URL, $linkname);
378            } elseif ($protoc == "http") { 
379                $link['link'] = "<img src=\"" . DATA_PATH . "/images/http.png\"> " . LinkURL($URL, $linkname);
380            } elseif ($protoc == "https") { 
381                $link['link'] = "<img src=\"" . DATA_PATH . "/images/https.png\"> " . LinkURL($URL, $linkname);
382            } elseif ($protoc == "ftp") { 
383                $link['link'] = "<img src=\"" . DATA_PATH . "/images/ftp.png\"> " . LinkURL($URL, $linkname);
384             } else {
385                $link['link'] = LinkURL($URL, $linkname);
386            }
387         }
388
389          }
390       } elseif (preg_match("#^phpwiki:(.*)#", $URL, $match)) {
391          $link['type'] = "url-wiki-$linktype";
392          $link['link'] = LinkPhpwikiURL($URL, $linkname);
393       } elseif (preg_match("#^\d+$#", $URL)) {
394          $link['type'] = "footnote-$linktype";
395          $link['link'] = $URL;
396       } elseif (function_exists('LinkInterWikiLink') &&
397                 preg_match("#^$InterWikiLinkRegexp:#", $URL)) {
398          $link['type'] = "interwiki-$linktype";
399          $link['link'] = LinkInterWikiLink($URL, $linkname);
400       } else {
401          $link['type'] = "wiki-unknown-$linktype";
402          $link['link'] = LinkUnknownWikiWord($URL, $linkname);
403       }
404
405       return $link;
406    }
407
408
409 function ExtractWikiPageLinks($content)
410 {
411     global $WikiNameRegexp;
412     
413     if (is_string($content))
414         $content = explode("\n", $content);
415
416     $wikilinks = array();
417     foreach ($content as $line) {
418         // remove plugin code
419         $line = preg_replace('/<\?plugin\s+\w.*?\?>/', '', $line);
420         // remove escaped '['
421         $line = str_replace('[[', ' ', $line);
422
423   // bracket links (only type wiki-* is of interest)
424   $numBracketLinks = preg_match_all("/\[\s*([^\]|]+\|)?\s*(.+?)\s*\]/", $line, $brktlinks);
425   for ($i = 0; $i < $numBracketLinks; $i++) {
426      $link = ParseAndLink($brktlinks[0][$i]);
427      if (preg_match("#^wiki#", $link['type']))
428         $wikilinks[$brktlinks[2][$i]] = 1;
429
430          $brktlink = preg_quote($brktlinks[0][$i]);
431          $line = preg_replace("|$brktlink|", '', $line);
432   }
433
434       // BumpyText old-style wiki links
435       if (preg_match_all("/!?$WikiNameRegexp/", $line, $link)) {
436          for ($i = 0; isset($link[0][$i]); $i++) {
437             if($link[0][$i][0] <> '!')
438                $wikilinks[$link[0][$i]] = 1;
439      }
440       }
441    }
442    return array_keys($wikilinks);
443 }      
444
445    function LinkRelatedPages($dbi, $pagename)
446    {
447       // currently not supported everywhere
448       if(!function_exists('GetWikiPageLinks'))
449          return '';
450
451       //FIXME: fix or toss?
452       $links = GetWikiPageLinks($dbi, $pagename);
453
454       $txt = QElement('strong',
455                       sprintf (gettext ("%d best incoming links:"), NUM_RELATED_PAGES));
456       for($i = 0; $i < NUM_RELATED_PAGES; $i++) {
457          if(isset($links['in'][$i])) {
458             list($name, $score) = $links['in'][$i];
459             $txt .= LinkExistingWikiWord($name) . " ($score), ";
460          }
461       }
462       
463       $txt .= "\n" . Element('br');
464       $txt .= Element('strong',
465                       sprintf (gettext ("%d best outgoing links:"), NUM_RELATED_PAGES));
466       for($i = 0; $i < NUM_RELATED_PAGES; $i++) {
467          if(isset($links['out'][$i])) {
468             list($name, $score) = $links['out'][$i];
469             if($dbi->isWikiPage($name))
470                $txt .= LinkExistingWikiWord($name) . " ($score), ";
471          }
472       }
473
474       $txt .= "\n" . Element('br');
475       $txt .= Element('strong',
476                       sprintf (gettext ("%d most popular nearby:"), NUM_RELATED_PAGES));
477       for($i = 0; $i < NUM_RELATED_PAGES; $i++) {
478          if(isset($links['popular'][$i])) {
479             list($name, $score) = $links['popular'][$i];
480             $txt .= LinkExistingWikiWord($name) . " ($score), ";
481          }
482       }
483       
484       return $txt;
485    }
486
487
488 /**
489  * Split WikiWords in page names.
490  *
491  * It has been deemed useful to split WikiWords (into "Wiki Words")
492  * in places like page titles.  This is rumored to help search engines
493  * quite a bit.
494  *
495  * @param $page string The page name.
496  *
497  * @return string The split name.
498  */
499 function split_pagename ($page) {
500     
501     if (preg_match("/\s/", $page))
502         return $page;           // Already split --- don't split any more.
503
504     // FIXME: this algorithm is Anglo-centric.
505     static $RE;
506     if (!isset($RE)) {
507         // This mess splits between a lower-case letter followed by either an upper-case
508         // or a numeral; except that it wont split the prefixes 'Mc', 'De', or 'Di' off
509         // of their tails.
510                         $RE[] = '/([[:lower:]])((?<!Mc|De|Di)[[:upper:]]|\d)/';
511         // This the single-letter words 'I' and 'A' from any following capitalized words.
512         $RE[] = '/(?: |^)([AI])([[:upper:]])/';
513         // Split numerals from following letters.
514         $RE[] = '/(\d)([[:alpha:]])/';
515
516         foreach ($RE as $key => $val)
517             $RE[$key] = pcre_fix_posix_classes($val);
518     }
519
520     foreach ($RE as $regexp)
521         $page = preg_replace($regexp, '\\1 \\2', $page);
522     return $page;
523 }
524
525 function NoSuchRevision ($page, $version) {
526     $html = Element('p', QElement('strong', gettext("Bad Version"))) . "\n";
527     $html .= QElement('p',
528                       sprintf(gettext("I'm sorry.  Version %d of %s is not in my database."),
529                               $version, $page->getName())) . "\n";
530
531     include_once('lib/Template.php');
532     echo GeneratePage('MESSAGE', $html, gettext("Bad Version"));
533     ExitWiki ("");
534 }
535
536
537 // (c-file-style: "gnu")
538 // Local Variables:
539 // mode: php
540 // tab-width: 8
541 // c-basic-offset: 4
542 // c-hanging-comment-ender-p: nil
543 // indent-tabs-mode: nil
544 // End:   
545 ?>