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