]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/EditToolbar.php
Add braces
[SourceForge/phpwiki.git] / lib / EditToolbar.php
1 <?php
2
3 /* Copyright 2004-2010 $ThePhpWikiProgrammingTeam
4  * Copyright 2008-2009 Marc-Etienne Vargenau, Alcatel-Lucent
5  *
6  * This file is part of PhpWiki.
7  *
8  * PhpWiki is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * PhpWiki is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License along
19  * with PhpWiki; if not, write to the Free Software Foundation, Inc.,
20  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21  */
22
23 /**
24  * EDIT Toolbar Initialization.
25  * The default/themes/toolbar.js is from Mediawiki, this PHP is written from scratch.
26  *
27  * Features:
28  * - save-preview and formatting buttons from mediawiki
29  * - Search&Replace from walterzorn.de
30  * - pageinsert popup by Reini Urban (TODO: should be a pulldown, use acdropdown)
31  */
32
33 class EditToolbar
34 {
35     function __construct()
36     {
37         global $WikiTheme;
38
39         $this->tokens = array();
40
41         //FIXME: enable Undo button for all other buttons also, not only the search/replace button
42         if (JS_SEARCHREPLACE) {
43             $this->tokens['JS_SEARCHREPLACE'] = 1;
44             $undo_btn = $WikiTheme->getImageURL("ed_undo.png");
45             $undo_d_btn = $WikiTheme->getImageURL("ed_undo_d.png");
46             // JS_SEARCHREPLACE from walterzorn.de
47             $js = Javascript("
48 uri_undo_btn   = '" . $undo_btn . "'
49 msg_undo_alt   = '" . _("Undo") . "'
50 uri_undo_d_btn = '" . $undo_d_btn . "'
51 msg_undo_d_alt = '" . _("Undo disabled") . "'
52 msg_do_undo    = '" . _("Operation undone") . "'
53 msg_replfound  = '" . _("Substring “\\1” found \\2 times. Replace with “\\3”?") . "'
54 msg_replnot    = '" . _("String “%s” not found.") . "'
55 msg_repl_title     = '" . _("Search & Replace") . "'
56 msg_repl_search    = '" . _("Search for") . "'
57 msg_repl_replace_with = '" . _("Replace with") . "'
58 msg_repl_ok        = '" . _("OK") . "'
59 msg_repl_close     = '" . _("Close") . "'
60 ");
61             if (empty($WikiTheme->_headers_printed)) {
62                 $WikiTheme->addMoreHeaders($js);
63                 $WikiTheme->addMoreAttr('body', "SearchReplace", " onload='define_f()'");
64             } else { // from an actionpage: WikiBlog, AddComment, WikiForum
65                 printXML($js);
66             }
67         } else {
68             $WikiTheme->addMoreAttr('body', "editfocus", "document.getElementById('edit-content]').editarea.focus()");
69         }
70
71         if (ENABLE_EDIT_TOOLBAR) {
72             $init = JavaScript("var data_path = '" . javascript_quote_string(DATA_PATH) . "';\n");
73             $js = JavaScript('', array('src' => $WikiTheme->_findData("toolbar.js")));
74             if (empty($WikiTheme->_headers_printed)) {
75                 $WikiTheme->addMoreHeaders($init);
76                 $WikiTheme->addMoreHeaders($js);
77             } else { // from an actionpage: WikiBlog, AddComment, WikiForum
78                 printXML($init);
79                 printXML($js);
80                 printXML(JavaScript('define_f()'));
81             }
82         }
83
84         require_once 'lib/WikiPluginCached.php';
85         $cache = WikiPluginCached::newCache();
86         $dbi = $GLOBALS['request']->getDbh();
87         // regenerate if number of pages changes (categories, pages, templates, images uploaded)
88         $key = $dbi->numPages();
89         $key .= '+categories+plugin' . (isBrowserSafari() ? '+safari' : '');
90         if (TOOLBAR_PAGELINK_PULLDOWN) {
91             $key .= "+pages";
92         }
93         if (TOOLBAR_TEMPLATE_PULLDOWN) {
94             $key .= "+templates_" . $dbi->getTimestamp();
95         }
96         if (TOOLBAR_IMAGE_PULLDOWN) {
97             if (file_exists(getUploadFilePath())) {
98                 $key .= "+images_" . filemtime(getUploadFilePath());
99             }
100         }
101         $id = $cache->generateId($key);
102         $content = $cache->get($id, 'toolbarcache');
103
104         if (!empty($content)) {
105             $this->tokens['EDIT_TOOLBAR'] =& $content;
106         } else {
107             $content = $this->_generate();
108             // regenerate buttons every 1 hr/6 hrs
109             $cache->save($id, $content, DEBUG ? '+3600' : '+21600', 'toolbarcache');
110             $this->tokens['EDIT_TOOLBAR'] =& $content;
111         }
112     }
113
114     public function getTokens()
115     {
116         return $this->tokens;
117     }
118
119     private function _generate()
120     {
121         global $WikiTheme, $request;
122
123         $toolbar = "document.writeln(\"<div class=\\\"edit-toolbar\\\" id=\\\"toolbar\\\">\");\n";
124
125         if (ENABLE_EDIT_TOOLBAR) {
126             $username = $request->_user->UserName();
127             if ((defined('FUSIONFORGE') and FUSIONFORGE) or DISABLE_MARKUP_WIKIWORD or (!isWikiWord($username))) {
128                 $username = '[[' . $username . ']]';
129             }
130             $signature = " ––" . $username . " " . CTime();
131             $toolarray = array(
132                 array(
133                     "image" => "ed_format_bold.png",
134                     "open" => "**",
135                     "close" => "**",
136                     "sample" => _("Bold text"),
137                     "title" => _("Bold text [alt-b]")),
138                 array("image" => "ed_format_italic.png",
139                     "open" => "//",
140                     "close" => "//",
141                     "sample" => _("Italic text"),
142                     "title" => _("Italic text [alt-i]")),
143                 array("image" => "ed_format_strike.png",
144                     "open" => "<s>",
145                     "close" => "</s>",
146                     "sample" => _("Strike-through text"),
147                     "title" => _("Strike")),
148                 array("image" => "ed_format_color.png",
149                     "open" => "%color=green% ",
150                     "close" => " %%",
151                     "sample" => _("Color text"),
152                     "title" => _("Color")),
153                 array("image" => "ed_pagelink.png",
154                     "open" => "[[",
155                     "close" => "]]",
156                     "sample" => _("PageName|optional label"),
157                     "title" => _("Link to page")),
158                 array("image" => "ed_link.png",
159                     "open" => "[[",
160                     "close" => "]]",
161                     "sample" => _("http://www.example.com|optional label"),
162                     "title" => _("External link (remember http:// prefix)")),
163                 array("image" => "ed_headline.png",
164                     "open" => "\\n== ",
165                     "close" => " ==\\n",
166                     "sample" => _("Headline text"),
167                     "title" => _("Level 1 headline")),
168                 array("image" => "ed_nowiki.png",
169                     "open" => "\\<verbatim\\>\\n",
170                     "close" => "\\n\\</verbatim\\>",
171                     "sample" => _("Insert non-formatted text here"),
172                     "title" => _("Ignore wiki formatting")),
173                 array("image" => "ed_sig.png",
174                     "open" => $signature,
175                     "close" => "",
176                     "sample" => "",
177                     "title" => _("Your signature")),
178                 array("image" => "ed_hr.png",
179                     "open" => "\\n----\\n",
180                     "close" => "",
181                     "sample" => "",
182                     "title" => _("Horizontal line")),
183                 array("image" => "ed_table.png",
184                     "open" => "\\n{| class=\"bordered\"\\n|+ This is the table caption\\n|-\\n! Header A !! Header B !! Header C\\n|-\\n| Cell A1 || Cell B1 || Cell C1\\n|-\\n| Cell A2 || Cell B2 || Cell C2\\n|-\\n| Cell A3 || Cell B3 || Cell C3\\n|}\\n",
185                     "close" => "",
186                     "sample" => "",
187                     "title" => _("Sample table")),
188                 array("image" => "ed_enumlist.png",
189                     "open" => "\\n# Item 1\\n# Item 2\\n# Item 3\\n",
190                     "close" => "",
191                     "sample" => "",
192                     "title" => _("Enumeration")),
193                 array("image" => "ed_list.png",
194                     "open" => "\\n* Item 1\\n* Item 2\\n* Item 3\\n",
195                     "close" => "",
196                     "sample" => "",
197                     "title" => _("List")),
198                 array("image" => "ed_toc.png",
199                     "open" => "<<CreateToc with_toclink||=1>>\\n",
200                     "close" => "",
201                     "sample" => "",
202                     "title" => _("Table of Contents")),
203                 array("image" => "ed_redirect.png",
204                     "open" => "<<RedirectTo page=\"",
205                     "close" => "\">>",
206                     "sample" => _("Page Name"),
207                     "title" => _("Redirect")),
208                 array("image" => "ed_templateplugin.png",
209                     "open" => "{{",
210                     "close" => "}}",
211                     "sample" => _("Template Name"),
212                     "title" => _("Template"))
213             );
214             $btn = new SubmitImageButton(_("Save"), "edit[save]", 'toolbar',
215                 $WikiTheme->getImageURL("ed_save.png"));
216             $btn->addTooltip(_("Save"));
217             $btn->setAccesskey("s");
218             $toolbar .= ('document.writeln("' . addslashes($btn->asXml()) . '");' . "\n");
219             // preview not supported yet on Wikiblog
220             if (empty($WikiTheme->_headers_printed)) {
221                 $btn = new SubmitImageButton(_("Preview"), "edit[preview]", 'toolbar',
222                     $WikiTheme->getImageURL("ed_preview.png"));
223                 $btn->addTooltip(_("Preview"));
224                 $btn->setAccesskey("p");
225                 $toolbar .= ('document.writeln("' . addslashes($btn->asXml()) . '");' . "\n");
226             }
227
228             foreach ($toolarray as $tool) {
229                 $image = $WikiTheme->getImageURL($tool["image"]);
230                 $open = $tool["open"];
231                 $close = $tool["close"];
232                 $sample = addslashes($tool["sample"]);
233                 // Note that we use the title both for the ALT tag and the TITLE tag of the image.
234                 // Older browsers show a "speedtip" type message only for ALT.
235                 // Ideally these should be different, realistically they
236                 // probably don't need to be.
237                 $tool = $WikiTheme->fixAccesskey($tool);
238                 $title = addslashes($tool["title"]);
239                 $toolbar .= ("addTagButton('$image','$title','$open','$close','$sample');\n");
240             }
241             /* Fails with Chrome */
242             if (!isBrowserSafari()) {
243                 $toolbar .= ("addInfobox('"
244                     . addslashes(_("Click a button to get an example text"))
245                     . "');\n");
246             }
247         }
248
249         if (JS_SEARCHREPLACE) {
250             $undo_d_btn = $WikiTheme->getImageURL("ed_undo_d.png");
251             //$redo_btn = $WikiTheme->getImageURL("ed_redo.png");
252             $sr_btn = $WikiTheme->getImageURL("ed_replace.png");
253             //TODO: generalize the UNDO button and fix it for Search & Replace
254             $sr_html = HTML(HTML::img
255                 (array('class' => "toolbar",
256                     'id' => "sr_undo",
257                     'src' => $undo_d_btn,
258                     'title' => _("Undo Search & Replace"),
259                     'alt' => _("Undo Search & Replace"),
260                     //'disabled'=>"disabled",   //non-XHTML conform
261                     //'onfocus' =>"if(this.blur && undo_buffer_index==0) this.blur()",
262                     'onclick' => "do_undo()")),
263                 HTML::img
264                 (array('class' => "toolbar",
265                     'src' => $sr_btn,
266                     'alt' => _("Search & Replace"),
267                     'title' => _("Search & Replace"),
268                     'onclick' => "replace()")));
269         } else {
270             $sr_html = '';
271         }
272
273         //TODO: Delegate this to run-time with showing an hidden input at the right, and do
274         // a separate moacdropdown and xmlrpc:titleSearch.
275
276         // Button to generate categories, display in extra window as popup and insert
277         $sr_html = HTML($sr_html, $this->categoriesPulldown());
278         // Button to generate plugins, display in extra window as popup and insert
279         $sr_html = HTML($sr_html, $this->pluginPulldown());
280
281         // Button to generate pagenames, display in extra window as popup and insert
282         if (TOOLBAR_PAGELINK_PULLDOWN)
283             $sr_html = HTML($sr_html, $this->pagesPulldown(TOOLBAR_PAGELINK_PULLDOWN));
284         // Button to insert from an template, display pagename in extra window as popup and insert
285         if (TOOLBAR_TEMPLATE_PULLDOWN)
286             $sr_html = HTML($sr_html, $this->templatePulldown(TOOLBAR_TEMPLATE_PULLDOWN));
287
288         // Button to add images, display in extra window as popup and insert
289         if (TOOLBAR_IMAGE_PULLDOWN)
290             $sr_html = HTML($sr_html, $this->imagePulldown());
291
292         // don't use document.write for replace, otherwise self.opener is not defined.
293         $toolbar_end = "document.writeln(\"</div>\");";
294         if ($sr_html)
295             return HTML(Javascript($toolbar),
296                 "\n", $sr_html, "\n",
297                 Javascript($toolbar_end));
298         else
299             return HTML(Javascript($toolbar . $toolbar_end));
300     }
301
302     //result is cached
303     private function categoriesPulldown()
304     {
305         global $WikiTheme;
306
307         require_once 'lib/TextSearchQuery.php';
308         $dbi =& $GLOBALS['request']->_dbi;
309         // KEYWORDS formerly known as $KeywordLinkRegexp
310         $pages = $dbi->titleSearch(new TextSearchQuery(KEYWORDS, true));
311         if ($pages) {
312             $categories = array();
313             while ($p = $pages->next()) {
314                 $page = $p->getName();
315                 if ((defined('FUSIONFORGE') and FUSIONFORGE)) {
316                     $categories[] = "['$page', '%0A----%0A%5B%5B" . $page . "%5D%5D']";
317                 } elseif (DISABLE_MARKUP_WIKIWORD or (!isWikiWord($page))) {
318                     $categories[] = "['$page', '%0A%5B" . $page . "%5D']";
319                 } else {
320                     $categories[] = "['$page', '%0A" . $page . "']";
321                 }
322             }
323             if (!$categories) return '';
324             // Ensure this to be inserted at the very end. Hence we added the id to the function.
325             $more_buttons = HTML::img(array('class' => "toolbar",
326                 'id' => 'tb-categories',
327                 'src' => $WikiTheme->getImageURL("ed_category.png"),
328                 'title' => _("Insert Categories"),
329                 'alt' => "Insert Categories", // to detect this at js
330                 'onclick' => "showPulldown('" .
331                     _("Insert Categories")
332                     . "',[" . join(",", $categories) . "],'"
333                     . _("Insert") . "','"
334                     . _("Close") . "','tb-categories')"));
335             return HTML("\n", $more_buttons);
336         }
337         return '';
338     }
339
340     // result is cached. Esp. the args are expensive
341     private function pluginPulldown()
342     {
343         global $WikiTheme;
344         global $AllAllowedPlugins;
345
346         $plugin_dir = 'lib/plugin';
347         if (defined('PHPWIKI_DIR'))
348             $plugin_dir = PHPWIKI_DIR . "/$plugin_dir";
349         $pd = new fileSet($plugin_dir, '*.php');
350         $plugins = $pd->getFiles();
351         unset($pd);
352         sort($plugins);
353         if (!empty($plugins)) {
354             $plugin_js = '';
355             require_once 'lib/WikiPlugin.php';
356             $w = new WikiPluginLoader();
357             foreach ($plugins as $plugin) {
358                 $pluginName = str_replace(".php", "", $plugin);
359                 if (in_array($pluginName, $AllAllowedPlugins)) {
360                     $p = $w->getPlugin($pluginName, false); // second arg?
361                     // trap php files which aren't WikiPlugin~s
362                     if (strtolower(substr(get_parent_class($p), 0, 10)) == 'wikiplugin') {
363                         $plugin_args = '';
364                         $desc = $p->getArgumentsDescription();
365                         $src = array("\n", '"', "'", '|', '[', ']', '\\');
366                         $replace = array('%0A', '%22', '%27', '%7C', '%5B', '%5D', '%5C');
367                         $desc = str_replace("<br />", ' ', $desc->asXML());
368                         if ($desc)
369                             $plugin_args = ' ' . str_replace($src, $replace, $desc);
370                         $toinsert = "%0A<<" . $pluginName . $plugin_args . ">>"; // args?
371                         $plugin_js .= ",['$pluginName','$toinsert']";
372                     }
373                 }
374             }
375             $plugin_js = substr($plugin_js, 1);
376             $more_buttons = HTML::img(array('class' => "toolbar",
377                 'id' => 'tb-plugins',
378                 'src' => $WikiTheme->getImageURL("ed_plugins.png"),
379                 'title' => _("Insert Plugin"),
380                 'alt' => _("Insert Plugin"),
381                 'onclick' => "showPulldown('" .
382                     _("Insert Plugin")
383                     . "',[" . $plugin_js . "],'"
384                     . _("Insert") . "','"
385                     . _("Close") . "','tb-plugins')"));
386             return HTML("\n", $more_buttons);
387         }
388         return '';
389     }
390
391     // result is cached. Esp. the args are expensive
392     private function pagesPulldown($query, $case_exact = false, $regex = 'auto')
393     {
394         require_once 'lib/TextSearchQuery.php';
395         $dbi =& $GLOBALS['request']->_dbi;
396         $page_iter = $dbi->titleSearch(new TextSearchQuery($query, $case_exact, $regex));
397         if ($page_iter->count() > 0) {
398             global $WikiTheme;
399             $pages = array();
400             while ($p = $page_iter->next()) {
401                 $page = $p->getName();
402                 if (DISABLE_MARKUP_WIKIWORD or (!isWikiWord($page)))
403                     $pages[] = "['$page', '%5B" . $page . "%5D']";
404                 else
405                     $pages[] = "['$page', '$page']";
406             }
407             return HTML("\n", HTML::img(array('class' => "toolbar",
408                 'id' => 'tb-pages',
409                 'src' => $WikiTheme->getImageURL("ed_pages.png"),
410                 'title' => _("Insert PageLink"),
411                 'alt' => _("Insert PageLink"),
412                 'onclick' => "showPulldown('" .
413                     _("Insert PageLink")
414                     . "',[" . join(",", $pages) . "],'"
415                     . _("Insert") . "','"
416                     . _("Close") . "','tb-pages')")));
417         }
418         return '';
419     }
420
421     // result is cached. Esp. the args are expensive
422     private function imagePulldown()
423     {
424         global $WikiTheme, $request;
425
426         $image_dir = getUploadFilePath();
427         $pd = new imageOrVideoSet($image_dir, '*');
428         $images = $pd->getFiles();
429         unset($pd);
430         if (UPLOAD_USERDIR) {
431             $image_dir .= "/" . $request->_user->_userid;
432             $pd = new imageOrVideoSet($image_dir, '*');
433             $images = array_merge($images, $pd->getFiles());
434             unset($pd);
435         }
436         sort($images);
437         if (!empty($images)) {
438             $image_js = '';
439             foreach ($images as $image) {
440                 $image_js .= ",['$image','{{" . $image . "}}']";
441             }
442             $image_js = substr($image_js, 1);
443             $more_buttons = HTML::img(array('class' => "toolbar",
444                 'id' => 'tb-images',
445                 'src' => $WikiTheme->getImageURL("ed_image.png"),
446                 'title' => _("Insert Image or Video"),
447                 'alt' => _("Insert Image or Video"),
448                 'onclick' => "showPulldown('" .
449                     _("Insert Image or Video")
450                     . "',[" . $image_js . "],'"
451                     . _("Insert") . "','"
452                     . _("Close") . "','tb-images')"));
453             return HTML("\n", $more_buttons);
454         }
455         return '';
456     }
457
458     // result is cached. Esp. the args are expensive
459     // FIXME!
460     private function templatePulldown($query, $case_exact = false, $regex = 'auto')
461     {
462         global $request;
463         require_once 'lib/TextSearchQuery.php';
464         $dbi =& $request->_dbi;
465         $page_iter = $dbi->titleSearch(new TextSearchQuery($query, $case_exact, $regex));
466         if ($page_iter->count()) {
467             global $WikiTheme;
468             $pages_js = '';
469             while ($p = $page_iter->next()) {
470                 $rev = $p->getCurrentRevision();
471                 $toinsert = str_replace(array("\n", '"'), array('_nl', '_quot'), $rev->_get_content());
472                 //$toinsert = str_replace("\n",'\n',addslashes($rev->_get_content()));
473                 $pages_js .= ",['" . $p->getName() . "','_nl$toinsert']";
474             }
475             $pages_js = substr($pages_js, 1);
476             if (!empty($pages_js))
477                 return HTML("\n", HTML::img
478                 (array('class' => "toolbar",
479                     'id' => 'tb-templates',
480                     'src' => $WikiTheme->getImageURL("ed_template.png"),
481                     'title' => _("Insert Template"),
482                     'alt' => _("Insert Template"),
483                     'onclick' => "showPulldown('" .
484                         _("Insert Template")
485                         . "',[" . $pages_js . "],'"
486                         . _("Insert") . "','"
487                         . _("Close") . "','tb-templates')")));
488         }
489         return '';
490     }
491
492 }
493
494 // Local Variables:
495 // mode: php
496 // tab-width: 8
497 // c-basic-offset: 4
498 // c-hanging-comment-ender-p: nil
499 // indent-tabs-mode: nil
500 // End: