thomascube
2010-06-08 af3cf8a0a7de74ab169f44277eda73f5f9e18cd7
commit | author | age
cc97ea 1 <?php
T 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
1d786c 18  $Id$
cc97ea 19
T 20 */
21
22 /**
23  * The plugin loader and global API
24  *
d062db 25  * @package PluginAPI
cc97ea 26  */
T 27 class 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();
05a631 37   private $tasks = array();
cc97ea 38   private $actions = array();
T 39   private $actionmap = array();
40   private $objectsmap = array();
41   private $template_contents = array();
42   
a366a3 43   private $required_plugins = array('filesystem_attachments');
T 44   private $active_hook = false;
cc97ea 45
T 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   {
7dbe2f 66     $this->dir = INSTALL_PATH . $this->url;
cc97ea 67   }
T 68   
69   
70   /**
71    * Load and init all enabled plugins
72    *
929a50 73    * This has to be done after rcmail::load_gui() or rcmail::json_init()
cc97ea 74    * was called because plugins need to have access to rcmail->output
T 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
9b94eb 94           if (is_subclass_of($plugin, 'rcube_plugin') && (!$plugin->task || preg_match('/^('.$plugin->task.')$/i', $rcmail->task))) {
cc97ea 95             $plugin->init();
T 96             $this->plugins[] = $plugin;
97           }
98         }
99         else {
10eedb 100           raise_error(array('code' => 520, 'type' => 'php',
A 101         'file' => __FILE__, 'line' => __LINE__,
102         'message' => "No plugin class $plugin_name found in $fn"), true, false);
cc97ea 103         }
T 104       }
105       else {
10eedb 106         raise_error(array('code' => 520, 'type' => 'php',
A 107       'file' => __FILE__, 'line' => __LINE__,
108       'message' => "Failed to load plugin file $fn"), true, false);
cc97ea 109       }
T 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)) {
912bbb 126           include_once($fn);
cc97ea 127           
T 128           if (class_exists($plugin_name, false)) {
129             $plugin = new $plugin_name($this);
130             // check inheritance
131             if (is_subclass_of($plugin, 'rcube_plugin')) {
912bbb 132           if (!$plugin->task || preg_match('/('.$plugin->task.')/i', $rcmail->task)) {
A 133                 $plugin->init();
134                 $this->plugins[] = $plugin;
135               }
136           $loaded = true;
cc97ea 137             }
T 138           }
139         }
140       }
141       
142       // trigger fatal error if still not loaded
143       if (!$loaded) {
10eedb 144         raise_error(array('code' => 520, 'type' => 'php',
A 145       'file' => __FILE__, 'line' => __LINE__,
146       'message' => "Requried plugin $plugin_name was not loaded"), true, true);
cc97ea 147       }
T 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
10eedb 168       raise_error(array('code' => 521, 'type' => 'php',
A 169         'file' => __FILE__, 'line' => __LINE__,
170         'message' => "Invalid callback function for $hook"), true, false);
cc97ea 171   }
T 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   {
463a03 184     if (!is_array($args))
A 185       $args = array('arg' => $args);
186
cc97ea 187     $args += array('abort' => false);
a366a3 188     $this->active_hook = $hook;
cc97ea 189     
T 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     
a366a3 199     $this->active_hook = false;
cc97ea 200     return $args;
T 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')
05a631 210    * @param string Task name registered by this plugin
cc97ea 211    */
05a631 212   public function register_action($action, $owner, $callback, $task = null)
cc97ea 213   {
T 214     // check action name
05a631 215     if ($task)
T 216       $action = $task.'.'.$action;
217     else if (strpos($action, 'plugin.') !== 0)
cc97ea 218       $action = 'plugin.'.$action;
T 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 {
10eedb 226       raise_error(array('code' => 523, 'type' => 'php',
A 227         'file' => __FILE__, 'line' => __LINE__,
228         'message' => "Cannot register action $action; already taken by another plugin"), true, false);
cc97ea 229     }
T 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 {
10eedb 245       raise_error(array('code' => 524, 'type' => 'php',
A 246         'file' => __FILE__, 'line' => __LINE__,
247         'message' => "No handler found for action $action"), true, true);
cc97ea 248     }
T 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 {
10eedb 271       raise_error(array('code' => 525, 'type' => 'php',
A 272         'file' => __FILE__, 'line' => __LINE__,
273         'message' => "Cannot register template handler $name; already taken by another plugin"), true, false);
cc97ea 274     }
T 275   }
276   
a366a3 277   
T 278   /**
05a631 279    * Register this plugin to be responsible for a specific task
T 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   /**
a366a3 318    * Check if a plugin hook is currently processing.
T 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   
cc97ea 329   /**
T 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') {
eb6f19 335       $src = $this->resource_url($fn);
cc97ea 336       $this->output->add_header(html::tag('script', array('type' => "text/javascript", 'src' => $src)));
T 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') {
eb6f19 346       $src = $this->resource_url($fn);
cc97ea 347       $this->output->add_header(html::tag('link', array('rel' => "stylesheet", 'type' => "text/css", 'href' => $src)));
T 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'];
8448fc 365     return array('content' => $attrib['content'] . $this->template_contents[$container]);
cc97ea 366   }
T 367   
368   /**
369    * Make the given file name link into the plugins directory
370    */
eb6f19 371   private function resource_url($fn)
cc97ea 372   {
23a2ee 373     if ($fn[0] != '/' && !preg_match('|^https?://|i', $fn))
cc97ea 374       return $this->url . $fn;
T 375     else
376       return $fn;
377   }
378
379 }
380