]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/stdlib.php
StartTag(): minor beautification: get rid of extra spaces in start tags.
[SourceForge/phpwiki.git] / lib / stdlib.php
1 <?php rcs_id('$Id: stdlib.php,v 1.36 2001-03-02 00:16:53 dairiki Exp $');
2
3
4    /*
5       Standard functions for Wiki functionality
6          WikiURL($pagename, $args, $abs)
7          
8          LinkExistingWikiWord($wikiword, $linktext) 
9          LinkUnknownWikiWord($wikiword, $linktext) 
10          LinkURL($url, $linktext)
11          LinkImage($url, $alt)
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)
20    */
21
22 function fix_magic_quotes_gpc (&$text)
23 {
24    if (get_magic_quotes_gpc()) {
25       $text = stripslashes($text);
26    }
27    return $text;
28 }
29
30 function arrays_equal ($a, $b) 
31 {
32    if (sizeof($a) != sizeof($b))
33       return false;
34    for ($i = 0; $i < sizeof($a); $i++)
35       if ($a[$i] != $b[$i])
36          return false;
37    return true;
38 }
39
40
41    function DataURL($url) {
42       if (preg_match('@^(\w+:|/)@', $url))
43          return $url;
44       return SERVER_URL . DATA_PATH . "/$url";
45    }
46           
47    function WikiURL($pagename, $args = '') {
48       if (is_array($args))
49       {
50          reset($args);
51          $enc_args = array();
52          while (list ($key, $val) = each($args)) {
53             $enc_args[] = urlencode($key) . '=' . urlencode($val);
54          }
55          $args = join('&', $enc_args);
56       }
57
58       if (USE_PATH_INFO) {
59          $url = rawurlencode($pagename);
60          if ($args)
61             $url .= "?$args";
62       }
63       else {
64          $url = basename(SCRIPT_NAME) .
65              "?pagename=" . rawurlencode($pagename);
66          if ($args)
67             $url .= "&$args";
68       }
69
70       return $url;
71    }
72
73 function StartTag($tag, $args = '')
74 {
75    $s = "<$tag";
76    if (is_array($args))
77    {
78       while (list($key, $val) = each($args))
79       {
80          if (is_string($val) || is_numeric($val))
81             $s .= sprintf(' %s="%s"', $key, htmlspecialchars($val));
82          else if ($val)
83             $s .= " $key";
84       }
85    }
86    return "$s>";
87 }
88
89    
90    define('NO_END_TAG_PAT',
91           '/^' . join('|', array('area', 'base', 'basefont',
92                                  'br', 'col', 'frame',
93                                  'hr', 'image', 'input',
94                                  'isindex', 'link', 'meta',
95                                  'param')) . '$/i');
96
97    function Element($tag, $args = '', $content = '')
98    {
99       $html = "<$tag";
100       if (!is_array($args))
101       {
102          $content = $args;
103          $args = false;
104       }
105       $html = StartTag($tag, $args);
106       if (!preg_match(NO_END_TAG_PAT, $tag))
107       {
108          $html .= $content;
109          $html .= "</$tag>";//FIXME: newline might not always be desired.
110       }
111       return $html;
112    }
113
114    function QElement($tag, $args = '', $content = '')
115    {
116       if (is_array($args))
117          return Element($tag, $args, htmlspecialchars($content));
118       else
119       {
120          $content = $args;
121          return Element($tag, htmlspecialchars($content));
122       }
123    }
124    
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 &lt;, &gt;, &quot;</u></b>";
129       }
130
131
132       if (empty($linktext))
133          $linktext = QElement('span', array('class' => 'rawurl'), $url);
134       else
135          $linktext = htmlspecialchars($linktext);
136
137       return Element('a',
138                      array('href' => $url, 'class' => 'linkurl'),
139                      $linktext);
140    }
141
142    function LinkExistingWikiWord($wikiword, $linktext='') {
143       if (empty($linktext))
144          $linktext = QElement('span', array('class' => 'wikiword'), $wikiword);
145       else
146          $linktext = htmlspecialchars($linktext);
147       
148       return Element('a', array('href' => WikiURL($wikiword),
149                                 'class' => 'wikilink'),
150                      $linktext);
151    }
152
153    function LinkUnknownWikiWord($wikiword, $linktext='') {
154       if (empty($linktext))
155          $linktext = QElement('span', array('class' => 'wikiword'), $wikiword);
156       else
157          $linktext = htmlspecialchars($linktext);
158
159       return Element('span', array('class' => 'wikiunknown'),
160                      Element('u', $linktext) .
161                      QElement('a',
162                               array('href' => WikiURL($wikiword, array('action' => 'edit')),
163                                     'class' => 'wikiunknown'),
164                               '?'));
165    }
166
167
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 &lt;, &gt;, &quot;</u></b>";
173       }
174       return Element('img', array('src' => $url, 'alt' => $alt));
175    }
176
177
178    // converts spaces to tabs
179    function CookSpaces($pagearray) {
180       return preg_replace("/ {3,8}/", "\t", $pagearray);
181    }
182
183
184    class Stack {
185       var $items = array();
186       var $size = 0;
187
188       function push($item) {
189          $this->items[$this->size] = $item;
190          $this->size++;
191          return true;
192       }  
193    
194       function pop() {
195          if ($this->size == 0) {
196             return false; // stack is empty
197          }  
198          $this->size--;
199          return $this->items[$this->size];
200       }  
201    
202       function cnt() {
203          return $this->size;
204       }  
205
206       function top() {
207          if($this->size)
208             return $this->items[$this->size - 1];
209          else
210             return '';
211       }  
212
213    }  
214    // end class definition
215
216
217    function MakeWikiForm ($pagename, $args, $class, $button_text = '')
218    {
219       $formargs['action'] = USE_PATH_INFO ? WikiURL($pagename) : SCRIPT_NAME;
220       $formargs['method'] = 'post';
221       $formargs['class'] = $class;
222       
223       $contents = '';
224       $input_seen = 0;
225       
226       while (list($key, $val) = each($args))
227       {
228          $a = array('name' => $key, 'value' => $val, 'type' => 'hidden');
229          
230          if (preg_match('/^ (\d*) \( (.*) \) ((upload)?) $/xi', $val, $m))
231          {
232             $input_seen++;
233             $a['type'] = 'text';
234             $a['size'] = $m[1] ? $m[1] : 30;
235             $a['value'] = $m[2];
236             if ($m[3])
237             {
238                $a['type'] = 'file';
239                $formargs['enctype'] = 'multipart/form-data';
240                $contents .= Element('input',
241                                     array('name' => 'MAX_FILE_SIZE',
242                                           'value' => MAX_UPLOAD_SIZE,
243                                           'type' => 'hidden'));
244             }
245          }
246
247          $contents .= Element('input', $a);
248       }
249
250       $row = Element('td', $contents);
251       
252       if (!empty($button_text)) {
253          $row .= Element('td', Element('input', array('type' => 'submit',
254                                                       'value' => $button_text)));
255       }
256
257       return Element('form', $formargs,
258                      Element('table', array('cellspacing' => 0, 'cellpadding' => 2, 'border' => 0),
259                              Element('tr', $row)));
260    }
261
262    function SplitQueryArgs ($query_args = '') 
263    {
264       $split_args = split('&', $query_args);
265       $args = array();
266       while (list($key, $val) = each($split_args))
267          if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
268             $args[$m[1]] = $m[2];
269       return $args;
270    }
271    
272    function LinkPhpwikiURL($url, $text = '') {
273       global $pagename;
274       $args = array();
275       $page = $pagename;
276
277       if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m))
278          return "<b><u>BAD phpwiki: URL</u></b>";
279
280       if ($m[1])
281          $page = urldecode($m[1]);
282       $qargs = $m[2];
283       
284       if (!$page && preg_match('/^(diff|edit|links|info|diff)=([^&]+)$/', $qargs, $m))
285       {
286          // Convert old style links (to not break diff links in RecentChanges).
287          $page = urldecode($m[2]);
288          $args = array("action" => $m[1]);
289       }
290       else
291       {
292          $args = SplitQueryArgs($qargs);
293       }
294
295       if (isset($args['action']) && $args['action'] == 'browse')
296          unset($args['action']);
297
298       if (empty($args['action']))
299          $class = 'wikilink';
300       else if (IsSafeAction($args['action']))
301          $class = 'wikiaction';
302       else
303       {
304          // Don't allow administrative links on unlocked pages.
305          // FIXME: Ugh: don't like this...
306          global $pagehash;
307          if (($pagehash['flags'] & FLAG_PAGE_LOCKED) == 0)
308             return QElement('u', array('class' => 'wikiunsafe'),
309                             gettext('Lock page to enable link'));
310
311          $class = 'wikiadmin';
312       }
313       
314       // FIXME: ug, don't like this
315       if (preg_match('/=\d*\(/', $qargs))
316          return MakeWikiForm($page, $args, $class, $text);
317       else
318       {
319          if ($text)
320             $text = htmlspecialchars($text);
321          else
322             $text = QElement('span', array('class' => 'rawurl'), $url);
323                              
324          return Element('a', array('href' => WikiURL($page, $args),
325                                    'class' => $class),
326                         $text);
327       }
328    }
329
330    function ParseAndLink($bracketlink) {
331       global $dbi, $AllowedProtocols, $InlineImages;
332       global $InterWikiLinkRegexp;
333
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.
336
337       // strip brackets and leading space
338       preg_match("/(\[\s*)(.+?)(\s*\])/", $bracketlink, $match);
339       // match the contents 
340       preg_match("/([^|]+)(\|)?([^|]+)?/", $match[2], $matches);
341
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]);
346          $linktype = 'named';
347       } else {
348          // unnamed link of the form "[http://blippy.com/] or [wiki page]"
349          $URL = trim($matches[1]);
350          $linkname = '';
351          $linktype = 'simple';
352       }
353
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);
362          } else {
363             $link['type'] = "url-$linktype";
364             $link['link'] = LinkURL($URL, $linkname);
365          }
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);
376       } else {
377          $link['type'] = "wiki-unknown-$linktype";
378          $link['link'] = LinkUnknownWikiWord($URL, $linkname);
379       }
380
381       return $link;
382    }
383
384
385    function ExtractWikiPageLinks($content)
386    {
387       global $WikiNameRegexp;
388
389       $wikilinks = array();
390       $numlines = count($content);
391       for($l = 0; $l < $numlines; $l++)
392       {
393          // remove escaped '['
394          $line = str_replace('[[', ' ', $content[$l]);
395
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;
402
403             $brktlink = preg_quote($brktlinks[0][$i]);
404             $line = preg_replace("|$brktlink|", '', $line);
405          }
406
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;
412             }
413          }
414       }
415       return $wikilinks;
416    }      
417
418    function LinkRelatedPages($dbi, $pagename)
419    {
420       // currently not supported everywhere
421       if(!function_exists('GetWikiPageLinks'))
422          return '';
423
424       $links = GetWikiPageLinks($dbi, $pagename);
425
426       $txt = "<b>";
427       $txt .= sprintf (gettext ("%d best incoming links:"), NUM_RELATED_PAGES);
428       $txt .= "</b>\n";
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), ";
433          }
434       }
435
436       $txt .= "\n<br><b>";
437       $txt .= sprintf (gettext ("%d best outgoing links:"), NUM_RELATED_PAGES);
438       $txt .= "</b>\n";
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), ";
444          }
445       }
446
447       $txt .= "\n<br><b>";
448       $txt .= sprintf (gettext ("%d most popular nearby:"), NUM_RELATED_PAGES);
449       $txt .= "</b>\n";
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), ";
454          }
455       }
456       
457       return $txt;
458    }
459
460    
461    # GeneratePage() -- takes $content and puts it in the template $template
462    # this function contains all the template logic
463    #
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.
469
470    function GeneratePage($template, $content, $name, $hash)
471    {
472       global $templates;
473       global $datetimeformat, $dbi, $logo, $FieldSeparator;
474       global $user, $pagename;
475       
476       if (!is_array($hash))
477          unset($hash);
478
479       function _dotoken ($id, $val, &$page) {
480          global $FieldSeparator;
481          $page = str_replace("$FieldSeparator#$id$FieldSeparator#",
482                                 $val, $page);
483       }
484
485       function _iftoken ($id, $condition, &$page) {
486          global $FieldSeparator;
487
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#";
496
497          if ($condition) {
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);
503          } else {
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);
509          }
510       }
511
512       $page = join('', file(FindLocalizedFile($templates[$template])));
513       $page = str_replace('###', "$FieldSeparator#", $page);
514
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);
521
522       if (empty($hash['minor_edit_checkbox']))
523           $hash['minor_edit_checkbox'] = '';
524       _iftoken('MINOR_EDIT_CHECKBOX', $hash['minor_edit_checkbox'], $page);
525       
526       _dotoken('MINOR_EDIT_CHECKBOX', $hash['minor_edit_checkbox'], $page);
527
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);
532
533       _dotoken('RCS_IDS', $GLOBALS['RCS_IDS'], $page);
534
535       $prefs = $user->getPreferences();
536       _dotoken('EDIT_AREA_WIDTH', $prefs['edit_area.width'], $page);
537       _dotoken('EDIT_AREA_HEIGHT', $prefs['edit_area.height'], $page);
538
539       // FIXME: Clean up this stuff
540       $browse_page = WikiURL($name);
541       _dotoken('BROWSE_PAGE', $browse_page, $page);
542       $arg_sep = strstr($browse_page, '?') ? '&amp;' : '?';
543       _dotoken('ACTION', $browse_page . $arg_sep . "action=", $page);
544       _dotoken('BROWSE', WikiURL(''), $page);
545
546       if (USE_PATH_INFO)
547          _dotoken('BASE_URL',
548                   SERVER_URL . VIRTUAL_PATH . "/" . WikiURL($pagename), $page);
549       else
550          _dotoken('BASE_URL', SERVER_URL . SCRIPT_NAME, $page);
551
552       if ($GLOBALS['action'] != 'browse')
553          _dotoken('ROBOTS_META',
554                   Element('meta', array('name' => 'robots',
555                                         'content' => 'noindex, nofollow')),
556                   $page);
557       else
558          _dotoken('ROBOTS_META', '', $page);
559       
560       
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);
573          }
574          if (strstr($page, "$FieldSeparator#RELATEDPAGES$FieldSeparator#")) {
575             _dotoken('RELATEDPAGES', LinkRelatedPages($dbi, $name), $page);
576          }
577       }
578
579       _dotoken('CONTENT', $content, $page);
580       return $page;
581    }
582
583 function UpdateRecentChanges($dbi, $pagename, $isnewpage)
584 {
585    global $user;
586    global $dateformat;
587    global $WikiPageStore;
588
589    $recentchanges = RetrievePage($dbi, gettext ("RecentChanges"), $WikiPageStore);
590
591    // this shouldn't be necessary, since PhpWiki loads 
592    // default pages if this is a new baby Wiki
593    $now = time();
594    $today = date($dateformat, $now);
595
596    if (!is_array($recentchanges)) {
597       $recentchanges = array('version' => 1,
598                              'created' => $now,
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."),
604                   '',
605                   "____$today " . gettext("(first day for this Wiki)"),
606                   '',
607                   gettext("Quick title search:"),
608                   '[phpwiki:?action=search&searchterm=()]',
609                   '----');
610    }
611
612    $isNewDay = date($dateformat, $recentchanges['lastmodified']) != $today;
613    $recentchanges['lastmodified'] = $now;
614
615    $numlines = sizeof($recentchanges['content']);
616    $newpage = array();
617    $k = 0;
618
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])) {
624          break;
625       } else {
626          $newpage[$k++] = $recentchanges['content'][$i];
627       }
628    }
629
630    // if it's a new date, insert it
631    $newpage[$k++] = $isNewDay ? "____$today\r"
632                               : $recentchanges['content'][$i++];
633
634    $userid = $user->id();
635
636    // add the updated page's name to the array
637    if($isnewpage) {
638       $newpage[$k++] = "* [$pagename] (new) ..... $userid\r";
639    } else {
640       $diffurl = "phpwiki:" . rawurlencode($pagename) . "?action=diff";
641       $newpage[$k++] = "* [$pagename] ([diff|$diffurl]) ..... $userid\r";
642    }
643    if ($isNewDay)
644       $newpage[$k++] = "\r";
645
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];
652       }
653    }
654
655    $recentchanges['content'] = $newpage;
656
657    InsertPage($dbi, gettext ("RecentChanges"), $recentchanges);
658 }
659
660 // For emacs users
661 // Local Variables:
662 // mode: php
663 // c-file-style: "ellemtel"
664 // End:   
665 ?>