2 rcs_id('$Id: WikiPlugin.php,v 1.65 2007-07-01 09:09:19 rurban Exp $');
6 function getDefaultArguments() {
7 return array('description' => $this->getDescription());
10 /** Does the plugin manage its own HTTP validators?
12 * This should be overwritten by (some) individual plugins.
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.
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.
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
28 function managesValidators() {
33 function run ($dbi, $argstr, &$request, $basepage) {
34 trigger_error("WikiPlugin::run: pure virtual function",
38 /** Get wiki-pages linked to by plugin invocation.
40 * A plugin may override this method to add pages to the
41 * link database for the invoking page.
43 * For example, the IncludePage plugin should override this so
44 * that the including page shows up in the backlinks list for the
47 * Not all plugins which generate links to wiki-pages need list
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.
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).
59 function getWikiPageLinks ($argstr, $basepage) {
66 * This is used (by default) by getDefaultLinkArguments and
67 * getDefaultFormArguments to compute the default link/form
70 * If you want to gettextify the name (probably a good idea),
71 * override this method in your plugin class, like:
73 * function getName() { return _("MyPlugin"); }
76 * @return string plugin name/target.
79 return preg_replace('/^.*_/', '', get_class($this));
82 function getDescription() {
83 return $this->getName();
86 // plugins should override this with the commented-out code
87 function getVersion() {
89 //return preg_replace("/[Revision: $]/", '',
90 // "\$Revision: 1.65 $");
93 function getArgs($argstr, $request=false, $defaults=false) {
94 if ($defaults === false) {
95 $defaults = $this->getDefaultArguments();
97 //Fixme: on POST argstr is empty
98 list ($argstr_args, $argstr_defaults) = $this->parseArgStr($argstr);
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];
109 $args[$arg] = $default_val;
112 if ($request and is_string($args[$arg]) and strstr($args[$arg], "[")) {
113 $args[$arg] = $this->expandArg($args[$arg], $request);
116 unset($argstr_args[$arg]);
117 unset($argstr_defaults[$arg]);
120 foreach (array_merge($argstr_args, $argstr_defaults) as $arg => $val) {
121 // TODO: where the heck comes this from? Put the new method over there and peace.
122 /*if ($request and $request->getArg('pagename') == _("PhpWikiAdministration")
123 and $arg == 'overwrite') // silence this warning
125 if ($this->allow_undeclared_arg($arg, $val))
129 // Add special handling of pages and exclude args to accept <! plugin-list !>
130 // and split explodePageList($args['exclude']) => array()
131 // TODO : handle p[] pagehash
132 foreach (array('pages', 'exclude') as $key) {
133 if (!empty($args[$key]) and array_key_exists($key, $defaults))
134 $args[$key] = is_string($args[$key])
135 ? explodePageList($args[$key])
136 : $args[$key]; // <! plugin-list !>
143 // Expand [arg] to $request->getArg("arg") unless preceded by ~
144 function expandArg($argval, &$request) {
145 // return preg_replace('/\[(\w[\w\d]*)\]/e', '$request->getArg("$1")',
146 // Replace the arg unless it is preceded by a ~
147 $ret = preg_replace('/([^~]|^)\[(\w[\w\d]*)\]/e',
148 '"$1" . $request->getArg("$2")',
150 // Ditch the ~ so later versions can be expanded if desired
151 return preg_replace('/~(\[\w[\w\d]*\])/', '$1', $ret);
154 function parseArgStr($argstr) {
158 return array($args,$defaults);
161 $op_p = '(?:\|\|)?=';
164 $qq_p = '" ( (?:[^"\\\\]|\\\\.)* ) "';
165 //"<--kludge for brain-dead syntax coloring
166 $q_p = "' ( (?:[^'\\\\]|\\\\.)* ) '";
167 $gt_p = "_\\( $opt_ws $qq_p $opt_ws \\)";
168 $argspec_p = "($arg_p) $opt_ws ($op_p) $opt_ws (?: $qq_p|$q_p|$gt_p|($word_p))";
170 // handle plugin-list arguments seperately
171 $plugin_p = '<!plugin-list\s+\w+.*?!>';
172 while (preg_match("/^($arg_p) $opt_ws ($op_p) $opt_ws ($plugin_p) $opt_ws/x", $argstr, $m)) {
173 @ list(,$arg, $op, $plugin_val) = $m;
174 $argstr = substr($argstr, strlen($m[0]));
175 $loader = new WikiPluginLoader();
178 $plugin_val = preg_replace(array("/^<!/","/!>$/"),array("<?","?>"),$plugin_val);
179 $val = $loader->expandPI($plugin_val, $GLOBALS['request'], $markup, $basepage);
181 $args[$arg] = $val; // comma delimited pagenames or array()?
183 assert($op == '||=');
184 $defaults[$arg] = $val;
187 while (preg_match("/^$opt_ws $argspec_p $opt_ws/x", $argstr, $m)) {
188 @ list(,$arg,$op,$qq_val,$q_val,$gt_val,$word_val) = $m;
189 $argstr = substr($argstr, strlen($m[0]));
191 // Remove quotes from string values.
193 $val = stripslashes($qq_val);
195 $val = stripslashes($q_val);
197 $val = _(stripslashes($gt_val));
205 // NOTE: This does work for multiple args. Use the
206 // separator character defined in your webserver
207 // configuration, usually & or & (See
208 // http://www.htmlhelp.com/faq/cgifaq.4.html)
209 // e.g. <plugin RecentChanges days||=1 show_all||=0 show_minor||=0>
210 // url: RecentChanges?days=1&show_all=1&show_minor=0
211 assert($op == '||=');
212 $defaults[$arg] = $val;
217 $this->handle_plugin_args_cruft($argstr, $args);
220 return array($args, $defaults);
223 /* A plugin can override this function to define how any remaining text is handled */
224 function handle_plugin_args_cruft($argstr, $args) {
225 trigger_error(sprintf(_("trailing cruft in plugin args: '%s'"),
226 $argstr), E_USER_NOTICE);
229 /* A plugin can override this to allow undeclared arguments.
230 Or to silence the warning.
232 function allow_undeclared_arg($name, $value) {
233 trigger_error(sprintf(_("Argument '%s' not declared by plugin."),
234 $name), E_USER_NOTICE);
238 /* handle plugin-list argument: use run(). */
239 function makeList($plugin_args, $request, $basepage) {
240 $dbi = $request->getDbh();
241 $pagelist = $this->run($dbi, $plugin_args, $request, $basepage);
243 if (is_object($pagelist) and isa($pagelist, 'PageList'))
244 return $pagelist->pageNames();
245 elseif (is_array($pagelist))
251 function getDefaultLinkArguments() {
252 return array('targetpage' => $this->getName(),
253 'linktext' => $this->getName(),
254 'description' => $this->getDescription(),
255 'class' => 'wikiaction');
258 function makeLink($argstr, $request) {
259 $defaults = $this->getDefaultArguments();
260 $link_defaults = $this->getDefaultLinkArguments();
261 $defaults = array_merge($defaults, $link_defaults);
263 $args = $this->getArgs($argstr, $request, $defaults);
264 $plugin = $this->getName();
266 $query_args = array();
267 foreach ($args as $arg => $val) {
268 if (isset($link_defaults[$arg]))
270 if ($val != $defaults[$arg])
271 $query_args[$arg] = $val;
274 $link = Button($query_args, $args['linktext'], $args['targetpage']);
275 if (!empty($args['description']))
276 $link->addTooltip($args['description']);
281 function getDefaultFormArguments() {
282 return array('targetpage' => $this->getName(),
283 'buttontext' => $this->getName(),
284 'class' => 'wikiaction',
287 'description'=> $this->getDescription(),
291 function makeForm($argstr, $request) {
292 $form_defaults = $this->getDefaultFormArguments();
293 $defaults = array_merge($form_defaults,
294 array('start_debug' => $request->getArg('start_debug')),
295 $this->getDefaultArguments());
297 $args = $this->getArgs($argstr, $request, $defaults);
298 $plugin = $this->getName();
299 $textinput = $args['textinput'];
300 assert(!empty($textinput) && isset($args['textinput']));
302 $form = HTML::form(array('action' => WikiURL($args['targetpage']),
303 'method' => $args['method'],
304 'class' => $args['class'],
305 'accept-charset' => $GLOBALS['charset']));
306 if (! USE_PATH_INFO ) {
307 $pagename = $request->get('pagename');
308 $form->pushContent(HTML::input(array('type' => 'hidden',
309 'name' => 'pagename',
310 'value' => $args['targetpage'])));
312 if ($args['targetpage'] != $this->getName()) {
313 $form->pushContent(HTML::input(array('type' => 'hidden',
315 'value' => $this->getName())));
317 $contents = HTML::div();
318 $contents->setAttr('class', $args['class']);
320 foreach ($args as $arg => $val) {
321 if (isset($form_defaults[$arg]))
323 if ($arg != $textinput && $val == $defaults[$arg])
326 $i = HTML::input(array('name' => $arg, 'value' => $val));
328 if ($arg == $textinput) {
329 //if ($inputs[$arg] == 'file')
330 // $attr['type'] = 'file';
332 $i->setAttr('type', 'text');
333 $i->setAttr('size', $args['formsize']);
334 if ($args['description'])
335 $i->addTooltip($args['description']);
338 $i->setAttr('type', 'hidden');
340 $contents->pushContent($i);
343 if ($i->getAttr('type') == 'file') {
344 $form->setAttr('enctype', 'multipart/form-data');
345 $form->setAttr('method', 'post');
346 $contents->pushContent(HTML::input(array('name' => 'MAX_FILE_SIZE',
347 'value' => MAX_UPLOAD_SIZE,
348 'type' => 'hidden')));
352 if (!empty($args['buttontext']))
353 $contents->pushContent(HTML::input(array('type' => 'submit',
355 'value' => $args['buttontext'])));
356 $form->pushContent($contents);
360 // box is used to display a fixed-width, narrow version with common header
361 function box($args=false, $request=false, $basepage=false) {
362 if (!$request) $request =& $GLOBALS['request'];
363 $dbi = $request->getDbh();
364 return $this->makeBox('', $this->run($dbi, $args, $request, $basepage));
367 function makeBox($title, $body) {
368 if (!$title) $title = $this->getName();
369 return HTML::div(array('class'=>'box'),
370 HTML::div(array('class'=>'box-title'), $title),
371 HTML::div(array('class'=>'box-data'), $body));
374 function error ($message) {
375 return HTML::div(array('class' => 'errors'),
376 HTML::strong(fmt("Plugin %s failed.", $this->getName())), ' ',
380 function disabled ($message='') {
381 $html[] = HTML::div(array('class' => 'title'),
382 fmt("Plugin %s disabled.", $this->getName()),
384 $html[] = HTML::pre($this->_pi);
385 return HTML::div(array('class' => 'disabled-plugin'), $html);
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 global $customPageListColumns;
394 if (empty($customPageListColumns)) $customPageListColumns = array();
395 foreach ($array as $column => $obj) {
396 $customPageListColumns[$column] = $obj;
400 // provide a sample usage text for automatic edit-toolbar insertion
401 function getUsage() {
402 $args = $this->getDefaultArguments();
403 $string = '<'.'?plugin '.$this->getName().' ';
405 foreach ($args as $key => $value) {
406 $string .= ($key."||=".(string)$value." ");
409 return $string . '?'.'>';
412 function getArgumentsDescription() {
414 foreach ($this->getDefaultArguments() as $arg => $default) {
415 // Work around UserPreferences plugin to avoid error
416 if ((is_array($default))) {
417 $default = '(array)';
418 // This is a bit flawed with UserPreferences object
419 //$default = sprintf("array('%s')",
420 // implode("', '", array_keys($default)));
423 if (stristr($default, ' '))
424 $default = "'$default'";
425 $arguments->pushcontent("$arg=$default", HTML::br());
432 class WikiPluginLoader {
435 function expandPI($pi, &$request, &$markup, $basepage=false) {
436 if (!($ppi = $this->parsePi($pi)))
438 list($pi_name, $plugin, $plugin_args) = $ppi;
440 if (!is_object($plugin)) {
441 return new HtmlElement($pi_name == 'plugin-link' ? 'span' : 'p',
442 array('class' => 'plugin-error'),
443 $this->getErrorDetail());
447 // FIXME: change API for run() (no $dbi needed).
448 $dbi = $request->getDbh();
449 // pass the parsed CachedMarkup context in dbi to the plugin
450 // to be able to know about itself, or even to change the markup XmlTree (CreateToc)
451 $dbi->_markup = &$markup;
452 // FIXME: could do better here...
453 if (! $plugin->managesValidators()) {
454 // Output of plugin (potentially) depends on
455 // the state of the WikiDB (other than the current
458 // Lacking other information, we'll assume things
459 // changed last time the wikidb was touched.
461 // As an additional hack, mark the ETag weak, since,
462 // for all we know, the page might depend
463 // on things other than the WikiDB (e.g. PhpWeather,
466 $timestamp = $dbi->getTimestamp();
467 $request->appendValidators(array('dbi_timestamp' => $timestamp,
468 '%mtime' => (int)$timestamp,
471 return $plugin->run($dbi, $plugin_args, $request, $basepage);
473 return $plugin->makeList($plugin_args, $request, $basepage);
475 return $plugin->makeLink($plugin_args, $request);
477 return $plugin->makeForm($plugin_args, $request);
481 function getWikiPageLinks($pi, $basepage) {
482 if (!($ppi = $this->parsePi($pi)))
484 list($pi_name, $plugin, $plugin_args) = $ppi;
485 if (!is_object($plugin))
487 if ($pi_name != 'plugin')
489 return $plugin->getWikiPageLinks($plugin_args, $basepage);
492 function parsePI($pi) {
493 if (!preg_match('/^\s*<\?(plugin(?:-form|-link|-list)?)\s+(\w+)\s*(.*?)\s*\?>\s*$/s', $pi, $m))
494 return $this->_error(sprintf("Bad %s", 'PI'));
496 list(, $pi_name, $plugin_name, $plugin_args) = $m;
497 $plugin = $this->getPlugin($plugin_name, $pi);
499 return array($pi_name, $plugin, $plugin_args);
502 function getPlugin($plugin_name, $pi=false) {
503 global $ErrorManager;
505 // Note that there seems to be no way to trap parse errors
506 // from this include. (At least not via set_error_handler().)
507 $plugin_source = "lib/plugin/$plugin_name.php";
509 $ErrorManager->pushErrorHandler(new WikiMethodCb($this, '_plugin_error_filter'));
510 $plugin_class = "WikiPlugin_$plugin_name";
511 if (!class_exists($plugin_class)) {
512 // $include_failed = !@include_once("lib/plugin/$plugin_name.php");
513 $include_failed = !include_once("lib/plugin/$plugin_name.php");
514 $ErrorManager->popErrorHandler();
516 if (!class_exists($plugin_class)) {
518 return $this->_error(sprintf(_("Include of '%s' failed."),
520 return $this->_error(sprintf(_("%s: no such class"), $plugin_class));
523 $ErrorManager->popErrorHandler();
524 $plugin = new $plugin_class;
525 if (!is_subclass_of($plugin, "WikiPlugin"))
526 return $this->_error(sprintf(_("%s: not a subclass of WikiPlugin."),
533 function _plugin_error_filter ($err) {
534 if (preg_match("/Failed opening '.*' for inclusion/", $err->errstr))
535 return true; // Ignore this error --- it's expected.
539 function getErrorDetail() {
540 return $this->_errors;
543 function _error($message) {
544 $this->_errors = $message;
549 // (c-file-style: "gnu")
554 // c-hanging-comment-ender-p: nil
555 // indent-tabs-mode: nil