Project

General

Profile

Paste
Download (36.1 KB) Statistics
| Branch: | Revision:

root / drupal7 / sites / all / modules / ctools / ctools.module @ 6e3ce7c2

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
 * @deprecated in CTools 1.15 and will be removed before CTools 2.0.0.
27
 *   Use the version provided by the drupal.org packaging system.
28
 */
29
define('CTOOLS_MODULE_VERSION', '7.x-1.13');
30

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

    
90
  if (isset($maximum) && version_compare(CTOOLS_API_VERSION, $maximum, '>')) {
91
    return FALSE;
92
  }
93

    
94
  return TRUE;
95
}
96

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

    
127
function ctools_include($file, $module = 'ctools', $dir = 'includes') {
128
  static $used = array();
129

    
130
  $dir = '/' . ($dir ? $dir . '/' : '');
131

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

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

    
149
  $dir = '/' . ($dir ? $dir . '/' : '');
150
  form_load_include($form_state, 'inc', $module, $dir . $file);
151
}
152

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

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

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

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

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

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

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

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

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

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

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

    
329
  if (empty($object->value)) {
330
    $object->value = array();
331
  }
332

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

    
338
  return $object;
339
}
340

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

    
369
  if (isset($token)) {
370
    $tokens[$token] = array($type, $argument);
371
  }
372
  return $tokens;
373
}
374

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

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

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

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

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

    
482
    $callback = &drupal_static(__FUNCTION__);
483

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

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

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

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

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

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

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

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

    
597
// -----------------------------------------------------------------------
598
// Drupal core hooks.
599
/**
600
 * Implement hook_init to keep our global CSS at the ready.
601
 */
602

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
750
function ctools_node_comment_form_submit(&$form, &$form_state) {
751
  $form_state['redirect'][0] = $_GET['q'];
752
}
753

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

    
761
function ctools_ctools_plugin_directory($owner, $plugin_type) {
762
  if ($owner == 'ctools') {
763
    return 'plugins/' . $plugin_type;
764
  }
765
}
766

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

    
776
  return $items;
777
}
778

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

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

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

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

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

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

    
860
  $classes = ctools_get_classes();
861

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

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

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

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

    
905
function ctools_access_menu($access) {
906
  $func_args = func_get_args();
907
  // Short circuit everything if there are no access tests.
908
  if (empty($access['plugins'])) {
909
    return TRUE;
910
  }
911

    
912
  $contexts = array();
913
  foreach ($func_args as $arg) {
914
    if (is_object($arg) && get_class($arg) == 'ctools_context') {
915
      $contexts[$arg->id] = $arg;
916
    }
917
  }
918

    
919
  ctools_include('context');
920
  return ctools_access($access, $contexts);
921
}
922

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

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

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

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

    
981
  if (!$return) {
982
    ctools_include('export-ui');
983
    $plugin = ctools_get_export_ui($plugin_name);
984
    $handler = ctools_export_ui_get_handler($plugin);
985

    
986
    if ($handler) {
987
      return $handler->load_item($item_name);
988
    }
989
  }
990

    
991
  return $return;
992
}
993

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

    
1004
  if ($handler) {
1005
    return $handler->access($op, $item);
1006
  }
1007

    
1008
  // Deny access if the handler cannot be found.
1009
  return FALSE;
1010
}
1011

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

    
1023
  $plugin = ctools_get_export_ui($plugin_name);
1024
  $handler = ctools_export_ui_get_handler($plugin);
1025

    
1026
  if ($handler) {
1027
    ctools_include('context');
1028
    $item = $handler->edit_cache_get($key);
1029
    if (!$item) {
1030
      $item = ctools_export_crud_load($handler->plugin['schema'], $key);
1031
    }
1032

    
1033
    $contexts = ctools_context_load_contexts($item);
1034
    return array($item->access, $contexts);
1035
  }
1036
}
1037

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

    
1049
  $plugin = ctools_get_export_ui($plugin_name);
1050
  $handler = ctools_export_ui_get_handler($plugin);
1051

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

    
1063
/**
1064
 * Implements hook_menu_local_tasks_alter().
1065
 */
1066
function ctools_menu_local_tasks_alter(&$data, $router_item, $root_path) {
1067
  ctools_include('menu');
1068
  _ctools_menu_add_dynamic_items($data, $router_item, $root_path);
1069
}
1070

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

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

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

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

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

    
1138
    case 'entity:user':
1139
      $plugin = ctools_get_context('user');
1140
      unset($plugin['no ui']);
1141
      unset($plugin['no required context ui']);
1142
      break;
1143
  }
1144

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

    
1158
/**
1159
 * Implements hook_field_create_field().
1160
 */
1161
function ctools_field_create_field($field) {
1162
  ctools_flush_field_caches();
1163
}
1164

    
1165
/**
1166
 * Implements hook_field_create_instance().
1167
 */
1168
function ctools_field_create_instance($instance) {
1169
  ctools_flush_field_caches();
1170
}
1171

    
1172
/**
1173
 * Implements hook_field_delete_field().
1174
 */
1175
function ctools_field_delete_field($field) {
1176
  ctools_flush_field_caches();
1177
}
1178

    
1179
/**
1180
 * Implements hook_field_delete_instance().
1181
 */
1182
function ctools_field_delete_instance($instance) {
1183
  ctools_flush_field_caches();
1184
}
1185

    
1186
/**
1187
 * Implements hook_field_update_field().
1188
 */
1189
function ctools_field_update_field($field, $prior_field, $has_data) {
1190
  ctools_flush_field_caches();
1191
}
1192

    
1193
/**
1194
 * Implements hook_field_update_instance().
1195
 */
1196
function ctools_field_update_instance($instance, $prior_instance) {
1197
  ctools_flush_field_caches();
1198
}
1199

    
1200
/**
1201
 * Clear field related caches.
1202
 */
1203
function ctools_flush_field_caches() {
1204
  // Clear caches of 'Entity field' content type plugin.
1205
  cache_clear_all('ctools_entity_field_content_type_content_types', 'cache');
1206
}