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