1 <?php rcs_id('$Id: stdlib.php,v 1.30 2001-02-14 05:22:49 dairiki Exp $');
5 Standard functions for Wiki functionality
7 WikiURL($pagename, $args, $abs)
9 LinkExistingWikiWord($wikiword, $linktext)
10 LinkUnknownWikiWord($wikiword, $linktext)
11 LinkURL($url, $linktext)
13 LinkInterWikiLink($link, $linktext)
14 CookSpaces($pagearray)
15 class Stack (push(), pop(), cnt(), top())
16 SetHTMLOutputMode($newmode, $depth)
17 UpdateRecentChanges($dbi, $pagename, $isnewpage)
18 ParseAndLink($bracketlink)
19 ExtractWikiPageLinks($content)
20 LinkRelatedPages($dbi, $pagename)
21 GeneratePage($template, $content, $name, $hash)
24 function fix_magic_quotes_gpc (&$text)
26 if (get_magic_quotes_gpc()) {
27 $text = stripslashes($text);
33 function get_remote_host () {
34 // Apache won't show REMOTE_HOST unless the admin configured it
35 // properly. We'll be nice and see if it's there.
36 if (getenv('REMOTE_HOST'))
37 return getenv('REMOTE_HOST');
38 $host = getenv('REMOTE_ADDR');
39 if (ENABLE_REVERSE_DNS)
40 return gethostbyaddr($host);
45 function arrays_equal ($a, $b)
47 if (sizeof($a) != sizeof($b))
49 for ($i = 0; $i < sizeof($a); $i++)
56 function DataURL($url) {
57 if (preg_match('@^(\w+:|/)@', $url))
59 return SERVER_URL . DATA_PATH . "/$url";
62 function WikiURL($pagename, $args = '') {
67 while (list ($key, $val) = each($args)) {
68 $enc_args[] = urlencode($key) . '=' . urlencode($val);
70 $args = join('&', $enc_args);
74 $url = rawurlencode($pagename);
79 $url = basename(SCRIPT_NAME) .
80 "?pagename=" . rawurlencode($pagename);
88 function StartTag($tag, $args = '')
93 while (list($key, $val) = each($args))
95 if (is_string($val) || is_numeric($val))
96 $s .= sprintf(' %s="%s"', $key, htmlspecialchars($val));
105 define('NO_END_TAG_PAT',
106 '/^' . join('|', array('area', 'base', 'basefont',
107 'br', 'col', 'frame',
108 'hr', 'image', 'input',
109 'isindex', 'link', 'meta',
112 function Element($tag, $args = '', $content = '')
115 if (!is_array($args))
120 $html = StartTag($tag, $args);
121 if (!preg_match(NO_END_TAG_PAT, $tag))
124 $html .= "</$tag>";//FIXME: newline might not always be desired.
129 function QElement($tag, $args = '', $content = '')
132 return Element($tag, $args, htmlspecialchars($content));
136 return Element($tag, htmlspecialchars($content));
140 function LinkURL($url, $linktext='') {
141 // FIXME: Is this needed (or sufficient?)
142 if(ereg("[<>\"]", $url)) {
143 return "<b><u>BAD URL -- remove all of <, >, "</u></b>";
147 if (empty($linktext))
148 $linktext = QElement('span', array('class' => 'rawurl'), $url);
150 $linktext = htmlspecialchars($linktext);
153 array('href' => $url, 'class' => 'linkurl'),
157 function LinkExistingWikiWord($wikiword, $linktext='') {
158 if (empty($linktext))
159 $linktext = QElement('span', array('class' => 'wikiword'), $wikiword);
161 $linktext = htmlspecialchars($linktext);
163 return Element('a', array('href' => WikiURL($wikiword),
164 'class' => 'wikilink'),
168 function LinkUnknownWikiWord($wikiword, $linktext='') {
169 if (empty($linktext))
170 $linktext = QElement('span', array('class' => 'wikiword'), $wikiword);
172 $linktext = htmlspecialchars($linktext);
174 return Element('span', array('class' => 'wikiunknown'),
175 Element('u', $linktext) .
177 array('href' => WikiURL($wikiword, array('action' => 'edit')),
178 'class' => 'wikiunknown'),
183 function LinkImage($url, $alt='[External Image]') {
184 // FIXME: Is this needed (or sufficient?)
185 // As long as the src in htmlspecialchars()ed I think it's safe.
186 if(ereg('[<>"]', $url)) {
187 return "<b><u>BAD URL -- remove all of <, >, "</u></b>";
189 return Element('img', array('src' => $url, 'alt' => $alt));
193 // converts spaces to tabs
194 function CookSpaces($pagearray) {
195 return preg_replace("/ {3,8}/", "\t", $pagearray);
200 var $items = array();
203 function push($item) {
204 $this->items[$this->size] = $item;
210 if ($this->size == 0) {
211 return false; // stack is empty
214 return $this->items[$this->size];
223 return $this->items[$this->size - 1];
229 // end class definition
232 function MakeWikiForm ($pagename, $args, $class, $button_text = '')
234 $formargs['action'] = USE_PATH_INFO ? WikiURL($pagename) : SCRIPT_NAME;
235 $formargs['method'] = 'post';
236 $formargs['class'] = $class;
241 while (list($key, $val) = each($args))
243 $a = array('name' => $key, 'value' => $val, 'type' => 'hidden');
245 if (preg_match('/^ (\d*) \( (.*) \) ((upload)?) $/xi', $val, $m))
249 $a['size'] = $m[1] ? $m[1] : 30;
254 $formargs['enctype'] = 'multipart/form-data';
255 $contents .= Element('input',
256 array('name' => 'MAX_FILE_SIZE',
257 'value' => MAX_UPLOAD_SIZE,
258 'type' => 'hidden'));
262 $contents .= Element('input', $a);
265 $row = Element('td', $contents);
267 if (!empty($button_text)) {
268 $row .= Element('td', Element('input', array('type' => 'submit',
269 'value' => $button_text)));
272 return Element('form', $formargs,
273 Element('table', array('cellspacing' => 0, 'cellpadding' => 2, 'border' => 0),
274 Element('tr', $row)));
277 function SplitQueryArgs ($query_args = '')
279 $split_args = split('&', $query_args);
281 while (list($key, $val) = each($split_args))
282 if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
283 $args[$m[1]] = $m[2];
287 function LinkPhpwikiURL($url, $text = '') {
292 if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m))
293 return "<b><u>BAD phpwiki: URL</u></b>";
296 $page = urldecode($m[1]);
299 if (!$page && preg_match('/^(diff|edit|links|info|diff)=([^&]+)$/', $qargs, $m))
301 // Convert old style links (to not break diff links in RecentChanges).
302 $page = urldecode($m[2]);
303 $args = array("action" => $m[1]);
307 $args = SplitQueryArgs($qargs);
310 if ($args['action'] == 'browse')
311 unset($args['action']);
313 if (empty($args['action']))
315 else if (IsSafeAction($args['action']))
316 $class = 'wikiaction';
319 // Don't allow administrative links on unlocked pages.
320 // FIXME: Ugh: don't like this...
322 if (($pagehash['flags'] & FLAG_PAGE_LOCKED) == 0)
323 return QElement('u', array('class' => 'wikiunsafe'),
324 gettext('Lock page to enable link'));
326 $class = 'wikiadmin';
329 // FIXME: ug, don't like this
330 if (preg_match('/=\d*\(/', $qargs))
331 return MakeWikiForm($page, $args, $class, $text);
335 $text = htmlspecialchars($text);
337 $text = QElement('span', array('class' => 'rawurl'), $url);
339 return Element('a', array('href' => WikiURL($page, $args),
345 function ParseAndLink($bracketlink) {
346 global $dbi, $AllowedProtocols, $InlineImages;
347 global $InterWikiLinkRegexp;
349 // $bracketlink will start and end with brackets; in between
350 // will be either a page name, a URL or both separated by a pipe.
352 // strip brackets and leading space
353 preg_match("/(\[\s*)(.+?)(\s*\])/", $bracketlink, $match);
354 // match the contents
355 preg_match("/([^|]+)(\|)?([^|]+)?/", $match[2], $matches);
357 if (isset($matches[3])) {
358 // named link of the form "[some link name | http://blippy.com/]"
359 $URL = trim($matches[3]);
360 $linkname = trim($matches[1]);
363 // unnamed link of the form "[http://blippy.com/] or [wiki page]"
364 $URL = trim($matches[1]);
366 $linktype = 'simple';
369 if (IsWikiPage($dbi, $URL)) {
370 $link['type'] = "wiki-$linktype";
371 $link['link'] = LinkExistingWikiWord($URL, $linkname);
372 } elseif (preg_match("#^($AllowedProtocols):#", $URL)) {
373 // if it's an image, embed it; otherwise, it's a regular link
374 if (preg_match("/($InlineImages)$/i", $URL)) {
375 $link['type'] = "image-$linktype";
376 $link['link'] = LinkImage($URL, $linkname);
378 $link['type'] = "url-$linktype";
379 $link['link'] = LinkURL($URL, $linkname);
381 } elseif (preg_match("#^phpwiki:(.*)#", $URL, $match)) {
382 $link['type'] = "url-wiki-$linktype";
383 $link['link'] = LinkPhpwikiURL($URL, $linkname);
384 } elseif (preg_match("#^\d+$#", $URL)) {
385 $link['type'] = "footnote-$linktype";
386 $link['link'] = $URL;
387 } elseif (function_exists('LinkInterWikiLink') &&
388 preg_match("#^$InterWikiLinkRegexp:#", $URL)) {
389 $link['type'] = "interwiki-$linktype";
390 $link['link'] = LinkInterWikiLink($URL, $linkname);
392 $link['type'] = "wiki-unknown-$linktype";
393 $link['link'] = LinkUnknownWikiWord($URL, $linkname);
400 function ExtractWikiPageLinks($content)
402 global $WikiNameRegexp;
404 $wikilinks = array();
405 $numlines = count($content);
406 for($l = 0; $l < $numlines; $l++)
408 // remove escaped '['
409 $line = str_replace('[[', ' ', $content[$l]);
411 // bracket links (only type wiki-* is of interest)
412 $numBracketLinks = preg_match_all("/\[\s*([^\]|]+\|)?\s*(.+?)\s*\]/", $line, $brktlinks);
413 for ($i = 0; $i < $numBracketLinks; $i++) {
414 $link = ParseAndLink($brktlinks[0][$i]);
415 if (preg_match("#^wiki#", $link['type']))
416 $wikilinks[$brktlinks[2][$i]] = 1;
418 $brktlink = preg_quote($brktlinks[0][$i]);
419 $line = preg_replace("|$brktlink|", '', $line);
422 // BumpyText old-style wiki links
423 if (preg_match_all("/!?$WikiNameRegexp/", $line, $link)) {
424 for ($i = 0; isset($link[0][$i]); $i++) {
425 if($link[0][$i][0] <> '!')
426 $wikilinks[$link[0][$i]] = 1;
433 function LinkRelatedPages($dbi, $pagename)
435 // currently not supported everywhere
436 if(!function_exists('GetWikiPageLinks'))
439 $links = GetWikiPageLinks($dbi, $pagename);
442 $txt .= sprintf (gettext ("%d best incoming links:"), NUM_RELATED_PAGES);
444 for($i = 0; $i < NUM_RELATED_PAGES; $i++) {
445 if(isset($links['in'][$i])) {
446 list($name, $score) = $links['in'][$i];
447 $txt .= LinkExistingWikiWord($name) . " ($score), ";
452 $txt .= sprintf (gettext ("%d best outgoing links:"), NUM_RELATED_PAGES);
454 for($i = 0; $i < NUM_RELATED_PAGES; $i++) {
455 if(isset($links['out'][$i])) {
456 list($name, $score) = $links['out'][$i];
457 if(IsWikiPage($dbi, $name))
458 $txt .= LinkExistingWikiWord($name) . " ($score), ";
463 $txt .= sprintf (gettext ("%d most popular nearby:"), NUM_RELATED_PAGES);
465 for($i = 0; $i < NUM_RELATED_PAGES; $i++) {
466 if(isset($links['popular'][$i])) {
467 list($name, $score) = $links['popular'][$i];
468 $txt .= LinkExistingWikiWord($name) . " ($score), ";
476 # GeneratePage() -- takes $content and puts it in the template $template
477 # this function contains all the template logic
479 # $template ... name of the template (see config.php for list of names)
480 # $content ... html content to put into the page
481 # $name ... page title
482 # $hash ... if called while creating a wiki page, $hash points to
483 # the $pagehash array of that wiki page.
485 function GeneratePage($template, $content, $name, $hash)
488 global $datetimeformat, $dbi, $logo, $FieldSeparator;
489 global $user, $pagename;
491 if (!is_array($hash))
494 function _dotoken ($id, $val, &$page) {
495 global $FieldSeparator;
496 $page = str_replace("$FieldSeparator#$id$FieldSeparator#",
500 function _iftoken ($id, $condition, &$page) {
501 global $FieldSeparator;
503 // line based IF directive
504 $lineyes = "$FieldSeparator#IF $id$FieldSeparator#";
505 $lineno = "$FieldSeparator#IF !$id$FieldSeparator#";
506 // block based IF directive
507 $blockyes = "$FieldSeparator#IF:$id$FieldSeparator#";
508 $blockyesend = "$FieldSeparator#ENDIF:$id$FieldSeparator#";
509 $blockno = "$FieldSeparator#IF:!$id$FieldSeparator#";
510 $blocknoend = "$FieldSeparator#ENDIF:!$id$FieldSeparator#";
513 $page = str_replace($lineyes, '', $page);
514 $page = str_replace($blockyes, '', $page);
515 $page = str_replace($blockyesend, '', $page);
516 $page = preg_replace("/$blockno(.*?)$blocknoend/s", '', $page);
517 $page = ereg_replace("${lineno}[^\n]*\n", '', $page);
519 $page = str_replace($lineno, '', $page);
520 $page = str_replace($blockno, '', $page);
521 $page = str_replace($blocknoend, '', $page);
522 $page = preg_replace("/$blockyes(.*?)$blockyesend/s", '', $page);
523 $page = ereg_replace("${lineyes}[^\n]*\n", '', $page);
527 $page = join('', file(SearchPath($templates[$template])));
528 $page = str_replace('###', "$FieldSeparator#", $page);
530 // valid for all pagetypes
531 _iftoken('COPY', isset($hash['copy']), $page);
532 _iftoken('LOCK', (isset($hash['flags']) &&
533 ($hash['flags'] & FLAG_PAGE_LOCKED)), $page);
534 _iftoken('ADMIN', $user->is_admin(), $page);
535 _iftoken('ANONYMOUS', !$user->is_authenticated(), $page);
537 if (empty($hash['minor_edit_checkbox']))
538 $hash['minor_edit_checkbox'] = '';
539 _iftoken('MINOR_EDIT_CHECKBOX', $hash['minor_edit_checkbox'], $page);
541 _dotoken('MINOR_EDIT_CHECKBOX', $hash['minor_edit_checkbox'], $page);
543 _dotoken('USERID', htmlspecialchars($user->id()), $page);
544 _dotoken('PAGE', htmlspecialchars($name), $page);
545 _dotoken('LOGO', htmlspecialchars(DataURL($logo)), $page);
546 _dotoken('CSS_URL', htmlspecialchars(DataURL(CSS_URL)), $page);
548 _dotoken('RCS_IDS', $GLOBALS['RCS_IDS'], $page);
550 $prefs = $user->getPreferences();
551 _dotoken('EDIT_AREA_WIDTH', $prefs['edit_area.width'], $page);
552 _dotoken('EDIT_AREA_HEIGHT', $prefs['edit_area.height'], $page);
554 // FIXME: Clean up this stuff
555 $browse_page = WikiURL($name);
556 _dotoken('BROWSE_PAGE', $browse_page, $page);
557 $arg_sep = strstr($browse_page, '?') ? '&' : '?';
558 _dotoken('ACTION', $browse_page . $arg_sep . "action=", $page);
559 _dotoken('BROWSE', WikiURL(''), $page);
563 SERVER_URL . VIRTUAL_PATH . "/" . WikiURL($pagename), $page);
565 _dotoken('BASE_URL', SERVER_URL . SCRIPT_NAME, $page);
567 // invalid for messages (search results, error messages)
568 if ($template != 'MESSAGE') {
569 _dotoken('PAGEURL', rawurlencode($name), $page);
570 if (!empty($hash['lastmodified']))
571 _dotoken('LASTMODIFIED',
572 date($datetimeformat, $hash['lastmodified']), $page);
573 if (!empty($hash['author']))
574 _dotoken('LASTAUTHOR', $hash['author'], $page);
575 if (!empty($hash['version']))
576 _dotoken('VERSION', $hash['version'], $page);
577 if (strstr($page, "$FieldSeparator#HITS$FieldSeparator#")) {
578 _dotoken('HITS', GetHitCount($dbi, $name), $page);
580 if (strstr($page, "$FieldSeparator#RELATEDPAGES$FieldSeparator#")) {
581 _dotoken('RELATEDPAGES', LinkRelatedPages($dbi, $name), $page);
585 _dotoken('CONTENT', $content, $page);
589 function UpdateRecentChanges($dbi, $pagename, $isnewpage)
593 global $WikiPageStore;
595 $recentchanges = RetrievePage($dbi, gettext ("RecentChanges"), $WikiPageStore);
597 // this shouldn't be necessary, since PhpWiki loads
598 // default pages if this is a new baby Wiki
600 $today = date($dateformat, $now);
602 if (!is_array($recentchanges)) {
603 $recentchanges = array('version' => 1,
605 'lastmodified' => $now - 48 * 4600, // force $isNewDay
606 'flags' => FLAG_PAGE_LOCKED,
607 'author' => $GLOBALS['user']->id());
608 $recentchanges['content']
609 = array(gettext("The most recently changed pages are listed below."),
611 "____$today " . gettext("(first day for this Wiki)"),
613 gettext("Quick title search:"),
614 '[phpwiki:?action=search&searchterm=()]',
617 $recentchanges['lastmodified'] = $now;
619 if (date($dateformat, $recentchanges['lastmodified']) != $today) {
625 $numlines = sizeof($recentchanges['content']);
629 // scroll through the page to the first date and break
630 // dates are marked with "____" at the beginning of the line
631 for ($i = 0; $i < $numlines; $i++) {
632 if (preg_match("/^____/",
633 $recentchanges['content'][$i])) {
636 $newpage[$k++] = $recentchanges['content'][$i];
640 // if it's a new date, insert it
641 $newpage[$k++] = $isNewDay ? "____$today\r"
642 : $recentchanges['content'][$i++];
644 $userid = $user->id();
646 // add the updated page's name to the array
648 $newpage[$k++] = "* [$pagename] (new) ..... $userid\r";
650 $diffurl = "phpwiki:" . rawurlencode($pagename) . "?action=diff";
651 $newpage[$k++] = "* [$pagename] ([diff|$diffurl]) ..... $userid\r";
654 $newpage[$k++] = "\r";
656 // copy the rest of the page into the new array
657 // and skip previous entry for $pagename
658 $pagename = preg_quote($pagename);
659 for (; $i < $numlines; $i++) {
660 if (!preg_match("|\[$pagename\]|", $recentchanges['content'][$i])) {
661 $newpage[$k++] = $recentchanges['content'][$i];
665 $recentchanges['content'] = $newpage;
667 InsertPage($dbi, gettext ("RecentChanges"), $recentchanges);
673 // c-file-style: "ellemtel"