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