theme.inc 88 KB
Newer Older
Dries's avatar
   
Dries committed
1
<?php
2

3
/**
Dries's avatar
   
Dries committed
4
 * @file
5
 * The theme system, which controls the output of Drupal.
Dries's avatar
   
Dries committed
6
7
8
9
 *
 * The theme system allows for nearly all output of the Drupal system to be
 * customized by user themes.
 */
Dries's avatar
   
Dries committed
10

11
use Drupal\Component\Serialization\Json;
12
use Drupal\Component\Utility\SafeMarkup;
13
use Drupal\Component\Utility\String;
14
use Drupal\Component\Utility\UrlHelper;
15
use Drupal\Component\Utility\Xss;
16
use Drupal\Core\Config\Config;
17
use Drupal\Core\Config\StorageException;
18
use Drupal\Core\Extension\Extension;
19
use Drupal\Core\Extension\ExtensionNameLengthException;
20
21
22
use Drupal\Core\Page\FeedLinkElement;
use Drupal\Core\Page\LinkElement;
use Drupal\Core\Page\MetaElement;
23
use Drupal\Core\Template\Attribute;
24
use Drupal\Core\Theme\ThemeSettings;
25
use Drupal\Component\Utility\NestedArray;
26
use Drupal\Core\Render\Element;
27
use Symfony\Component\HttpFoundation\Request;
28

29
/**
30
 * @defgroup content_flags Content markers
31
 * @{
32
33
34
35
 * Markers used by mark.html.twig and node_mark() to designate content.
 *
 * @see mark.html.twig
 * @see node_mark()
36
 */
37
38
39
40

/**
 * Mark content as read.
 */
41
const MARK_READ = 0;
42
43
44
45

/**
 * Mark content as being new.
 */
46
const MARK_NEW = 1;
47
48
49
50

/**
 * Mark content as being updated.
 */
51
const MARK_UPDATED = 2;
52

53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/**
 * A responsive table class; hide table cell on narrow devices.
 *
 * Indicates that a column has medium priority and thus can be hidden on narrow
 * width devices and shown on medium+ width devices (i.e. tablets and desktops).
 */
const RESPONSIVE_PRIORITY_MEDIUM = 'priority-medium';

/**
 * A responsive table class; only show table cell on wide devices.
 *
 * Indicates that a column has low priority and thus can be hidden on narrow
 * and medium viewports and shown on wide devices (i.e. desktops).
 */
const RESPONSIVE_PRIORITY_LOW = 'priority-low';

69
/**
70
 * @} End of "defgroup content_flags".
71
72
 */

73
74
75
/**
 * Determines if a theme is available to use.
 *
76
 * @param string|\Drupal\Core\Extension\Extension $theme
77
78
 *   Either the name of a theme or a full theme object.
 *
79
 * @return bool
80
81
 *   Boolean TRUE if the theme is enabled or is the site administration theme;
 *   FALSE otherwise.
82
 *
83
84
85
86
 * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.
 *   Use \Drupal::service('access_check.theme')->checkAccess().
 *
 * @see \Drupal\Core\Theme\ThemeAccessCheck::checkAccess().
87
88
 */
function drupal_theme_access($theme) {
89
  if ($theme instanceof Extension) {
90
    $theme = $theme->getName();
91
  }
92
  return \Drupal::service('access_check.theme')->checkAccess($theme);
93
94
}

95
/**
96
 * Gets the theme registry.
97
 *
98
 * @param bool $complete
99
 *   Optional boolean to indicate whether to return the complete theme registry
100
101
102
103
104
105
106
 *   array or an instance of the Drupal\Core\Utility\ThemeRegistry class.
 *   If TRUE, the complete theme registry array will be returned. This is useful
 *   if you want to foreach over the whole registry, use array_* functions or
 *   inspect it in a debugger. If FALSE, an instance of the
 *   Drupal\Core\Utility\ThemeRegistry class will be returned, this provides an
 *   ArrayObject which allows it to be accessed with array syntax and isset(),
 *   and should be more lightweight than the full registry. Defaults to TRUE.
107
 *
108
 * @return
109
110
 *   The complete theme registry array, or an instance of the
 *   Drupal\Core\Utility\ThemeRegistry class.
111
 */
112
function theme_get_registry($complete = TRUE) {
113
  $theme_registry = \Drupal::service('theme.registry');
114
  if ($complete) {
115
    return $theme_registry->get();
116
117
  }
  else {
118
    return $theme_registry->getRuntime();
119
120
121
122
  }
}

/**
123
124
125
126
 * Forces the system to rebuild the theme registry.
 *
 * This function should be called when modules are added to the system, or when
 * a dynamic system needs to add more theme hooks.
127
 */
128
function drupal_theme_rebuild() {
129
  \Drupal::service('theme.registry')->reset();
130
131
}

Dries's avatar
   
Dries committed
132
/**
133
 * Returns a list of all currently available themes.
Dries's avatar
   
Dries committed
134
 *
135
136
 * Retrieved from the database, if available and the site is not in maintenance
 * mode; otherwise compiled freshly from the filesystem.
137
 *
Dries's avatar
   
Dries committed
138
 * @param $refresh
139
 *   Whether to reload the list of themes from the database. Defaults to FALSE.
140
 *
141
142
 * @return array
 *   An associative array of the currently available themes.
143
 *
144
145
146
147
 * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.
 *   Use \Drupal::service('theme_handler')->listInfo().
 *
 * @see \Drupal\Core\Extension\ThemeHandler::listInfo().
148
 */
149
function list_themes($refresh = FALSE) {
150
151
  /** @var \Drupal\Core\Extension\ThemeHandler $theme_handler */
  $theme_handler = \Drupal::service('theme_handler');
Dries's avatar
   
Dries committed
152
153

  if ($refresh) {
154
    $theme_handler->reset();
155
    system_list_reset();
Dries's avatar
   
Dries committed
156
157
  }

158
  return $theme_handler->listInfo();
Dries's avatar
   
Dries committed
159
160
}

Dries's avatar
   
Dries committed
161
/**
162
 * Generates themed output (internal use only).
163
 *
164
165
166
167
168
169
170
171
 * _theme() is an internal function. Do not call this function directly as it
 * will prevent the following items from working correctly:
 * - Render caching.
 * - JavaScript and CSS asset attachment.
 * - Pre / post render hooks.
 * - Defaults provided by hook_element_info(), including attached assets.
 * Instead, build a render array with a #theme key, and either return the
 * array (where possible) or call drupal_render() to convert it to HTML.
172
 *
173
174
175
176
177
178
 * All requests for themed output must go through this function, which is
 * invoked as part of the @link theme_render drupal_render() process @endlink.
 * The appropriate theme function is indicated by the #theme property
 * of a renderable array. _theme() examines the request and routes it to the
 * appropriate @link themeable theme function or template @endlink, by checking
 * the theme registry.
179
 *
180
 * @param $hook
181
182
 *   The name of the theme hook to call. If the name contains a
 *   double-underscore ('__') and there isn't an implementation for the full
183
 *   name, the part before the '__' is checked. This allows a fallback to a
184
 *   more generic implementation. For example, if _theme('links__node', ...) is
185
186
 *   called, but there is no implementation of that theme hook, then the
 *   'links' implementation is used. This process is iterative, so if
187
 *   _theme('links__contextual__node', ...) is called, _theme() checks for the
188
189
190
191
192
193
 *   following implementations, and uses the first one that exists:
 *   - links__contextual__node
 *   - links__contextual
 *   - links
 *   This allows themes to create specific theme implementations for named
 *   objects and contexts of otherwise generic theme hooks. The $hook parameter
194
 *   may also be an array, in which case the first theme hook that has an
195
 *   implementation is used. This allows for the code that calls _theme() to
196
 *   explicitly specify the fallback order in a situation where using the '__'
197
 *   convention is not desired or is insufficient.
198
199
 * @param $variables
 *   An associative array of variables to merge with defaults from the theme
200
201
202
203
 *   registry, pass to preprocess functions for modification, and finally, pass
 *   to the function or template implementing the theme hook. Alternatively,
 *   this can be a renderable array, in which case, its properties are mapped to
 *   variables expected by the theme hook implementations.
204
 *
205
206
207
 * @return string|false
 *   An HTML string representing the themed output or FALSE if the passed $hook
 *   is not implemented.
208
 *
209
 * @see drupal_render()
210
 * @see themeable
211
212
 * @see hook_theme()
 * @see template_preprocess()
Dries's avatar
   
Dries committed
213
 */
214
function _theme($hook, $variables = array()) {
215
  static $default_attributes;
216
217

  $module_handler = \Drupal::moduleHandler();
218
  $active_theme = \Drupal::theme()->getActiveTheme();
219

220
221
  // If called before all modules are loaded, we do not necessarily have a full
  // theme registry to work with, and therefore cannot process the theme
222
  // request properly. See also \Drupal\Core\Theme\Registry::get().
223
  if (!$module_handler->isLoaded() && !defined('MAINTENANCE_MODE')) {
224
    throw new Exception(t('_theme() may not be called until all modules are loaded.'));
225
226
  }

227
228
  /** @var \Drupal\Core\Utility\ThemeRegistry $theme_registry */
  $theme_registry = \Drupal::service('theme.registry')->getRuntime();
229

230
231
  // If an array of hook candidates were passed, use the first one that has an
  // implementation.
232
233
  if (is_array($hook)) {
    foreach ($hook as $candidate) {
234
      if ($theme_registry->has($candidate)) {
235
236
237
238
239
        break;
      }
    }
    $hook = $candidate;
  }
240
241
242
  // Save the original theme hook, so it can be supplied to theme variable
  // preprocess callbacks.
  $original_hook = $hook;
243

244
245
  // If there's no implementation, check for more generic fallbacks. If there's
  // still no implementation, log an error and return an empty string.
246
  if (!$theme_registry->has($hook)) {
247
248
249
250
    // Iteratively strip everything after the last '__' delimiter, until an
    // implementation is found.
    while ($pos = strrpos($hook, '__')) {
      $hook = substr($hook, 0, $pos);
251
      if ($theme_registry->has($hook)) {
252
253
254
        break;
      }
    }
255
    if (!$theme_registry->has($hook)) {
256
257
258
      // Only log a message when not trying theme suggestions ($hook being an
      // array).
      if (!isset($candidate)) {
259
        \Drupal::logger('theme')->warning('Theme hook %hook not found.', array('%hook' => $hook));
260
      }
261
      // There is no theme implementation for the hook passed. Return FALSE so
262
      // the function calling _theme() can differentiate between a hook that
263
264
      // exists and renders an empty string and a hook that is not implemented.
      return FALSE;
265
    }
266
267
  }

268
  $info = $theme_registry->get($hook);
269
270

  // If a renderable array is passed as $variables, then set $variables to
271
  // the arguments expected by the theme function.
272
273
274
  if (isset($variables['#theme']) || isset($variables['#theme_wrappers'])) {
    $element = $variables;
    $variables = array();
275
276
    if (isset($info['variables'])) {
      foreach (array_keys($info['variables']) as $name) {
277
        if (isset($element["#$name"]) || array_key_exists("#$name", $element)) {
278
279
          $variables[$name] = $element["#$name"];
        }
280
281
      }
    }
282
283
    else {
      $variables[$info['render element']] = $element;
284
285
      // Give a hint to render engines to prevent infinite recursion.
      $variables[$info['render element']]['#render_children'] = TRUE;
286
    }
287
  }
288

289
  // Merge in argument defaults.
290
291
292
293
294
  if (!empty($info['variables'])) {
    $variables += $info['variables'];
  }
  elseif (!empty($info['render element'])) {
    $variables += array($info['render element'] => array());
295
  }
296
297
298
299
  // Supply original caller info.
  $variables += array(
    'theme_hook_original' => $original_hook,
  );
300

301
302
303
304
305
306
307
308
309
310
311
312
  // Set base hook for later use. For example if '#theme' => 'node__article'
  // is called, we run hook_theme_suggestions_node_alter() rather than
  // hook_theme_suggestions_node__article_alter(), and also pass in the base
  // hook as the last parameter to the suggestions alter hooks.
  if (isset($info['base hook'])) {
    $base_theme_hook = $info['base hook'];
  }
  else {
    $base_theme_hook = $hook;
  }

  // Invoke hook_theme_suggestions_HOOK().
313
  $suggestions = $module_handler->invokeAll('theme_suggestions_' . $base_theme_hook, array($variables));
314
  // If _theme() was invoked with a direct theme suggestion like
315
316
317
318
319
  // '#theme' => 'node__article', add it to the suggestions array before
  // invoking suggestion alter hooks.
  if (isset($info['base hook'])) {
    $suggestions[] = $hook;
  }
320
321
322
323
324
325
326

  // Invoke hook_theme_suggestions_alter() and
  // hook_theme_suggestions_HOOK_alter().
  $hooks = array(
    'theme_suggestions',
    'theme_suggestions_' . $base_theme_hook,
  );
327
  $module_handler->alter($hooks, $suggestions, $variables, $base_theme_hook);
328
  \Drupal::theme()->alter($hooks, $suggestions, $variables, $base_theme_hook);
329
330

  // Check if each suggestion exists in the theme registry, and if so,
331
332
  // use it instead of the hook that _theme() was called with. For example, a
  // function may call _theme('node', ...), but a module can add
333
334
335
  // 'node__article' as a suggestion via hook_theme_suggestions_HOOK_alter(),
  // enabling a theme to have an alternate template file for article nodes.
  foreach (array_reverse($suggestions) as $suggestion) {
336
337
    if ($theme_registry->has($suggestion)) {
      $info = $theme_registry->get($suggestion);
338
339
340
341
      break;
    }
  }

342
343
344
345
346
347
348
349
  // Include a file if the theme function or variable preprocessor is held
  // elsewhere.
  if (!empty($info['includes'])) {
    foreach ($info['includes'] as $include_file) {
      include_once DRUPAL_ROOT . '/' . $include_file;
    }
  }

350
  // Invoke the variable preprocessors, if any.
351
352
  if (isset($info['base hook'])) {
    $base_hook = $info['base hook'];
353
    $base_hook_info = $theme_registry->get($base_hook);
354
    // Include files required by the base hook, since its variable preprocessors
355
356
357
358
359
360
    // might reside there.
    if (!empty($base_hook_info['includes'])) {
      foreach ($base_hook_info['includes'] as $include_file) {
        include_once DRUPAL_ROOT . '/' . $include_file;
      }
    }
361
    // Replace the preprocess functions with those from the base hook.
362
    if (isset($base_hook_info['preprocess functions'])) {
363
364
365
366
      // Set a variable for the 'theme_hook_suggestion'. This is used to
      // maintain backwards compatibility with template engines.
      $theme_hook_suggestion = $hook;
      $info['preprocess functions'] = $base_hook_info['preprocess functions'];
367
368
    }
  }
369
370
371
372
  if (isset($info['preprocess functions'])) {
    foreach ($info['preprocess functions'] as $preprocessor_function) {
      if (function_exists($preprocessor_function)) {
        $preprocessor_function($variables, $hook, $info);
373
      }
374
375
    }
  }
376

377
  // Generate the output using either a function or a template.
378
  $output = '';
379
  if (isset($info['function'])) {
380
    if (function_exists($info['function'])) {
381
      $output = SafeMarkup::set($info['function']($variables));
Dries's avatar
   
Dries committed
382
    }
Dries's avatar
   
Dries committed
383
  }
384
  else {
385
386
    $render_function = 'twig_render_template';
    $extension = '.html.twig';
387

388
    // The theme engine may use a different extension and a different renderer.
389
    $theme_engine = $active_theme->getEngine();
390
    if (isset($theme_engine)) {
391
      if ($info['type'] != 'module') {
392
393
        if (function_exists($theme_engine . '_render_template')) {
          $render_function = $theme_engine . '_render_template';
394
        }
395
        $extension_function = $theme_engine . '_extension';
396
397
398
399
400
401
        if (function_exists($extension_function)) {
          $extension = $extension_function();
        }
      }
    }

402
403
404
405
406
    // In some cases, a template implementation may not have had
    // template_preprocess() run (for example, if the default implementation is
    // a function, but a template overrides that default implementation). In
    // these cases, a template should still be able to expect to have access to
    // the variables provided by template_preprocess(), so we add them here if
407
408
409
410
411
    // they don't already exist. We don't want the overhead of running
    // template_preprocess() twice, so we use the 'directory' variable to
    // determine if it has already run, which while not completely intuitive,
    // is reasonably safe, and allows us to save on the overhead of adding some
    // new variable to track that.
412
413
    if (!isset($variables['directory'])) {
      $default_template_variables = array();
414
      template_preprocess($default_template_variables, $hook, $info);
415
416
      $variables += $default_template_variables;
    }
417
418
419
420
421
422
423
424
425
426
427
428
429
430
    if (!isset($default_attributes)) {
      $default_attributes = new Attribute();
    }
    foreach (array('attributes', 'title_attributes', 'content_attributes') as $key) {
      if (isset($variables[$key]) && !($variables[$key] instanceof Attribute)) {
        if ($variables[$key]) {
          $variables[$key] = new Attribute($variables[$key]);
        }
        else {
          // Create empty attributes.
          $variables[$key] = clone $default_attributes;
        }
      }
    }
431

432
433
434
435
    // Render the output using the template file.
    $template_file = $info['template'] . $extension;
    if (isset($info['path'])) {
      $template_file = $info['path'] . '/' . $template_file;
436
    }
437
438
439
440
441
442
443
444
445
446
    // Add the theme suggestions to the variables array just before rendering
    // the template for backwards compatibility with template engines.
    $variables['theme_hook_suggestions'] = $suggestions;
    // For backwards compatibility, pass 'theme_hook_suggestion' on to the
    // template engine. This is only set when calling a direct suggestion like
    // '#theme' => 'menu_tree__shortcut_default' when the template exists in the
    // current theme.
    if (isset($theme_hook_suggestion)) {
      $variables['theme_hook_suggestion'] = $theme_hook_suggestion;
    }
447
    $output = $render_function($template_file, $variables);
Dries's avatar
   
Dries committed
448
  }
449

450
  return (string) $output;
451
452
}

453
/**
454
 * Allows themes and/or theme engines to discover overridden theme functions.
455
456
457
458
459
460
 *
 * @param $cache
 *   The existing cache of theme hooks to test against.
 * @param $prefixes
 *   An array of prefixes to test, in reverse order of importance.
 *
461
 * @return $implementations
462
463
464
 *   The functions found, suitable for returning from hook_theme;
 */
function drupal_find_theme_functions($cache, $prefixes) {
465
  $implementations = array();
466
467
468
469
  $functions = get_defined_functions();

  foreach ($cache as $hook => $info) {
    foreach ($prefixes as $prefix) {
470
471
472
473
474
475
      // Find theme functions that implement possible "suggestion" variants of
      // registered theme hooks and add those as new registered theme hooks.
      // The 'pattern' key defines a common prefix that all suggestions must
      // start with. The default is the name of the hook followed by '__'. An
      // 'base hook' key is added to each entry made for a found suggestion,
      // so that common functionality can be implemented for all suggestions of
476
      // the same base hook. To keep things simple, deep hierarchy of
477
478
479
480
      // suggestions is not supported: each suggestion's 'base hook' key
      // refers to a base hook, not to another suggestion, and all suggestions
      // are found using the base hook's pattern, not a pattern from an
      // intermediary suggestion.
481
      $pattern = isset($info['pattern']) ? $info['pattern'] : ($hook . '__');
482
      if (!isset($info['base hook']) && !empty($pattern)) {
483
        $matches = preg_grep('/^' . $prefix . '_' . $pattern . '/', $functions['user']);
484
485
        if ($matches) {
          foreach ($matches as $match) {
486
            $new_hook = substr($match, strlen($prefix) + 1);
487
            $arg_name = isset($info['variables']) ? 'variables' : 'render element';
488
            $implementations[$new_hook] = array(
489
              'function' => $match,
490
              $arg_name => $info[$arg_name],
491
              'base hook' => $hook,
492
493
494
495
            );
          }
        }
      }
496
497
498
      // Find theme functions that implement registered theme hooks and include
      // that in what is returned so that the registry knows that the theme has
      // this implementation.
499
      if (function_exists($prefix . '_' . $hook)) {
500
        $implementations[$hook] = array(
501
          'function' => $prefix . '_' . $hook,
502
503
504
505
506
        );
      }
    }
  }

507
  return $implementations;
508
509
510
}

/**
511
 * Allows themes and/or theme engines to easily discover overridden templates.
512
513
514
515
516
517
518
519
520
 *
 * @param $cache
 *   The existing cache of theme hooks to test against.
 * @param $extension
 *   The extension that these templates will have.
 * @param $path
 *   The path to search.
 */
function drupal_find_theme_templates($cache, $extension, $path) {
521
  $implementations = array();
522

523
524
525
526
  // Collect paths to all sub-themes grouped by base themes. These will be
  // used for filtering. This allows base themes to have sub-themes in its
  // folder hierarchy without affecting the base themes template discovery.
  $theme_paths = array();
527
  foreach (list_themes() as $theme_info) {
528
    if (!empty($theme_info->base_theme)) {
529
      $theme_paths[$theme_info->base_theme][$theme_info->getName()] = $theme_info->getPath();
530
531
532
533
534
535
536
    }
  }
  foreach ($theme_paths as $basetheme => $subthemes) {
    foreach ($subthemes as $subtheme => $subtheme_path) {
      if (isset($theme_paths[$subtheme])) {
        $theme_paths[$basetheme] = array_merge($theme_paths[$basetheme], $theme_paths[$subtheme]);
      }
537
538
    }
  }
539
  $theme = \Drupal::theme()->getActiveTheme()->getName();
540
  $subtheme_paths = isset($theme_paths[$theme]) ? $theme_paths[$theme] : array();
541

542
  // Escape the periods in the extension.
543
  $regex = '/' . str_replace('.', '\.', $extension) . '$/';
544
  // Get a listing of all template files in the path to search.
545
  $files = file_scan_directory($path, $regex, array('key' => 'filename'));
546
547
548
549

  // Find templates that implement registered theme hooks and include that in
  // what is returned so that the registry knows that the theme has this
  // implementation.
550
  foreach ($files as $template => $file) {
551
    // Ignore sub-theme templates for the current theme.
552
    if (strpos($file->uri, str_replace($subtheme_paths, '', $file->uri)) !== 0) {
553
554
      continue;
    }
555
556
    // Remove the extension from the filename.
    $template = str_replace($extension, '', $template);
557
558
559
560
    // Transform - in filenames to _ to match function naming scheme
    // for the purposes of searching.
    $hook = strtr($template, '-', '_');
    if (isset($cache[$hook])) {
561
      $implementations[$hook] = array(
562
        'template' => $template,
563
        'path' => dirname($file->uri),
564
565
      );
    }
566
567
568
569

    // Match templates based on the 'template' filename.
    foreach ($cache as $hook => $info) {
      if (isset($info['template'])) {
570
        $template_candidates = array($info['template'], str_replace($info['theme path'] . '/templates/', '', $info['template']));
571
572
573
574
575
576
577
578
        if (in_array($template, $template_candidates)) {
          $implementations[$hook] = array(
            'template' => $template,
            'path' => dirname($file->uri),
          );
        }
      }
    }
579
580
  }

581
  // Find templates that implement possible "suggestion" variants of registered
582
  // theme hooks and add those as new registered theme hooks. See
583
584
  // drupal_find_theme_functions() for more information about suggestions and
  // the use of 'pattern' and 'base hook'.
585
586
  $patterns = array_keys($files);
  foreach ($cache as $hook => $info) {
587
    $pattern = isset($info['pattern']) ? $info['pattern'] : ($hook . '__');
588
    if (!isset($info['base hook']) && !empty($pattern)) {
589
590
      // Transform _ in pattern to - to match file naming scheme
      // for the purposes of searching.
591
      $pattern = strtr($pattern, '_', '-');
592

593
      $matches = preg_grep('/^' . $pattern . '/', $patterns);
594
595
      if ($matches) {
        foreach ($matches as $match) {
596
          $file = $match;
597
598
          // Remove the extension from the filename.
          $file = str_replace($extension, '', $file);
599
600
          // Put the underscores back in for the hook name and register this
          // pattern.
601
          $arg_name = isset($info['variables']) ? 'variables' : 'render element';
602
          $implementations[strtr($file, '-', '_')] = array(
603
            'template' => $file,
604
            'path' => dirname($files[$match]->uri),
605
            $arg_name => $info[$arg_name],
606
            'base hook' => $hook,
607
608
609
610
611
          );
        }
      }
    }
  }
612
  return $implementations;
613
614
}

Dries's avatar
   
Dries committed
615
/**
616
 * Retrieves a setting for the current theme or for a given theme.
Dries's avatar
   
Dries committed
617
 *
618
619
 * The final setting is obtained from the last value found in the following
 * sources:
620
621
622
 * - the default theme-specific settings defined in any base theme's .info.yml
 *   file
 * - the default theme-specific settings defined in the theme's .info.yml file
623
624
625
626
 * - the saved values from the global theme settings form
 * - the saved values from the theme's settings form
 * To only retrieve the default global theme setting, an empty string should be
 * given for $theme.
Dries's avatar
   
Dries committed
627
628
 *
 * @param $setting_name
629
 *   The name of the setting to be retrieved.
630
 * @param $theme
631
632
 *   The name of a given theme; defaults to the current theme.
 *
Dries's avatar
   
Dries committed
633
634
635
 * @return
 *   The value of the requested setting, NULL if the setting does not exist.
 */
636
637
function theme_get_setting($setting_name, $theme = NULL) {
  $cache = &drupal_static(__FUNCTION__, array());
Dries's avatar
   
Dries committed
638

639
  // If no key is given, use the current theme if we can determine it.
640
  if (!isset($theme)) {
641
    $theme = \Drupal::theme()->getActiveTheme()->getName();
642
  }
Dries's avatar
   
Dries committed
643

644
  if (empty($cache[$theme])) {
645
646
    // Create a theme settings object.
    $cache[$theme] = new ThemeSettings($theme);
647

648
649
    // Get the values for the theme-specific settings from the .info.yml files
    // of the theme and all its base themes.
650
651
    $themes = list_themes();
    if ($theme && isset($themes[$theme])) {
652
653
654
655
656
657
      $theme_object = $themes[$theme];

      // Create a list which includes the current theme and all its base themes.
      if (isset($theme_object->base_themes)) {
        $theme_keys = array_keys($theme_object->base_themes);
        $theme_keys[] = $theme;
Dries's avatar
   
Dries committed
658
      }
659
660
661
      else {
        $theme_keys = array($theme);
      }
662
      // Read hard-coded default settings from the theme info files.
663
664
      foreach ($theme_keys as $theme_key) {
        if (!empty($themes[$theme_key]->info['settings'])) {
665
          $cache[$theme]->merge($themes[$theme_key]->info['settings']);
666
        }
Dries's avatar
   
Dries committed
667
668
669
      }
    }

670
    // Get the global settings from configuration.
671
    $cache[$theme]->merge(\Drupal::config('system.theme.global')->get());
672

673
    if ($theme && isset($themes[$theme])) {
674
675
676
677
678
679
680
681
      // Retrieve configured theme-specific settings, if any.
      try {
        if ($theme_settings = \Drupal::config($theme . '.settings')->get()) {
          $cache[$theme]->merge($theme_settings);
        }
      }
      catch (StorageException $e) {
      }
682

683
684
685
      // If the theme does not support a particular feature, override the global
      // setting and set the value to NULL.
      if (!empty($theme_object->info['features'])) {
686
        foreach (_system_default_theme_features() as $feature) {
687
          if (!in_array($feature, $theme_object->info['features'])) {
688
            $cache[$theme]->set('features.' . $feature, NULL);
689
690
691
692
          }
        }
      }

693
      // Generate the path to the logo image.
694
695
696
      if ($cache[$theme]->get('features.logo')) {
        $logo_path = $cache[$theme]->get('logo.path');
        if ($cache[$theme]->get('logo.use_default')) {
697
          $cache[$theme]->set('logo.url', file_create_url($theme_object->getPath() . '/logo.png'));
698
        }
699
700
        elseif ($logo_path) {
          $cache[$theme]->set('logo.url', file_create_url($logo_path));
701
702
        }
      }
703
704

      // Generate the path to the favicon.
705
706
707
      if ($cache[$theme]->get('features.favicon')) {
        $favicon_path = $cache[$theme]->get('favicon.path');
        if ($cache[$theme]->get('favicon.use_default')) {
708
          if (file_exists($favicon = $theme_object->getPath() . '/favicon.ico')) {
709
            $cache[$theme]->set('favicon.url', file_create_url($favicon));
710
711
          }
          else {
712
            $cache[$theme]->set('favicon.url', file_create_url('core/misc/favicon.ico'));
713
714
          }
        }
715
716
        elseif ($favicon_path) {
          $cache[$theme]->set('favicon.url', file_create_url($favicon_path));
717
718
        }
        else {
719
          $cache[$theme]->set('features.favicon', FALSE);
720
        }
721
      }
722
    }
Dries's avatar
   
Dries committed
723
724
  }

725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
  return $cache[$theme]->get($setting_name);
}

/**
 * Converts theme settings to configuration.
 *
 * @see system_theme_settings_submit()
 *
 * @param array $theme_settings
 *   An array of theme settings from system setting form or a Drupal 7 variable.
 * @param Config $config
 *   The configuration object to update.
 *
 * @return
 *   The Config object with updated data.
 */
function theme_settings_convert_to_config(array $theme_settings, Config $config) {
  foreach ($theme_settings as $key => $value) {
    if ($key == 'default_logo') {
      $config->set('logo.use_default', $value);
    }
    else if ($key == 'logo_path') {
      $config->set('logo.path', $value);
    }
    else if ($key == 'default_favicon') {
      $config->set('favicon.use_default', $value);
    }
    else if ($key == 'favicon_path') {
      $config->set('favicon.path', $value);
    }
    else if ($key == 'favicon_mimetype') {
      $config->set('favicon.mimetype', $value);
    }
    else if (substr($key, 0, 7) == 'toggle_') {
      $config->set('features.' . drupal_substr($key, 7), $value);
    }
    else if (!in_array($key, array('theme', 'logo_upload'))) {
      $config->set($key, $value);
    }
  }
  return $config;
Dries's avatar
   
Dries committed
766
767
}

768
/**
769
 * Enables a given list of themes.
770
771
772
 *
 * @param $theme_list
 *   An array of theme names.
773
 *
774
775
776
 * @return bool
 *   Whether any of the given themes have been enabled.
 *
777
778
779
780
 * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.
 *   Use \Drupal::service('theme_handler')->enable().
 *
 * @see \Drupal\Core\Extension\ThemeHandler::enable().
781
782
 */
function theme_enable($theme_list) {
783
  return \Drupal::service('theme_handler')->enable($theme_list);
784
785
786
}

/**
787
 * Disables a given list of themes.
788
789
790
 *
 * @param $theme_list
 *   An array of theme names.
791
 *
792
793
794
 * @return bool
 *   Whether any of the given themes have been disabled.
 *
795
796
797
798
 * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.
 *   Use \Drupal::service('theme_handler')->disable().
 *
 * @see \Drupal\Core\Extension\ThemeHandler::disable().
799
800
 */
function theme_disable($theme_list) {
801
  return \Drupal::service('theme_handler')->disable($theme_list);
802
803
}

804
/**
805
 * @addtogroup themeable
806
807
 * @{
 */
808

809
/**
810
811
812
 * Prepares variables for time templates.
 *
 * Default template: time.html.twig.
813
814
 *
 * @param array $variables
815
 *   An associative array possibly containing:
816
817
818
 *   - attributes['timestamp']:
 *   - timestamp:
 *   - text:
819
 */
820
function template_preprocess_time(&$variables) {
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
  // Format the 'datetime' attribute based on the timestamp.
  // @see http://www.w3.org/TR/html5-author/the-time-element.html#attr-time-datetime
  if (!isset($variables['attributes']['datetime']) && isset($variables['timestamp'])) {
    $variables['attributes']['datetime'] = format_date($variables['timestamp'], 'html_datetime', '', 'UTC');
  }

  // If no text was provided, try to auto-generate it.
  if (!isset($variables['text'])) {
    // Format and use a human-readable version of the timestamp, if any.
    if (isset($variables['timestamp'])) {
      $variables['text'] = format_date($variables['timestamp']);
      $variables['html'] = FALSE;
    }
    // Otherwise, use the literal datetime attribute.
    elseif (isset($variables['attributes']['datetime'])) {
      $variables['text'] = $variables['attributes']['datetime'];
      $variables['html'] = FALSE;
    }
  }
840
841
842
843

  // Add a 'datetime' class.
  $variables['attributes']['class'][] = 'datetime';

844
  $variables['attributes'] = new Attribute($variables['attributes']);
845
846
}

847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
/**
 * Prepares variables for datetime form element templates.
 *
 * The datetime form element serves as a wrapper around the date element type,
 * which creates a date and a time component for a date.
 *
 * Default template: datetime-form.html.twig.
 *
 * @param array $variables
 *   An associative array containing:
 *   - element: An associative array containing the properties of the element.
 *     Properties used: #title, #value, #options, #description, #required,
 *     #attributes.
 *
 * @see form_process_datetime()
 */
function template_preprocess_datetime_form(&$variables) {
  $element = $variables['element'];

  $variables['attributes'] = array();
  if (isset($element['#id'])) {
    $variables['attributes']['id'] = $element['#id'];
  }
  if (!empty($element['#attributes']['class'])) {
    $variables['attributes']['class'] = (array) $element['#attributes']['class'];
  }
  $variables['attributes']['class'][] = 'container-inline';

  $variables['content'] = $element;
}

/**
 * Prepares variables for datetime form wrapper templates.
 *
 * Default template: datetime-wrapper.html.twig.
 *
 * @param array $variables
 *   An associative array containing:
 *   - element: An associative array containing the properties of the element.
 *     Properties used: #title, #children, #required, #attributes.
 */
function template_preprocess_datetime_wrapper(&$variables) {
  $element = $variables['element'];

  if (!empty($element['#title'])) {
    $variables['title'] = $element['#title'];
  }

  if (!empty($element['#description'])) {
    $variables['description'] = $element['#description'];
  }

  $title_attributes = array('class' => array('label'));
  // For required datetime fields a 'form-required' class is appended to the
  // label attributes.
  if (!empty($element['#required'])) {
    $title_attributes['class'][] = 'form-required';
  }
  $variables['title_attributes'] = new Attribute($title_attributes);
  $variables['content'] = $element['#children'];
}

Dries's avatar
   
Dries committed
909
/**
910
 * Prepares variables for status message templates.
Dries's avatar
   
Dries committed
911
 *
912
 * Default template: status-messages.html.twig.
913
 *
914
 * @param array $variables
915
 *   An associative array containing:
916
917
 *   - display: (optional) May have a value of 'status' or 'error' when only
 *     displaying messages of that specific type.
Dries's avatar
   
Dries committed
918
 */
919
920
921
function template_preprocess_status_messages(&$variables) {
  $variables['message_list'] = drupal_get_messages($variables['display']);
  $variables['status_headings'] = array(
922
923
924
925
    'status' => t('Status message'),
    'error' => t('Error message'),
    'warning' => t('Warning message'),
  );
Dries's avatar
   
Dries committed
926
927
}

Dries's avatar
   
Dries committed
928
/**
929
 * Prepares variables for links templates.
930
 *
931
932
933
 * Default template: links.html.twig.
 *
 * @param array $variables
934
 *   An associative array containing:
935
 *   - links: An associative array of links to be themed. The key for each link
936
 *     is used as its CSS class. Each link should be itself an array, with the
937
938
 *     following elements:
 *     - title: The link text.
939
940
941
942
943
944
945
946
 *     - route_name: (optional) The name of the route to link to. If omitted
 *       (and if 'href' is omitted as well), the 'title' is shown as
 *       a plain text item in the links list.
 *     - route_parameters: (optional) An array of route parameters for the link.
 *     - href: (optional) The link URL. It is preferred to use 'route_name' and
 *       'route parameters' for internal links. Use 'href' for links to external
 *       URLs. If omitted (and if 'route_name' is omitted as well), the 'title'
 *       is shown as a plain text item in the links list.
947
 *     - html: (optional) Whether or not 'title' is HTML. If set, the title
948
949
 *       will not be passed through
 *       \Drupal\Component\Utility\String::checkPlain().
950
951
 *     - attributes: (optional) Attributes for the anchor, or for the <span>
 *       tag used in its place if no 'href' is supplied. If element 'class' is
952
 *       included, it must be an array of one or more class names.
953
954
 *     If the 'href' element is supplied, the entire link array is passed to
 *     l() as its $options parameter.
955
956
 *   - attributes: A keyed array of attributes for the UL containing the
 *     list of links.
957
 *   - set_active_class: (optional) Whether each link should compare the
958
 *     route_name + route_parameters or href (path), language and query options
959
960
961
962
 *     to the current URL, to determine whether the link is "active". If so, an
 *     "active" class will be applied to the list item containing the link, as
 *     well as the link itself. It is important to use this sparingly since it
 *     is usually unnecessary and requires extra processing.
963
964
965
966
967
968
 *     For anonymous users, the "active" class will be calculated on the server,
 *     because most sites serve each anonymous user the same cached page anyway.
 *     For authenticated users, the "active" class will be calculated on the
 *     client (through JavaScript), only data- attributes are added to list
 *     items and contained links, to prevent breaking the render cache. The
 *     JavaScript is added in system_page_build().
969
970
971
 *   - heading: (optional) A heading to precede the links. May be an
 *     associative array or a string. If it's an array, it can have the
 *     following elements:
972
973
 *     - text: The heading text.
 *     - level: The heading level (e.g. 'h2', 'h3').
974
 *     - attributes: (optional) An array of the CSS attributes for the heading.
975
 *     When using a string it will be used as the text of the heading and the
976
977
 *     level will default to 'h2'. Headings should be used on navigation menus
 *     and any list of links that consistently appears on multiple pages. To
978
 *     make the heading invisible use the 'visually-hidden' CSS class. Do not
979
980
 *     use 'display:none', which removes it from screen readers and assistive
 *     technology. Headings allow screen reader and keyboard only users to
981
982
983
 *     navigate to or skip the links. See
 *     http://juicystudio.com/article/screen-readers-display-none.php and
 *     http://www.w3.org/TR/WCAG-TECHS/H42.html for more information.
984
 *
985
986
 * Unfortunately links templates duplicate the "active" class handling of l()
 * and LinkGenerator::generate() because it needs to be able to set the "active"
987
988
989
990
991
992
993
994
995
996
 * class not on the links themselves ("a" tags), but on the list items ("li"
 * tags) that contain the links. This is necessary for CSS to be able to style
 * list items differently when the link is active, since CSS does not yet allow
 * one to style list items only if it contains a certain element with a certain
 * class. I.e. we cannot yet convert this jQuery selector to a CSS selector:
 *   jQuery('li:has("a.active")')
 *
 * @see l()
 * @see \Drupal\Core\Utility\LinkGenerator::generate()
 * @see system_page_build()
Dries's avatar
   
Dries committed
997
 */
998
function template_preprocess_links(&$variables) {
999
  $links = $variables['links'];
1000
  $heading = &$variables['heading'];
1001