]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/WikiTheme.php
Put flipAll Javascript function in wikicommon.js
[SourceForge/phpwiki.git] / lib / WikiTheme.php
1 <?php rcs_id('$Id$');
2 /* Copyright (C) 2002,2004,2005,2006,2008,2009 $ThePhpWikiProgrammingTeam
3  *
4  * This file is part of PhpWiki.
5  * 
6  * PhpWiki is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  * 
11  * PhpWiki is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  * 
16  * You should have received a copy of the GNU General Public License
17  * along with PhpWiki; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  */
20
21 /**
22  * Customize output by themes: templates, css, special links functions, 
23  * and more formatting.
24  */
25
26 require_once(dirname(__FILE__).'/HtmlElement.php');
27
28 /**
29  * Make a link to a wiki page (in this wiki).
30  *
31  * This is a convenience function.
32  *
33  * @param mixed $page_or_rev
34  * Can be:<dl>
35  * <dt>A string</dt><dd>The page to link to.</dd>
36  * <dt>A WikiDB_Page object</dt><dd>The page to link to.</dd>
37  * <dt>A WikiDB_PageRevision object</dt><dd>A specific version of the page to link to.</dd>
38  * </dl>
39  *
40  * @param string $type
41  * One of:<dl>
42  * <dt>'unknown'</dt><dd>Make link appropriate for a non-existant page.</dd>
43  * <dt>'known'</dt><dd>Make link appropriate for an existing page.</dd>
44  * <dt>'auto'</dt><dd>Either 'unknown' or 'known' as appropriate.</dd>
45  * <dt>'button'</dt><dd>Make a button-style link.</dd>
46  * <dt>'if_known'</dt><dd>Only linkify if page exists.</dd>
47  * </dl>
48  * Unless $type of of the latter form, the link will be of class 'wiki', 'wikiunknown',
49  * 'named-wiki', or 'named-wikiunknown', as appropriate.
50  *
51  * @param mixed $label (string or XmlContent object)
52  * Label for the link.  If not given, defaults to the page name.
53  *
54  * @return XmlContent The link
55  */
56 function WikiLink ($page_or_rev, $type = 'known', $label = false) {
57     global $WikiTheme, $request;
58
59     if ($type == 'button') {
60         return $WikiTheme->makeLinkButton($page_or_rev, $label);
61     }
62
63     $version = false;
64     
65     if (isa($page_or_rev, 'WikiDB_PageRevision')) {
66         $version = $page_or_rev->getVersion();
67         if ($page_or_rev->isCurrent())
68             $version = false;
69         $page = $page_or_rev->getPage();
70         $pagename = $page->getName();
71         $wikipage = $pagename;
72         $exists = true;
73     }
74     elseif (isa($page_or_rev, 'WikiDB_Page')) {
75         $page = $page_or_rev;
76         $pagename = $page->getName();
77         $wikipage = $pagename;
78     }
79     elseif (isa($page_or_rev, 'WikiPageName')) {
80         $wikipage = $page_or_rev;
81         $pagename = $wikipage->name;
82         if (!$wikipage->isValid('strict'))
83             return $WikiTheme->linkBadWikiWord($wikipage, $label);
84     }
85     else {
86         $wikipage = new WikiPageName($page_or_rev, $request->getPage());
87         $pagename = $wikipage->name;
88         if (!$wikipage->isValid('strict'))
89             return $WikiTheme->linkBadWikiWord($wikipage, $label);
90     }
91     
92     if ($type == 'auto' or $type == 'if_known') {
93         if (isset($page)) {
94             $exists = $page->exists();
95         }
96         else {
97             $dbi =& $request->_dbi;
98             $exists = $dbi->isWikiPage($wikipage->name);
99         }
100     }
101     elseif ($type == 'unknown') {
102         $exists = false;
103     }
104     else {
105         $exists = true;
106     }
107
108     // FIXME: this should be somewhere else, if really needed.
109     // WikiLink makes A link, not a string of fancy ones.
110     // (I think that the fancy split links are just confusing.)
111     // Todo: test external ImageLinks http://some/images/next.gif
112     if (isa($wikipage, 'WikiPageName') and 
113         ! $label and 
114         strchr(substr($wikipage->shortName,1), SUBPAGE_SEPARATOR))
115     {
116         $parts = explode(SUBPAGE_SEPARATOR, $wikipage->shortName);
117         $last_part = array_pop($parts);
118         $sep = '';
119         $link = HTML::span();
120         foreach ($parts as $part) {
121             $path[] = $part;
122             $parent = join(SUBPAGE_SEPARATOR, $path);
123             if ($WikiTheme->_autosplitWikiWords)
124                 $part = " " . $part;
125             if ($part)
126                 $link->pushContent($WikiTheme->linkExistingWikiWord($parent, $sep . $part));
127             $sep = $WikiTheme->_autosplitWikiWords 
128                    ? ' ' . SUBPAGE_SEPARATOR : SUBPAGE_SEPARATOR;
129         }
130         if ($exists)
131             $link->pushContent($WikiTheme->linkExistingWikiWord($wikipage, $sep . $last_part, 
132                                                                 $version));
133         else
134             $link->pushContent($WikiTheme->linkUnknownWikiWord($wikipage, $sep . $last_part));
135         return $link;
136     }
137
138     if ($exists) {
139         return $WikiTheme->linkExistingWikiWord($wikipage, $label, $version);
140     }
141     elseif ($type == 'if_known') {
142         if (!$label && isa($wikipage, 'WikiPageName'))
143             $label = $wikipage->shortName;
144         return HTML($label ? $label : $pagename);
145     }
146     else {
147         return $WikiTheme->linkUnknownWikiWord($wikipage, $label);
148     }
149 }
150
151
152
153 /**
154  * Make a button.
155  *
156  * This is a convenience function.
157  *
158  * @param $action string
159  * One of <dl>
160  * <dt>[action]</dt><dd>Perform action (e.g. 'edit') on the selected page.</dd>
161  * <dt>[ActionPage]</dt><dd>Run the actionpage (e.g. 'BackLinks') on the selected page.</dd>
162  * <dt>'submit:'[name]</dt><dd>Make a form submission button with the given name.
163  *      ([name] can be blank for a nameless submit button.)</dd>
164  * <dt>a hash</dt><dd>Query args for the action. E.g.<pre>
165  *      array('action' => 'diff', 'previous' => 'author')
166  * </pre></dd>
167  * </dl>
168  *
169  * @param $label string
170  * A label for the button.  If ommited, a suitable default (based on the valued of $action)
171  * will be picked.
172  *
173  * @param $page_or_rev mixed
174  * Which page (& version) to perform the action on.
175  * Can be one of:<dl>
176  * <dt>A string</dt><dd>The pagename.</dd>
177  * <dt>A WikiDB_Page object</dt><dd>The page.</dd>
178  * <dt>A WikiDB_PageRevision object</dt><dd>A specific version of the page.</dd>
179  * </dl>
180  * ($Page_or_rev is ignored for submit buttons.)
181  */
182 function Button ($action, $label = false, $page_or_rev = false, $options = false) {
183     global $WikiTheme;
184
185     if (!is_array($action) && preg_match('/^submit:(.*)/', $action, $m))
186         return $WikiTheme->makeSubmitButton($label, $m[1], $page_or_rev, $options);
187     else
188         return $WikiTheme->makeActionButton($action, $label, $page_or_rev, $options);
189 }
190
191 class WikiTheme {
192     var $HTML_DUMP_SUFFIX = '';
193     var $DUMP_MODE = false, $dumped_images, $dumped_css; 
194
195     /**
196      * noinit: Do not initialize unnecessary items in default_theme fallback twice.
197      */
198     function WikiTheme ($theme_name = 'default', $noinit = false) {
199         $this->_name = $theme_name;
200         $this->_themes_dir = NormalizeLocalFileName("themes");
201         $this->_path  = defined('PHPWIKI_DIR') ? NormalizeLocalFileName("") : "";
202         $this->_theme = "themes/$theme_name";
203         $this->_parents = array();
204
205         if ($theme_name != 'default') {
206             $parent = $this;
207             /* derived classes should search all parent classes */
208             while ($parent = get_parent_class($parent)) {
209                 if (strtolower($parent) == 'wikitheme') {
210                     $this->_default_theme = new WikiTheme('default', true);
211                     $this->_parents[] = $this->_default_theme;
212                 } elseif ($parent) {
213                     $this->_parents[] = new WikiTheme
214                       (preg_replace("/^WikiTheme_/i", "", $parent), true);
215                 }
216             }
217         }
218         if ($noinit) return;
219
220         $this->addMoreHeaders(JavaScript('',array('src' => $this->_findData("wikicommon.js"))));
221         $script_url = deduce_script_name();
222         if ((DEBUG & _DEBUG_REMOTE) and isset($_GET['start_debug']))
223             $script_url .= ("?start_debug=".$_GET['start_debug']);
224         $pagename = $GLOBALS['request']->getArg('pagename');
225         $this->addMoreHeaders
226             (JavaScript
227              ("var data_path = '". javascript_quote_string(DATA_PATH) ."';\n"
228               ."var pagename  = '". javascript_quote_string($pagename) ."';\n"
229               ."var script_url= '". javascript_quote_string($script_url) ."';\n"
230               ."var stylepath = '". javascript_quote_string(DATA_PATH) . '/'.$this->_theme."/';\n"));
231         // by pixels
232         if ((is_object($GLOBALS['request']) // guard against unittests
233              and $GLOBALS['request']->getPref('doubleClickEdit'))
234             or ENABLE_DOUBLECLICKEDIT)
235             $this->initDoubleClickEdit();
236
237         // will be replaced by acDropDown
238         if (ENABLE_LIVESEARCH) { // by bitflux.ch
239             $this->initLiveSearch();
240         }
241         // replaces external LiveSearch
242         if (defined("ENABLE_ACDROPDOWN") and ENABLE_ACDROPDOWN) { 
243             $this->initMoAcDropDown();
244         }
245         $this->_css = array();
246     }
247
248     function file ($file) {
249         return $this->_path . "$this->_theme/$file";
250    } 
251
252     function _findFile ($file, $missing_okay = false) {
253         if (file_exists($this->file($file)))
254             return "$this->_theme/$file";
255
256         // FIXME: this is a short-term hack.  Delete this after all files
257         // get moved into themes/...
258         // Needed for button paths in parent themes
259         if (file_exists($this->_path . $file))
260             return $file;
261
262         /* Derived classes should search all parent classes */
263         foreach ($this->_parents as $parent) {
264             $path = $parent->_findFile($file, 1);
265             if ($path) {
266                 return $path;
267             } elseif (0 and DEBUG & (_DEBUG_VERBOSE + _DEBUG_REMOTE)) {
268                 trigger_error("$parent->_theme/$file: not found", E_USER_NOTICE);
269             }
270         }
271         if (isset($this->_default_theme)) {
272             return $this->_default_theme->_findFile($file, $missing_okay);
273         }
274         else if (!$missing_okay) {
275             trigger_error("$this->_theme/$file: not found", E_USER_NOTICE);
276             if ((DEBUG & _DEBUG_TRACE) && function_exists('debug_backtrace')) { // >= 4.3.0
277                 echo "<pre>", printSimpleTrace(debug_backtrace()), "</pre>\n";
278             }
279         }
280         return false;
281     }
282
283     function _findData ($file, $missing_okay = false) {
284         if (!string_starts_with($file, "themes")) { // common case
285             $path = $this->_findFile($file, $missing_okay);
286         } else {
287             // _findButton only
288             if (file_exists($file)) {
289                 $path = $file;
290             } elseif (defined('DATA_PATH') 
291                       and file_exists(DATA_PATH . "/$file")) {
292                 $path = $file;
293             } else { // fallback for buttons in parent themes
294                 $path = $this->_findFile($file, $missing_okay);
295             }
296         }
297         if (!$path)
298             return false;
299
300         if (defined('DATA_PATH'))
301             return DATA_PATH . "/$path";
302         return $path;
303     }
304
305     ////////////////////////////////////////////////////////////////
306     //
307     // Date and Time formatting
308     //
309     ////////////////////////////////////////////////////////////////
310
311     // Note:  Windows' implemetation of strftime does not include certain
312         // format specifiers, such as %e (for date without leading zeros).  In
313         // general, see:
314         // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vclib/html/_crt_strftime.2c_.wcsftime.asp
315         // As a result, we have to use %d, and strip out leading zeros ourselves.
316
317     var $_dateFormat = "%B %d, %Y";
318     var $_timeFormat = "%I:%M %p";
319
320     var $_showModTime = true;
321
322     /**
323      * Set format string used for dates.
324      *
325      * @param $fs string Format string for dates.
326      *
327      * @param $show_mod_time bool If true (default) then times
328      * are included in the messages generated by getLastModifiedMessage(),
329      * otherwise, only the date of last modification will be shown.
330      */
331     function setDateFormat ($fs, $show_mod_time = true) {
332         $this->_dateFormat = $fs;
333         $this->_showModTime = $show_mod_time;
334     }
335
336     /**
337      * Set format string used for times.
338      *
339      * @param $fs string Format string for times.
340      */
341     function setTimeFormat ($fs) {
342         $this->_timeFormat = $fs;
343     }
344
345     /**
346      * Format a date.
347      *
348      * Any time zone offset specified in the users preferences is
349      * taken into account by this method.
350      *
351      * @param $time_t integer Unix-style time.
352      *
353      * @return string The date.
354      */
355     function formatDate ($time_t) {
356         global $request;
357         
358         $offset_time = $time_t + 3600 * $request->getPref('timeOffset');
359         // strip leading zeros from date elements (ie space followed by zero)
360         return preg_replace('/ 0/', ' ', 
361                             strftime($this->_dateFormat, $offset_time));
362     }
363
364     /**
365      * Format a date.
366      *
367      * Any time zone offset specified in the users preferences is
368      * taken into account by this method.
369      *
370      * @param $time_t integer Unix-style time.
371      *
372      * @return string The time.
373      */
374     function formatTime ($time_t) {
375         //FIXME: make 24-hour mode configurable?
376         global $request;
377         $offset_time = $time_t + 3600 * $request->getPref('timeOffset');
378         return preg_replace('/^0/', ' ',
379                             strtolower(strftime($this->_timeFormat, $offset_time)));
380     }
381
382     /**
383      * Format a date and time.
384      *
385      * Any time zone offset specified in the users preferences is
386      * taken into account by this method.
387      *
388      * @param $time_t integer Unix-style time.
389      *
390      * @return string The date and time.
391      */
392     function formatDateTime ($time_t) {
393         return $this->formatDate($time_t) . ' ' . $this->formatTime($time_t);
394     }
395
396     /**
397      * Format a (possibly relative) date.
398      *
399      * If enabled in the users preferences, this method might
400      * return a relative day (e.g. 'Today', 'Yesterday').
401      *
402      * Any time zone offset specified in the users preferences is
403      * taken into account by this method.
404      *
405      * @param $time_t integer Unix-style time.
406      *
407      * @return string The day.
408      */
409     function getDay ($time_t) {
410         global $request;
411         
412         if ($request->getPref('relativeDates') && ($date = $this->_relativeDay($time_t))) {
413             return ucfirst($date);
414         }
415         return $this->formatDate($time_t);
416     }
417     
418     /**
419      * Format the "last modified" message for a page revision.
420      *
421      * @param $revision object A WikiDB_PageRevision object.
422      *
423      * @param $show_version bool Should the page version number
424      * be included in the message.  (If this argument is omitted,
425      * then the version number will be shown only iff the revision
426      * is not the current one.
427      *
428      * @return string The "last modified" message.
429      */
430     function getLastModifiedMessage ($revision, $show_version = 'auto') {
431         global $request;
432         if (!$revision) return '';
433         
434         // dates >= this are considered invalid.
435         if (! defined('EPOCH'))
436             define('EPOCH', 0); // seconds since ~ January 1 1970
437         
438         $mtime = $revision->get('mtime');
439         if ($mtime <= EPOCH)
440             return fmt("Never edited");
441
442         if ($show_version == 'auto')
443             $show_version = !$revision->isCurrent();
444
445         if ($request->getPref('relativeDates') && ($date = $this->_relativeDay($mtime))) {
446             if ($this->_showModTime)
447                 $date =  sprintf(_("%s at %s"),
448                                  $date, $this->formatTime($mtime));
449             
450             if ($show_version)
451                 return fmt("Version %s, saved %s", $revision->getVersion(), $date);
452             else
453                 return fmt("Last edited %s", $date);
454         }
455
456         if ($this->_showModTime)
457             $date = $this->formatDateTime($mtime);
458         else
459             $date = $this->formatDate($mtime);
460         
461         if ($show_version)
462             return fmt("Version %s, saved on %s", $revision->getVersion(), $date);
463         else
464             return fmt("Last edited on %s", $date);
465     }
466     
467     function _relativeDay ($time_t) {
468         global $request;
469         
470         if (is_numeric($request->getPref('timeOffset')))
471           $offset = 3600 * $request->getPref('timeOffset');
472         else 
473           $offset = 0;          
474
475         $now = time() + $offset;
476         $today = localtime($now, true);
477         $time = localtime($time_t + $offset, true);
478
479         if ($time['tm_yday'] == $today['tm_yday'] && $time['tm_year'] == $today['tm_year'])
480             return _("today");
481         
482         // Note that due to daylight savings chages (and leap seconds), $now minus
483         // 24 hours is not guaranteed to be yesterday.
484         $yesterday = localtime($now - (12 + $today['tm_hour']) * 3600, true);
485         if ($time['tm_yday'] == $yesterday['tm_yday'] 
486             and $time['tm_year'] == $yesterday['tm_year'])
487             return _("yesterday");
488
489         return false;
490     }
491
492     /**
493      * Format the "Author" and "Owner" messages for a page revision.
494      */
495     function getOwnerMessage ($page) {
496         if (!ENABLE_PAGEPERM or !class_exists("PagePermission"))
497             return '';
498         $dbi =& $GLOBALS['request']->_dbi;
499         $owner = $page->getOwner();
500         if ($owner) {
501             /*
502             if ( mayAccessPage('change',$page->getName()) )
503                 return fmt("Owner: %s", $this->makeActionButton(array('action'=>_("chown"),
504                                                                       's' => $page->getName()),
505                                                                 $owner, $page));
506             */
507             if ( $dbi->isWikiPage($owner) )
508                 return fmt("Owner: %s", WikiLink($owner));
509             else
510                 return fmt("Owner: %s", '"'.$owner.'"');
511         }
512     }
513
514     /* New behaviour: (by Matt Brown)
515        Prefer author (name) over internal author_id (IP) */
516     function getAuthorMessage ($revision) {
517         if (!$revision) return '';
518         $dbi =& $GLOBALS['request']->_dbi;
519         $author = $revision->get('author');
520         if (!$author) $author = $revision->get('author_id');
521             if (!$author) return '';
522         if ( $dbi->isWikiPage($author) ) {
523                 return fmt("by %s", WikiLink($author));
524         } else {
525                 return fmt("by %s", '"'.$author.'"');
526         }
527     }
528
529     ////////////////////////////////////////////////////////////////
530     //
531     // Hooks for other formatting
532     //
533     ////////////////////////////////////////////////////////////////
534
535     //FIXME: PHP 4.1 Warnings
536     //lib/WikiTheme.php:84: Notice[8]: The call_user_method() function is deprecated,
537     //use the call_user_func variety with the array(&$obj, "method") syntax instead
538
539     function getFormatter ($type, $format) {
540         $method = strtolower("get${type}Formatter");
541         if (method_exists($this, $method))
542             return $this->{$method}($format);
543         return false;
544     }
545
546     ////////////////////////////////////////////////////////////////
547     //
548     // Links
549     //
550     ////////////////////////////////////////////////////////////////
551
552     var $_autosplitWikiWords = false;
553     function setAutosplitWikiWords($autosplit=true) {
554         $this->_autosplitWikiWords = $autosplit ? true : false;
555     }
556
557     function maybeSplitWikiWord ($wikiword) {
558         if ($this->_autosplitWikiWords)
559             return SplitPagename($wikiword);
560         else
561             return $wikiword;
562     }
563
564     var $_anonEditUnknownLinks = true;
565     function setAnonEditUnknownLinks($anonedit=true) {
566         $this->_anonEditUnknownLinks = $anonedit ? true : false;
567     }
568
569     function linkExistingWikiWord($wikiword, $linktext = '', $version = false) {
570         global $request;
571
572         if ($version !== false and !$this->HTML_DUMP_SUFFIX)
573             $url = WikiURL($wikiword, array('version' => $version));
574         else
575             $url = WikiURL($wikiword);
576
577         // Extra steps for dumping page to an html file.
578         if ($this->HTML_DUMP_SUFFIX) {
579             $url = preg_replace('/^\./', '%2e', $url); // dot pages
580         }
581
582         $link = HTML::a(array('href' => $url));
583
584         if (isa($wikiword, 'WikiPageName'))
585              $default_text = $wikiword->shortName;
586          else
587              $default_text = $wikiword;
588          
589         if (!empty($linktext)) {
590             $link->pushContent($linktext);
591             $link->setAttr('class', 'named-wiki');
592             $link->setAttr('title', $this->maybeSplitWikiWord($default_text));
593         }
594         else {
595             $link->pushContent($this->maybeSplitWikiWord($default_text));
596             $link->setAttr('class', 'wiki');
597         }
598         if ($request->getArg('frame'))
599             $link->setAttr('target', '_top');
600         return $link;
601     }
602
603     function linkUnknownWikiWord($wikiword, $linktext = '') {
604         global $request;
605
606         // Get rid of anchors on unknown wikiwords
607         if (isa($wikiword, 'WikiPageName')) {
608             $default_text = $wikiword->shortName;
609             $wikiword = $wikiword->name;
610         }
611         else {
612             $default_text = $wikiword;
613         }
614         
615         if ($this->DUMP_MODE) { // HTML, PDF or XML
616             $link = HTML::u( empty($linktext) ? $wikiword : $linktext);
617             $link->addTooltip(sprintf(_("Empty link to: %s"), $wikiword));
618             $link->setAttr('class', empty($linktext) ? 'wikiunknown' : 'named-wikiunknown');
619             return $link;
620         } else {
621             // if AnonEditUnknownLinks show "?" only users which are allowed to edit this page
622             if (! $this->_anonEditUnknownLinks and 
623                 ( ! $request->_user->isSignedIn() 
624                   or ! mayAccessPage('edit', $request->getArg('pagename')))) 
625             {
626                 $text = HTML::span( empty($linktext) ? $wikiword : $linktext);
627                 $text->setAttr('class', empty($linktext) ? 'wikiunknown' : 'named-wikiunknown');
628                 return $text;
629             } else {
630                 $url = WikiURL($wikiword, array('action' => 'create'));
631                 $button = $this->makeButton('?', $url);
632                 $button->addTooltip(sprintf(_("Create: %s"), $wikiword));
633             }
634         }
635
636         $link = HTML::span();
637         if (!empty($linktext)) {
638             $link->pushContent(HTML::u($linktext));
639             $link->setAttr('class', 'named-wikiunknown');
640         }
641         else {
642             $link->pushContent(HTML::u($this->maybeSplitWikiWord($default_text)));
643             $link->setAttr('class', 'wikiunknown');
644         }
645         if (!isa($button, "ImageButton"))
646             $button->setAttr('rel', 'nofollow');
647         $link->pushContent($button);
648         if ($request->getPref('googleLink')) {
649             $gbutton = $this->makeButton('G', "http://www.google.com/search?q="
650                                          . urlencode($wikiword));
651             $gbutton->addTooltip(sprintf(_("Google:%s"), $wikiword));
652             $link->pushContent($gbutton);
653         }
654         if ($request->getArg('frame'))
655             $link->setAttr('target', '_top');
656
657         return $link;
658     }
659
660     function linkBadWikiWord($wikiword, $linktext = '') {
661         global $ErrorManager;
662         
663         if ($linktext) {
664             $text = $linktext;
665         }
666         elseif (isa($wikiword, 'WikiPageName')) {
667             $text = $wikiword->shortName;
668         }
669         else {
670             $text = $wikiword;
671         }
672
673         if (isa($wikiword, 'WikiPageName'))
674             $message = $wikiword->getWarnings();
675         else
676             $message = sprintf(_("'%s': Bad page name"), $wikiword);
677         $ErrorManager->warning($message);
678         
679         return HTML::span(array('class' => 'badwikiword'), $text);
680     }
681     
682     ////////////////////////////////////////////////////////////////
683     //
684     // Images and Icons
685     //
686     ////////////////////////////////////////////////////////////////
687     var $_imageAliases = array();
688     var $_imageAlt = array();
689
690     /**
691      *
692      * (To disable an image, alias the image to <code>false</code>.
693      */
694     function addImageAlias ($alias, $image_name) {
695         // fall back to the PhpWiki-supplied image if not found
696         if ((empty($this->_imageAliases[$alias])
697                and $this->_findFile("images/$image_name", true))
698             or $image_name === false)
699             $this->_imageAliases[$alias] = $image_name;
700     }
701
702     function addImageAlt ($alias, $alt_text) {
703         $this->_imageAlt[$alias] = $alt_text;
704     }
705     function getImageAlt ($alias) {
706         return $this->_imageAlt[$alias];
707     }
708
709     function getImageURL ($image) {
710         $aliases = &$this->_imageAliases;
711
712         if (isset($aliases[$image])) {
713             $image = $aliases[$image];
714             if (!$image)
715                 return false;
716         }
717
718         // If not extension, default to .png.
719         if (!preg_match('/\.\w+$/', $image))
720             $image .= '.png';
721
722         // FIXME: this should probably be made to fall back
723         //        automatically to .gif, .jpg.
724         //        Also try .gif before .png if browser doesn't like png.
725
726         $path = $this->_findData("images/$image", 'missing okay');
727         if (!$path) // search explicit images/ or button/ links also
728             $path = $this->_findData("$image", 'missing okay');
729
730         if ($this->DUMP_MODE) {
731             if (empty($this->dumped_images)) $this->dumped_images = array();
732             $path = "images/". basename($path);
733             if (!in_array($path,$this->dumped_images)) 
734                 $this->dumped_images[] = $path;
735         }
736         return $path;   
737     }
738
739     function setLinkIcon($proto, $image = false) {
740         if (!$image)
741             $image = $proto;
742
743         $this->_linkIcons[$proto] = $image;
744     }
745
746     function getLinkIconURL ($proto) {
747         $icons = &$this->_linkIcons;
748         if (!empty($icons[$proto]))
749             return $this->getImageURL($icons[$proto]);
750         elseif (!empty($icons['*']))
751             return $this->getImageURL($icons['*']);
752         return false;
753     }
754
755     var $_linkIcon = 'front'; // or 'after' or 'no'. 
756     // maybe also 'spanall': there is a scheme currently in effect with front, which 
757     // spans the icon only to the first, to let the next words wrap on line breaks
758     // see stdlib.php:PossiblyGlueIconToText()
759     function getLinkIconAttr () {
760         return $this->_linkIcon;
761     }
762     function setLinkIconAttr ($where) {
763         $this->_linkIcon = $where;
764     }
765
766     function addButtonAlias ($text, $alias = false) {
767         $aliases = &$this->_buttonAliases;
768
769         if (is_array($text))
770             $aliases = array_merge($aliases, $text);
771         elseif ($alias === false)
772             unset($aliases[$text]);
773         else
774             $aliases[$text] = $alias;
775     }
776
777     function getButtonURL ($text) {
778         $aliases = &$this->_buttonAliases;
779         if (isset($aliases[$text]))
780             $text = $aliases[$text];
781
782         $qtext = urlencode($text);
783         $url = $this->_findButton("$qtext.png");
784         if ($url && strstr($url, '%')) {
785             $url = preg_replace('|([^/]+)$|e', 'urlencode("\\1")', $url);
786         }
787         if (!$url) {// Jeff complained about png not supported everywhere. 
788                     // This was not PC until 2005.
789             $url = $this->_findButton("$qtext.gif");
790             if ($url && strstr($url, '%')) {
791                 $url = preg_replace('|([^/]+)$|e', 'urlencode("\\1")', $url);
792             }
793         }
794         if ($url and $this->DUMP_MODE) {
795             if (empty($this->dumped_buttons)) $this->dumped_buttons = array();
796             $file = $url;
797             if (defined('DATA_PATH'))
798                 $file = substr($url,strlen(DATA_PATH)+1);
799             $url = "images/buttons/".basename($file);
800             if (!array_key_exists($text, $this->dumped_buttons))
801                 $this->dumped_buttons[$text] = $file;
802         }
803         return $url;
804     }
805
806     function _findButton ($button_file) {
807         if (empty($this->_button_path))
808             $this->_button_path = $this->_getButtonPath();
809
810         foreach ($this->_button_path as $dir) {
811             if ($path = $this->_findData("$dir/$button_file", 1))
812                 return $path; 
813         }
814         return false;
815     }
816
817     function _getButtonPath () {
818         $button_dir = $this->_findFile("buttons");
819         $path_dir = $this->_path . $button_dir;
820         if (!file_exists($path_dir) || !is_dir($path_dir))
821             return array();
822         $path = array($button_dir);
823         
824         $dir = dir($path_dir);
825         while (($subdir = $dir->read()) !== false) {
826             if ($subdir[0] == '.')
827                 continue;
828             if ($subdir == 'CVS')
829                 continue;
830             if (is_dir("$path_dir/$subdir"))
831                 $path[] = "$button_dir/$subdir";
832         }
833         $dir->close();
834         // add default buttons
835         $path[] = "themes/default/buttons";
836         $path_dir = $this->_path . "themes/default/buttons";
837         $dir = dir($path_dir);
838         while (($subdir = $dir->read()) !== false) {
839             if ($subdir[0] == '.')
840                 continue;
841             if ($subdir == 'CVS')
842                 continue;
843             if (is_dir("$path_dir/$subdir"))
844                 $path[] = "themes/default/buttons/$subdir";
845         }
846         $dir->close();
847
848         return $path;
849     }
850
851     ////////////////////////////////////////////////////////////////
852     //
853     // Button style
854     //
855     ////////////////////////////////////////////////////////////////
856
857     function makeButton ($text, $url, $class = false, $options = false) {
858         // FIXME: don't always try for image button?
859
860         // Special case: URLs like 'submit:preview' generate form
861         // submission buttons.
862         if (preg_match('/^submit:(.*)$/', $url, $m))
863             return $this->makeSubmitButton($text, $m[1], $class, $options);
864
865         if (is_string($text))           
866             $imgurl = $this->getButtonURL($text);
867         else 
868             $imgurl = $text;
869         if ($imgurl)
870             return new ImageButton($text, $url, 
871                                    in_array($class,array("wikiaction","wikiadmin"))?"wikibutton":$class, 
872                                    $imgurl, $options);
873         else
874             return new Button($this->maybeSplitWikiWord($text), $url, 
875                               $class, $options);
876     }
877
878     function makeSubmitButton ($text, $name, $class = false, $options = false) {
879         $imgurl = $this->getButtonURL($text);
880
881         if ($imgurl)
882             return new SubmitImageButton($text, $name, !$class ? "wikibutton" : $class, $imgurl, $options);
883         else
884             return new SubmitButton($text, $name, $class, $options);
885     }
886
887     /**
888      * Make button to perform action.
889      *
890      * This constructs a button which performs an action on the
891      * currently selected version of the current page.
892      * (Or anotherpage or version, if you want...)
893      *
894      * @param $action string The action to perform (e.g. 'edit', 'lock').
895      * This can also be the name of an "action page" like 'LikePages'.
896      * Alternatively you can give a hash of query args to be applied
897      * to the page.
898      *
899      * @param $label string Textual label for the button.  If left empty,
900      * a suitable name will be guessed.
901      *
902      * @param $page_or_rev mixed  The page to link to.  This can be
903      * given as a string (the page name), a WikiDB_Page object, or as
904      * WikiDB_PageRevision object.  If given as a WikiDB_PageRevision
905      * object, the button will link to a specific version of the
906      * designated page, otherwise the button links to the most recent
907      * version of the page.
908      *
909      * @return object A Button object.
910      */
911     function makeActionButton ($action, $label = false, 
912                                $page_or_rev = false, $options = false) 
913     {
914         extract($this->_get_name_and_rev($page_or_rev));
915
916         if (is_array($action)) {
917             $attr = $action;
918             $action = isset($attr['action']) ? $attr['action'] : 'browse';
919         }
920         else
921             $attr['action'] = $action;
922
923         $class = is_safe_action($action) ? 'wikiaction' : 'wikiadmin';
924         if ( !$label )
925             $label = $this->_labelForAction($action);
926
927         if ($version)
928             $attr['version'] = $version;
929
930         if ($action == 'browse')
931             unset($attr['action']);
932
933         $options = $this->fixAccesskey($options);
934
935         return $this->makeButton($label, WikiURL($pagename, $attr), $class, $options);
936     }
937     
938     function tooltipAccessKeyPrefix() {
939         static $tooltipAccessKeyPrefix = null;
940         if ($tooltipAccessKeyPrefix) return $tooltipAccessKeyPrefix;
941
942         $tooltipAccessKeyPrefix = 'alt';
943         if (isBrowserOpera()) $tooltipAccessKeyPrefix = 'shift-esc';
944         elseif (isBrowserSafari() or browserDetect("Mac") or isBrowserKonqueror()) 
945             $tooltipAccessKeyPrefix = 'ctrl';
946         // ff2 win and x11 only
947         elseif ((browserDetect("firefox/2") or browserDetect("minefield/3") or browserDetect("SeaMonkey/1.1")) 
948                 and ((browserDetect("windows") or browserDetect("x11"))))
949             $tooltipAccessKeyPrefix = 'alt-shift'; 
950         return $tooltipAccessKeyPrefix;
951     }
952
953     /** Define the accesskey in the title only, with ending [p] or [alt-p].
954      *  This fixes the prefix in the title and sets the accesskey.
955      */
956     function fixAccesskey($attrs) {
957         if (!empty($attrs['title']) and preg_match("/\[(alt-)?(.)\]$/", $attrs['title'], $m))
958         {
959             if (empty($attrs['accesskey'])) $attrs['accesskey'] = $m[2];
960             // firefox 'alt-shift', MSIE: 'alt', ... see wikibits.js
961             $attrs['title'] = preg_replace("/\[(alt-)?(.)\]$/", "[".$this->tooltipAccessKeyPrefix()."-\\2]", $attrs['title']);
962         }
963         return $attrs;
964     }
965     
966     /**
967      * Make a "button" which links to a wiki-page.
968      *
969      * These are really just regular WikiLinks, possibly
970      * disguised (e.g. behind an image button) by the theme.
971      *
972      * This method should probably only be used for links
973      * which appear in page navigation bars, or similar places.
974      *
975      * Use linkExistingWikiWord, or LinkWikiWord for normal links.
976      *
977      * @param $page_or_rev mixed The page to link to.  This can be
978      * given as a string (the page name), a WikiDB_Page object, or as
979      * WikiDB_PageRevision object.  If given as a WikiDB_PageRevision
980      * object, the button will link to a specific version of the
981      * designated page, otherwise the button links to the most recent
982      * version of the page.
983      *
984      * @return object A Button object.
985      */
986     function makeLinkButton ($page_or_rev, $label = false, $action = false) {
987         extract($this->_get_name_and_rev($page_or_rev));
988
989         $args = $version ? array('version' => $version) : false;
990         if ($action) $args['action'] = $action;
991
992         return $this->makeButton($label ? $label : $pagename, 
993                                  WikiURL($pagename, $args), 'wiki');
994     }
995
996     function _get_name_and_rev ($page_or_rev) {
997         $version = false;
998
999         if (empty($page_or_rev)) {
1000             global $request;
1001             $pagename = $request->getArg("pagename");
1002             $version = $request->getArg("version");
1003         }
1004         elseif (is_object($page_or_rev)) {
1005             if (isa($page_or_rev, 'WikiDB_PageRevision')) {
1006                 $rev = $page_or_rev;
1007                 $page = $rev->getPage();
1008                 if (!$rev->isCurrent()) $version = $rev->getVersion();
1009             }
1010             else {
1011                 $page = $page_or_rev;
1012             }
1013             $pagename = $page->getName();
1014         }
1015         elseif (is_numeric($page_or_rev)) {
1016             $version = $page_or_rev;
1017         }
1018         else {
1019             $pagename = (string) $page_or_rev;
1020         }
1021         return compact('pagename', 'version');
1022     }
1023
1024     function _labelForAction ($action) {
1025         switch ($action) {
1026             case 'edit':   return _("Edit");
1027             case 'diff':   return _("Diff");
1028             case 'logout': return _("Sign Out");
1029             case 'login':  return _("Sign In");
1030             case 'rename': return _("Rename Page");
1031             case 'lock':   return _("Lock Page");
1032             case 'unlock': return _("Unlock Page");
1033             case 'remove': return _("Remove Page");
1034             case 'purge':  return _("Purge Page");
1035             default:
1036                 // I don't think the rest of these actually get used.
1037                 // 'setprefs'
1038                 // 'upload' 'dumpserial' 'loadfile' 'zip'
1039                 // 'save' 'browse'
1040                 return gettext(ucfirst($action));
1041         }
1042     }
1043
1044     //----------------------------------------------------------------
1045     var $_buttonSeparator = "\n | ";
1046
1047     function setButtonSeparator($separator) {
1048         $this->_buttonSeparator = $separator;
1049     }
1050
1051     function getButtonSeparator() {
1052         return $this->_buttonSeparator;
1053     }
1054
1055
1056     ////////////////////////////////////////////////////////////////
1057     //
1058     // CSS
1059     //
1060     // Notes:
1061     //
1062     // Based on testing with Galeon 1.2.7 (Mozilla 1.2):
1063     // Automatic media-based style selection (via <link> tags) only
1064     // seems to work for the default style, not for alternate styles.
1065     //
1066     // Doing
1067     //
1068     //  <link rel="stylesheet" type="text/css" href="phpwiki.css" />
1069     //  <link rel="stylesheet" type="text/css" href="phpwiki-printer.css" media="print" />
1070     //
1071     // works to make it so that the printer style sheet get used
1072     // automatically when printing (or print-previewing) a page
1073     // (but when only when the default style is selected.)
1074     //
1075     // Attempts like:
1076     //
1077     //  <link rel="alternate stylesheet" title="Modern"
1078     //        type="text/css" href="phpwiki-modern.css" />
1079     //  <link rel="alternate stylesheet" title="Modern"
1080     //        type="text/css" href="phpwiki-printer.css" media="print" />
1081     //
1082     // Result in two "Modern" choices when trying to select alternate style.
1083     // If one selects the first of those choices, one gets phpwiki-modern
1084     // both when browsing and printing.  If one selects the second "Modern",
1085     // one gets no CSS when browsing, and phpwiki-printer when printing.
1086     //
1087     // The Real Fix?
1088     // =============
1089     //
1090     // We should probably move to doing the media based style
1091     // switching in the CSS files themselves using, e.g.:
1092     //
1093     //  @import url(print.css) print;
1094     //
1095     ////////////////////////////////////////////////////////////////
1096
1097     function _CSSlink($title, $css_file, $media, $is_alt = false) {
1098         // Don't set title on default style.  This makes it clear to
1099         // the user which is the default (i.e. most supported) style.
1100         if ($is_alt and isBrowserKonqueror())
1101             return HTML();
1102         $link = HTML::link(array('rel'     => $is_alt ? 'alternate stylesheet' : 'stylesheet',
1103                                  'type'    => 'text/css',
1104                                  'charset' => $GLOBALS['charset'],
1105                                  'href'    => $this->_findData($css_file)));
1106         if ($is_alt)
1107             $link->setAttr('title', $title);
1108
1109         if ($media) 
1110             $link->setAttr('media', $media);
1111         if ($this->DUMP_MODE) {
1112             if (empty($this->dumped_css)) $this->dumped_css = array();
1113             if (!in_array($css_file,$this->dumped_css)) $this->dumped_css[] = $css_file;
1114             $link->setAttr('href', basename($link->getAttr('href')));
1115         }
1116         
1117         return $link;
1118     }
1119
1120     /** Set default CSS source for this theme.
1121      *
1122      * To set styles to be used for different media, pass a
1123      * hash for the second argument, e.g.
1124      *
1125      * $theme->setDefaultCSS('default', array('' => 'normal.css',
1126      *                                        'print' => 'printer.css'));
1127      *
1128      * If you call this more than once, the last one called takes
1129      * precedence as the default style.
1130      *
1131      * @param string $title Name of style (currently ignored, unless
1132      * you call this more than once, in which case, some of the style
1133      * will become alternate (rather than default) styles, and then their
1134      * titles will be used.
1135      *
1136      * @param mixed $css_files Name of CSS file, or hash containing a mapping
1137      * between media types and CSS file names.  Use a key of '' (the empty string)
1138      * to set the default CSS for non-specified media.  (See above for an example.)
1139      */
1140     function setDefaultCSS ($title, $css_files) {
1141         if (!is_array($css_files))
1142             $css_files = array('' => $css_files);
1143         // Add to the front of $this->_css
1144         unset($this->_css[$title]);
1145         $this->_css = array_merge(array($title => $css_files), $this->_css);
1146     }
1147
1148     /** Set alternate CSS source for this theme.
1149      *
1150      * @param string $title Name of style.
1151      * @param string $css_files Name of CSS file.
1152      */
1153     function addAlternateCSS ($title, $css_files) {
1154         if (!is_array($css_files))
1155             $css_files = array('' => $css_files);
1156         $this->_css[$title] = $css_files;
1157     }
1158
1159     /**
1160      * @return string HTML for CSS.
1161      */
1162     function getCSS () {
1163         $css = array();
1164         $is_alt = false;
1165         foreach ($this->_css as $title => $css_files) {
1166             ksort($css_files); // move $css_files[''] to front.
1167             foreach ($css_files as $media => $css_file) {
1168                 if (!empty($this->DUMP_MODE)) {
1169                     if ($media == 'print')
1170                         $css[] = $this->_CSSlink($title, $css_file, '', $is_alt);
1171                 } else {
1172                     $css[] = $this->_CSSlink($title, $css_file, $media, $is_alt);
1173                 }
1174                 if ($is_alt) break;
1175             }
1176             $is_alt = true;
1177         }
1178         return HTML($css);
1179     }
1180
1181     function findTemplate ($name) {
1182         if ($tmp = $this->_findFile("templates/$name.tmpl", 1))
1183             return $this->_path . $tmp;
1184         else {
1185             $f1 = $this->file("templates/$name.tmpl");
1186             foreach ($this->_parents as $parent) {
1187                 if ($tmp = $parent->_findFile("templates/$name.tmpl", 1))
1188                     return $this->_path . $tmp;
1189             }
1190             trigger_error("$f1 not found", E_USER_ERROR);
1191             return false;
1192         }
1193     }
1194
1195     var $_MoreHeaders = array();
1196     function addMoreHeaders ($element) {
1197         $this->_MoreHeaders[] = $element;
1198         if (!empty($this->_headers_printed) and $this->_headers_printed) {
1199             trigger_error(_("Some action(page) wanted to add more headers, but they were already printed.")
1200                           ."\n". $element->asXML(),
1201                            E_USER_NOTICE);
1202         }
1203     }
1204
1205     /**
1206       * Singleton. Only called once, by the head template. See the warning above.
1207       */
1208     function getMoreHeaders () {
1209         // actionpages cannot add headers, because recursive template expansion
1210         // already expanded the head template before.
1211         $this->_headers_printed = 1;
1212         if (empty($this->_MoreHeaders))
1213             return '';
1214         $out = '';
1215         //$out = "<!-- More Headers -->\n";
1216         foreach ($this->_MoreHeaders as $h) {
1217             if (is_object($h))
1218                 $out .= printXML($h);
1219             else
1220                 $out .= "$h\n";
1221         }
1222         return $out;
1223     }
1224
1225     var $_MoreAttr = array();
1226     // new arg: named elements to be able to remove them. such as DoubleClickEdit for htmldumps
1227     function addMoreAttr ($tag, $name, $element) {
1228         // protect from duplicate attr (body jscript: themes, prefs, ...)
1229         static $_attr_cache = array();
1230         $hash = md5($tag."/".$element);
1231         if (!empty($_attr_cache[$hash])) return;
1232         $_attr_cache[$hash] = 1;
1233
1234         if (empty($this->_MoreAttr) or !is_array($this->_MoreAttr[$tag]))
1235             $this->_MoreAttr[$tag] = array($name => $element);
1236         else
1237             $this->_MoreAttr[$tag][$name] = $element;
1238     }
1239
1240     function getMoreAttr ($tag) {
1241         if (empty($this->_MoreAttr[$tag]))
1242             return '';
1243         $out = '';
1244         foreach ($this->_MoreAttr[$tag] as $name => $element) {
1245             if (is_object($element))
1246                 $out .= printXML($element);
1247             else
1248                 $out .= "$element";
1249         }
1250         return $out;
1251     }
1252
1253     /**
1254      * Common Initialisations
1255      */
1256
1257     /**
1258      * The ->load() method replaces the formerly global code in themeinfo.php.
1259      * Without this you would not be able to derive from other themes.
1260      */
1261     function load() {
1262
1263         // CSS file defines fonts, colors and background images for this
1264         // style.  The companion '*-heavy.css' file isn't defined, it's just
1265         // expected to be in the same directory that the base style is in.
1266
1267         // This should result in phpwiki-printer.css being used when
1268         // printing or print-previewing with style "PhpWiki" or "MacOSX" selected.
1269         $this->setDefaultCSS('PhpWiki',
1270                              array(''      => 'phpwiki.css',
1271                                    'print' => 'phpwiki-printer.css'));
1272
1273         // This allows one to manually select "Printer" style (when browsing page)
1274         // to see what the printer style looks like.
1275         $this->addAlternateCSS(_("Printer"), 'phpwiki-printer.css', 'print, screen');
1276         $this->addAlternateCSS(_("Top & bottom toolbars"), 'phpwiki-topbottombars.css');
1277         $this->addAlternateCSS(_("Modern"), 'phpwiki-modern.css');
1278
1279         if (isBrowserIE()) {
1280             $this->addMoreHeaders($this->_CSSlink(0,
1281                                                   $this->_findFile('IEFixes.css'),'all'));
1282             $this->addMoreHeaders("\n");
1283         }
1284
1285         /**
1286          * The logo image appears on every page and links to the HomePage.
1287          */
1288         $this->addImageAlias('logo', WIKI_NAME . 'Logo.png');
1289         
1290         $this->addImageAlias('search', 'search.png');
1291
1292         /**
1293          * The Signature image is shown after saving an edited page. If this
1294          * is set to false then the "Thank you for editing..." screen will
1295          * be omitted.
1296          */
1297
1298         $this->addImageAlias('signature', WIKI_NAME . "Signature.png");
1299         // Uncomment this next line to disable the signature.
1300         //$this->addImageAlias('signature', false);
1301
1302         /*
1303          * Link icons.
1304          */
1305         $this->setLinkIcon('http');
1306         $this->setLinkIcon('https');
1307         $this->setLinkIcon('ftp');
1308         $this->setLinkIcon('mailto');
1309         $this->setLinkIcon('interwiki');
1310         $this->setLinkIcon('wikiuser');
1311         $this->setLinkIcon('*', 'url');
1312
1313         $this->setButtonSeparator("\n | ");
1314
1315         /**
1316          * WikiWords can automatically be split by inserting spaces between
1317          * the words. The default is to leave WordsSmashedTogetherLikeSo.
1318          */
1319         $this->setAutosplitWikiWords(false);
1320
1321         /**
1322          * Layout improvement with dangling links for mostly closed wiki's:
1323          * If false, only users with edit permissions will be presented the 
1324          * special wikiunknown class with "?" and Tooltip.
1325          * If true (default), any user will see the ?, but will be presented 
1326          * the PrintLoginForm on a click.
1327          */
1328         //$this->setAnonEditUnknownLinks(false);
1329
1330         /*
1331          * You may adjust the formats used for formatting dates and times
1332          * below.  (These examples give the default formats.)
1333          * Formats are given as format strings to PHP strftime() function See
1334          * http://www.php.net/manual/en/function.strftime.php for details.
1335          * Do not include the server's zone (%Z), times are converted to the
1336          * user's time zone.
1337          *
1338          * Suggestion for french: 
1339          *   $this->setDateFormat("%A %e %B %Y");
1340          *   $this->setTimeFormat("%H:%M:%S");
1341          * Suggestion for capable php versions, using the server locale:
1342          *   $this->setDateFormat("%x");
1343          *   $this->setTimeFormat("%X");
1344          */
1345         //$this->setDateFormat("%B %d, %Y");
1346         //$this->setTimeFormat("%I:%M %p");
1347
1348         /*
1349          * To suppress times in the "Last edited on" messages, give a
1350          * give a second argument of false:
1351          */
1352         //$this->setDateFormat("%B %d, %Y", false); 
1353
1354
1355         /**
1356          * Custom UserPreferences:
1357          * A list of name => _UserPreference class pairs.
1358          * Rationale: Certain themes should be able to extend the predefined list 
1359          * of preferences. Display/editing is done in the theme specific userprefs.tmpl
1360          * but storage/sanification/update/... must be extended to the Get/SetPreferences methods.
1361          * See themes/wikilens/themeinfo.php
1362          */
1363         //$this->customUserPreference(); 
1364
1365         /**
1366          * Register custom PageList type and define custom PageList classes.
1367          * Rationale: Certain themes should be able to extend the predefined list 
1368          * of pagelist types. E.g. certain plugins, like MostPopular might use 
1369          * info=pagename,hits,rating
1370          * which displays the rating column whenever the wikilens theme is active.
1371          * See themes/wikilens/themeinfo.php
1372          */
1373         //$this->addPageListColumn(); 
1374
1375     } // end of load
1376
1377     /**
1378      * Custom UserPreferences:
1379      * A list of name => _UserPreference class pairs.
1380      * Rationale: Certain themes should be able to extend the predefined list 
1381      * of preferences. Display/editing is done in the theme specific userprefs.tmpl
1382      * but storage/sanification/update/... must be extended to the Get/SetPreferences methods.
1383      * These values are just ignored if another theme is used.
1384      */
1385     function customUserPreferences($array) {
1386         global $customUserPreferenceColumns; // FIXME: really a global?
1387         if (empty($customUserPreferenceColumns)) $customUserPreferenceColumns = array();
1388         //array('wikilens' => new _UserPreference_wikilens());
1389         foreach ($array as $field => $prefobj) {
1390             $customUserPreferenceColumns[$field] = $prefobj;
1391         }
1392     }
1393
1394     /** addPageListColumn(array('rating' => new _PageList_Column_rating('rating', _("Rate"))))
1395      *  Register custom PageList types for special themes, like 
1396      *  'rating' for wikilens
1397      */
1398     function addPageListColumn ($array) {
1399         global $customPageListColumns;
1400         if (empty($customPageListColumns)) $customPageListColumns = array();
1401         foreach ($array as $column => $obj) {
1402             $customPageListColumns[$column] = $obj;
1403         }
1404     }
1405
1406     // Works only on action=browse. Patch #970004 by pixels
1407     // Usage: call $WikiTheme->initDoubleClickEdit() from theme init or 
1408     // define ENABLE_DOUBLECLICKEDIT
1409     function initDoubleClickEdit() {
1410         if (!$this->HTML_DUMP_SUFFIX)
1411             $this->addMoreAttr('body', 'DoubleClickEdit', HTML::Raw(" OnDblClick=\"url = document.URL; url2 = url; if (url.indexOf('?') != -1) url2 = url.slice(0, url.indexOf('?')); if ((url.indexOf('action') == -1) || (url.indexOf('action=browse') != -1)) document.location = url2 + '?action=edit';\""));
1412     }
1413
1414     // Immediate title search results via XMLHTML(HttpRequest)
1415     // by Bitflux GmbH, bitflux.ch. You need to install the livesearch.js seperately.
1416     // Google's or acdropdown is better.
1417     function initLiveSearch() {
1418         //subclasses of Sidebar will init this twice 
1419         static $already = 0;
1420         if (!$this->HTML_DUMP_SUFFIX and !$already) {
1421             $this->addMoreAttr('body', 'LiveSearch', 
1422                                HTML::Raw(" onload=\"liveSearchInit()"));
1423             $this->addMoreHeaders(JavaScript('var liveSearchURI="'
1424                                              .WikiURL(_("TitleSearch"),false,true).'";'));
1425             $this->addMoreHeaders(JavaScript('', array
1426                                              ('src' => $this->_findData('livesearch.js'))));
1427             $already = 1;
1428         }
1429     }
1430
1431     // Immediate title search results via XMLHttpRequest
1432     // using the shipped moacdropdown js-lib
1433     function initMoAcDropDown() {
1434         //subclasses of Sidebar will init this twice 
1435         static $already = 0;
1436         if (!$this->HTML_DUMP_SUFFIX and !$already) {
1437             $dir = $this->_findData('moacdropdown');
1438             // if autocomplete_remote is used: (getobject2 also for calc. the showlist width)
1439             if (DEBUG) {
1440                 foreach (array("mobrowser.js","modomevent3.js","modomt.js",
1441                                "modomext.js","getobject2.js","xmlextras.js") as $js) 
1442                 {
1443                     $this->addMoreHeaders(JavaScript('', array('src' => "$dir/js/$js")));
1444                 }
1445                 $this->addMoreHeaders(JavaScript('', array('src' => "$dir/js/acdropdown.js")));
1446             } else {
1447                 $this->addMoreHeaders(JavaScript('', array('src' => DATA_PATH . "/themes/default/moacdropdown.js")));
1448             }
1449             //$this->addMoreHeaders($this->_CSSlink(0, 
1450             //                      $this->_findFile('moacdropdown/css/dropdown.css'), 'all'));
1451             $this->addMoreHeaders(HTML::style("  @import url( $dir/css/dropdown.css );\n"));
1452             /*
1453             // for local xmlrpc requests
1454             $xmlrpc_url = deduce_script_name();
1455             //if (1 or DATABASE_TYPE == 'dba')
1456             $xmlrpc_url = DATA_PATH . "/RPC2.php";
1457             if ((DEBUG & _DEBUG_REMOTE) and isset($_GET['start_debug']))
1458                 $xmlrpc_url .= ("?start_debug=".$_GET['start_debug']);
1459             $this->addMoreHeaders(JavaScript("var xmlrpc_url = '$xmlrpc_url'"));
1460             */
1461             $already = 1;
1462         }
1463     }
1464
1465     function calendarLink($date = false) {
1466         return $this->calendarBase() . SUBPAGE_SEPARATOR . 
1467                strftime("%Y-%m-%d", $date ? $date : time());
1468     }
1469
1470     function calendarBase() {
1471         static $UserCalPageTitle = false;
1472         global $request;
1473
1474         if (!$UserCalPageTitle) 
1475             $UserCalPageTitle = $request->_user->getId() . 
1476                                 SUBPAGE_SEPARATOR . _("Calendar");
1477         if (!$UserCalPageTitle)
1478             $UserCalPageTitle = (BLOG_EMPTY_DEFAULT_PREFIX ? '' 
1479                                  : ($request->_user->getId() . SUBPAGE_SEPARATOR)) . "Blog";
1480         return $UserCalPageTitle;
1481     }
1482
1483     function calendarInit($force = false) {
1484         $dbi = $GLOBALS['request']->getDbh();
1485         // display flat calender dhtml in the sidebar
1486         if ($force or $dbi->isWikiPage($this->calendarBase())) {
1487             $jslang = @$GLOBALS['LANG'];
1488             $this->addMoreHeaders
1489                 (
1490                  $this->_CSSlink(0, 
1491                                  $this->_findFile('jscalendar/calendar-phpwiki.css'), 'all'));
1492             $this->addMoreHeaders
1493                 (JavaScript('',
1494                             array('src' => $this->_findData('jscalendar/calendar'.(DEBUG?'':'_stripped').'.js'))));
1495             if (!($langfile = $this->_findData("jscalendar/lang/calendar-$jslang.js")))
1496                 $langfile = $this->_findData("jscalendar/lang/calendar-en.js");
1497             $this->addMoreHeaders(JavaScript('',array('src' => $langfile)));
1498             $this->addMoreHeaders
1499                 (JavaScript('',
1500                             array('src' => 
1501                                   $this->_findData('jscalendar/calendar-setup'.(DEBUG?'':'_stripped').'.js'))));
1502
1503             // Get existing date entries for the current user
1504             require_once("lib/TextSearchQuery.php");
1505             $iter = $dbi->titleSearch(new TextSearchQuery("^".$this->calendarBase().SUBPAGE_SEPARATOR, true, "auto"));
1506             $existing = array();
1507             while ($page = $iter->next()) {
1508                 if ($page->exists())
1509                     $existing[] = basename($page->_pagename);
1510             }
1511             if (!empty($existing)) {
1512                 $js_exist = '{"'.join('":1,"',$existing).'":1}';
1513                 //var SPECIAL_DAYS = {"2004-05-11":1,"2004-05-12":1,"2004-06-01":1}
1514                 $this->addMoreHeaders(JavaScript('
1515 /* This table holds the existing calender entries for the current user
1516  *  calculated from the database 
1517  */
1518
1519 var SPECIAL_DAYS = '.javascript_quote_string($js_exist).';
1520
1521 /* This function returns true if the date exists in SPECIAL_DAYS */
1522 function dateExists(date, y, m, d) {
1523     var year = date.getFullYear();
1524     m = m + 1;
1525     m = m < 10 ? "0" + m : m;  // integer, 0..11
1526     d = d < 10 ? "0" + d : d;  // integer, 1..31
1527     var date = year+"-"+m+"-"+d;
1528     var exists = SPECIAL_DAYS[date];
1529     if (!exists) return false;
1530     else return true;
1531 }
1532 // This is the actual date status handler. 
1533 // Note that it receives the date object as well as separate 
1534 // values of year, month and date.
1535 function dateStatusFunc(date, y, m, d) {
1536     if (dateExists(date, y, m, d)) return "existing";
1537     else return false;
1538 }
1539 '));
1540             }
1541             else {
1542                 $this->addMoreHeaders(JavaScript('
1543 function dateStatusFunc(date, y, m, d) { return false;}'));
1544             }
1545         }
1546     }
1547
1548     ////////////////////////////////////////////////////////////////
1549     //
1550     // Events
1551     //
1552     ////////////////////////////////////////////////////////////////
1553
1554     /**  CbUserLogin (&$request, $userid)
1555      * Callback when a user logs in
1556     */
1557     function CbUserLogin (&$request, $userid) {
1558         ; // do nothing
1559     }
1560
1561     /** CbNewUserEdit (&$request, $userid)
1562      * Callback when a new user creates or edits a page 
1563      */
1564     function CbNewUserEdit (&$request, $userid) {
1565         ; // i.e. create homepage with Template/UserPage
1566     }
1567
1568     /** CbNewUserLogin (&$request, $userid)
1569      * Callback when a "new user" logs in. 
1570      *  What is new? We only record changes, not logins.
1571      *  Should we track user actions?
1572      *  Let's say a new user is a user without homepage.
1573      */
1574     function CbNewUserLogin (&$request, $userid) {
1575         ; // do nothing
1576     }
1577
1578     /** CbUserLogout (&$request, $userid) 
1579      * Callback when a user logs out
1580      */
1581     function CbUserLogout (&$request, $userid) {
1582         ; // do nothing
1583     }
1584
1585 };
1586
1587
1588 /**
1589  * A class representing a clickable "button".
1590  *
1591  * In it's simplest (default) form, a "button" is just a link associated
1592  * with some sort of wiki-action.
1593  */
1594 class Button extends HtmlElement {
1595     /** Constructor
1596      *
1597      * @param $text string The text for the button.
1598      * @param $url string The url (href) for the button.
1599      * @param $class string The CSS class for the button.
1600      * @param $options array Additional attributes for the &lt;input&gt; tag.
1601      */
1602     function Button ($text, $url, $class=false, $options=false) {
1603         global $request;
1604         //php5 workaround
1605         if (check_php_version(5)) {
1606             $this->_init('a', array('href' => $url));
1607         } else {
1608             $this->__construct('a', array('href' => $url));
1609         }
1610         if ($class)
1611             $this->setAttr('class', $class);
1612         if ($request->getArg('frame'))
1613             $this->setAttr('target', '_top');
1614         if (!empty($options) and is_array($options)) {
1615             foreach ($options as $key => $val)
1616                 $this->setAttr($key, $val);
1617         }
1618         // Google honors this
1619         if (in_array(strtolower($text), array('edit','create','diff','pdf'))
1620             and !$request->_user->isAuthenticated())
1621             $this->setAttr('rel', 'nofollow');
1622         $this->pushContent($GLOBALS['WikiTheme']->maybeSplitWikiWord($text));
1623     }
1624
1625 };
1626
1627
1628 /**
1629  * A clickable image button.
1630  */
1631 class ImageButton extends Button {
1632     /** Constructor
1633      *
1634      * @param $text string The text for the button.
1635      * @param $url string The url (href) for the button.
1636      * @param $class string The CSS class for the button.
1637      * @param $img_url string URL for button's image.
1638      * @param $img_attr array Additional attributes for the &lt;img&gt; tag.
1639      */
1640     function ImageButton ($text, $url, $class, $img_url, $img_attr=false) {
1641         $this->__construct('a', array('href' => $url));
1642         if ($class)
1643             $this->setAttr('class', $class);
1644         // Google honors this
1645         if (in_array(strtolower($text), array('edit','create','diff','pdf'))
1646             and !$GLOBALS['request']->_user->isAuthenticated())
1647             $this->setAttr('rel', 'nofollow');
1648
1649         if (!is_array($img_attr))
1650             $img_attr = array();
1651         $img_attr['src'] = $img_url;
1652         $img_attr['alt'] = $text;
1653         $img_attr['class'] = 'wiki-button';
1654         $img_attr['border'] = 0;
1655         $this->pushContent(HTML::img($img_attr));
1656     }
1657 };
1658
1659 /**
1660  * A class representing a form <samp>submit</samp> button.
1661  */
1662 class SubmitButton extends HtmlElement {
1663     /** Constructor
1664      *
1665      * @param $text string The text for the button.
1666      * @param $name string The name of the form field.
1667      * @param $class string The CSS class for the button.
1668      * @param $options array Additional attributes for the &lt;input&gt; tag.
1669      */
1670     function SubmitButton ($text, $name=false, $class=false, $options=false) {
1671         $this->__construct('input', array('type' => 'submit',
1672                                           'value' => $text));
1673         if ($name)
1674             $this->setAttr('name', $name);
1675         if ($class)
1676             $this->setAttr('class', $class);
1677         if (!empty($options)) {
1678             foreach ($options as $key => $val)
1679                 $this->setAttr($key, $val);
1680         }
1681     }
1682
1683 };
1684
1685
1686 /**
1687  * A class representing an image form <samp>submit</samp> button.
1688  */
1689 class SubmitImageButton extends SubmitButton {
1690     /** Constructor
1691      *
1692      * @param $text string The text for the button.
1693      * @param $name string The name of the form field.
1694      * @param $class string The CSS class for the button.
1695      * @param $img_url string URL for button's image.
1696      * @param $img_attr array Additional attributes for the &lt;img&gt; tag.
1697      */
1698     function SubmitImageButton ($text, $name=false, $class=false, $img_url, $img_attr=false) {
1699         $this->__construct('input', array('type'  => 'image',
1700                                           'src'   => $img_url,
1701                                           'value' => $text,
1702                                           'alt'   => $text));
1703         if ($name)
1704             $this->setAttr('name', $name);
1705         if ($class)
1706             $this->setAttr('class', $class);
1707         if (!empty($img_attr)) {
1708             foreach ($img_attr as $key => $val)
1709                 $this->setAttr($key, $val);
1710         }
1711     }
1712
1713 };
1714
1715 /** 
1716  * A sidebar box with title and body, narrow fixed-width.
1717  * To represent abbrevated content of plugins, links or forms,
1718  * like "Getting Started", "Search", "Sarch Pagename", 
1719  * "Login", "Menu", "Recent Changes", "Last comments", "Last Blogs"
1720  * "Calendar"
1721  * ... See http://tikiwiki.org/
1722  *
1723  * Usage:
1724  * sidebar.tmpl:
1725  *   $menu = SidebarBox("Menu",HTML::dl(HTML::dt(...))); $menu->format();
1726  *   $menu = PluginSidebarBox("RecentChanges",array('limit'=>10)); $menu->format();
1727  */
1728 class SidebarBox {
1729
1730     function SidebarBox($title, $body) {
1731         require_once('lib/WikiPlugin.php');
1732         $this->title = $title;
1733         $this->body = $body;
1734     }
1735     function format() {
1736         return WikiPlugin::makeBox($this->title, $this->body);
1737     }
1738 }
1739
1740 /** 
1741  * A sidebar box for plugins.
1742  * Any plugin may provide a box($args=false, $request=false, $basepage=false)
1743  * method, with the help of WikiPlugin::makeBox()
1744  */
1745 class PluginSidebarBox extends SidebarBox {
1746
1747     var $_plugin, $_args = false, $_basepage = false;
1748
1749     function PluginSidebarBox($name, $args = false, $basepage = false) {
1750         require_once("lib/WikiPlugin.php");
1751
1752         $loader = new WikiPluginLoader();
1753         $plugin = $loader->getPlugin($name);
1754         if (!$plugin) {
1755             return $loader->_error(sprintf(_("Plugin %s: undefined"),
1756                                           $name));
1757         }/*
1758         if (!method_exists($plugin, 'box')) {
1759             return $loader->_error(sprintf(_("%s: has no box method"),
1760                                            get_class($plugin)));
1761         }*/
1762         $this->_plugin   =& $plugin;
1763         $this->_args     = $args ? $args : array();
1764         $this->_basepage = $basepage;
1765     }
1766
1767     function format($args = false) {
1768         return $this->_plugin->box($args ? array_merge($this->_args, $args) : $this->_args,
1769                                    $GLOBALS['request'], 
1770                                    $this->_basepage);
1771     }
1772 }
1773
1774 // Various boxes which are no plugins
1775 class RelatedLinksBox extends SidebarBox {
1776     function RelatedLinksBox($title = false, $body = '', $limit = 20) {
1777         global $request;
1778         $this->title = $title ? $title : _("Related Links");
1779         $this->body = HTML($body);
1780         $page = $request->getPage($request->getArg('pagename'));
1781         $revision = $page->getCurrentRevision();
1782         $page_content = $revision->getTransformedContent();
1783         //$cache = &$page->_wikidb->_cache;
1784         $counter = 0;
1785         $sp = HTML::Raw('&middot; ');
1786         foreach ($page_content->getWikiPageLinks() as $link) {
1787             $linkto = $link['linkto'];
1788             if (!$request->_dbi->isWikiPage($linkto)) continue;
1789             $this->body->pushContent($sp, WikiLink($linkto), HTML::br());
1790             $counter++;
1791             if ($limit and $counter > $limit) continue;
1792         }
1793     }
1794 }
1795
1796 class RelatedExternalLinksBox extends SidebarBox {
1797     function RelatedExternalLinksBox($title = false, $body = '', $limit = 20) {
1798         global $request;
1799         $this->title = $title ? $title : _("External Links");
1800         $this->body = HTML($body);
1801         $page = $request->getPage($request->getArg('pagename'));
1802         $cache = &$page->_wikidb->_cache;
1803         $counter = 0;
1804         $sp = HTML::Raw('&middot; ');
1805         foreach ($cache->getWikiPageLinks() as $link) {
1806             $linkto = $link['linkto'];
1807             if ($linkto) {
1808                 $this->body->pushContent($sp, WikiLink($linkto), HTML::br());
1809                 $counter++;
1810                 if ($limit and $counter > $limit) continue;
1811             }
1812         }
1813     }
1814 }
1815
1816 function listAvailableThemes() {
1817     $available_themes = array(); 
1818     $dir_root = 'themes';
1819     if (defined('PHPWIKI_DIR'))
1820         $dir_root = PHPWIKI_DIR . "/$dir_root";
1821     $dir = dir($dir_root);
1822     if ($dir) {
1823         while($entry = $dir->read()) {
1824             if (is_dir($dir_root.'/'.$entry) 
1825                 and file_exists($dir_root.'/'.$entry.'/themeinfo.php')) 
1826             {
1827                 array_push($available_themes, $entry);
1828             }
1829         }
1830         $dir->close();
1831     }
1832     return $available_themes;
1833 }
1834
1835 function listAvailableLanguages() {
1836     $available_languages = array('en');
1837     $dir_root = 'locale';
1838     if (defined('PHPWIKI_DIR'))
1839         $dir_root = PHPWIKI_DIR . "/$dir_root";
1840     if ($dir = dir($dir_root)) {
1841         while($entry = $dir->read()) {
1842             if (is_dir($dir_root."/".$entry) and is_dir($dir_root.'/'.$entry.'/LC_MESSAGES'))
1843             {
1844                 array_push($available_languages, $entry);
1845             }
1846         }
1847         $dir->close();
1848     }
1849     return $available_languages;
1850 }
1851
1852 // (c-file-style: "gnu")
1853 // Local Variables:
1854 // mode: php
1855 // tab-width: 8
1856 // c-basic-offset: 4
1857 // c-hanging-comment-ender-p: nil
1858 // indent-tabs-mode: nil
1859 // End:
1860 ?>