theme.inc 85.1 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
 *   Boolean TRUE if the theme is installed or is the site administration theme;
81
 *   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 378 379 380 381 382 383
    // Allow theme preprocess functions to set $variables['#attached'] and use
    // it like the #attached property on render arrays. In Drupal 8, this is the
    // (only) officially supported method of attaching assets from preprocess
    // functions. Assets attached here should be associated with the template
    // that we're preprocessing variables for.
    if (isset($variables['#attached'])) {
      $preprocess_attached = ['#attached' => $variables['#attached']];
      drupal_render($preprocess_attached, TRUE);
    }
384
  }
385

386
  // Generate the output using either a function or a template.
387
  $output = '';
388
  if (isset($info['function'])) {
389
    if (function_exists($info['function'])) {
390
      $output = SafeMarkup::set($info['function']($variables));
Dries's avatar
 
Dries committed
391
    }
Dries's avatar
 
Dries committed
392
  }
393
  else {
394 395
    $render_function = 'twig_render_template';
    $extension = '.html.twig';
396

397
    // The theme engine may use a different extension and a different renderer.
398
    $theme_engine = $active_theme->getEngine();
399
    if (isset($theme_engine)) {
400
      if ($info['type'] != 'module') {
401 402
        if (function_exists($theme_engine . '_render_template')) {
          $render_function = $theme_engine . '_render_template';
403
        }
404
        $extension_function = $theme_engine . '_extension';
405 406 407 408 409 410
        if (function_exists($extension_function)) {
          $extension = $extension_function();
        }
      }
    }

411 412 413 414 415
    // 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
416 417 418 419 420
    // 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.
421 422
    if (!isset($variables['directory'])) {
      $default_template_variables = array();
423
      template_preprocess($default_template_variables, $hook, $info);
424 425
      $variables += $default_template_variables;
    }
426 427 428 429 430 431 432 433 434 435 436 437 438 439
    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;
        }
      }
    }
440

441 442 443 444
    // Render the output using the template file.
    $template_file = $info['template'] . $extension;
    if (isset($info['path'])) {
      $template_file = $info['path'] . '/' . $template_file;
445
    }
446 447 448 449 450
    // 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
451
    // '#theme' => 'menu__shortcut_default' when the template exists in the
452 453 454 455
    // current theme.
    if (isset($theme_hook_suggestion)) {
      $variables['theme_hook_suggestion'] = $theme_hook_suggestion;
    }
456
    $output = $render_function($template_file, $variables);
Dries's avatar
 
Dries committed
457
  }
458

459
  return (string) $output;
460 461
}

462
/**
463
 * Allows themes and/or theme engines to discover overridden theme functions.
464 465 466 467 468 469
 *
 * @param $cache
 *   The existing cache of theme hooks to test against.
 * @param $prefixes
 *   An array of prefixes to test, in reverse order of importance.
 *
470
 * @return $implementations
471 472 473
 *   The functions found, suitable for returning from hook_theme;
 */
function drupal_find_theme_functions($cache, $prefixes) {
474
  $implementations = array();
475 476 477 478
  $functions = get_defined_functions();

  foreach ($cache as $hook => $info) {
    foreach ($prefixes as $prefix) {
479 480 481 482 483 484
      // 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
485
      // the same base hook. To keep things simple, deep hierarchy of
486 487 488 489
      // 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.
490
      $pattern = isset($info['pattern']) ? $info['pattern'] : ($hook . '__');
491
      if (!isset($info['base hook']) && !empty($pattern)) {
492
        $matches = preg_grep('/^' . $prefix . '_' . $pattern . '/', $functions['user']);
493 494
        if ($matches) {
          foreach ($matches as $match) {
495
            $new_hook = substr($match, strlen($prefix) + 1);
496
            $arg_name = isset($info['variables']) ? 'variables' : 'render element';
497
            $implementations[$new_hook] = array(
498
              'function' => $match,
499
              $arg_name => $info[$arg_name],
500
              'base hook' => $hook,
501 502 503 504
            );
          }
        }
      }
505 506 507
      // 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.
508
      if (function_exists($prefix . '_' . $hook)) {
509
        $implementations[$hook] = array(
510
          'function' => $prefix . '_' . $hook,
511 512 513 514 515
        );
      }
    }
  }

516
  return $implementations;
517 518 519
}

/**
520
 * Allows themes and/or theme engines to easily discover overridden templates.
521 522 523 524 525 526 527 528 529
 *
 * @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) {
530
  $implementations = array();
531

532 533 534 535
  // 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();
536
  foreach (list_themes() as $theme_info) {
537
    if (!empty($theme_info->base_theme)) {
538
      $theme_paths[$theme_info->base_theme][$theme_info->getName()] = $theme_info->getPath();
539 540 541 542 543 544 545
    }
  }
  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]);
      }
546 547
    }
  }
548
  $theme = \Drupal::theme()->getActiveTheme()->getName();
549
  $subtheme_paths = isset($theme_paths[$theme]) ? $theme_paths[$theme] : array();
550

551
  // Escape the periods in the extension.
552
  $regex = '/' . str_replace('.', '\.', $extension) . '$/';
553
  // Get a listing of all template files in the path to search.
554
  $files = file_scan_directory($path, $regex, array('key' => 'filename'));
555 556 557 558

  // 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.
559
  foreach ($files as $template => $file) {
560
    // Ignore sub-theme templates for the current theme.
561
    if (strpos($file->uri, str_replace($subtheme_paths, '', $file->uri)) !== 0) {
562 563
      continue;
    }
564 565
    // Remove the extension from the filename.
    $template = str_replace($extension, '', $template);
566 567 568 569
    // Transform - in filenames to _ to match function naming scheme
    // for the purposes of searching.
    $hook = strtr($template, '-', '_');
    if (isset($cache[$hook])) {
570
      $implementations[$hook] = array(
571
        'template' => $template,
572
        'path' => dirname($file->uri),
573 574
      );
    }
575 576 577 578

    // Match templates based on the 'template' filename.
    foreach ($cache as $hook => $info) {
      if (isset($info['template'])) {
579
        $template_candidates = array($info['template'], str_replace($info['theme path'] . '/templates/', '', $info['template']));
580 581 582 583 584 585 586 587
        if (in_array($template, $template_candidates)) {
          $implementations[$hook] = array(
            'template' => $template,
            'path' => dirname($file->uri),
          );
        }
      }
    }
588 589
  }

590
  // Find templates that implement possible "suggestion" variants of registered
591
  // theme hooks and add those as new registered theme hooks. See
592 593
  // drupal_find_theme_functions() for more information about suggestions and
  // the use of 'pattern' and 'base hook'.
594 595
  $patterns = array_keys($files);
  foreach ($cache as $hook => $info) {
596
    $pattern = isset($info['pattern']) ? $info['pattern'] : ($hook . '__');
597
    if (!isset($info['base hook']) && !empty($pattern)) {
598 599
      // Transform _ in pattern to - to match file naming scheme
      // for the purposes of searching.
600
      $pattern = strtr($pattern, '_', '-');
601

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

Dries's avatar
 
Dries committed
624
/**
625
 * Retrieves a setting for the current theme or for a given theme.
Dries's avatar
 
Dries committed
626
 *
627 628
 * The final setting is obtained from the last value found in the following
 * sources:
629 630 631
 * - 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
632 633 634 635
 * - 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
636 637
 *
 * @param $setting_name
638
 *   The name of the setting to be retrieved.
639
 * @param $theme
640 641
 *   The name of a given theme; defaults to the current theme.
 *
Dries's avatar
 
Dries committed
642 643 644
 * @return
 *   The value of the requested setting, NULL if the setting does not exist.
 */
645 646
function theme_get_setting($setting_name, $theme = NULL) {
  $cache = &drupal_static(__FUNCTION__, array());
Dries's avatar
 
Dries committed
647

648
  // If no key is given, use the current theme if we can determine it.
649
  if (!isset($theme)) {
650
    $theme = \Drupal::theme()->getActiveTheme()->getName();
651
  }
Dries's avatar
 
Dries committed
652

653
  if (empty($cache[$theme])) {
654 655
    // Create a theme settings object.
    $cache[$theme] = new ThemeSettings($theme);
656

657 658
    // Get the values for the theme-specific settings from the .info.yml files
    // of the theme and all its base themes.
659 660
    $themes = list_themes();
    if ($theme && isset($themes[$theme])) {
661 662 663 664 665 666
      $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
667
      }
668 669 670
      else {
        $theme_keys = array($theme);
      }
671
      // Read hard-coded default settings from the theme info files.
672 673
      foreach ($theme_keys as $theme_key) {
        if (!empty($themes[$theme_key]->info['settings'])) {
674
          $cache[$theme]->merge($themes[$theme_key]->info['settings']);
675
        }
Dries's avatar
 
Dries committed
676 677 678
      }
    }

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

682
    if ($theme && isset($themes[$theme])) {
683 684 685 686 687 688 689 690
      // Retrieve configured theme-specific settings, if any.
      try {
        if ($theme_settings = \Drupal::config($theme . '.settings')->get()) {
          $cache[$theme]->merge($theme_settings);
        }
      }
      catch (StorageException $e) {
      }
691

692 693 694
      // 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'])) {
695
        foreach (_system_default_theme_features() as $feature) {
696
          if (!in_array($feature, $theme_object->info['features'])) {
697
            $cache[$theme]->set('features.' . $feature, NULL);
698 699 700 701
          }
        }
      }

702
      // Generate the path to the logo image.
703 704 705
      if ($cache[$theme]->get('features.logo')) {
        $logo_path = $cache[$theme]->get('logo.path');
        if ($cache[$theme]->get('logo.use_default')) {
706
          $cache[$theme]->set('logo.url', file_create_url($theme_object->getPath() . '/logo.png'));
707
        }
708 709
        elseif ($logo_path) {
          $cache[$theme]->set('logo.url', file_create_url($logo_path));
710 711
        }
      }
712 713

      // Generate the path to the favicon.
714 715 716
      if ($cache[$theme]->get('features.favicon')) {
        $favicon_path = $cache[$theme]->get('favicon.path');
        if ($cache[$theme]->get('favicon.use_default')) {
717
          if (file_exists($favicon = $theme_object->getPath() . '/favicon.ico')) {
718
            $cache[$theme]->set('favicon.url', file_create_url($favicon));
719 720
          }
          else {
721
            $cache[$theme]->set('favicon.url', file_create_url('core/misc/favicon.ico'));
722 723
          }
        }
724 725
        elseif ($favicon_path) {
          $cache[$theme]->set('favicon.url', file_create_url($favicon_path));
726 727
        }
        else {
728
          $cache[$theme]->set('features.favicon', FALSE);
729
        }
730
      }
731
    }
Dries's avatar
 
Dries committed
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 766 767 768 769 770 771 772 773 774
  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
775 776
}

777
/**
778
 * @addtogroup themeable
779 780
 * @{
 */
781

782
/**
783 784 785
 * Prepares variables for time templates.
 *
 * Default template: time.html.twig.
786 787
 *
 * @param array $variables
788
 *   An associative array possibly containing:
789 790 791
 *   - attributes['timestamp']:
 *   - timestamp:
 *   - text:
792
 */
793
function template_preprocess_time(&$variables) {
794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814
  // 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;
    }
  }
}

815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865
/**
 * 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.
 *
<