Projet

Général

Profil

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

root / drupal7 / sites / all / modules / ds / ds.module @ a2baadd1

1
<?php
2

    
3
/**
4
 * @file
5
 * Display Suite core functions.
6
 */
7

    
8
/**
9
 * Constants for field types.
10
 */
11
define('DS_FIELD_TYPE_THEME', 1);
12
define('DS_FIELD_TYPE_FUNCTION', 2);
13
define('DS_FIELD_TYPE_PREPROCESS', 3);
14
define('DS_FIELD_TYPE_IGNORE', 4);
15
define('DS_FIELD_TYPE_CODE', 5);
16
define('DS_FIELD_TYPE_BLOCK', 6);
17
define('DS_FIELD_TYPE_CTOOLS', 7);
18

    
19
/**
20
 * Constants for block fields rendering.
21
 */
22
define('DS_BLOCK_TEMPLATE', 1);
23
define('DS_BLOCK_TITLE_CONTENT', 2);
24
define('DS_BLOCK_CONTENT', 3);
25

    
26
/**
27
 * Implements hook_permission().
28
 */
29
function ds_permission() {
30
  return array(
31
    'admin_display_suite' => array(
32
      'title' => t('Administer Display Suite'),
33
      'description' => t('General permission for Display Suite settings pages.')
34
    ),
35
  );
36
}
37

    
38
/**
39
 * Implements hook_hook_info().
40
 */
41
function ds_hook_info() {
42
  $hooks['ds_fields_info'] = array(
43
    'group' => 'ds_fields_info',
44
  );
45
  return $hooks;
46
}
47

    
48
/**
49
 * Implements hook_menu().
50
 */
51
function ds_menu() {
52
  module_load_include('inc', 'ds', 'includes/ds.registry');
53
  return _ds_menu();
54
}
55

    
56
/**
57
 * Implements hook_menu_alter().
58
 */
59
function ds_menu_alter(&$items) {
60
  module_load_include('inc', 'ds', 'includes/ds.registry');
61
  return _ds_menu_alter($items);
62
}
63

    
64
/**
65
 * Implements hook_theme().
66
 */
67
function ds_theme() {
68
  module_load_include('inc', 'ds', 'includes/ds.registry');
69
  return _ds_theme();
70
}
71

    
72
/**
73
 * Implements hook_ds_layout_info().
74
 */
75
function ds_ds_layout_info() {
76
  module_load_include('inc', 'ds', 'includes/ds.registry');
77
  return _ds_ds_layout_info();
78
}
79

    
80
/**
81
 * Implements hook_ctools_plugin_api().
82
 */
83
function ds_ctools_plugin_api($owner, $api) {
84
  if ($owner == 'ds' && ($api == 'ds' || $api == 'plugins')) {
85
    return array('version' => 1);
86
  }
87
}
88

    
89
/**
90
 * Implements hook_ctools_plugin_directory().
91
 */
92
function ds_ctools_plugin_directory($owner, $plugin_type) {
93
  if ($owner == 'ctools' && $plugin_type == 'content_types') {
94
    return 'plugins/' . $plugin_type;
95
  }
96
}
97

    
98
/**
99
 * Implements hook_views_api().
100
 */
101
function ds_views_api() {
102
  return array('api' => 3);
103
}
104

    
105
/**
106
 * Implements hook_node_type_update().
107
 */
108
function ds_node_type_update($info) {
109
  if (!empty($info->old_type) && $info->old_type != $info->type) {
110
    module_load_include('inc', 'ds', 'includes/ds.registry');
111
    _ds_entity_type_update('node', $info, 'update');
112
  }
113
}
114

    
115
/**
116
 * Implements hook_node_type_delete().
117
 */
118
function ds_node_type_delete($info) {
119
  module_load_include('inc', 'ds', 'includes/ds.registry');
120
  _ds_entity_type_update('node', $info, 'delete');
121
}
122

    
123
/**
124
 * Implements hook_theme_registry_alter().
125
 */
126
function ds_theme_registry_alter(&$theme_registry) {
127
  module_load_include('inc', 'ds', 'includes/ds.registry');
128
  _ds_theme_registry_alter($theme_registry);
129
}
130

    
131
/**
132
 * Implements hook_entity_info_alter().
133
 */
134
function ds_entity_info_alter(&$entity_info) {
135
  module_load_include('inc', 'ds', 'includes/ds.registry');
136
  _ds_entity_info_alter($entity_info);
137
}
138

    
139
/**
140
 * Implements hook_form_FORM_ID_alter().
141
 */
142
function ds_form_field_ui_display_overview_form_alter(&$form, &$form_state) {
143
  form_load_include($form_state, 'inc', 'ds', 'includes/ds.field_ui');
144
  // Also load admin on behalf of DS extras when enabled.
145
  if (module_exists('ds_extras')) {
146
    form_load_include($form_state, 'inc', 'ds_extras', 'includes/ds_extras.admin');
147
  }
148
  ds_field_ui_fields_layouts($form, $form_state);
149
}
150

    
151
/**
152
 * Implements hook_module_implements_alter().
153
 */
154
function ds_module_implements_alter(&$implementations, $hook) {
155
  // node_field_display_module_alter() disables all labels on all fields
156
  // when the view mode is 'search_index'. If you set display modes for
157
  // this view mode by hand, then the hook isn't needed. Since this
158
  // may be called hundreds of times on some pages, it's worth disabling it.
159
  // See http://drupal.org/node/834278
160
  // This code is also in Performance hacks module, but it's not bad to
161
  // disable this too in Display Suite by default.
162
  if ($hook == 'field_display_node_alter') {
163
    unset($implementations['node']);
164
  }
165
}
166

    
167
/**
168
 * Implements hook_features_api().
169
 */
170
function ds_features_api() {
171
  module_load_include('inc', 'ds', 'includes/ds.registry');
172
  return _ds_features_api();
173
}
174

    
175
/**
176
 * Function to check if we go on with Display Suite.
177
 */
178
function ds_kill_switch() {
179
  if (variable_get('ds_disable', FALSE)) {
180
    return TRUE;
181
  }
182
  return FALSE;
183
}
184

    
185
/**
186
 * Get entity view modes.
187
 *
188
 * @param $entity_type
189
 *   The name of the entity type.
190
 */
191
function ds_entity_view_modes($entity_type = NULL) {
192
  if (!empty($entity_type)) {
193
    switch ($entity_type) {
194
      // For taxonomy terms the base table and the entity type are different
195
      case 'taxonomy_term_data':
196
        $entity_info = entity_get_info('taxonomy_term');
197
        break;
198
      default:
199
        $entity_info = entity_get_info($entity_type);
200
        break;
201
    }
202
    return $entity_info['view modes'];
203
  }
204
}
205

    
206
/**
207
 * Get Display Suite layouts.
208
 */
209
function ds_get_layout_info() {
210
  static $layouts = FALSE;
211

    
212
  if (!$layouts) {
213
    $errors = array();
214

    
215
    $layouts = module_invoke_all('ds_layout_info');
216

    
217
    // Give modules a chance to alter the layouts information.
218
    drupal_alter('ds_layout_info', $layouts);
219

    
220
    // Check that there is no 'content' region, but ignore panel layouts.
221
    // Because when entities are rendered, the field items are stored into a
222
    // 'content' key so fields would be overwritten before they're all moved.
223
    foreach ($layouts as $key => $info) {
224
      if (isset($info['panels'])) {
225
        continue;
226
      }
227
      if (isset($info['regions']['content'])) {
228
        $errors[] = $key;
229
      }
230
    }
231
    if (!empty($errors)) {
232
      drupal_set_message(t('Following layouts have a "content" region key which is invalid: %layouts.', array('%layouts' => implode(', ', $errors))), 'error');
233
    }
234
  }
235

    
236
  return $layouts;
237
}
238

    
239
/**
240
 * Get a layout for a given entity.
241
 *
242
 * @param $entity_type
243
 *   The name of the entity.
244
 * @param $bundle
245
 *   The name of the bundle.
246
 * @param $view_mode
247
 *   The name of the view mode.
248
 * @param $fallback
249
 *   Whether to fallback to default or not.
250
 *
251
 * @return $layout
252
 *   Array of layout variables for the regions.
253
 */
254
function ds_get_layout($entity_type, $bundle, $view_mode, $fallback = TRUE) {
255

    
256
  static $layouts = array();
257
  $layout_key = $entity_type . '_' . $bundle . '_' . $view_mode;
258

    
259
  if (!isset($layouts[$layout_key])) {
260

    
261
    $entity_info = entity_get_info();
262

    
263
    $overridden = TRUE;
264
    if ($view_mode != 'form') {
265
      $view_mode_settings = field_view_mode_settings($entity_type, $bundle);
266
      $overridden = (!empty($view_mode_settings[$view_mode]['custom_settings']) ? TRUE : FALSE);
267
    }
268
    // Check if a layout is configured.
269
    if (isset($entity_info[$entity_type]['bundles'][$bundle]['layouts'][$view_mode]) && ($overridden || $view_mode == 'default')) {
270
      $layouts[$layout_key] = $entity_info[$entity_type]['bundles'][$bundle]['layouts'][$view_mode];
271
      $layouts[$layout_key]['view_mode'] = $view_mode;
272
    }
273

    
274
    // In case $view_mode is not found, check if we have a default layout,
275
    // but only if the view mode settings aren't overridden for this view mode.
276
    if ($view_mode != 'default' && !$overridden && $fallback && isset($entity_info[$entity_type]['bundles'][$bundle]['layouts']['default'])) {
277
      $layouts[$layout_key] = $entity_info[$entity_type]['bundles'][$bundle]['layouts']['default'];
278
      $layouts[$layout_key]['view_mode'] = 'default';
279
    }
280

    
281
    // Register the false return value as well.
282
    if (!isset($layouts[$layout_key])) {
283
      $layouts[$layout_key] = FALSE;
284
    }
285
  }
286

    
287
  return $layouts[$layout_key];
288
}
289

    
290
/**
291
 * Get all fields.
292
 *
293
 * @param $entity_type
294
 *   The name of the entity.
295
 * @param $cache
296
 *   Whether we need to get the fields from cache or not.
297
 * @return
298
 *   Collection of fields.
299
 */
300
function ds_get_fields($entity_type, $cache = TRUE) {
301
  global $language;
302

    
303
  static $static_fields, $fields_cached = array();
304
  static $loaded = FALSE;
305

    
306
  // Get fields from cache.
307
  if (!$loaded) {
308
    $loaded = TRUE;
309
    if ($cache && $cached_fields = cache_get('ds_fields:' . $language->language)) {
310
      $fields_cached = $static_fields = $cached_fields->data;
311
    }
312
  }
313

    
314
  if (!isset($static_fields[$entity_type])) {
315

    
316
    // Do we have them cached or not ?
317
    if (!isset($fields_cached[$entity_type])) {
318

    
319
      // Get all fields for this entity type.
320
      $fields = array();
321
      foreach (module_implements('ds_fields_info') as $module) {
322
        $function = $module . '_ds_fields_info';
323
        $all_fields = $function($entity_type);
324
        if (!empty($all_fields)) {
325
          foreach ($all_fields as $key => $field_results) {
326
            if ($key === $entity_type) {
327
              // Add module key to field definition.
328
              foreach ($field_results as $f => $d) {
329
                $field_results[$f]['module'] = $module;
330
              }
331
              $fields = array_merge($field_results, $fields);
332
            }
333
          }
334
        }
335
      }
336

    
337
      // Give modules a change to alter fields.
338
      drupal_alter('ds_fields_info', $fields, $entity_type);
339

    
340
      $fields_cached[$entity_type] = $fields;
341

    
342
      // Cache the fields.
343
      if ($cache) {
344
        cache_set('ds_fields:' . $language->language, $fields_cached, 'cache');
345
      }
346
    }
347
    else {
348
      $fields = $fields_cached[$entity_type];
349
    }
350

    
351
    // Store the fields statically.
352
    $static_fields[$entity_type] = $fields;
353
  }
354

    
355
  return isset($static_fields[$entity_type]) ? $static_fields[$entity_type] : array();
356
}
357

    
358
/**
359
 * Get the field settings.
360
 *
361
 * @param $entity_type
362
 *   The name of the entity.
363
 * @param $bundle
364
 *   The name of bundle (ie, page or story for node types, profile for users)
365
 * @param $view_mode
366
 *   The name of view mode.
367
 */
368
function ds_get_field_settings($entity_type, $bundle, $view_mode, $default = TRUE) {
369
  static $field_settings = NULL;
370

    
371
  if (!isset($field_settings)) {
372
    if ($cache = cache_get('ds_field_settings')) {
373
      $field_settings = $cache->data;
374
    }
375
    else {
376
      ctools_include('export');
377
      $ds_field_settings = ctools_export_crud_load_all('ds_field_settings');
378
      foreach ($ds_field_settings as $layout => $layout_settings) {
379
        // Do not store configuration when the field settings is disabled.
380
        if (!empty($layout_settings->disabled)) {
381
          continue;
382
        }
383
        // Do not store configuration if settings key is not set.
384
        if (!isset($layout_settings->settings)) {
385
          continue;
386
        }
387
        foreach ($layout_settings->settings as $field => $settings) {
388
          $field_settings[$layout_settings->entity_type][$layout_settings->bundle][$layout_settings->view_mode][$field] = $settings;
389
        }
390
      }
391
      cache_set('ds_field_settings', $field_settings, 'cache');
392
    }
393
  }
394

    
395
  return (isset($field_settings[$entity_type][$bundle][$view_mode])) ? $field_settings[$entity_type][$bundle][$view_mode] : (isset($field_settings[$entity_type][$bundle]['default']) && $default ? $field_settings[$entity_type][$bundle]['default'] : array());
396
}
397

    
398
/**
399
 * Get the value for a Display Suite field.
400
 *
401
 * @param $key
402
 *   The key of the field.
403
 * @param $field
404
 *   The configuration of a DS field.
405
 * @param $entity
406
 *   The current entity.
407
 * @param $entity_type
408
 *   The name of the entity.
409
 * @param $bundle
410
 *   The name of the bundle.
411
 * @param $view_mode
412
 *   The name of the view mode.
413
 * @param $build
414
 *   The current built of the entity.
415
 * @return $markup
416
 *   The markup of the field used for output.
417
 */
418
function ds_get_field_value($key, $field, $entity, $entity_type, $bundle, $view_mode, $build = array()) {
419

    
420
  $field['field_name'] = $key;
421
  $field['entity'] = $entity;
422
  $field['entity_type'] = $entity_type;
423
  $field['bundle'] = $bundle;
424
  $field['view_mode'] = $view_mode;
425
  $field['build'] = $build;
426

    
427
  // Special case for ds_views which can handle custom fields now.
428
  if ($field['field_type'] != DS_FIELD_TYPE_PREPROCESS && $entity_type == 'ds_views') {
429
    $entity->preprocess_fields[] = $key;
430
  }
431

    
432
  switch ($field['field_type']) {
433

    
434
    case DS_FIELD_TYPE_PREPROCESS:
435
      $entity->preprocess_fields[] = $key;
436
      break;
437

    
438
    case DS_FIELD_TYPE_FUNCTION:
439
      if (isset($field['file'])) {
440
        include_once $field['file'];
441
      }
442
      return $field['function']($field);
443

    
444
    case DS_FIELD_TYPE_THEME:
445
      $format = (isset($field['formatter'])) ? $field['formatter'] : key($field['properties']['formatters']);
446
      return theme($format, $field);
447

    
448
    case DS_FIELD_TYPE_CODE:
449
      return ds_render_code_field($field);
450

    
451
    case DS_FIELD_TYPE_CTOOLS:
452
      return ds_render_ctools_field($field);
453

    
454
    case DS_FIELD_TYPE_BLOCK:
455
      return ds_render_block_field($field);
456
  }
457
}
458

    
459
/**
460
 * Implements hook_field_attach_view_alter().
461
 */
462
function ds_field_attach_view_alter(&$build, $context) {
463
  static $loaded_css = array();
464

    
465
  // Global kill switch. In some edge cases, a view might
466
  // be inserted into the view of an entity, in which the
467
  // same entity is available as well. This is simply not
468
  // possible, so you can temporarily disable DS completely
469
  // by setting this variable, either from code or via
470
  // the UI through admin/structure/ds/
471
  if (ds_kill_switch()) {
472
    return;
473
  }
474

    
475
  // If views and core doesn't send information along on the entity,
476
  // Display Suite doesn't have a context to render the fields.
477
  if (!isset($build['#entity_type']) && !isset($build['#bundle'])) {
478
    return;
479
  }
480

    
481
  // If no layout is configured, stop as well.
482
  if (!ds_get_layout($build['#entity_type'], $build['#bundle'], $context['view_mode'])) {
483
    return;
484
  }
485

    
486
  $entity_type = $build['#entity_type'];
487
  $bundle = $build['#bundle'];
488
  $view_mode = $context['view_mode'];
489
  $entity = $context['entity'];
490
  $layout = ds_get_layout($entity_type, $bundle, $view_mode);
491

    
492
  // Check on field/delta limit.
493
  if (isset($layout['settings']['limit'])) {
494
    foreach ($layout['settings']['limit'] as $field => $limit) {
495
      if (isset($build[$field])) {
496
        if ($limit === 'delta' && isset($entity->ds_delta) && isset($entity->ds_delta[$field])) {
497
          $delta = $entity->ds_delta[$field];
498
          foreach ($build[$field]['#items'] as $key => $item) {
499
            if ($key != $delta) {
500
              unset($build[$field][$key]);
501
            }
502
          }
503
        }
504
        else {
505
          $count = count($build[$field]['#items']);
506
          if ($count > $limit) {
507
            $build[$field]['#items'] = array_slice($build[$field]['#items'], 0, $limit);
508
          }
509
        }
510
      }
511
    }
512
  }
513

    
514
  // Add Display Suite display fields.
515
  $fields = ds_get_fields($entity_type);
516
  $field_values = ds_get_field_settings($entity_type, $bundle, $layout['view_mode']);
517

    
518
  foreach ($field_values as $key => $field) {
519

    
520
    // Ignore if this field is not a DS field.
521
    if (!isset($fields[$key])) {
522
      continue;
523
    }
524

    
525
    $field = $fields[$key];
526
    if (isset($field_values[$key]['format'])) {
527
      $field['formatter'] = $field_values[$key]['format'];
528
    }
529

    
530
    if (isset($field_values[$key]['formatter_settings'])) {
531
      $field['formatter_settings'] = $field_values[$key]['formatter_settings'];
532
    }
533
    $field_value = ds_get_field_value($key, $field, $entity, $entity_type, $bundle, $view_mode, $build);
534

    
535
    // Title label.
536
    if ($key == 'title' && $entity_type == 'node') {
537
      $node_type = node_type_get_type($entity);
538
      $field['title'] = function_exists('i18n_node_translate_type') ? i18n_node_translate_type($node_type->type, 'title_label', $node_type->title_label) : $node_type->title_label;
539
    }
540

    
541
    if (!empty($field_value) || (string) $field_value === '0') {
542

    
543
      // Special case for views.
544
      if (!empty($build['render_code_fields'])) {
545
        $build[$key] = $field_value;
546
      }
547
      else {
548
        $build[$key] = array(
549
          '#theme' => 'field',
550
          '#field_type' => 'ds',
551
          '#skip_edit' => TRUE,
552
          '#title' => $field['title'],
553
          '#weight' => isset($field_values[$key]['weight']) ? $field_values[$key]['weight'] : 0,
554
          '#label_display' => isset($field_values[$key]['label']) ? $field_values[$key]['label'] : 'inline',
555
          '#field_name' => $key,
556
          '#bundle' => $bundle,
557
          '#object' => $entity,
558
          '#entity_type' => $entity_type,
559
          '#view_mode' => $view_mode,
560
          '#access' => (variable_get('ds_extras_field_permissions', FALSE) && function_exists('ds_extras_ds_field_access')) ? ds_extras_ds_field_access($key, $entity_type) : TRUE,
561
          '#items' => array(
562
            0 => array(
563
              'value' => $field_value,
564
            ),
565
          ),
566
          0 => array(
567
            '#markup' => $field_value,
568
          ),
569
        );
570
      }
571
    }
572
  }
573

    
574
  // Add path to css file for this layout and disable block regions if necessary.
575
  if (isset($layout['css']) && !isset($loaded_css[$layout['path'] . '/' . $layout['layout'] . '.css'])) {
576
    // Register css file.
577
    $loaded_css[$layout['path'] . '/' . $layout['layout'] . '.css'] = TRUE;
578
    // Add css file.
579
    if (isset($layout['module']) && $layout['module'] == 'panels') {
580
      $build['#attached']['css'][] = $layout['path'] . '/' . $layout['panels']['css'];
581
    }
582
    else {
583
      $build['#attached']['css'][] = $layout['path'] . '/' . $layout['layout'] . '.css';
584
    }
585
  }
586
}
587

    
588
/**
589
 * Add variables to an entity.
590
 *
591
 * This function is added in ds_theme_registry_alter().
592
 */
593
function ds_entity_variables(&$vars) {
594
  if (isset($vars['elements']) && isset($vars['elements']['#bundle']) && $layout = ds_get_layout($vars['elements']['#entity_type'], $vars['elements']['#bundle'], $vars['elements']['#view_mode'])) {
595

    
596
    $render_container = 'content';
597
    // User uses user_profile as container.
598
    if ($vars['elements']['#entity_type'] == 'user') {
599
      $render_container = 'user_profile';
600
    }
601

    
602
    // Move any preprocess fields to render container.
603
    // Inconsitency in taxonomy term naming.
604
    $object = $vars['elements']['#entity_type'];
605
    if ($vars['elements']['#entity_type'] == 'taxonomy_term') {
606
      $object = 'term';
607
    }
608
    if (isset($vars[$object]->preprocess_fields)) {
609
      foreach ($vars[$object]->preprocess_fields as $field) {
610

    
611
        // Process RDF if the module is enabled before moving preprocess fields.
612
        if (module_exists('rdf')) {
613
          rdf_process($vars, $field);
614
          // Remove it so we can unset the field later on.
615
          unset($vars['rdf_template_variable_attributes_array'][$field]);
616
        }
617

    
618
        // Move the field to content so it renders, remove it
619
        // because we don't need it anymore.
620
        if (isset($vars[$field])) {
621
          $vars[$render_container][$field] = array('#markup' => $vars[$field]);
622
          if (!isset($vars['preprocess_keep'])) {
623
            unset($vars[$field]);
624
          }
625
        }
626
      }
627
    }
628

    
629
    // Check if this is a flexible panels layout.
630
    if (!empty($layout['flexible'])) {
631
      ctools_include('plugins', 'panels');
632
      $vars['css_id'] = $vars['settings'] = $vars['display'] =  $vars['renderer'] = '';
633
      $vars['layout'] = panels_get_layout($layout['panels']['name']);
634
      $vars['theme_hook_suggestion'] = 'panels_flexible';
635
    }
636
    else {
637
      // Template layout.
638
      if (!isset($vars['classes_array'])) {
639
        $vars['classes_array'] = array();
640
      }
641

    
642
      // Add view-mode-{name} to classes.
643
      if (!in_array('view-mode-' . $vars['elements']['#view_mode'], $vars['classes_array'])) {
644
        $vars['classes_array'][] = 'view-mode-' . $vars['elements']['#view_mode'];
645
      }
646

    
647
      // In case this is a panels layout, use panels info array.
648
      if (isset($layout['module']) && $layout['module'] == 'panels') {
649
        $layout['layout'] = $layout['panels']['theme'];
650
      }
651

    
652
      $vars['theme_hook_suggestions'][] = $layout['layout'];
653
      $vars['theme_hook_suggestions'][] = $layout['layout'] . '__' . $vars['elements']['#entity_type'];
654
      $vars['theme_hook_suggestions'][] = $layout['layout'] . '__' . $vars['elements']['#entity_type'] . '_' . $vars['elements']['#view_mode'];
655
      $vars['theme_hook_suggestions'][] = $layout['layout'] . '__' . $vars['elements']['#entity_type'] . '_' . $vars['elements']['#bundle'];
656
      $vars['theme_hook_suggestions'][] = $layout['layout'] . '__' . $vars['elements']['#entity_type'] . '_' . $vars['elements']['#bundle'] . '_' . $vars['elements']['#view_mode'];
657
    }
658

    
659
    // If the layout has wrapper class lets add it.
660
    if (isset($layout['settings']['classes']['layout_class'])) {
661
      foreach ($layout['settings']['classes']['layout_class'] as $layout_class) {
662
        $vars['classes_array'][] = $layout_class;
663
      }
664
    }
665

    
666
    // Create region variables based on the layout settings.
667
    foreach ($layout['regions'] as $region_name => $region) {
668

    
669
      // Create the region content.
670
      $layout_render_array[$region_name] = array();
671
      if (isset($layout['settings']['regions'][$region_name])) {
672
        foreach ($layout['settings']['regions'][$region_name] as $key => $field) {
673
          // Make sure the field exists.
674
          if (!isset($vars[$render_container][$field])) {
675
            continue;
676
          }
677
          if (!isset($vars[$render_container][$field]['#weight'])) {
678
            $vars[$render_container][$field]['#weight'] = $key;
679
          }
680
          $layout_render_array[$region_name][$key] = $vars[$render_container][$field];
681
        }
682
      }
683

    
684
      // Add extras classes to the region.
685
      if (empty($layout['flexible'])) {
686
        $vars[$region_name . '_classes'] = !empty($layout['settings']['classes'][$region_name]) ? ' ' . implode(' ', $layout['settings']['classes'][$region_name]) : '';
687
      }
688
      // Add a wrapper to the region.
689
      if (empty($layout['flexible'])) {
690
        $vars[$region_name . '_wrapper'] = isset($layout['settings']['wrappers'][$region_name]) ? $layout['settings']['wrappers'][$region_name] : 'div';
691
      }
692
    }
693

    
694
    // Let other modules know we have rendered.
695
    $vars['rendered_by_ds'] = TRUE;
696

    
697
    // Add a layout wrapper.
698
    $vars['layout_wrapper'] = isset($layout['settings']['layout_wrapper']) ? $layout['settings']['layout_wrapper'] : 'div';
699

    
700
    // Add layout attributes if any.
701
    $vars['layout_attributes'] = '';
702
    if (!empty($layout['settings']['layout_attributes'])) {
703
      $vars['layout_attributes'] .= ' ' . $layout['settings']['layout_attributes'];
704
    }
705
    // Merge in other attributes which were passed to the template.
706
    if (!empty($layout['settings']['layout_attributes_merge'])) {
707
      // Handle classes separately.
708
      if (isset($vars['attributes_array']['class'])) {
709
        $vars['classes_array'] += $vars['attributes_array']['class'];
710
        unset($vars['attributes_array']['class']);
711
      }
712
      $vars['layout_attributes'] .= ' ' . drupal_attributes($vars['attributes_array']);
713
    }
714

    
715
    // Add an onclick attribute on the wrapper.
716
    if (!empty($layout['settings']['layout_link_attribute'])) {
717
      $url = '';
718
      switch ($layout['settings']['layout_link_attribute']) {
719
        case 'content':
720
          $uri = entity_uri($vars['elements']['#entity_type'], $vars[$object]);
721
          if (!empty($uri)) {
722
            $url = $uri['path'];
723
          }
724
          break;
725
        case 'custom':
726
          $url = $layout['settings']['layout_link_custom'];
727
          break;
728
        case 'tokens':
729
          $url = token_replace($layout['settings']['layout_link_custom'], array($vars['elements']['#entity_type'] => $vars[$object]));
730
          break;
731
      }
732

    
733
      if (!empty($url)) {
734
        $vars['layout_attributes'] .= ' onclick="location.href=\'' . url($url) . '\'"';
735
      }
736
    }
737

    
738
    // Let other modules alter the ds array before creating the region variables.
739
    $context = array('entity' => isset($vars[$object]) ? $vars[$object] : (isset($vars['elements']['#' . $object]) ? $vars['elements']['#' . $object] : ''), 'entity_type' => $vars['elements']['#entity_type'], 'bundle' => $vars['elements']['#bundle'], 'view_mode' => $vars['elements']['#view_mode']);
740
    drupal_alter('ds_pre_render', $layout_render_array, $context);
741
    foreach ($layout_render_array as $region_name => $content) {
742
      // In case this is a panels layout, add the region to the $content variable.
743
      if (isset($layout['module']) && $layout['module'] == 'panels') {
744
        $vars['content'][$region_name] = drupal_render($content);
745
      }
746
      else {
747
        $vars[$region_name] = drupal_render($content);
748
      }
749
    }
750
  }
751
}
752

    
753
/**
754
 * Create entity context.
755
 */
756
function ds_create_entity_context($entity_type, $entity, &$contexts, $context_arguments = array()) {
757
  ctools_include('context');
758
  if (empty($context_arguments)) {
759
    $context_arguments = array(array(
760
      'keyword' => $entity_type,
761
      'identifier' => drupal_ucfirst($entity_type) . ' being viewed',
762
      'id' => 1,
763
      'name' => 'entity_id:' . $entity_type,
764
      'settings' => array(),
765
    ));
766
  }
767
  ctools_context_get_context_from_arguments($context_arguments, $contexts, array($entity));
768
}
769

    
770
/**
771
 * Render a code field.
772
 */
773
function ds_render_code_field($field) {
774
  if (isset($field['properties']['code'])) {
775
    $format = (isset($field['properties']['code']['format'])) ? $field['properties']['code']['format'] : 'plain_text';
776
    if ($format == 'ds_code' && module_exists('ds_format')) {
777
      $value = ds_format_php_eval($field['properties']['code']['value'], $field['entity'], isset($field['build']) ? $field['build'] : array());
778
    }
779
    else {
780
      $value = check_markup($field['properties']['code']['value'], $format);
781
    }
782
    // Token support - check on token property so we don't run every single field through token.
783
    if (isset($field['properties']['use_token']) && $field['properties']['use_token'] == TRUE) {
784
      $value = token_replace($value, array($field['entity_type'] => $field['entity']), array('clear' => TRUE));
785
    }
786
    return $value;
787
  }
788
}
789

    
790
/**
791
 * Render a CTools field.
792
 */
793
function ds_render_ctools_field($field) {
794
  if (isset($field['formatter_settings']['ctools'])) {
795

    
796
    // Extreme use case where a taxonomy_term object is not
797
    // loaded on the entity and triggers notices if a view is embedded
798
    // with taxonomy term fields from the same object.
799
    // see http://drupal.org/node/1238132 - To reproduce:
800
    // 1) add 2 taxonomy field instances on a bundle
801
    // 2) configure a ds layout showing only one
802
    // 3) embed a view with the 2 taxonomies as fields.
803
    if (isset($field['formatter_settings']['load_terms']) && $field['formatter_settings']['load_terms']) {
804
      static $terms_loaded = array();
805
      $language = $field['entity']->language;
806
      $instances = field_info_instances($field['entity_type'], $field['bundle']);
807
      foreach ($instances as $key => $instance) {
808
        $info = field_info_field($key);
809
        if ($info['module'] == 'taxonomy') {
810
          if (empty($field['entity']->{$key})) {
811
            continue;
812
          }
813
          if (!isset($field['entity']->{$key}[$language])) {
814
            $language = LANGUAGE_NONE;
815
          }
816
          foreach ($field['entity']->{$key}[$language] as $tkey => $item) {
817
            if (isset($item['tid']) && !isset($item['taxonomy_term'])) {
818
              if (!isset($terms_loaded[$item['tid']])) {
819
                $terms_loaded[$item['tid']] = taxonomy_term_load($item['tid']);
820
              }
821
              $field['entity']->{$key}[$language][$tkey]['taxonomy_term'] = $terms_loaded[$item['tid']];
822
            }
823
          }
824
        }
825
      }
826
    }
827

    
828
    ctools_include('content');
829
    ctools_include('context');
830

    
831
    // Get variables.
832
    $show_title = $field['formatter_settings']['show_title'];
833
    $title_wrapper = trim($field['formatter_settings']['title_wrapper']);
834
    $ctools = unserialize($field['formatter_settings']['ctools']);
835
    $type = $ctools['type'];
836
    $subtype = $ctools['subtype'];
837
    $conf = $ctools['conf'];
838
    $entity_type = $field['entity_type'];
839
    $keywords = $arguments = $contexts = array();
840

    
841
    // Create entity context.
842
    ds_create_entity_context($entity_type, $field['entity'], $contexts);
843

    
844
    // Build the content.
845
    $data = ctools_content_render($type, $subtype, $conf, $keywords, $arguments, $contexts);
846
    // Return content.
847
    if (!empty($data->content)) {
848
      $content = '';
849
      if ($show_title) {
850
        if (empty($title_wrapper)) $title_wrapper = 'div';
851
        $content .= '<' . check_plain($title_wrapper) . '>' . $data->title . '</' . check_plain($title_wrapper) . '>';
852
      }
853
      if (is_array($data->content)) {
854
        $content .= drupal_render($data->content);
855
      }
856
      else {
857
        $content .= $data->content;
858
      }
859
      return $content;
860
    }
861
  }
862
}
863

    
864
/**
865
 * Render a block field.
866
 */
867
function ds_render_block_field($field) {
868
  // Invoke the block_view hook of the module.
869
  list($module, $delta) = explode('|', $field['properties']['block']);
870
  $block = module_invoke($module, 'block_view', $delta);
871

    
872
  // Get contextual links.
873
  $contextual_links = array();
874
  $contextual = module_exists('contextual') && user_access('access contextual links');
875
  if ($contextual) {
876
    if (is_array($block['content']) && isset($block['content']['#contextual_links'])) {
877
      $contextual_links = $block['content']['#contextual_links'];
878
    }
879
  }
880

    
881
  // Render the block content.
882
  if (isset($block['content']) && is_array($block['content'])) {
883
    $block['content'] = drupal_render($block['content']);
884
  }
885

    
886
  // Go through in case we have actual content.
887
  if (!empty($block['content'])) {
888

    
889
    // Make sure subject is set.
890
    if (!isset($block['subject'])) {
891
      $block['subject'] = '';
892
    }
893

    
894
    global $theme_key;
895
    $full_block = db_query("SELECT * FROM {block} WHERE module = :module AND delta = :delta AND theme = :theme", array(':module' => $module, ':delta' => $delta, ':theme' => $theme_key))->fetchObject();
896
    if (!empty($full_block)) {
897
      if ($full_block->title == '<none>') {
898
        $block['subject'] = '';
899
      }
900
      elseif (!empty($full_block->title)) {
901
        $block['subject'] = $full_block->title;
902
      }
903
    }
904

    
905
    // i18n support.
906
    if (function_exists('i18n_block_block_view_alter')) {
907

    
908
      // Check language visibility.
909
      global $language;
910
      static $block_languages = FALSE;
911
      if (!$block_languages) {
912
        $block_languages = array();
913
        $result = db_query('SELECT module, delta, language FROM {i18n_block_language}');
914
        foreach ($result as $record) {
915
          $block_languages[$record->module][$record->delta][$record->language] = TRUE;
916
        }
917
      }
918
      if (isset($block_languages[$module][$delta]) && !isset($block_languages[$module][$delta][$language->language])) {
919
        return;
920
      }
921

    
922
      // Translate.
923
      if (!empty($full_block->i18n_mode)) {
924
        i18n_block_block_view_alter($block, $full_block);
925
        if (!empty($block['title'])) {
926
          $block['subject'] = $block['title'];
927
        }
928
      }
929
    }
930

    
931
    $block = (object) $block;
932
    switch ($field['properties']['block_render']) {
933
      case DS_BLOCK_TEMPLATE:
934
        $block->region = NULL;
935
        $block->module = $module;
936
        $block->delta = $delta;
937
        $elements = array('elements' => array('#block' => $block, '#children' => $block->content));
938
        // Add contextual links.
939
        if ($contextual) {
940
          $elements['elements'] += array('#contextual_links' => array_merge($contextual_links, array('block' => array('admin/structure/block/manage', array($block->module, $block->delta)))));
941
        }
942
        return theme('block', $elements);
943
        break;
944
      case DS_BLOCK_TITLE_CONTENT:
945
        return '<h2 class="block-title">' . $block->subject . '</h2>' . $block->content;
946
        break;
947
      case DS_BLOCK_CONTENT:
948
        return $block->content;
949
        break;
950
    }
951
  }
952
}
953

    
954
/**
955
 * Render a field.
956
 */
957
function ds_render_field($field) {
958

    
959
  $title_field = FALSE;
960

    
961
  $output = '';
962
  $settings = isset($field['formatter_settings']) ? $field['formatter_settings'] : array();
963
  $settings += $field['properties']['default'];
964

    
965
  // Basic string.
966
  if (isset($settings['link text'])) {
967
    $output = t($settings['link text']);
968
  }
969
  elseif (isset($field['properties']['entity_render_key']) && isset($field['entity']->{$field['properties']['entity_render_key']})) {
970
    if ($field['entity_type'] == 'user' && $field['properties']['entity_render_key'] == 'name') {
971
      $output = format_username($field['entity']);
972
    }
973
    else {
974
      $title_field = $field['properties']['entity_render_key'] == 'title' && $field['entity_type'] == 'node';
975
      $output = $field['entity']->{$field['properties']['entity_render_key']};
976
    }
977
  }
978

    
979
  if (empty($output)) {
980
    return;
981
  }
982

    
983
  // Link.
984
  if ($settings['link']) {
985
    if (isset($field['entity']->uri['path'])) {
986
      $path = $field['entity']->uri['path'];
987
    }
988
    else {
989
      $uri_info = entity_uri($field['entity_type'], $field['entity']);
990
      $path = $uri_info['path'];
991
    }
992
    $output = l($output, $path);
993
    if ($title_field) {
994
      $output = ds_edit_support('title', $output, $field);
995
    }
996
  }
997
  else {
998
    $output = check_plain($output);
999
    if ($title_field) {
1000
      $output = ds_edit_support('title', $output, $field);
1001
    }
1002
  }
1003

    
1004
  // Wrapper and class.
1005
  if (!empty($settings['wrapper'])) {
1006
    $wrapper = check_plain($settings['wrapper']);
1007
    $class = (!empty($settings['class'])) ? ' class="' . check_plain($settings['class']) . '"' : '';
1008
    $output = '<' . $wrapper . $class . '>' . $output . '</' . $wrapper . '>';
1009
  }
1010

    
1011
  return $output;
1012
}
1013

    
1014
/**
1015
 * Support for edit module.
1016
 *
1017
 * @param $field_name
1018
 *   The name of the field.
1019
 * @param $output
1020
 *   The output of the field.
1021
 * @param $field
1022
 *   The complete field array.
1023
 *
1024
 * @return
1025
 *   The field ready for edit module or the same value in case
1026
 *   the edit module is not enabled.
1027
 */
1028
function ds_edit_support($field_name, $output, $field) {
1029

    
1030
  if (module_exists('edit')) {
1031
    $edit_id = "node/" . $field['entity']->nid . "/" . $field_name . "/" . $field['entity']->language . "/" . $field['view_mode'];
1032
    $output = edit_wrap_pseudofield($output, $edit_id);
1033
  }
1034

    
1035
  return $output;
1036
}
1037

    
1038
/**
1039
 * Render an author field.
1040
 */
1041
function ds_render_author_field($field) {
1042

    
1043
  // Users without a user name are anonymous users. These are never linked.
1044
  if (empty($field['entity']->name)) {
1045
    $output = check_plain(variable_get('anonymous', t('Anonymous')));
1046
  }
1047

    
1048
  if ($field['formatter'] == 'author') {
1049
    $output = format_username($field['entity']);
1050
  }
1051

    
1052
  if ($field['formatter'] == 'author_linked') {
1053
    $output = theme('username', array('account' => $field['entity']));
1054
  }
1055

    
1056
  return ds_edit_support('author', $output, $field);
1057
}
1058

    
1059
/**
1060
 * Render a markup field.
1061
 */
1062
function ds_render_markup($field) {
1063
  if (isset($field['entity']->{$field['properties']['key']})) {
1064
    // Check for format, and let's take filtered_html as a sane default.
1065
    $format = isset($field['entity']->{$field['properties']['format']}) ? $field['entity']->{$field['properties']['format']} : 'filtered_html';
1066
    return check_markup($field['entity']->{$field['properties']['key']}, $format, '', TRUE);;
1067
  }
1068
}
1069

    
1070
/**
1071
 * Return the picture.
1072
 */
1073
function ds_return_picture($entity) {
1074

    
1075
  // Gravatar support.
1076
  if (module_exists('gravatar')) {
1077
    $entity = _gravatar_load_account($entity);
1078
    $entity->picture = _gravatar_get_account_user_picture($entity);
1079
  }
1080

    
1081
  if (!empty($entity->picture)) {
1082
    if (is_numeric($entity->picture)) {
1083
      return file_load($entity->picture);
1084
    }
1085
    else {
1086
      return $entity->picture;
1087
    }
1088
  }
1089
  elseif (variable_get('user_picture_default', '')) {
1090
    return variable_get('user_picture_default', '');
1091
  }
1092
}
1093

    
1094
/**
1095
 * Render a user picture.
1096
 */
1097
function ds_render_user_picture($field) {
1098
  $picture = ds_return_picture($field['entity']);
1099

    
1100
  if (!empty($picture)) {
1101
    $vars = array();
1102
    $filepath = (isset($picture->uri)) ? $picture->uri : $picture;
1103
    $name = !empty($field['entity']->name) ? $field['entity']->name : variable_get('anonymous', t('Anonymous'));
1104
    $alt = t("@user's picture", array('@user' => $name));
1105
    $vars = array('path' => $filepath, 'alt' => $alt, 'title' => $alt);
1106

    
1107
    // If the image does not have a valid Drupal scheme (for eg. HTTP),
1108
    // don't load image styles.
1109
    if (module_exists('image') && file_valid_uri($filepath)) {
1110
      $vars['style_name'] = str_replace('ds_picture_', '', $field['formatter']);
1111
      $image = theme('image_style', $vars);
1112
    }
1113
    else {
1114
      $image = theme('image', $vars);
1115
    }
1116

    
1117
    if (!empty($field['entity']->uid) && user_access('access user profiles')) {
1118
      return l($image, 'user/' . $field['entity']->uid, array('html' => TRUE));
1119
    }
1120
    else {
1121
      return $image;
1122
    }
1123
  }
1124
}
1125

    
1126
/**
1127
 * Render a date field.
1128
 */
1129
function ds_render_date_field($field) {
1130
  $date_format = str_replace('ds_post_date_', '', $field['formatter']);
1131
  return ds_edit_support($field['properties']['entity_render_key'], format_date($field['entity']->{$field['properties']['entity_render_key']}, $date_format), $field);
1132
}
1133

    
1134
/**
1135
 * Render a "Submitted by"-line.
1136
 */
1137
function ds_render_submitted_by($field) {
1138
  $account = user_load($field['entity']->uid);
1139
  switch ($field['formatter']) {
1140
    case 'ds_time_ago':
1141
      $interval = REQUEST_TIME - $field['entity']->created;
1142
      return t('Submitted !interval ago by !user.', array('!interval' => format_interval($interval), '!user' => theme('username', array('account' => $account))));
1143
    default:
1144
      $date_format = str_replace('ds_post_date_', '', $field['formatter']);
1145
      return t('Submitted by !user on !date.', array('!user' => theme('username', array('account' => $account)), '!date' => format_date($field['entity']->created, $date_format)));
1146
  }
1147
}
1148

    
1149
/**
1150
 * Implements hook_field_formatter_info().
1151
 */
1152
function ds_field_formatter_info() {
1153

    
1154
  $formatters = array();
1155
  if (module_exists('taxonomy')) {
1156
    $formatters['ds_taxonomy_view_mode'] = array(
1157
      'label'       => t('Rendered taxonomy term'),
1158
      'description' => t('Display the referenced term in a specific view mode'),
1159
      'field types' => array('taxonomy_term_reference'),
1160
      'settings'    => array('taxonomy_term_reference_view_mode' => 'full'),
1161
    );
1162
    $formatters['ds_taxonomy_separator'] = array(
1163
      'label'       => t('Separated'),
1164
      'description' => t('Display the referenced term with a separator.'),
1165
      'field types' => array('taxonomy_term_reference'),
1166
      'settings'    => array(
1167
        'taxonomy_term_link' => TRUE,
1168
        'taxonomy_term_separator' => ', ',
1169
      ),
1170
    );
1171

    
1172
    if (module_exists('i18n_taxonomy')) {
1173
      $formatters['ds_taxonomy_separator_localized'] = array(
1174
        'label'       => t('Separated (localized)'),
1175
        'description' => t('Display the referenced term with a separator. Use this with the "localize" translation mode for vocabularies.'),
1176
        'field types' => array('taxonomy_term_reference'),
1177
        'settings'    => array(
1178
          'taxonomy_term_link' => TRUE,
1179
          'taxonomy_term_separator' => ', ',
1180
        ),
1181
      );
1182
    }
1183
  }
1184

    
1185
  return $formatters;
1186
}
1187

    
1188
/**
1189
 * Implements hook_field_formatter_view().
1190
 */
1191
function ds_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
1192
  global $language;
1193
  $element = array();
1194

    
1195
  if ($display['type'] === 'ds_taxonomy_view_mode') {
1196
    $view_mode = $display['settings']['taxonomy_term_reference_view_mode'];
1197
    foreach ($items as $delta => $item) {
1198
      if ($item['tid'] == 'autocreate') {
1199
        // We don't necessarily have a link when this is
1200
        // an autocreated term, usually in preview.
1201
        // So just send the term as check plained markup.
1202
        $build['#markup'] = check_plain($item['name']);
1203
      }
1204
      else {
1205
        $term = taxonomy_term_load($item['tid']);
1206
        if (!empty($term)) {
1207
          $build = taxonomy_term_view($term, $view_mode, $langcode);
1208
        }
1209
        else {
1210
          $build['#markup'] = '';
1211
        }
1212
      }
1213
      $element[$delta] = $build;
1214
    }
1215
  }
1216

    
1217
  if ($display['type'] === 'ds_taxonomy_separator' || $display['type'] == 'ds_taxonomy_separator_localized') {
1218
    $linked = $display['settings']['taxonomy_term_link'];
1219

    
1220
    $terms = array();
1221
    foreach ($items as $delta => $item) {
1222
      if ($item['tid'] == 'autocreate') {
1223
        // We don't necessarily have a link when this is
1224
        // an autocreated term, usually in preview.
1225
        // So just send the term as check plained markup.
1226
        $item_display = check_plain($item['name']);
1227
      }
1228
      else {
1229
        $term = taxonomy_term_load($item['tid']);
1230
        if ($display['type'] == 'ds_taxonomy_separator_localized' && function_exists('i18n_taxonomy_term_name')) {
1231
          $term->name = i18n_taxonomy_term_name($term, $language->language);
1232
        }
1233
        $item_display = check_plain($term->name);
1234
        if ($linked) {
1235
          $uri = entity_uri('taxonomy_term', $term);
1236
          $item_display = l($term->name, $uri['path']);
1237
        }
1238
      }
1239
      $terms[] = $item_display;
1240
    }
1241

    
1242
    if (!empty($terms)) {
1243
      $output = '';
1244
      $separator = $display['settings']['taxonomy_term_separator'];
1245
      $output = implode($separator, $terms);
1246
      $element[0] = array('#markup' => $output);
1247
    }
1248
  }
1249

    
1250
  return $element;
1251
}
1252

    
1253
/**
1254
 * Implements hook_contextual_links_view_alter().
1255
 */
1256
function ds_contextual_links_view_alter(&$element, $items) {
1257

    
1258
  if (!empty($element['#element']['#entity_type']) && !empty($element['#element']['#bundle']) && module_exists('field_ui') && user_access('administer content types')) {
1259
    $entity_type = $element['#element']['#entity_type'];
1260
    $bundle = $element['#element']['#bundle'];
1261
    $view_mode = isset($element['#element']['#view_mode']) ? $element['#element']['#view_mode'] : 'default';
1262

    
1263
    // Get the manage display URI.
1264
    $admin_path = _field_ui_bundle_admin_path($entity_type, $bundle);
1265

    
1266
    // Check view mode settings.
1267
    $view_mode_settings = field_view_mode_settings($entity_type, $bundle);
1268
    $overridden = (!empty($view_mode_settings[$view_mode]['custom_settings']) ? TRUE : FALSE);
1269

    
1270
    if (!$overridden) {
1271
      $admin_path .= '/display';
1272
    }
1273
    else {
1274
      $admin_path .= '/display/' . $view_mode;
1275
    }
1276

    
1277
    $element['#links']['manage-display'] = array(
1278
      'title' => t('Manage display'),
1279
      'href' => $admin_path,
1280
      'query' => drupal_get_destination(),
1281
    );
1282
  }
1283
}