1 <?php rcs_id('$Id: stdlib.php,v 1.51 2001-12-03 23:12:04 carstenklapp 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";
25 // Beginnings of theme support by Carsten Klapp:
28 return SERVER_URL . DATA_PATH . "/templates/$theme/$url";
32 function WikiURL($pagename, $args = '', $get_abs_url = false) {
33 if (is_array($args)) {
35 foreach ($args as $key => $val) {
36 $enc_args[] = urlencode($key) . '=' . urlencode($val);
38 $args = join('&', $enc_args);
42 $url = $get_abs_url ? SERVER_URL . VIRTUAL_PATH . "/" : '';
43 $url .= rawurlencode($pagename);
48 $url = $get_abs_url ? SERVER_URL . SCRIPT_NAME : basename(SCRIPT_NAME);
49 $url .= "?pagename=" . rawurlencode($pagename);
57 define('NO_END_TAG_PAT',
58 '/^' . join('|', array('area', 'base', 'basefont',
61 'isindex', 'link', 'meta',
64 function StartTag($tag, $args = '')
69 while (list($key, $val) = each($args))
71 if (is_string($val) || is_numeric($val))
72 $s .= sprintf(' %s="%s"', $key, htmlspecialchars($val));
74 $s .= " $key=\"$key\"";
81 function Element($tag, $args = '', $content = '')
84 if (!is_array($args)) {
88 $html = StartTag($tag, $args);
89 if (preg_match(NO_END_TAG_PAT, $tag)) {
91 return preg_replace('/>$/', " />", $html);
94 $html .= "</$tag>";//FIXME: newline might not always be desired.
99 function QElement($tag, $args = '', $content = '')
102 return Element($tag, $args, htmlspecialchars($content));
105 return Element($tag, htmlspecialchars($content));
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 <, >, "'));
117 if (empty($linktext)) {
125 if (!defined('USE_LINK_ICONS')) {
127 array('href' => $url, 'class' => $class),
130 //ideally the link image would be specified by a map file
131 //similar to the interwiki.map
132 $linkproto = substr($url, 0, strrpos($url, ":"));
133 if ($linkproto == "mailto") {
134 $linkimg = "/images/mailto.png";
135 } elseif ($linkproto == "http") {
136 $linkimg = "/images/http.png";
137 } elseif ($linkproto == "https") {
138 $linkimg = "/images/https.png";
139 } elseif ($linkproto == "ftp") {
140 $linkimg = "/images/ftp.png";
142 $linkimg = "/images/http.png";
145 array('href' => $url, 'class' => $class),
146 Element('img', array('src' => DATA_PATH . $linkimg, 'alt' => $linkproto)) ." ". $linktext);
150 function LinkWikiWord($wikiword, $linktext='') {
152 if ($dbi->isWikiPage($wikiword))
153 return LinkExistingWikiWord($wikiword, $linktext);
155 return LinkUnknownWikiWord($wikiword, $linktext);
159 function LinkExistingWikiWord($wikiword, $linktext='') {
160 if (empty($linktext)) {
161 $linktext = $wikiword;
162 if (defined("autosplit_wikiwords"))
163 $linktext=split_pagename($linktext);
167 $class = 'named-wiki';
169 return QElement('a', array('href' => WikiURL($wikiword),
174 function LinkUnknownWikiWord($wikiword, $linktext='') {
175 if (empty($linktext)) {
176 $linktext = $wikiword;
177 if (defined("autosplit_wikiwords"))
178 $linktext=split_pagename($linktext);
179 $class = 'wikiunknown';
182 $class = 'named-wikiunknown';
185 return Element('span', array('class' => $class),
187 array('href' => WikiURL($wikiword, array('action' => 'edit'))),
189 . Element('u', $linktext));
192 function LinkImage($url, $alt='[External Image]') {
193 // FIXME: Is this needed (or sufficient?)
194 // As long as the src in htmlspecialchars()ed I think it's safe.
195 if(ereg('[<>"]', $url)) {
196 return Element('strong',
197 QElement('u', array('class' => 'baduri'),
198 'BAD URL -- remove all of <, >, "'));
200 return Element('img', array('src' => $url, 'alt' => $alt));
203 // converts spaces to tabs
204 function CookSpaces($pagearray) {
205 return preg_replace("/ {3,8}/", "\t", $pagearray);
210 var $items = array();
213 function push($item) {
214 $this->items[$this->size] = $item;
220 if ($this->size == 0) {
221 return false; // stack is empty
224 return $this->items[$this->size];
233 return $this->items[$this->size - 1];
239 // end class definition
242 function MakeWikiForm ($pagename, $args, $class, $button_text = '')
244 $formargs['action'] = USE_PATH_INFO ? WikiURL($pagename) : SCRIPT_NAME;
245 $formargs['method'] = 'get';
246 $formargs['class'] = $class;
251 while (list($key, $val) = each($args))
253 $a = array('name' => $key, 'value' => $val, 'type' => 'hidden');
255 if (preg_match('/^ (\d*) \( (.*) \) ((upload)?) $/xi', $val, $m))
259 $a['size'] = $m[1] ? $m[1] : 30;
264 $formargs['enctype'] = 'multipart/form-data';
265 $contents .= Element('input',
266 array('name' => 'MAX_FILE_SIZE',
267 'value' => MAX_UPLOAD_SIZE,
268 'type' => 'hidden'));
269 $formargs['method'] = 'post';
273 $contents .= Element('input', $a);
276 $row = Element('td', $contents);
278 if (!empty($button_text)) {
279 $row .= Element('td', Element('input', array('type' => 'submit',
281 'value' => $button_text)));
284 return Element('form', $formargs,
285 Element('table', array('cellspacing' => 0, 'cellpadding' => 2, 'border' => 0),
286 Element('tr', $row)));
289 function SplitQueryArgs ($query_args = '')
291 $split_args = split('&', $query_args);
293 while (list($key, $val) = each($split_args))
294 if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
295 $args[$m[1]] = $m[2];
299 function LinkPhpwikiURL($url, $text = '') {
302 if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m))
303 return Element('strong',
304 QElement('u', array('class' => 'baduri'),
305 'BAD phpwiki: URL'));
307 $pagename = urldecode($m[1]);
310 if (empty($pagename) && preg_match('/^(diff|edit|links|info)=([^&]+)$/', $qargs, $m)) {
311 // Convert old style links (to not break diff links in RecentChanges).
312 $pagename = urldecode($m[2]);
313 $args = array("action" => $m[1]);
316 $args = SplitQueryArgs($qargs);
319 if (empty($pagename))
320 $pagename = $GLOBALS['pagename'];
322 if (isset($args['action']) && $args['action'] == 'browse')
323 unset($args['action']);
325 if (empty($args['action']))
327 else if (is_safe_action($args['action']))
328 $class = 'wikiaction';
330 if (empty($args['action']) || is_safe_action($args['action']))
331 $class = 'wikiaction';
333 // Don't allow administrative links on unlocked pages.
334 // FIXME: Ugh: don't like this...
336 $page = $dbi->getPage($GLOBALS['pagename']);
337 if (!$page->get('locked'))
338 return QElement('u', array('class' => 'wikiunsafe'),
339 gettext('Lock page to enable link'));
341 $class = 'wikiadmin';
344 // FIXME: ug, don't like this
345 if (preg_match('/=\d*\(/', $qargs))
346 return MakeWikiForm($pagename, $args, $class, $text);
348 $text = htmlspecialchars($text);
350 $text = QElement('span', array('class' => 'rawurl'), $url);
352 return Element('a', array('href' => WikiURL($pagename, $args),
357 function ParseAndLink($bracketlink) {
358 global $dbi, $AllowedProtocols, $InlineImages;
359 global $InterWikiLinkRegexp;
361 // $bracketlink will start and end with brackets; in between
362 // will be either a page name, a URL or both separated by a pipe.
364 // strip brackets and leading space
365 preg_match("/(\[\s*)(.+?)(\s*\])/", $bracketlink, $match);
366 // match the contents
367 preg_match("/([^|]+)(\|)?([^|]+)?/", $match[2], $matches);
369 if (isset($matches[3])) {
370 // named link of the form "[some link name | http://blippy.com/]"
371 $URL = trim($matches[3]);
372 $linkname = trim($matches[1]);
375 // unnamed link of the form "[http://blippy.com/] or [wiki page]"
376 $URL = trim($matches[1]);
378 $linktype = 'simple';
381 if ($dbi->isWikiPage($URL)) {
382 $link['type'] = "wiki-$linktype";
383 $link['link'] = LinkExistingWikiWord($URL, $linkname);
384 } elseif (preg_match("#^($AllowedProtocols):#", $URL)) {
385 // if it's an image, embed it; otherwise, it's a regular link
386 if (preg_match("/($InlineImages)$/i", $URL)) {
387 $link['type'] = "image-$linktype";
388 $link['link'] = LinkImage($URL, $linkname);
390 $link['type'] = "url-$linktype";
391 $link['link'] = LinkURL($URL, $linkname);
394 $link['link'] = LinkURL($URL, $linkname);
398 } elseif (preg_match("#^phpwiki:(.*)#", $URL, $match)) {
399 $link['type'] = "url-wiki-$linktype";
400 $link['link'] = LinkPhpwikiURL($URL, $linkname);
401 } elseif (preg_match("#^\d+$#", $URL)) {
402 $link['type'] = "footnote-$linktype";
403 $link['link'] = $URL;
404 } elseif (function_exists('LinkInterWikiLink') &&
405 preg_match("#^$InterWikiLinkRegexp:#", $URL)) {
406 $link['type'] = "interwiki-$linktype";
407 $link['link'] = LinkInterWikiLink($URL, $linkname);
409 $link['type'] = "wiki-unknown-$linktype";
410 $link['link'] = LinkUnknownWikiWord($URL, $linkname);
417 function ExtractWikiPageLinks($content)
419 global $WikiNameRegexp;
421 if (is_string($content))
422 $content = explode("\n", $content);
424 $wikilinks = array();
425 foreach ($content as $line) {
426 // remove plugin code
427 $line = preg_replace('/<\?plugin\s+\w.*?\?>/', '', $line);
428 // remove escaped '['
429 $line = str_replace('[[', ' ', $line);
431 // bracket links (only type wiki-* is of interest)
432 $numBracketLinks = preg_match_all("/\[\s*([^\]|]+\|)?\s*(.+?)\s*\]/", $line, $brktlinks);
433 for ($i = 0; $i < $numBracketLinks; $i++) {
434 $link = ParseAndLink($brktlinks[0][$i]);
435 if (preg_match("#^wiki#", $link['type']))
436 $wikilinks[$brktlinks[2][$i]] = 1;
438 $brktlink = preg_quote($brktlinks[0][$i]);
439 $line = preg_replace("|$brktlink|", '', $line);
442 // BumpyText old-style wiki links
443 if (preg_match_all("/!?$WikiNameRegexp/", $line, $link)) {
444 for ($i = 0; isset($link[0][$i]); $i++) {
445 if($link[0][$i][0] <> '!')
446 $wikilinks[$link[0][$i]] = 1;
450 return array_keys($wikilinks);
453 function LinkRelatedPages($dbi, $pagename)
455 // currently not supported everywhere
456 if(!function_exists('GetWikiPageLinks'))
459 //FIXME: fix or toss?
460 $links = GetWikiPageLinks($dbi, $pagename);
462 $txt = QElement('strong',
463 sprintf (gettext ("%d best incoming links:"), NUM_RELATED_PAGES));
464 for($i = 0; $i < NUM_RELATED_PAGES; $i++) {
465 if(isset($links['in'][$i])) {
466 list($name, $score) = $links['in'][$i];
467 $txt .= LinkExistingWikiWord($name) . " ($score), ";
471 $txt .= "\n" . Element('br');
472 $txt .= Element('strong',
473 sprintf (gettext ("%d best outgoing links:"), NUM_RELATED_PAGES));
474 for($i = 0; $i < NUM_RELATED_PAGES; $i++) {
475 if(isset($links['out'][$i])) {
476 list($name, $score) = $links['out'][$i];
477 if($dbi->isWikiPage($name))
478 $txt .= LinkExistingWikiWord($name) . " ($score), ";
482 $txt .= "\n" . Element('br');
483 $txt .= Element('strong',
484 sprintf (gettext ("%d most popular nearby:"), NUM_RELATED_PAGES));
485 for($i = 0; $i < NUM_RELATED_PAGES; $i++) {
486 if(isset($links['popular'][$i])) {
487 list($name, $score) = $links['popular'][$i];
488 $txt .= LinkExistingWikiWord($name) . " ($score), ";
497 * Split WikiWords in page names.
499 * It has been deemed useful to split WikiWords (into "Wiki Words")
500 * in places like page titles. This is rumored to help search engines
503 * @param $page string The page name.
505 * @return string The split name.
507 function split_pagename ($page) {
509 if (preg_match("/\s/", $page))
510 return $page; // Already split --- don't split any more.
512 // FIXME: this algorithm is Anglo-centric.
515 // This mess splits between a lower-case letter followed by either an upper-case
516 // or a numeral; except that it wont split the prefixes 'Mc', 'De', or 'Di' off
518 $RE[] = '/([[:lower:]])((?<!Mc|De|Di)[[:upper:]]|\d)/';
519 // This the single-letter words 'I' and 'A' from any following capitalized words.
520 $RE[] = '/(?: |^)([AI])([[:upper:]])/';
521 // Split numerals from following letters.
522 $RE[] = '/(\d)([[:alpha:]])/';
524 foreach ($RE as $key => $val)
525 $RE[$key] = pcre_fix_posix_classes($val);
528 foreach ($RE as $regexp)
529 $page = preg_replace($regexp, '\\1 \\2', $page);
533 function NoSuchRevision ($page, $version) {
534 $html = Element('p', QElement('strong', gettext("Bad Version"))) . "\n";
535 $html .= QElement('p',
536 sprintf(gettext("I'm sorry. Version %d of %s is not in my database."),
537 $version, $page->getName())) . "\n";
539 include_once('lib/Template.php');
540 echo GeneratePage('MESSAGE', $html, gettext("Bad Version"));
545 // (c-file-style: "gnu")
550 // c-hanging-comment-ender-p: nil
551 // indent-tabs-mode: nil