1 <?php rcs_id('$Id: stdlib.php,v 1.36 2001-03-02 00:16:53 dairiki Exp $');
5 Standard functions for Wiki functionality
6 WikiURL($pagename, $args, $abs)
8 LinkExistingWikiWord($wikiword, $linktext)
9 LinkUnknownWikiWord($wikiword, $linktext)
10 LinkURL($url, $linktext)
12 LinkInterWikiLink($link, $linktext)
13 CookSpaces($pagearray)
14 class Stack (push(), pop(), cnt(), top())
15 UpdateRecentChanges($dbi, $pagename, $isnewpage)
16 ParseAndLink($bracketlink)
17 ExtractWikiPageLinks($content)
18 LinkRelatedPages($dbi, $pagename)
19 GeneratePage($template, $content, $name, $hash)
22 function fix_magic_quotes_gpc (&$text)
24 if (get_magic_quotes_gpc()) {
25 $text = stripslashes($text);
30 function arrays_equal ($a, $b)
32 if (sizeof($a) != sizeof($b))
34 for ($i = 0; $i < sizeof($a); $i++)
41 function DataURL($url) {
42 if (preg_match('@^(\w+:|/)@', $url))
44 return SERVER_URL . DATA_PATH . "/$url";
47 function WikiURL($pagename, $args = '') {
52 while (list ($key, $val) = each($args)) {
53 $enc_args[] = urlencode($key) . '=' . urlencode($val);
55 $args = join('&', $enc_args);
59 $url = rawurlencode($pagename);
64 $url = basename(SCRIPT_NAME) .
65 "?pagename=" . rawurlencode($pagename);
73 function StartTag($tag, $args = '')
78 while (list($key, $val) = each($args))
80 if (is_string($val) || is_numeric($val))
81 $s .= sprintf(' %s="%s"', $key, htmlspecialchars($val));
90 define('NO_END_TAG_PAT',
91 '/^' . join('|', array('area', 'base', 'basefont',
93 'hr', 'image', 'input',
94 'isindex', 'link', 'meta',
97 function Element($tag, $args = '', $content = '')
100 if (!is_array($args))
105 $html = StartTag($tag, $args);
106 if (!preg_match(NO_END_TAG_PAT, $tag))
109 $html .= "</$tag>";//FIXME: newline might not always be desired.
114 function QElement($tag, $args = '', $content = '')
117 return Element($tag, $args, htmlspecialchars($content));
121 return Element($tag, htmlspecialchars($content));
125 function LinkURL($url, $linktext='') {
126 // FIXME: Is this needed (or sufficient?)
127 if(ereg("[<>\"]", $url)) {
128 return "<b><u>BAD URL -- remove all of <, >, "</u></b>";
132 if (empty($linktext))
133 $linktext = QElement('span', array('class' => 'rawurl'), $url);
135 $linktext = htmlspecialchars($linktext);
138 array('href' => $url, 'class' => 'linkurl'),
142 function LinkExistingWikiWord($wikiword, $linktext='') {
143 if (empty($linktext))
144 $linktext = QElement('span', array('class' => 'wikiword'), $wikiword);
146 $linktext = htmlspecialchars($linktext);
148 return Element('a', array('href' => WikiURL($wikiword),
149 'class' => 'wikilink'),
153 function LinkUnknownWikiWord($wikiword, $linktext='') {
154 if (empty($linktext))
155 $linktext = QElement('span', array('class' => 'wikiword'), $wikiword);
157 $linktext = htmlspecialchars($linktext);
159 return Element('span', array('class' => 'wikiunknown'),
160 Element('u', $linktext) .
162 array('href' => WikiURL($wikiword, array('action' => 'edit')),
163 'class' => 'wikiunknown'),
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 "<b><u>BAD URL -- remove all of <, >, "</u></b>";
174 return Element('img', array('src' => $url, 'alt' => $alt));
178 // converts spaces to tabs
179 function CookSpaces($pagearray) {
180 return preg_replace("/ {3,8}/", "\t", $pagearray);
185 var $items = array();
188 function push($item) {
189 $this->items[$this->size] = $item;
195 if ($this->size == 0) {
196 return false; // stack is empty
199 return $this->items[$this->size];
208 return $this->items[$this->size - 1];
214 // end class definition
217 function MakeWikiForm ($pagename, $args, $class, $button_text = '')
219 $formargs['action'] = USE_PATH_INFO ? WikiURL($pagename) : SCRIPT_NAME;
220 $formargs['method'] = 'post';
221 $formargs['class'] = $class;
226 while (list($key, $val) = each($args))
228 $a = array('name' => $key, 'value' => $val, 'type' => 'hidden');
230 if (preg_match('/^ (\d*) \( (.*) \) ((upload)?) $/xi', $val, $m))
234 $a['size'] = $m[1] ? $m[1] : 30;
239 $formargs['enctype'] = 'multipart/form-data';
240 $contents .= Element('input',
241 array('name' => 'MAX_FILE_SIZE',
242 'value' => MAX_UPLOAD_SIZE,
243 'type' => 'hidden'));
247 $contents .= Element('input', $a);
250 $row = Element('td', $contents);
252 if (!empty($button_text)) {
253 $row .= Element('td', Element('input', array('type' => 'submit',
254 'value' => $button_text)));
257 return Element('form', $formargs,
258 Element('table', array('cellspacing' => 0, 'cellpadding' => 2, 'border' => 0),
259 Element('tr', $row)));
262 function SplitQueryArgs ($query_args = '')
264 $split_args = split('&', $query_args);
266 while (list($key, $val) = each($split_args))
267 if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
268 $args[$m[1]] = $m[2];
272 function LinkPhpwikiURL($url, $text = '') {
277 if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m))
278 return "<b><u>BAD phpwiki: URL</u></b>";
281 $page = urldecode($m[1]);
284 if (!$page && preg_match('/^(diff|edit|links|info|diff)=([^&]+)$/', $qargs, $m))
286 // Convert old style links (to not break diff links in RecentChanges).
287 $page = urldecode($m[2]);
288 $args = array("action" => $m[1]);
292 $args = SplitQueryArgs($qargs);
295 if (isset($args['action']) && $args['action'] == 'browse')
296 unset($args['action']);
298 if (empty($args['action']))
300 else if (IsSafeAction($args['action']))
301 $class = 'wikiaction';
304 // Don't allow administrative links on unlocked pages.
305 // FIXME: Ugh: don't like this...
307 if (($pagehash['flags'] & FLAG_PAGE_LOCKED) == 0)
308 return QElement('u', array('class' => 'wikiunsafe'),
309 gettext('Lock page to enable link'));
311 $class = 'wikiadmin';
314 // FIXME: ug, don't like this
315 if (preg_match('/=\d*\(/', $qargs))
316 return MakeWikiForm($page, $args, $class, $text);
320 $text = htmlspecialchars($text);
322 $text = QElement('span', array('class' => 'rawurl'), $url);
324 return Element('a', array('href' => WikiURL($page, $args),
330 function ParseAndLink($bracketlink) {
331 global $dbi, $AllowedProtocols, $InlineImages;
332 global $InterWikiLinkRegexp;
334 // $bracketlink will start and end with brackets; in between
335 // will be either a page name, a URL or both separated by a pipe.
337 // strip brackets and leading space
338 preg_match("/(\[\s*)(.+?)(\s*\])/", $bracketlink, $match);
339 // match the contents
340 preg_match("/([^|]+)(\|)?([^|]+)?/", $match[2], $matches);
342 if (isset($matches[3])) {
343 // named link of the form "[some link name | http://blippy.com/]"
344 $URL = trim($matches[3]);
345 $linkname = trim($matches[1]);
348 // unnamed link of the form "[http://blippy.com/] or [wiki page]"
349 $URL = trim($matches[1]);
351 $linktype = 'simple';
354 if (IsWikiPage($dbi, $URL)) {
355 $link['type'] = "wiki-$linktype";
356 $link['link'] = LinkExistingWikiWord($URL, $linkname);
357 } elseif (preg_match("#^($AllowedProtocols):#", $URL)) {
358 // if it's an image, embed it; otherwise, it's a regular link
359 if (preg_match("/($InlineImages)$/i", $URL)) {
360 $link['type'] = "image-$linktype";
361 $link['link'] = LinkImage($URL, $linkname);
363 $link['type'] = "url-$linktype";
364 $link['link'] = LinkURL($URL, $linkname);
366 } elseif (preg_match("#^phpwiki:(.*)#", $URL, $match)) {
367 $link['type'] = "url-wiki-$linktype";
368 $link['link'] = LinkPhpwikiURL($URL, $linkname);
369 } elseif (preg_match("#^\d+$#", $URL)) {
370 $link['type'] = "footnote-$linktype";
371 $link['link'] = $URL;
372 } elseif (function_exists('LinkInterWikiLink') &&
373 preg_match("#^$InterWikiLinkRegexp:#", $URL)) {
374 $link['type'] = "interwiki-$linktype";
375 $link['link'] = LinkInterWikiLink($URL, $linkname);
377 $link['type'] = "wiki-unknown-$linktype";
378 $link['link'] = LinkUnknownWikiWord($URL, $linkname);
385 function ExtractWikiPageLinks($content)
387 global $WikiNameRegexp;
389 $wikilinks = array();
390 $numlines = count($content);
391 for($l = 0; $l < $numlines; $l++)
393 // remove escaped '['
394 $line = str_replace('[[', ' ', $content[$l]);
396 // bracket links (only type wiki-* is of interest)
397 $numBracketLinks = preg_match_all("/\[\s*([^\]|]+\|)?\s*(.+?)\s*\]/", $line, $brktlinks);
398 for ($i = 0; $i < $numBracketLinks; $i++) {
399 $link = ParseAndLink($brktlinks[0][$i]);
400 if (preg_match("#^wiki#", $link['type']))
401 $wikilinks[$brktlinks[2][$i]] = 1;
403 $brktlink = preg_quote($brktlinks[0][$i]);
404 $line = preg_replace("|$brktlink|", '', $line);
407 // BumpyText old-style wiki links
408 if (preg_match_all("/!?$WikiNameRegexp/", $line, $link)) {
409 for ($i = 0; isset($link[0][$i]); $i++) {
410 if($link[0][$i][0] <> '!')
411 $wikilinks[$link[0][$i]] = 1;
418 function LinkRelatedPages($dbi, $pagename)
420 // currently not supported everywhere
421 if(!function_exists('GetWikiPageLinks'))
424 $links = GetWikiPageLinks($dbi, $pagename);
427 $txt .= sprintf (gettext ("%d best incoming links:"), NUM_RELATED_PAGES);
429 for($i = 0; $i < NUM_RELATED_PAGES; $i++) {
430 if(isset($links['in'][$i])) {
431 list($name, $score) = $links['in'][$i];
432 $txt .= LinkExistingWikiWord($name) . " ($score), ";
437 $txt .= sprintf (gettext ("%d best outgoing links:"), NUM_RELATED_PAGES);
439 for($i = 0; $i < NUM_RELATED_PAGES; $i++) {
440 if(isset($links['out'][$i])) {
441 list($name, $score) = $links['out'][$i];
442 if(IsWikiPage($dbi, $name))
443 $txt .= LinkExistingWikiWord($name) . " ($score), ";
448 $txt .= sprintf (gettext ("%d most popular nearby:"), NUM_RELATED_PAGES);
450 for($i = 0; $i < NUM_RELATED_PAGES; $i++) {
451 if(isset($links['popular'][$i])) {
452 list($name, $score) = $links['popular'][$i];
453 $txt .= LinkExistingWikiWord($name) . " ($score), ";
461 # GeneratePage() -- takes $content and puts it in the template $template
462 # this function contains all the template logic
464 # $template ... name of the template (see config.php for list of names)
465 # $content ... html content to put into the page
466 # $name ... page title
467 # $hash ... if called while creating a wiki page, $hash points to
468 # the $pagehash array of that wiki page.
470 function GeneratePage($template, $content, $name, $hash)
473 global $datetimeformat, $dbi, $logo, $FieldSeparator;
474 global $user, $pagename;
476 if (!is_array($hash))
479 function _dotoken ($id, $val, &$page) {
480 global $FieldSeparator;
481 $page = str_replace("$FieldSeparator#$id$FieldSeparator#",
485 function _iftoken ($id, $condition, &$page) {
486 global $FieldSeparator;
488 // line based IF directive
489 $lineyes = "$FieldSeparator#IF $id$FieldSeparator#";
490 $lineno = "$FieldSeparator#IF !$id$FieldSeparator#";
491 // block based IF directive
492 $blockyes = "$FieldSeparator#IF:$id$FieldSeparator#";
493 $blockyesend = "$FieldSeparator#ENDIF:$id$FieldSeparator#";
494 $blockno = "$FieldSeparator#IF:!$id$FieldSeparator#";
495 $blocknoend = "$FieldSeparator#ENDIF:!$id$FieldSeparator#";
498 $page = str_replace($lineyes, '', $page);
499 $page = str_replace($blockyes, '', $page);
500 $page = str_replace($blockyesend, '', $page);
501 $page = preg_replace("/$blockno(.*?)$blocknoend/s", '', $page);
502 $page = ereg_replace("${lineno}[^\n]*\n", '', $page);
504 $page = str_replace($lineno, '', $page);
505 $page = str_replace($blockno, '', $page);
506 $page = str_replace($blocknoend, '', $page);
507 $page = preg_replace("/$blockyes(.*?)$blockyesend/s", '', $page);
508 $page = ereg_replace("${lineyes}[^\n]*\n", '', $page);
512 $page = join('', file(FindLocalizedFile($templates[$template])));
513 $page = str_replace('###', "$FieldSeparator#", $page);
515 // valid for all pagetypes
516 _iftoken('COPY', isset($hash['copy']), $page);
517 _iftoken('LOCK', (isset($hash['flags']) &&
518 ($hash['flags'] & FLAG_PAGE_LOCKED)), $page);
519 _iftoken('ADMIN', $user->is_admin(), $page);
520 _iftoken('ANONYMOUS', !$user->is_authenticated(), $page);
522 if (empty($hash['minor_edit_checkbox']))
523 $hash['minor_edit_checkbox'] = '';
524 _iftoken('MINOR_EDIT_CHECKBOX', $hash['minor_edit_checkbox'], $page);
526 _dotoken('MINOR_EDIT_CHECKBOX', $hash['minor_edit_checkbox'], $page);
528 _dotoken('USERID', htmlspecialchars($user->id()), $page);
529 _dotoken('PAGE', htmlspecialchars($name), $page);
530 _dotoken('LOGO', htmlspecialchars(DataURL($logo)), $page);
531 _dotoken('CSS_URL', htmlspecialchars(DataURL(CSS_URL)), $page);
533 _dotoken('RCS_IDS', $GLOBALS['RCS_IDS'], $page);
535 $prefs = $user->getPreferences();
536 _dotoken('EDIT_AREA_WIDTH', $prefs['edit_area.width'], $page);
537 _dotoken('EDIT_AREA_HEIGHT', $prefs['edit_area.height'], $page);
539 // FIXME: Clean up this stuff
540 $browse_page = WikiURL($name);
541 _dotoken('BROWSE_PAGE', $browse_page, $page);
542 $arg_sep = strstr($browse_page, '?') ? '&' : '?';
543 _dotoken('ACTION', $browse_page . $arg_sep . "action=", $page);
544 _dotoken('BROWSE', WikiURL(''), $page);
548 SERVER_URL . VIRTUAL_PATH . "/" . WikiURL($pagename), $page);
550 _dotoken('BASE_URL', SERVER_URL . SCRIPT_NAME, $page);
552 if ($GLOBALS['action'] != 'browse')
553 _dotoken('ROBOTS_META',
554 Element('meta', array('name' => 'robots',
555 'content' => 'noindex, nofollow')),
558 _dotoken('ROBOTS_META', '', $page);
561 // invalid for messages (search results, error messages)
562 if ($template != 'MESSAGE') {
563 _dotoken('PAGEURL', rawurlencode($name), $page);
564 if (!empty($hash['lastmodified']))
565 _dotoken('LASTMODIFIED',
566 date($datetimeformat, $hash['lastmodified']), $page);
567 if (!empty($hash['author']))
568 _dotoken('LASTAUTHOR', $hash['author'], $page);
569 if (!empty($hash['version']))
570 _dotoken('VERSION', $hash['version'], $page);
571 if (strstr($page, "$FieldSeparator#HITS$FieldSeparator#")) {
572 _dotoken('HITS', GetHitCount($dbi, $name), $page);
574 if (strstr($page, "$FieldSeparator#RELATEDPAGES$FieldSeparator#")) {
575 _dotoken('RELATEDPAGES', LinkRelatedPages($dbi, $name), $page);
579 _dotoken('CONTENT', $content, $page);
583 function UpdateRecentChanges($dbi, $pagename, $isnewpage)
587 global $WikiPageStore;
589 $recentchanges = RetrievePage($dbi, gettext ("RecentChanges"), $WikiPageStore);
591 // this shouldn't be necessary, since PhpWiki loads
592 // default pages if this is a new baby Wiki
594 $today = date($dateformat, $now);
596 if (!is_array($recentchanges)) {
597 $recentchanges = array('version' => 1,
599 'lastmodified' => $now - 48 * 4600, // force $isNewDay
600 'flags' => FLAG_PAGE_LOCKED,
601 'author' => $GLOBALS['user']->id());
602 $recentchanges['content']
603 = array(gettext("The most recently changed pages are listed below."),
605 "____$today " . gettext("(first day for this Wiki)"),
607 gettext("Quick title search:"),
608 '[phpwiki:?action=search&searchterm=()]',
612 $isNewDay = date($dateformat, $recentchanges['lastmodified']) != $today;
613 $recentchanges['lastmodified'] = $now;
615 $numlines = sizeof($recentchanges['content']);
619 // scroll through the page to the first date and break
620 // dates are marked with "____" at the beginning of the line
621 for ($i = 0; $i < $numlines; $i++) {
622 if (preg_match("/^____/",
623 $recentchanges['content'][$i])) {
626 $newpage[$k++] = $recentchanges['content'][$i];
630 // if it's a new date, insert it
631 $newpage[$k++] = $isNewDay ? "____$today\r"
632 : $recentchanges['content'][$i++];
634 $userid = $user->id();
636 // add the updated page's name to the array
638 $newpage[$k++] = "* [$pagename] (new) ..... $userid\r";
640 $diffurl = "phpwiki:" . rawurlencode($pagename) . "?action=diff";
641 $newpage[$k++] = "* [$pagename] ([diff|$diffurl]) ..... $userid\r";
644 $newpage[$k++] = "\r";
646 // copy the rest of the page into the new array
647 // and skip previous entry for $pagename
648 $pagename = preg_quote($pagename);
649 for (; $i < $numlines; $i++) {
650 if (!preg_match("|\[$pagename\]|", $recentchanges['content'][$i])) {
651 $newpage[$k++] = $recentchanges['content'][$i];
655 $recentchanges['content'] = $newpage;
657 InsertPage($dbi, gettext ("RecentChanges"), $recentchanges);
663 // c-file-style: "ellemtel"