source: subversion/trunk/roundcubemail/program/include/rcube_plugin_api.php @ 3700

Last change on this file since 3700 was 3700, checked in by thomasb, 3 years ago

Allow plugins to register their own tasks

  • Property svn:keywords set to Id
File size: 11.3 KB
Line 
1<?php
2
3/*
4 +-----------------------------------------------------------------------+
5 | program/include/rcube_plugin_api.php                                  |
6 |                                                                       |
7 | This file is part of the RoundCube Webmail client                     |
8 | Copyright (C) 2008-2009, RoundCube Dev. - Switzerland                 |
9 | Licensed under the GNU GPL                                            |
10 |                                                                       |
11 | PURPOSE:                                                              |
12 |   Plugins repository                                                  |
13 |                                                                       |
14 +-----------------------------------------------------------------------+
15 | Author: Thomas Bruederli <roundcube@gmail.com>                        |
16 +-----------------------------------------------------------------------+
17
18 $Id$
19
20*/
21
22/**
23 * The plugin loader and global API
24 *
25 * @package PluginAPI
26 */
27class rcube_plugin_api
28{
29  static private $instance;
30 
31  public $dir;
32  public $url = 'plugins/';
33  public $output;
34 
35  public $handlers = array();
36  private $plugins = array();
37  private $tasks = array();
38  private $actions = array();
39  private $actionmap = array();
40  private $objectsmap = array();
41  private $template_contents = array();
42 
43  private $required_plugins = array('filesystem_attachments');
44  private $active_hook = false;
45
46  /**
47   * This implements the 'singleton' design pattern
48   *
49   * @return object rcube_plugin_api The one and only instance if this class
50   */
51  static function get_instance()
52  {
53    if (!self::$instance) {
54      self::$instance = new rcube_plugin_api();
55    }
56
57    return self::$instance;
58  }
59 
60 
61  /**
62   * Private constructor
63   */
64  private function __construct()
65  {
66    $this->dir = INSTALL_PATH . $this->url;
67  }
68 
69 
70  /**
71   * Load and init all enabled plugins
72   *
73   * This has to be done after rcmail::load_gui() or rcmail::json_init()
74   * was called because plugins need to have access to rcmail->output
75   */
76  public function init()
77  {
78    $rcmail = rcmail::get_instance();
79    $this->output = $rcmail->output;
80   
81    $plugins_dir = dir($this->dir);
82    $plugins_enabled = (array)$rcmail->config->get('plugins', array());
83   
84    foreach ($plugins_enabled as $plugin_name) {
85      $fn = $plugins_dir->path . DIRECTORY_SEPARATOR . $plugin_name . DIRECTORY_SEPARATOR . $plugin_name . '.php';
86     
87      if (file_exists($fn)) {
88        include($fn);
89       
90        // instantiate class if exists
91        if (class_exists($plugin_name, false)) {
92          $plugin = new $plugin_name($this);
93          // check inheritance and task specification
94          if (is_subclass_of($plugin, 'rcube_plugin') && (!$plugin->task || preg_match('/^('.$plugin->task.')$/i', $rcmail->task))) {
95            $plugin->init();
96            $this->plugins[] = $plugin;
97          }
98        }
99        else {
100          raise_error(array('code' => 520, 'type' => 'php',
101            'file' => __FILE__, 'line' => __LINE__,
102            'message' => "No plugin class $plugin_name found in $fn"), true, false);
103        }
104      }
105      else {
106        raise_error(array('code' => 520, 'type' => 'php',
107          'file' => __FILE__, 'line' => __LINE__,
108          'message' => "Failed to load plugin file $fn"), true, false);
109      }
110    }
111   
112    // check existance of all required core plugins
113    foreach ($this->required_plugins as $plugin_name) {
114      $loaded = false;
115      foreach ($this->plugins as $plugin) {
116        if ($plugin instanceof $plugin_name) {
117          $loaded = true;
118          break;
119        }
120      }
121     
122      // load required core plugin if no derivate was found
123      if (!$loaded) {
124        $fn = $plugins_dir->path . DIRECTORY_SEPARATOR . $plugin_name . DIRECTORY_SEPARATOR . $plugin_name . '.php';
125        if (file_exists($fn)) {
126          include_once($fn);
127         
128          if (class_exists($plugin_name, false)) {
129            $plugin = new $plugin_name($this);
130            // check inheritance
131            if (is_subclass_of($plugin, 'rcube_plugin')) {
132              if (!$plugin->task || preg_match('/('.$plugin->task.')/i', $rcmail->task)) {
133                $plugin->init();
134                $this->plugins[] = $plugin;
135              }
136              $loaded = true;
137            }
138          }
139        }
140      }
141     
142      // trigger fatal error if still not loaded
143      if (!$loaded) {
144        raise_error(array('code' => 520, 'type' => 'php',
145          'file' => __FILE__, 'line' => __LINE__,
146          'message' => "Requried plugin $plugin_name was not loaded"), true, true);
147      }
148    }
149
150    // register an internal hook
151    $this->register_hook('template_container', array($this, 'template_container_hook'));
152   
153    // maybe also register a shudown function which triggers shutdown functions of all plugin objects
154  }
155 
156 
157  /**
158   * Allows a plugin object to register a callback for a certain hook
159   *
160   * @param string Hook name
161   * @param mixed String with global function name or array($obj, 'methodname')
162   */
163  public function register_hook($hook, $callback)
164  {
165    if (is_callable($callback))
166      $this->handlers[$hook][] = $callback;
167    else
168      raise_error(array('code' => 521, 'type' => 'php',
169        'file' => __FILE__, 'line' => __LINE__,
170        'message' => "Invalid callback function for $hook"), true, false);
171  }
172 
173 
174  /**
175   * Triggers a plugin hook.
176   * This is called from the application and executes all registered handlers
177   *
178   * @param string Hook name
179   * @param array Named arguments (key->value pairs)
180   * @return array The (probably) altered hook arguments
181   */
182  public function exec_hook($hook, $args = array())
183  {
184    if (!is_array($args))
185      $args = array('arg' => $args);
186
187    $args += array('abort' => false);
188    $this->active_hook = $hook;
189   
190    foreach ((array)$this->handlers[$hook] as $callback) {
191      $ret = call_user_func($callback, $args);
192      if ($ret && is_array($ret))
193        $args = $ret + $args;
194     
195      if ($args['abort'])
196        break;
197    }
198   
199    $this->active_hook = false;
200    return $args;
201  }
202
203
204  /**
205   * Let a plugin register a handler for a specific request
206   *
207   * @param string Action name (_task=mail&_action=plugin.foo)
208   * @param string Plugin name that registers this action
209   * @param mixed Callback: string with global function name or array($obj, 'methodname')
210   * @param string Task name registered by this plugin
211   */
212  public function register_action($action, $owner, $callback, $task = null)
213  {
214    // check action name
215    if ($task)
216      $action = $task.'.'.$action;
217    else if (strpos($action, 'plugin.') !== 0)
218      $action = 'plugin.'.$action;
219   
220    // can register action only if it's not taken or registered by myself
221    if (!isset($this->actionmap[$action]) || $this->actionmap[$action] == $owner) {
222      $this->actions[$action] = $callback;
223      $this->actionmap[$action] = $owner;
224    }
225    else {
226      raise_error(array('code' => 523, 'type' => 'php',
227        'file' => __FILE__, 'line' => __LINE__,
228        'message' => "Cannot register action $action; already taken by another plugin"), true, false);
229    }
230  }
231
232
233  /**
234   * This method handles requests like _task=mail&_action=plugin.foo
235   * It executes the callback function that was registered with the given action.
236   *
237   * @param string Action name
238   */
239  public function exec_action($action)
240  {
241    if (isset($this->actions[$action])) {
242      call_user_func($this->actions[$action]);
243    }
244    else {
245      raise_error(array('code' => 524, 'type' => 'php',
246        'file' => __FILE__, 'line' => __LINE__,
247        'message' => "No handler found for action $action"), true, true);
248    }
249  }
250
251
252  /**
253   * Register a handler function for template objects
254   *
255   * @param string Object name
256   * @param string Plugin name that registers this action
257   * @param mixed Callback: string with global function name or array($obj, 'methodname')
258   */
259  public function register_handler($name, $owner, $callback)
260  {
261    // check name
262    if (strpos($name, 'plugin.') !== 0)
263      $name = 'plugin.'.$name;
264   
265    // can register handler only if it's not taken or registered by myself
266    if (!isset($this->objectsmap[$name]) || $this->objectsmap[$name] == $owner) {
267      $this->output->add_handler($name, $callback);
268      $this->objectsmap[$name] = $owner;
269    }
270    else {
271      raise_error(array('code' => 525, 'type' => 'php',
272        'file' => __FILE__, 'line' => __LINE__,
273        'message' => "Cannot register template handler $name; already taken by another plugin"), true, false);
274    }
275  }
276 
277 
278  /**
279   * Register this plugin to be responsible for a specific task
280   *
281   * @param string Task name (only characters [a-z0-9_.-] are allowed)
282   * @param string Plugin name that registers this action
283   */
284  public function register_task($task, $owner)
285  {
286    if ($task != asciiwords($task)) {
287      raise_error(array('code' => 526, 'type' => 'php',
288        'file' => __FILE__, 'line' => __LINE__,
289        'message' => "Invalid task name: $task. Only characters [a-z0-9_.-] are allowed"), true, false);
290    }
291    else if (in_array($task, rcmail::$main_tasks)) {
292      raise_error(array('code' => 526, 'type' => 'php',
293        'file' => __FILE__, 'line' => __LINE__,
294        'message' => "Cannot register taks $task; already taken by another plugin or the application itself"), true, false);
295    }
296    else {
297      $this->tasks[$task] = $owner;
298      rcmail::$main_tasks[] = $task;
299      return true;
300    }
301   
302    return false;
303  }
304
305
306  /**
307   * Checks whether the given task is registered by a plugin
308   *
309   * @return boolean True if registered, otherwise false
310   */
311  public function is_plugin_task($task)
312  {
313    return $this->tasks[$task] ? true : false;
314  }
315
316
317  /**
318   * Check if a plugin hook is currently processing.
319   * Mainly used to prevent loops and recursion.
320   *
321   * @param string Hook to check (optional)
322   * @return boolean True if any/the given hook is currently processed, otherwise false
323   */
324  public function is_processing($hook = null)
325  {
326    return $this->active_hook && (!$hook || $this->active_hook == $hook);
327  }
328 
329  /**
330   * Include a plugin script file in the current HTML page
331   */
332  public function include_script($fn)
333  {
334    if ($this->output->type == 'html') {
335      $src = $this->resource_url($fn);
336      $this->output->add_header(html::tag('script', array('type' => "text/javascript", 'src' => $src)));
337    }
338  }
339
340  /**
341   * Include a plugin stylesheet in the current HTML page
342   */
343  public function include_stylesheet($fn)
344  {
345    if ($this->output->type == 'html') {
346      $src = $this->resource_url($fn);
347      $this->output->add_header(html::tag('link', array('rel' => "stylesheet", 'type' => "text/css", 'href' => $src)));
348    }
349  }
350 
351  /**
352   * Save the given HTML content to be added to a template container
353   */
354  public function add_content($html, $container)
355  {
356    $this->template_contents[$container] .= $html . "\n";
357  }
358 
359  /**
360   * Callback for template_container hooks
361   */
362  private function template_container_hook($attrib)
363  {
364    $container = $attrib['name'];
365    return array('content' => $attrib['content'] . $this->template_contents[$container]);
366  }
367 
368  /**
369   * Make the given file name link into the plugins directory
370   */
371  private function resource_url($fn)
372  {
373    if ($fn[0] != '/' && !preg_match('|^https?://|i', $fn))
374      return $this->url . $fn;
375    else
376      return $fn;
377  }
378
379}
380
Note: See TracBrowser for help on using the repository browser.