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