]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/stdlib.php
XHTML fixes. At this point, PhpWiki's output is almost valid XHTML.
[SourceForge/phpwiki.git] / lib / stdlib.php
1 <?php rcs_id('$Id: stdlib.php,v 1.44 2001-11-14 21:05:38 dairiki 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    }
26           
27 function WikiURL($pagename, $args = '', $get_abs_url = false) {
28     if (is_array($args)) {
29         $enc_args = array();
30         foreach  ($args as $key => $val) {
31             $enc_args[] = urlencode($key) . '=' . urlencode($val);
32         }
33         $args = join('&', $enc_args);
34     }
35
36     if (USE_PATH_INFO) {
37         $url = $get_abs_url ? SERVER_URL . VIRTUAL_PATH . "/" : '';
38         $url .= rawurlencode($pagename);
39         if ($args)
40             $url .= "?$args";
41     }
42     else {
43         $url = $get_abs_url ? SERVER_URL . SCRIPT_NAME : basename(SCRIPT_NAME);
44         $url .= "?pagename=" . rawurlencode($pagename);
45         if ($args)
46             $url .= "&$args";
47     }
48
49     return $url;
50 }
51
52 define('NO_END_TAG_PAT',
53        '/^' . join('|', array('area', 'base', 'basefont',
54                               'br', 'col', 'frame',
55                               'hr', 'img', 'input',
56                               'isindex', 'link', 'meta',
57                               'param')) . '$/i');
58
59 function StartTag($tag, $args = '')
60 {
61    $s = "<$tag";
62    if (is_array($args))
63    {
64       while (list($key, $val) = each($args))
65       {
66          if (is_string($val) || is_numeric($val))
67             $s .= sprintf(' %s="%s"', $key, htmlspecialchars($val));
68          else if ($val)
69             $s .= " $key=\"$key\"";
70       }
71    }
72    return "$s>";
73 }
74
75    
76 function Element($tag, $args = '', $content = '')
77 {
78     $html = "<$tag";
79     if (!is_array($args)) {
80         $content = $args;
81         $args = false;
82     }
83     $html = StartTag($tag, $args);
84     if (preg_match(NO_END_TAG_PAT, $tag)) {
85         assert(! $content);
86         return preg_replace('/>$/', " />", $html);
87     } else {
88         $html .= $content;
89         $html .= "</$tag>";//FIXME: newline might not always be desired.
90     }
91     return $html;
92 }
93
94 function QElement($tag, $args = '', $content = '')
95 {
96     if (is_array($args))
97         return Element($tag, $args, htmlspecialchars($content));
98     else {
99         $content = $args;
100         return Element($tag, htmlspecialchars($content));
101     }
102 }
103    
104    function LinkURL($url, $linktext='') {
105       // FIXME: Is this needed (or sufficient?)
106       if(ereg("[<>\"]", $url)) {
107           return Element('strong',
108                          QElement('u', array('class' => 'baduri'),
109                                   'BAD URL -- remove all of <, >, "'));
110       }
111
112       if (empty($linktext)) {
113           $linktext = $url;
114           $class = 'rawurl';
115       }
116       else {
117           $class = 'namedurl';
118       }
119
120       return QElement('a',
121                       array('href' => $url, 'class' => $class),
122                       $linktext);
123    }
124
125 function LinkWikiWord($wikiword, $linktext='') {
126     global $dbi;
127     if ($dbi->isWikiPage($wikiword))
128         return LinkExistingWikiWord($wikiword, $linktext);
129     else
130         return LinkUnknownWikiWord($wikiword, $linktext);
131 }
132
133     
134    function LinkExistingWikiWord($wikiword, $linktext='') {
135       if (empty($linktext)) {
136           $linktext = $wikiword;
137           $class = 'wiki';
138       }
139       else
140           $class = 'named-wiki';
141       
142       return QElement('a', array('href' => WikiURL($wikiword),
143                                  'class' => $class),
144                      $linktext);
145    }
146
147    function LinkUnknownWikiWord($wikiword, $linktext='') {
148       if (empty($linktext)) {
149           $linktext = $wikiword;
150           $class = 'wikiunknown';
151       }
152       else {
153           $class = 'named-wikiunknown';
154       }
155
156       return Element('span', array('class' => $class),
157                      QElement('a',
158                               array('href' => WikiURL($wikiword, array('action' => 'edit'))),
159                               '?')
160                      . Element('u', $linktext));
161    }
162
163    function LinkImage($url, $alt='[External Image]') {
164       // FIXME: Is this needed (or sufficient?)
165       //  As long as the src in htmlspecialchars()ed I think it's safe.
166       if(ereg('[<>"]', $url)) {
167          return Element('strong',
168                         QElement('u', array('class' => 'baduri'),
169                                  'BAD URL -- remove all of <, >, "'));
170       }
171       return Element('img', array('src' => $url, 'alt' => $alt));
172    }
173
174    // converts spaces to tabs
175    function CookSpaces($pagearray) {
176       return preg_replace("/ {3,8}/", "\t", $pagearray);
177    }
178
179
180    class Stack {
181       var $items = array();
182       var $size = 0;
183
184       function push($item) {
185          $this->items[$this->size] = $item;
186          $this->size++;
187          return true;
188       }  
189    
190       function pop() {
191          if ($this->size == 0) {
192             return false; // stack is empty
193          }  
194          $this->size--;
195          return $this->items[$this->size];
196       }  
197    
198       function cnt() {
199          return $this->size;
200       }  
201
202       function top() {
203          if($this->size)
204             return $this->items[$this->size - 1];
205          else
206             return '';
207       }  
208
209    }  
210    // end class definition
211
212
213    function MakeWikiForm ($pagename, $args, $class, $button_text = '')
214    {
215       $formargs['action'] = USE_PATH_INFO ? WikiURL($pagename) : SCRIPT_NAME;
216       $formargs['method'] = 'get';
217       $formargs['class'] = $class;
218       
219       $contents = '';
220       $input_seen = 0;
221       
222       while (list($key, $val) = each($args))
223       {
224          $a = array('name' => $key, 'value' => $val, 'type' => 'hidden');
225          
226          if (preg_match('/^ (\d*) \( (.*) \) ((upload)?) $/xi', $val, $m))
227          {
228             $input_seen++;
229             $a['type'] = 'text';
230             $a['size'] = $m[1] ? $m[1] : 30;
231             $a['value'] = $m[2];
232             if ($m[3])
233             {
234                $a['type'] = 'file';
235                $formargs['enctype'] = 'multipart/form-data';
236                $contents .= Element('input',
237                                     array('name' => 'MAX_FILE_SIZE',
238                                           'value' => MAX_UPLOAD_SIZE,
239                                           'type' => 'hidden'));
240                $formargs['method'] = 'post';
241             }
242          }
243
244          $contents .= Element('input', $a);
245       }
246
247       $row = Element('td', $contents);
248       
249       if (!empty($button_text)) {
250          $row .= Element('td', 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, 'cellpadding' => 2, 'border' => 0),
257                              Element('tr', $row)));
258    }
259
260    function SplitQueryArgs ($query_args = '') 
261    {
262       $split_args = split('&', $query_args);
263       $args = array();
264       while (list($key, $val) = each($split_args))
265          if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
266             $args[$m[1]] = $m[2];
267       return $args;
268    }
269    
270 function LinkPhpwikiURL($url, $text = '') {
271         $args = array();
272
273         if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m))
274             return Element('strong',
275                            QElement('u', array('class' => 'baduri'),
276                                     'BAD phpwiki: URL'));
277         if ($m[1])
278                 $pagename = urldecode($m[1]);
279         $qargs = $m[2];
280       
281         if (empty($pagename) && preg_match('/^(diff|edit|links|info)=([^&]+)$/', $qargs, $m)) {
282                 // Convert old style links (to not break diff links in RecentChanges).
283                 $pagename = urldecode($m[2]);
284                 $args = array("action" => $m[1]);
285         }
286         else {
287                 $args = SplitQueryArgs($qargs);
288         }
289
290         if (empty($pagename))
291                 $pagename = $GLOBALS['pagename'];
292
293         if (isset($args['action']) && $args['action'] == 'browse')
294                 unset($args['action']);
295         /*FIXME:
296         if (empty($args['action']))
297                 $class = 'wikilink';
298         else if (is_safe_action($args['action']))
299                 $class = 'wikiaction';
300         */
301         if (empty($args['action']) || is_safe_action($args['action']))
302                 $class = 'wikiaction';
303         else {
304                 // Don't allow administrative links on unlocked pages.
305                 // FIXME: Ugh: don't like this...
306                 global $dbi;
307                 $page = $dbi->getPage($GLOBALS['pagename']);
308                 if (!$page->get('locked'))
309                         return QElement('u', array('class' => 'wikiunsafe'),
310                                                         gettext('Lock page to enable link'));
311
312                 $class = 'wikiadmin';
313         }
314       
315         // FIXME: ug, don't like this
316         if (preg_match('/=\d*\(/', $qargs))
317                 return MakeWikiForm($pagename, $args, $class, $text);
318         if ($text)
319                 $text = htmlspecialchars($text);
320         else
321                 $text = QElement('span', array('class' => 'rawurl'), $url);
322
323         return Element('a', array('href' => WikiURL($pagename, $args),
324                                                           'class' => $class),
325                                    $text);
326 }
327
328    function ParseAndLink($bracketlink) {
329       global $dbi, $AllowedProtocols, $InlineImages;
330       global $InterWikiLinkRegexp;
331
332       // $bracketlink will start and end with brackets; in between
333       // will be either a page name, a URL or both separated by a pipe.
334
335       // strip brackets and leading space
336       preg_match("/(\[\s*)(.+?)(\s*\])/", $bracketlink, $match);
337       // match the contents 
338       preg_match("/([^|]+)(\|)?([^|]+)?/", $match[2], $matches);
339
340       if (isset($matches[3])) {
341          // named link of the form  "[some link name | http://blippy.com/]"
342          $URL = trim($matches[3]);
343          $linkname = trim($matches[1]);
344          $linktype = 'named';
345       } else {
346          // unnamed link of the form "[http://blippy.com/] or [wiki page]"
347          $URL = trim($matches[1]);
348          $linkname = '';
349          $linktype = 'simple';
350       }
351
352       if ($dbi->isWikiPage($URL)) {
353          $link['type'] = "wiki-$linktype";
354          $link['link'] = LinkExistingWikiWord($URL, $linkname);
355       } elseif (preg_match("#^($AllowedProtocols):#", $URL)) {
356         // if it's an image, embed it; otherwise, it's a regular link
357          if (preg_match("/($InlineImages)$/i", $URL)) {
358             $link['type'] = "image-$linktype";
359             $link['link'] = LinkImage($URL, $linkname);
360          } else {
361             $link['type'] = "url-$linktype";
362             $link['link'] = LinkURL($URL, $linkname);
363          }
364       } elseif (preg_match("#^phpwiki:(.*)#", $URL, $match)) {
365          $link['type'] = "url-wiki-$linktype";
366          $link['link'] = LinkPhpwikiURL($URL, $linkname);
367       } elseif (preg_match("#^\d+$#", $URL)) {
368          $link['type'] = "footnote-$linktype";
369          $link['link'] = $URL;
370       } elseif (function_exists('LinkInterWikiLink') &&
371                 preg_match("#^$InterWikiLinkRegexp:#", $URL)) {
372          $link['type'] = "interwiki-$linktype";
373          $link['link'] = LinkInterWikiLink($URL, $linkname);
374       } else {
375          $link['type'] = "wiki-unknown-$linktype";
376          $link['link'] = LinkUnknownWikiWord($URL, $linkname);
377       }
378
379       return $link;
380    }
381
382
383 function ExtractWikiPageLinks($content)
384 {
385     global $WikiNameRegexp;
386     
387     if (is_string($content))
388         $content = explode("\n", $content);
389
390     $wikilinks = array();
391     foreach ($content as $line) {
392         // remove plugin code
393         $line = preg_replace('/<\?plugin\s+\w.*?\?>/', '', $line);
394         // remove escaped '['
395         $line = str_replace('[[', ' ', $line);
396
397   // bracket links (only type wiki-* is of interest)
398   $numBracketLinks = preg_match_all("/\[\s*([^\]|]+\|)?\s*(.+?)\s*\]/", $line, $brktlinks);
399   for ($i = 0; $i < $numBracketLinks; $i++) {
400      $link = ParseAndLink($brktlinks[0][$i]);
401      if (preg_match("#^wiki#", $link['type']))
402         $wikilinks[$brktlinks[2][$i]] = 1;
403
404          $brktlink = preg_quote($brktlinks[0][$i]);
405          $line = preg_replace("|$brktlink|", '', $line);
406   }
407
408       // BumpyText old-style wiki links
409       if (preg_match_all("/!?$WikiNameRegexp/", $line, $link)) {
410          for ($i = 0; isset($link[0][$i]); $i++) {
411             if($link[0][$i][0] <> '!')
412                $wikilinks[$link[0][$i]] = 1;
413      }
414       }
415    }
416    return array_keys($wikilinks);
417 }      
418
419    function LinkRelatedPages($dbi, $pagename)
420    {
421       // currently not supported everywhere
422       if(!function_exists('GetWikiPageLinks'))
423          return '';
424
425       //FIXME: fix or toss?
426       $links = GetWikiPageLinks($dbi, $pagename);
427
428       $txt = QElement('strong',
429                       sprintf (gettext ("%d best incoming links:"), NUM_RELATED_PAGES));
430       for($i = 0; $i < NUM_RELATED_PAGES; $i++) {
431          if(isset($links['in'][$i])) {
432             list($name, $score) = $links['in'][$i];
433             $txt .= LinkExistingWikiWord($name) . " ($score), ";
434          }
435       }
436       
437       $txt .= "\n" . Element('br');
438       $txt .= Element('strong',
439                       sprintf (gettext ("%d best outgoing links:"), NUM_RELATED_PAGES));
440       for($i = 0; $i < NUM_RELATED_PAGES; $i++) {
441          if(isset($links['out'][$i])) {
442             list($name, $score) = $links['out'][$i];
443             if($dbi->isWikiPage($name))
444                $txt .= LinkExistingWikiWord($name) . " ($score), ";
445          }
446       }
447
448       $txt .= "\n" . Element('br');
449       $txt .= Element('strong',
450                       sprintf (gettext ("%d most popular nearby:"), NUM_RELATED_PAGES));
451       for($i = 0; $i < NUM_RELATED_PAGES; $i++) {
452          if(isset($links['popular'][$i])) {
453             list($name, $score) = $links['popular'][$i];
454             $txt .= LinkExistingWikiWord($name) . " ($score), ";
455          }
456       }
457       
458       return $txt;
459    }
460
461
462 /**
463  * Split WikiWords in page names.
464  *
465  * It has been deemed useful to split WikiWords (into "Wiki Words")
466  * in places like page titles.  This is rumored to help search engines
467  * quite a bit.
468  *
469  * @param $page string The page name.
470  *
471  * @return string The split name.
472  */
473 function split_pagename ($page) {
474     
475     if (preg_match("/\s/", $page))
476         return $page;           // Already split --- don't split any more.
477
478     // FIXME: this algorithm is Anglo-centric.
479     static $RE;
480     if (!isset($RE)) {
481         // This mess splits between a lower-case letter followed by either an upper-case
482         // or a numeral; except that it wont split the prefixes 'Mc', 'De', or 'Di' off
483         // of their tails.
484                         $RE[] = '/([[:lower:]])((?<!Mc|De|Di)[[:upper:]]|\d)/';
485         // This the single-letter words 'I' and 'A' from any following capitalized words.
486         $RE[] = '/(?: |^)([AI])([[:upper:]])/';
487         // Split numerals from following letters.
488         $RE[] = '/(\d)([[:alpha:]])/';
489
490         foreach ($RE as $key => $val)
491             $RE[$key] = pcre_fix_posix_classes($val);
492     }
493
494     foreach ($RE as $regexp)
495         $page = preg_replace($regexp, '\\1 \\2', $page);
496     return $page;
497 }
498
499 function NoSuchRevision ($page, $version) {
500     $html = Element('p', QElement('strong', gettext("Bad Version"))) . "\n";
501     $html .= QElement('p',
502                       sprintf(gettext("I'm sorry.  Version %d of %s is not in my database."),
503                               $version, $page->getName())) . "\n";
504
505     include_once('lib/Template.php');
506     echo GeneratePage('MESSAGE', $html, gettext("Bad Version"));
507     ExitWiki ("");
508 }
509
510
511 // (c-file-style: "gnu")
512 // Local Variables:
513 // mode: php
514 // tab-width: 8
515 // c-basic-offset: 4
516 // c-hanging-comment-ender-p: nil
517 // indent-tabs-mode: nil
518 // End:   
519 ?>