Projet

Général

Profil

Paste
Télécharger (31,8 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / ctools / includes / plugins.inc @ e4c061ad

1
<?php
2

    
3
/**
4
 * @file
5
 *
6
 * Contains routines to organize and load plugins. It allows a special
7
 * variation of the hook system so that plugins can be kept in separate
8
 * .inc files, and can be either loaded all at once or loaded only when
9
 * necessary.
10
 */
11

    
12
/**
13
 * Get an array of information about modules that support an API.
14
 *
15
 * This will ask each module if they support the given API, and if they do
16
 * it will return an array of information about the modules that do.
17
 *
18
 * This function invokes hook_ctools_api. This invocation is statically
19
 * cached, so feel free to call it as often per page run as you like, it
20
 * will cost very little.
21
 *
22
 * This function can be used as an alternative to module_implements and can
23
 * thus be used to find a precise list of modules that not only support
24
 * a given hook (aka 'api') but also restrict to only modules that use
25
 * the given version. This will allow multiple modules moving at different
26
 * paces to still be able to work together and, in the event of a mismatch,
27
 * either fall back to older behaviors or simply cease loading, which is
28
 * still better than a crash.
29
 *
30
 * @param $owner
31
 *   The name of the module that controls the API.
32
 * @param $api
33
 *   The name of the api. The api name forms the file name:
34
 *   $module.$api.inc
35
 * @param $minimum_version
36
 *   The lowest version API that is compatible with this one. If a module
37
 *   reports its API as older than this, its files will not be loaded. This
38
 *   should never change during operation.
39
 * @param $current_version
40
 *   The current version of the api. If a module reports its minimum API as
41
 *   higher than this, its files will not be loaded. This should never change
42
 *   during operation.
43
 *
44
 * @return
45
 *   An array of API information, keyed by module. Each module's information will
46
 *   contain:
47
 *   - 'version': The version of the API required by the module. The module
48
 *     should use the lowest number it can support so that the widest range
49
 *     of supported versions can be used.
50
 *   - 'path': If not provided, this will be the module's path. This is
51
 *     where the module will store any subsidiary files. This differs from
52
 *     plugin paths which are figured separately.
53
 *
54
 *   APIs can request any other information to be placed here that they might
55
 *   need. This should be in the documentation for that particular API.
56
 */
57
function ctools_plugin_api_info($owner, $api, $minimum_version, $current_version) {
58
  $cache = &drupal_static(__FUNCTION__, array());
59
  if (!isset($cache[$owner][$api])) {
60
    $cache[$owner][$api] = array();
61

    
62
    $hook = ctools_plugin_api_get_hook($owner, $api);
63

    
64
    foreach (module_implements($hook) as $module) {
65
      $function = $module . '_' . $hook;
66
      $info = $function($owner, $api);
67
      $version = NULL;
68
      // This is added to make hook_views_api() compatible with this, since
69
      // views used a different version key.
70
      if (isset($info['version'])) {
71
        $version = $info['version'];
72
      }
73
      else if (isset($info['api'])) {
74
        $version = $info['api'];
75
      }
76

    
77
      if (!isset($version)) {
78
        continue;
79
      }
80

    
81
      // Only process if version is between minimum and current, inclusive.
82
      if (version_compare($version, $minimum_version, '>=') && version_compare($version, $current_version, '<=')) {
83
        if (!isset($info['path'])) {
84
          $info['path'] = drupal_get_path('module', $module);
85
        }
86
        $cache[$owner][$api][$module] = $info;
87
      }
88
    }
89

    
90
    // And allow themes to implement these as well.
91
    $themes = _ctools_list_themes();
92
    foreach ($themes as $name => $theme) {
93
      if (!empty($theme->info['api'][$owner][$api])) {
94
        $info = $theme->info['api'][$owner][$api];
95
        if (!isset($info['version'])) {
96
          continue;
97
        }
98

    
99
        // Only process if version is between minimum and current, inclusive.
100
      if (version_compare($info['version'], $minimum_version, '>=') && version_compare($info['version'], $current_version, '<=')) {
101
          if (!isset($info['path'])) {
102
            $info['path'] = '';
103
          }
104
          // Because themes can't easily specify full path, we add it here
105
          // even though we do not for modules:
106
          $info['path'] = drupal_get_path('theme', $name) . '/' . $info['path'];
107
          $cache[$owner][$api][$name] = $info;
108
        }
109
      }
110
    }
111

    
112
    // Allow other modules to hook in.
113
    drupal_alter($hook, $cache[$owner][$api]);
114
  }
115

    
116
  return $cache[$owner][$api];
117
}
118

    
119
/**
120
 * Load a group of API files.
121
 *
122
 * This will ask each module if they support the given API, and if they do
123
 * it will load the specified file name. The API and the file name
124
 * coincide by design.
125
 *
126
 * @param $owner
127
 *   The name of the module that controls the API.
128
 * @param $api
129
 *   The name of the api. The api name forms the file name:
130
 *   $module.$api.inc, though this can be overridden by the module's response.
131
 * @param $minimum_version
132
 *   The lowest version API that is compatible with this one. If a module
133
 *   reports its API as older than this, its files will not be loaded. This
134
 *   should never change during operation.
135
 * @param $current_version
136
 *   The current version of the api. If a module reports its minimum API as
137
 *   higher than this, its files will not be loaded. This should never change
138
 *   during operation.
139
 *
140
 * @return
141
 *   The API information, in case you need it.
142
 */
143
function ctools_plugin_api_include($owner, $api, $minimum_version, $current_version) {
144
  static $already_done = array();
145

    
146
  $info = ctools_plugin_api_info($owner, $api, $minimum_version, $current_version);
147
  foreach ($info as $module => $plugin_info) {
148
    if (!isset($already_done[$owner][$api][$module])) {
149
      if (isset($plugin_info["$api file"])) {
150
        $file = $plugin_info["$api file"];
151
      }
152
      else if (isset($plugin_info['file'])) {
153
        $file = $plugin_info['file'];
154
      }
155
      else {
156
        $file = "$module.$api.inc";
157
      }
158

    
159
      if (file_exists(DRUPAL_ROOT . "/$plugin_info[path]/$file")) {
160
        require_once DRUPAL_ROOT . "/$plugin_info[path]/$file";
161
      }
162
      else if (file_exists(DRUPAL_ROOT . "/$file")) {
163
        require_once DRUPAL_ROOT . "/$file";
164
      }
165
      $already_done[$owner][$api][$module] = TRUE;
166
    }
167
  }
168

    
169
  return $info;
170
}
171

    
172
/**
173
 * Find out what hook to use to determine if modules support an API.
174
 *
175
 * By default, most APIs will use hook_ctools_plugin_api, but some modules
176
 * want sole ownership. This technique lets modules define what hook
177
 * to use.
178
 */
179
function ctools_plugin_api_get_hook($owner, $api) {
180
  // Allow modules to use their own hook for this. The only easy way to do
181
  // this right now is with a magically named function.
182
  if (function_exists($function = $owner . '_' . $api . '_hook_name')) {
183
    $hook = $function();
184
  }
185
  else if (function_exists($function = $owner . '_ctools_plugin_api_hook_name')) {
186
    $hook = $function();
187
  }
188

    
189
  // Do this last so that if the $function above failed to return, we have a
190
  // sane default.
191
  if (empty($hook)) {
192
    $hook = 'ctools_plugin_api';
193
  }
194

    
195
  return $hook;
196
}
197

    
198
/**
199
 * Fetch a group of plugins by name.
200
 *
201
 * @param $module
202
 *   The name of the module that utilizes this plugin system. It will be
203
 *   used to call hook_ctools_plugin_$plugin() to get more data about the plugin.
204
 * @param $type
205
 *   The type identifier of the plugin.
206
 * @param $id
207
 *   If specified, return only information about plugin with this identifier.
208
 *   The system will do its utmost to load only plugins with this id.
209
 *
210
 * @return
211
 *   An array of information arrays about the plugins received. The contents
212
 *   of the array are specific to the plugin.
213
 */
214
function ctools_get_plugins($module, $type, $id = NULL) {
215
  // Store local caches of plugins and plugin info so we don't have to do full
216
  // lookups everytime.
217
  static $drupal_static_fast;
218
  if (!isset($drupal_static_fast)) {
219
    $drupal_static_fast['plugins'] = &drupal_static('ctools_plugins', array());
220
  }
221
  $plugins = &$drupal_static_fast['plugins'];
222

    
223
  $info = ctools_plugin_get_plugin_type_info();
224

    
225
  // Bail out noisily if an invalid module/type combination is requested.
226
  if (!isset($info[$module][$type])) {
227
    watchdog('ctools', 'Invalid plugin module/type combination requested: module @module and type @type', array('@module' => $module, '@type' => $type), WATCHDOG_ERROR);
228
    return array();
229
  }
230

    
231
  // Make sure our plugins array is populated.
232
  if (!isset($plugins[$module][$type])) {
233
    $plugins[$module][$type] = array();
234
  }
235

    
236
  // Attempt to shortcut this whole piece of code if we already have
237
  // the requested plugin:
238
  if ($id && array_key_exists($id, $plugins[$module][$type])) {
239
    return $plugins[$module][$type][$id];
240
  }
241

    
242
  // Store the status of plugin loading. If a module plugin type pair is true,
243
  // then it is fully loaded and no searching or setup needs to be done.
244
  $setup = &drupal_static('ctools_plugin_setup', array());
245

    
246
  // We assume we don't need to build a cache.
247
  $build_cache = FALSE;
248

    
249
  // If the plugin info says this can be cached, check cache first.
250
  if ($info[$module][$type]['cache'] && empty($setup[$module][$type])) {
251
    $cache = cache_get("plugins:$module:$type", $info[$module][$type]['cache table']);
252

    
253
    if (!empty($cache->data)) {
254
      // Cache load succeeded so use the cached plugin list.
255
      $plugins[$module][$type]   = $cache->data;
256
      // Set $setup to true so we know things where loaded.
257
      $setup[$module][$type]     = TRUE;
258
    }
259
    else {
260
      // Cache load failed so store that we need to build and write the cache.
261
      $build_cache = TRUE;
262
    }
263
  }
264

    
265
  // Always load all hooks if we need them. Note we only need them now if the
266
  // plugin asks for them. We can assume that if we have plugins we've already
267
  // called the global hook.
268
  if (!empty($info[$module][$type]['use hooks']) && empty($plugins[$module][$type])) {
269
    $plugins[$module][$type] = ctools_plugin_load_hooks($info[$module][$type]);
270
  }
271

    
272
  // Then see if we should load all files. We only do this if we
273
  // want a list of all plugins or there was a cache miss.
274
  if (empty($setup[$module][$type]) && ($build_cache || !$id)) {
275
    $setup[$module][$type] = TRUE;
276
    $plugins[$module][$type] = array_merge($plugins[$module][$type], ctools_plugin_load_includes($info[$module][$type]));
277
    // If the plugin can have child plugins, and we're loading all plugins,
278
    // go through the list of plugins we have and find child plugins.
279
    if (!$id && !empty($info[$module][$type]['child plugins'])) {
280
      // If a plugin supports children, go through each plugin and ask.
281
      $temp = array();
282
      foreach ($plugins[$module][$type] as $name => $plugin) {
283
        // The strpos ensures that we don't try to find children for plugins
284
        // that are already children.
285
        if (!empty($plugin['get children']) && function_exists($plugin['get children']) && strpos($name, ':') === FALSE) {
286
          $temp = array_merge($plugin['get children']($plugin, $name), $temp);
287
        }
288
        else {
289
          $temp[$name] = $plugin;
290
        }
291
      }
292
      $plugins[$module][$type] = $temp;
293
    }
294
  }
295

    
296

    
297
  // If we were told earlier that this is cacheable and the cache was
298
  // empty, give something back.
299
  if ($build_cache) {
300
    cache_set("plugins:$module:$type", $plugins[$module][$type], $info[$module][$type]['cache table']);
301
  }
302

    
303
  // If no id was requested, we are finished here:
304
  if (!$id) {
305
    // Use array_filter because looking for unknown plugins could cause NULL
306
    // entries to appear in the list later.
307
    return array_filter($plugins[$module][$type]);
308
  }
309

    
310
  // Check to see if we need to look for the file
311
  if (!array_key_exists($id, $plugins[$module][$type])) {
312
    // If we can have child plugins, check to see if the plugin name is in the
313
    // format of parent:child and break it up if it is.
314
    if (!empty($info[$module][$type]['child plugins']) && strpos($id, ':') !== FALSE) {
315
      list($parent, $child) = explode(':', $id, 2);
316
    }
317
    else {
318
      $parent = $id;
319
    }
320

    
321
    if (!array_key_exists($parent, $plugins[$module][$type])) {
322
      $result = ctools_plugin_load_includes($info[$module][$type], $parent);
323
      // Set to either what was returned or NULL.
324
      $plugins[$module][$type][$parent] = isset($result[$parent]) ? $result[$parent] : NULL;
325
    }
326

    
327
    // If we are looking for a child, and have the parent, ask the parent for the child.
328
    if (!empty($child) && !empty($plugins[$module][$type][$parent]) && function_exists($plugins[$module][$type][$parent]['get child'])) {
329
      $plugins[$module][$type][$id] = $plugins[$module][$type][$parent]['get child']($plugins[$module][$type][$parent], $parent, $child);
330
    }
331
  }
332

    
333
  // At this point we should either have the plugin, or a NULL.
334
  return $plugins[$module][$type][$id];
335
}
336

    
337
/**
338
 * Return the full list of plugin type info for all plugin types registered in
339
 * the current system.
340
 *
341
 * This function manages its own cache getting/setting, and should always be
342
 * used as the way to initially populate the list of plugin types. Make sure you
343
 * call this function to properly populate the ctools_plugin_type_info static
344
 * variable.
345
 *
346
 * @return array
347
 *   A multilevel array of plugin type info, the outer array keyed on module
348
 *   name and each inner array keyed on plugin type name.
349
 */
350
function ctools_plugin_get_plugin_type_info($flush = FALSE) {
351
  static $drupal_static_fast;
352
  if (!isset($drupal_static_fast)) {
353
    $drupal_static_fast['info_loaded'] = &drupal_static('ctools_plugin_type_info_loaded', FALSE);
354
    $drupal_static_fast['all_type_info'] = &drupal_static('ctools_plugin_type_info', array());
355
  }
356
  $info_loaded = &$drupal_static_fast['info_loaded'];
357
  $all_type_info = &$drupal_static_fast['all_type_info'];
358

    
359
  // Only trigger info loading once.
360
  if ($info_loaded && !$flush) {
361
    return $all_type_info;
362
  }
363
  $info_loaded = TRUE;
364

    
365
  $cache = cache_get('ctools_plugin_type_info');
366
  if (!empty($cache->data) && !$flush) {
367
    // Plugin type info cache is warm, use it.
368
    $all_type_info = $cache->data;
369
  }
370
  else {
371
    // Cache expired, refill it.
372
    foreach (module_implements('ctools_plugin_type') as $module) {
373
      $module_infos = array();
374
      $function = $module . '_ctools_plugin_type';
375
      $module_infos = $function();
376

    
377
      foreach ($module_infos as $plugin_type_name => $plugin_type_info) {
378
        // Apply defaults. Array addition will not overwrite pre-existing keys.
379
        $plugin_type_info += array(
380
          'module' => $module,
381
          'type' => $plugin_type_name,
382
          'cache' => FALSE,
383
          'cache table' => 'cache',
384
          'classes' => array(),
385
          'use hooks' => FALSE,
386
          'defaults' => array(),
387
          'process' => '',
388
          'alterable' => TRUE,
389
          'extension' => 'inc',
390
          'info file' => FALSE,
391
          'hook' => $module . '_' . $plugin_type_name,
392
          'load themes' => FALSE,
393
        );
394
        $all_type_info[$module][$plugin_type_name] = $plugin_type_info;
395
      }
396
    }
397
    cache_set('ctools_plugin_type_info', $all_type_info);
398
  }
399

    
400
  return $all_type_info;
401
}
402

    
403
/**
404
 * Reset all static caches that affect the result of ctools_get_plugins().
405
 */
406
function ctools_get_plugins_reset() {
407
  drupal_static_reset('ctools_plugins');
408
  drupal_static_reset('ctools_plugin_setup');
409
  drupal_static_reset('ctools_plugin_load_includes');
410
  drupal_static_reset('ctools_plugin_api_info');
411
}
412

    
413
/**
414
 * Load plugins from a directory.
415
 *
416
 * @param $info
417
 *   The plugin info as returned by ctools_plugin_get_info()
418
 * @param $file
419
 *   The file to load if we're looking for just one particular plugin.
420
 *
421
 * @return
422
 *   An array of information created for this plugin.
423
 */
424
function ctools_plugin_load_includes($info, $filename = NULL) {
425
  // Keep a static array so we don't hit file_scan_directory more than necessary.
426
  $all_files = &drupal_static(__FUNCTION__, array());
427

    
428
  // store static of plugin arrays for reference because they can't be reincluded.
429
  static $plugin_arrays = array();
430

    
431
  if (!isset($all_files[$info['module']][$info['type']])) {
432
    $cache = cache_get("ctools_plugin_files:$info[module]:$info[type]");
433
    if ($cache) {
434
      $all_files[$info['module']][$info['type']] = $cache->data;
435
    }
436
    // Do not attempt any file scan even if the cached entry was empty.
437
    // A NULL entry here would mean the plugin just does not exists, and we
438
    // cannot afford to run file scan on production sites normal run.
439
    elseif (!isset($all_files[$info['module']][$info['type']])) {
440
      $all_files[$info['module']][$info['type']] = array();
441
      // Load all our plugins.
442
      $directories = ctools_plugin_get_directories($info);
443
      $extension = (empty($info['info file']) || ($info['extension'] != 'inc')) ? $info['extension'] : 'info';
444

    
445
      foreach ($directories as $module => $path) {
446
        $all_files[$info['module']][$info['type']][$module] = file_scan_directory($path, '/\.' . $extension . '$/', array('key' => 'name'));
447
      }
448

    
449
      cache_set("ctools_plugin_files:$info[module]:$info[type]", $all_files[$info['module']][$info['type']]);
450
    }
451
  }
452
  $file_list = $all_files[$info['module']][$info['type']];
453
  $plugins = array();
454

    
455
  // Iterate through all the plugin .inc files, load them and process the hook
456
  // that should now be available.
457
  foreach (array_filter($file_list) as $module => $files) {
458
    if ($filename) {
459
      $files = isset($files[$filename]) ? array($filename => $files[$filename]) : array();
460
    }
461
    foreach ($files as $file) {
462
      if (!empty($info['info file'])) {
463
        // Parse a .info file
464
        $result = ctools_plugin_process_info($info, $module, $file);
465
      }
466
      else {
467
        // Parse a hook.
468
        $plugin = NULL; // ensure that we don't have something leftover from earlier.
469

    
470
        if (isset($plugin_arrays[$file->uri])) {
471
          $identifier = $plugin_arrays[$file->uri];
472
        }
473
        else {
474

    
475
          require_once DRUPAL_ROOT . '/' . $file->uri;
476
          // .inc files have a special format for the hook identifier.
477
          // For example, 'foo.inc' in the module 'mogul' using the plugin
478
          // whose hook is named 'borg_type' should have a function named (deep breath)
479
          // mogul_foo_borg_type()
480

    
481
          // If, however, the .inc file set the quasi-global $plugin array, we
482
          // can use that and not even call a function. Set the $identifier
483
          // appropriately and ctools_plugin_process() will handle it.
484
          if (isset($plugin)) {
485
            $plugin_arrays[$file->uri] = $plugin;
486
            $identifier = $plugin;
487
          }
488
          else {
489
            $identifier = $module . '_' . $file->name;
490
          }
491
        }
492

    
493
        $result = ctools_plugin_process($info, $module, $identifier, dirname($file->uri), basename($file->uri), $file->name);
494
      }
495
      if (is_array($result)) {
496
        $plugins = array_merge($plugins, $result);
497
      }
498
    }
499
  }
500
  return $plugins;
501
}
502

    
503
/**
504
 * Get a list of directories to search for plugins of the given type.
505
 *
506
 * This utilizes hook_ctools_plugin_directory() to determine a complete list of
507
 * directories. Only modules that implement this hook and return a string
508
 * value will have their directories included.
509
 *
510
 * @param $info
511
 *   The $info array for the plugin as returned by ctools_plugin_get_info().
512
 *
513
 * @return array $directories
514
 *   An array of directories to search.
515
 */
516
function ctools_plugin_get_directories($info) {
517
  $directories = array();
518

    
519
  foreach (module_implements('ctools_plugin_directory') as $module) {
520
    $function = $module . '_ctools_plugin_directory';
521
    $result = $function($info['module'], $info['type']);
522
    if ($result && is_string($result)) {
523
      $directories[$module] = drupal_get_path('module', $module) . '/' . $result;
524
    }
525
  }
526

    
527
  if (!empty($info['load themes'])) {
528
    $themes = _ctools_list_themes();
529
    foreach ($themes as $name => $theme) {
530
      if (!empty($theme->info['plugins'][$info['module']][$info['type']])) {
531
        $directories[$name] = drupal_get_path('theme', $name) . '/' . $theme->info['plugins'][$info['module']][$info['type']];
532
      }
533
    }
534
  }
535
  return $directories;
536
}
537

    
538
/**
539
 * Helper function to build a ctools-friendly list of themes capable of
540
 * providing plugins.
541
 *
542
 * @return array $themes
543
 *   A list of themes that can act as plugin providers, sorted parent-first with
544
 *   the active theme placed last.
545
 */
546
function _ctools_list_themes() {
547
  static $themes;
548
  if (is_null($themes)) {
549
    $current = variable_get('theme_default', FALSE);
550
    $themes = $active = array();
551
    $all_themes = list_themes();
552
    foreach ($all_themes as $name => $theme) {
553
      // Only search from active themes
554
      if (empty($theme->status) && $theme->name != $current) {
555
        continue;
556
      }
557
      $active[$name] = $theme;
558
      // Prior to drupal 6.14, $theme->base_themes does not exist. Build it.
559
      if (!isset($theme->base_themes) && !empty($theme->base_theme)) {
560
        $active[$name]->base_themes = ctools_find_base_themes($all_themes, $name);
561
      }
562
    }
563

    
564
    // Construct a parent-first list of all themes
565
    foreach ($active as $name => $theme) {
566
      $base_themes = isset($theme->base_themes) ? $theme->base_themes : array();
567
      $themes = array_merge($themes, $base_themes, array($name => $theme->info['name']));
568
    }
569
    // Put the actual theme info objects into the array
570
    foreach (array_keys($themes) as $name) {
571
      if (isset($all_themes[$name])) {
572
        $themes[$name] = $all_themes[$name];
573
      }
574
    }
575

    
576
    // Make sure the current default theme always gets the last word
577
    if ($current_key = array_search($current, array_keys($themes))) {
578
      $themes += array_splice($themes, $current_key, 1);
579
    }
580
  }
581
  return $themes;
582
}
583

    
584

    
585
/**
586
 * Find all the base themes for the specified theme.
587
 *
588
 * Themes can inherit templates and function implementations from earlier themes.
589
 *
590
 * NOTE: this is a verbatim copy of system_find_base_themes(), which was not
591
 * implemented until 6.14. It is included here only as a fallback for outdated
592
 * versions of drupal core.
593
 *
594
 * @param $themes
595
 *   An array of available themes.
596
 * @param $key
597
 *   The name of the theme whose base we are looking for.
598
 * @param $used_keys
599
 *   A recursion parameter preventing endless loops.
600
 * @return
601
 *   Returns an array of all of the theme's ancestors; the first element's value
602
 *   will be NULL if an error occurred.
603
 */
604
function ctools_find_base_themes($themes, $key, $used_keys = array()) {
605
  $base_key = $themes[$key]->info['base theme'];
606
  // Does the base theme exist?
607
  if (!isset($themes[$base_key])) {
608
    return array($base_key => NULL);
609
  }
610

    
611
  $current_base_theme = array($base_key => $themes[$base_key]->info['name']);
612

    
613
  // Is the base theme itself a child of another theme?
614
  if (isset($themes[$base_key]->info['base theme'])) {
615
    // Do we already know the base themes of this theme?
616
    if (isset($themes[$base_key]->base_themes)) {
617
      return $themes[$base_key]->base_themes + $current_base_theme;
618
    }
619
    // Prevent loops.
620
    if (!empty($used_keys[$base_key])) {
621
      return array($base_key => NULL);
622
    }
623
    $used_keys[$base_key] = TRUE;
624
    return ctools_find_base_themes($themes, $base_key, $used_keys) + $current_base_theme;
625
  }
626
  // If we get here, then this is our parent theme.
627
  return $current_base_theme;
628
}
629

    
630

    
631
/**
632
 * Load plugin info for the provided hook; this is handled separately from
633
 * plugins from files.
634
 *
635
 * @param $info
636
 *   The info array about the plugin as created by ctools_plugin_get_info()
637
 *
638
 * @return
639
 *   An array of info supplied by any hook implementations.
640
 */
641
function ctools_plugin_load_hooks($info) {
642
  $hooks = array();
643
  foreach (module_implements($info['hook']) as $module) {
644
    $result = ctools_plugin_process($info, $module, $module, drupal_get_path('module', $module));
645
    if (is_array($result)) {
646
      $hooks = array_merge($hooks, $result);
647
    }
648
  }
649
  return $hooks;
650
}
651

    
652
/**
653
 * Process a single hook implementation of a ctools plugin.
654
 *
655
 * @param $info
656
 *   The $info array about the plugin as returned by ctools_plugin_get_info()
657
 * @param $module
658
 *   The module that implements the plugin being processed.
659
 * @param $identifier
660
 *   The plugin identifier, which is used to create the name of the hook
661
 *   function being called.
662
 * @param $path
663
 *   The path where files utilized by this plugin will be found.
664
 * @param $file
665
 *   The file that was loaded for this plugin, if it exists.
666
 * @param $base
667
 *   The base plugin name to use. If a file was loaded for the plugin, this
668
 *   is the plugin to assume must be present. This is used to automatically
669
 *   translate the array to make the syntax more friendly to plugin
670
 *   implementors.
671
 */
672
function ctools_plugin_process($info, $module, $identifier, $path, $file = NULL, $base = NULL) {
673
  if (is_array($identifier)) {
674
    $result = $identifier;
675
  }
676
  else {
677
    $function = $identifier . '_' . $info['hook'];
678
    if (!function_exists($function)) {
679
      return NULL;
680
    }
681
    $result = $function($info);
682
    if (!isset($result) || !is_array($result)) {
683
      return NULL;
684
    }
685
  }
686

    
687
  // Automatically convert to the proper format that lets plugin implementations
688
  // not nest arrays as deeply as they used to, but still support the older
689
  // format where they do:
690
  if ($base && (!isset($result[$base]) || !is_array($result[$base]))) {
691
    $result = array($base => $result);
692
  }
693

    
694
  return _ctools_process_data($result, $info, $module, $path, $file);
695
}
696

    
697
/**
698
 * Fill in default values and run hooks for data loaded for one or
699
 * more plugins.
700
 */
701
function _ctools_process_data($result, $plugin_type_info, $module, $path, $file) {
702
  // Fill in global defaults.
703
  foreach ($result as $name => $plugin) {
704
    $result[$name] += array(
705
      'module' => $module,
706
      'name' => $name,
707
      'path' => $path,
708
      'file' => $file,
709
      'plugin module' => $plugin_type_info['module'],
710
      'plugin type' => $plugin_type_info['type'],
711
    );
712

    
713
    // Fill in plugin-specific defaults, if they exist.
714
    if (!empty($plugin_type_info['defaults'])) {
715
      if (is_array($plugin_type_info['defaults'])) {
716
        $result[$name] += $plugin_type_info['defaults'];
717
      }
718
    }
719

    
720
    // Allow the plugin to be altered before processing.
721
    if (!empty($plugin_type_info['alterable']) && $plugin_type_info['alterable']) {
722
      drupal_alter('ctools_plugin_pre', $result[$name], $plugin_type_info);
723
    }
724

    
725
    // Allow the plugin owner to do additional processing.
726
    if (!empty($plugin_type_info['process']) && $function = ctools_plugin_get_function($plugin_type_info, 'process')) {
727
      $function($result[$name], $plugin_type_info);
728
    }
729

    
730
    // Allow the plugin to be altered after processing.
731
    if (!empty($plugin_type_info['alterable']) && $plugin_type_info['alterable']) {
732
      drupal_alter('ctools_plugin_post', $result[$name], $plugin_type_info);
733
    }
734
  }
735
  return $result;
736
}
737

    
738

    
739
/**
740
 * Process an info file for plugin information, rather than a hook.
741
 */
742
function ctools_plugin_process_info($info, $module, $file) {
743
  $result = drupal_parse_info_file($file->uri);
744
  if ($result) {
745
    $result = array($file->name => $result);
746
    return _ctools_process_data($result, $info, $module, dirname($file->uri), basename($file->uri));
747
  }
748
}
749

    
750
/**
751
 * Ask a module for info about a particular plugin type.
752
 */
753
function ctools_plugin_get_info($module, $type) {
754
  $all_info = ctools_plugin_get_plugin_type_info();
755
  return isset($all_info[$module][$type]) ? $all_info[$module][$type] : array();
756
}
757

    
758
/**
759
 * Get a function from a plugin, if it exists. If the plugin is not already
760
 * loaded, try ctools_plugin_load_function() instead.
761
 *
762
 * @param $plugin_definition
763
 *   The loaded plugin type.
764
 * @param $function_name
765
 *   The identifier of the function. For example, 'settings form'.
766
 *
767
 * @return
768
 *   The actual name of the function to call, or NULL if the function
769
 *   does not exist.
770
 */
771
function ctools_plugin_get_function($plugin_definition, $function_name) {
772
  // If cached the .inc file may not have been loaded. require_once is quite safe
773
  // and fast so it's okay to keep calling it.
774
  if (isset($plugin_definition['file'])) {
775
    // Plugins that are loaded from info files have the info file as
776
    // $plugin['file'].  Don't try to run those.
777
    $info = ctools_plugin_get_info($plugin_definition['plugin module'], $plugin_definition['plugin type']);
778
    if (empty($info['info file'])) {
779
      require_once DRUPAL_ROOT . '/' . $plugin_definition['path'] . '/' . $plugin_definition['file'];
780
    }
781
  }
782

    
783
  if (!isset($plugin_definition[$function_name])) {
784
    return;
785
  }
786

    
787
  if (is_array($plugin_definition[$function_name]) && isset($plugin_definition[$function_name]['function'])) {
788
    $function = $plugin_definition[$function_name]['function'];
789
    if (isset($plugin_definition[$function_name]['file'])) {
790
      $file = $plugin_definition[$function_name]['file'];
791
      if (isset($plugin_definition[$function_name]['path'])) {
792
        $file = $plugin_definition[$function_name]['path'] . '/' . $file;
793
      }
794
      require_once DRUPAL_ROOT . '/' . $file;
795
    }
796
  }
797
  else {
798
    $function = $plugin_definition[$function_name];
799
  }
800

    
801
  if (function_exists($function)) {
802
    return $function;
803
  }
804
}
805

    
806
/**
807
 * Load a plugin and get a function name from it, returning success only
808
 * if the function exists.
809
 *
810
 * @param $module
811
 *   The module that owns the plugin type.
812
 * @param $type
813
 *   The type of plugin.
814
 * @param $id
815
 *   The id of the specific plugin to load.
816
 * @param $function_name
817
 *   The identifier of the function. For example, 'settings form'.
818
 *
819
 * @return
820
 *   The actual name of the function to call, or NULL if the function
821
 *   does not exist.
822
 */
823
function ctools_plugin_load_function($module, $type, $id, $function_name) {
824
  $plugin = ctools_get_plugins($module, $type, $id);
825
  return ctools_plugin_get_function($plugin, $function_name);
826
}
827

    
828
/**
829
 * Get a class from a plugin, if it exists. If the plugin is not already
830
 * loaded, try ctools_plugin_load_class() instead.
831
 *
832
 * @param $plugin_definition
833
 *   The loaded plugin type.
834
 * @param $class_name
835
 *   The identifier of the class. For example, 'handler'.
836
 *
837
 * @return
838
 *   The actual name of the class to call, or NULL if the class does not exist.
839
 */
840
function ctools_plugin_get_class($plugin_definition, $class_name) {
841
  // If cached the .inc file may not have been loaded. require_once is quite safe
842
  // and fast so it's okay to keep calling it.
843
  if (isset($plugin_definition['file'])) {
844
    // Plugins that are loaded from info files have the info file as
845
    // $plugin['file'].  Don't try to run those.
846
    $info = ctools_plugin_get_info($plugin_definition['plugin module'], $plugin_definition['plugin type']);
847
    if (empty($info['info file'])) {
848
      require_once DRUPAL_ROOT . '/' . $plugin_definition['path'] . '/' . $plugin_definition['file'];
849
    }
850
  }
851

    
852
  $return = FALSE;
853
  if (!isset($plugin_definition[$class_name])) {
854
    return;
855
  }
856
  else if (is_string($plugin_definition[$class_name])) {
857
    // Plugin uses the string form shorthand.
858
    $return = $plugin_definition[$class_name];
859
  }
860
  else if (isset($plugin_definition[$class_name]['class'])) {
861
    // Plugin uses the verbose array form.
862
    $return = $plugin_definition[$class_name]['class'];
863
  }
864
  // @todo consider adding an else {watchdog(...)} here
865

    
866
  return ($return && class_exists($return)) ? $return : NULL;
867
}
868

    
869
/**
870
 * Load a plugin and get a class name from it, returning success only if the
871
 * class exists.
872
 *
873
 * @param $module
874
 *   The module that owns the plugin type.
875
 * @param $type
876
 *   The type of plugin.
877
 * @param $id
878
 *   The id of the specific plugin to load.
879
 * @param $class_name
880
 *   The identifier of the class. For example, 'handler'.
881
 *
882
 * @return
883
 *   The actual name of the class to call, or NULL if the class does not exist.
884
 */
885
function ctools_plugin_load_class($module, $type, $id, $class_name) {
886
  $plugin = ctools_get_plugins($module, $type, $id);
887
  return ctools_plugin_get_class($plugin, $class_name);
888
}
889

    
890
/**
891
 * Sort callback for sorting plugins naturally.
892
 *
893
 * Sort first by weight, then by title.
894
 */
895
function ctools_plugin_sort($a, $b) {
896
  if (is_object($a)) {
897
    $a = (array) $a;
898
  }
899
  if (is_object($b)) {
900
    $b = (array) $b;
901
  }
902

    
903
  if (empty($a['weight'])) {
904
    $a['weight'] = 0;
905
  }
906

    
907
  if (empty($b['weight'])) {
908
    $b['weight'] = 0;
909
  }
910

    
911
  if ($a['weight'] == $b['weight']) {
912
    return strnatcmp(strtolower($a['title']), strtolower($b['title']));
913
  }
914
  return ($a['weight'] < $b['weight']) ? -1 : 1;
915
}