]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/WikiPlugin.php
Added a default getVersion() function for any remaining
[SourceForge/phpwiki.git] / lib / WikiPlugin.php
1 <?php //-*-php-*-
2 rcs_id('$Id: WikiPlugin.php,v 1.33 2003-09-13 22:20:55 carstenklapp 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.33 $");
91     }
92
93     function getArgs($argstr, $request=false, $defaults = false) {
94         if ($defaults === false)
95             $defaults = $this->getDefaultArguments();
96
97         list ($argstr_args, $argstr_defaults) = $this->parseArgStr($argstr);
98         $args = array();
99         foreach ($defaults as $arg => $default_val) {
100             if (isset($argstr_args[$arg]))
101                 $args[$arg] = $argstr_args[$arg];
102             elseif ( $request and ($argval = $request->getArg($arg)) !== false )
103                 $args[$arg] = $argval;
104             elseif (isset($argstr_defaults[$arg]))
105                 $args[$arg] = (string) $argstr_defaults[$arg];
106             else
107                 $args[$arg] = $default_val;
108
109             if ($request)
110                 $args[$arg] = $this->expandArg($args[$arg], $request);
111
112             unset($argstr_args[$arg]);
113             unset($argstr_defaults[$arg]);
114         }
115
116         foreach (array_merge($argstr_args, $argstr_defaults) as $arg => $val) {
117             trigger_error(sprintf(_("argument '%s' not declared by plugin"),
118                                   $arg), E_USER_NOTICE);
119         }
120
121         return $args;
122     }
123
124     function expandArg($argval, $request) {
125         return preg_replace('/\[(\w[\w\d]*)\]/e', '$request->getArg("$1")',
126                             $argval);
127     }
128
129     function parseArgStr($argstr) {
130         $arg_p = '\w+';
131         $op_p = '(?:\|\|)?=';
132         $word_p = '\S+';
133         $opt_ws = '\s*';
134         $qq_p = '" ( (?:[^"\\\\]|\\\\.)* ) "';
135         //"<--kludge for brain-dead syntax coloring
136         $q_p  = "' ( (?:[^'\\\\]|\\\\.)* ) '";
137         $gt_p = "_\\( $opt_ws $qq_p $opt_ws \\)";
138         $argspec_p = "($arg_p) $opt_ws ($op_p) $opt_ws (?: $qq_p|$q_p|$gt_p|($word_p))";
139
140         $args = array();
141         $defaults = array();
142
143         while (preg_match("/^$opt_ws $argspec_p $opt_ws/x", $argstr, $m)) {
144             @ list(,$arg,$op,$qq_val,$q_val,$gt_val,$word_val) = $m;
145             $argstr = substr($argstr, strlen($m[0]));
146
147             // Remove quotes from string values.
148             if ($qq_val)
149                 $val = stripslashes($qq_val);
150             elseif ($q_val)
151                 $val = stripslashes($q_val);
152             elseif ($gt_val)
153                 $val = _(stripslashes($gt_val));
154             else
155                 $val = $word_val;
156
157             if ($op == '=') {
158                 $args[$arg] = $val;
159             }
160             else {
161                 // NOTE: This does work for multiple args. Use the
162                 // separator character defined in your webserver
163                 // configuration, usually & or &amp; (See
164                 // http://www.htmlhelp.com/faq/cgifaq.4.html)
165                 // e.g. <plugin RecentChanges days||=1 show_all||=0 show_minor||=0>
166                 // url: RecentChanges?days=1&show_all=1&show_minor=0
167                 assert($op == '||=');
168                 $defaults[$arg] = $val;
169             }
170         }
171
172         if ($argstr) {
173            $this->handle_plugin_args_cruft($argstr, $args);
174         }
175
176         return array($args, $defaults);
177     }
178
179     /* A plugin can override this function to define how any remaining text is handled */
180     function handle_plugin_args_cruft($argstr, $args) {
181         trigger_error(sprintf(_("trailing cruft in plugin args: '%s'"),
182                               $argstr), E_USER_NOTICE);
183     }
184
185     function getDefaultLinkArguments() {
186         return array('targetpage' => $this->getName(),
187                      'linktext' => $this->getName(),
188                      'description' => $this->getDescription(),
189                      'class' => 'wikiaction');
190     }
191
192     function makeLink($argstr, $request) {
193         $defaults = $this->getDefaultArguments();
194         $link_defaults = $this->getDefaultLinkArguments();
195         $defaults = array_merge($defaults, $link_defaults);
196     
197         $args = $this->getArgs($argstr, $request, $defaults);
198         $plugin = $this->getName();
199     
200         $query_args = array();
201         foreach ($args as $arg => $val) {
202             if (isset($link_defaults[$arg]))
203                 continue;
204             if ($val != $defaults[$arg])
205                 $query_args[$arg] = $val;
206         }
207     
208         $link = Button($query_args, $args['linktext'], $args['targetpage']);
209         if (!empty($args['description']))
210             $link->addTooltip($args['description']);
211     
212         return $link;
213     }
214     
215     function getDefaultFormArguments() {
216         return array('targetpage' => $this->getName(),
217                      'buttontext' => $this->getName(),
218                      'class' => 'wikiaction',
219                      'method' => 'get',
220                      'textinput' => 's',
221                      'description' => $this->getDescription(),
222                      'formsize' => 30);
223     }
224     
225     function makeForm($argstr, $request) {
226         $form_defaults = $this->getDefaultFormArguments();
227         $defaults = array_merge($this->getDefaultArguments(),
228                                 $form_defaults);
229     
230         $args = $this->getArgs($argstr, $request, $defaults);
231         $plugin = $this->getName();
232         $textinput = $args['textinput'];
233         assert(!empty($textinput) && isset($args['textinput']));
234     
235         $form = HTML::form(array('action' => WikiURL($args['targetpage']),
236                                  'method' => $args['method'],
237                                  'class' => $args['class'],
238                                  'accept-charset' => CHARSET));
239         if (! USE_PATH_INFO ) {
240             $pagename = $request->get('pagename');
241             $form->pushContent(HTML::input(array('type' => 'hidden', 'name' => 'pagename', 
242                                                  'value' => $args['targetpage'])));
243         }
244         $contents = HTML::div();
245         $contents->setAttr('class', $args['class']);
246     
247         foreach ($args as $arg => $val) {
248             if (isset($form_defaults[$arg]))
249                 continue;
250             if ($arg != $textinput && $val == $defaults[$arg])
251                 continue;
252     
253             $i = HTML::input(array('name' => $arg, 'value' => $val));
254     
255             if ($arg == $textinput) {
256                 //if ($inputs[$arg] == 'file')
257                 //    $attr['type'] = 'file';
258                 //else
259                 $i->setAttr('type', 'text');
260                 $i->setAttr('size', $args['formsize']);
261                 if ($args['description'])
262                     $i->addTooltip($args['description']);
263             }
264             else {
265                 $i->setAttr('type', 'hidden');
266             }
267             $contents->pushContent($i);
268     
269             // FIXME: hackage
270             if ($i->getAttr('type') == 'file') {
271                 $form->setAttr('enctype', 'multipart/form-data');
272                 $form->setAttr('method', 'post');
273                 $contents->pushContent(HTML::input(array('name' => 'MAX_FILE_SIZE',
274                                                          'value' => MAX_UPLOAD_SIZE,
275                                                          'type' => 'hidden')));
276             }
277         }
278     
279         if (!empty($args['buttontext']))
280             $contents->pushContent(HTML::input(array('type' => 'submit',
281                                                      'class' => 'button',
282                                                      'value' => $args['buttontext'])));
283     
284         $form->pushContent($contents);
285         return $form;
286     }
287     
288     function error ($message) {
289         return HTML::div(array('class' => 'errors'),
290                         HTML::strong(fmt("Plugin %s failed.", $this->getName())), ' ',
291                         $message);
292     }
293
294     function disabled ($message='') {
295         $html[] = HTML::div(array('class' => 'title'),
296                             fmt("Plugin %s disabled.", $this->getName()),
297                             ' ', $message);
298         $html[] = HTML::pre($this->_pi);
299         return HTML::div(array('class' => 'disabled-plugin'), $html);
300     }
301 }
302
303 class WikiPluginLoader {
304     var $_errors;
305
306     function expandPI($pi, &$request, $basepage=false) {
307         if (!($ppi = $this->parsePi($pi)))
308             return false;
309         list($pi_name, $plugin, $plugin_args) = $ppi;
310
311         if (!is_object($plugin)) {
312             return new HtmlElement($pi_name == 'plugin-link' ? 'span' : 'p',
313                                    array('class' => 'plugin-error'),
314                                    $this->getErrorDetail());
315         }
316         switch ($pi_name) {
317             case 'plugin':
318                 // FIXME: change API for run() (no $dbi needed).
319                 $dbi = $request->getDbh();
320                 // FIXME: could do better here...
321                 if (! $plugin->managesValidators()) {
322                     // Output of plugin (potentially) depends on
323                     // the state of the WikiDB (other than the current
324                     // page.)
325                     
326                     // Lacking other information, we'll assume things
327                     // changed last time the wikidb was touched.
328                     
329                     // As an additional hack, mark the ETag weak, since,
330                     // for all we know, the page might depend
331                     // on things other than the WikiDB (e.g. PhpWeather,
332                     // Calendar...)
333                     
334                     $timestamp = $dbi->getTimestamp();
335                     $request->appendValidators(array('dbi_timestamp' => $timestamp,
336                                                      '%mtime' => (int)$timestamp,
337                                                      '%weak' => true));
338                 }
339                 return $plugin->run($dbi, $plugin_args, $request, $basepage);
340             case 'plugin-link':
341                 return $plugin->makeLink($plugin_args, $request);
342             case 'plugin-form':
343                 return $plugin->makeForm($plugin_args, $request);
344         }
345     }
346
347     function getWikiPageLinks($pi, $basepage) {
348         if (!($ppi = $this->parsePi($pi)))
349             return false;
350         list($pi_name, $plugin, $plugin_args) = $ppi;
351         if (!is_object($plugin))
352             return false;
353         if ($pi_name != 'plugin')
354             return false;
355         return $plugin->getWikiPageLinks($plugin_args, $basepage);
356     }
357     
358     function parsePI($pi) {
359         if (!preg_match('/^\s*<\?(plugin(?:-form|-link)?)\s+(\w+)\s*(.*?)\s*\?>\s*$/s', $pi, $m))
360             return $this->_error(sprintf("Bad %s", 'PI'));
361
362         list(, $pi_name, $plugin_name, $plugin_args) = $m;
363         $plugin = $this->getPlugin($plugin_name, $pi);
364
365         return array($pi_name, $plugin, $plugin_args);
366     }
367     
368     function getPlugin($plugin_name, $pi) {
369         global $ErrorManager;
370
371         // Note that there seems to be no way to trap parse errors
372         // from this include.  (At least not via set_error_handler().)
373         $plugin_source = "lib/plugin/$plugin_name.php";
374
375         $ErrorManager->pushErrorHandler(new WikiMethodCb($this, '_plugin_error_filter'));
376         // $include_failed = !@include_once("lib/plugin/$plugin_name.php");
377         $include_failed = !include_once("lib/plugin/$plugin_name.php");
378         $ErrorManager->popErrorHandler();
379
380         $plugin_class = "WikiPlugin_$plugin_name";
381         if (!class_exists($plugin_class)) {
382             if ($include_failed)
383                 return $this->_error(sprintf(_("Include of '%s' failed"),
384                                              $plugin_source));
385             return $this->_error(sprintf("%s: no such class", $plugin_class));
386         }
387
388         $plugin = new $plugin_class;
389         if (!is_subclass_of($plugin, "WikiPlugin"))
390             return $this->_error(sprintf("%s: not a subclass of WikiPlugin",
391                                          $plugin_class));
392
393         $plugin->_pi = $pi;
394         return $plugin;
395     }
396
397     function _plugin_error_filter ($err) {
398         if (preg_match("/Failed opening '.*' for inclusion/", $err->errstr))
399             return true;        // Ignore this error --- it's expected.
400         return false;
401     }
402
403     function getErrorDetail() {
404         return $this->_errors;
405     }
406
407     function _error($message) {
408         $this->_errors = $message;
409         return false;
410     }
411 };
412
413 // (c-file-style: "gnu")
414 // Local Variables:
415 // mode: php
416 // tab-width: 8
417 // c-basic-offset: 4
418 // c-hanging-comment-ender-p: nil
419 // indent-tabs-mode: nil
420 // End:
421 ?>