1 <?php rcs_id('$Id: stdlib.php,v 1.55 2001-12-06 19:15:05 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 $attr['href'] = $url;
114 if (empty($linktext)) {
116 $attr['class'] = 'rawurl';
119 $attr['class'] = 'namedurl';
121 $linktext = htmlspecialchars($linktext);
123 $linkproto = substr($url, 0, strpos($url, ":"));
124 $ICONS = &$GLOBALS['URL_LINK_ICONS'];
126 $linkimg = isset($ICONS[$linkproto]) ? $ICONS[$linkproto] : $ICONS['*'];
127 if (!empty($linkimg)) {
128 $imgtag = Element('img', array('src' => DataURL($linkimg),
130 'class' => 'linkicon'));
131 $linktext = $imgtag . $linktext;
134 return Element('a', $attr, $linktext);
137 function LinkWikiWord($wikiword, $linktext='') {
139 if ($dbi->isWikiPage($wikiword))
140 return LinkExistingWikiWord($wikiword, $linktext);
142 return LinkUnknownWikiWord($wikiword, $linktext);
146 function LinkExistingWikiWord($wikiword, $linktext='') {
147 if (empty($linktext)) {
148 $linktext = $wikiword;
149 if (defined("autosplit_wikiwords"))
150 $linktext=split_pagename($linktext);
154 $class = 'named-wiki';
156 return QElement('a', array('href' => WikiURL($wikiword),
161 function LinkUnknownWikiWord($wikiword, $linktext='') {
162 if (empty($linktext)) {
163 $linktext = $wikiword;
164 if (defined("autosplit_wikiwords"))
165 $linktext=split_pagename($linktext);
166 $class = 'wikiunknown';
169 $class = 'named-wikiunknown';
172 return Element('span', array('class' => $class),
174 array('href' => WikiURL($wikiword, array('action' => 'edit'))),
176 . Element('u', $linktext));
179 function LinkImage($url, $alt='[External Image]') {
180 // FIXME: Is this needed (or sufficient?)
181 // As long as the src in htmlspecialchars()ed I think it's safe.
182 if(ereg('[<>"]', $url)) {
183 return Element('strong',
184 QElement('u', array('class' => 'baduri'),
185 'BAD URL -- remove all of <, >, "'));
187 return Element('img', array('src' => $url, 'alt' => $alt));
190 // converts spaces to tabs
191 function CookSpaces($pagearray) {
192 return preg_replace("/ {3,8}/", "\t", $pagearray);
197 var $items = array();
200 function push($item) {
201 $this->items[$this->size] = $item;
207 if ($this->size == 0) {
208 return false; // stack is empty
211 return $this->items[$this->size];
220 return $this->items[$this->size - 1];
226 // end class definition
229 function MakeWikiForm ($pagename, $args, $class, $button_text = '')
231 $formargs['action'] = USE_PATH_INFO ? WikiURL($pagename) : SCRIPT_NAME;
232 $formargs['method'] = 'get';
233 $formargs['class'] = $class;
238 while (list($key, $val) = each($args))
240 $a = array('name' => $key, 'value' => $val, 'type' => 'hidden');
242 if (preg_match('/^ (\d*) \( (.*) \) ((upload)?) $/xi', $val, $m))
246 $a['size'] = $m[1] ? $m[1] : 30;
251 $formargs['enctype'] = 'multipart/form-data';
252 $contents .= Element('input',
253 array('name' => 'MAX_FILE_SIZE',
254 'value' => MAX_UPLOAD_SIZE,
255 'type' => 'hidden'));
256 $formargs['method'] = 'post';
260 $contents .= Element('input', $a);
263 $row = Element('td', $contents);
265 if (!empty($button_text)) {
266 $row .= Element('td', Element('input', array('type' => 'submit',
268 'value' => $button_text)));
271 return Element('form', $formargs,
272 Element('table', array('cellspacing' => 0, 'cellpadding' => 2, 'border' => 0),
273 Element('tr', $row)));
276 function SplitQueryArgs ($query_args = '')
278 $split_args = split('&', $query_args);
280 while (list($key, $val) = each($split_args))
281 if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
282 $args[$m[1]] = $m[2];
286 function LinkPhpwikiURL($url, $text = '') {
289 if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m))
290 return Element('strong',
291 QElement('u', array('class' => 'baduri'),
292 'BAD phpwiki: URL'));
294 $pagename = urldecode($m[1]);
297 if (empty($pagename) && preg_match('/^(diff|edit|links|info)=([^&]+)$/', $qargs, $m)) {
298 // Convert old style links (to not break diff links in RecentChanges).
299 $pagename = urldecode($m[2]);
300 $args = array("action" => $m[1]);
303 $args = SplitQueryArgs($qargs);
306 if (empty($pagename))
307 $pagename = $GLOBALS['pagename'];
309 if (isset($args['action']) && $args['action'] == 'browse')
310 unset($args['action']);
312 if (empty($args['action']))
314 else if (is_safe_action($args['action']))
315 $class = 'wikiaction';
317 if (empty($args['action']) || is_safe_action($args['action']))
318 $class = 'wikiaction';
320 // Don't allow administrative links on unlocked pages.
321 // FIXME: Ugh: don't like this...
323 $page = $dbi->getPage($GLOBALS['pagename']);
324 if (!$page->get('locked'))
325 return QElement('u', array('class' => 'wikiunsafe'),
326 gettext('Lock page to enable link'));
328 $class = 'wikiadmin';
331 // FIXME: ug, don't like this
332 if (preg_match('/=\d*\(/', $qargs))
333 return MakeWikiForm($pagename, $args, $class, $text);
335 $text = htmlspecialchars($text);
337 $text = QElement('span', array('class' => 'rawurl'), $url);
339 return Element('a', array('href' => WikiURL($pagename, $args),
344 function ParseAndLink($bracketlink) {
345 global $dbi, $AllowedProtocols, $InlineImages;
346 global $InterWikiLinkRegexp;
348 // $bracketlink will start and end with brackets; in between
349 // will be either a page name, a URL or both separated by a pipe.
351 // strip brackets and leading space
352 preg_match("/(\[\s*)(.+?)(\s*\])/", $bracketlink, $match);
353 // match the contents
354 preg_match("/([^|]+)(\|)?([^|]+)?/", $match[2], $matches);
356 if (isset($matches[3])) {
357 // named link of the form "[some link name | http://blippy.com/]"
358 $URL = trim($matches[3]);
359 $linkname = trim($matches[1]);
362 // unnamed link of the form "[http://blippy.com/] or [wiki page]"
363 $URL = trim($matches[1]);
365 $linktype = 'simple';
368 if ($dbi->isWikiPage($URL)) {
369 $link['type'] = "wiki-$linktype";
370 $link['link'] = LinkExistingWikiWord($URL, $linkname);
371 } elseif (preg_match("#^($AllowedProtocols):#", $URL)) {
372 // if it's an image, embed it; otherwise, it's a regular link
373 if (preg_match("/($InlineImages)$/i", $URL)) {
374 $link['type'] = "image-$linktype";
375 $link['link'] = LinkImage($URL, $linkname);
377 $link['type'] = "url-$linktype";
378 $link['link'] = LinkURL($URL, $linkname);
380 } elseif (preg_match("#^phpwiki:(.*)#", $URL, $match)) {
381 $link['type'] = "url-wiki-$linktype";
382 $link['link'] = LinkPhpwikiURL($URL, $linkname);
383 } elseif (preg_match("#^\d+$#", $URL)) {
384 $link['type'] = "footnote-$linktype";
385 $link['link'] = $URL;
386 } elseif (function_exists('LinkInterWikiLink') &&
387 preg_match("#^$InterWikiLinkRegexp:#", $URL)) {
388 $link['type'] = "interwiki-$linktype";
389 $link['link'] = LinkInterWikiLink($URL, $linkname);
391 $link['type'] = "wiki-unknown-$linktype";
392 $link['link'] = LinkUnknownWikiWord($URL, $linkname);
399 function ExtractWikiPageLinks($content)
401 global $WikiNameRegexp;
403 if (is_string($content))
404 $content = explode("\n", $content);
406 $wikilinks = array();
407 foreach ($content as $line) {
408 // remove plugin code
409 $line = preg_replace('/<\?plugin\s+\w.*?\?>/', '', $line);
410 // remove escaped '['
411 $line = str_replace('[[', ' ', $line);
413 // bracket links (only type wiki-* is of interest)
414 $numBracketLinks = preg_match_all("/\[\s*([^\]|]+\|)?\s*(.+?)\s*\]/", $line, $brktlinks);
415 for ($i = 0; $i < $numBracketLinks; $i++) {
416 $link = ParseAndLink($brktlinks[0][$i]);
417 if (preg_match("#^wiki#", $link['type']))
418 $wikilinks[$brktlinks[2][$i]] = 1;
420 $brktlink = preg_quote($brktlinks[0][$i]);
421 $line = preg_replace("|$brktlink|", '', $line);
424 // BumpyText old-style wiki links
425 if (preg_match_all("/!?$WikiNameRegexp/", $line, $link)) {
426 for ($i = 0; isset($link[0][$i]); $i++) {
427 if($link[0][$i][0] <> '!')
428 $wikilinks[$link[0][$i]] = 1;
432 return array_keys($wikilinks);
435 function LinkRelatedPages($dbi, $pagename)
437 // currently not supported everywhere
438 if(!function_exists('GetWikiPageLinks'))
441 //FIXME: fix or toss?
442 $links = GetWikiPageLinks($dbi, $pagename);
444 $txt = QElement('strong',
445 sprintf (gettext ("%d best incoming links:"), NUM_RELATED_PAGES));
446 for($i = 0; $i < NUM_RELATED_PAGES; $i++) {
447 if(isset($links['in'][$i])) {
448 list($name, $score) = $links['in'][$i];
449 $txt .= LinkExistingWikiWord($name) . " ($score), ";
453 $txt .= "\n" . Element('br');
454 $txt .= Element('strong',
455 sprintf (gettext ("%d best outgoing links:"), NUM_RELATED_PAGES));
456 for($i = 0; $i < NUM_RELATED_PAGES; $i++) {
457 if(isset($links['out'][$i])) {
458 list($name, $score) = $links['out'][$i];
459 if($dbi->isWikiPage($name))
460 $txt .= LinkExistingWikiWord($name) . " ($score), ";
464 $txt .= "\n" . Element('br');
465 $txt .= Element('strong',
466 sprintf (gettext ("%d most popular nearby:"), NUM_RELATED_PAGES));
467 for($i = 0; $i < NUM_RELATED_PAGES; $i++) {
468 if(isset($links['popular'][$i])) {
469 list($name, $score) = $links['popular'][$i];
470 $txt .= LinkExistingWikiWord($name) . " ($score), ";
479 * Split WikiWords in page names.
481 * It has been deemed useful to split WikiWords (into "Wiki Words")
482 * in places like page titles. This is rumored to help search engines
485 * @param $page string The page name.
487 * @return string The split name.
489 function split_pagename ($page) {
491 if (preg_match("/\s/", $page))
492 return $page; // Already split --- don't split any more.
494 // FIXME: this algorithm is Anglo-centric.
497 // This mess splits between a lower-case letter followed by either an upper-case
498 // or a numeral; except that it wont split the prefixes 'Mc', 'De', or 'Di' off
500 $RE[] = '/([[:lower:]])((?<!Mc|De|Di)[[:upper:]]|\d)/';
501 // This the single-letter words 'I' and 'A' from any following capitalized words.
502 $RE[] = '/(?: |^)([AI])([[:upper:]])/';
503 // Split numerals from following letters.
504 $RE[] = '/(\d)([[:alpha:]])/';
506 foreach ($RE as $key => $val)
507 $RE[$key] = pcre_fix_posix_classes($val);
510 foreach ($RE as $regexp)
511 $page = preg_replace($regexp, '\\1 \\2', $page);
515 function NoSuchRevision ($page, $version) {
516 $html = Element('p', QElement('strong', gettext("Bad Version"))) . "\n";
517 $html .= QElement('p',
518 sprintf(gettext("I'm sorry. Version %d of %s is not in my database."),
519 $version, $page->getName())) . "\n";
521 include_once('lib/Template.php');
522 echo GeneratePage('MESSAGE', $html, gettext("Bad Version"));
527 // (c-file-style: "gnu")
532 // c-hanging-comment-ender-p: nil
533 // indent-tabs-mode: nil