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