Projet

Général

Profil

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

root / drupal7 / sites / all / modules / ctools / includes / context.inc @ 1e39edcb

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 (!isset($context_keywords[$context])) {
680
        $keywords['%' . $keyword] = '%' . $keyword;
681
      }
682
      else {
683
        if (empty($context_keywords[$context]) || !empty($context_keywords[$context]->empty)) {
684
          $keywords['%' . $keyword] = '';
685
        }
686
        else if (!empty($converter)) {
687
          $keywords['%' . $keyword] = ctools_context_convert_context($context_keywords[$context], $converter, $converter_options);
688
        }
689
        else {
690
          $keywords['%' . $keyword] = $context_keywords[$keyword]->title;
691
        }
692
      }
693
    }
694
  }
695
  return strtr($string, $keywords);
696
}
697

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

    
710
  return $type . '_' . $context['name'] . '_' . $context['id'];
711
}
712

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

    
730
  foreach ($objects as $object) {
731
    if (isset($object['name']) && $object['name'] == $name) {
732
      if ($object['id'] > $id) {
733
        $id = $object['id'];
734
      }
735
    }
736
  }
737

    
738
  return $id + 1;
739
}
740

    
741

    
742
// ---------------------------------------------------------------------------
743
// Functions related to contexts from arguments.
744

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

    
759
/**
760
 * Fetch metadata for all argument plugins.
761
 *
762
 * @return
763
 *   An array of arrays with information about all available argument plugins.
764
 */
765
function ctools_get_arguments() {
766
  ctools_include('plugins');
767
  return ctools_get_plugins('ctools', 'arguments');
768
}
769

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

    
797
  if ($function = ctools_plugin_load_function('ctools', 'arguments', $argument['name'], 'context')) {
798
    // Backward compatibility: Merge old style settings into new style:
799
    if (!empty($argument['settings'])) {
800
      $argument += $argument['settings'];
801
      unset($argument['settings']);
802
    }
803

    
804
    $context = $function($arg, $argument, $empty);
805

    
806
    if (is_object($context)) {
807
      $context->identifier = $argument['identifier'];
808
      $context->page_title = isset($argument['title']) ? $argument['title'] : '';
809
      $context->keyword    = $argument['keyword'];
810
      $context->id         = ctools_context_id($argument, 'argument');
811
      $context->original_argument = $arg;
812

    
813
      if (!empty($context->empty)) {
814
        $context->placeholder = array(
815
          'type' => 'argument',
816
          'conf' => $argument,
817
        );
818
      }
819
    }
820
    return $context;
821
  }
822
}
823

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

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

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

    
868
    if ((empty($context) || empty($context->data)) && !empty($argument['default']) && $argument['default'] == '404') {
869
      return FALSE;
870
    }
871
  }
872
  return TRUE;
873
}
874

    
875
// ---------------------------------------------------------------------------
876
// Functions related to contexts from relationships.
877

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

    
892
/**
893
 * Fetch metadata for all relationship plugins.
894
 *
895
 * @return
896
 *   An array of arrays with information about all available relationships.
897
 */
898
function ctools_get_relationships() {
899
  ctools_include('plugins');
900
  return ctools_get_plugins('ctools', 'relationships');
901
}
902

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

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

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

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

    
974
  return $relevant;
975
}
976

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

    
997
  foreach ($relationships as $rdata) {
998
    if (!isset($rdata['context'])) {
999
      continue;
1000
    }
1001

    
1002
    if (is_array($rdata['context'])) {
1003
      $rcontexts = array();
1004
      foreach ($rdata['context'] as $cid) {
1005
        if (empty($contexts[$cid])) {
1006
          continue 2;
1007
        }
1008
        $rcontexts[] = $contexts[$cid];
1009
      }
1010
    }
1011
    else {
1012
      if (empty($contexts[$rdata['context']])) {
1013
        continue;
1014
      }
1015
      $rcontexts = $contexts[$rdata['context']];
1016
    }
1017

    
1018
    $cid = ctools_context_id($rdata, 'relationship');
1019
    if ($context = ctools_context_get_context_from_relationship($rdata, $rcontexts)) {
1020
      $contexts[$cid] = $context;
1021
    }
1022
  }
1023
}
1024

    
1025
// ---------------------------------------------------------------------------
1026
// Functions related to loading contexts from simple context definitions.
1027

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

    
1047
    // If a new plugin was returned, return it. Otherwise fall through and
1048
    // return the original we fetched.
1049
    if ($new_plugin) {
1050
      return $new_plugin;
1051
    }
1052
  }
1053

    
1054
  return $plugin;
1055
}
1056

    
1057
/**
1058
 * Fetch metadata for all context plugins.
1059
 *
1060
 * @return
1061
 *   An array of arrays with information about all available panel contexts.
1062
 */
1063
function ctools_get_contexts() {
1064
  ctools_include('plugins');
1065
  return ctools_get_plugins('ctools', 'contexts');
1066
}
1067

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

    
1096
    if (isset($argument) && isset($plugin['placeholder name'])) {
1097
      $context[$plugin['placeholder name']] = $argument;
1098
    }
1099

    
1100
    $return = $function($type == 'requiredcontext', $context, TRUE, $plugin);
1101
    if ($return) {
1102
      $return->identifier = $context['identifier'];
1103
      $return->page_title = isset($context['title']) ? $context['title'] : '';
1104
      $return->keyword    = $context['keyword'];
1105

    
1106
      if (!empty($context->empty)) {
1107
        $context->placeholder = array(
1108
          'type' => 'context',
1109
          'conf' => $context,
1110
        );
1111
      }
1112

    
1113
      return $return;
1114
    }
1115
  }
1116
}
1117

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

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

    
1166
  foreach ($required as $r) {
1167
    $context = clone array_shift($contexts);
1168
    $context->identifier = $r['identifier'];
1169
    $context->page_title = isset($r['title']) ? $r['title'] : '';
1170
    $context->keyword    = $r['keyword'];
1171
    $return[ctools_context_id($r, 'requiredcontext')] = $context;
1172
  }
1173

    
1174
  return $return;
1175
}
1176

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

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

    
1221
    if (!empty($object->arguments) && is_array($object->arguments)) {
1222
      $contexts += ctools_context_get_placeholders_from_argument($object->arguments);
1223
    }
1224
  }
1225

    
1226
  if (!empty($object->contexts) && is_array($object->contexts)) {
1227
    $contexts += ctools_context_get_context_from_contexts($object->contexts, 'context', $placeholders);
1228
  }
1229

    
1230
  // add contexts from relationships
1231
  if (!empty($object->relationships) && is_array($object->relationships)) {
1232
    ctools_context_get_context_from_relationships($object->relationships, $contexts, $placeholders);
1233
  }
1234

    
1235
  return $contexts;
1236
}
1237

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

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

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

    
1301
    if ($new_context && empty($new_context->empty)) {
1302
      $contexts[$cid] = $new_context;
1303
    }
1304
  }
1305

    
1306
  return $contexts;
1307
}
1308

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

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

    
1330
      case 'context':
1331
        $info = $context->placeholder['conf'];
1332
        $plugin = ctools_get_context($info['name']);
1333
        break;
1334
    }
1335

    
1336
    // Ask the plugin where the form is.
1337
    if ($plugin && isset($plugin['placeholder form'])) {
1338
      if (is_array($plugin['placeholder form'])) {
1339
        $form[$cid] = $plugin['placeholder form'];
1340
      }
1341
      else if (function_exists($plugin['placeholder form'])) {
1342
        $widget = $plugin['placeholder form']($info);
1343
        if ($widget) {
1344
          $form[$cid] = $widget;
1345
        }
1346
      }
1347

    
1348
      if (!empty($form[$cid])) {
1349
        $form[$cid]['#title'] = t('@identifier (@keyword)', array('@keyword' => '%' . $context->keyword, '@identifier' => $context->identifier));
1350
      }
1351
    }
1352
  }
1353
}
1354

    
1355
// ---------------------------------------------------------------------------
1356
// Functions related to loading access control plugins
1357

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

    
1372
/**
1373
 * Fetch metadata for all access control plugins.
1374
 *
1375
 * @return
1376
 *   An array of arrays with information about all available access control plugins.
1377
 */
1378
function ctools_get_access_plugins() {
1379
  ctools_include('plugins');
1380
  return ctools_get_plugins('ctools', 'access');
1381
}
1382

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

    
1395
  $all_plugins = ctools_get_access_plugins();
1396
  $plugins = array();
1397
  foreach ($all_plugins as $id => $plugin) {
1398
    if (!empty($plugin['required context']) && !ctools_context_match_requirements($contexts, $plugin['required context'])) {
1399
      continue;
1400
    }
1401
    $plugins[$id] = $plugin;
1402
  }
1403

    
1404
  return $plugins;
1405
}
1406

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

    
1416
  return $context;
1417
}
1418

    
1419
/**
1420
 * Get a summary of an access plugin's settings.
1421
 */
1422
function ctools_access_summary($plugin, $contexts, $test) {
1423
  if (!isset($contexts['logged-in-user'])) {
1424
    $contexts['logged-in-user'] = ctools_access_get_loggedin_context();
1425
  }
1426

    
1427
  $description = '';
1428
  if ($function = ctools_plugin_get_function($plugin, 'summary')) {
1429
    $required_context = isset($plugin['required context']) ? $plugin['required context'] : array();
1430
    $context          = isset($test['context']) ? $test['context'] : array();
1431
    $description      = $function($test['settings'], ctools_context_select($contexts, $required_context, $context), $plugin);
1432
  }
1433

    
1434
  if (!empty($test['not'])) {
1435
    $description = "NOT ($description)";
1436
  }
1437

    
1438
  return $description;
1439
}
1440

    
1441
/**
1442
 * Get a summary of a group of access plugin's settings.
1443
 */
1444
function ctools_access_group_summary($access, $contexts) {
1445
  if (empty($access['plugins'])) {
1446
    return;
1447
  }
1448

    
1449
  $descriptions = array();
1450
  foreach ($access['plugins'] as $id => $test) {
1451
    $plugin = ctools_get_access_plugin($test['name']);
1452
    $descriptions[] = ctools_access_summary($plugin, $contexts, $test);
1453
  }
1454

    
1455
  $separator = (isset($access['logic']) && $access['logic'] == 'and') ? t(', and ') : t(', or ');
1456
  return implode($separator, $descriptions);
1457
}
1458

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

    
1476
  if (!isset($settings['logic'])) {
1477
    $settings['logic'] = 'and';
1478
  }
1479

    
1480
  if (!isset($contexts['logged-in-user'])) {
1481
    $contexts['logged-in-user'] = ctools_access_get_loggedin_context();
1482
  }
1483

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

    
1498
      $pass = $function($test['settings'], $test_contexts, $plugin);
1499
      if (!empty($test['not'])) {
1500
        $pass = !$pass;
1501
      }
1502
    }
1503

    
1504
    if ($pass && $settings['logic'] == 'or') {
1505
      // Pass if 'or' and this rule passed.
1506
      return TRUE;
1507
    }
1508
    else if (!$pass && $settings['logic'] == 'and') {
1509
      // Fail if 'and' and this rule failed.
1510
      return FALSE;
1511
    }
1512
  }
1513

    
1514
  // Return TRUE if logic was and, meaning all rules passed.
1515
  // Return FALSE if logic was or, meaning no rule passed.
1516
  return $settings['logic'] == 'and';
1517
}
1518

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

    
1534
  // Set up required context defaults.
1535
  if (isset($plugin['required context'])) {
1536
    if (is_object($plugin['required context'])) {
1537
      $test['context'] = '';
1538
    }
1539
    else {
1540
      $test['context'] = array();
1541
      foreach ($plugin['required context'] as $required) {
1542
        $test['context'][] = '';
1543
      }
1544
    }
1545
  }
1546

    
1547

    
1548
  $default = NULL;
1549
  if (isset($plugin['default'])) {
1550
    $default = $plugin['default'];
1551
  }
1552
  elseif (isset($plugin['defaults'])) {
1553
    $default = $plugin['defaults'];
1554
  }
1555

    
1556
  // Setup plugin defaults.
1557
  if (isset($default)) {
1558
    if (is_array($default)) {
1559
      $test['settings'] = $default;
1560
    }
1561
    else if (function_exists($default)) {
1562
      $test['settings'] = $default();
1563
    }
1564
    else {
1565
      $test['settings'] = array();
1566
    }
1567
  }
1568

    
1569
  return $test;
1570
}
1571

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

    
1583
  if (!isset($settings['logic'])) {
1584
    $settings['logic'] = 'and';
1585
  }
1586

    
1587
  // We're not going to try to figure out restrictions on the or.
1588
  if ($settings['logic'] == 'or' && count($settings['plugins']) > 1) {
1589
    return;
1590
  }
1591

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