]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/WikiTheme.php
No tabs
[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
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 /**
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) && function_exists('debug_backtrace')) { // >= 4.3.0
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 fmt("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 %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         elseif (is_numeric($page_or_rev)) {
1020             $version = $page_or_rev;
1021         }
1022         else {
1023             $pagename = (string) $page_or_rev;
1024         }
1025         return compact('pagename', 'version');
1026     }
1027
1028     function _labelForAction ($action) {
1029         switch ($action) {
1030             case 'edit':   return _("Edit");
1031             case 'diff':   return _("Diff");
1032             case 'logout': return _("Sign Out");
1033             case 'login':  return _("Sign In");
1034             case 'rename': return _("Rename Page");
1035             case 'lock':   return _("Lock Page");
1036             case 'unlock': return _("Unlock Page");
1037             case 'remove': return _("Remove Page");
1038             case 'purge':  return _("Purge Page");
1039             default:
1040                 // I don't think the rest of these actually get used.
1041                 // 'setprefs'
1042                 // 'upload' 'dumpserial' 'loadfile' 'zip'
1043                 // 'save' 'browse'
1044                 return gettext(ucfirst($action));
1045         }
1046     }
1047
1048     //----------------------------------------------------------------
1049     var $_buttonSeparator = "\n | ";
1050
1051     function setButtonSeparator($separator) {
1052         $this->_buttonSeparator = $separator;
1053     }
1054
1055     function getButtonSeparator() {
1056         return $this->_buttonSeparator;
1057     }
1058
1059
1060     ////////////////////////////////////////////////////////////////
1061     //
1062     // CSS
1063     //
1064     // Notes:
1065     //
1066     // Based on testing with Galeon 1.2.7 (Mozilla 1.2):
1067     // Automatic media-based style selection (via <link> tags) only
1068     // seems to work for the default style, not for alternate styles.
1069     //
1070     // Doing
1071     //
1072     //  <link rel="stylesheet" type="text/css" href="phpwiki.css" />
1073     //  <link rel="stylesheet" type="text/css" href="phpwiki-printer.css" media="print" />
1074     //
1075     // works to make it so that the printer style sheet get used
1076     // automatically when printing (or print-previewing) a page
1077     // (but when only when the default style is selected.)
1078     //
1079     // Attempts like:
1080     //
1081     //  <link rel="alternate stylesheet" title="Modern"
1082     //        type="text/css" href="phpwiki-modern.css" />
1083     //  <link rel="alternate stylesheet" title="Modern"
1084     //        type="text/css" href="phpwiki-printer.css" media="print" />
1085     //
1086     // Result in two "Modern" choices when trying to select alternate style.
1087     // If one selects the first of those choices, one gets phpwiki-modern
1088     // both when browsing and printing.  If one selects the second "Modern",
1089     // one gets no CSS when browsing, and phpwiki-printer when printing.
1090     //
1091     // The Real Fix?
1092     // =============
1093     //
1094     // We should probably move to doing the media based style
1095     // switching in the CSS files themselves using, e.g.:
1096     //
1097     //  @import url(print.css) print;
1098     //
1099     ////////////////////////////////////////////////////////////////
1100
1101     function _CSSlink($title, $css_file, $media, $is_alt = false) {
1102         // Don't set title on default style.  This makes it clear to
1103         // the user which is the default (i.e. most supported) style.
1104         if ($is_alt and isBrowserKonqueror())
1105             return HTML();
1106         $link = HTML::link(array('rel'     => $is_alt ? 'alternate stylesheet' : 'stylesheet',
1107                                  'type'    => 'text/css',
1108                                  'charset' => $GLOBALS['charset'],
1109                                  'href'    => $this->_findData($css_file)));
1110         if ($is_alt)
1111             $link->setAttr('title', $title);
1112
1113         if ($media)
1114             $link->setAttr('media', $media);
1115         if ($this->DUMP_MODE) {
1116             if (empty($this->dumped_css)) $this->dumped_css = array();
1117             if (!in_array($css_file,$this->dumped_css)) $this->dumped_css[] = $css_file;
1118             $link->setAttr('href', basename($link->getAttr('href')));
1119         }
1120
1121         return $link;
1122     }
1123
1124     /** Set default CSS source for this theme.
1125      *
1126      * To set styles to be used for different media, pass a
1127      * hash for the second argument, e.g.
1128      *
1129      * $theme->setDefaultCSS('default', array('' => 'normal.css',
1130      *                                        'print' => 'printer.css'));
1131      *
1132      * If you call this more than once, the last one called takes
1133      * precedence as the default style.
1134      *
1135      * @param string $title Name of style (currently ignored, unless
1136      * you call this more than once, in which case, some of the style
1137      * will become alternate (rather than default) styles, and then their
1138      * titles will be used.
1139      *
1140      * @param mixed $css_files Name of CSS file, or hash containing a mapping
1141      * between media types and CSS file names.  Use a key of '' (the empty string)
1142      * to set the default CSS for non-specified media.  (See above for an example.)
1143      */
1144     function setDefaultCSS ($title, $css_files) {
1145         if (!is_array($css_files))
1146             $css_files = array('' => $css_files);
1147         // Add to the front of $this->_css
1148         unset($this->_css[$title]);
1149         $this->_css = array_merge(array($title => $css_files), $this->_css);
1150     }
1151
1152     /** Set alternate CSS source for this theme.
1153      *
1154      * @param string $title Name of style.
1155      * @param string $css_files Name of CSS file.
1156      */
1157     function addAlternateCSS ($title, $css_files) {
1158         if (!is_array($css_files))
1159             $css_files = array('' => $css_files);
1160         $this->_css[$title] = $css_files;
1161     }
1162
1163     /**
1164      * @return string HTML for CSS.
1165      */
1166     function getCSS () {
1167         $css = array();
1168         $is_alt = false;
1169         foreach ($this->_css as $title => $css_files) {
1170             ksort($css_files); // move $css_files[''] to front.
1171             foreach ($css_files as $media => $css_file) {
1172         if (!empty($this->DUMP_MODE)) {
1173             if ($media == 'print')
1174             $css[] = $this->_CSSlink($title, $css_file, '', $is_alt);
1175         } else {
1176             $css[] = $this->_CSSlink($title, $css_file, $media, $is_alt);
1177         }
1178                 if ($is_alt) break;
1179             }
1180             $is_alt = true;
1181         }
1182         return HTML($css);
1183     }
1184
1185     function findTemplate ($name) {
1186         if ($tmp = $this->_findFile("templates/$name.tmpl", 1))
1187             return $this->_path . $tmp;
1188         else {
1189             $f1 = $this->file("templates/$name.tmpl");
1190             foreach ($this->_parents as $parent) {
1191                 if ($tmp = $parent->_findFile("templates/$name.tmpl", 1))
1192                     return $this->_path . $tmp;
1193             }
1194             trigger_error("$f1 not found", E_USER_ERROR);
1195             return false;
1196         }
1197     }
1198
1199     /**
1200      * Add a random header element to head
1201      * TODO: first css, then js. Maybe seperate it into addJSHeaders/addCSSHeaders
1202      * or use an optional type argument, and seperate it within _MoreHeaders[]
1203      */
1204     //$GLOBALS['request']->_MoreHeaders = array();
1205     function addMoreHeaders ($element) {
1206         $GLOBALS['request']->_MoreHeaders[] = $element;
1207         if (!empty($this->_headers_printed) and $this->_headers_printed) {
1208         trigger_error(_("Some action(page) wanted to add more headers, but they were already printed.")
1209               ."\n". $element->asXML(),
1210                            E_USER_NOTICE);
1211         }
1212     }
1213
1214     /**
1215       * Singleton. Only called once, by the head template. See the warning above.
1216       */
1217     function getMoreHeaders () {
1218         global $request;
1219         // actionpages cannot add headers, because recursive template expansion
1220         // already expanded the head template before.
1221         $this->_headers_printed = 1;
1222         if (empty($request->_MoreHeaders))
1223             return '';
1224         $out = '';
1225         if (false and ($file = $this->_findData('delayed.js'))) {
1226             $request->_MoreHeaders[] = JavaScript('
1227 // Add a script element as a child of the body
1228 function downloadJSAtOnload() {
1229 var element = document.createElement("script");
1230 element.src = "' . $file . '";
1231 document.body.appendChild(element);
1232 }
1233 // Check for browser support of event handling capability
1234 if (window.addEventListener)
1235 window.addEventListener("load", downloadJSAtOnload, false);
1236 else if (window.attachEvent)
1237 window.attachEvent("onload", downloadJSAtOnload);
1238 else window.onload = downloadJSAtOnload;');
1239         }
1240         //$out = "<!-- More Headers -->\n";
1241         foreach ($request->_MoreHeaders as $h) {
1242             if (is_object($h))
1243                 $out .= $h->printXML();
1244             else
1245                 $out .= "$h\n";
1246         }
1247         return $out;
1248     }
1249
1250     //$GLOBALS['request']->_MoreAttr = array();
1251     // new arg: named elements to be able to remove them. such as DoubleClickEdit for htmldumps
1252     function addMoreAttr ($tag, $name, $element) {
1253         global $request;
1254         // protect from duplicate attr (body jscript: themes, prefs, ...)
1255         static $_attr_cache = array();
1256         $hash = md5($tag."/".$element);
1257         if (!empty($_attr_cache[$hash])) return;
1258         $_attr_cache[$hash] = 1;
1259
1260         if (empty($request->_MoreAttr) or !is_array($request->_MoreAttr[$tag]))
1261             $request->_MoreAttr[$tag] = array($name => $element);
1262         else
1263             $request->_MoreAttr[$tag][$name] = $element;
1264     }
1265
1266     function getMoreAttr ($tag) {
1267         global $request;
1268         if (empty($request->_MoreAttr[$tag]))
1269             return '';
1270         $out = '';
1271         foreach ($request->_MoreAttr[$tag] as $name => $element) {
1272             if (is_object($element))
1273                 $out .= $element->printXML();
1274             else
1275                 $out .= "$element";
1276         }
1277         return $out;
1278     }
1279
1280     /**
1281      * Common Initialisations
1282      */
1283
1284     /**
1285      * The ->load() method replaces the formerly global code in themeinfo.php.
1286      * This is run only once for the selected theme, and not for the parent themes.
1287      * Without this you would not be able to derive from other themes.
1288      */
1289     function load() {
1290
1291         $this->initGlobals();
1292
1293     // CSS file defines fonts, colors and background images for this
1294     // style.  The companion '*-heavy.css' file isn't defined, it's just
1295     // expected to be in the same directory that the base style is in.
1296
1297     // This should result in phpwiki-printer.css being used when
1298     // printing or print-previewing with style "PhpWiki" or "MacOSX" selected.
1299     $this->setDefaultCSS('PhpWiki',
1300                  array(''      => 'phpwiki.css',
1301                    'print' => 'phpwiki-printer.css'));
1302
1303     // This allows one to manually select "Printer" style (when browsing page)
1304     // to see what the printer style looks like.
1305     $this->addAlternateCSS(_("Printer"), 'phpwiki-printer.css', 'print, screen');
1306     $this->addAlternateCSS(_("Top & bottom toolbars"), 'phpwiki-topbottombars.css');
1307     $this->addAlternateCSS(_("Modern"), 'phpwiki-modern.css');
1308
1309     if (isBrowserIE()) {
1310         $this->addMoreHeaders($this->_CSSlink(0,
1311                           $this->_findFile('IEFixes.css'),'all'));
1312         $this->addMoreHeaders("\n");
1313     }
1314
1315     /**
1316      * The logo image appears on every page and links to the HomePage.
1317      */
1318     $this->addImageAlias('logo', WIKI_NAME . 'Logo.png');
1319
1320     $this->addImageAlias('search', 'search.png');
1321
1322     /**
1323      * The Signature image is shown after saving an edited page. If this
1324      * is set to false then the "Thank you for editing..." screen will
1325      * be omitted.
1326      */
1327
1328     $this->addImageAlias('signature', WIKI_NAME . "Signature.png");
1329     // Uncomment this next line to disable the signature.
1330     //$this->addImageAlias('signature', false);
1331
1332     /*
1333      * Link icons.
1334      */
1335     $this->setLinkIcon('http');
1336     $this->setLinkIcon('https');
1337     $this->setLinkIcon('ftp');
1338     $this->setLinkIcon('mailto');
1339     $this->setLinkIcon('interwiki');
1340     $this->setLinkIcon('wikiuser');
1341     $this->setLinkIcon('*', 'url');
1342
1343     $this->setButtonSeparator("\n | ");
1344
1345     /**
1346      * WikiWords can automatically be split by inserting spaces between
1347      * the words. The default is to leave WordsSmashedTogetherLikeSo.
1348      */
1349     $this->setAutosplitWikiWords(false);
1350
1351     /**
1352      * Layout improvement with dangling links for mostly closed wiki's:
1353      * If false, only users with edit permissions will be presented the
1354      * special wikiunknown class with "?" and Tooltip.
1355      * If true (default), any user will see the ?, but will be presented
1356      * the PrintLoginForm on a click.
1357      */
1358     //$this->setAnonEditUnknownLinks(false);
1359
1360     /*
1361      * You may adjust the formats used for formatting dates and times
1362      * below.  (These examples give the default formats.)
1363      * Formats are given as format strings to PHP strftime() function See
1364      * http://www.php.net/manual/en/function.strftime.php for details.
1365      * Do not include the server's zone (%Z), times are converted to the
1366      * user's time zone.
1367      *
1368      * Suggestion for french:
1369      *   $this->setDateFormat("%A %e %B %Y");
1370      *   $this->setTimeFormat("%H:%M:%S");
1371      * Suggestion for capable php versions, using the server locale:
1372      *   $this->setDateFormat("%x");
1373      *   $this->setTimeFormat("%X");
1374      */
1375     //$this->setDateFormat("%B %d, %Y");
1376     //$this->setTimeFormat("%I:%M %p");
1377
1378     /*
1379      * To suppress times in the "Last edited on" messages, give a
1380      * give a second argument of false:
1381      */
1382     //$this->setDateFormat("%B %d, %Y", false);
1383
1384
1385     /**
1386      * Custom UserPreferences:
1387      * A list of name => _UserPreference class pairs.
1388      * Rationale: Certain themes should be able to extend the predefined list
1389      * of preferences. Display/editing is done in the theme specific userprefs.tmpl
1390      * but storage/sanification/update/... must be extended to the Get/SetPreferences methods.
1391      * See themes/wikilens/themeinfo.php
1392      */
1393     //$this->customUserPreference();
1394
1395     /**
1396      * Register custom PageList type and define custom PageList classes.
1397      * Rationale: Certain themes should be able to extend the predefined list
1398      * of pagelist types. E.g. certain plugins, like MostPopular might use
1399      * info=pagename,hits,rating
1400      * which displays the rating column whenever the wikilens theme is active.
1401      * See themes/wikilens/themeinfo.php
1402      */
1403     //$this->addPageListColumn();
1404
1405     } // end of load
1406
1407     /**
1408      * Custom UserPreferences:
1409      * A list of name => _UserPreference class pairs.
1410      * Rationale: Certain themes should be able to extend the predefined list
1411      * of preferences. Display/editing is done in the theme specific userprefs.tmpl
1412      * but storage/sanification/update/... must be extended to the Get/SetPreferences methods.
1413      * These values are just ignored if another theme is used.
1414      */
1415     function customUserPreferences($array) {
1416         global $customUserPreferenceColumns; // FIXME: really a global?
1417         if (empty($customUserPreferenceColumns)) $customUserPreferenceColumns = array();
1418         //array('wikilens' => new _UserPreference_wikilens());
1419         foreach ($array as $field => $prefobj) {
1420             $customUserPreferenceColumns[$field] = $prefobj;
1421         }
1422     }
1423
1424     /** addPageListColumn(array('rating' => new _PageList_Column_rating('rating', _("Rate"))))
1425      *  Register custom PageList types for special themes, like
1426      *  'rating' for wikilens
1427      */
1428     function addPageListColumn ($array) {
1429         global $customPageListColumns;
1430         if (empty($customPageListColumns)) $customPageListColumns = array();
1431         foreach ($array as $column => $obj) {
1432             $customPageListColumns[$column] = $obj;
1433         }
1434     }
1435
1436     function initGlobals() {
1437         global $request;
1438     static $already = 0;
1439         if (!$already) {
1440             $script_url = deduce_script_name();
1441             if ((DEBUG & _DEBUG_REMOTE) and isset($_GET['start_debug']))
1442                 $script_url .= ("?start_debug=".$_GET['start_debug']);
1443             $folderArrowPath = dirname($this->_findData('images/folderArrowLoading.gif'));
1444             $pagename = $request->getArg('pagename');
1445             $js = "var data_path = '". javascript_quote_string(DATA_PATH) ."';\n"
1446                 // XSS warning with pagename
1447                 ."var pagename  = '". javascript_quote_string($pagename) ."';\n"
1448                 ."var script_url= '". javascript_quote_string($script_url) ."';\n"
1449                 ."var stylepath = data_path+'/".javascript_quote_string($this->_theme)."/';\n"
1450                 ."var folderArrowPath = '".javascript_quote_string($folderArrowPath)."';\n"
1451                 ."var use_path_info = " . (USE_PATH_INFO ? "true" : "false") .";\n";
1452             $this->addMoreHeaders(JavaScript($js));
1453         $already = 1;
1454         }
1455     }
1456
1457     // Works only on action=browse. Patch #970004 by pixels
1458     // Usage: call $WikiTheme->initDoubleClickEdit() from theme init or
1459     // define ENABLE_DOUBLECLICKEDIT
1460     function initDoubleClickEdit() {
1461         if (!$this->HTML_DUMP_SUFFIX)
1462             $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';\""));
1463     }
1464
1465     // Immediate title search results via XMLHTML(HttpRequest)
1466     // by Bitflux GmbH, bitflux.ch. You need to install the livesearch.js seperately.
1467     // Google's or acdropdown is better.
1468     function initLiveSearch() {
1469     //subclasses of Sidebar will init this twice
1470     static $already = 0;
1471         if (!$this->HTML_DUMP_SUFFIX and !$already) {
1472             $this->addMoreAttr('body', 'LiveSearch',
1473                                HTML::Raw(" onload=\"liveSearchInit()"));
1474             $this->addMoreHeaders(JavaScript('var liveSearchURI="'
1475                                              .WikiURL(_("TitleSearch"),false,true).'";'));
1476             $this->addMoreHeaders(JavaScript('', array
1477                                              ('src' => $this->_findData('livesearch.js'))));
1478         $already = 1;
1479         }
1480     }
1481
1482     // Immediate title search results via XMLHttpRequest
1483     // using the shipped moacdropdown js-lib
1484     function initMoAcDropDown() {
1485     //subclasses of Sidebar will init this twice
1486     static $already = 0;
1487         if (!$this->HTML_DUMP_SUFFIX and !$already) {
1488             $dir = $this->_findData('moacdropdown');
1489             if (!DEBUG and ($css = $this->_findFile('moacdropdown/css/dropdown-min.css'))) {
1490                 $this->addMoreHeaders($this->_CSSlink(0, $css, 'all'));
1491             } else {
1492                 $this->addMoreHeaders(HTML::style(array('type' => 'text/css'), "  @import url( $dir/css/dropdown.css );\n"));
1493             }
1494             // if autocomplete_remote is used: (getobject2 also for calc. the showlist width)
1495         if (DEBUG) {
1496         foreach (array("mobrowser.js","modomevent3.js","modomt.js",
1497                    "modomext.js","getobject2.js","xmlextras.js") as $js)
1498         {
1499             $this->addMoreHeaders(JavaScript('', array('src' => "$dir/js/$js")));
1500         }
1501         $this->addMoreHeaders(JavaScript('', array('src' => "$dir/js/acdropdown.js")));
1502         } else {
1503                 // already in wikicommon-min.js
1504         ; //$this->addMoreHeaders(JavaScript('', array('src' => DATA_PATH . "/themes/default/moacdropdown.js")));
1505         }
1506         /*
1507         // for local xmlrpc requests
1508         $xmlrpc_url = deduce_script_name();
1509         //if (1 or DATABASE_TYPE == 'dba')
1510         $xmlrpc_url = DATA_PATH . "/RPC2.php";
1511         if ((DEBUG & _DEBUG_REMOTE) and isset($_GET['start_debug']))
1512         $xmlrpc_url .= ("?start_debug=".$_GET['start_debug']);
1513             $this->addMoreHeaders(JavaScript("var xmlrpc_url = '$xmlrpc_url'"));
1514         */
1515         $already = 1;
1516         }
1517     }
1518
1519     function calendarLink($date = false) {
1520         return $this->calendarBase() . SUBPAGE_SEPARATOR .
1521                strftime("%Y-%m-%d", $date ? $date : time());
1522     }
1523
1524     function calendarBase() {
1525         static $UserCalPageTitle = false;
1526         global $request;
1527
1528         if (!$UserCalPageTitle)
1529             $UserCalPageTitle = $request->_user->getId() .
1530                                 SUBPAGE_SEPARATOR . _("Calendar");
1531         if (!$UserCalPageTitle)
1532             $UserCalPageTitle = (BLOG_EMPTY_DEFAULT_PREFIX ? ''
1533                                  : ($request->_user->getId() . SUBPAGE_SEPARATOR)) . "Blog";
1534         return $UserCalPageTitle;
1535     }
1536
1537     function calendarInit($force = false) {
1538         $dbi = $GLOBALS['request']->getDbh();
1539         // display flat calender dhtml in the sidebar
1540         if ($force or $dbi->isWikiPage($this->calendarBase())) {
1541             $jslang = @$GLOBALS['LANG'];
1542             $this->addMoreHeaders
1543                 (
1544                  $this->_CSSlink(0,
1545                                  $this->_findFile('jscalendar/calendar-phpwiki.css'), 'all'));
1546             $this->addMoreHeaders
1547                 (JavaScript('',
1548                             array('src' => $this->_findData('jscalendar/calendar'.(DEBUG?'':'_stripped').'.js'))));
1549             if (!($langfile = $this->_findData("jscalendar/lang/calendar-$jslang.js")))
1550                 $langfile = $this->_findData("jscalendar/lang/calendar-en.js");
1551             $this->addMoreHeaders(JavaScript('',array('src' => $langfile)));
1552             $this->addMoreHeaders
1553                 (JavaScript('',
1554                             array('src' =>
1555                                   $this->_findData('jscalendar/calendar-setup'.(DEBUG?'':'_stripped').'.js'))));
1556
1557             // Get existing date entries for the current user
1558             require_once("lib/TextSearchQuery.php");
1559             $iter = $dbi->titleSearch(new TextSearchQuery("^".$this->calendarBase().SUBPAGE_SEPARATOR, true, "auto"));
1560             $existing = array();
1561             while ($page = $iter->next()) {
1562                 if ($page->exists())
1563                     $existing[] = basename($page->_pagename);
1564             }
1565             if (!empty($existing)) {
1566                 $js_exist = '{"'.join('":1,"',$existing).'":1}';
1567                 //var SPECIAL_DAYS = {"2004-05-11":1,"2004-05-12":1,"2004-06-01":1}
1568                 $this->addMoreHeaders(JavaScript('
1569 /* This table holds the existing calender entries for the current user
1570  *  calculated from the database
1571  */
1572
1573 var SPECIAL_DAYS = '.javascript_quote_string($js_exist).';
1574
1575 /* This function returns true if the date exists in SPECIAL_DAYS */
1576 function dateExists(date, y, m, d) {
1577     var year = date.getFullYear();
1578     m = m + 1;
1579     m = m < 10 ? "0" + m : m;  // integer, 0..11
1580     d = d < 10 ? "0" + d : d;  // integer, 1..31
1581     var date = year+"-"+m+"-"+d;
1582     var exists = SPECIAL_DAYS[date];
1583     if (!exists) return false;
1584     else return true;
1585 }
1586 // This is the actual date status handler.
1587 // Note that it receives the date object as well as separate
1588 // values of year, month and date.
1589 function dateStatusFunc(date, y, m, d) {
1590     if (dateExists(date, y, m, d)) return "existing";
1591     else return false;
1592 }
1593 '));
1594             }
1595             else {
1596                 $this->addMoreHeaders(JavaScript('
1597 function dateStatusFunc(date, y, m, d) { return false;}'));
1598             }
1599         }
1600     }
1601
1602     ////////////////////////////////////////////////////////////////
1603     //
1604     // Events
1605     //
1606     ////////////////////////////////////////////////////////////////
1607
1608     /**  CbUserLogin (&$request, $userid)
1609      * Callback when a user logs in
1610     */
1611     function CbUserLogin (&$request, $userid) {
1612     ; // do nothing
1613     }
1614
1615     /** CbNewUserEdit (&$request, $userid)
1616      * Callback when a new user creates or edits a page
1617      */
1618     function CbNewUserEdit (&$request, $userid) {
1619     ; // i.e. create homepage with Template/UserPage
1620     }
1621
1622     /** CbNewUserLogin (&$request, $userid)
1623      * Callback when a "new user" logs in.
1624      *  What is new? We only record changes, not logins.
1625      *  Should we track user actions?
1626      *  Let's say a new user is a user without homepage.
1627      */
1628     function CbNewUserLogin (&$request, $userid) {
1629     ; // do nothing
1630     }
1631
1632     /** CbUserLogout (&$request, $userid)
1633      * Callback when a user logs out
1634      */
1635     function CbUserLogout (&$request, $userid) {
1636     ; // do nothing
1637     }
1638
1639 };
1640
1641
1642 /**
1643  * A class representing a clickable "button".
1644  *
1645  * In it's simplest (default) form, a "button" is just a link associated
1646  * with some sort of wiki-action.
1647  */
1648 class Button extends HtmlElement {
1649     /** Constructor
1650      *
1651      * @param $text string The text for the button.
1652      * @param $url string The url (href) for the button.
1653      * @param $class string The CSS class for the button.
1654      * @param $options array Additional attributes for the &lt;input&gt; tag.
1655      */
1656     function Button ($text, $url, $class=false, $options=false) {
1657         global $request;
1658         //php5 workaround
1659         if (check_php_version(5)) {
1660             $this->_init('a', array('href' => $url));
1661         } else {
1662             $this->__construct('a', array('href' => $url));
1663         }
1664         if ($class)
1665             $this->setAttr('class', $class);
1666         if ($request->getArg('frame'))
1667             $this->setAttr('target', '_top');
1668         if (!empty($options) and is_array($options)) {
1669             foreach ($options as $key => $val)
1670                 $this->setAttr($key, $val);
1671         }
1672         // Google honors this
1673         if (in_array(strtolower($text), array('edit','create','diff','pdf'))
1674             and !$request->_user->isAuthenticated())
1675             $this->setAttr('rel', 'nofollow');
1676         $this->pushContent($GLOBALS['WikiTheme']->maybeSplitWikiWord($text));
1677     }
1678
1679 };
1680
1681
1682 /**
1683  * A clickable image button.
1684  */
1685 class ImageButton extends Button {
1686     /** Constructor
1687      *
1688      * @param $text string The text for the button.
1689      * @param $url string The url (href) for the button.
1690      * @param $class string The CSS class for the button.
1691      * @param $img_url string URL for button's image.
1692      * @param $img_attr array Additional attributes for the &lt;img&gt; tag.
1693      */
1694     function ImageButton ($text, $url, $class, $img_url, $img_attr=false) {
1695         $this->__construct('a', array('href' => $url));
1696         if ($class)
1697             $this->setAttr('class', $class);
1698         // Google honors this
1699         if (in_array(strtolower($text), array('edit','create','diff','pdf'))
1700             and !$GLOBALS['request']->_user->isAuthenticated())
1701             $this->setAttr('rel', 'nofollow');
1702
1703         if (!is_array($img_attr))
1704             $img_attr = array();
1705         $img_attr['src'] = $img_url;
1706         $img_attr['alt'] = $text;
1707         $img_attr['class'] = 'wiki-button';
1708         $this->pushContent(HTML::img($img_attr));
1709     }
1710 };
1711
1712 /**
1713  * A class representing a form <samp>submit</samp> button.
1714  */
1715 class SubmitButton extends HtmlElement {
1716     /** Constructor
1717      *
1718      * @param $text string The text for the button.
1719      * @param $name string The name of the form field.
1720      * @param $class string The CSS class for the button.
1721      * @param $options array Additional attributes for the &lt;input&gt; tag.
1722      */
1723     function SubmitButton ($text, $name=false, $class=false, $options=false) {
1724         $this->__construct('input', array('type' => 'submit',
1725                                           'value' => $text));
1726         if ($name)
1727             $this->setAttr('name', $name);
1728         if ($class)
1729             $this->setAttr('class', $class);
1730         if (!empty($options)) {
1731             foreach ($options as $key => $val)
1732                 $this->setAttr($key, $val);
1733         }
1734     }
1735
1736 };
1737
1738
1739 /**
1740  * A class representing an image form <samp>submit</samp> button.
1741  */
1742 class SubmitImageButton extends SubmitButton {
1743     /** Constructor
1744      *
1745      * @param $text string The text for the button.
1746      * @param $name string The name of the form field.
1747      * @param $class string The CSS class for the button.
1748      * @param $img_url string URL for button's image.
1749      * @param $img_attr array Additional attributes for the &lt;img&gt; tag.
1750      */
1751     function SubmitImageButton ($text, $name=false, $class=false, $img_url, $img_attr=false) {
1752         $this->__construct('input', array('type'  => 'image',
1753                                           'src'   => $img_url,
1754                                           'value' => $text,
1755                                           'alt'   => $text));
1756         if ($name)
1757             $this->setAttr('name', $name);
1758         if ($class)
1759             $this->setAttr('class', $class);
1760         if (!empty($img_attr)) {
1761             foreach ($img_attr as $key => $val)
1762                 $this->setAttr($key, $val);
1763         }
1764     }
1765
1766 };
1767
1768 /**
1769  * A sidebar box with title and body, narrow fixed-width.
1770  * To represent abbrevated content of plugins, links or forms,
1771  * like "Getting Started", "Search", "Sarch Pagename",
1772  * "Login", "Menu", "Recent Changes", "Last comments", "Last Blogs"
1773  * "Calendar"
1774  * ... See http://tikiwiki.org/
1775  *
1776  * Usage:
1777  * sidebar.tmpl:
1778  *   $menu = SidebarBox("Menu",HTML::dl(HTML::dt(...))); $menu->format();
1779  *   $menu = PluginSidebarBox("RecentChanges",array('limit'=>10)); $menu->format();
1780  */
1781 class SidebarBox {
1782
1783     function SidebarBox($title, $body) {
1784         require_once('lib/WikiPlugin.php');
1785         $this->title = $title;
1786         $this->body = $body;
1787     }
1788     function format() {
1789         return WikiPlugin::makeBox($this->title, $this->body);
1790     }
1791 }
1792
1793 /**
1794  * A sidebar box for plugins.
1795  * Any plugin may provide a box($args=false, $request=false, $basepage=false)
1796  * method, with the help of WikiPlugin::makeBox()
1797  */
1798 class PluginSidebarBox extends SidebarBox {
1799
1800     var $_plugin, $_args = false, $_basepage = false;
1801
1802     function PluginSidebarBox($name, $args = false, $basepage = false) {
1803     require_once("lib/WikiPlugin.php");
1804
1805         $loader = new WikiPluginLoader();
1806         $plugin = $loader->getPlugin($name);
1807         if (!$plugin) {
1808             return $loader->_error(sprintf(_("Plugin %s: undefined"),
1809                                           $name));
1810         }/*
1811         if (!method_exists($plugin, 'box')) {
1812             return $loader->_error(sprintf(_("%s: has no box method"),
1813                                            get_class($plugin)));
1814         }*/
1815         $this->_plugin   =& $plugin;
1816         $this->_args     = $args ? $args : array();
1817         $this->_basepage = $basepage;
1818     }
1819
1820     function format($args = false) {
1821         return $this->_plugin->box($args ? array_merge($this->_args, $args) : $this->_args,
1822                                    $GLOBALS['request'],
1823                                    $this->_basepage);
1824     }
1825 }
1826
1827 // Various boxes which are no plugins
1828 class RelatedLinksBox extends SidebarBox {
1829     function RelatedLinksBox($title = false, $body = '', $limit = 20) {
1830         global $request;
1831         $this->title = $title ? $title : _("Related Links");
1832         $this->body = HTML($body);
1833         $page = $request->getPage($request->getArg('pagename'));
1834         $revision = $page->getCurrentRevision();
1835         $page_content = $revision->getTransformedContent();
1836         //$cache = &$page->_wikidb->_cache;
1837         $counter = 0;
1838         $sp = HTML::Raw('&middot; ');
1839         foreach ($page_content->getWikiPageLinks() as $link) {
1840             $linkto = $link['linkto'];
1841             if (!$request->_dbi->isWikiPage($linkto)) continue;
1842             $this->body->pushContent($sp, WikiLink($linkto), HTML::br());
1843             $counter++;
1844             if ($limit and $counter > $limit) continue;
1845         }
1846     }
1847 }
1848
1849 class RelatedExternalLinksBox extends SidebarBox {
1850     function RelatedExternalLinksBox($title = false, $body = '', $limit = 20) {
1851         global $request;
1852         $this->title = $title ? $title : _("External Links");
1853         $this->body = HTML($body);
1854         $page = $request->getPage($request->getArg('pagename'));
1855         $cache = &$page->_wikidb->_cache;
1856         $counter = 0;
1857         $sp = HTML::Raw('&middot; ');
1858         foreach ($cache->getWikiPageLinks() as $link) {
1859             $linkto = $link['linkto'];
1860             if ($linkto) {
1861                 $this->body->pushContent($sp, WikiLink($linkto), HTML::br());
1862                 $counter++;
1863                 if ($limit and $counter > $limit) continue;
1864             }
1865         }
1866     }
1867 }
1868
1869 function listAvailableThemes() {
1870     $available_themes = array();
1871     $dir_root = 'themes';
1872     if (defined('PHPWIKI_DIR'))
1873         $dir_root = PHPWIKI_DIR . "/$dir_root";
1874     $dir = dir($dir_root);
1875     if ($dir) {
1876         while($entry = $dir->read()) {
1877             if (is_dir($dir_root.'/'.$entry)
1878                 and file_exists($dir_root.'/'.$entry.'/themeinfo.php'))
1879             {
1880                 array_push($available_themes, $entry);
1881             }
1882         }
1883         $dir->close();
1884     }
1885     return $available_themes;
1886 }
1887
1888 function listAvailableLanguages() {
1889     $available_languages = array('en');
1890     $dir_root = 'locale';
1891     if (defined('PHPWIKI_DIR'))
1892         $dir_root = PHPWIKI_DIR . "/$dir_root";
1893     if ($dir = dir($dir_root)) {
1894         while($entry = $dir->read()) {
1895             if (is_dir($dir_root."/".$entry) and is_dir($dir_root.'/'.$entry.'/LC_MESSAGES'))
1896             {
1897                 array_push($available_languages, $entry);
1898             }
1899         }
1900         $dir->close();
1901     }
1902     return $available_languages;
1903 }
1904
1905 // Local Variables:
1906 // mode: php
1907 // tab-width: 8
1908 // c-basic-offset: 4
1909 // c-hanging-comment-ender-p: nil
1910 // indent-tabs-mode: nil
1911 // End:
1912 ?>