1 <?php rcs_id('$Id: stdlib.php,v 1.45 2001-11-26 06:23:42 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) {
23 if (preg_match('@^(\w+:|/)@', $url))
25 return SERVER_URL . DATA_PATH . "/templates/$theme/$url";
28 function WikiURL($pagename, $args = '', $get_abs_url = false) {
29 if (is_array($args)) {
31 foreach ($args as $key => $val) {
32 $enc_args[] = urlencode($key) . '=' . urlencode($val);
34 $args = join('&', $enc_args);
38 $url = $get_abs_url ? SERVER_URL . VIRTUAL_PATH . "/" : '';
39 $url .= rawurlencode($pagename);
44 $url = $get_abs_url ? SERVER_URL . SCRIPT_NAME : basename(SCRIPT_NAME);
45 $url .= "?pagename=" . rawurlencode($pagename);
53 define('NO_END_TAG_PAT',
54 '/^' . join('|', array('area', 'base', 'basefont',
57 'isindex', 'link', 'meta',
60 function StartTag($tag, $args = '')
65 while (list($key, $val) = each($args))
67 if (is_string($val) || is_numeric($val))
68 $s .= sprintf(' %s="%s"', $key, htmlspecialchars($val));
70 $s .= " $key=\"$key\"";
77 function Element($tag, $args = '', $content = '')
80 if (!is_array($args)) {
84 $html = StartTag($tag, $args);
85 if (preg_match(NO_END_TAG_PAT, $tag)) {
87 return preg_replace('/>$/', " />", $html);
90 $html .= "</$tag>";//FIXME: newline might not always be desired.
95 function QElement($tag, $args = '', $content = '')
98 return Element($tag, $args, htmlspecialchars($content));
101 return Element($tag, htmlspecialchars($content));
105 function LinkURL($url, $linktext='') {
106 // FIXME: Is this needed (or sufficient?)
107 if(ereg("[<>\"]", $url)) {
108 return Element('strong',
109 QElement('u', array('class' => 'baduri'),
110 'BAD URL -- remove all of <, >, "'));
113 if (empty($linktext)) {
122 array('href' => $url, 'class' => $class),
126 function LinkWikiWord($wikiword, $linktext='') {
128 if ($dbi->isWikiPage($wikiword))
129 return LinkExistingWikiWord($wikiword, $linktext);
131 return LinkUnknownWikiWord($wikiword, $linktext);
135 function LinkExistingWikiWord($wikiword, $linktext='') {
136 if (empty($linktext)) {
137 $linktext = $wikiword;
141 $class = 'named-wiki';
143 return QElement('a', array('href' => WikiURL($wikiword),
148 function LinkUnknownWikiWord($wikiword, $linktext='') {
149 if (empty($linktext)) {
150 $linktext = $wikiword;
151 $class = 'wikiunknown';
154 $class = 'named-wikiunknown';
157 return Element('span', array('class' => $class),
159 array('href' => WikiURL($wikiword, array('action' => 'edit'))),
161 . Element('u', $linktext));
164 function LinkImage($url, $alt='[External Image]') {
165 // FIXME: Is this needed (or sufficient?)
166 // As long as the src in htmlspecialchars()ed I think it's safe.
167 if(ereg('[<>"]', $url)) {
168 return Element('strong',
169 QElement('u', array('class' => 'baduri'),
170 'BAD URL -- remove all of <, >, "'));
172 return Element('img', array('src' => $url, 'alt' => $alt));
175 // converts spaces to tabs
176 function CookSpaces($pagearray) {
177 return preg_replace("/ {3,8}/", "\t", $pagearray);
182 var $items = array();
185 function push($item) {
186 $this->items[$this->size] = $item;
192 if ($this->size == 0) {
193 return false; // stack is empty
196 return $this->items[$this->size];
205 return $this->items[$this->size - 1];
211 // end class definition
214 function MakeWikiForm ($pagename, $args, $class, $button_text = '')
216 $formargs['action'] = USE_PATH_INFO ? WikiURL($pagename) : SCRIPT_NAME;
217 $formargs['method'] = 'get';
218 $formargs['class'] = $class;
223 while (list($key, $val) = each($args))
225 $a = array('name' => $key, 'value' => $val, 'type' => 'hidden');
227 if (preg_match('/^ (\d*) \( (.*) \) ((upload)?) $/xi', $val, $m))
231 $a['size'] = $m[1] ? $m[1] : 30;
236 $formargs['enctype'] = 'multipart/form-data';
237 $contents .= Element('input',
238 array('name' => 'MAX_FILE_SIZE',
239 'value' => MAX_UPLOAD_SIZE,
240 'type' => 'hidden'));
241 $formargs['method'] = 'post';
245 $contents .= Element('input', $a);
248 $row = Element('td', $contents);
250 if (!empty($button_text)) {
251 $row .= Element('td', Element('input', array('type' => 'submit',
253 'value' => $button_text)));
256 return Element('form', $formargs,
257 Element('table', array('cellspacing' => 0, 'cellpadding' => 2, 'border' => 0),
258 Element('tr', $row)));
261 function SplitQueryArgs ($query_args = '')
263 $split_args = split('&', $query_args);
265 while (list($key, $val) = each($split_args))
266 if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
267 $args[$m[1]] = $m[2];
271 function LinkPhpwikiURL($url, $text = '') {
274 if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m))
275 return Element('strong',
276 QElement('u', array('class' => 'baduri'),
277 'BAD phpwiki: URL'));
279 $pagename = urldecode($m[1]);
282 if (empty($pagename) && preg_match('/^(diff|edit|links|info)=([^&]+)$/', $qargs, $m)) {
283 // Convert old style links (to not break diff links in RecentChanges).
284 $pagename = urldecode($m[2]);
285 $args = array("action" => $m[1]);
288 $args = SplitQueryArgs($qargs);
291 if (empty($pagename))
292 $pagename = $GLOBALS['pagename'];
294 if (isset($args['action']) && $args['action'] == 'browse')
295 unset($args['action']);
297 if (empty($args['action']))
299 else if (is_safe_action($args['action']))
300 $class = 'wikiaction';
302 if (empty($args['action']) || is_safe_action($args['action']))
303 $class = 'wikiaction';
305 // Don't allow administrative links on unlocked pages.
306 // FIXME: Ugh: don't like this...
308 $page = $dbi->getPage($GLOBALS['pagename']);
309 if (!$page->get('locked'))
310 return QElement('u', array('class' => 'wikiunsafe'),
311 gettext('Lock page to enable link'));
313 $class = 'wikiadmin';
316 // FIXME: ug, don't like this
317 if (preg_match('/=\d*\(/', $qargs))
318 return MakeWikiForm($pagename, $args, $class, $text);
320 $text = htmlspecialchars($text);
322 $text = QElement('span', array('class' => 'rawurl'), $url);
324 return Element('a', array('href' => WikiURL($pagename, $args),
329 function ParseAndLink($bracketlink) {
330 global $dbi, $AllowedProtocols, $InlineImages;
331 global $InterWikiLinkRegexp;
333 // $bracketlink will start and end with brackets; in between
334 // will be either a page name, a URL or both separated by a pipe.
336 // strip brackets and leading space
337 preg_match("/(\[\s*)(.+?)(\s*\])/", $bracketlink, $match);
338 // match the contents
339 preg_match("/([^|]+)(\|)?([^|]+)?/", $match[2], $matches);
341 if (isset($matches[3])) {
342 // named link of the form "[some link name | http://blippy.com/]"
343 $URL = trim($matches[3]);
344 $linkname = trim($matches[1]);
347 // unnamed link of the form "[http://blippy.com/] or [wiki page]"
348 $URL = trim($matches[1]);
350 $linktype = 'simple';
353 if ($dbi->isWikiPage($URL)) {
354 $link['type'] = "wiki-$linktype";
355 $link['link'] = LinkExistingWikiWord($URL, $linkname);
356 } elseif (preg_match("#^($AllowedProtocols):#", $URL)) {
357 // if it's an image, embed it; otherwise, it's a regular link
358 if (preg_match("/($InlineImages)$/i", $URL)) {
359 $link['type'] = "image-$linktype";
360 $link['link'] = LinkImage($URL, $linkname);
362 $link['type'] = "url-$linktype";
363 $link['link'] = LinkURL($URL, $linkname);
365 } elseif (preg_match("#^phpwiki:(.*)#", $URL, $match)) {
366 $link['type'] = "url-wiki-$linktype";
367 $link['link'] = LinkPhpwikiURL($URL, $linkname);
368 } elseif (preg_match("#^\d+$#", $URL)) {
369 $link['type'] = "footnote-$linktype";
370 $link['link'] = $URL;
371 } elseif (function_exists('LinkInterWikiLink') &&
372 preg_match("#^$InterWikiLinkRegexp:#", $URL)) {
373 $link['type'] = "interwiki-$linktype";
374 $link['link'] = LinkInterWikiLink($URL, $linkname);
376 $link['type'] = "wiki-unknown-$linktype";
377 $link['link'] = LinkUnknownWikiWord($URL, $linkname);
384 function ExtractWikiPageLinks($content)
386 global $WikiNameRegexp;
388 if (is_string($content))
389 $content = explode("\n", $content);
391 $wikilinks = array();
392 foreach ($content as $line) {
393 // remove plugin code
394 $line = preg_replace('/<\?plugin\s+\w.*?\?>/', '', $line);
395 // remove escaped '['
396 $line = str_replace('[[', ' ', $line);
398 // bracket links (only type wiki-* is of interest)
399 $numBracketLinks = preg_match_all("/\[\s*([^\]|]+\|)?\s*(.+?)\s*\]/", $line, $brktlinks);
400 for ($i = 0; $i < $numBracketLinks; $i++) {
401 $link = ParseAndLink($brktlinks[0][$i]);
402 if (preg_match("#^wiki#", $link['type']))
403 $wikilinks[$brktlinks[2][$i]] = 1;
405 $brktlink = preg_quote($brktlinks[0][$i]);
406 $line = preg_replace("|$brktlink|", '', $line);
409 // BumpyText old-style wiki links
410 if (preg_match_all("/!?$WikiNameRegexp/", $line, $link)) {
411 for ($i = 0; isset($link[0][$i]); $i++) {
412 if($link[0][$i][0] <> '!')
413 $wikilinks[$link[0][$i]] = 1;
417 return array_keys($wikilinks);
420 function LinkRelatedPages($dbi, $pagename)
422 // currently not supported everywhere
423 if(!function_exists('GetWikiPageLinks'))
426 //FIXME: fix or toss?
427 $links = GetWikiPageLinks($dbi, $pagename);
429 $txt = QElement('strong',
430 sprintf (gettext ("%d best incoming links:"), NUM_RELATED_PAGES));
431 for($i = 0; $i < NUM_RELATED_PAGES; $i++) {
432 if(isset($links['in'][$i])) {
433 list($name, $score) = $links['in'][$i];
434 $txt .= LinkExistingWikiWord($name) . " ($score), ";
438 $txt .= "\n" . Element('br');
439 $txt .= Element('strong',
440 sprintf (gettext ("%d best outgoing links:"), NUM_RELATED_PAGES));
441 for($i = 0; $i < NUM_RELATED_PAGES; $i++) {
442 if(isset($links['out'][$i])) {
443 list($name, $score) = $links['out'][$i];
444 if($dbi->isWikiPage($name))
445 $txt .= LinkExistingWikiWord($name) . " ($score), ";
449 $txt .= "\n" . Element('br');
450 $txt .= Element('strong',
451 sprintf (gettext ("%d most popular nearby:"), NUM_RELATED_PAGES));
452 for($i = 0; $i < NUM_RELATED_PAGES; $i++) {
453 if(isset($links['popular'][$i])) {
454 list($name, $score) = $links['popular'][$i];
455 $txt .= LinkExistingWikiWord($name) . " ($score), ";
464 * Split WikiWords in page names.
466 * It has been deemed useful to split WikiWords (into "Wiki Words")
467 * in places like page titles. This is rumored to help search engines
470 * @param $page string The page name.
472 * @return string The split name.
474 function split_pagename ($page) {
476 if (preg_match("/\s/", $page))
477 return $page; // Already split --- don't split any more.
479 // FIXME: this algorithm is Anglo-centric.
482 // This mess splits between a lower-case letter followed by either an upper-case
483 // or a numeral; except that it wont split the prefixes 'Mc', 'De', or 'Di' off
485 $RE[] = '/([[:lower:]])((?<!Mc|De|Di)[[:upper:]]|\d)/';
486 // This the single-letter words 'I' and 'A' from any following capitalized words.
487 $RE[] = '/(?: |^)([AI])([[:upper:]])/';
488 // Split numerals from following letters.
489 $RE[] = '/(\d)([[:alpha:]])/';
491 foreach ($RE as $key => $val)
492 $RE[$key] = pcre_fix_posix_classes($val);
495 foreach ($RE as $regexp)
496 $page = preg_replace($regexp, '\\1 \\2', $page);
500 function NoSuchRevision ($page, $version) {
501 $html = Element('p', QElement('strong', gettext("Bad Version"))) . "\n";
502 $html .= QElement('p',
503 sprintf(gettext("I'm sorry. Version %d of %s is not in my database."),
504 $version, $page->getName())) . "\n";
506 include_once('lib/Template.php');
507 echo GeneratePage('MESSAGE', $html, gettext("Bad Version"));
512 // (c-file-style: "gnu")
517 // c-hanging-comment-ender-p: nil
518 // indent-tabs-mode: nil