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