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

Last change on this file since 3840 was 3840, checked in by alec, 3 years ago
  • Unify hooks names, see rcube_plugin_api::deprecated_hooks for complete list (old names are supported without errors nor warnings)
  • Property svn:keywords set to Id
File size: 12.9 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  // Deprecated names of hooks, will be removed after 0.5-stable release
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
73  /**
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  {
93    $this->dir = INSTALL_PATH . $this->url;
94  }
95 
96 
97  /**
98   * Load and init all enabled plugins
99   *
100   * This has to be done after rcmail::load_gui() or rcmail::json_init()
101   * was called because plugins need to have access to rcmail->output
102   */
103  public function init()
104  {
105    $rcmail = rcmail::get_instance();
106    $this->output = $rcmail->output;
107
108    $plugins_dir = dir($this->dir);
109    $plugins_dir = unslashify($plugins_dir->path);
110    $plugins_enabled = (array)$rcmail->config->get('plugins', array());
111
112    foreach ($plugins_enabled as $plugin_name) {
113      $fn = $plugins_dir . DIRECTORY_SEPARATOR . $plugin_name . DIRECTORY_SEPARATOR . $plugin_name . '.php';
114
115      if (file_exists($fn)) {
116        include($fn);
117
118        // instantiate class if exists
119        if (class_exists($plugin_name, false)) {
120          $plugin = new $plugin_name($this);
121          // check inheritance and task specification
122          if (is_subclass_of($plugin, 'rcube_plugin') && (!$plugin->task || preg_match('/^('.$plugin->task.')$/i', $rcmail->task))) {
123            $plugin->init();
124            $this->plugins[] = $plugin;
125          }
126        }
127        else {
128          raise_error(array('code' => 520, 'type' => 'php',
129            'file' => __FILE__, 'line' => __LINE__,
130            'message' => "No plugin class $plugin_name found in $fn"), true, false);
131        }
132      }
133      else {
134        raise_error(array('code' => 520, 'type' => 'php',
135          'file' => __FILE__, 'line' => __LINE__,
136          'message' => "Failed to load plugin file $fn"), true, false);
137      }
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) {
152        $fn = $plugins_dir . DIRECTORY_SEPARATOR . $plugin_name . DIRECTORY_SEPARATOR . $plugin_name . '.php';
153
154        if (file_exists($fn)) {
155          include_once($fn);
156         
157          if (class_exists($plugin_name, false)) {
158            $plugin = new $plugin_name($this);
159            // check inheritance
160            if (is_subclass_of($plugin, 'rcube_plugin')) {
161              if (!$plugin->task || preg_match('/('.$plugin->task.')/i', $rcmail->task)) {
162                $plugin->init();
163                $this->plugins[] = $plugin;
164              }
165              $loaded = true;
166            }
167          }
168        }
169      }
170     
171      // trigger fatal error if still not loaded
172      if (!$loaded) {
173        raise_error(array('code' => 520, 'type' => 'php',
174          'file' => __FILE__, 'line' => __LINE__,
175          'message' => "Requried plugin $plugin_name was not loaded"), true, true);
176      }
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  {
194    if (is_callable($callback)) {
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      }
203      $this->handlers[$hook][] = $callback;
204    }
205    else
206      raise_error(array('code' => 521, 'type' => 'php',
207        'file' => __FILE__, 'line' => __LINE__,
208        'message' => "Invalid callback function for $hook"), true, false);
209  }
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  {
222    if (!is_array($args))
223      $args = array('arg' => $args);
224
225    $args += array('abort' => false);
226    $this->active_hook = $hook;
227   
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   
237    $this->active_hook = false;
238    return $args;
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')
248   * @param string Task name registered by this plugin
249   */
250  public function register_action($action, $owner, $callback, $task = null)
251  {
252    // check action name
253    if ($task)
254      $action = $task.'.'.$action;
255    else if (strpos($action, 'plugin.') !== 0)
256      $action = 'plugin.'.$action;
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 {
264      raise_error(array('code' => 523, 'type' => 'php',
265        'file' => __FILE__, 'line' => __LINE__,
266        'message' => "Cannot register action $action; already taken by another plugin"), true, false);
267    }
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 {
283      raise_error(array('code' => 524, 'type' => 'php',
284        'file' => __FILE__, 'line' => __LINE__,
285        'message' => "No handler found for action $action"), true, true);
286    }
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 {
309      raise_error(array('code' => 525, 'type' => 'php',
310        'file' => __FILE__, 'line' => __LINE__,
311        'message' => "Cannot register template handler $name; already taken by another plugin"), true, false);
312    }
313  }
314 
315 
316  /**
317   * Register this plugin to be responsible for a specific task
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  /**
356   * Check if a plugin hook is currently processing.
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 
367  /**
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') {
373      $src = $this->resource_url($fn);
374      $this->output->add_header(html::tag('script', array('type' => "text/javascript", 'src' => $src)));
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') {
384      $src = $this->resource_url($fn);
385      $this->output->add_header(html::tag('link', array('rel' => "stylesheet", 'type' => "text/css", 'href' => $src)));
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'];
403    return array('content' => $attrib['content'] . $this->template_contents[$container]);
404  }
405 
406  /**
407   * Make the given file name link into the plugins directory
408   */
409  private function resource_url($fn)
410  {
411    if ($fn[0] != '/' && !preg_match('|^https?://|i', $fn))
412      return $this->url . $fn;
413    else
414      return $fn;
415  }
416
417}
418
Note: See TracBrowser for help on using the repository browser.