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

Last change on this file since 3827 was 3827, checked in by alec, 3 years ago
  • Fix double slash in plugin directory path (#1486872)
  • 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_dir = unslashify($plugins_dir->path);
83    $plugins_enabled = (array)$rcmail->config->get('plugins', array());
84
85    foreach ($plugins_enabled as $plugin_name) {
86      $fn = $plugins_dir . DIRECTORY_SEPARATOR . $plugin_name . DIRECTORY_SEPARATOR . $plugin_name . '.php';
87
88      if (file_exists($fn)) {
89        include($fn);
90
91        // instantiate class if exists
92        if (class_exists($plugin_name, false)) {
93          $plugin = new $plugin_name($this);
94          // check inheritance and task specification
95          if (is_subclass_of($plugin, 'rcube_plugin') && (!$plugin->task || preg_match('/^('.$plugin->task.')$/i', $rcmail->task))) {
96            $plugin->init();
97            $this->plugins[] = $plugin;
98          }
99        }
100        else {
101          raise_error(array('code' => 520, 'type' => 'php',
102            'file' => __FILE__, 'line' => __LINE__,
103            'message' => "No plugin class $plugin_name found in $fn"), true, false);
104        }
105      }
106      else {
107        raise_error(array('code' => 520, 'type' => 'php',
108          'file' => __FILE__, 'line' => __LINE__,
109          'message' => "Failed to load plugin file $fn"), true, false);
110      }
111    }
112   
113    // check existance of all required core plugins
114    foreach ($this->required_plugins as $plugin_name) {
115      $loaded = false;
116      foreach ($this->plugins as $plugin) {
117        if ($plugin instanceof $plugin_name) {
118          $loaded = true;
119          break;
120        }
121      }
122     
123      // load required core plugin if no derivate was found
124      if (!$loaded) {
125        $fn = $plugins_dir . DIRECTORY_SEPARATOR . $plugin_name . DIRECTORY_SEPARATOR . $plugin_name . '.php';
126
127        if (file_exists($fn)) {
128          include_once($fn);
129         
130          if (class_exists($plugin_name, false)) {
131            $plugin = new $plugin_name($this);
132            // check inheritance
133            if (is_subclass_of($plugin, 'rcube_plugin')) {
134              if (!$plugin->task || preg_match('/('.$plugin->task.')/i', $rcmail->task)) {
135                $plugin->init();
136                $this->plugins[] = $plugin;
137              }
138              $loaded = true;
139            }
140          }
141        }
142      }
143     
144      // trigger fatal error if still not loaded
145      if (!$loaded) {
146        raise_error(array('code' => 520, 'type' => 'php',
147          'file' => __FILE__, 'line' => __LINE__,
148          'message' => "Requried plugin $plugin_name was not loaded"), true, true);
149      }
150    }
151
152    // register an internal hook
153    $this->register_hook('template_container', array($this, 'template_container_hook'));
154   
155    // maybe also register a shudown function which triggers shutdown functions of all plugin objects
156  }
157 
158 
159  /**
160   * Allows a plugin object to register a callback for a certain hook
161   *
162   * @param string Hook name
163   * @param mixed String with global function name or array($obj, 'methodname')
164   */
165  public function register_hook($hook, $callback)
166  {
167    if (is_callable($callback))
168      $this->handlers[$hook][] = $callback;
169    else
170      raise_error(array('code' => 521, 'type' => 'php',
171        'file' => __FILE__, 'line' => __LINE__,
172        'message' => "Invalid callback function for $hook"), true, false);
173  }
174 
175 
176  /**
177   * Triggers a plugin hook.
178   * This is called from the application and executes all registered handlers
179   *
180   * @param string Hook name
181   * @param array Named arguments (key->value pairs)
182   * @return array The (probably) altered hook arguments
183   */
184  public function exec_hook($hook, $args = array())
185  {
186    if (!is_array($args))
187      $args = array('arg' => $args);
188
189    $args += array('abort' => false);
190    $this->active_hook = $hook;
191   
192    foreach ((array)$this->handlers[$hook] as $callback) {
193      $ret = call_user_func($callback, $args);
194      if ($ret && is_array($ret))
195        $args = $ret + $args;
196     
197      if ($args['abort'])
198        break;
199    }
200   
201    $this->active_hook = false;
202    return $args;
203  }
204
205
206  /**
207   * Let a plugin register a handler for a specific request
208   *
209   * @param string Action name (_task=mail&_action=plugin.foo)
210   * @param string Plugin name that registers this action
211   * @param mixed Callback: string with global function name or array($obj, 'methodname')
212   * @param string Task name registered by this plugin
213   */
214  public function register_action($action, $owner, $callback, $task = null)
215  {
216    // check action name
217    if ($task)
218      $action = $task.'.'.$action;
219    else if (strpos($action, 'plugin.') !== 0)
220      $action = 'plugin.'.$action;
221   
222    // can register action only if it's not taken or registered by myself
223    if (!isset($this->actionmap[$action]) || $this->actionmap[$action] == $owner) {
224      $this->actions[$action] = $callback;
225      $this->actionmap[$action] = $owner;
226    }
227    else {
228      raise_error(array('code' => 523, 'type' => 'php',
229        'file' => __FILE__, 'line' => __LINE__,
230        'message' => "Cannot register action $action; already taken by another plugin"), true, false);
231    }
232  }
233
234
235  /**
236   * This method handles requests like _task=mail&_action=plugin.foo
237   * It executes the callback function that was registered with the given action.
238   *
239   * @param string Action name
240   */
241  public function exec_action($action)
242  {
243    if (isset($this->actions[$action])) {
244      call_user_func($this->actions[$action]);
245    }
246    else {
247      raise_error(array('code' => 524, 'type' => 'php',
248        'file' => __FILE__, 'line' => __LINE__,
249        'message' => "No handler found for action $action"), true, true);
250    }
251  }
252
253
254  /**
255   * Register a handler function for template objects
256   *
257   * @param string Object name
258   * @param string Plugin name that registers this action
259   * @param mixed Callback: string with global function name or array($obj, 'methodname')
260   */
261  public function register_handler($name, $owner, $callback)
262  {
263    // check name
264    if (strpos($name, 'plugin.') !== 0)
265      $name = 'plugin.'.$name;
266   
267    // can register handler only if it's not taken or registered by myself
268    if (!isset($this->objectsmap[$name]) || $this->objectsmap[$name] == $owner) {
269      $this->output->add_handler($name, $callback);
270      $this->objectsmap[$name] = $owner;
271    }
272    else {
273      raise_error(array('code' => 525, 'type' => 'php',
274        'file' => __FILE__, 'line' => __LINE__,
275        'message' => "Cannot register template handler $name; already taken by another plugin"), true, false);
276    }
277  }
278 
279 
280  /**
281   * Register this plugin to be responsible for a specific task
282   *
283   * @param string Task name (only characters [a-z0-9_.-] are allowed)
284   * @param string Plugin name that registers this action
285   */
286  public function register_task($task, $owner)
287  {
288    if ($task != asciiwords($task)) {
289      raise_error(array('code' => 526, 'type' => 'php',
290        'file' => __FILE__, 'line' => __LINE__,
291        'message' => "Invalid task name: $task. Only characters [a-z0-9_.-] are allowed"), true, false);
292    }
293    else if (in_array($task, rcmail::$main_tasks)) {
294      raise_error(array('code' => 526, 'type' => 'php',
295        'file' => __FILE__, 'line' => __LINE__,
296        'message' => "Cannot register taks $task; already taken by another plugin or the application itself"), true, false);
297    }
298    else {
299      $this->tasks[$task] = $owner;
300      rcmail::$main_tasks[] = $task;
301      return true;
302    }
303   
304    return false;
305  }
306
307
308  /**
309   * Checks whether the given task is registered by a plugin
310   *
311   * @return boolean True if registered, otherwise false
312   */
313  public function is_plugin_task($task)
314  {
315    return $this->tasks[$task] ? true : false;
316  }
317
318
319  /**
320   * Check if a plugin hook is currently processing.
321   * Mainly used to prevent loops and recursion.
322   *
323   * @param string Hook to check (optional)
324   * @return boolean True if any/the given hook is currently processed, otherwise false
325   */
326  public function is_processing($hook = null)
327  {
328    return $this->active_hook && (!$hook || $this->active_hook == $hook);
329  }
330 
331  /**
332   * Include a plugin script file in the current HTML page
333   */
334  public function include_script($fn)
335  {
336    if ($this->output->type == 'html') {
337      $src = $this->resource_url($fn);
338      $this->output->add_header(html::tag('script', array('type' => "text/javascript", 'src' => $src)));
339    }
340  }
341
342  /**
343   * Include a plugin stylesheet in the current HTML page
344   */
345  public function include_stylesheet($fn)
346  {
347    if ($this->output->type == 'html') {
348      $src = $this->resource_url($fn);
349      $this->output->add_header(html::tag('link', array('rel' => "stylesheet", 'type' => "text/css", 'href' => $src)));
350    }
351  }
352 
353  /**
354   * Save the given HTML content to be added to a template container
355   */
356  public function add_content($html, $container)
357  {
358    $this->template_contents[$container] .= $html . "\n";
359  }
360 
361  /**
362   * Callback for template_container hooks
363   */
364  private function template_container_hook($attrib)
365  {
366    $container = $attrib['name'];
367    return array('content' => $attrib['content'] . $this->template_contents[$container]);
368  }
369 
370  /**
371   * Make the given file name link into the plugins directory
372   */
373  private function resource_url($fn)
374  {
375    if ($fn[0] != '/' && !preg_match('|^https?://|i', $fn))
376      return $this->url . $fn;
377    else
378      return $fn;
379  }
380
381}
382
Note: See TracBrowser for help on using the repository browser.