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