]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/stdlib.php
*** empty log message ***
[SourceForge/phpwiki.git] / lib / stdlib.php
1 <?php rcs_id('$Id: stdlib.php,v 1.47 2001-12-02 01:59:23 joe_edelman 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, 'class' => 'wikiimage'));
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       } 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          $link['link'] = LinkUnknownWikiWord($URL, $linkname);
382       }
383
384       return $link;
385    }
386
387
388 function ExtractWikiPageLinks($content)
389 {
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*\]/", $line, $brktlinks);
404   for ($i = 0; $i < $numBracketLinks; $i++) {
405      $link = ParseAndLink($brktlinks[0][$i]);
406      if (preg_match("#^wiki#", $link['type']))
407         $wikilinks[$brktlinks[2][$i]] = 1;
408
409          $brktlink = preg_quote($brktlinks[0][$i]);
410          $line = preg_replace("|$brktlink|", '', $line);
411   }
412
413       // BumpyText old-style wiki links
414       if (preg_match_all("/!?$WikiNameRegexp/", $line, $link)) {
415          for ($i = 0; isset($link[0][$i]); $i++) {
416             if($link[0][$i][0] <> '!')
417                $wikilinks[$link[0][$i]] = 1;
418      }
419       }
420    }
421    return array_keys($wikilinks);
422 }      
423
424    function LinkRelatedPages($dbi, $pagename)
425    {
426       // currently not supported everywhere
427       if(!function_exists('GetWikiPageLinks'))
428          return '';
429
430       //FIXME: fix or toss?
431       $links = GetWikiPageLinks($dbi, $pagename);
432
433       $txt = QElement('strong',
434                       sprintf (gettext ("%d best incoming links:"), NUM_RELATED_PAGES));
435       for($i = 0; $i < NUM_RELATED_PAGES; $i++) {
436          if(isset($links['in'][$i])) {
437             list($name, $score) = $links['in'][$i];
438             $txt .= LinkExistingWikiWord($name) . " ($score), ";
439          }
440       }
441       
442       $txt .= "\n" . Element('br');
443       $txt .= Element('strong',
444                       sprintf (gettext ("%d best outgoing links:"), NUM_RELATED_PAGES));
445       for($i = 0; $i < NUM_RELATED_PAGES; $i++) {
446          if(isset($links['out'][$i])) {
447             list($name, $score) = $links['out'][$i];
448             if($dbi->isWikiPage($name))
449                $txt .= LinkExistingWikiWord($name) . " ($score), ";
450          }
451       }
452
453       $txt .= "\n" . Element('br');
454       $txt .= Element('strong',
455                       sprintf (gettext ("%d most popular nearby:"), NUM_RELATED_PAGES));
456       for($i = 0; $i < NUM_RELATED_PAGES; $i++) {
457          if(isset($links['popular'][$i])) {
458             list($name, $score) = $links['popular'][$i];
459             $txt .= LinkExistingWikiWord($name) . " ($score), ";
460          }
461       }
462       
463       return $txt;
464    }
465
466
467 /**
468  * Split WikiWords in page names.
469  *
470  * It has been deemed useful to split WikiWords (into "Wiki Words")
471  * in places like page titles.  This is rumored to help search engines
472  * quite a bit.
473  *
474  * @param $page string The page name.
475  *
476  * @return string The split name.
477  */
478 function split_pagename ($page) {
479     
480     if (preg_match("/\s/", $page))
481         return $page;           // Already split --- don't split any more.
482
483     // FIXME: this algorithm is Anglo-centric.
484     static $RE;
485     if (!isset($RE)) {
486         // This mess splits between a lower-case letter followed by either an upper-case
487         // or a numeral; except that it wont split the prefixes 'Mc', 'De', or 'Di' off
488         // of their tails.
489                         $RE[] = '/([[:lower:]])((?<!Mc|De|Di)[[:upper:]]|\d)/';
490         // This the single-letter words 'I' and 'A' from any following capitalized words.
491         $RE[] = '/(?: |^)([AI])([[:upper:]])/';
492         // Split numerals from following letters.
493         $RE[] = '/(\d)([[:alpha:]])/';
494
495         foreach ($RE as $key => $val)
496             $RE[$key] = pcre_fix_posix_classes($val);
497     }
498
499     foreach ($RE as $regexp)
500         $page = preg_replace($regexp, '\\1 \\2', $page);
501     return $page;
502 }
503
504 function NoSuchRevision ($page, $version) {
505     $html = Element('p', QElement('strong', gettext("Bad Version"))) . "\n";
506     $html .= QElement('p',
507                       sprintf(gettext("I'm sorry.  Version %d of %s is not in my database."),
508                               $version, $page->getName())) . "\n";
509
510     include_once('lib/Template.php');
511     echo GeneratePage('MESSAGE', $html, gettext("Bad Version"));
512     ExitWiki ("");
513 }
514
515
516 // (c-file-style: "gnu")
517 // Local Variables:
518 // mode: php
519 // tab-width: 8
520 // c-basic-offset: 4
521 // c-hanging-comment-ender-p: nil
522 // indent-tabs-mode: nil
523 // End:   
524 ?>