Projet

Général

Profil

Paste
Télécharger (47,2 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / ctools / includes / context.inc @ 136a805a

1
<?php
2

    
3
/**
4
 * @file
5
 *
6
 * Contains code related to the ctools system of 'context'.
7
 *
8
 * Context, originally from Panels, is a method of packaging objects into
9
 * a more generic bundle and providing a plugin system so that a UI can
10
 * take advantage of them. The idea is that the context objects
11
 * represent 'the context' that a given operation (usually a page view)
12
 * is operating in or on.
13
 *
14
 * For example, when viewing a page, the 'context' is a node object. When
15
 * viewing a user, the 'context' is a user object. Contexts can also
16
 * have related contexts. For example, when viewing a 'node' you may need
17
 * to know something about the node author. Therefore, the node author
18
 * is a related context.
19
 */
20

    
21
/**
22
 * The context object is largely a wrapper around some other object, with
23
 * an interface to finding out what is contained and getting to both
24
 * the object and information about the object.
25
 *
26
 * Each context object has its own information, but some things are very
27
 * common, such as titles, data, keywords, etc. In particulare, the 'type'
28
 * of the context is important.
29
 */
30
class ctools_context {
31
  var $type = NULL;
32
  var $data = NULL;
33
  // The title of this object.
34
  var $title = '';
35
  // The title of the page if this object exists
36
  var $page_title = '';
37
  // The identifier (in the UI) of this object
38
  var $identifier = '';
39
  var $argument = NULL;
40
  var $keyword = '';
41
  var $original_argument = NULL;
42
  var $restrictions = array();
43
  var $empty = FALSE;
44

    
45
  function __construct($type = 'none', $data = NULL) {
46
    $this->type  = $type;
47
    $this->data  = $data;
48
    $this->title = t('Unknown context');
49
  }
50

    
51
  function is_type($type) {
52
    if ($type == 'any' || $this->type == 'any') {
53
      return TRUE;
54
    }
55

    
56
    $a = is_array($type) ? $type : array($type);
57
    $b = is_array($this->type) ? $this->type : array($this->type);
58
    return (bool) array_intersect($a, $b);
59
  }
60

    
61
  function get_argument() {
62
    return $this->argument;
63
  }
64

    
65
  function get_original_argument() {
66
    if (!is_null($this->original_argument)) {
67
      return $this->original_argument;
68
    }
69
    return $this->argument;
70
  }
71

    
72
  function get_keyword() {
73
    return $this->keyword;
74
  }
75

    
76
  function get_identifier() {
77
    return $this->identifier;
78
  }
79

    
80
  function get_title() {
81
    return $this->title;
82
  }
83

    
84
  function get_page_title() {
85
    return $this->page_title;
86
  }
87
}
88

    
89
/**
90
 * Used to create a method of comparing if a list of contexts
91
 * match a required context type.
92
 */
93
class ctools_context_required {
94
  var $keywords = '';
95

    
96
  /**
97
   * If set, the title will be used in the selector to identify
98
   * the context. This is very useful when multiple contexts
99
   * are required to inform the user will be used for what.
100
   */
101
  var $title = NULL;
102

    
103
  /**
104
   * Test to see if this context is required.
105
   */
106
  var $required = TRUE;
107

    
108
  /**
109
   * If TRUE, skip the check in ctools_context_required::select()
110
   * for contexts whose names may have changed.
111
   */
112
  var $skip_name_check = FALSE;
113

    
114
  /**
115
   *
116
   * @param $title
117
   *   The first parameter should be the 'title' of the context for use
118
   *   in UYI selectors when multiple contexts qualify.
119
   * @param ...
120
   *   One or more keywords to use for matching which contexts are allowed.
121
   */
122
  function __construct($title) {
123
    $args = func_get_args();
124
    $this->title = array_shift($args);
125

    
126
    // If we have a boolean value at the end for $skip_name_check, store it
127
    if (is_bool(end($args))) {
128
      $this->skip_name_check = array_pop($args);
129
    }
130

    
131
    // If we were given restrictions at the end, store them.
132
    if (count($args) > 1 && is_array(end($args))) {
133
      $this->restrictions = array_pop($args);
134
    }
135

    
136
    if (count($args) == 1) {
137
      $args = array_shift($args);
138
    }
139
    $this->keywords = $args;
140
  }
141

    
142
  function filter($contexts) {
143
    $result = array();
144

    
145
    // See which of these contexts are valid
146
    foreach ((array) $contexts as $cid => $context) {
147
      if ($context->is_type($this->keywords)) {
148
        // Compare to see if our contexts were met.
149
        if (!empty($this->restrictions) && !empty($context->restrictions)) {
150
          foreach ($this->restrictions as $key => $values) {
151
            // If we have a restriction, the context must either not have that
152
            // restriction listed, which means we simply don't know what it is,
153
            // or there must be an intersection of the restricted values on
154
            // both sides.
155
            if (!is_array($values)) {
156
              $values = array($values);
157
            }
158
            if (!empty($context->restrictions[$key]) && !array_intersect($values, $context->restrictions[$key])) {
159
              continue 2;
160
            }
161
          }
162
        }
163
        $result[$cid] = $context;
164
      }
165
    }
166

    
167
    return $result;
168
  }
169

    
170
  function select($contexts, $context) {
171
    if (!is_array($contexts)) {
172
      if (is_object($contexts) && $contexts instanceof ctools_context) {
173
        $contexts = array($contexts->id => $contexts);
174
      }
175
      else {
176
        $contexts = array($contexts);
177
      }
178
    }
179

    
180
    // If we had requested a $context but that $context doesn't exist
181
    // in our context list, there is a good chance that what happened
182
    // is our context IDs changed. See if there's another context
183
    // that satisfies our requirements.
184
    if (!$this->skip_name_check && !empty($context) && !isset($contexts[$context])) {
185
      $choices = $this->filter($contexts);
186

    
187
      // If we got a hit, take the first one that matches.
188
      if ($choices) {
189
        $keys = array_keys($choices);
190
        $context = reset($keys);
191
      }
192
    }
193

    
194
    if (empty($context) || empty($contexts[$context])) {
195
      return FALSE;
196
    }
197
    return $contexts[$context];
198
  }
199
}
200

    
201
/**
202
 * Used to compare to see if a list of contexts match an optional context. This
203
 * can produce empty contexts to use as placeholders.
204
 */
205
class ctools_context_optional extends ctools_context_required {
206
  var $required = FALSE;
207

    
208
  /**
209
   * Add the 'empty' context which is possible for optional
210
   */
211
  function add_empty(&$contexts) {
212
    $context = new ctools_context('any');
213
    $context->title      = t('No context');
214
    $context->identifier = t('No context');
215
    $contexts['empty'] = $context;
216
  }
217

    
218
  function filter($contexts) {
219
    $this->add_empty($contexts);
220
    return parent::filter($contexts);
221
  }
222

    
223
  function select($contexts, $context) {
224
    $this->add_empty($contexts);
225
    if (empty($context)) {
226
      return $contexts['empty'];
227
    }
228

    
229
    $result = parent::select($contexts, $context);
230

    
231
    // Don't flip out if it can't find the context; this is optional, put
232
    // in an empty.
233
    if ($result == FALSE) {
234
      $result = $contexts['empty'];
235
    }
236
    return $result;
237
  }
238
}
239

    
240
/**
241
 * Return a keyed array of context that match the given 'required context'
242
 * filters.
243
 *
244
 * Functions or systems that require contexts of a particular type provide a
245
 * ctools_context_required or ctools_context_optional object. This function
246
 * examines that object and an array of contexts to determine which contexts
247
 * match the filter.
248
 *
249
 * Since multiple contexts can be required, this function will accept either
250
 * an array of all required contexts, or just a single required context object.
251
 *
252
 * @param $contexts
253
 *   A keyed array of all available contexts.
254
 * @param $required
255
 *   A ctools_context_required or ctools_context_optional object, or an array
256
 *   of such objects.
257
 *
258
 * @return
259
 *   A keyed array of contexts that match the filter.
260
 */
261
function ctools_context_filter($contexts, $required) {
262
  if (is_array($required)) {
263
    $result = array();
264
    foreach ($required as $r) {
265
      $result = array_merge($result, _ctools_context_filter($contexts, $r));
266
    }
267
    return $result;
268
  }
269

    
270
  return _ctools_context_filter($contexts, $required);
271
}
272

    
273
function _ctools_context_filter($contexts, $required) {
274
  $result = array();
275

    
276
  if (is_object($required)) {
277
    $result = $required->filter($contexts);
278
  }
279

    
280
  return $result;
281
}
282

    
283
/**
284
 * Create a select box to choose possible contexts.
285
 *
286
 * This only creates a selector if there is actually a choice; if there
287
 * is only one possible context, that one is silently assigned.
288
 *
289
 * If an array of required contexts is provided, one selector will be
290
 * provided for each context.
291
 *
292
 * @param $contexts
293
 *   A keyed array of all available contexts.
294
 * @param $required
295
 *   The required context object or array of objects.
296
 *
297
 * @return
298
 *   A form element, or NULL if there are no contexts that satisfy the
299
 *   requirements.
300
 */
301
function ctools_context_selector($contexts, $required, $default) {
302
  if (is_array($required)) {
303
    $result = array('#tree' => TRUE);
304
    $count = 1;
305
    foreach ($required as $id => $r) {
306
      $result[] = _ctools_context_selector($contexts, $r, isset($default[$id]) ? $default[$id] : '', $count++);
307
    }
308
    return $result;
309
  }
310

    
311
  return _ctools_context_selector($contexts, $required, $default);
312
}
313

    
314
function _ctools_context_selector($contexts, $required, $default, $num = 0) {
315
  $filtered = ctools_context_filter($contexts, $required);
316
  $count = count($filtered);
317

    
318
  $form = array();
319

    
320
  if ($count >= 1) {
321
    // If there's more than one to choose from, create a select widget.
322
    foreach ($filtered as $cid => $context) {
323
      $options[$cid] = $context->get_identifier();
324
    }
325
    if (!empty($required->title)) {
326
      $title = $required->title;
327
    }
328
    else {
329
      $title = $num ? t('Context %count', array('%count' => $num)) : t('Context');
330
    }
331

    
332
    $form = array(
333
      '#type' => 'select',
334
      '#options' => $options,
335
      '#title' => $title,
336
      '#default_value' => $default,
337
    );
338
  }
339

    
340
  return $form;
341
}
342

    
343
/**
344
 * Are there enough contexts for a plugin?
345
 *
346
 * Some plugins can have a 'required contexts' item which can either
347
 * be a context requirement object or an array of them. When contexts
348
 * are required, items that do not have enough contexts should not
349
 * appear. This tests an item to see if it has enough contexts
350
 * to actually appear.
351
 *
352
 * @param $contexts
353
 *   A keyed array of all available contexts.
354
 * @param $required
355
 *   The required context object or array of objects.
356
 *
357
 * @return
358
 *   TRUE if there are enough contexts, FALSE if there are not.
359
 */
360
function ctools_context_match_requirements($contexts, $required) {
361
  if (!is_array($required)) {
362
    $required = array($required);
363
  }
364

    
365
  // Get the keys to avoid bugs in PHP 5.0.8 with keys and loops.
366
  // And use it to remove optional contexts.
367
  $keys = array_keys($required);
368
  foreach ($keys as $key) {
369
    if (empty($required[$key]->required)) {
370
      unset($required[$key]);
371
    }
372
  }
373

    
374
  $count = count($required);
375
  return (count(ctools_context_filter($contexts, $required)) >= $count);
376
}
377

    
378
/**
379
 * Create a select box to choose possible contexts.
380
 *
381
 * This only creates a selector if there is actually a choice; if there
382
 * is only one possible context, that one is silently assigned.
383
 *
384
 * If an array of required contexts is provided, one selector will be
385
 * provided for each context.
386
 *
387
 * @param $contexts
388
 *   A keyed array of all available contexts.
389
 * @param $required
390
 *   The required context object or array of objects.
391
 *
392
 * @return
393
 *   A form element, or NULL if there are no contexts that satisfy the
394
 *   requirements.
395
 */
396
function ctools_context_converter_selector($contexts, $required, $default) {
397
  if (is_array($required)) {
398
    $result = array('#tree' => TRUE);
399
    $count = 1;
400
    foreach ($required as $id => $r) {
401
      $result[] = _ctools_context_converter_selector($contexts, $r, isset($default[$id]) ? $default[$id] : '', $count++);
402
    }
403
    return $result;
404
  }
405

    
406
  return _ctools_context_converter_selector($contexts, $required, $default);
407
}
408

    
409
function _ctools_context_converter_selector($contexts, $required, $default, $num = 0) {
410
  $filtered = ctools_context_filter($contexts, $required);
411
  $count = count($filtered);
412

    
413
  $form = array();
414

    
415
  if ($count > 1) {
416
    // If there's more than one to choose from, create a select widget.
417
    $options = array();
418
    foreach ($filtered as $cid => $context) {
419
      if ($context->type == 'any') {
420
        $options[''] = t('No context');
421
        continue;
422
      }
423
      $key = $context->get_identifier();
424
      if ($converters = ctools_context_get_converters($cid . '.', $context)) {
425
        $options[$key] = $converters;
426
      }
427
    }
428
    if (empty($options)) {
429
      return array(
430
        '#type' => 'value',
431
        '#value' => 'any',
432
      );
433
    }
434
    if (!empty($required->title)) {
435
      $title = $required->title;
436
    }
437
    else {
438
      $title = $num ? t('Context %count', array('%count' => $num)) : t('Context');
439
    }
440

    
441
    return array(
442
      '#type' => 'select',
443
      '#options' => $options,
444
      '#title' => $title,
445
      '#description' => t('Please choose which context and how you would like it converted.'),
446
      '#default_value' => $default,
447
    );
448
  }
449
}
450

    
451
/**
452
 * Get a list of converters available for a given context.
453
 */
454
function ctools_context_get_converters($cid, $context) {
455
  if (empty($context->plugin)) {
456
    return array();
457
  }
458

    
459
  return _ctools_context_get_converters($cid, $context->plugin);
460
}
461

    
462
/**
463
 * Get a list of converters available for a given context.
464
 */
465
function _ctools_context_get_converters($id, $plugin_name) {
466
  $plugin = ctools_get_context($plugin_name);
467
  if (empty($plugin['convert list'])) {
468
    return array();
469
  }
470

    
471
  $converters = array();
472
  if (is_array($plugin['convert list'])) {
473
    $converters = $plugin['convert list'];
474
  }
475
  else if ($function = ctools_plugin_get_function($plugin, 'convert list')) {
476
    $converters = (array) $function($plugin);
477
  }
478

    
479
  foreach (module_implements('ctools_context_convert_list_alter') as $module) {
480
    $function = $module . '_ctools_context_convert_list_alter';
481
    $function($plugin, $converters);
482
  }
483

    
484
  // Now, change them all to include the plugin:
485
  $return = array();
486
  foreach ($converters as $key => $title) {
487
    $return[$id . $key] = $title;
488
  }
489

    
490
  natcasesort($return);
491
  return $return;
492
}
493

    
494
/**
495
 * Get a list of all contexts + converters available.
496
 */
497
function ctools_context_get_all_converters() {
498
  $contexts = ctools_get_contexts();
499
  $converters = array();
500
  foreach ($contexts as $name => $context) {
501
    if (empty($context['no required context ui'])) {
502
      $context_converters = _ctools_context_get_converters($name . '.', $name);
503
      if ($context_converters) {
504
        $converters[$context['title']] = $context_converters;
505
      }
506
    }
507
  }
508

    
509
  return $converters;
510
}
511

    
512
/**
513
 * Let the context convert an argument based upon the converter that was given.
514
 *
515
 * @param $context
516
 *   The context object
517
 * @param $converter
518
 *   The converter to use, which should be a string provided by the converter list.
519
 * @param $converter_options
520
 *   A n array of options to pass on to the generation function. For contexts
521
 *   that use token module, of particular use is 'sanitize' => FALSE which can
522
 *   get raw tokens. This should ONLY be used in values that will later be
523
 *   treated as unsafe user input since these values are by themselves unsafe.
524
 *   It is particularly useful to get raw values from Field API.
525
 */
526
function ctools_context_convert_context($context, $converter, $converter_options = array()) {
527
  // Contexts without plugins might be optional placeholders.
528
  if (empty($context->plugin)) {
529
    return;
530
  }
531

    
532
  $value = $context->argument;
533
  $plugin = ctools_get_context($context->plugin);
534
  if ($function = ctools_plugin_get_function($plugin, 'convert')) {
535
    $value = $function($context, $converter, $converter_options);
536
  }
537

    
538
  foreach (module_implements('ctools_context_converter_alter') as $module) {
539
    $function = $module . '_ctools_context_converter_alter';
540
    $function($context, $converter, $value, $converter_options);
541
  }
542

    
543
  return $value;
544
}
545

    
546
/**
547
 * Choose a context or contexts based upon the selection made via
548
 * ctools_context_filter.
549
 *
550
 * @param $contexts
551
 *   A keyed array of all available contexts
552
 * @param $required
553
 *   The required context object provided by the plugin
554
 * @param $context
555
 *   The selection made using ctools_context_selector
556
 */
557
function ctools_context_select($contexts, $required, $context) {
558
  if (is_array($required)) {
559
    $result = array();
560
    foreach ($required as $id => $r) {
561
      if (empty($required[$id])) {
562
        continue;
563
      }
564

    
565
      if (($result[] = _ctools_context_select($contexts, $r, $context[$id])) === FALSE) {
566
        return FALSE;
567
      }
568
    }
569
    return $result;
570
  }
571

    
572
  return _ctools_context_select($contexts, $required, $context);
573
}
574

    
575
function _ctools_context_select($contexts, $required, $context) {
576
  if (!is_object($required)) {
577
    return FALSE;
578
  }
579

    
580
  return $required->select($contexts, $context);
581
}
582

    
583
/**
584
 * Create a new context object.
585
 *
586
 * @param $type
587
 *   The type of context to create; this loads a plugin.
588
 * @param $data
589
 *   The data to put into the context.
590
 * @param $empty
591
 *   Whether or not this context is specifically empty.
592
 * @param $conf
593
 *   A configuration structure if this context was created via UI.
594
 *
595
 * @return
596
 *   A $context or NULL if one could not be created.
597
 */
598
function ctools_context_create($type, $data = NULL, $conf = FALSE) {
599
  ctools_include('plugins');
600
  $plugin = ctools_get_context($type);
601

    
602
  if ($function = ctools_plugin_get_function($plugin, 'context')) {
603
    return $function(FALSE, $data, $conf, $plugin);
604
  }
605
}
606

    
607
/**
608
 * Create an empty context object.
609
 *
610
 * Empty context objects are primarily used as placeholders in the UI where
611
 * the actual contents of a context object may not be known. It may have
612
 * additional text embedded to give the user clues as to how the context
613
 * is used.
614
 *
615
 * @param $type
616
 *   The type of context to create; this loads a plugin.
617
 *
618
 * @return
619
 *   A $context or NULL if one could not be created.
620
 */
621
function ctools_context_create_empty($type) {
622
  $plugin = ctools_get_context($type);
623
  if ($function = ctools_plugin_get_function($plugin, 'context')) {
624
    $context = $function(TRUE, NULL, FALSE, $plugin);
625
    if (is_object($context)) {
626
      $context->empty = TRUE;
627
    }
628

    
629
    return $context;
630
  }
631
}
632

    
633
/**
634
 * Perform keyword and context substitutions.
635
 */
636
function ctools_context_keyword_substitute($string, $keywords, $contexts, $converter_options = array()) {
637
  // Ensure a default keyword exists:
638
  $keywords['%%'] = '%';
639

    
640
  // Match contexts to the base keywords:
641
  $context_keywords = array();
642
  foreach ($contexts as $context) {
643
    if (isset($context->keyword)) {
644
      $context_keywords[$context->keyword] = $context;
645
    }
646
  }
647

    
648
  // Look for context matches we we only have to convert known matches.
649
  $matches = array();
650
  if (preg_match_all('/%(%|[a-zA-Z0-9_-]+(?:\:[a-zA-Z0-9_-]+)*)/us', $string, $matches)) {
651
    foreach ($matches[1] as $keyword) {
652
      // Ignore anything it finds with %%.
653
      if ($keyword[0] == '%') {
654
        continue;
655
      }
656

    
657
      // If the keyword is already set by something passed in, don't try to
658
      // overwrite it.
659
      if (!empty($keywords['%' . $keyword])) {
660
        continue;
661
      }
662

    
663
      // Figure out our keyword and converter, if specified.
664
      if (strpos($keyword, ':')) {
665
        list($context, $converter) = explode(':', $keyword, 2);
666
      }
667
      else {
668
        $context = $keyword;
669
        if (isset($context_keywords[$keyword])) {
670
          $plugin = ctools_get_context($context_keywords[$context]->plugin);
671

    
672
          // Fall back to a default converter, if specified.
673
          if ($plugin && !empty($plugin['convert default'])) {
674
            $converter = $plugin['convert default'];
675
          }
676
        }
677
      }
678

    
679
      if (empty($context_keywords[$context]) || !empty($context_keywords[$context]->empty)) {
680
        $keywords['%' . $keyword] = '';
681
      }
682
      else if (!empty($converter)) {
683
        $keywords['%' . $keyword] = ctools_context_convert_context($context_keywords[$context], $converter, $converter_options);
684
      }
685
      else {
686
        $keywords['%' . $keyword] = $context_keywords[$keyword]->title;
687
      }
688
    }
689
  }
690
  return strtr($string, $keywords);
691
}
692

    
693
/**
694
 * Determine a unique context ID for a context
695
 *
696
 * Often contexts of many different types will be placed into a list. This
697
 * ensures that even though contexts of multiple types may share IDs, they
698
 * are unique in the final list.
699
 */
700
function ctools_context_id($context, $type = 'context') {
701
  if (!$context['id']) {
702
    $context['id'] = 1;
703
  }
704

    
705
  return $type . '_' . $context['name'] . '_' . $context['id'];
706
}
707

    
708
/**
709
 * Get the next id available given a list of already existing objects.
710
 *
711
 * This finds the next id available for the named object.
712
 *
713
 * @param $objects
714
 *   A list of context descriptor objects, i.e, arguments, relationships, contexts, etc.
715
 * @param $name
716
 *   The name being used.
717
 */
718
function ctools_context_next_id($objects, $name) {
719
  $id = 0;
720
  // Figure out which instance of this argument we're creating
721
  if (!$objects) {
722
    return $id + 1;
723
  }
724

    
725
  foreach ($objects as $object) {
726
    if (isset($object['name']) && $object['name'] == $name) {
727
      if ($object['id'] > $id) {
728
        $id = $object['id'];
729
      }
730
    }
731
  }
732

    
733
  return $id + 1;
734
}
735

    
736

    
737
// ---------------------------------------------------------------------------
738
// Functions related to contexts from arguments.
739

    
740
/**
741
 * Fetch metadata on a specific argument plugin.
742
 *
743
 * @param $argument
744
 *   Name of an argument plugin.
745
 *
746
 * @return
747
 *   An array with information about the requested argument plugin.
748
 */
749
function ctools_get_argument($argument) {
750
  ctools_include('plugins');
751
  return ctools_get_plugins('ctools', 'arguments', $argument);
752
}
753

    
754
/**
755
 * Fetch metadata for all argument plugins.
756
 *
757
 * @return
758
 *   An array of arrays with information about all available argument plugins.
759
 */
760
function ctools_get_arguments() {
761
  ctools_include('plugins');
762
  return ctools_get_plugins('ctools', 'arguments');
763
}
764

    
765
/**
766
 * Get a context from an argument.
767
 *
768
 * @param $argument
769
 *   The configuration of an argument. It must contain the following data:
770
 *   - name: The name of the argument plugin being used.
771
 *   - argument_settings: The configuration based upon the plugin forms.
772
 *   - identifier: The human readable identifier for this argument, usually
773
 *     defined by the UI.
774
 *   - keyword: The keyword used for this argument for substitutions.
775
 *
776
 * @param $arg
777
 *   The actual argument received. This is expected to be a string from a URL but
778
 *   this does not have to be the only source of arguments.
779
 * @param $empty
780
 *   If true, the $arg will not be used to load the context. Instead, an empty
781
 *   placeholder context will be loaded.
782
 *
783
 * @return
784
 *   A context object if one can be loaded.
785
 */
786
function ctools_context_get_context_from_argument($argument, $arg, $empty = FALSE) {
787
  ctools_include('plugins');
788
  if (empty($argument['name'])) {
789
    return;
790
  }
791

    
792
  if ($function = ctools_plugin_load_function('ctools', 'arguments', $argument['name'], 'context')) {
793
    // Backward compatibility: Merge old style settings into new style:
794
    if (!empty($argument['settings'])) {
795
      $argument += $argument['settings'];
796
      unset($argument['settings']);
797
    }
798

    
799
    $context = $function($arg, $argument, $empty);
800

    
801
    if (is_object($context)) {
802
      $context->identifier = $argument['identifier'];
803
      $context->page_title = isset($argument['title']) ? $argument['title'] : '';
804
      $context->keyword    = $argument['keyword'];
805
      $context->id         = ctools_context_id($argument, 'argument');
806
      $context->original_argument = $arg;
807

    
808
      if (!empty($context->empty)) {
809
        $context->placeholder = array(
810
          'type' => 'argument',
811
          'conf' => $argument,
812
        );
813
      }
814
    }
815
    return $context;
816
  }
817
}
818

    
819
/**
820
 * Retrieve a list of empty contexts for all arguments.
821
 */
822
function ctools_context_get_placeholders_from_argument($arguments) {
823
  $contexts = array();
824
  foreach ($arguments as $argument) {
825
    $context = ctools_context_get_context_from_argument($argument, NULL, TRUE);
826
    if ($context) {
827
      $contexts[ctools_context_id($argument, 'argument')] = $context;
828
    }
829
  }
830
  return $contexts;
831
}
832

    
833
/**
834
 * Load the contexts for a given list of arguments.
835
 *
836
 * @param $arguments
837
 *   The array of argument definitions.
838
 * @param &$contexts
839
 *   The array of existing contexts. New contexts will be added to this array.
840
 * @param $args
841
 *   The arguments to load.
842
 *
843
 * @return
844
 *   FALSE if an argument wants to 404.
845
 */
846
function ctools_context_get_context_from_arguments($arguments, &$contexts, $args) {
847
  foreach ($arguments as $argument) {
848
    // pull the argument off the list.
849
    $arg = array_shift($args);
850
    $id = ctools_context_id($argument, 'argument');
851

    
852
    // For % arguments embedded in the URL, our context is already loaded.
853
    // There is no need to go and load it again.
854
    if (empty($contexts[$id])) {
855
      if ($context = ctools_context_get_context_from_argument($argument, $arg)) {
856
        $contexts[$id] = $context;
857
      }
858
    }
859
    else {
860
      $context = $contexts[$id];
861
    }
862

    
863
    if ((empty($context) || empty($context->data)) && !empty($argument['default']) && $argument['default'] == '404') {
864
      return FALSE;
865
    }
866
  }
867
  return TRUE;
868
}
869

    
870
// ---------------------------------------------------------------------------
871
// Functions related to contexts from relationships.
872

    
873
/**
874
 * Fetch metadata on a specific relationship plugin.
875
 *
876
 * @param $content type
877
 *   Name of a panel content type.
878
 *
879
 * @return
880
 *   An array with information about the requested relationship.
881
 */
882
function ctools_get_relationship($relationship) {
883
  ctools_include('plugins');
884
  return ctools_get_plugins('ctools', 'relationships', $relationship);
885
}
886

    
887
/**
888
 * Fetch metadata for all relationship plugins.
889
 *
890
 * @return
891
 *   An array of arrays with information about all available relationships.
892
 */
893
function ctools_get_relationships() {
894
  ctools_include('plugins');
895
  return ctools_get_plugins('ctools', 'relationships');
896
}
897

    
898
/**
899
 *
900
 * @param $relationship
901
 *   The configuration of a relationship. It must contain the following data:
902
 *   - name: The name of the relationship plugin being used.
903
 *   - relationship_settings: The configuration based upon the plugin forms.
904
 *   - identifier: The human readable identifier for this relationship, usually
905
 *     defined by the UI.
906
 *   - keyword: The keyword used for this relationship for substitutions.
907
 *
908
 * @param $source_context
909
 *   The context this relationship is based upon.
910
 *
911
 * @param $placeholders
912
 *   If TRUE, placeholders are acceptable.
913
 *
914
 * @return
915
 *   A context object if one can be loaded.
916
 */
917
function ctools_context_get_context_from_relationship($relationship, $source_context, $placeholders = FALSE) {
918
  ctools_include('plugins');
919
  if ($function = ctools_plugin_load_function('ctools', 'relationships', $relationship['name'], 'context')) {
920
    // Backward compatibility: Merge old style settings into new style:
921
    if (!empty($relationship['relationship_settings'])) {
922
      $relationship += $relationship['relationship_settings'];
923
      unset($relationship['relationship_settings']);
924
    }
925

    
926
    $context = $function($source_context, $relationship, $placeholders);
927
    if ($context) {
928
      $context->identifier = $relationship['identifier'];
929
      $context->page_title = isset($relationship['title']) ? $relationship['title'] : '';
930
      $context->keyword    = $relationship['keyword'];
931
      if (!empty($context->empty)) {
932
        $context->placeholder = array(
933
          'type' => 'relationship',
934
          'conf' => $relationship,
935
        );
936
      }
937
      return $context;
938
    }
939
  }
940
}
941

    
942
/**
943
 * Fetch all relevant relationships.
944
 *
945
 * Relevant relationships are any relationship that can be created based upon
946
 * the list of existing contexts. For example, the 'node author' relationship
947
 * is relevant if there is a 'node' context, but makes no sense if there is
948
 * not one.
949
 *
950
 * @param $contexts
951
 *   An array of contexts used to figure out which relationships are relevant.
952
 *
953
 * @return
954
 *   An array of relationship keys that are relevant for the given set of
955
 *   contexts.
956
 */
957
function ctools_context_get_relevant_relationships($contexts) {
958
  $relevant = array();
959
  $relationships = ctools_get_relationships();
960

    
961
  // Go through each relationship
962
  foreach ($relationships as $rid => $relationship) {
963
    // For each relationship, see if there is a context that satisfies it.
964
    if (empty($relationship['no ui']) && ctools_context_filter($contexts, $relationship['required context'])) {
965
      $relevant[$rid] = $relationship['title'];
966
    }
967
  }
968

    
969
  return $relevant;
970
}
971

    
972
/**
973
 * Fetch all active relationships
974
 *
975
 * @param $relationships
976
 *   An keyed array of relationship data including:
977
 *   - name: name of relationship
978
 *   - context: context id relationship belongs to. This will be used to
979
 *     identify which context in the $contexts array to use to create the
980
 *     relationship context.
981
 *
982
 * @param $contexts
983
 *   A keyed array of contexts used to figure out which relationships
984
 *   are relevant. New contexts will be added to this.
985
 *
986
 * @param $placeholders
987
 *   If TRUE, placeholders are acceptable.
988
 */
989
function ctools_context_get_context_from_relationships($relationships, &$contexts, $placeholders = FALSE) {
990
  $return = array();
991

    
992
  foreach ($relationships as $rdata) {
993
    if (!isset($rdata['context'])) {
994
      continue;
995
    }
996

    
997
    if (is_array($rdata['context'])) {
998
      $rcontexts = array();
999
      foreach ($rdata['context'] as $cid) {
1000
        if (empty($contexts[$cid])) {
1001
          continue 2;
1002
        }
1003
        $rcontexts[] = $contexts[$cid];
1004
      }
1005
    }
1006
    else {
1007
      if (empty($contexts[$rdata['context']])) {
1008
        continue;
1009
      }
1010
      $rcontexts = $contexts[$rdata['context']];
1011
    }
1012

    
1013
    $cid = ctools_context_id($rdata, 'relationship');
1014
    if ($context = ctools_context_get_context_from_relationship($rdata, $rcontexts)) {
1015
      $contexts[$cid] = $context;
1016
    }
1017
  }
1018
}
1019

    
1020
// ---------------------------------------------------------------------------
1021
// Functions related to loading contexts from simple context definitions.
1022

    
1023
/**
1024
 * Fetch metadata on a specific context plugin.
1025
 *
1026
 * @param $context
1027
 *   Name of a context.
1028
 *
1029
 * @return
1030
 *   An array with information about the requested panel context.
1031
 */
1032
function ctools_get_context($context) {
1033
  static $gate = array();
1034
  ctools_include('plugins');
1035
  $plugin = ctools_get_plugins('ctools', 'contexts', $context);
1036
  if (empty($gate['context']) && !empty($plugin['superceded by'])) {
1037
    // This gate prevents infinite loops.
1038
    $gate[$context] = TRUE;
1039
    $new_plugin = ctools_get_plugins('ctools', 'contexts', $plugin['superceded by']);
1040
    $gate[$context] = FALSE;
1041

    
1042
    // If a new plugin was returned, return it. Otherwise fall through and
1043
    // return the original we fetched.
1044
    if ($new_plugin) {
1045
      return $new_plugin;
1046
    }
1047
  }
1048

    
1049
  return $plugin;
1050
}
1051

    
1052
/**
1053
 * Fetch metadata for all context plugins.
1054
 *
1055
 * @return
1056
 *   An array of arrays with information about all available panel contexts.
1057
 */
1058
function ctools_get_contexts() {
1059
  ctools_include('plugins');
1060
  return ctools_get_plugins('ctools', 'contexts');
1061
}
1062

    
1063
/**
1064
 *
1065
 * @param $context
1066
 *   The configuration of a context. It must contain the following data:
1067
 *   - name: The name of the context plugin being used.
1068
 *   - context_settings: The configuration based upon the plugin forms.
1069
 *   - identifier: The human readable identifier for this context, usually
1070
 *     defined by the UI.
1071
 *   - keyword: The keyword used for this context for substitutions.
1072
 * @param $type
1073
 *   This is either 'context' which indicates the context will be loaded
1074
 *   from data in the settings, or 'required_context' which means the
1075
 *   context must be acquired from an external source. This is the method
1076
 *   used to pass pure contexts from one system to another.
1077
 *
1078
 * @return
1079
 *   A context object if one can be loaded.
1080
 */
1081
function ctools_context_get_context_from_context($context, $type = 'context', $argument = NULL) {
1082
  ctools_include('plugins');
1083
  $plugin = ctools_get_context($context['name']);
1084
  if ($function = ctools_plugin_get_function($plugin, 'context')) {
1085
    // Backward compatibility: Merge old style settings into new style:
1086
    if (!empty($context['context_settings'])) {
1087
      $context += $context['context_settings'];
1088
      unset($context['context_settings']);
1089
    }
1090

    
1091
    if (isset($argument) && isset($plugin['placeholder name'])) {
1092
      $context[$plugin['placeholder name']] = $argument;
1093
    }
1094

    
1095
    $return = $function($type == 'requiredcontext', $context, TRUE, $plugin);
1096
    if ($return) {
1097
      $return->identifier = $context['identifier'];
1098
      $return->page_title = isset($context['title']) ? $context['title'] : '';
1099
      $return->keyword    = $context['keyword'];
1100

    
1101
      if (!empty($context->empty)) {
1102
        $context->placeholder = array(
1103
          'type' => 'context',
1104
          'conf' => $context,
1105
        );
1106
      }
1107

    
1108
      return $return;
1109
    }
1110
  }
1111
}
1112

    
1113
/**
1114
 * Retrieve a list of base contexts based upon a simple 'contexts' definition.
1115
 *
1116
 * For required contexts this will always retrieve placeholders.
1117
 *
1118
 * @param $contexts
1119
 *   The list of contexts defined in the UI.
1120
 * @param $type
1121
 *   Either 'context' or 'requiredcontext', which indicates whether the contexts
1122
 *   are loaded from internal data or copied from an external source.
1123
 * @param $placeholders
1124
 *   If true, placeholders are acceptable.
1125
 */
1126
function ctools_context_get_context_from_contexts($contexts, $type = 'context', $placeholders = FALSE) {
1127
  $return = array();
1128
  foreach ($contexts as $context) {
1129
    $ctext = ctools_context_get_context_from_context($context, $type);
1130
    if ($ctext) {
1131
      if ($placeholders) {
1132
        $ctext->placeholder = TRUE;
1133
      }
1134
      $return[ctools_context_id($context, $type)] = $ctext;
1135
    }
1136
  }
1137
  return $return;
1138
}
1139

    
1140
/**
1141
 * Match up external contexts to our required contexts.
1142
 *
1143
 * This function is used to create a list of contexts with proper
1144
 * IDs based upon a list of required contexts.
1145
 *
1146
 * These contexts passed in should match the numeric positions of the
1147
 * required contexts. The caller must ensure this has already happened
1148
 * correctly as this function will not detect errors here.
1149
 *
1150
 * @param $required
1151
 *   A list of required contexts as defined by the UI.
1152
 * @param $contexts
1153
 *   A list of matching contexts as passed in from the calling system.
1154
 */
1155
function ctools_context_match_required_contexts($required, $contexts) {
1156
  $return = array();
1157
  if (!is_array($required)) {
1158
    return $return;
1159
  }
1160

    
1161
  foreach ($required as $r) {
1162
    $context = clone array_shift($contexts);
1163
    $context->identifier = $r['identifier'];
1164
    $context->page_title = isset($r['title']) ? $r['title'] : '';
1165
    $context->keyword    = $r['keyword'];
1166
    $return[ctools_context_id($r, 'requiredcontext')] = $context;
1167
  }
1168

    
1169
  return $return;
1170
}
1171

    
1172
/**
1173
 * Load a full array of contexts for an object.
1174
 *
1175
 * Not all of the types need to be supported by this object.
1176
 *
1177
 * This function is not used to load contexts from external data, but may
1178
 * be used to load internal contexts and relationships. Otherwise it can also
1179
 * be used to generate a full set of placeholders for UI purposes.
1180
 *
1181
 * @param $object
1182
 *   An object that contains some or all of the following variables:
1183
 *
1184
 * - requiredcontexts: A list of UI configured contexts that are required
1185
 *   from an external source. Since these require external data, they will
1186
 *   only be added if $placeholders is set to TRUE, and empty contexts will
1187
 *   be created.
1188
 * - arguments: A list of UI configured arguments that will create contexts.
1189
 *   Since these require external data, they will only be added if $placeholders
1190
 *   is set to TRUE.
1191
 * - contexts: A list of UI configured contexts that have no external source,
1192
 *   and are essentially hardcoded. For example, these might configure a
1193
 *   particular node or a particular taxonomy term.
1194
 * - relationships: A list of UI configured contexts to be derived from other
1195
 *   contexts that already exist from other sources. For example, these might
1196
 *   be used to get a user object from a node via the node author relationship.
1197
 * @param $placeholders
1198
 *   If TRUE, this will generate placeholder objects for types this function
1199
 *   cannot load.
1200
 * @param $contexts
1201
 *   An array of pre-existing contexts that will be part of the return value.
1202
 */
1203
function ctools_context_load_contexts($object, $placeholders = TRUE, $contexts = array()) {
1204
  if (!empty($object->base_contexts)) {
1205
    $contexts += $object->base_contexts;
1206
  }
1207

    
1208
  if ($placeholders) {
1209
    // This will load empty contexts as placeholders for arguments that come
1210
    // from external sources. If this isn't set, it's assumed these context
1211
    // will already have been matched up and loaded.
1212
    if (!empty($object->requiredcontexts) && is_array($object->requiredcontexts)) {
1213
      $contexts += ctools_context_get_context_from_contexts($object->requiredcontexts, 'requiredcontext', $placeholders);
1214
    }
1215

    
1216
    if (!empty($object->arguments) && is_array($object->arguments)) {
1217
      $contexts += ctools_context_get_placeholders_from_argument($object->arguments);
1218
    }
1219
  }
1220

    
1221
  if (!empty($object->contexts) && is_array($object->contexts)) {
1222
    $contexts += ctools_context_get_context_from_contexts($object->contexts, 'context', $placeholders);
1223
  }
1224

    
1225
  // add contexts from relationships
1226
  if (!empty($object->relationships) && is_array($object->relationships)) {
1227
    ctools_context_get_context_from_relationships($object->relationships, $contexts, $placeholders);
1228
  }
1229

    
1230
  return $contexts;
1231
}
1232

    
1233
/**
1234
 * Return the first context with a form id from a list of contexts.
1235
 *
1236
 * This function is used to figure out which contexts represents 'the form'
1237
 * from a list of contexts. Only one contexts can actually be 'the form' for
1238
 * a given page, since the @code{<form>} tag can not be embedded within
1239
 * itself.
1240
 */
1241
function ctools_context_get_form($contexts) {
1242
  if (!empty($contexts)) {
1243
    foreach ($contexts as $id => $context) {
1244
      // if a form shows its id as being a 'required context' that means the
1245
      // the context is external to this display and does not count.
1246
      if (!empty($context->form_id) && substr($id, 0, 15) != 'requiredcontext') {
1247
        return $context;
1248
      }
1249
    }
1250
  }
1251
}
1252

    
1253
/**
1254
 * Replace placeholders with real contexts using data extracted from a form
1255
 * for the purposes of previews.
1256
 *
1257
 * @param $contexts
1258
 *   All of the contexts, including the placeholders.
1259
 * @param $arguments
1260
 *   The arguments. These will be acquired from $form_state['values'] and the
1261
 *   keys must match the context IDs.
1262
 *
1263
 * @return
1264
 *   A new $contexts array containing the replaced contexts. Not all contexts
1265
 *   may be replaced if, for example, an argument was unable to be converted
1266
 *   into a context.
1267
 */
1268
function ctools_context_replace_placeholders($contexts, $arguments) {
1269
  foreach ($contexts as $cid => $context) {
1270
    if (empty($context->empty)) {
1271
      continue;
1272
    }
1273

    
1274
    $new_context = NULL;
1275
    switch ($context->placeholder['type']) {
1276
      case 'relationship':
1277
        $relationship = $context->placeholder['conf'];
1278
        if (isset($contexts[$relationship['context']])) {
1279
          $new_context = ctools_context_get_context_from_relationship($relationship, $contexts[$relationship['context']]);
1280
        }
1281
        break;
1282
      case 'argument':
1283
        if (isset($arguments[$cid]) && $arguments[$cid] !== '') {
1284
          $argument = $context->placeholder['conf'];
1285
          $new_context = ctools_context_get_context_from_argument($argument, $arguments[$cid]);
1286
        }
1287
        break;
1288
      case 'context':
1289
        if (!empty($arguments[$cid])) {
1290
          $context_info = $context->placeholder['conf'];
1291
          $new_context = ctools_context_get_context_from_context($context_info, 'requiredcontext', $arguments[$cid]);
1292
        }
1293
        break;
1294
    }
1295

    
1296
    if ($new_context && empty($new_context->empty)) {
1297
      $contexts[$cid] = $new_context;
1298
    }
1299
  }
1300

    
1301
  return $contexts;
1302
}
1303

    
1304
/**
1305
 * Provide a form array for getting data to replace placeholder contexts
1306
 * with real data.
1307
 */
1308
function ctools_context_replace_form(&$form, $contexts) {
1309
  foreach ($contexts as $cid => $context) {
1310
    if (empty($context->empty)) {
1311
      continue;
1312
    }
1313

    
1314
    // Get plugin info from the context which should have been set when the
1315
    // empty context was created.
1316
    $info = NULL;
1317
    $plugin = NULL;
1318
    $settings = NULL;
1319
    switch ($context->placeholder['type']) {
1320
      case 'argument':
1321
        $info = $context->placeholder['conf'];
1322
        $plugin = ctools_get_argument($info['name']);
1323
        break;
1324

    
1325
      case 'context':
1326
        $info = $context->placeholder['conf'];
1327
        $plugin = ctools_get_context($info['name']);
1328
        break;
1329
    }
1330

    
1331
    // Ask the plugin where the form is.
1332
    if ($plugin && isset($plugin['placeholder form'])) {
1333
      if (is_array($plugin['placeholder form'])) {
1334
        $form[$cid] = $plugin['placeholder form'];
1335
      }
1336
      else if (function_exists($plugin['placeholder form'])) {
1337
        $widget = $plugin['placeholder form']($info);
1338
        if ($widget) {
1339
          $form[$cid] = $widget;
1340
        }
1341
      }
1342

    
1343
      if (!empty($form[$cid])) {
1344
        $form[$cid]['#title'] = t('@identifier (@keyword)', array('@keyword' => '%' . $context->keyword, '@identifier' => $context->identifier));
1345
      }
1346
    }
1347
  }
1348
}
1349

    
1350
// ---------------------------------------------------------------------------
1351
// Functions related to loading access control plugins
1352

    
1353
/**
1354
 * Fetch metadata on a specific access control plugin.
1355
 *
1356
 * @param $name
1357
 *   Name of a plugin.
1358
 *
1359
 * @return
1360
 *   An array with information about the requested access control plugin.
1361
 */
1362
function ctools_get_access_plugin($name) {
1363
  ctools_include('plugins');
1364
  return ctools_get_plugins('ctools', 'access', $name);
1365
}
1366

    
1367
/**
1368
 * Fetch metadata for all access control plugins.
1369
 *
1370
 * @return
1371
 *   An array of arrays with information about all available access control plugins.
1372
 */
1373
function ctools_get_access_plugins() {
1374
  ctools_include('plugins');
1375
  return ctools_get_plugins('ctools', 'access');
1376
}
1377

    
1378
/**
1379
 * Fetch a list of access plugins that are available for a given list of
1380
 * contexts.
1381
 *
1382
 * if 'logged-in-user' is not in the list of contexts, it will be added as
1383
 * this is required.
1384
 */
1385
function ctools_get_relevant_access_plugins($contexts) {
1386
  if (!isset($contexts['logged-in-user'])) {
1387
    $contexts['logged-in-user'] = ctools_access_get_loggedin_context();
1388
  }
1389

    
1390
  $all_plugins = ctools_get_access_plugins();
1391
  $plugins = array();
1392
  foreach ($all_plugins as $id => $plugin) {
1393
    if (!empty($plugin['required context']) && !ctools_context_match_requirements($contexts, $plugin['required context'])) {
1394
      continue;
1395
    }
1396
    $plugins[$id] = $plugin;
1397
  }
1398

    
1399
  return $plugins;
1400
}
1401

    
1402
/**
1403
 * Create a context for the logged in user.
1404
 */
1405
function ctools_access_get_loggedin_context() {
1406
  $context = ctools_context_create('entity:user', array('type' => 'current'), TRUE);
1407
  $context->identifier = t('Logged in user');
1408
  $context->keyword    = 'viewer';
1409
  $context->id         = 0;
1410

    
1411
  return $context;
1412
}
1413

    
1414
/**
1415
 * Get a summary of an access plugin's settings.
1416
 */
1417
function ctools_access_summary($plugin, $contexts, $test) {
1418
  if (!isset($contexts['logged-in-user'])) {
1419
    $contexts['logged-in-user'] = ctools_access_get_loggedin_context();
1420
  }
1421

    
1422
  $description = '';
1423
  if ($function = ctools_plugin_get_function($plugin, 'summary')) {
1424
    $required_context = isset($plugin['required context']) ? $plugin['required context'] : array();
1425
    $context          = isset($test['context']) ? $test['context'] : array();
1426
    $description      = $function($test['settings'], ctools_context_select($contexts, $required_context, $context), $plugin);
1427
  }
1428

    
1429
  if (!empty($test['not'])) {
1430
    $description = "NOT ($description)";
1431
  }
1432

    
1433
  return $description;
1434
}
1435

    
1436
/**
1437
 * Get a summary of a group of access plugin's settings.
1438
 */
1439
function ctools_access_group_summary($access, $contexts) {
1440
  if (empty($access['plugins'])) {
1441
    return;
1442
  }
1443

    
1444
  $descriptions = array();
1445
  foreach ($access['plugins'] as $id => $test) {
1446
    $plugin = ctools_get_access_plugin($test['name']);
1447
    $descriptions[] = ctools_access_summary($plugin, $contexts, $test);
1448
  }
1449

    
1450
  $separator = (isset($access['logic']) && $access['logic'] == 'and') ? t(', and ') : t(', or ');
1451
  return implode($separator, $descriptions);
1452
}
1453

    
1454
/**
1455
 * Determine if the current user has access via  plugin.
1456
 *
1457
 * @param $settings
1458
 *   An array of settings theoretically set by the user.
1459
 * @param $contexts
1460
 *   An array of zero or more contexts that may be used to determine if
1461
 *   the user has access.
1462
 *
1463
 * @return
1464
 *   TRUE if access is granted, false if otherwise.
1465
 */
1466
function ctools_access($settings, $contexts = array()) {
1467
  if (empty($settings['plugins'])) {
1468
    return TRUE;
1469
  }
1470

    
1471
  if (!isset($settings['logic'])) {
1472
    $settings['logic'] = 'and';
1473
  }
1474

    
1475
  if (!isset($contexts['logged-in-user'])) {
1476
    $contexts['logged-in-user'] = ctools_access_get_loggedin_context();
1477
  }
1478

    
1479
  foreach ($settings['plugins'] as $test) {
1480
    $pass = FALSE;
1481
    $plugin = ctools_get_access_plugin($test['name']);
1482
    if ($plugin && $function = ctools_plugin_get_function($plugin, 'callback')) {
1483
      // Do we need just some contexts or all of them?
1484
      if (!empty($plugin['all contexts'])) {
1485
        $test_contexts = $contexts;
1486
      }
1487
      else {
1488
        $required_context = isset($plugin['required context']) ? $plugin['required context'] : array();
1489
        $context = isset($test['context']) ? $test['context'] : array();
1490
        $test_contexts = ctools_context_select($contexts, $required_context, $context);
1491
      }
1492

    
1493
      $pass = $function($test['settings'], $test_contexts, $plugin);
1494
      if (!empty($test['not'])) {
1495
        $pass = !$pass;
1496
      }
1497
    }
1498

    
1499
    if ($pass && $settings['logic'] == 'or') {
1500
      // Pass if 'or' and this rule passed.
1501
      return TRUE;
1502
    }
1503
    else if (!$pass && $settings['logic'] == 'and') {
1504
      // Fail if 'and' and this rule failed.
1505
      return FALSE;
1506
    }
1507
  }
1508

    
1509
  // Return TRUE if logic was and, meaning all rules passed.
1510
  // Return FALSE if logic was or, meaning no rule passed.
1511
  return $settings['logic'] == 'and';
1512
}
1513

    
1514
/**
1515
 * Create default settings for a new access plugin.
1516
 *
1517
 * @param $plugin
1518
 *   The access plugin being used.
1519
 *
1520
 * @return
1521
 *   A default configured test that should be placed in $access['plugins'];
1522
 */
1523
function ctools_access_new_test($plugin) {
1524
  $test = array(
1525
    'name' => $plugin['name'],
1526
    'settings' => array(),
1527
  );
1528

    
1529
  // Set up required context defaults.
1530
  if (isset($plugin['required context'])) {
1531
    if (is_object($plugin['required context'])) {
1532
      $test['context'] = '';
1533
    }
1534
    else {
1535
      $test['context'] = array();
1536
      foreach ($plugin['required context'] as $required) {
1537
        $test['context'][] = '';
1538
      }
1539
    }
1540
  }
1541

    
1542

    
1543
  $default = NULL;
1544
  if (isset($plugin['default'])) {
1545
    $default = $plugin['default'];
1546
  }
1547
  elseif (isset($plugin['defaults'])) {
1548
    $default = $plugin['defaults'];
1549
  }
1550

    
1551
  // Setup plugin defaults.
1552
  if (isset($default)) {
1553
    if (is_array($default)) {
1554
      $test['settings'] = $default;
1555
    }
1556
    else if (function_exists($default)) {
1557
      $test['settings'] = $default();
1558
    }
1559
    else {
1560
      $test['settings'] = array();
1561
    }
1562
  }
1563

    
1564
  return $test;
1565
}
1566

    
1567
/**
1568
 * Apply restrictions to contexts based upon the access control configured.
1569
 *
1570
 * These restrictions allow the UI to not show content that may not
1571
 * be relevant to all types of a particular context.
1572
 */
1573
function ctools_access_add_restrictions($settings, $contexts) {
1574
  if (empty($settings['plugins'])) {
1575
    return;
1576
  }
1577

    
1578
  if (!isset($settings['logic'])) {
1579
    $settings['logic'] = 'and';
1580
  }
1581

    
1582
  // We're not going to try to figure out restrictions on the or.
1583
  if ($settings['logic'] == 'or' && count($settings['plugins']) > 1) {
1584
    return;
1585
  }
1586

    
1587
  foreach ($settings['plugins'] as $test) {
1588
    $plugin = ctools_get_access_plugin($test['name']);
1589
    if ($plugin && $function = ctools_plugin_get_function($plugin, 'restrictions')) {
1590
      $required_context = isset($plugin['required context']) ? $plugin['required context'] : array();
1591
      $context = isset($test['context']) ? $test['context'] : array();
1592
      $contexts = ctools_context_select($contexts, $required_context, $context);
1593
      if ($contexts !== FALSE) {
1594
        $function($test['settings'], $contexts);
1595
      }
1596
    }
1597
  }
1598
}