]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/stdlib.php
Cleaned up linkimage code.
[SourceForge/phpwiki.git] / lib / stdlib.php
1 <?php rcs_id('$Id: stdlib.php,v 1.53 2001-12-06 06:24:44 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    }
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       if (!defined('USE_LINK_ICONS')) {
121           return QElement('a',
122                      array('href' => $url, 'class' => $class),
123                      $linktext);
124       } else {
125             //ideally the link image would be specified by a map file
126             //similar to the interwiki.map
127             $linkproto = substr($url, 0, strrpos($url, ":"));
128                         switch($linkproto) {
129             case "mailto":
130                 $linkimg = "/images/mailto.png";
131             case "http":
132                 $linkimg = "/images/http.png";
133             case "https":
134                 $linkimg = "/images/https.png";
135             case "ftp":
136                 $linkimg = "/images/ftp.png";
137             else
138                 $linkimg = "/images/http.png";
139             }
140       return Element('a',
141                  array('href' => $url, 'class' => $class),
142                  Element('img', array('src' => DATA_PATH . $linkimg, 'alt' => $linkproto)) . $linktext);
143     }
144    }
145
146 function LinkWikiWord($wikiword, $linktext='') {
147     global $dbi;
148     if ($dbi->isWikiPage($wikiword))
149         return LinkExistingWikiWord($wikiword, $linktext);
150     else
151         return LinkUnknownWikiWord($wikiword, $linktext);
152 }
153
154     
155    function LinkExistingWikiWord($wikiword, $linktext='') {
156       if (empty($linktext)) {
157           $linktext = $wikiword;
158           if (defined("autosplit_wikiwords"))
159               $linktext=split_pagename($linktext);
160          $class = 'wiki';
161       }
162       else
163           $class = 'named-wiki';
164       
165       return QElement('a', array('href' => WikiURL($wikiword),
166                                  'class' => $class),
167                      $linktext);
168    }
169
170    function LinkUnknownWikiWord($wikiword, $linktext='') {
171       if (empty($linktext)) {
172           $linktext = $wikiword;
173           if (defined("autosplit_wikiwords"))
174               $linktext=split_pagename($linktext);
175           $class = 'wikiunknown';
176       }
177       else {
178           $class = 'named-wikiunknown';
179       }
180
181       return Element('span', array('class' => $class),
182                      QElement('a',
183                               array('href' => WikiURL($wikiword, array('action' => 'edit'))),
184                               '?')
185                      . Element('u', $linktext));
186    }
187
188    function LinkImage($url, $alt='[External Image]') {
189       // FIXME: Is this needed (or sufficient?)
190       //  As long as the src in htmlspecialchars()ed I think it's safe.
191       if(ereg('[<>"]', $url)) {
192          return Element('strong',
193                         QElement('u', array('class' => 'baduri'),
194                                  'BAD URL -- remove all of <, >, "'));
195       }
196       return Element('img', array('src' => $url, 'alt' => $alt));
197    }
198
199    // converts spaces to tabs
200    function CookSpaces($pagearray) {
201       return preg_replace("/ {3,8}/", "\t", $pagearray);
202    }
203
204
205    class Stack {
206       var $items = array();
207       var $size = 0;
208
209       function push($item) {
210          $this->items[$this->size] = $item;
211          $this->size++;
212          return true;
213       }  
214    
215       function pop() {
216          if ($this->size == 0) {
217             return false; // stack is empty
218          }  
219          $this->size--;
220          return $this->items[$this->size];
221       }  
222    
223       function cnt() {
224          return $this->size;
225       }  
226
227       function top() {
228          if($this->size)
229             return $this->items[$this->size - 1];
230          else
231             return '';
232       }  
233
234    }  
235    // end class definition
236
237
238    function MakeWikiForm ($pagename, $args, $class, $button_text = '')
239    {
240       $formargs['action'] = USE_PATH_INFO ? WikiURL($pagename) : SCRIPT_NAME;
241       $formargs['method'] = 'get';
242       $formargs['class'] = $class;
243       
244       $contents = '';
245       $input_seen = 0;
246       
247       while (list($key, $val) = each($args))
248       {
249          $a = array('name' => $key, 'value' => $val, 'type' => 'hidden');
250          
251          if (preg_match('/^ (\d*) \( (.*) \) ((upload)?) $/xi', $val, $m))
252          {
253             $input_seen++;
254             $a['type'] = 'text';
255             $a['size'] = $m[1] ? $m[1] : 30;
256             $a['value'] = $m[2];
257             if ($m[3])
258             {
259                $a['type'] = 'file';
260                $formargs['enctype'] = 'multipart/form-data';
261                $contents .= Element('input',
262                                     array('name' => 'MAX_FILE_SIZE',
263                                           'value' => MAX_UPLOAD_SIZE,
264                                           'type' => 'hidden'));
265                $formargs['method'] = 'post';
266             }
267          }
268
269          $contents .= Element('input', $a);
270       }
271
272       $row = Element('td', $contents);
273       
274       if (!empty($button_text)) {
275          $row .= Element('td', Element('input', array('type' => 'submit',
276                                                       'class' => 'button',
277                                                       'value' => $button_text)));
278       }
279
280       return Element('form', $formargs,
281                      Element('table', array('cellspacing' => 0, 'cellpadding' => 2, 'border' => 0),
282                              Element('tr', $row)));
283    }
284
285    function SplitQueryArgs ($query_args = '') 
286    {
287       $split_args = split('&', $query_args);
288       $args = array();
289       while (list($key, $val) = each($split_args))
290          if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
291             $args[$m[1]] = $m[2];
292       return $args;
293    }
294    
295 function LinkPhpwikiURL($url, $text = '') {
296         $args = array();
297
298         if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m))
299             return Element('strong',
300                            QElement('u', array('class' => 'baduri'),
301                                     'BAD phpwiki: URL'));
302         if ($m[1])
303                 $pagename = urldecode($m[1]);
304         $qargs = $m[2];
305       
306         if (empty($pagename) && preg_match('/^(diff|edit|links|info)=([^&]+)$/', $qargs, $m)) {
307                 // Convert old style links (to not break diff links in RecentChanges).
308                 $pagename = urldecode($m[2]);
309                 $args = array("action" => $m[1]);
310         }
311         else {
312                 $args = SplitQueryArgs($qargs);
313         }
314
315         if (empty($pagename))
316                 $pagename = $GLOBALS['pagename'];
317
318         if (isset($args['action']) && $args['action'] == 'browse')
319                 unset($args['action']);
320         /*FIXME:
321         if (empty($args['action']))
322                 $class = 'wikilink';
323         else if (is_safe_action($args['action']))
324                 $class = 'wikiaction';
325         */
326         if (empty($args['action']) || is_safe_action($args['action']))
327                 $class = 'wikiaction';
328         else {
329                 // Don't allow administrative links on unlocked pages.
330                 // FIXME: Ugh: don't like this...
331                 global $dbi;
332                 $page = $dbi->getPage($GLOBALS['pagename']);
333                 if (!$page->get('locked'))
334                         return QElement('u', array('class' => 'wikiunsafe'),
335                                                         gettext('Lock page to enable link'));
336
337                 $class = 'wikiadmin';
338         }
339       
340         // FIXME: ug, don't like this
341         if (preg_match('/=\d*\(/', $qargs))
342                 return MakeWikiForm($pagename, $args, $class, $text);
343         if ($text)
344                 $text = htmlspecialchars($text);
345         else
346                 $text = QElement('span', array('class' => 'rawurl'), $url);
347
348         return Element('a', array('href' => WikiURL($pagename, $args),
349                                                           'class' => $class),
350                                    $text);
351 }
352
353    function ParseAndLink($bracketlink) {
354       global $dbi, $AllowedProtocols, $InlineImages;
355       global $InterWikiLinkRegexp;
356
357       // $bracketlink will start and end with brackets; in between
358       // will be either a page name, a URL or both separated by a pipe.
359
360       // strip brackets and leading space
361       preg_match("/(\[\s*)(.+?)(\s*\])/", $bracketlink, $match);
362       // match the contents 
363       preg_match("/([^|]+)(\|)?([^|]+)?/", $match[2], $matches);
364
365       if (isset($matches[3])) {
366          // named link of the form  "[some link name | http://blippy.com/]"
367          $URL = trim($matches[3]);
368          $linkname = trim($matches[1]);
369          $linktype = 'named';
370       } else {
371          // unnamed link of the form "[http://blippy.com/] or [wiki page]"
372          $URL = trim($matches[1]);
373          $linkname = '';
374          $linktype = 'simple';
375       }
376
377       if ($dbi->isWikiPage($URL)) {
378          $link['type'] = "wiki-$linktype";
379          $link['link'] = LinkExistingWikiWord($URL, $linkname);
380       } elseif (preg_match("#^($AllowedProtocols):#", $URL)) {
381         // if it's an image, embed it; otherwise, it's a regular link
382          if (preg_match("/($InlineImages)$/i", $URL)) {
383             $link['type'] = "image-$linktype";
384             $link['link'] = LinkImage($URL, $linkname);
385          } else {
386             $link['type'] = "url-$linktype";
387             $link['link'] = LinkURL($URL, $linkname);
388             
389         
390            $link['link'] = LinkURL($URL, $linkname);
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 ?>