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