]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/WikiPlugin.php
ModeratePage part1: change status
[SourceForge/phpwiki.git] / lib / WikiPlugin.php
1 <?php //-*-php-*-
2 rcs_id('$Id: WikiPlugin.php,v 1.53 2004-11-19 19:22:03 rurban Exp $');
3
4 class WikiPlugin
5 {
6     function getDefaultArguments() {
7         return array('description' => $this->getDescription());
8     }
9
10     /** Does the plugin manage its own HTTP validators?
11      *
12      * This should be overwritten by (some) individual plugins.
13      *
14      * If the output of the plugin is static, depending only
15      * on the plugin arguments, query arguments and contents
16      * of the current page, this can (and should) return true.
17      *
18      * If the plugin can deduce a modification time, or equivalent
19      * sort of tag for it's content, then the plugin should
20      * call $request->appendValidators() with appropriate arguments,
21      * and should override this method to return true.
22      *
23      * When in doubt, the safe answer here is false.
24      * Unfortunately, returning false here will most likely make
25      * any page which invokes the plugin uncacheable (by HTTP proxies
26      * or browsers).
27      */
28     function managesValidators() {
29         return false;
30     }
31     
32     // FIXME: args?
33     function run ($dbi, $argstr, &$request, $basepage) {
34         trigger_error("WikiPlugin::run: pure virtual function",
35                       E_USER_ERROR);
36     }
37
38     /** Get wiki-pages linked to by plugin invocation.
39      *
40      * A plugin may override this method to add pages to the
41      * link database for the invoking page.
42      *
43      * For example, the IncludePage plugin should override this so
44      * that the including page shows up in the backlinks list for the
45      * included page.
46      *
47      * Not all plugins which generate links to wiki-pages need list
48      * those pages here.
49      *
50      * Note also that currently the links are calculated at page save
51      * time, so only static page links (e.g. those dependent on the PI
52      * args, not the rest of the wikidb state or any request query args)
53      * will work correctly here.
54      *
55      * @param string $argstr The plugin argument string.
56      * @param string $basepage The pagename the plugin is invoked from.
57      * @return array List of pagenames linked to (or false).
58      */
59     function getWikiPageLinks ($argstr, $basepage) {
60         return false;
61     }
62     
63     /**
64      * Get name of plugin.
65      *
66      * This is used (by default) by getDefaultLinkArguments and
67      * getDefaultFormArguments to compute the default link/form
68      * targets.
69      *
70      * If you want to gettextify the name (probably a good idea),
71      * override this method in your plugin class, like:
72      * <pre>
73      *   function getName() { return _("MyPlugin"); }
74      * </pre>
75      *
76      * @return string plugin name/target.
77      */
78     function getName() {
79         return preg_replace('/^.*_/', '',  get_class($this));
80     }
81
82     function getDescription() {
83         return $this->getName();
84     }
85     
86     // plugins should override this with the commented-out code
87     function getVersion() {
88         return _("n/a");
89         //return preg_replace("/[Revision: $]/", '',
90         //                    "\$Revision: 1.53 $");
91     }
92
93     function getArgs($argstr, $request=false, $defaults = false) {
94         if ($defaults === false) {
95             $defaults = $this->getDefaultArguments();
96         }
97         //Fixme: on POST argstr is empty
98         list ($argstr_args, $argstr_defaults) = $this->parseArgStr($argstr);
99         $args = array();
100         if (!empty($defaults))
101           foreach ($defaults as $arg => $default_val) {
102             if (isset($argstr_args[$arg])) {
103                 $args[$arg] = $argstr_args[$arg];
104             } elseif ( $request and ($argval = $request->getArg($arg)) !== false ) {
105                 $args[$arg] = $argval;
106             } elseif (isset($argstr_defaults[$arg])) {
107                 $args[$arg] = (string) $argstr_defaults[$arg];
108             } else {
109                 $args[$arg] = $default_val;
110             }
111             // expand [arg]
112             if ($request and is_string($args[$arg]) and strstr($args[$arg], "[")) {
113                 $args[$arg] = $this->expandArg($args[$arg], $request);
114             }
115
116             unset($argstr_args[$arg]);
117             unset($argstr_defaults[$arg]);
118         }
119
120         foreach (array_merge($argstr_args, $argstr_defaults) as $arg => $val) {
121             if ($request and $request->getArg('pagename') == _("PhpWikiAdministration") 
122                 and $arg == 'overwrite') // silence this warning
123                 ;
124             else
125                 trigger_error(sprintf(_("argument '%s' not declared by plugin"),
126                                       $arg), E_USER_NOTICE);
127         }
128         return $args;
129     }
130
131     // Patch by Dan F:
132     // Expand [arg] to $request->getArg("arg") unless preceded by ~
133     function expandArg($argval, &$request) {
134         // return preg_replace('/\[(\w[\w\d]*)\]/e', '$request->getArg("$1")',
135         // Replace the arg unless it is preceded by a ~
136         $ret = preg_replace('/([^~]|^)\[(\w[\w\d]*)\]/e',
137                             '"$1" . $request->getArg("$2")',
138                            $argval);
139         // Ditch the ~ so later versions can be expanded if desired
140         return preg_replace('/~(\[\w[\w\d]*\])/', '$1', $ret);
141     }
142
143     function parseArgStr($argstr) {
144         $args = array();
145         $defaults = array();
146         if (empty($argstr))
147             return array($args,$defaults);
148             
149         $arg_p = '\w+';
150         $op_p = '(?:\|\|)?=';
151         $word_p = '\S+';
152         $opt_ws = '\s*';
153         $qq_p = '" ( (?:[^"\\\\]|\\\\.)* ) "';
154         //"<--kludge for brain-dead syntax coloring
155         $q_p  = "' ( (?:[^'\\\\]|\\\\.)* ) '";
156         $gt_p = "_\\( $opt_ws $qq_p $opt_ws \\)";
157         $argspec_p = "($arg_p) $opt_ws ($op_p) $opt_ws (?: $qq_p|$q_p|$gt_p|($word_p))";
158
159         // handle plugin-list arguments seperately
160         $plugin_p = '<!plugin-list\s+\w+.*?!>';
161         while (preg_match("/^($arg_p) $opt_ws ($op_p) $opt_ws ($plugin_p) $opt_ws/x", $argstr, $m)) {
162             @ list(,$arg, $op, $plugin_val) = $m;
163             $argstr = substr($argstr, strlen($m[0]));
164             $loader = new WikiPluginLoader();
165             $markup = null;
166             $basepage = null;
167             $plugin_val = preg_replace(array("/^<!/","/!>$/"),array("<?","?>"),$plugin_val);
168             $val = $loader->expandPI($plugin_val, $GLOBALS['request'], $markup, $basepage);
169             if ($op == '=') {
170                 $args[$arg] = $val; // comma delimited pagenames or array()?
171             } else {
172                 assert($op == '||=');
173                 $defaults[$arg] = $val;
174             }
175         }
176         while (preg_match("/^$opt_ws $argspec_p $opt_ws/x", $argstr, $m)) {
177             @ list(,$arg,$op,$qq_val,$q_val,$gt_val,$word_val) = $m;
178             $argstr = substr($argstr, strlen($m[0]));
179
180             // Remove quotes from string values.
181             if ($qq_val)
182                 $val = stripslashes($qq_val);
183             elseif ($q_val)
184                 $val = stripslashes($q_val);
185             elseif ($gt_val)
186                 $val = _(stripslashes($gt_val));
187             else
188                 $val = $word_val;
189
190             if ($op == '=') {
191                 $args[$arg] = $val;
192             }
193             else {
194                 // NOTE: This does work for multiple args. Use the
195                 // separator character defined in your webserver
196                 // configuration, usually & or &amp; (See
197                 // http://www.htmlhelp.com/faq/cgifaq.4.html)
198                 // e.g. <plugin RecentChanges days||=1 show_all||=0 show_minor||=0>
199                 // url: RecentChanges?days=1&show_all=1&show_minor=0
200                 assert($op == '||=');
201                 $defaults[$arg] = $val;
202             }
203         }
204
205         if ($argstr) {
206            $this->handle_plugin_args_cruft($argstr, $args);
207         }
208
209         return array($args, $defaults);
210     }
211
212     /* A plugin can override this function to define how any remaining text is handled */
213     function handle_plugin_args_cruft($argstr, $args) {
214         trigger_error(sprintf(_("trailing cruft in plugin args: '%s'"),
215                               $argstr), E_USER_NOTICE);
216     }
217
218     /* handle plugin-list argument: use run(). */
219     function makeList($plugin_args, $request, $basepage) {
220         $dbi = $request->getDbh();
221         $pagelist = $this->run($dbi, $plugin_args, $request, $basepage);
222         $list = array();
223         if (is_object($pagelist) and isa($pagelist, 'PageList')) {
224             // table or list?
225             foreach ($pagelist->_pages as $page) {
226                 $list[] = $page->_page->_pagename;
227             }
228         }
229         return $list;
230     }
231
232     function getDefaultLinkArguments() {
233         return array('targetpage'  => $this->getName(),
234                      'linktext'    => $this->getName(),
235                      'description' => $this->getDescription(),
236                      'class'       => 'wikiaction');
237     }
238
239     function makeLink($argstr, $request) {
240         $defaults = $this->getDefaultArguments();
241         $link_defaults = $this->getDefaultLinkArguments();
242         $defaults = array_merge($defaults, $link_defaults);
243     
244         $args = $this->getArgs($argstr, $request, $defaults);
245         $plugin = $this->getName();
246     
247         $query_args = array();
248         foreach ($args as $arg => $val) {
249             if (isset($link_defaults[$arg]))
250                 continue;
251             if ($val != $defaults[$arg])
252                 $query_args[$arg] = $val;
253         }
254     
255         $link = Button($query_args, $args['linktext'], $args['targetpage']);
256         if (!empty($args['description']))
257             $link->addTooltip($args['description']);
258     
259         return $link;
260     }
261     
262     function getDefaultFormArguments() {
263         return array('targetpage' => $this->getName(),
264                      'buttontext' => $this->getName(),
265                      'class'      => 'wikiaction',
266                      'method'     => 'get',
267                      'textinput'  => 's',
268                      'description'=> $this->getDescription(),
269                      'formsize'   => 30);
270     }
271     
272     function makeForm($argstr, $request) {
273         $form_defaults = $this->getDefaultFormArguments();
274         $defaults = array_merge($form_defaults, 
275                                 array('start_debug' => false),
276                                 $this->getDefaultArguments());
277     
278         $args = $this->getArgs($argstr, $request, $defaults);
279         $plugin = $this->getName();
280         $textinput = $args['textinput'];
281         assert(!empty($textinput) && isset($args['textinput']));
282     
283         $form = HTML::form(array('action' => WikiURL($args['targetpage']),
284                                  'method' => $args['method'],
285                                  'class'  => $args['class'],
286                                  'accept-charset' => $GLOBALS['charset']));
287         if (! USE_PATH_INFO ) {
288             $pagename = $request->get('pagename');
289             $form->pushContent(HTML::input(array('type' => 'hidden', 'name' => 'pagename', 
290                                                  'value' => $args['targetpage'])));
291         }
292         if ($args['targetpage'] != $this->getName()) {
293             $form->pushContent(HTML::input(array('type' => 'hidden', 
294                                                  'name' => 'action', 
295                                                  'value' => $this->getName())));
296         }
297         $contents = HTML::div();
298         $contents->setAttr('class', $args['class']);
299     
300         foreach ($args as $arg => $val) {
301             if (isset($form_defaults[$arg]))
302                 continue;
303             if ($arg != $textinput && $val == $defaults[$arg])
304                 continue;
305     
306             $i = HTML::input(array('name' => $arg, 'value' => $val));
307     
308             if ($arg == $textinput) {
309                 //if ($inputs[$arg] == 'file')
310                 //    $attr['type'] = 'file';
311                 //else
312                 $i->setAttr('type', 'text');
313                 $i->setAttr('size', $args['formsize']);
314                 if ($args['description'])
315                     $i->addTooltip($args['description']);
316             }
317             else {
318                 $i->setAttr('type', 'hidden');
319             }
320             $contents->pushContent($i);
321     
322             // FIXME: hackage
323             if ($i->getAttr('type') == 'file') {
324                 $form->setAttr('enctype', 'multipart/form-data');
325                 $form->setAttr('method', 'post');
326                 $contents->pushContent(HTML::input(array('name' => 'MAX_FILE_SIZE',
327                                                          'value' => MAX_UPLOAD_SIZE,
328                                                          'type' => 'hidden')));
329             }
330         }
331     
332         if (!empty($args['buttontext']))
333             $contents->pushContent(HTML::input(array('type' => 'submit',
334                                                      'class' => 'button',
335                                                      'value' => $args['buttontext'])));
336         $form->pushContent($contents);
337         return $form;
338     }
339
340     function makeBox($title,$body) {
341         if (!$title) $title = $this->_getName();
342         return HTML::div(array('class'=>'box'),
343                          HTML::div(array('class'=>'box-title'),$title),
344                          HTML::div(array('class'=>'box-data'),$body));
345     }
346     
347     function error ($message) {
348         return HTML::div(array('class' => 'errors'),
349                         HTML::strong(fmt("Plugin %s failed.", $this->getName())), ' ',
350                         $message);
351     }
352
353     function disabled ($message='') {
354         $html[] = HTML::div(array('class' => 'title'),
355                             fmt("Plugin %s disabled.", $this->getName()),
356                             ' ', $message);
357         $html[] = HTML::pre($this->_pi);
358         return HTML::div(array('class' => 'disabled-plugin'), $html);
359     }
360
361     // TODO: Not really needed, since our plugins generally initialize their own 
362     // PageList object, which accepts options['types'].
363     // Register custom PageList types for special plugins, like 
364     // 'hi_content' for WikiAdminSearcheplace, 'renamed_pagename' for WikiAdminRename, ...
365     function addPageListColumn ($array) {
366         global $customPageListColumns;
367         if (empty($customPageListColumns)) $customPageListColumns = array();
368         foreach ($array as $column => $obj) {
369             $customPageListColumns[$column] = $obj;
370         }
371     }
372     
373     // provide a sample usage text for automatic edit-toolbar insertion
374     function getUsage() {
375         $args = $this->getDefaultArguments();
376         $string = '<'.'?plugin '.$this->getName().' ';
377         if ($args) {
378             foreach ($args as $key => $value) {
379                 $string .= ($key."||=".(string)$value." ");
380             }
381         }
382         return $string . '?'.'>';
383     }
384 }
385
386 class WikiPluginLoader {
387     var $_errors;
388
389     function expandPI($pi, &$request, &$markup, $basepage=false) {
390         if (!($ppi = $this->parsePi($pi)))
391             return false;
392         list($pi_name, $plugin, $plugin_args) = $ppi;
393
394         if (!is_object($plugin)) {
395             return new HtmlElement($pi_name == 'plugin-link' ? 'span' : 'p',
396                                    array('class' => 'plugin-error'),
397                                    $this->getErrorDetail());
398         }
399         switch ($pi_name) {
400             case 'plugin':
401                 // FIXME: change API for run() (no $dbi needed).
402                 $dbi = $request->getDbh();
403                 // pass the parsed CachedMarkup context in dbi to the plugin 
404                 // to be able to know about itself, or even to change the markup XmlTree (CreateToc)
405                 $dbi->_markup = &$markup; 
406                 // FIXME: could do better here...
407                 if (! $plugin->managesValidators()) {
408                     // Output of plugin (potentially) depends on
409                     // the state of the WikiDB (other than the current
410                     // page.)
411                     
412                     // Lacking other information, we'll assume things
413                     // changed last time the wikidb was touched.
414                     
415                     // As an additional hack, mark the ETag weak, since,
416                     // for all we know, the page might depend
417                     // on things other than the WikiDB (e.g. PhpWeather,
418                     // Calendar...)
419                     
420                     $timestamp = $dbi->getTimestamp();
421                     $request->appendValidators(array('dbi_timestamp' => $timestamp,
422                                                      '%mtime' => (int)$timestamp,
423                                                      '%weak' => true));
424                 }
425                 return $plugin->run($dbi, $plugin_args, $request, $basepage);
426             case 'plugin-list':
427                 return $plugin->makeList($plugin_args, $request, $basepage);
428             case 'plugin-link':
429                 return $plugin->makeLink($plugin_args, $request);
430             case 'plugin-form':
431                 return $plugin->makeForm($plugin_args, $request);
432         }
433     }
434
435     function getWikiPageLinks($pi, $basepage) {
436         if (!($ppi = $this->parsePi($pi)))
437             return false;
438         list($pi_name, $plugin, $plugin_args) = $ppi;
439         if (!is_object($plugin))
440             return false;
441         if ($pi_name != 'plugin')
442             return false;
443         return $plugin->getWikiPageLinks($plugin_args, $basepage);
444     }
445     
446     function parsePI($pi) {
447         if (!preg_match('/^\s*<\?(plugin(?:-form|-link|-list)?)\s+(\w+)\s*(.*?)\s*\?>\s*$/s', $pi, $m))
448             return $this->_error(sprintf("Bad %s", 'PI'));
449
450         list(, $pi_name, $plugin_name, $plugin_args) = $m;
451         $plugin = $this->getPlugin($plugin_name, $pi);
452
453         return array($pi_name, $plugin, $plugin_args);
454     }
455     
456     function getPlugin($plugin_name, $pi=false) {
457         global $ErrorManager;
458
459         // Note that there seems to be no way to trap parse errors
460         // from this include.  (At least not via set_error_handler().)
461         $plugin_source = "lib/plugin/$plugin_name.php";
462
463         $ErrorManager->pushErrorHandler(new WikiMethodCb($this, '_plugin_error_filter'));
464         $plugin_class = "WikiPlugin_$plugin_name";
465         if (!class_exists($plugin_class)) {
466             // $include_failed = !@include_once("lib/plugin/$plugin_name.php");
467             $include_failed = !include_once("lib/plugin/$plugin_name.php");
468             $ErrorManager->popErrorHandler();
469             
470             if (!class_exists($plugin_class)) {
471                 if ($include_failed)
472                     return $this->_error(sprintf(_("Include of '%s' failed"),
473                                                  $plugin_source));
474                 return $this->_error(sprintf(_("%s: no such class"), $plugin_class));
475             }
476         }
477         $ErrorManager->popErrorHandler();
478         $plugin = new $plugin_class;
479         if (!is_subclass_of($plugin, "WikiPlugin"))
480             return $this->_error(sprintf(_("%s: not a subclass of WikiPlugin"),
481                                          $plugin_class));
482
483         $plugin->_pi = $pi;
484         return $plugin;
485     }
486
487     function _plugin_error_filter ($err) {
488         if (preg_match("/Failed opening '.*' for inclusion/", $err->errstr))
489             return true;        // Ignore this error --- it's expected.
490         return false;
491     }
492
493     function getErrorDetail() {
494         return $this->_errors;
495     }
496
497     function _error($message) {
498         $this->_errors = $message;
499         return false;
500     }
501 };
502
503 // (c-file-style: "gnu")
504 // Local Variables:
505 // mode: php
506 // tab-width: 8
507 // c-basic-offset: 4
508 // c-hanging-comment-ender-p: nil
509 // indent-tabs-mode: nil
510 // End:
511 ?>