Projet

Général

Profil

Paste
Télécharger (35,9 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / ctools / ctools.module @ 7e72b748

1
<?php
2

    
3
/**
4
 * @file
5
 * CTools primary module file.
6
 *
7
 * Most of the CTools tools are in their own .inc files. This contains
8
 * nothing more than a few convenience functions and some hooks that
9
 * must be implemented in the module file.
10
 */
11

    
12
define('CTOOLS_API_VERSION', '2.0.9');
13

    
14
/**
15
 * The current working ctools version.
16
 *
17
 * In a release, it should be 7.x-1.x, which should match what drush make will
18
 * create. In a dev format, it should be 7.x-1.(x+1)-dev, which will allow
19
 * modules depending on new features in ctools to depend on ctools > 7.x-1.x.
20
 *
21
 * To define a specific version of CTools as a dependency for another module,
22
 * simply include a dependency line in that module's info file, e.g.:
23
 *   ; Requires CTools v7.x-1.4 or newer.
24
 *   dependencies[] = ctools (>=1.4)
25
 */
26
define('CTOOLS_MODULE_VERSION', '7.x-1.13');
27

    
28
/**
29
 * Test the CTools API version.
30
 *
31
 * This function can always be used to safely test if CTools has the minimum
32
 * API version that your module can use. It can also try to protect you from
33
 * running if the CTools API version is too new, but if you do that you need
34
 * to be very quick about watching CTools API releases and release new versions
35
 * of your software as soon as the new release is made, or people might end up
36
 * updating CTools and having your module shut down without any recourse.
37
 *
38
 * It is recommended that every hook of your module that might use CTools or
39
 * might lead to a use of CTools be guarded like this:
40
 *
41
 * @code
42
 * if (!module_invoke('ctools', 'api_version', '1.0')) {
43
 *   return;
44
 * }
45
 * @endcode
46
 *
47
 * Note that some hooks such as _menu() or _theme() must return an array().
48
 *
49
 * You can use it in your hook_requirements to report this error condition
50
 * like this:
51
 *
52
 * @code
53
 * define('MODULENAME_MINIMUM_CTOOLS_API_VERSION', '1.0');
54
 * define('MODULENAME_MAXIMUM_CTOOLS_API_VERSION', '1.1');
55
 *
56
 * function MODULENAME_requirements($phase) {
57
 *   $requirements = array();
58
 *   if (!module_invoke('ctools', 'api_version', MODULENAME_MINIMUM_CTOOLS_API_VERSION, MODULENAME_MAXIMUM_CTOOLS_API_VERSION)) {
59
 *      $requirements['MODULENAME_ctools'] = array(
60
 *        'title' => $t('MODULENAME required Chaos Tool Suite (CTools) API Version'),
61
 *        'value' => t('Between @a and @b', array('@a' => MODULENAME_MINIMUM_CTOOLS_API_VERSION, '@b' => MODULENAME_MAXIMUM_CTOOLS_API_VERSION)),
62
 *        'severity' => REQUIREMENT_ERROR,
63
 *      );
64
 *   }
65
 *   return $requirements;
66
 * }
67
 * @endcode
68
 *
69
 * Please note that the version is a string, not an floating point number.
70
 * This will matter once CTools reaches version 1.10.
71
 *
72
 * A CTools API changes history will be kept in API.txt. Not every new
73
 * version of CTools will necessarily update the API version.
74
 * @param $minimum
75
 *   The minimum version of CTools necessary for your software to run with it.
76
 * @param $maximum
77
 *   The maximum version of CTools allowed for your software to run with it.
78
 *
79
 * @return bool
80
 *   TRUE if the running ctools is usable, FALSE otherwise.
81
 */
82
function ctools_api_version($minimum, $maximum = NULL) {
83
  if (version_compare(CTOOLS_API_VERSION, $minimum, '<')) {
84
    return FALSE;
85
  }
86

    
87
  if (isset($maximum) && version_compare(CTOOLS_API_VERSION, $maximum, '>')) {
88
    return FALSE;
89
  }
90

    
91
  return TRUE;
92
}
93

    
94
// -----------------------------------------------------------------------
95
// General utility functions.
96
/**
97
 * Include .inc files as necessary.
98
 *
99
 * This fuction is helpful for including .inc files for your module. The
100
 * general case is including ctools funcitonality like this:
101
 *
102
 * @code
103
 * ctools_include('plugins');
104
 * @endcode
105
 *
106
 * Similar funcitonality can be used for other modules by providing the $module
107
 * and $dir arguments like this:
108
 *
109
 * @code
110
 * // include mymodule/includes/import.inc
111
 * ctools_include('import', 'mymodule');
112
 * // include mymodule/plugins/foobar.inc
113
 * ctools_include('foobar', 'mymodule', 'plugins');
114
 * @endcode
115
 *
116
 * @param $file
117
 *   The base file name to be included.
118
 * @param $module
119
 *   Optional module containing the include.
120
 * @param $dir
121
 *   Optional subdirectory containing the include file.
122
 */
123

    
124
function ctools_include($file, $module = 'ctools', $dir = 'includes') {
125
  static $used = array();
126

    
127
  $dir = '/' . ($dir ? $dir . '/' : '');
128

    
129
  if (!isset($used[$module][$dir][$file])) {
130
    require_once DRUPAL_ROOT . '/' . drupal_get_path('module', $module) . "$dir$file.inc";
131
    $used[$module][$dir][$file] = TRUE;
132
  }
133
}
134

    
135
/**
136
 * Include .inc files in a form context.
137
 *
138
 * This is a variant of ctools_include that will save information in the
139
 * the form_state so that cached forms will properly include things.
140
 */
141
function ctools_form_include(&$form_state, $file, $module = 'ctools', $dir = 'includes') {
142
  if (!isset($form_state['build_info']['args'])) {
143
    $form_state['build_info']['args'] = array();
144
  }
145

    
146
  $dir = '/' . ($dir ? $dir . '/' : '');
147
  form_load_include($form_state, 'inc', $module, $dir . $file);
148
}
149

    
150
/**
151
 * Add an arbitrary path to the $form_state so it can work with form cache.
152
 *
153
 * The module_load_include() function uses an unfortunately annoying syntax to
154
 * work, making it difficult to translate the more simple $path + $file syntax.
155
 */
156
function ctools_form_include_file(&$form_state, $filename) {
157
  if (!isset($form_state['build_info']['args'])) {
158
    $form_state['build_info']['args'] = array();
159
  }
160

    
161
  // Now add this to the build info files so that AJAX requests will know to load it.
162
  $form_state['build_info']['files']["$filename"] = $filename;
163
  require_once DRUPAL_ROOT . '/' . $filename;
164
}
165

    
166
/**
167
 * Provide the proper path to an image as necessary.
168
 *
169
 * This helper function is used by ctools but can also be used in other
170
 * modules in the same way as explained in the comments of ctools_include.
171
 *
172
 * @param $image
173
 *   The base file name (with extension)  of the image to be included.
174
 * @param $module
175
 *   Optional module containing the include.
176
 * @param $dir
177
 *   Optional subdirectory containing the include file.
178
 *
179
 * @return string
180
 *   A string containing the appropriate path from drupal root.
181
 */
182
function ctools_image_path($image, $module = 'ctools', $dir = 'images') {
183
  return drupal_get_path('module', $module) . "/$dir/" . $image;
184
}
185

    
186
/**
187
 * Include css files as necessary.
188
 *
189
 * This helper function is used by ctools but can also be used in other
190
 * modules in the same way as explained in the comments of ctools_include.
191
 *
192
 * @param $file
193
 *   The base file name to be included.
194
 * @param $module
195
 *   Optional module containing the include.
196
 * @param $dir
197
 *   Optional subdirectory containing the include file.
198
 */
199
function ctools_add_css($file, $module = 'ctools', $dir = 'css') {
200
  drupal_add_css(drupal_get_path('module', $module) . "/$dir/$file.css");
201
}
202

    
203
/**
204
 * Format a css file name for use with $form['#attached']['css'].
205
 *
206
 * This helper function is used by ctools but can also be used in other
207
 * modules in the same way as explained in the comments of ctools_include.
208
 *
209
 * @code
210
 *   $form['#attached']['css'] = array(ctools_attach_css('collapsible-div'));
211
 *   $form['#attached']['css'][ctools_attach_css('collapsible-div')] = array('preprocess' => FALSE);
212
 * @endcode
213
 *
214
 * @param $file
215
 *   The base file name to be included.
216
 * @param $module
217
 *   Optional module containing the include.
218
 * @param $dir
219
 *   Optional subdirectory containing the include file.
220
 *
221
 * @return string
222
 *   A string containing the appropriate path from drupal root.
223
 */
224
function ctools_attach_css($file, $module = 'ctools', $dir = 'css') {
225
  return drupal_get_path('module', $module) . "/$dir/$file.css";
226
}
227

    
228
/**
229
 * Include js files as necessary.
230
 *
231
 * This helper function is used by ctools but can also be used in other
232
 * modules in the same way as explained in the comments of ctools_include.
233
 *
234
 * @param $file
235
 *   The base file name to be included.
236
 * @param $module
237
 *   Optional module containing the include.
238
 * @param $dir
239
 *   Optional subdirectory containing the include file.
240
 */
241
function ctools_add_js($file, $module = 'ctools', $dir = 'js') {
242
  drupal_add_js(drupal_get_path('module', $module) . "/$dir/$file.js");
243
}
244

    
245
/**
246
 * Format a javascript file name for use with $form['#attached']['js'].
247
 *
248
 * This helper function is used by ctools but can also be used in other
249
 * modules in the same way as explained in the comments of ctools_include.
250
 *
251
 * @code
252
 *   $form['#attached']['js'] = array(ctools_attach_js('auto-submit'));
253
 * @endcode
254
 *
255
 * @param $file
256
 *   The base file name to be included.
257
 * @param $module
258
 *   Optional module containing the include.
259
 * @param $dir
260
 *   Optional subdirectory containing the include file.
261
 *
262
 * @return string
263
 *   A string containing the appropriate path from drupal root.
264
 */
265
function ctools_attach_js($file, $module = 'ctools', $dir = 'js') {
266
  return drupal_get_path('module', $module) . "/$dir/$file.js";
267
}
268

    
269
/**
270
 * Get a list of roles in the system.
271
 *
272
 * @return
273
 *   An array of role names keyed by role ID.
274
 *
275
 * @deprecated
276
 *    user_roles() should be used instead.
277
 */
278
function ctools_get_roles() {
279
  return user_roles();
280
}
281

    
282
/**
283
 * Parse integer sequences of the form "x,y,z" or "x+y+z" into separate values.
284
 *
285
 * A string with integers separated by comma (,) is reported as an 'and' set;
286
 * separation by a plus sign (+) or a space ( ) is an 'or' set. The meaning
287
 * of this is up to the caller. Negative or fractional numbers are not
288
 * recognised.
289
 *
290
 * Additional space characters within or around the sequence are not allowed.
291
 *
292
 * @param $str
293
 *   The string to parse.
294
 *
295
 * @return object
296
 *   An object containing the properties:
297
 *
298
 *   - operator: Either 'and' or 'or' when there are multiple matched values.
299
 *   Absent when invalid_input is TRUE or there is only one value.
300
 *   - value: An array of integers (never strings) from $str. An empty array is
301
 *   returned if the input is empty. A single integer input is returned
302
 *   as a single value, but no 'operator' is defined.
303
 *   - invalid_input: TRUE if input could not be parsed and the values array
304
 *   will contain just -1. This property is otherwise absent.
305
 */
306
function ctools_break_phrase($str) {
307
  $object = new stdClass();
308

    
309
  if (preg_match('/^([0-9]+[+ ])+[0-9]+$/', $str)) {
310
    // The '+' character in a query string may be parsed as ' '.
311
    $object->operator = 'or';
312
    $object->value = preg_split('/[+ ]/', $str);
313
  }
314
  elseif (preg_match('/^([0-9]+,)*[0-9]+$/', $str)) {
315
    $object->operator = 'and';
316
    $object->value = explode(',', $str);
317
  }
318

    
319
  // Keep an 'error' value if invalid strings were given.
320
  if (!empty($str) && (empty($object->value) || !is_array($object->value))) {
321
    $object->value = array(-1);
322
    $object->invalid_input = TRUE;
323
    return $object;
324
  }
325

    
326
  if (empty($object->value)) {
327
    $object->value = array();
328
  }
329

    
330
  // Doubly ensure that all values are numeric only.
331
  foreach ($object->value as $id => $value) {
332
    $object->value[$id] = (int) $value;
333
  }
334

    
335
  return $object;
336
}
337

    
338
/**
339
 * Set a token/value pair to be replaced later in the request, specifically in
340
 * ctools_page_token_processing().
341
 *
342
 * @param string $token
343
 *   The token to be replaced later, during page rendering.  This should
344
 *   ideally be a string inside of an HTML comment, so that if there is
345
 *   no replacement, the token will not render on the page.
346
 *   If $token is NULL, the token set is not changed, but is still
347
 *   returned.
348
 * @param string $type
349
 *   The type of the token. Can be either 'variable', which will pull data
350
 *   directly from the page variables, or 'callback', which causes a function
351
 *   to be called to calculate the value. No other values are supported.
352
 * @param string|array $argument
353
 *   For $type of:
354
 *   - 'variable': argument should be the key to fetch from the $variables.
355
 *   - 'callback': then it should either be the callback function name as a
356
 *     string, or an array that will be sent to call_user_func_array(). Argument
357
 *     arrays must not use array keys (i.e. $a[0] is the first and $a[1] the
358
 *     second element, etc.)
359
 *
360
 * @return array
361
 *   A array of token/variable names to be replaced.
362
 */
363
function ctools_set_page_token($token = NULL, $type = NULL, $argument = NULL) {
364
  $tokens = &drupal_static('ctools_set_page_token', array());
365

    
366
  if (isset($token)) {
367
    $tokens[$token] = array($type, $argument);
368
  }
369
  return $tokens;
370
}
371

    
372
/**
373
 * Reset the defined page tokens within this request.
374
 *
375
 * Introduced for simpletest purposes. Normally not needed.
376
 */
377
function ctools_reset_page_tokens() {
378
  drupal_static_reset('ctools_set_page_token');
379
}
380

    
381
/**
382
 * Set a replacement token from the containing element's children during #post_render.
383
 *
384
 * This function can be used like this:
385
 *   $token = ctools_set_variable_token('tabs');
386
 *
387
 * The token "<!-- ctools-page-tabs -->" would then be replaced by the value of
388
 * this element's (sibling) render array key 'tabs' during post-render (or be
389
 * deleted if there was no such key by that point).
390
 *
391
 * @param string $token
392
 *   The token string for the page callback, e.g. 'title'.
393
 *
394
 * @return string
395
 *   The constructed token.
396
 *
397
 * @see ctools_set_callback_token()
398
 * @see ctools_page_token_processing()
399
 */
400
function ctools_set_variable_token($token) {
401
  $string = '<!-- ctools-page-' . $token . ' -->';
402
  ctools_set_page_token($string, 'variable', $token);
403
  return $string;
404
}
405

    
406
/**
407
 * Set a replacement token from the value of a function during #post_render.
408
 *
409
 * This function can be used like this:
410
 *   $token = ctools_set_callback_token('id', 'mymodule_myfunction');
411
 *
412
 * Or this (from its use in ctools_page_title_content_type_render):
413
 *   $token = ctools_set_callback_token('title', array(
414
 *       'ctools_page_title_content_type_token', $conf['markup'], $conf['id'], $conf['class']
415
 *     )
416
 *   );
417
 *
418
 * The token (e.g: "<!-- ctools-page-id-1b7f84d1c8851290cc342631ac663053 -->")
419
 * would then be replaced during post-render by the return value of:
420
 *
421
 *   ctools_page_title_content_type_token($value_markup, $value_id, $value_class);
422
 *
423
 * @param string $token
424
 *   The token string for the page callback, e.g. 'title'.
425
 *
426
 * @param string|array $callback
427
 *   For callback functions that require no args, the name of the function as a
428
 *   string; otherwise an array of two or more elements: the function name
429
 *   followed by one or more function arguments.
430
 *
431
 *   NB: the value of $callback must be a procedural (non-class) function that
432
 *   passes the php function_exists() check.
433
 *
434
 *   The callback function itself will be called with args dependent
435
 *   on $callback. If:
436
 *    - $callback is a string, the function is called with a reference to the
437
 *      render array;
438
 *    - $callback is an array, the function is called with $callback merged
439
 *      with an array containing a reference to the render array.
440
 *
441
 * @return string
442
 *   The constructed token.
443
 *
444
 * @see ctools_set_variable_token()
445
 * @see ctools_page_token_processing()
446
 */
447
function ctools_set_callback_token($token, $callback) {
448
  // If the callback uses arguments they are considered in the token.
449
  if (is_array($callback)) {
450
    $token .= '-' . md5(serialize($callback));
451
  }
452
  $string = '<!-- ctools-page-' . $token . ' -->';
453
  ctools_set_page_token($string, 'callback', $callback);
454
  return $string;
455
}
456

    
457
/**
458
 * Tell CTools that sidebar blocks should not be rendered.
459
 *
460
 * It is often desirable to not display sidebars when rendering a page,
461
 * particularly when using Panels. This informs CTools to alter out any
462
 * sidebar regions during block render.
463
 */
464
function ctools_set_no_blocks($blocks = FALSE) {
465
  $status = &drupal_static(__FUNCTION__, TRUE);
466
  $status = $blocks;
467
}
468

    
469
/**
470
 * Wrapper function to create UUIDs via ctools, falls back on UUID module
471
 * if it is enabled. This code is a copy of uuid.inc from the uuid module.
472
 *
473
 * @see http://php.net/uniqid#65879
474
 */
475
function ctools_uuid_generate() {
476
  if (!module_exists('uuid')) {
477
    ctools_include('uuid');
478

    
479
    $callback = drupal_static(__FUNCTION__);
480

    
481
    if (empty($callback)) {
482
      if (function_exists('uuid_create') && !function_exists('uuid_make')) {
483
        $callback = '_ctools_uuid_generate_pecl';
484
      }
485
      elseif (function_exists('com_create_guid')) {
486
        $callback = '_ctools_uuid_generate_com';
487
      }
488
      else {
489
        $callback = '_ctools_uuid_generate_php';
490
      }
491
    }
492
    return $callback();
493
  }
494
  else {
495
    return uuid_generate();
496
  }
497
}
498

    
499
/**
500
 * Check that a string appears to be in the format of a UUID.
501
 *
502
 * @see http://drupal.org/project/uuid
503
 *
504
 * @param $uuid
505
 *   The string to test.
506
 *
507
 * @return
508
 *   TRUE if the string is well formed.
509
 */
510
function ctools_uuid_is_valid($uuid = '') {
511
  if (empty($uuid)) {
512
    return FALSE;
513
  }
514
  if (function_exists('uuid_is_valid') || module_exists('uuid')) {
515
    return uuid_is_valid($uuid);
516
  }
517
  else {
518
    ctools_include('uuid');
519
    return uuid_is_valid($uuid);
520
  }
521
}
522

    
523
/**
524
 * Add an array of classes to the body.
525
 *
526
 * @param mixed $classes
527
 *   A string or an array of class strings to add.
528
 * @param string $hook
529
 *   The theme hook to add the class to. The default is 'html' which will
530
 *   affect the body tag.
531
 */
532
function ctools_class_add($classes, $hook = 'html') {
533
  if (!is_array($classes)) {
534
    $classes = array($classes);
535
  }
536

    
537
  $static = &drupal_static('ctools_process_classes', array());
538
  if (!isset($static[$hook]['add'])) {
539
    $static[$hook]['add'] = array();
540
  }
541
  foreach ($classes as $class) {
542
    $static[$hook]['add'][] = $class;
543
  }
544
}
545

    
546
/**
547
 * Remove an array of classes from the body.
548
 *
549
 * @param mixed $classes
550
 *   A string or an array of class strings to remove.
551
 * @param string $hook
552
 *   The theme hook to remove the class from. The default is 'html' which will
553
 *   affect the body tag.
554
 */
555
function ctools_class_remove($classes, $hook = 'html') {
556
  if (!is_array($classes)) {
557
    // @todo Consider using explode(' ', $classes);
558
    // @todo Consider checking that $classes is a string before adding.
559
    $classes = array($classes);
560
  }
561

    
562
  $static = &drupal_static('ctools_process_classes', array());
563
  if (!isset($static[$hook]['remove'])) {
564
    $static[$hook]['remove'] = array();
565
  }
566
  foreach ($classes as $class) {
567
    $static[$hook]['remove'][] = $class;
568
  }
569
}
570

    
571
/**
572
 * Reset the storage used for ctools_class_add and ctools_class_remove.
573
 *
574
 * @see ctools_class_add()
575
 * @see ctools_class_remove()
576
 */
577
function ctools_class_reset() {
578
  drupal_static_reset('ctools_process_classes');
579
}
580

    
581
/**
582
 * Return the classes for the body (added by ctools_class_add).
583
 *
584
 * @return array
585
 *   A copy of the array of classes to add to the body tag. If none have been
586
 *   added, this will be an empty array.
587
 *
588
 * @see ctools_class_add()
589
 */
590
function ctools_get_classes() {
591
  return drupal_static('ctools_process_classes', array());
592
}
593

    
594
// -----------------------------------------------------------------------
595
// Drupal core hooks.
596
/**
597
 * Implement hook_init to keep our global CSS at the ready.
598
 */
599

    
600
function ctools_init() {
601
  ctools_add_css('ctools');
602
  // If we are sure that CTools' AJAX is in use, change the error handling.
603
  if (!empty($_REQUEST['ctools_ajax'])) {
604
    ini_set('display_errors', 0);
605
    register_shutdown_function('ctools_shutdown_handler');
606
  }
607

    
608
  // Clear plugin cache on the module page submit.
609
  if ($_GET['q'] == 'admin/modules/list/confirm' && !empty($_POST)) {
610
    cache_clear_all('ctools_plugin_files:', 'cache', TRUE);
611
  }
612
}
613

    
614
/**
615
 * Shutdown handler used during ajax operations to help catch fatal errors.
616
 */
617
function ctools_shutdown_handler() {
618
  if (function_exists('error_get_last') && ($error = error_get_last())) {
619
    switch ($error['type']) {
620
      case E_ERROR:
621
      case E_CORE_ERROR:
622
      case E_COMPILE_ERROR:
623
      case E_USER_ERROR:
624
        // Do this manually because including files here is dangerous.
625
        $commands = array(
626
          array(
627
            'command' => 'alert',
628
            'title' => t('Error'),
629
            'text' => t('Unable to complete operation. Fatal error in @file on line @line: @message', array(
630
              '@file' => $error['file'],
631
              '@line' => $error['line'],
632
              '@message' => $error['message'],
633
            )),
634
          ),
635
        );
636

    
637
        // Change the status code so that the client will read the AJAX returned.
638
        header('HTTP/1.1 200 OK');
639
        drupal_json($commands);
640
    }
641
  }
642
}
643

    
644
/**
645
 * Implements hook_theme().
646
 */
647
function ctools_theme() {
648
  ctools_include('utility');
649
  $items = array();
650
  ctools_passthrough('ctools', 'theme', $items);
651
  return $items;
652
}
653

    
654
/**
655
 * Implements hook_menu().
656
 */
657
function ctools_menu() {
658
  ctools_include('utility');
659
  $items = array();
660
  ctools_passthrough('ctools', 'menu', $items);
661
  return $items;
662
}
663

    
664
/**
665
 * Implements hook_permission().
666
 */
667
function ctools_permission() {
668
  return array(
669
    'use ctools import' => array(
670
      'title' => t('Use CTools importer'),
671
      'description' => t('The import functionality allows users to execute arbitrary PHP code, so extreme caution must be taken.'),
672
      'restrict access' => TRUE,
673
    ),
674
  );
675
}
676

    
677
/**
678
 * Implementation of hook_cron. Clean up old caches.
679
 */
680
function ctools_cron() {
681
  ctools_include('utility');
682
  $items = array();
683
  ctools_passthrough('ctools', 'cron', $items);
684
}
685

    
686
/**
687
 * Implements hook_flush_caches().
688
 */
689
function ctools_flush_caches() {
690
  // Only return the CSS cache bin if it has been activated, to avoid
691
  // drupal_flush_all_caches() from trying to truncate a non-existing table.
692
  return variable_get('cache_class_cache_ctools_css', FALSE) ? array('cache_ctools_css') : array();
693
}
694

    
695
/**
696
 * Implements hook_element_info_alter().
697
 */
698
function ctools_element_info_alter(&$type) {
699
  ctools_include('dependent');
700
  ctools_dependent_element_info_alter($type);
701
}
702

    
703
/**
704
 * Implementation of hook_file_download()
705
 *
706
 * When using the private file system, we have to let Drupal know it's ok to
707
 * download CSS and image files from our temporary directory.
708
 */
709
function ctools_file_download($filepath) {
710
  if (strpos($filepath, 'ctools') === 0) {
711
    $mime = file_get_mimetype($filepath);
712
    // For safety's sake, we allow only text and images.
713
    if (strpos($mime, 'text') === 0 || strpos($mime, 'image') === 0) {
714
      return array('Content-type:' . $mime);
715
    }
716
  }
717
}
718

    
719
/**
720
 * Implements hook_registry_files_alter().
721
 *
722
 * Alter the registry of files to automagically include all classes in
723
 * class-based plugins.
724
 */
725
function ctools_registry_files_alter(&$files, $indexed_modules) {
726
  ctools_include('registry');
727
  return _ctools_registry_files_alter($files, $indexed_modules);
728
}
729

    
730
// -----------------------------------------------------------------------
731
// FAPI hooks that must be in the .module file.
732
/**
733
 * Alter the comment form to get a little more control over it.
734
 */
735

    
736
function ctools_form_comment_form_alter(&$form, &$form_state) {
737
  if (!empty($form_state['ctools comment alter'])) {
738
    // Force the form to post back to wherever we are.
739
    $form['#action'] = url($_GET['q'], array('fragment' => 'comment-form'));
740
    if (empty($form['#submit'])) {
741
      $form['#submit'] = array('comment_form_submit');
742
    }
743
    $form['#submit'][] = 'ctools_node_comment_form_submit';
744
  }
745
}
746

    
747
function ctools_node_comment_form_submit(&$form, &$form_state) {
748
  $form_state['redirect'][0] = $_GET['q'];
749
}
750

    
751
// -----------------------------------------------------------------------
752
// CTools hook implementations.
753
/**
754
 * Implementation of hook_ctools_plugin_directory() to let the system know
755
 * where all our own plugins are.
756
 */
757

    
758
function ctools_ctools_plugin_directory($owner, $plugin_type) {
759
  if ($owner == 'ctools') {
760
    return 'plugins/' . $plugin_type;
761
  }
762
}
763

    
764
/**
765
 * Implements hook_ctools_plugin_type().
766
 */
767
function ctools_ctools_plugin_type() {
768
  ctools_include('utility');
769
  $items = array();
770
  // Add all the plugins that have their own declaration space elsewhere.
771
  ctools_passthrough('ctools', 'plugin-type', $items);
772

    
773
  return $items;
774
}
775

    
776
// -----------------------------------------------------------------------
777
// Drupal theme preprocess hooks that must be in the .module file.
778
/**
779
 * A theme preprocess function to automatically allow panels-based node
780
 * templates based upon input when the panel was configured.
781
 */
782

    
783
function ctools_preprocess_node(&$vars) {
784
  // The 'ctools_template_identifier' attribute of the node is added when the pane is
785
  // rendered.
786
  if (!empty($vars['node']->ctools_template_identifier)) {
787
    $vars['ctools_template_identifier'] = check_plain($vars['node']->ctools_template_identifier);
788
    $vars['theme_hook_suggestions'][] = 'node__panel__' . check_plain($vars['node']->ctools_template_identifier);
789
  }
790
}
791

    
792
/**
793
 * Implements hook_page_alter().
794
 *
795
 * Last ditch attempt to remove sidebar regions if the "no blocks"
796
 * functionality has been activated.
797
 *
798
 * @see ctools_block_list_alter()
799
 */
800
function ctools_page_alter(&$page) {
801
  $check = drupal_static('ctools_set_no_blocks', TRUE);
802
  if (!$check) {
803
    foreach ($page as $region_id => $region) {
804
      // @todo -- possibly we can set configuration for this so that users can
805
      // specify which blocks will not get rendered.
806
      if (strpos($region_id, 'sidebar') !== FALSE) {
807
        unset($page[$region_id]);
808
      }
809
    }
810
  }
811
  $page['#post_render'][] = 'ctools_page_token_processing';
812
}
813

    
814
/**
815
 * A theme post_render callback to allow content type plugins to use page
816
 * template variables which are not yet available when the content type is
817
 * rendered.
818
 */
819
function ctools_page_token_processing($children, $elements) {
820
  $tokens = ctools_set_page_token();
821
  if (!empty($tokens)) {
822
    foreach ($tokens as $token => $key) {
823
      list($type, $argument) = $key;
824
      switch ($type) {
825
        case 'variable':
826
          $tokens[$token] = isset($elements[$argument]) ? $elements[$argument] : '';
827
          break;
828

    
829
        case 'callback':
830
          if (is_string($argument) && function_exists($argument)) {
831
            $tokens[$token] = $argument($elements);
832
          }
833
          if (is_array($argument) && function_exists($argument[0])) {
834
            $function = array_shift($argument);
835
            $argument = array_merge(array(&$elements), $argument);
836
            $tokens[$token] = call_user_func_array($function, $argument);
837
          }
838
          break;
839
      }
840
    }
841
    $children = strtr($children, $tokens);
842
  }
843
  return $children;
844
}
845

    
846
/**
847
 * Implements hook_process().
848
 *
849
 * Add and remove CSS classes from the variables array. We use process so that
850
 * we alter anything added in the preprocess hooks.
851
 */
852
function ctools_process(&$variables, $hook) {
853
  if (!isset($variables['classes'])) {
854
    return;
855
  }
856

    
857
  $classes = ctools_get_classes();
858

    
859
  // Process the classses to add.
860
  if (!empty($classes[$hook]['add'])) {
861
    $add_classes = array_map('drupal_clean_css_identifier', $classes[$hook]['add']);
862
    $variables['classes_array'] = array_unique(array_merge($variables['classes_array'], $add_classes));
863
  }
864

    
865
  // Process the classes to remove.
866
  if (!empty($classes[$hook]['remove'])) {
867
    $remove_classes = array_map('drupal_clean_css_identifier', $classes[$hook]['remove']);
868
    $variables['classes_array'] = array_diff($variables['classes_array'], $remove_classes);
869
  }
870

    
871
  // Since this runs after template_process(), we need to re-implode the
872
  // classes array.
873
  $variables['classes'] = implode(' ', $variables['classes_array']);
874
}
875

    
876
// -----------------------------------------------------------------------
877
// Menu callbacks that must be in the .module file.
878
/**
879
 * Determine if the current user has access via a plugin.
880
 *
881
 * This function is meant to be embedded in the Drupal menu system, and
882
 * therefore is in the .module file since sub files can't be loaded, and
883
 * takes arguments a little bit more haphazardly than ctools_access().
884
 *
885
 * @param $access
886
 *   An access control array which contains the following information:
887
 *   - 'logic': and or or. Whether all tests must pass or one must pass.
888
 *   - 'plugins': An array of access plugins. Each contains:
889
 *   - - 'name': The name of the plugin
890
 *   - - 'settings': The settings from the plugin UI.
891
 *   - - 'context': Which context to use.
892
 * @param ...
893
 *   zero or more context arguments generated from argument plugins. These
894
 *   contexts must have an 'id' attached to them so that they can be
895
 *   properly associated. The argument plugin system should set this, but
896
 *   if the context is coming from elsewhere it will need to be set manually.
897
 *
898
 * @return
899
 *   TRUE if access is granted, false if otherwise.
900
 */
901

    
902
function ctools_access_menu($access) {
903
  // Short circuit everything if there are no access tests.
904
  if (empty($access['plugins'])) {
905
    return TRUE;
906
  }
907

    
908
  $contexts = array();
909
  foreach (func_get_args() as $arg) {
910
    if (is_object($arg) && get_class($arg) == 'ctools_context') {
911
      $contexts[$arg->id] = $arg;
912
    }
913
  }
914

    
915
  ctools_include('context');
916
  return ctools_access($access, $contexts);
917
}
918

    
919
/**
920
 * Determine if the current user has access via checks to multiple different
921
 * permissions.
922
 *
923
 * This function is a thin wrapper around user_access that allows multiple
924
 * permissions to be easily designated for use on, for example, a menu callback.
925
 *
926
 * @param ...
927
 *   An indexed array of zero or more permission strings to be checked by
928
 *   user_access().
929
 *
930
 * @return bool
931
 *   Iff all checks pass will this function return TRUE. If an invalid argument
932
 *   is passed (e.g., not a string), this function errs on the safe said and
933
 *   returns FALSE.
934
 */
935
function ctools_access_multiperm() {
936
  foreach (func_get_args() as $arg) {
937
    if (!is_string($arg) || !user_access($arg)) {
938
      return FALSE;
939
    }
940
  }
941
  return TRUE;
942
}
943

    
944
/**
945
 * Check to see if the incoming menu item is js capable or not.
946
 *
947
 * This can be used as %ctools_js as part of a path in hook menu. CTools
948
 * ajax functions will automatically change the phrase 'nojs' to 'ajax'
949
 * when it attaches ajax to a link. This can be used to autodetect if
950
 * that happened.
951
 */
952
function ctools_js_load($js) {
953
  if ($js == 'ajax') {
954
    return TRUE;
955
  }
956
  return 0;
957
}
958

    
959
/**
960
 * Provides the default value for %ctools_js.
961
 *
962
 * This allows drupal_valid_path() to work with %ctools_js.
963
 */
964
function ctools_js_to_arg($arg) {
965
  return empty($arg) || $arg == '%' ? 'nojs' : $arg;
966
}
967

    
968
/**
969
 * Menu _load hook.
970
 *
971
 * This function will be called to load an object as a replacement for
972
 * %ctools_export_ui in menu paths.
973
 */
974
function ctools_export_ui_load($item_name, $plugin_name) {
975
  $return = &drupal_static(__FUNCTION__, FALSE);
976

    
977
  if (!$return) {
978
    ctools_include('export-ui');
979
    $plugin = ctools_get_export_ui($plugin_name);
980
    $handler = ctools_export_ui_get_handler($plugin);
981

    
982
    if ($handler) {
983
      return $handler->load_item($item_name);
984
    }
985
  }
986

    
987
  return $return;
988
}
989

    
990
// -----------------------------------------------------------------------
991
// Caching callbacks on behalf of export-ui.
992
/**
993
 * Menu access callback for various tasks of export-ui.
994
 */
995
function ctools_export_ui_task_access($plugin_name, $op, $item = NULL) {
996
  ctools_include('export-ui');
997
  $plugin = ctools_get_export_ui($plugin_name);
998
  $handler = ctools_export_ui_get_handler($plugin);
999

    
1000
  if ($handler) {
1001
    return $handler->access($op, $item);
1002
  }
1003

    
1004
  // Deny access if the handler cannot be found.
1005
  return FALSE;
1006
}
1007

    
1008
/**
1009
 * Callback for access control ajax form on behalf of export ui.
1010
 *
1011
 * Returns the cached access config and contexts used.
1012
 * Note that this is assuming that access will be in $item->access -- if it
1013
 * is not, an export UI plugin will have to make its own callbacks.
1014
 */
1015
function ctools_export_ui_ctools_access_get($argument) {
1016
  ctools_include('export-ui');
1017
  list($plugin_name, $key) = explode(':', $argument, 2);
1018

    
1019
  $plugin = ctools_get_export_ui($plugin_name);
1020
  $handler = ctools_export_ui_get_handler($plugin);
1021

    
1022
  if ($handler) {
1023
    ctools_include('context');
1024
    $item = $handler->edit_cache_get($key);
1025
    if (!$item) {
1026
      $item = ctools_export_crud_load($handler->plugin['schema'], $key);
1027
    }
1028

    
1029
    $contexts = ctools_context_load_contexts($item);
1030
    return array($item->access, $contexts);
1031
  }
1032
}
1033

    
1034
/**
1035
 * Callback for access control ajax form on behalf of export ui.
1036
 *
1037
 * Returns the cached access config and contexts used.
1038
 * Note that this is assuming that access will be in $item->access -- if it
1039
 * is not, an export UI plugin will have to make its own callbacks.
1040
 */
1041
function ctools_export_ui_ctools_access_set($argument, $access) {
1042
  ctools_include('export-ui');
1043
  list($plugin_name, $key) = explode(':', $argument, 2);
1044

    
1045
  $plugin = ctools_get_export_ui($plugin_name);
1046
  $handler = ctools_export_ui_get_handler($plugin);
1047

    
1048
  if ($handler) {
1049
    ctools_include('context');
1050
    $item = $handler->edit_cache_get($key);
1051
    if (!$item) {
1052
      $item = ctools_export_crud_load($handler->plugin['schema'], $key);
1053
    }
1054
    $item->access = $access;
1055
    return $handler->edit_cache_set_key($item, $key);
1056
  }
1057
}
1058

    
1059
/**
1060
 * Implements hook_menu_local_tasks_alter().
1061
 */
1062
function ctools_menu_local_tasks_alter(&$data, $router_item, $root_path) {
1063
  ctools_include('menu');
1064
  _ctools_menu_add_dynamic_items($data, $router_item, $root_path);
1065
}
1066

    
1067
/**
1068
 * Implements hook_block_list_alter().
1069
 *
1070
 * Used to potentially remove blocks.
1071
 * This exists in order to replicate Drupal 6's "no blocks" functionality.
1072
 */
1073
function ctools_block_list_alter(&$blocks) {
1074
  $check = drupal_static('ctools_set_no_blocks', TRUE);
1075
  if (!$check) {
1076
    foreach ($blocks as $block_id => $block) {
1077
      // @todo -- possibly we can set configuration for this so that users can
1078
      // specify which blocks will not get rendered.
1079
      if (strpos($block->region, 'sidebar') !== FALSE) {
1080
        unset($blocks[$block_id]);
1081
      }
1082
    }
1083
  }
1084
}
1085

    
1086
/**
1087
 * Implements hook_modules_enabled().
1088
 *
1089
 * Clear caches for detecting new plugins.
1090
 */
1091
function ctools_modules_enabled($modules) {
1092
  ctools_include('plugins');
1093
  ctools_get_plugins_reset();
1094
  cache_clear_all('ctools_plugin_files:', 'cache', TRUE);
1095
}
1096

    
1097
/**
1098
 * Implements hook_modules_disabled().
1099
 *
1100
 * Clear caches for removing disabled plugins.
1101
 */
1102
function ctools_modules_disabled($modules) {
1103
  ctools_include('plugins');
1104
  ctools_get_plugins_reset();
1105
  cache_clear_all('ctools_plugin_files:', 'cache', TRUE);
1106
}
1107

    
1108
/**
1109
 * Menu theme callback.
1110
 *
1111
 * This simply ensures that Panels ajax calls are rendered in the same
1112
 * theme as the original page to prevent .css file confusion.
1113
 *
1114
 * To use this, set this as the theme callback on AJAX related menu
1115
 * items. Since the ajax page state won't be sent during ajax requests,
1116
 * it should be safe to use even if ajax isn't invoked.
1117
 */
1118
function ctools_ajax_theme_callback() {
1119
  if (!empty($_POST['ajax_page_state']['theme'])) {
1120
    return $_POST['ajax_page_state']['theme'];
1121
  }
1122
}
1123

    
1124
/**
1125
 * Implements hook_ctools_entity_context_alter().
1126
 */
1127
function ctools_ctools_entity_context_alter(&$plugin, &$entity, $plugin_id) {
1128
  ctools_include('context');
1129
  switch ($plugin_id) {
1130
    case 'entity_id:taxonomy_term':
1131
      $plugin['no ui'] = TRUE;
1132
      break;
1133

    
1134
    case 'entity:user':
1135
      $plugin = ctools_get_context('user');
1136
      unset($plugin['no ui']);
1137
      unset($plugin['no required context ui']);
1138
      break;
1139
  }
1140

    
1141
  // Apply restrictions on taxonomy term reverse relationships whose
1142
  // restrictions are in the settings on the field.
1143
  if (!empty($plugin['parent']) &&
1144
      $plugin['parent'] == 'entity_from_field' &&
1145
      !empty($plugin['reverse']) &&
1146
      $plugin['to entity'] == 'taxonomy_term') {
1147
    $field = field_info_field($plugin['field name']);
1148
    if (isset($field['settings']['allowed_values'][0]['vocabulary'])) {
1149
      $plugin['required context']->restrictions = array('vocabulary' => array($field['settings']['allowed_values'][0]['vocabulary']));
1150
    }
1151
  }
1152
}
1153

    
1154
/**
1155
 * Implements hook_field_create_field().
1156
 */
1157
function ctools_field_create_field($field) {
1158
  ctools_flush_field_caches();
1159
}
1160

    
1161
/**
1162
 * Implements hook_field_create_instance().
1163
 */
1164
function ctools_field_create_instance($instance) {
1165
  ctools_flush_field_caches();
1166
}
1167

    
1168
/**
1169
 * Implements hook_field_delete_field().
1170
 */
1171
function ctools_field_delete_field($field) {
1172
  ctools_flush_field_caches();
1173
}
1174

    
1175
/**
1176
 * Implements hook_field_delete_instance().
1177
 */
1178
function ctools_field_delete_instance($instance) {
1179
  ctools_flush_field_caches();
1180
}
1181

    
1182
/**
1183
 * Implements hook_field_update_field().
1184
 */
1185
function ctools_field_update_field($field, $prior_field, $has_data) {
1186
  ctools_flush_field_caches();
1187
}
1188

    
1189
/**
1190
 * Implements hook_field_update_instance().
1191
 */
1192
function ctools_field_update_instance($instance, $prior_instance) {
1193
  ctools_flush_field_caches();
1194
}
1195

    
1196
/**
1197
 * Clear field related caches.
1198
 */
1199
function ctools_flush_field_caches() {
1200
  // Clear caches of 'Entity field' content type plugin.
1201
  cache_clear_all('ctools_entity_field_content_type_content_types', 'cache');
1202
}