alecpl
2010-07-30 2537686d1dc06c7b0588bc4663342a052ebaca6e
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
e6ce00 46   // Deprecated names of hooks, will be removed after 0.5-stable release
A 47   private $deprecated_hooks = array(
48     'create_user'       => 'user_create',
49     'kill_session'      => 'session_destroy',
50     'upload_attachment' => 'attachment_upload',
51     'save_attachment'   => 'attachment_save',
52     'get_attachment'    => 'attachment_get',
53     'cleanup_attachments' => 'attachments_cleanup',
54     'display_attachment' => 'attachment_display',
55     'remove_attachment' => 'attachment_delete',
56     'outgoing_message_headers' => 'message_outgoing_headers',
57     'outgoing_message_body' => 'message_outgoing_body',
58     'address_sources'   => 'addressbooks_list',
59     'get_address_book'  => 'addressbook_get',
60     'create_contact'    => 'contact_create',
61     'save_contact'      => 'contact_save',
62     'delete_contact'    => 'contact_delete',
63     'manage_folders'    => 'folders_list',
64     'list_mailboxes'    => 'mailboxes_list',
65     'save_preferences'  => 'preferences_save',
66     'user_preferences'  => 'preferences_list',
67     'list_prefs_sections' => 'preferences_sections_list',
68     'list_identities'   => 'identities_list',
69     'create_identity'   => 'identity_create',
70     'save_identity'     => 'identity_save',
71   );
72
cc97ea 73   /**
T 74    * This implements the 'singleton' design pattern
75    *
76    * @return object rcube_plugin_api The one and only instance if this class
77    */
78   static function get_instance()
79   {
80     if (!self::$instance) {
81       self::$instance = new rcube_plugin_api();
82     }
83
84     return self::$instance;
85   }
86   
87   
88   /**
89    * Private constructor
90    */
91   private function __construct()
92   {
7dbe2f 93     $this->dir = INSTALL_PATH . $this->url;
cc97ea 94   }
T 95   
96   
97   /**
98    * Load and init all enabled plugins
99    *
929a50 100    * This has to be done after rcmail::load_gui() or rcmail::json_init()
cc97ea 101    * was called because plugins need to have access to rcmail->output
T 102    */
103   public function init()
104   {
105     $rcmail = rcmail::get_instance();
106     $this->output = $rcmail->output;
d5d968 107
cc97ea 108     $plugins_dir = dir($this->dir);
d5d968 109     $plugins_dir = unslashify($plugins_dir->path);
cc97ea 110     $plugins_enabled = (array)$rcmail->config->get('plugins', array());
d5d968 111
cc97ea 112     foreach ($plugins_enabled as $plugin_name) {
d5d968 113       $fn = $plugins_dir . DIRECTORY_SEPARATOR . $plugin_name . DIRECTORY_SEPARATOR . $plugin_name . '.php';
A 114
cc97ea 115       if (file_exists($fn)) {
T 116         include($fn);
d5d968 117
cc97ea 118         // instantiate class if exists
T 119         if (class_exists($plugin_name, false)) {
120           $plugin = new $plugin_name($this);
121           // check inheritance and task specification
9b94eb 122           if (is_subclass_of($plugin, 'rcube_plugin') && (!$plugin->task || preg_match('/^('.$plugin->task.')$/i', $rcmail->task))) {
cc97ea 123             $plugin->init();
T 124             $this->plugins[] = $plugin;
125           }
126         }
127         else {
10eedb 128           raise_error(array('code' => 520, 'type' => 'php',
A 129         'file' => __FILE__, 'line' => __LINE__,
130         'message' => "No plugin class $plugin_name found in $fn"), true, false);
cc97ea 131         }
T 132       }
133       else {
10eedb 134         raise_error(array('code' => 520, 'type' => 'php',
A 135       'file' => __FILE__, 'line' => __LINE__,
136       'message' => "Failed to load plugin file $fn"), true, false);
cc97ea 137       }
T 138     }
139     
140     // check existance of all required core plugins
141     foreach ($this->required_plugins as $plugin_name) {
142       $loaded = false;
143       foreach ($this->plugins as $plugin) {
144         if ($plugin instanceof $plugin_name) {
145           $loaded = true;
146           break;
147         }
148       }
149       
150       // load required core plugin if no derivate was found
151       if (!$loaded) {
d5d968 152         $fn = $plugins_dir . DIRECTORY_SEPARATOR . $plugin_name . DIRECTORY_SEPARATOR . $plugin_name . '.php';
A 153
cc97ea 154         if (file_exists($fn)) {
912bbb 155           include_once($fn);
cc97ea 156           
T 157           if (class_exists($plugin_name, false)) {
158             $plugin = new $plugin_name($this);
159             // check inheritance
160             if (is_subclass_of($plugin, 'rcube_plugin')) {
912bbb 161           if (!$plugin->task || preg_match('/('.$plugin->task.')/i', $rcmail->task)) {
A 162                 $plugin->init();
163                 $this->plugins[] = $plugin;
164               }
165           $loaded = true;
cc97ea 166             }
T 167           }
168         }
169       }
170       
171       // trigger fatal error if still not loaded
172       if (!$loaded) {
10eedb 173         raise_error(array('code' => 520, 'type' => 'php',
A 174       'file' => __FILE__, 'line' => __LINE__,
175       'message' => "Requried plugin $plugin_name was not loaded"), true, true);
cc97ea 176       }
T 177     }
178
179     // register an internal hook
180     $this->register_hook('template_container', array($this, 'template_container_hook'));
181     
182     // maybe also register a shudown function which triggers shutdown functions of all plugin objects
183   }
184   
185   
186   /**
187    * Allows a plugin object to register a callback for a certain hook
188    *
189    * @param string Hook name
190    * @param mixed String with global function name or array($obj, 'methodname')
191    */
192   public function register_hook($hook, $callback)
193   {
e6ce00 194     if (is_callable($callback)) {
A 195       if (isset($this->deprecated_hooks[$hook])) {
196         /* Uncoment after 0.4-stable release
197         raise_error(array('code' => 522, 'type' => 'php',
198           'file' => __FILE__, 'line' => __LINE__,
199           'message' => "Deprecated hook name. ".$hook.' -> '.$this->deprecated_hooks[$hook]), true, false);
200         */
201         $hook = $this->deprecated_hooks[$hook];
202       }
cc97ea 203       $this->handlers[$hook][] = $callback;
e6ce00 204     }
cc97ea 205     else
10eedb 206       raise_error(array('code' => 521, 'type' => 'php',
A 207         'file' => __FILE__, 'line' => __LINE__,
208         'message' => "Invalid callback function for $hook"), true, false);
cc97ea 209   }
T 210   
211   
212   /**
213    * Triggers a plugin hook.
214    * This is called from the application and executes all registered handlers
215    *
216    * @param string Hook name
217    * @param array Named arguments (key->value pairs)
218    * @return array The (probably) altered hook arguments
219    */
220   public function exec_hook($hook, $args = array())
221   {
463a03 222     if (!is_array($args))
A 223       $args = array('arg' => $args);
224
cc97ea 225     $args += array('abort' => false);
a366a3 226     $this->active_hook = $hook;
cc97ea 227     
T 228     foreach ((array)$this->handlers[$hook] as $callback) {
229       $ret = call_user_func($callback, $args);
230       if ($ret && is_array($ret))
231         $args = $ret + $args;
232       
233       if ($args['abort'])
234         break;
235     }
236     
a366a3 237     $this->active_hook = false;
cc97ea 238     return $args;
T 239   }
240
241
242   /**
243    * Let a plugin register a handler for a specific request
244    *
245    * @param string Action name (_task=mail&_action=plugin.foo)
246    * @param string Plugin name that registers this action
247    * @param mixed Callback: string with global function name or array($obj, 'methodname')
05a631 248    * @param string Task name registered by this plugin
cc97ea 249    */
05a631 250   public function register_action($action, $owner, $callback, $task = null)
cc97ea 251   {
T 252     // check action name
05a631 253     if ($task)
T 254       $action = $task.'.'.$action;
255     else if (strpos($action, 'plugin.') !== 0)
cc97ea 256       $action = 'plugin.'.$action;
T 257     
258     // can register action only if it's not taken or registered by myself
259     if (!isset($this->actionmap[$action]) || $this->actionmap[$action] == $owner) {
260       $this->actions[$action] = $callback;
261       $this->actionmap[$action] = $owner;
262     }
263     else {
10eedb 264       raise_error(array('code' => 523, 'type' => 'php',
A 265         'file' => __FILE__, 'line' => __LINE__,
266         'message' => "Cannot register action $action; already taken by another plugin"), true, false);
cc97ea 267     }
T 268   }
269
270
271   /**
272    * This method handles requests like _task=mail&_action=plugin.foo
273    * It executes the callback function that was registered with the given action.
274    *
275    * @param string Action name
276    */
277   public function exec_action($action)
278   {
279     if (isset($this->actions[$action])) {
280       call_user_func($this->actions[$action]);
281     }
282     else {
10eedb 283       raise_error(array('code' => 524, 'type' => 'php',
A 284         'file' => __FILE__, 'line' => __LINE__,
285         'message' => "No handler found for action $action"), true, true);
cc97ea 286     }
T 287   }
288
289
290   /**
291    * Register a handler function for template objects
292    *
293    * @param string Object name
294    * @param string Plugin name that registers this action
295    * @param mixed Callback: string with global function name or array($obj, 'methodname')
296    */
297   public function register_handler($name, $owner, $callback)
298   {
299     // check name
300     if (strpos($name, 'plugin.') !== 0)
301       $name = 'plugin.'.$name;
302     
303     // can register handler only if it's not taken or registered by myself
304     if (!isset($this->objectsmap[$name]) || $this->objectsmap[$name] == $owner) {
305       $this->output->add_handler($name, $callback);
306       $this->objectsmap[$name] = $owner;
307     }
308     else {
10eedb 309       raise_error(array('code' => 525, 'type' => 'php',
A 310         'file' => __FILE__, 'line' => __LINE__,
311         'message' => "Cannot register template handler $name; already taken by another plugin"), true, false);
cc97ea 312     }
T 313   }
314   
a366a3 315   
T 316   /**
05a631 317    * Register this plugin to be responsible for a specific task
T 318    *
319    * @param string Task name (only characters [a-z0-9_.-] are allowed)
320    * @param string Plugin name that registers this action
321    */
322   public function register_task($task, $owner)
323   {
324     if ($task != asciiwords($task)) {
325       raise_error(array('code' => 526, 'type' => 'php',
326         'file' => __FILE__, 'line' => __LINE__,
327         'message' => "Invalid task name: $task. Only characters [a-z0-9_.-] are allowed"), true, false);
328     }
329     else if (in_array($task, rcmail::$main_tasks)) {
330       raise_error(array('code' => 526, 'type' => 'php',
331         'file' => __FILE__, 'line' => __LINE__,
332         'message' => "Cannot register taks $task; already taken by another plugin or the application itself"), true, false);
333     }
334     else {
335       $this->tasks[$task] = $owner;
336       rcmail::$main_tasks[] = $task;
337       return true;
338     }
339     
340     return false;
341   }
342
343
344   /**
345    * Checks whether the given task is registered by a plugin
346    *
347    * @return boolean True if registered, otherwise false
348    */
349   public function is_plugin_task($task)
350   {
351     return $this->tasks[$task] ? true : false;
352   }
353
354
355   /**
a366a3 356    * Check if a plugin hook is currently processing.
T 357    * Mainly used to prevent loops and recursion.
358    *
359    * @param string Hook to check (optional)
360    * @return boolean True if any/the given hook is currently processed, otherwise false
361    */
362   public function is_processing($hook = null)
363   {
364     return $this->active_hook && (!$hook || $this->active_hook == $hook);
365   }
366   
cc97ea 367   /**
T 368    * Include a plugin script file in the current HTML page
369    */
370   public function include_script($fn)
371   {
372     if ($this->output->type == 'html') {
eb6f19 373       $src = $this->resource_url($fn);
cc97ea 374       $this->output->add_header(html::tag('script', array('type' => "text/javascript", 'src' => $src)));
T 375     }
376   }
377
378   /**
379    * Include a plugin stylesheet in the current HTML page
380    */
381   public function include_stylesheet($fn)
382   {
383     if ($this->output->type == 'html') {
eb6f19 384       $src = $this->resource_url($fn);
cc97ea 385       $this->output->add_header(html::tag('link', array('rel' => "stylesheet", 'type' => "text/css", 'href' => $src)));
T 386     }
387   }
388   
389   /**
390    * Save the given HTML content to be added to a template container
391    */
392   public function add_content($html, $container)
393   {
394     $this->template_contents[$container] .= $html . "\n";
395   }
396   
397   /**
398    * Callback for template_container hooks
399    */
400   private function template_container_hook($attrib)
401   {
402     $container = $attrib['name'];
8448fc 403     return array('content' => $attrib['content'] . $this->template_contents[$container]);
cc97ea 404   }
T 405   
406   /**
407    * Make the given file name link into the plugins directory
408    */
eb6f19 409   private function resource_url($fn)
cc97ea 410   {
23a2ee 411     if ($fn[0] != '/' && !preg_match('|^https?://|i', $fn))
cc97ea 412       return $this->url . $fn;
T 413     else
414       return $fn;
415   }
416
417 }
418