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