1 <?php rcs_id('$Id: stdlib.php,v 1.47 2001-12-02 01:59:23 joe_edelman 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)) {
126 array('href' => $url, 'class' => $class),
130 function LinkWikiWord($wikiword, $linktext='') {
132 if ($dbi->isWikiPage($wikiword))
133 return LinkExistingWikiWord($wikiword, $linktext);
135 return LinkUnknownWikiWord($wikiword, $linktext);
139 function LinkExistingWikiWord($wikiword, $linktext='') {
140 if (empty($linktext)) {
141 $linktext = $wikiword;
145 $class = 'named-wiki';
147 return QElement('a', array('href' => WikiURL($wikiword),
152 function LinkUnknownWikiWord($wikiword, $linktext='') {
153 if (empty($linktext)) {
154 $linktext = $wikiword;
155 $class = 'wikiunknown';
158 $class = 'named-wikiunknown';
161 return Element('span', array('class' => $class),
163 array('href' => WikiURL($wikiword, array('action' => 'edit'))),
165 . Element('u', $linktext));
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 <, >, "'));
176 return Element('img', array('src' => $url, 'alt' => $alt, 'class' => 'wikiimage'));
179 // converts spaces to tabs
180 function CookSpaces($pagearray) {
181 return preg_replace("/ {3,8}/", "\t", $pagearray);
186 var $items = array();
189 function push($item) {
190 $this->items[$this->size] = $item;
196 if ($this->size == 0) {
197 return false; // stack is empty
200 return $this->items[$this->size];
209 return $this->items[$this->size - 1];
215 // end class definition
218 function MakeWikiForm ($pagename, $args, $class, $button_text = '')
220 $formargs['action'] = USE_PATH_INFO ? WikiURL($pagename) : SCRIPT_NAME;
221 $formargs['method'] = 'get';
222 $formargs['class'] = $class;
227 while (list($key, $val) = each($args))
229 $a = array('name' => $key, 'value' => $val, 'type' => 'hidden');
231 if (preg_match('/^ (\d*) \( (.*) \) ((upload)?) $/xi', $val, $m))
235 $a['size'] = $m[1] ? $m[1] : 30;
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';
249 $contents .= Element('input', $a);
252 $row = Element('td', $contents);
254 if (!empty($button_text)) {
255 $row .= Element('td', Element('input', array('type' => 'submit',
257 'value' => $button_text)));
260 return Element('form', $formargs,
261 Element('table', array('cellspacing' => 0, 'cellpadding' => 2, 'border' => 0),
262 Element('tr', $row)));
265 function SplitQueryArgs ($query_args = '')
267 $split_args = split('&', $query_args);
269 while (list($key, $val) = each($split_args))
270 if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
271 $args[$m[1]] = $m[2];
275 function LinkPhpwikiURL($url, $text = '') {
278 if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m))
279 return Element('strong',
280 QElement('u', array('class' => 'baduri'),
281 'BAD phpwiki: URL'));
283 $pagename = urldecode($m[1]);
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]);
292 $args = SplitQueryArgs($qargs);
295 if (empty($pagename))
296 $pagename = $GLOBALS['pagename'];
298 if (isset($args['action']) && $args['action'] == 'browse')
299 unset($args['action']);
301 if (empty($args['action']))
303 else if (is_safe_action($args['action']))
304 $class = 'wikiaction';
306 if (empty($args['action']) || is_safe_action($args['action']))
307 $class = 'wikiaction';
309 // Don't allow administrative links on unlocked pages.
310 // FIXME: Ugh: don't like this...
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'));
317 $class = 'wikiadmin';
320 // FIXME: ug, don't like this
321 if (preg_match('/=\d*\(/', $qargs))
322 return MakeWikiForm($pagename, $args, $class, $text);
324 $text = htmlspecialchars($text);
326 $text = QElement('span', array('class' => 'rawurl'), $url);
328 return Element('a', array('href' => WikiURL($pagename, $args),
333 function ParseAndLink($bracketlink) {
334 global $dbi, $AllowedProtocols, $InlineImages;
335 global $InterWikiLinkRegexp;
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.
340 // strip brackets and leading space
341 preg_match("/(\[\s*)(.+?)(\s*\])/", $bracketlink, $match);
342 // match the contents
343 preg_match("/([^|]+)(\|)?([^|]+)?/", $match[2], $matches);
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]);
351 // unnamed link of the form "[http://blippy.com/] or [wiki page]"
352 $URL = trim($matches[1]);
354 $linktype = 'simple';
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);
366 $link['type'] = "url-$linktype";
367 $link['link'] = LinkURL($URL, $linkname);
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);
380 $link['type'] = "wiki-unknown-$linktype";
381 $link['link'] = LinkUnknownWikiWord($URL, $linkname);
388 function ExtractWikiPageLinks($content)
390 global $WikiNameRegexp;
392 if (is_string($content))
393 $content = explode("\n", $content);
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);
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;
409 $brktlink = preg_quote($brktlinks[0][$i]);
410 $line = preg_replace("|$brktlink|", '', $line);
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;
421 return array_keys($wikilinks);
424 function LinkRelatedPages($dbi, $pagename)
426 // currently not supported everywhere
427 if(!function_exists('GetWikiPageLinks'))
430 //FIXME: fix or toss?
431 $links = GetWikiPageLinks($dbi, $pagename);
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), ";
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), ";
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), ";
468 * Split WikiWords in page names.
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
474 * @param $page string The page name.
476 * @return string The split name.
478 function split_pagename ($page) {
480 if (preg_match("/\s/", $page))
481 return $page; // Already split --- don't split any more.
483 // FIXME: this algorithm is Anglo-centric.
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
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:]])/';
495 foreach ($RE as $key => $val)
496 $RE[$key] = pcre_fix_posix_classes($val);
499 foreach ($RE as $regexp)
500 $page = preg_replace($regexp, '\\1 \\2', $page);
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";
510 include_once('lib/Template.php');
511 echo GeneratePage('MESSAGE', $html, gettext("Bad Version"));
516 // (c-file-style: "gnu")
521 // c-hanging-comment-ender-p: nil
522 // indent-tabs-mode: nil