]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/EditToolbar.php
for the previous pcre short-cut
[SourceForge/phpwiki.git] / lib / EditToolbar.php
1 <?php
2 rcs_id('$Id: EditToolbar.php,v 1.15 2008-04-02 18:07:05 vargenau Exp $');
3
4 /**
5  * EDIT Toolbar Initialization.
6  * The default/themes/toolbar.js is from mediawiki, this php is written from scratch.
7  *
8  * Features: 
9  * - save-preview and formatting buttons from mediawiki
10  * - Search&Replace from walterzorn.de
11  * - pageinsert popup by Reini Urban (TODO: should be a pulldown, use acdropdown))
12  */
13
14 class EditToolbar {
15
16     function EditToolbar() {
17         global $WikiTheme;
18
19         $this->tokens = array();
20
21         //FIXME: enable Undo button for all other buttons also, not only the search/replace button
22         if (JS_SEARCHREPLACE) {
23             $this->tokens['JS_SEARCHREPLACE'] = 1;
24             $undo_btn = $WikiTheme->getImageURL("ed_undo.png"); 
25             $undo_d_btn = $WikiTheme->getImageURL("ed_undo_d.png"); 
26             // JS_SEARCHREPLACE from walterzorn.de
27             $js = Javascript("
28 uri_undo_btn   = '".$undo_btn."'
29 msg_undo_alt   = '"._("Undo")."'
30 uri_undo_d_btn = '".$undo_d_btn."'
31 msg_undo_d_alt = '"._("Undo disabled")."'
32 msg_do_undo    = '"._("Operation undone")."'
33 msg_replfound  = '"._("Substring \"\\1\" found \\2 times. Replace with \"\\3\"?")."'
34 msg_replnot    = '"._("String \"%s\" not found.")."'
35 msg_repl_title     = '"._("Search & Replace")."'
36 msg_repl_search    = '"._("Search for")."'
37 msg_repl_replace_with = '"._("Replace with")."'
38 msg_repl_ok        = '"._("OK")."'
39 msg_repl_close     = '"._("Close")."'
40 ");
41             if (empty($WikiTheme->_headers_printed)) {
42                 $WikiTheme->addMoreHeaders($js);
43                 $WikiTheme->addMoreAttr('body', "SearchReplace"," onload='define_f()'");
44             } else { // from an actionpage: WikiBlog, AddComment, WikiForum
45                 printXML($js);
46             }
47         } else {
48             $WikiTheme->addMoreAttr('body', "editfocus", "document.getElementById('edit-content]').editarea.focus()");
49         }
50     
51         if (ENABLE_EDIT_TOOLBAR) {
52             $js = JavaScript('',array('src' => $WikiTheme->_findData("toolbar.js")));
53             if (empty($WikiTheme->_headers_printed))
54                 $WikiTheme->addMoreHeaders($js);
55             else { // from an actionpage: WikiBlog, AddComment, WikiForum
56                 printXML($js);
57                 printXML(JavaScript('define_f()'));
58             }
59         }
60
61         require_once("lib/WikiPluginCached.php");
62         $cache = WikiPluginCached::newCache();
63         $dbi = $GLOBALS['request']->getDbh();
64         // regenerate if number of pages changes (categories, pages, templates)
65         $key = $dbi->numPages();
66         $key .= '+categories+plugin';
67         if (TOOLBAR_PAGELINK_PULLDOWN) {
68             $key .= "+pages";
69         }
70         if (TOOLBAR_TEMPLATE_PULLDOWN) {
71             $key .= "+templates_" . $dbi->getTimestamp();
72         }
73         $id = $cache->generateId($key);
74         $content = $cache->get($id, 'toolbarcache');
75
76         if (!empty($content)) {
77             $this->tokens['EDIT_TOOLBAR'] =& $content;
78         } else {
79             $content = $this->_generate();
80             // regenerate buttons every 3600 seconds
81             $cache->save($id, $content, '+3600', 'toolbarcache'); 
82             $this->tokens['EDIT_TOOLBAR'] =& $content;
83         }
84     }
85
86     function getTokens () {
87         return $this->tokens;
88     }
89
90     function _generate () {
91         global $WikiTheme, $request;
92
93         $toolbar = "document.writeln(\"<div class=\\\"edit-toolbar\\\" id=\\\"toolbar\\\">\");\n";
94         $accessKeyPrefix = $WikiTheme->tooltipAccessKeyPrefix();
95
96         if (ENABLE_EDIT_TOOLBAR) {
97             $username = $request->_user->UserName();
98             if (DISABLE_MARKUP_WIKIWORD or (!isWikiWord($username))) {
99                 $username = '['.$username.']';
100             }
101             $signature = " --".$username." ".CTime();
102             $toolarray = array(
103                            array(
104                                  "image"=>"ed_format_bold.png",
105                                  "open"=>"<strong>",
106                                  "close"=>"</strong>",
107                                  "sample"=>_("Bold text"),
108                                  "title"=>_("Bold text [alt-b]")),
109                            array("image"=>"ed_format_italic.png",
110                                  "open"=>"<em>",
111                                  "close"=>"</em>",
112                                  "sample"=>_("Italic text"),
113                                  "title"=>_("Italic text [alt-i]")),
114                            array("image"=>"ed_format_strike.png",
115                                  "open"=>"<s>",
116                                  "close"=>"</s>",
117                                  "sample"=>_("Strike-through text"),
118                                  "title"=>_("Strike")),
119                            array("image"=>"ed_format_color.png",
120                                  "open"=>"%color=green% ",
121                                  "close"=>" %%",
122                                  "sample"=>_("Color text"),
123                                  "title"=>_("Color")),
124                            array("image"=>"ed_pagelink.png",
125                                  "open"=>"[",
126                                  "close"=>"]",
127                                  "sample"=>_("optional label | PageName"),
128                                  "title"=>_("Link to page")),
129                            array("image"=>"ed_link.png",
130                                  "open"=>"[",
131                                  "close"=>"]",
132                                  "sample"=>_("optional label | http://www.example.com"),
133                                  "title"=>_("External link (remember http:// prefix)")),
134                            array("image"=>"ed_headline.png",
135                                  "open"=>"\\n!!! ",
136                                  "close"=>"\\n",
137                                  "sample"=>_("Headline text"),
138                                  "title"=>_("Level 1 headline")),
139                            array("image"=>"ed_image.png",
140                                  "open"=>"[ ",
141                                  "close"=>" ]",
142                                  "sample"=>_("Example.jpg"),
143                                  "title"=>_("Embedded image")),
144                            array("image"=>"ed_nowiki.png",
145                                  "open"=>"\\<verbatim\\>\\n",
146                                  "close"=>"\\n\\</verbatim\\>",
147                                  "sample"=>_("Insert non-formatted text here"),
148                                  "title"=>_("Ignore wiki formatting")),
149                            array("image"=>"ed_sig.png",
150                                  "open" => $signature,
151                                  "close" => "",
152                                  "sample"=>"",
153                                  "title"=>_("Your signature")),
154                            array("image"=>"ed_hr.png",
155                                  "open"=>"\\n----\\n",
156                                  "close"=>"",
157                                  "sample"=>"",
158                                  "title"=>_("Horizontal line")),
159                            array("image"=>"ed_table.png",
160                                  "open"=>"\\n{| class=\"bordered\"\\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",
161                                  "close"=>"",
162                                  "sample"=>"",
163                                  "title"=>_("Sample table")),
164                            array("image"=>"ed_enumlist.png",
165                                  "open"=>"\\n# Item 1\\n# Item 2\\n# Item 3\\n",
166                                  "close"=>"",
167                                  "sample"=>"",
168                                  "title"=>_("Enumeration")),
169                            array("image"=>"ed_list.png",
170                                  "open"=>"\\n* Item 1\\n* Item 2\\n* Item 3\\n",
171                                  "close"=>"",
172                                  "sample"=>"",
173                                  "title"=>_("List")),
174                            array("image"=>"ed_toc.png",
175                                  "open"=>"<?plugin CreateToc with_toclink||=1 headers||=1,2,3 liststyle||=ol?>\\n",
176                                  "close"=>"",
177                                  "sample"=>"",
178                                  "title"=>_("Table of Contents")),
179                            array("image"=>"ed_redirect.png",
180                                  "open"=>"<?plugin RedirectTo page=\"",
181                                  "close"=>"\" ?>",
182                                  "sample"=>_("Page Name"),
183                                  "title"=>_("Redirect")),
184                            array("image"=>"ed_templateplugin.png",
185                                  "open"=>"{{",
186                                  "close"=>"}}",
187                                  "sample"=>_("template name"),
188                                  "title"=>_("Template"))
189                            );
190             $btn = new SubmitImageButton(_("Save"), "edit[save]", 'toolbar', 
191                                          $WikiTheme->getImageURL("ed_save.png"));
192             $btn->addTooltip(_("Save"));
193             $btn->setAccesskey("s");
194             $toolbar .= ('document.writeln("'.addslashes($btn->asXml()).'");'."\n");
195             // preview not supported yet on Wikiblog
196             if (empty($WikiTheme->_headers_printed)) {
197                 $btn = new SubmitImageButton(_("Preview"), "edit[preview]", 'toolbar', 
198                                              $WikiTheme->getImageURL("ed_preview.png"));
199                 $btn->addTooltip(_("Preview"));
200                 $btn->setAccesskey("p");
201                 $toolbar .= ('document.writeln("'.addslashes($btn->asXml()).'");'."\n");
202             }
203     
204             foreach ($toolarray as $tool) {
205                 global $WikiTheme;
206                 $image = $WikiTheme->getImageURL($tool["image"]);
207                 $open  = $tool["open"];
208                 $close = $tool["close"];
209                 $sample = addslashes( $tool["sample"] );
210                 // Note that we use the title both for the ALT tag and the TITLE tag of the image.
211                 // Older browsers show a "speedtip" type message only for ALT.
212                 // Ideally these should be different, realistically they
213                 // probably don't need to be.
214                 $tool = $WikiTheme->fixAccesskey($tool);
215                 $title = addslashes( $tool["title"] );
216                 $toolbar .= ("addTagButton('$image','$title','$open','$close','$sample');\n");
217             }
218             $toolbar .= ("addInfobox('" 
219                          . addslashes( _("Click a button to get an example text") ) 
220                          . "');\n");
221         }
222
223         if (JS_SEARCHREPLACE) {
224             $undo_d_btn = $WikiTheme->getImageURL("ed_undo_d.png"); 
225             //$redo_btn = $WikiTheme->getImageURL("ed_redo.png");
226             $sr_btn   = $WikiTheme->getImageURL("ed_replace.png");
227             //TODO: generalize the UNDO button and fix it for Search & Replace
228             $sr_html = HTML(HTML::img
229                             (array('class'=>"toolbar",
230                                    'id'   =>"sr_undo",
231                                    'src'  =>$undo_d_btn,
232                                    'title'=>_("Undo Search & Replace"),
233                                    'alt'  =>_("Undo Search & Replace"),
234                                    //'disabled'=>"disabled",   //non-XHTML conform
235                                    //'onfocus' =>"if(this.blur && undo_buffer_index==0) this.blur()",
236                                    'onclick' =>"do_undo()")),
237                             HTML::img
238                             (array('class'=>"toolbar",
239                                    'src'  => $sr_btn,
240                                    'alt'  =>_("Search & Replace"),
241                                    'title'=>_("Search & Replace")." [$accessKeyPrefix-h]",
242                                    'accesskey' => 'h',
243                                    'onclick'=>"replace()")));
244         } else {
245             $sr_html = '';
246         }
247
248         //TODO: Delegate this to run-time with showing an hidden input at the right, and do 
249         // a seperate moacdropdown and xmlrpc:titleSearch.
250
251         // Button to generate categories, display in extra window as popup and insert
252         $sr_html = HTML($sr_html, $this->categoriesPulldown());
253         // Button to generate plugins, display in extra window as popup and insert
254         $sr_html = HTML($sr_html, $this->pluginPulldown());
255
256         // Button to generate pagenames, display in extra window as popup and insert
257         if (TOOLBAR_PAGELINK_PULLDOWN)
258             $sr_html = HTML($sr_html, $this->pagesPulldown(TOOLBAR_PAGELINK_PULLDOWN));
259         // Button to insert from an template, display pagename in extra window as popup and insert
260         if (TOOLBAR_TEMPLATE_PULLDOWN)
261             $sr_html = HTML($sr_html, $this->templatePulldown(TOOLBAR_TEMPLATE_PULLDOWN));
262
263         // don't use document.write for replace, otherwise self.opener is not defined.
264         $toolbar_end = "document.writeln(\"</div>\");";
265         if ($sr_html)
266             return HTML(Javascript($toolbar),
267                         "\n", $sr_html, "\n",
268                         Javascript($toolbar_end));
269         else
270             return HTML(Javascript($toolbar . $toolbar_end));
271     }
272
273     //result is cached
274     function categoriesPulldown() {
275         global $WikiTheme;
276
277         require_once('lib/TextSearchQuery.php');
278         $dbi =& $GLOBALS['request']->_dbi;
279         // KEYWORDS formerly known as $KeywordLinkRegexp
280         $pages = $dbi->titleSearch(new TextSearchQuery(KEYWORDS, true));
281         if ($pages) {
282             $categories = array();
283             while ($p = $pages->next()) {
284                 $page = $p->getName();
285                 if (DISABLE_MARKUP_WIKIWORD or (!isWikiWord($page)))
286                     $categories[] = "['$page', '%5B".$page."%5D']";
287                 else
288                     $categories[] = "['$page', '$page']";
289             }
290             if (!$categories) return '';
291             // Ensure this to be inserted at the very end. Hence we added the id to the function.
292             $more_buttons = HTML::img(array('class'=> "toolbar",
293                                             'id' => 'tb-categories',
294                                             'src'  => $WikiTheme->getImageURL("ed_category.png"),
295                                             'title'=>_("AddCategory"),
296                                             'alt'=>"AddCategory", // to detect this at js
297                                             'onclick'=>"showPulldown('".
298                                             _("Insert Categories (double-click)")
299                                             ."',[".join(",",$categories)."],'"
300                                             ._("Insert")."','"
301                                             ._("Close")."','tb-categories')"));
302             return HTML("\n", $more_buttons);
303         }
304         return '';
305     }
306
307     // result is cached. Esp. the args are expensive
308     function pluginPulldown() {
309         global $WikiTheme;
310
311         $plugin_dir = 'lib/plugin';
312         if (defined('PHPWIKI_DIR'))
313             $plugin_dir = PHPWIKI_DIR . "/$plugin_dir";
314         $pd = new fileSet($plugin_dir, '*.php');
315         $plugins = $pd->getFiles();
316         unset($pd);
317         sort($plugins);
318         if (!empty($plugins)) {
319             $plugin_js = '';
320             require_once("lib/WikiPlugin.php");
321             $w = new WikiPluginLoader;
322             foreach ($plugins as $plugin) {
323                 $pluginName = str_replace(".php", "", $plugin);
324                 $p = $w->getPlugin($pluginName, false); // second arg?
325                 // trap php files which aren't WikiPlugin~s
326                 if (strtolower(substr(get_parent_class($p), 0, 10)) == 'wikiplugin') {
327                     $plugin_args = '';
328                     $desc = $p->getArgumentsDescription();
329                     $src = array("\n",'"',"'",'|','[',']','\\');
330                     $replace = array('%0A','%22','%27','%7C','%5B','%5D','%5C');
331                     $desc = str_replace("<br />",' ',$desc->asXML());
332                     if ($desc)
333                         $plugin_args = ' '.str_replace($src, $replace, $desc);
334                     $toinsert = "%0A<?plugin ".$pluginName.$plugin_args."?>"; // args?
335                     $plugin_js .= ",['$pluginName','$toinsert']";
336                 }
337             }
338             $plugin_js = substr($plugin_js, 1);
339             $more_buttons = HTML::img(array('class'=>"toolbar",
340                                             'id' => 'tb-plugins',
341                                             'src'  => $WikiTheme->getImageURL("ed_plugins.png"),
342                                             'title'=>_("AddPlugin"),
343                                             'alt'=>_("AddPlugin"),
344                                             'onclick'=>"showPulldown('".
345                                             _("Insert Plugin (double-click)")
346                                             ."',[".$plugin_js."],'"
347                                             ._("Insert")."','"
348                                             ._("Close")."','tb-plugins')"));
349             return HTML("\n", $more_buttons);
350         }
351         return '';
352     }
353
354     // result is cached. Esp. the args are expensive
355     function pagesPulldown($query, $case_exact=false, $regex='auto') {
356         require_once('lib/TextSearchQuery.php');
357         $dbi =& $GLOBALS['request']->_dbi;
358         $page_iter = $dbi->titleSearch(new TextSearchQuery($query, $case_exact, $regex));
359         if ($page_iter->count()) {
360             global $WikiTheme;
361             $pages = array();
362             while ($p = $page_iter->next()) {
363                 $page = $p->getName();
364                 if (DISABLE_MARKUP_WIKIWORD or (!isWikiWord($page)))
365                     $pages[] = "['$page', '%5B".$page."%5D']";
366                 else
367                     $pages[] = "['$page', '$page']";
368             }
369             return HTML("\n", HTML::img(array('class'=>"toolbar",
370                                               'id' => 'tb-pages',
371                                               'src'  => $WikiTheme->getImageURL("ed_pages.png"),
372                                               'title'=>_("AddPageLink"),
373                                               'alt'=>_("AddPageLink"),
374                                               'onclick'=>"showPulldown('".
375                                               _("Insert PageLink (double-click)")
376                                               ."',[".join(",",$pages)."],'"
377                                               ._("Insert")."','"
378                                               ._("Close")."','tb-pages')")));
379         }
380         return '';
381     }
382
383     // result is cached. Esp. the args are expensive
384     // FIXME!
385     function templatePulldown($query, $case_exact=false, $regex='auto') {
386         global $request;
387         require_once('lib/TextSearchQuery.php');
388         $dbi =& $request->_dbi;
389         $page_iter = $dbi->titleSearch(new TextSearchQuery($query, $case_exact, $regex));
390         $count = 0;
391         if ($page_iter->count()) {
392             global $WikiTheme;
393             $pages_js = '';
394             while ($p = $page_iter->next()) {
395                 $rev = $p->getCurrentRevision();
396                 $toinsert = str_replace(array("\n",'"'), array('_nl','_quot'), $rev->_get_content());
397                 //$toinsert = str_replace("\n",'\n',addslashes($rev->_get_content()));
398                 $pages_js .= ",['".$p->getName()."','_nl$toinsert']";
399             }
400             $pages_js = substr($pages_js, 1);
401             if (!empty($pages_js))
402                 return HTML("\n", HTML::img
403                             (array('class'=>"toolbar",
404                                    'id' => 'tb-templates',
405                                    'src'  => $WikiTheme->getImageURL("ed_template.png"),
406                                    'title'=>_("AddTemplate"),
407                                    'alt'=>_("AddTemplate"),
408                                    'onclick'=>"showPulldown('".
409                                    _("Insert Template (double-click)")
410                                    ."',[".$pages_js."],'"
411                                    ._("Insert")."','"
412                                    ._("Close")."','tb-templates')")));
413         }
414         return '';
415     }
416
417 }
418
419 /*
420 $Log: not supported by cvs2svn $
421 Revision 1.14  2008/02/19 19:07:23  vargenau
422 More icons for toolbar
423
424 Revision 1.13  2007/07/14 12:03:12  rurban
425 just aesthetics
426
427 Revision 1.12  2007/06/02 18:23:36  rurban
428 Added accesskeys
429
430 Revision 1.11  2007/02/17 14:16:21  rurban
431 move define_f after toolbar.js
432
433 Revision 1.10  2007/01/07 18:42:19  rurban
434 Improve id: edit: to edit-. Move search&replace js from body (defined in EditToolbar) to the toolbar.js. Support actionpages. Add tb-name argument to showPulldown
435
436 Revision 1.9  2007/01/02 13:18:26  rurban
437 fix id to edit:content
438
439 Revision 1.8  2006/12/22 00:17:06  rurban
440 add time to signature
441
442 Revision 1.7  2006/09/06 05:45:26  rurban
443 use html tags for emphasis. workaround ^* problem
444
445 Revision 1.6  2006/08/30 05:25:40  rurban
446 Handle inserting DISABLE_MARKUP_WIKIWORD and non wikiword links.
447
448 Revision 1.5  2005/10/29 14:16:17  rurban
449 fix typo
450
451 Revision 1.4  2005/09/29 23:07:58  rurban
452 cache toolbar
453
454 Revision 1.3  2005/09/26 06:25:50  rurban
455 EditToolbar enhancements by Thomas Harding: add plugins args, properly quote control chars. added plugin method getArgumentsDescription to override the default description string
456
457 Revision 1.3  2005/09/22 13:40:00 tharding
458 add modules arguments
459  
460 Revision 1.2  2005/05/06 18:43:41  rurban
461 add AddTemplate EditToolbar icon
462
463 Revision 1.1  2005/01/25 15:19:09  rurban
464 extract Toolbar code from editpage.php
465 */
466
467 // Local Variables:
468 // mode: php
469 // tab-width: 8
470 // c-basic-offset: 4
471 // c-hanging-comment-ender-p: nil
472 // indent-tabs-mode: nil
473 // End:
474 ?>