1 <?php rcs_id('$Id: stdlib.php,v 1.54 2001-12-06 18:29:15 dairiki Exp $');
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)
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)
21 function DataURL($url) {
22 if (preg_match('@^(\w+:|/)@', $url))
24 return SERVER_URL . DATA_PATH . "/$url";
27 function WikiURL($pagename, $args = '', $get_abs_url = false) {
28 if (is_array($args)) {
30 foreach ($args as $key => $val) {
31 $enc_args[] = urlencode($key) . '=' . urlencode($val);
33 $args = join('&', $enc_args);
37 $url = $get_abs_url ? SERVER_URL . VIRTUAL_PATH . "/" : '';
38 $url .= rawurlencode($pagename);
43 $url = $get_abs_url ? SERVER_URL . SCRIPT_NAME : basename(SCRIPT_NAME);
44 $url .= "?pagename=" . rawurlencode($pagename);
52 define('NO_END_TAG_PAT',
53 '/^' . join('|', array('area', 'base', 'basefont',
56 'isindex', 'link', 'meta',
59 function StartTag($tag, $args = '')
64 while (list($key, $val) = each($args))
66 if (is_string($val) || is_numeric($val))
67 $s .= sprintf(' %s="%s"', $key, htmlspecialchars($val));
69 $s .= " $key=\"$key\"";
76 function Element($tag, $args = '', $content = '')
79 if (!is_array($args)) {
83 $html = StartTag($tag, $args);
84 if (preg_match(NO_END_TAG_PAT, $tag)) {
86 return preg_replace('/>$/', " />", $html);
89 $html .= "</$tag>";//FIXME: newline might not always be desired.
94 function QElement($tag, $args = '', $content = '')
97 return Element($tag, $args, htmlspecialchars($content));
100 return Element($tag, htmlspecialchars($content));
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 <, >, "')); //"
112 if (empty($linktext)) {
120 if (!defined('USE_LINK_ICONS')) {
122 array('href' => $url, 'class' => $class),
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, ":"));
130 $linkimg = "/images/mailto.png";
133 $linkimg = "/images/http.png";
136 $linkimg = "/images/https.png";
139 $linkimg = "/images/ftp.png";
142 $linkimg = "/images/http.png";
146 array('href' => $url, 'class' => $class),
147 Element('img', array('src' => DATA_PATH . $linkimg,
148 'alt' => $linkproto))
153 function LinkWikiWord($wikiword, $linktext='') {
155 if ($dbi->isWikiPage($wikiword))
156 return LinkExistingWikiWord($wikiword, $linktext);
158 return LinkUnknownWikiWord($wikiword, $linktext);
162 function LinkExistingWikiWord($wikiword, $linktext='') {
163 if (empty($linktext)) {
164 $linktext = $wikiword;
165 if (defined("autosplit_wikiwords"))
166 $linktext=split_pagename($linktext);
170 $class = 'named-wiki';
172 return QElement('a', array('href' => WikiURL($wikiword),
177 function LinkUnknownWikiWord($wikiword, $linktext='') {
178 if (empty($linktext)) {
179 $linktext = $wikiword;
180 if (defined("autosplit_wikiwords"))
181 $linktext=split_pagename($linktext);
182 $class = 'wikiunknown';
185 $class = 'named-wikiunknown';
188 return Element('span', array('class' => $class),
190 array('href' => WikiURL($wikiword, array('action' => 'edit'))),
192 . Element('u', $linktext));
195 function LinkImage($url, $alt='[External Image]') {
196 // FIXME: Is this needed (or sufficient?)
197 // As long as the src in htmlspecialchars()ed I think it's safe.
198 if(ereg('[<>"]', $url)) {
199 return Element('strong',
200 QElement('u', array('class' => 'baduri'),
201 'BAD URL -- remove all of <, >, "'));
203 return Element('img', array('src' => $url, 'alt' => $alt));
206 // converts spaces to tabs
207 function CookSpaces($pagearray) {
208 return preg_replace("/ {3,8}/", "\t", $pagearray);
213 var $items = array();
216 function push($item) {
217 $this->items[$this->size] = $item;
223 if ($this->size == 0) {
224 return false; // stack is empty
227 return $this->items[$this->size];
236 return $this->items[$this->size - 1];
242 // end class definition
245 function MakeWikiForm ($pagename, $args, $class, $button_text = '')
247 $formargs['action'] = USE_PATH_INFO ? WikiURL($pagename) : SCRIPT_NAME;
248 $formargs['method'] = 'get';
249 $formargs['class'] = $class;
254 while (list($key, $val) = each($args))
256 $a = array('name' => $key, 'value' => $val, 'type' => 'hidden');
258 if (preg_match('/^ (\d*) \( (.*) \) ((upload)?) $/xi', $val, $m))
262 $a['size'] = $m[1] ? $m[1] : 30;
267 $formargs['enctype'] = 'multipart/form-data';
268 $contents .= Element('input',
269 array('name' => 'MAX_FILE_SIZE',
270 'value' => MAX_UPLOAD_SIZE,
271 'type' => 'hidden'));
272 $formargs['method'] = 'post';
276 $contents .= Element('input', $a);
279 $row = Element('td', $contents);
281 if (!empty($button_text)) {
282 $row .= Element('td', Element('input', array('type' => 'submit',
284 'value' => $button_text)));
287 return Element('form', $formargs,
288 Element('table', array('cellspacing' => 0, 'cellpadding' => 2, 'border' => 0),
289 Element('tr', $row)));
292 function SplitQueryArgs ($query_args = '')
294 $split_args = split('&', $query_args);
296 while (list($key, $val) = each($split_args))
297 if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
298 $args[$m[1]] = $m[2];
302 function LinkPhpwikiURL($url, $text = '') {
305 if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m))
306 return Element('strong',
307 QElement('u', array('class' => 'baduri'),
308 'BAD phpwiki: URL'));
310 $pagename = urldecode($m[1]);
313 if (empty($pagename) && preg_match('/^(diff|edit|links|info)=([^&]+)$/', $qargs, $m)) {
314 // Convert old style links (to not break diff links in RecentChanges).
315 $pagename = urldecode($m[2]);
316 $args = array("action" => $m[1]);
319 $args = SplitQueryArgs($qargs);
322 if (empty($pagename))
323 $pagename = $GLOBALS['pagename'];
325 if (isset($args['action']) && $args['action'] == 'browse')
326 unset($args['action']);
328 if (empty($args['action']))
330 else if (is_safe_action($args['action']))
331 $class = 'wikiaction';
333 if (empty($args['action']) || is_safe_action($args['action']))
334 $class = 'wikiaction';
336 // Don't allow administrative links on unlocked pages.
337 // FIXME: Ugh: don't like this...
339 $page = $dbi->getPage($GLOBALS['pagename']);
340 if (!$page->get('locked'))
341 return QElement('u', array('class' => 'wikiunsafe'),
342 gettext('Lock page to enable link'));
344 $class = 'wikiadmin';
347 // FIXME: ug, don't like this
348 if (preg_match('/=\d*\(/', $qargs))
349 return MakeWikiForm($pagename, $args, $class, $text);
351 $text = htmlspecialchars($text);
353 $text = QElement('span', array('class' => 'rawurl'), $url);
355 return Element('a', array('href' => WikiURL($pagename, $args),
360 function ParseAndLink($bracketlink) {
361 global $dbi, $AllowedProtocols, $InlineImages;
362 global $InterWikiLinkRegexp;
364 // $bracketlink will start and end with brackets; in between
365 // will be either a page name, a URL or both separated by a pipe.
367 // strip brackets and leading space
368 preg_match("/(\[\s*)(.+?)(\s*\])/", $bracketlink, $match);
369 // match the contents
370 preg_match("/([^|]+)(\|)?([^|]+)?/", $match[2], $matches);
372 if (isset($matches[3])) {
373 // named link of the form "[some link name | http://blippy.com/]"
374 $URL = trim($matches[3]);
375 $linkname = trim($matches[1]);
378 // unnamed link of the form "[http://blippy.com/] or [wiki page]"
379 $URL = trim($matches[1]);
381 $linktype = 'simple';
384 if ($dbi->isWikiPage($URL)) {
385 $link['type'] = "wiki-$linktype";
386 $link['link'] = LinkExistingWikiWord($URL, $linkname);
387 } elseif (preg_match("#^($AllowedProtocols):#", $URL)) {
388 // if it's an image, embed it; otherwise, it's a regular link
389 if (preg_match("/($InlineImages)$/i", $URL)) {
390 $link['type'] = "image-$linktype";
391 $link['link'] = LinkImage($URL, $linkname);
393 $link['type'] = "url-$linktype";
394 $link['link'] = LinkURL($URL, $linkname);
396 } elseif (preg_match("#^phpwiki:(.*)#", $URL, $match)) {
397 $link['type'] = "url-wiki-$linktype";
398 $link['link'] = LinkPhpwikiURL($URL, $linkname);
399 } elseif (preg_match("#^\d+$#", $URL)) {
400 $link['type'] = "footnote-$linktype";
401 $link['link'] = $URL;
402 } elseif (function_exists('LinkInterWikiLink') &&
403 preg_match("#^$InterWikiLinkRegexp:#", $URL)) {
404 $link['type'] = "interwiki-$linktype";
405 $link['link'] = LinkInterWikiLink($URL, $linkname);
407 $link['type'] = "wiki-unknown-$linktype";
408 $link['link'] = LinkUnknownWikiWord($URL, $linkname);
415 function ExtractWikiPageLinks($content)
417 global $WikiNameRegexp;
419 if (is_string($content))
420 $content = explode("\n", $content);
422 $wikilinks = array();
423 foreach ($content as $line) {
424 // remove plugin code
425 $line = preg_replace('/<\?plugin\s+\w.*?\?>/', '', $line);
426 // remove escaped '['
427 $line = str_replace('[[', ' ', $line);
429 // bracket links (only type wiki-* is of interest)
430 $numBracketLinks = preg_match_all("/\[\s*([^\]|]+\|)?\s*(.+?)\s*\]/", $line, $brktlinks);
431 for ($i = 0; $i < $numBracketLinks; $i++) {
432 $link = ParseAndLink($brktlinks[0][$i]);
433 if (preg_match("#^wiki#", $link['type']))
434 $wikilinks[$brktlinks[2][$i]] = 1;
436 $brktlink = preg_quote($brktlinks[0][$i]);
437 $line = preg_replace("|$brktlink|", '', $line);
440 // BumpyText old-style wiki links
441 if (preg_match_all("/!?$WikiNameRegexp/", $line, $link)) {
442 for ($i = 0; isset($link[0][$i]); $i++) {
443 if($link[0][$i][0] <> '!')
444 $wikilinks[$link[0][$i]] = 1;
448 return array_keys($wikilinks);
451 function LinkRelatedPages($dbi, $pagename)
453 // currently not supported everywhere
454 if(!function_exists('GetWikiPageLinks'))
457 //FIXME: fix or toss?
458 $links = GetWikiPageLinks($dbi, $pagename);
460 $txt = QElement('strong',
461 sprintf (gettext ("%d best incoming links:"), NUM_RELATED_PAGES));
462 for($i = 0; $i < NUM_RELATED_PAGES; $i++) {
463 if(isset($links['in'][$i])) {
464 list($name, $score) = $links['in'][$i];
465 $txt .= LinkExistingWikiWord($name) . " ($score), ";
469 $txt .= "\n" . Element('br');
470 $txt .= Element('strong',
471 sprintf (gettext ("%d best outgoing links:"), NUM_RELATED_PAGES));
472 for($i = 0; $i < NUM_RELATED_PAGES; $i++) {
473 if(isset($links['out'][$i])) {
474 list($name, $score) = $links['out'][$i];
475 if($dbi->isWikiPage($name))
476 $txt .= LinkExistingWikiWord($name) . " ($score), ";
480 $txt .= "\n" . Element('br');
481 $txt .= Element('strong',
482 sprintf (gettext ("%d most popular nearby:"), NUM_RELATED_PAGES));
483 for($i = 0; $i < NUM_RELATED_PAGES; $i++) {
484 if(isset($links['popular'][$i])) {
485 list($name, $score) = $links['popular'][$i];
486 $txt .= LinkExistingWikiWord($name) . " ($score), ";
495 * Split WikiWords in page names.
497 * It has been deemed useful to split WikiWords (into "Wiki Words")
498 * in places like page titles. This is rumored to help search engines
501 * @param $page string The page name.
503 * @return string The split name.
505 function split_pagename ($page) {
507 if (preg_match("/\s/", $page))
508 return $page; // Already split --- don't split any more.
510 // FIXME: this algorithm is Anglo-centric.
513 // This mess splits between a lower-case letter followed by either an upper-case
514 // or a numeral; except that it wont split the prefixes 'Mc', 'De', or 'Di' off
516 $RE[] = '/([[:lower:]])((?<!Mc|De|Di)[[:upper:]]|\d)/';
517 // This the single-letter words 'I' and 'A' from any following capitalized words.
518 $RE[] = '/(?: |^)([AI])([[:upper:]])/';
519 // Split numerals from following letters.
520 $RE[] = '/(\d)([[:alpha:]])/';
522 foreach ($RE as $key => $val)
523 $RE[$key] = pcre_fix_posix_classes($val);
526 foreach ($RE as $regexp)
527 $page = preg_replace($regexp, '\\1 \\2', $page);
531 function NoSuchRevision ($page, $version) {
532 $html = Element('p', QElement('strong', gettext("Bad Version"))) . "\n";
533 $html .= QElement('p',
534 sprintf(gettext("I'm sorry. Version %d of %s is not in my database."),
535 $version, $page->getName())) . "\n";
537 include_once('lib/Template.php');
538 echo GeneratePage('MESSAGE', $html, gettext("Bad Version"));
543 // (c-file-style: "gnu")
548 // c-hanging-comment-ender-p: nil
549 // indent-tabs-mode: nil