]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/stdlib.php
//define("autosplit_wikiwords", 1); option to automatically split WikiWords by insert...
[SourceForge/phpwiki.git] / lib / stdlib.php
1 <?php rcs_id('$Id: stdlib.php,v 1.50 2001-12-02 07:53:59 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       if (defined("autosplit_wikiwords"))
143           $linktext=split_pagename($linktext);
144           $class = 'wiki';
145       }
146       else
147           $class = 'named-wiki';
148       
149       return QElement('a', array('href' => WikiURL($wikiword),
150                                  'class' => $class),
151                      $linktext);
152    }
153
154    function LinkUnknownWikiWord($wikiword, $linktext='') {
155       if (empty($linktext)) {
156           $linktext = $wikiword;
157       if (defined("autosplit_wikiwords"))
158           $linktext=split_pagename($linktext);
159           $class = 'wikiunknown';
160       }
161       else {
162           $class = 'named-wikiunknown';
163       }
164
165       return Element('span', array('class' => $class),
166                      QElement('a',
167                               array('href' => WikiURL($wikiword, array('action' => 'edit'))),
168                               '?')
169                      . Element('u', $linktext));
170    }
171
172    function LinkImage($url, $alt='[External Image]') {
173       // FIXME: Is this needed (or sufficient?)
174       //  As long as the src in htmlspecialchars()ed I think it's safe.
175       if(ereg('[<>"]', $url)) {
176          return Element('strong',
177                         QElement('u', array('class' => 'baduri'),
178                                  'BAD URL -- remove all of <, >, "'));
179       }
180       return Element('img', array('src' => $url, 'alt' => $alt));
181    }
182
183    // converts spaces to tabs
184    function CookSpaces($pagearray) {
185       return preg_replace("/ {3,8}/", "\t", $pagearray);
186    }
187
188
189    class Stack {
190       var $items = array();
191       var $size = 0;
192
193       function push($item) {
194          $this->items[$this->size] = $item;
195          $this->size++;
196          return true;
197       }  
198    
199       function pop() {
200          if ($this->size == 0) {
201             return false; // stack is empty
202          }  
203          $this->size--;
204          return $this->items[$this->size];
205       }  
206    
207       function cnt() {
208          return $this->size;
209       }  
210
211       function top() {
212          if($this->size)
213             return $this->items[$this->size - 1];
214          else
215             return '';
216       }  
217
218    }  
219    // end class definition
220
221
222    function MakeWikiForm ($pagename, $args, $class, $button_text = '')
223    {
224       $formargs['action'] = USE_PATH_INFO ? WikiURL($pagename) : SCRIPT_NAME;
225       $formargs['method'] = 'get';
226       $formargs['class'] = $class;
227       
228       $contents = '';
229       $input_seen = 0;
230       
231       while (list($key, $val) = each($args))
232       {
233          $a = array('name' => $key, 'value' => $val, 'type' => 'hidden');
234          
235          if (preg_match('/^ (\d*) \( (.*) \) ((upload)?) $/xi', $val, $m))
236          {
237             $input_seen++;
238             $a['type'] = 'text';
239             $a['size'] = $m[1] ? $m[1] : 30;
240             $a['value'] = $m[2];
241             if ($m[3])
242             {
243                $a['type'] = 'file';
244                $formargs['enctype'] = 'multipart/form-data';
245                $contents .= Element('input',
246                                     array('name' => 'MAX_FILE_SIZE',
247                                           'value' => MAX_UPLOAD_SIZE,
248                                           'type' => 'hidden'));
249                $formargs['method'] = 'post';
250             }
251          }
252
253          $contents .= Element('input', $a);
254       }
255
256       $row = Element('td', $contents);
257       
258       if (!empty($button_text)) {
259          $row .= Element('td', Element('input', array('type' => 'submit',
260                                                       'class' => 'button',
261                                                       'value' => $button_text)));
262       }
263
264       return Element('form', $formargs,
265                      Element('table', array('cellspacing' => 0, 'cellpadding' => 2, 'border' => 0),
266                              Element('tr', $row)));
267    }
268
269    function SplitQueryArgs ($query_args = '') 
270    {
271       $split_args = split('&', $query_args);
272       $args = array();
273       while (list($key, $val) = each($split_args))
274          if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
275             $args[$m[1]] = $m[2];
276       return $args;
277    }
278    
279 function LinkPhpwikiURL($url, $text = '') {
280         $args = array();
281
282         if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m))
283             return Element('strong',
284                            QElement('u', array('class' => 'baduri'),
285                                     'BAD phpwiki: URL'));
286         if ($m[1])
287                 $pagename = urldecode($m[1]);
288         $qargs = $m[2];
289       
290         if (empty($pagename) && preg_match('/^(diff|edit|links|info)=([^&]+)$/', $qargs, $m)) {
291                 // Convert old style links (to not break diff links in RecentChanges).
292                 $pagename = urldecode($m[2]);
293                 $args = array("action" => $m[1]);
294         }
295         else {
296                 $args = SplitQueryArgs($qargs);
297         }
298
299         if (empty($pagename))
300                 $pagename = $GLOBALS['pagename'];
301
302         if (isset($args['action']) && $args['action'] == 'browse')
303                 unset($args['action']);
304         /*FIXME:
305         if (empty($args['action']))
306                 $class = 'wikilink';
307         else if (is_safe_action($args['action']))
308                 $class = 'wikiaction';
309         */
310         if (empty($args['action']) || is_safe_action($args['action']))
311                 $class = 'wikiaction';
312         else {
313                 // Don't allow administrative links on unlocked pages.
314                 // FIXME: Ugh: don't like this...
315                 global $dbi;
316                 $page = $dbi->getPage($GLOBALS['pagename']);
317                 if (!$page->get('locked'))
318                         return QElement('u', array('class' => 'wikiunsafe'),
319                                                         gettext('Lock page to enable link'));
320
321                 $class = 'wikiadmin';
322         }
323       
324         // FIXME: ug, don't like this
325         if (preg_match('/=\d*\(/', $qargs))
326                 return MakeWikiForm($pagename, $args, $class, $text);
327         if ($text)
328                 $text = htmlspecialchars($text);
329         else
330                 $text = QElement('span', array('class' => 'rawurl'), $url);
331
332         return Element('a', array('href' => WikiURL($pagename, $args),
333                                                           'class' => $class),
334                                    $text);
335 }
336
337    function ParseAndLink($bracketlink) {
338       global $dbi, $AllowedProtocols, $InlineImages;
339       global $InterWikiLinkRegexp;
340
341       // $bracketlink will start and end with brackets; in between
342       // will be either a page name, a URL or both separated by a pipe.
343
344       // strip brackets and leading space
345       preg_match("/(\[\s*)(.+?)(\s*\])/", $bracketlink, $match);
346       // match the contents 
347       preg_match("/([^|]+)(\|)?([^|]+)?/", $match[2], $matches);
348
349       if (isset($matches[3])) {
350          // named link of the form  "[some link name | http://blippy.com/]"
351          $URL = trim($matches[3]);
352          $linkname = trim($matches[1]);
353          $linktype = 'named';
354       } else {
355          // unnamed link of the form "[http://blippy.com/] or [wiki page]"
356          $URL = trim($matches[1]);
357          $linkname = '';
358          $linktype = 'simple';
359       }
360
361       if ($dbi->isWikiPage($URL)) {
362          $link['type'] = "wiki-$linktype";
363          $link['link'] = LinkExistingWikiWord($URL, $linkname);
364       } elseif (preg_match("#^($AllowedProtocols):#", $URL)) {
365         // if it's an image, embed it; otherwise, it's a regular link
366          if (preg_match("/($InlineImages)$/i", $URL)) {
367             $link['type'] = "image-$linktype";
368             $link['link'] = LinkImage($URL, $linkname);
369          } else {
370             $link['type'] = "url-$linktype";
371             $link['link'] = LinkURL($URL, $linkname);
372             
373         if (!defined("USE_LINK_ICONS")) {
374            $link['link'] = LinkURL($URL, $linkname);
375         } else {
376            //preg_split((.*?):(.*)$, $URL, $matches);
377            //preg_split("[:]", $URL, $matches);
378            //$protoc = $matches[0] . "-" . $matches[1];
379            $protoc = substr($URL, 0, strrpos($URL, ":"));
380            if ($protoc == "mailto") {
381                $link['link'] = "<img src=\"" . DATA_PATH . "/images/mailto.png\"> " . LinkURL($URL, $linkname);
382            } elseif ($protoc == "http") { 
383                $link['link'] = "<img src=\"" . DATA_PATH . "/images/http.png\"> " . LinkURL($URL, $linkname);
384            } elseif ($protoc == "https") { 
385                $link['link'] = "<img src=\"" . DATA_PATH . "/images/https.png\"> " . LinkURL($URL, $linkname);
386            } elseif ($protoc == "ftp") { 
387                $link['link'] = "<img src=\"" . DATA_PATH . "/images/ftp.png\"> " . LinkURL($URL, $linkname);
388             } else {
389                $link['link'] = LinkURL($URL, $linkname);
390            }
391         }
392
393          }
394       } elseif (preg_match("#^phpwiki:(.*)#", $URL, $match)) {
395          $link['type'] = "url-wiki-$linktype";
396          $link['link'] = LinkPhpwikiURL($URL, $linkname);
397       } elseif (preg_match("#^\d+$#", $URL)) {
398          $link['type'] = "footnote-$linktype";
399          $link['link'] = $URL;
400       } elseif (function_exists('LinkInterWikiLink') &&
401                 preg_match("#^$InterWikiLinkRegexp:#", $URL)) {
402          $link['type'] = "interwiki-$linktype";
403          $link['link'] = LinkInterWikiLink($URL, $linkname);
404       } else {
405          $link['type'] = "wiki-unknown-$linktype";
406          $link['link'] = LinkUnknownWikiWord($URL, $linkname);
407       }
408
409       return $link;
410    }
411
412
413 function ExtractWikiPageLinks($content)
414 {
415     global $WikiNameRegexp;
416     
417     if (is_string($content))
418         $content = explode("\n", $content);
419
420     $wikilinks = array();
421     foreach ($content as $line) {
422         // remove plugin code
423         $line = preg_replace('/<\?plugin\s+\w.*?\?>/', '', $line);
424         // remove escaped '['
425         $line = str_replace('[[', ' ', $line);
426
427   // bracket links (only type wiki-* is of interest)
428   $numBracketLinks = preg_match_all("/\[\s*([^\]|]+\|)?\s*(.+?)\s*\]/", $line, $brktlinks);
429   for ($i = 0; $i < $numBracketLinks; $i++) {
430      $link = ParseAndLink($brktlinks[0][$i]);
431      if (preg_match("#^wiki#", $link['type']))
432         $wikilinks[$brktlinks[2][$i]] = 1;
433
434          $brktlink = preg_quote($brktlinks[0][$i]);
435          $line = preg_replace("|$brktlink|", '', $line);
436   }
437
438       // BumpyText old-style wiki links
439       if (preg_match_all("/!?$WikiNameRegexp/", $line, $link)) {
440          for ($i = 0; isset($link[0][$i]); $i++) {
441             if($link[0][$i][0] <> '!')
442                $wikilinks[$link[0][$i]] = 1;
443      }
444       }
445    }
446    return array_keys($wikilinks);
447 }      
448
449    function LinkRelatedPages($dbi, $pagename)
450    {
451       // currently not supported everywhere
452       if(!function_exists('GetWikiPageLinks'))
453          return '';
454
455       //FIXME: fix or toss?
456       $links = GetWikiPageLinks($dbi, $pagename);
457
458       $txt = QElement('strong',
459                       sprintf (gettext ("%d best incoming links:"), NUM_RELATED_PAGES));
460       for($i = 0; $i < NUM_RELATED_PAGES; $i++) {
461          if(isset($links['in'][$i])) {
462             list($name, $score) = $links['in'][$i];
463             $txt .= LinkExistingWikiWord($name) . " ($score), ";
464          }
465       }
466       
467       $txt .= "\n" . Element('br');
468       $txt .= Element('strong',
469                       sprintf (gettext ("%d best outgoing links:"), NUM_RELATED_PAGES));
470       for($i = 0; $i < NUM_RELATED_PAGES; $i++) {
471          if(isset($links['out'][$i])) {
472             list($name, $score) = $links['out'][$i];
473             if($dbi->isWikiPage($name))
474                $txt .= LinkExistingWikiWord($name) . " ($score), ";
475          }
476       }
477
478       $txt .= "\n" . Element('br');
479       $txt .= Element('strong',
480                       sprintf (gettext ("%d most popular nearby:"), NUM_RELATED_PAGES));
481       for($i = 0; $i < NUM_RELATED_PAGES; $i++) {
482          if(isset($links['popular'][$i])) {
483             list($name, $score) = $links['popular'][$i];
484             $txt .= LinkExistingWikiWord($name) . " ($score), ";
485          }
486       }
487       
488       return $txt;
489    }
490
491
492 /**
493  * Split WikiWords in page names.
494  *
495  * It has been deemed useful to split WikiWords (into "Wiki Words")
496  * in places like page titles.  This is rumored to help search engines
497  * quite a bit.
498  *
499  * @param $page string The page name.
500  *
501  * @return string The split name.
502  */
503 function split_pagename ($page) {
504     
505     if (preg_match("/\s/", $page))
506         return $page;           // Already split --- don't split any more.
507
508     // FIXME: this algorithm is Anglo-centric.
509     static $RE;
510     if (!isset($RE)) {
511         // This mess splits between a lower-case letter followed by either an upper-case
512         // or a numeral; except that it wont split the prefixes 'Mc', 'De', or 'Di' off
513         // of their tails.
514                         $RE[] = '/([[:lower:]])((?<!Mc|De|Di)[[:upper:]]|\d)/';
515         // This the single-letter words 'I' and 'A' from any following capitalized words.
516         $RE[] = '/(?: |^)([AI])([[:upper:]])/';
517         // Split numerals from following letters.
518         $RE[] = '/(\d)([[:alpha:]])/';
519
520         foreach ($RE as $key => $val)
521             $RE[$key] = pcre_fix_posix_classes($val);
522     }
523
524     foreach ($RE as $regexp)
525         $page = preg_replace($regexp, '\\1 \\2', $page);
526     return $page;
527 }
528
529 function NoSuchRevision ($page, $version) {
530     $html = Element('p', QElement('strong', gettext("Bad Version"))) . "\n";
531     $html .= QElement('p',
532                       sprintf(gettext("I'm sorry.  Version %d of %s is not in my database."),
533                               $version, $page->getName())) . "\n";
534
535     include_once('lib/Template.php');
536     echo GeneratePage('MESSAGE', $html, gettext("Bad Version"));
537     ExitWiki ("");
538 }
539
540
541 // (c-file-style: "gnu")
542 // Local Variables:
543 // mode: php
544 // tab-width: 8
545 // c-basic-offset: 4
546 // c-hanging-comment-ender-p: nil
547 // indent-tabs-mode: nil
548 // End:   
549 ?>