file Bootstrap.php

  1. 8.x-3.x src/Bootstrap.php
  2. 8.x-3.x scripts/bootstrap.php

Namespace

Drupal\bootstrap
  1. <?php
  2. namespace Drupal\bootstrap;
  3. use Drupal\bootstrap\Plugin\AlterManager;
  4. use Drupal\bootstrap\Plugin\FormManager;
  5. use Drupal\bootstrap\Plugin\PreprocessManager;
  6. use Drupal\bootstrap\Utility\Crypt;
  7. use Drupal\bootstrap\Utility\Element;
  8. use Drupal\bootstrap\Utility\Unicode;
  9. use Drupal\Component\Render\FormattableMarkup;
  10. use Drupal\Component\Utility\NestedArray;
  11. use Drupal\Core\Extension\ThemeHandlerInterface;
  12. use Drupal\Core\Form\FormStateInterface;
  13. use Drupal\Core\Render\Markup;
  14. use Drupal\Core\Render\RenderContext;
  15. use Drupal\Core\Session\AccountInterface;
  16. use Drupal\Core\StringTranslation\TranslatableMarkup;
  17. use GuzzleHttp\Exception\GuzzleException;
  18. use GuzzleHttp\Psr7\Request;
  19. /**
  20. * The primary class for the Drupal Bootstrap base theme.
  21. *
  22. * Provides many helper methods.
  23. *
  24. * @ingroup utility
  25. */
  26. class Bootstrap {
  27. /**
  28. * Tag used to invalidate caches.
  29. *
  30. * @var string
  31. */
  32. const CACHE_TAG = 'theme_registry';
  33. /**
  34. * Append a callback.
  35. *
  36. * @var int
  37. */
  38. const CALLBACK_APPEND = 1;
  39. /**
  40. * Prepend a callback.
  41. *
  42. * @var int
  43. */
  44. const CALLBACK_PREPEND = 2;
  45. /**
  46. * Replace a callback or append it if not found.
  47. *
  48. * @var int
  49. */
  50. const CALLBACK_REPLACE_APPEND = 3;
  51. /**
  52. * Replace a callback or prepend it if not found.
  53. *
  54. * @var int
  55. */
  56. const CALLBACK_REPLACE_PREPEND = 4;
  57. /**
  58. * The current supported Bootstrap Framework version.
  59. *
  60. * @var string
  61. */
  62. const FRAMEWORK_VERSION = '3.4.1';
  63. /**
  64. * The Bootstrap Framework documentation site.
  65. *
  66. * @var string
  67. */
  68. const FRAMEWORK_HOMEPAGE = 'https://getbootstrap.com/docs/3.4/';
  69. /**
  70. * The Bootstrap Framework repository.
  71. *
  72. * @var string
  73. */
  74. const FRAMEWORK_REPOSITORY = 'https://github.com/twbs/bootstrap';
  75. /**
  76. * The project branch.
  77. *
  78. * @var string
  79. */
  80. const PROJECT_BRANCH = '8.x-3.x';
  81. /**
  82. * The Drupal Bootstrap documentation site.
  83. *
  84. * @var string
  85. */
  86. const PROJECT_DOCUMENTATION = 'https://drupal-bootstrap.org';
  87. /**
  88. * The project API search URL.
  89. *
  90. * @var string
  91. *
  92. * @todo Enable constant once PHP 5.5 is no longer supported.
  93. */
  94. // const PROJECT_API_SEARCH_URL = self::PROJECT_DOCUMENTATION . '/api/bootstrap/' . self::PROJECT_BRANCH . '/search/@query';
  95. /**
  96. * The Drupal Bootstrap project page.
  97. *
  98. * @var string
  99. */
  100. const PROJECT_PAGE = 'https://www.drupal.org/project/bootstrap';
  101. /**
  102. * The Messenger service, if it exists.
  103. *
  104. * @var \Drupal\Core\Messenger\MessengerInterface
  105. */
  106. protected static $messenger;
  107. /**
  108. * The Renderer service.
  109. *
  110. * @var \Drupal\Core\Render\Renderer
  111. */
  112. protected static $renderer;
  113. /**
  114. * The Theme Registry service.
  115. *
  116. * @var \Drupal\Core\Theme\Registry
  117. */
  118. protected static $themeRegistry;
  119. /**
  120. * The Twig service.
  121. *
  122. * @var \Drupal\Core\Template\TwigEnvironment
  123. */
  124. protected static $twig;
  125. /**
  126. * Adds a callback to an array.
  127. *
  128. * @param array $callbacks
  129. * An array of callbacks to add the callback to, passed by reference.
  130. * @param array|string $callback
  131. * The callback to add.
  132. * @param array|string $replace
  133. * If specified, the callback will instead replace the specified value
  134. * instead of being appended to the $callbacks array.
  135. * @param int $action
  136. * Flag that determines how to add the callback to the array.
  137. *
  138. * @return bool
  139. * TRUE if the callback was added, FALSE if $replace was specified but its
  140. * callback could be found in the list of callbacks.
  141. */
  142. public static function addCallback(array &$callbacks, $callback, $replace = NULL, $action = Bootstrap::CALLBACK_APPEND) {
  143. // Replace a callback.
  144. if ($replace) {
  145. // Iterate through the callbacks.
  146. foreach ($callbacks as $key => $value) {
  147. // Convert each callback and match the string values.
  148. if (Unicode::convertCallback($value) === Unicode::convertCallback($replace)) {
  149. $callbacks[$key] = $callback;
  150. return TRUE;
  151. }
  152. }
  153. // No match found and action shouldn't append or prepend.
  154. if ($action !== self::CALLBACK_REPLACE_APPEND || $action !== self::CALLBACK_REPLACE_PREPEND) {
  155. return FALSE;
  156. }
  157. }
  158. // Append or prepend the callback.
  159. switch ($action) {
  160. case self::CALLBACK_APPEND:
  161. case self::CALLBACK_REPLACE_APPEND:
  162. $callbacks[] = $callback;
  163. return TRUE;
  164. case self::CALLBACK_PREPEND:
  165. case self::CALLBACK_REPLACE_PREPEND:
  166. array_unshift($callbacks, $callback);
  167. return TRUE;
  168. default:
  169. return FALSE;
  170. }
  171. }
  172. /**
  173. * Manages theme alter hooks as classes and allows sub-themes to sub-class.
  174. *
  175. * @param string $function
  176. * The procedural function name of the alter (e.g. __FUNCTION__).
  177. * @param mixed $data
  178. * The variable that was passed to the hook_TYPE_alter() implementation to
  179. * be altered. The type of this variable depends on the value of the $type
  180. * argument. For example, when altering a 'form', $data will be a structured
  181. * array. When altering a 'profile', $data will be an object.
  182. * @param mixed $context1
  183. * (optional) An additional variable that is passed by reference.
  184. * @param mixed $context2
  185. * (optional) An additional variable that is passed by reference. If more
  186. * context needs to be provided to implementations, then this should be an
  187. * associative array as described above.
  188. */
  189. public static function alter($function, &$data, &$context1 = NULL, &$context2 = NULL) {
  190. // Do not statically cache this as the active theme may change.
  191. $theme = static::getTheme();
  192. $theme_name = $theme->getName();
  193. // Immediately return if the active theme is not Bootstrap based.
  194. if (!$theme->isBootstrap()) {
  195. return;
  196. }
  197. // Handle alter and form managers.
  198. static $drupal_static_fast;
  199. if (!isset($drupal_static_fast)) {
  200. $drupal_static_fast['alter_managers'] = &drupal_static(__METHOD__ . '__alterManagers', []);
  201. $drupal_static_fast['form_managers'] = &drupal_static(__METHOD__ . '__formManagers', []);
  202. }
  203. /* @var \Drupal\bootstrap\Plugin\AlterManager[] $alter_managers */
  204. $alter_managers = &$drupal_static_fast['alter_managers'];
  205. if (!isset($alter_managers[$theme_name])) {
  206. $alter_managers[$theme_name] = new AlterManager($theme);
  207. }
  208. /* @var \Drupal\bootstrap\Plugin\FormManager[] $form_managers */
  209. $form_managers = &$drupal_static_fast['form_managers'];
  210. if (!isset($form_managers[$theme_name])) {
  211. $form_managers[$theme_name] = new FormManager($theme);
  212. }
  213. // Retrieve the alter and form managers for this theme.
  214. $alter_manager = $alter_managers[$theme_name];
  215. $form_manager = $form_managers[$theme_name];
  216. // Extract the alter hook name.
  217. $hook = Unicode::extractHook($function, 'alter');
  218. // Handle form alters as a separate plugin.
  219. if (strpos($hook, 'form') === 0 && $context1 instanceof FormStateInterface) {
  220. $form_state = $context1;
  221. $form_id = $context2;
  222. // Due to a core bug that affects admin themes, we should not double
  223. // process the "system_theme_settings" form twice in the global
  224. // hook_form_alter() invocation.
  225. // @see https://www.drupal.org/node/943212
  226. if ($form_id === 'system_theme_settings') {
  227. return;
  228. }
  229. // Keep track of the form identifiers.
  230. $ids = [];
  231. // Get the build data.
  232. $build_info = $form_state->getBuildInfo();
  233. // Extract the base_form_id.
  234. $base_form_id = !empty($build_info['base_form_id']) ? $build_info['base_form_id'] : FALSE;
  235. if ($base_form_id) {
  236. $ids[] = $base_form_id;
  237. }
  238. // If there was no provided form identifier, extract it.
  239. if (!$form_id) {
  240. $form_id = !empty($build_info['form_id']) ? $build_info['form_id'] : Unicode::extractHook($function, 'alter', 'form');
  241. }
  242. if ($form_id) {
  243. $ids[] = $form_id;
  244. }
  245. // Iterate over each form identifier and look for a possible plugin.
  246. foreach ($ids as $id) {
  247. /** @var \Drupal\bootstrap\Plugin\Form\FormInterface $form */
  248. if ($form_manager->hasDefinition($id) && ($form = $form_manager->createInstance($id, ['theme' => $theme]))) {
  249. $data['#submit'][] = [get_class($form), 'submitForm'];
  250. $data['#validate'][] = [get_class($form), 'validateForm'];
  251. $form->alterForm($data, $form_state, $form_id);
  252. }
  253. }
  254. }
  255. // Process hook alter normally.
  256. else {
  257. /** @var \Drupal\bootstrap\Plugin\Alter\AlterInterface $class */
  258. if ($alter_manager->hasDefinition($hook) && ($class = $alter_manager->createInstance($hook, ['theme' => $theme]))) {
  259. $class->alter($data, $context1, $context2);
  260. }
  261. }
  262. }
  263. /**
  264. * Returns a documentation search URL for a given query.
  265. *
  266. * @param string $query
  267. * The query to search for.
  268. *
  269. * @return \Drupal\Component\Render\FormattableMarkup
  270. * The complete URL to the documentation site.
  271. */
  272. public static function apiSearchUrl($query = '') {
  273. // @todo Move to a constant once PHP 5.5 is no longer supported.
  274. return new FormattableMarkup(self::PROJECT_DOCUMENTATION . '/api/bootstrap/' . self::PROJECT_BRANCH . '/search/@query', [
  275. '@query' => $query,
  276. ]);
  277. }
  278. /**
  279. * Returns the autoload fix include path.
  280. *
  281. * This method assists class based callbacks that normally do not work.
  282. *
  283. * If you notice that your class based callback is never invoked, you may try
  284. * using this helper method as an "include" or "file" for your callback, if
  285. * the callback metadata supports such an option.
  286. *
  287. * Depending on when or where a callback is invoked during a request, such as
  288. * an ajax or batch request, the theme handler may not yet be fully
  289. * initialized.
  290. *
  291. * Typically there is little that can be done about this "issue" from core.
  292. * It must balance the appropriate level that should be bootstrapped along
  293. * with common functionality. Cross-request class based callbacks are not
  294. * common in themes.
  295. *
  296. * When this file is included, it will attempt to jump start this process.
  297. *
  298. * Please keep in mind, that it is merely an attempt and does not guarantee
  299. * that it will actually work. If it does not appear to work, do not use it.
  300. *
  301. * @see \Drupal\Core\Extension\ThemeHandler::listInfo
  302. * @see \Drupal\Core\Extension\ThemeHandler::systemThemeList
  303. * @see system_list
  304. * @see system_register()
  305. * @see drupal_classloader_register()
  306. *
  307. * @return string
  308. * The autoload fix include path, relative to Drupal root.
  309. */
  310. public static function autoloadFixInclude() {
  311. return static::getTheme('bootstrap')->getPath() . '/autoload-fix.php';
  312. }
  313. /**
  314. * Checks whether a specific URL is reachable.
  315. *
  316. * @param string $url
  317. * The URL to check.
  318. * @param array $options
  319. * Additional options to pass to the HTTP client.
  320. * @param \Exception|null $exception
  321. * Any Exceptions throw, passed by reference.
  322. *
  323. * @return \Drupal\bootstrap\SerializedResponse
  324. * A SerializedResponse object.
  325. */
  326. public static function checkUrlIsReachable($url, array $options = [], &$exception = NULL) {
  327. $options['method'] = 'HEAD';
  328. $options['ttl'] = 0;
  329. return static::request($url, $options, $exception);
  330. }
  331. /**
  332. * Retrieves a response from a URL, using cached response if available.
  333. *
  334. * @param string $url
  335. * The URL to retrieve.
  336. * @param array $options
  337. * The options to pass to the HTTP client.
  338. * @param \Exception|null $exception
  339. * The exception thrown if there was an error, passed by reference.
  340. *
  341. * @return \Drupal\bootstrap\SerializedResponse
  342. * A Response object.
  343. */
  344. public static function request($url, array $options = [], &$exception = NULL) {
  345. $options += [
  346. 'method' => 'GET',
  347. 'headers' => [
  348. 'User-Agent' => 'Drupal Bootstrap ' . static::PROJECT_BRANCH . ' (' . static::PROJECT_PAGE . ')',
  349. ],
  350. ];
  351. // Determine if a custom TTL value was set.
  352. $ttl = isset($options['ttl']) ? $options['ttl'] : NULL;
  353. unset($options['ttl']);
  354. $cache = \Drupal::keyValueExpirable('theme:' . static::getTheme()->getName() . ':http');
  355. // The URL cannot be part of the prefix as the "name" field of
  356. // "key_value_expire" has a max length of 128.
  357. $hash = Crypt::generateBase64HashIdentifier(['url' => $url] + $options, 'request');
  358. $response = $cache->get($hash);
  359. if (!isset($response)) {
  360. /** @var \GuzzleHttp\Client $client */
  361. $client = \Drupal::service('http_client_factory')->fromOptions($options);
  362. $request = new Request($options['method'], $url, $options['headers']);
  363. try {
  364. $response = SerializedResponse::createFromGuzzleResponse($client->send($request, $options), $request);
  365. }
  366. catch (GuzzleException $e) {
  367. $exception = $e;
  368. $response = SerializedResponse::createFromException($e, $request);
  369. }
  370. catch (\Exception $e) {
  371. $exception = $e;
  372. $response = SerializedResponse::createFromException($e, $request);
  373. }
  374. // Only cache if a maximum age has been detected.
  375. $maxAge = (int) isset($ttl) ? $ttl : $response->getMaxAge();
  376. if ($response->getStatusCode() == 200 && $maxAge > 0) {
  377. // Due to key_value_expire setting the "expire" field to "INT(11)", it
  378. // is technically limited to a 32bit max value (Y2K38 bug).
  379. // @todo Remove this once this is no longer an issue.
  380. // @see https://www.drupal.org/project/drupal/issues/65474
  381. // @see https://www.drupal.org/project/drupal/issues/1003692
  382. $requestTime = \Drupal::time()->getRequestTime();
  383. if (($requestTime + $maxAge) > 2147483647) {
  384. $maxAge = 2147483647 - $requestTime;
  385. }
  386. try {
  387. $cache->setWithExpire($hash, $response, $maxAge);
  388. }
  389. catch (\Exception $e) {
  390. // Intentionally do nothing, tried to cache response... it failed.
  391. }
  392. }
  393. }
  394. return $response;
  395. }
  396. /**
  397. * Matches a Bootstrap class based on a string value.
  398. *
  399. * @param string|array $value
  400. * The string to match against to determine the class. Passed by reference
  401. * in case it is a render array that needs to be rendered and typecast.
  402. * @param string $default
  403. * The default class to return if no match is found.
  404. *
  405. * @return string
  406. * The Bootstrap class matched against the value of $haystack or $default
  407. * if no match could be made.
  408. */
  409. public static function cssClassFromString(&$value, $default = '') {
  410. static $lang;
  411. if (!isset($lang)) {
  412. $lang = \Drupal::languageManager()->getCurrentLanguage()->getId();
  413. }
  414. $theme = static::getTheme();
  415. $texts = $theme->getCache('cssClassFromString', [$lang]);
  416. // Ensure it's a string value that was passed.
  417. $string = static::toString($value);
  418. if ($texts->isEmpty()) {
  419. $data = [
  420. // Text that match these specific strings are checked first.
  421. 'matches' => [
  422. // Primary class.
  423. t('Download feature')->render() => 'primary',
  424. // Success class.
  425. t('Add effect')->render() => 'success',
  426. t('Add and configure')->render() => 'success',
  427. t('Save configuration')->render() => 'success',
  428. t('Install and set as default')->render() => 'success',
  429. // Info class.
  430. t('Save and add')->render() => 'info',
  431. t('Add another item')->render() => 'info',
  432. t('Update style')->render() => 'info',
  433. ],
  434. // Text containing these words anywhere in the string are checked last.
  435. 'contains' => [
  436. // Primary class.
  437. t('Confirm')->render() => 'primary',
  438. t('Filter')->render() => 'primary',
  439. t('Log in')->render() => 'primary',
  440. t('Submit')->render() => 'primary',
  441. t('Search')->render() => 'primary',
  442. t('Settings')->render() => 'primary',
  443. t('Upload')->render() => 'primary',
  444. // Danger class.
  445. t('Delete')->render() => 'danger',
  446. t('Remove')->render() => 'danger',
  447. t('Reset')->render() => 'danger',
  448. t('Uninstall')->render() => 'danger',
  449. // Success class.
  450. t('Add')->render() => 'success',
  451. t('Create')->render() => 'success',
  452. t('Install')->render() => 'success',
  453. t('Save')->render() => 'success',
  454. t('Write')->render() => 'success',
  455. // Warning class.
  456. t('Export')->render() => 'warning',
  457. t('Import')->render() => 'warning',
  458. t('Restore')->render() => 'warning',
  459. t('Rebuild')->render() => 'warning',
  460. // Info class.
  461. t('Apply')->render() => 'info',
  462. t('Update')->render() => 'info',
  463. ],
  464. ];
  465. // Allow sub-themes to alter this array of patterns.
  466. /** @var \Drupal\Core\Theme\ThemeManager $theme_manager */
  467. $theme_manager = \Drupal::service('theme.manager');
  468. $theme_manager->alter('bootstrap_colorize_text', $data);
  469. $texts->setMultiple($data);
  470. }
  471. // Iterate over the array.
  472. foreach ($texts as $pattern => $strings) {
  473. foreach ($strings as $text => $class) {
  474. switch ($pattern) {
  475. case 'matches':
  476. if ($string === $text) {
  477. return $class;
  478. }
  479. break;
  480. case 'contains':
  481. if (strpos(Unicode::strtolower($string), Unicode::strtolower($text)) !== FALSE) {
  482. return $class;
  483. }
  484. break;
  485. }
  486. }
  487. }
  488. // Return the default if nothing was matched.
  489. return $default;
  490. }
  491. /**
  492. * Logs and displays a warning about a deprecated function/method being used.
  493. *
  494. * @param string $caller
  495. * Optional. The function or Class::method that should be shown as
  496. * deprecated. If not set, it will be extrapolated automatically from
  497. * the backtrace. This is primarily used when this method is being invoked
  498. * from inside another method that isn't technically deprecated but has to
  499. * support deprecated functionality.
  500. * @param bool $show_message
  501. * Flag indicating whether to show a message to the user. If TRUE, it will
  502. * force show the message. If FALSE, it will only log the message. If not
  503. * set, the message will be shown based on whether the current user is an
  504. * administrator and if the theme has suppressed deprecated warnings.
  505. * @param \Drupal\Core\StringTranslation\TranslatableMarkup $message
  506. * Optional. The message to show/log. If not set, it will be determined
  507. * automatically based on the caller.
  508. */
  509. public static function deprecated($caller = NULL, $show_message = NULL, TranslatableMarkup $message = NULL) {
  510. $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
  511. // Extrapolate the caller.
  512. if (!isset($caller) && !empty($backtrace[1]) && ($info = $backtrace[1])) {
  513. $caller = (!empty($info['class']) ? $info['class'] . '::' : '') . $info['function'];
  514. }
  515. // Remove class namespace.
  516. $method = FALSE;
  517. if (is_string($caller) && strpos($caller, '::') !== FALSE && ($parts = explode('\\', $caller))) {
  518. $method = TRUE;
  519. $caller = array_pop($parts);
  520. }
  521. if (!isset($message)) {
  522. $message = t('The following @type has been deprecated: <a href=":url" target="_blank">@title</a>. Please check the logs for a more detailed backtrace on where it is being invoked.', [
  523. '@type' => $method ? 'method' : 'function',
  524. ':url' => static::apiSearchUrl($caller),
  525. '@title' => $caller,
  526. ]);
  527. }
  528. if ($show_message || (!isset($show_message) && static::isAdmin() && !static::getTheme()->getSetting('suppress_deprecated_warnings', FALSE))) {
  529. static::message($message, 'warning');
  530. }
  531. // Log message and accompanying backtrace.
  532. \Drupal::logger('bootstrap')->warning('<div>@message</div><pre><code>@backtrace</code></pre>', [
  533. '@message' => $message,
  534. '@backtrace' => Markup::create(print_r($backtrace, TRUE)),
  535. ]);
  536. }
  537. /**
  538. * Provides additional variables to be used in elements and templates.
  539. *
  540. * @return array
  541. * An associative array containing key/default value pairs.
  542. */
  543. public static function extraVariables() {
  544. return [
  545. // @see https://www.drupal.org/node/2035055
  546. 'context' => [],
  547. // @see https://www.drupal.org/node/2219965
  548. 'icon' => NULL,
  549. 'icon_position' => 'before',
  550. 'icon_only' => FALSE,
  551. ];
  552. }
  553. /**
  554. * Retrieves a theme instance of \Drupal\bootstrap.
  555. *
  556. * @param string $name
  557. * The machine name of a theme. If omitted, the active theme will be used.
  558. * @param \Drupal\Core\Extension\ThemeHandlerInterface $theme_handler
  559. * The theme handler object.
  560. *
  561. * @return \Drupal\bootstrap\Theme
  562. * A theme object.
  563. */
  564. public static function getTheme($name = NULL, ThemeHandlerInterface $theme_handler = NULL) {
  565. // Immediately return if theme passed is already instantiated.
  566. if ($name instanceof Theme) {
  567. return $name;
  568. }
  569. static $themes = [];
  570. // Retrieve the active theme.
  571. // Do not statically cache this as the active theme may change.
  572. if (!isset($name)) {
  573. $name = \Drupal::theme()->getActiveTheme()->getName();
  574. }
  575. if (!isset($theme_handler)) {
  576. $theme_handler = self::getThemeHandler();
  577. }
  578. if (!isset($themes[$name])) {
  579. $themes[$name] = new Theme($theme_handler->getTheme($name), $theme_handler);
  580. }
  581. return $themes[$name];
  582. }
  583. /**
  584. * Retrieves the theme handler instance.
  585. *
  586. * @return \Drupal\Core\Extension\ThemeHandlerInterface
  587. * The theme handler instance.
  588. */
  589. public static function getThemeHandler() {
  590. static $theme_handler;
  591. if (!isset($theme_handler)) {
  592. $theme_handler = \Drupal::service('theme_handler');
  593. }
  594. return $theme_handler;
  595. }
  596. /**
  597. * Returns the theme hook definition information.
  598. *
  599. * This base-theme's custom theme hook implementations. Never define "path"
  600. * as this is automatically detected and added.
  601. *
  602. * @see \Drupal\bootstrap\Plugin\Alter\ThemeRegistry::alter()
  603. * @see bootstrap_theme_registry_alter()
  604. * @see bootstrap_theme()
  605. * @see hook_theme()
  606. */
  607. public static function getThemeHooks() {
  608. $hooks['bootstrap_carousel'] = [
  609. 'variables' => [
  610. 'attributes' => [],
  611. 'controls' => TRUE,
  612. 'id' => NULL,
  613. 'indicators' => TRUE,
  614. 'interval' => 5000,
  615. 'pause' => 'hover',
  616. 'slides' => [],
  617. 'start_index' => 0,
  618. 'wrap' => TRUE,
  619. ],
  620. ];
  621. $hooks['bootstrap_dropdown'] = [
  622. 'variables' => [
  623. 'alignment' => 'down',
  624. 'attributes' => [],
  625. 'items' => [],
  626. 'split' => FALSE,
  627. 'toggle' => NULL,
  628. ],
  629. ];
  630. $hooks['bootstrap_modal'] = [
  631. 'variables' => [
  632. 'attributes' => [],
  633. 'body' => '',
  634. 'body_attributes' => [],
  635. 'close_button' => TRUE,
  636. 'content_attributes' => [],
  637. 'description' => NULL,
  638. 'description_display' => 'before',
  639. 'dialog_attributes' => [],
  640. 'footer' => '',
  641. 'footer_attributes' => [],
  642. 'header_attributes' => [],
  643. 'id' => NULL,
  644. 'size' => NULL,
  645. 'title' => '',
  646. 'title_attributes' => [],
  647. ],
  648. ];
  649. $hooks['bootstrap_panel'] = [
  650. 'variables' => [
  651. 'attributes' => [],
  652. 'body' => [],
  653. 'body_attributes' => [],
  654. 'collapsible' => FALSE,
  655. 'collapsed' => FALSE,
  656. 'description' => NULL,
  657. 'description_display' => 'before',
  658. 'footer' => NULL,
  659. 'footer_attributes' => [],
  660. 'heading' => NULL,
  661. 'heading_attributes' => [],
  662. 'id' => NULL,
  663. 'panel_type' => 'default',
  664. ],
  665. ];
  666. return $hooks;
  667. }
  668. /**
  669. * Returns a specific Bootstrap Glyphicon.
  670. *
  671. * @param string $name
  672. * The icon name, minus the "glyphicon-" prefix.
  673. * @param array $default
  674. * (Optional) The default render array to use if $name is not available.
  675. *
  676. * @return array
  677. * The render containing the icon defined by $name, $default value if
  678. * icon does not exist or returns NULL if no icon could be rendered.
  679. */
  680. public static function glyphicon($name, array $default = []) {
  681. $icon = [];
  682. // Ensure the icon specified is a valid Bootstrap Glyphicon.
  683. // @todo Supply a specific version to _bootstrap_glyphicons() when Icon API
  684. // supports versioning.
  685. if (self::getTheme()->hasGlyphicons() && in_array($name, self::glyphicons())) {
  686. // Attempt to use the Icon API module, if enabled and it generates output.
  687. if (\Drupal::moduleHandler()->moduleExists('icon')) {
  688. $icon = [
  689. '#type' => 'icon',
  690. '#bundle' => 'bootstrap',
  691. '#icon' => 'glyphicon-' . $name,
  692. ];
  693. }
  694. else {
  695. $icon = [
  696. '#type' => 'html_tag',
  697. '#tag' => 'span',
  698. '#value' => '',
  699. '#attributes' => [
  700. 'class' => ['icon', 'glyphicon', 'glyphicon-' . $name],
  701. 'aria-hidden' => 'true',
  702. ],
  703. ];
  704. }
  705. }
  706. return $icon ?: $default;
  707. }
  708. /**
  709. * Matches a Bootstrap Glyphicon based on a string value.
  710. *
  711. * @param string $value
  712. * The string to match against to determine the icon. Passed by reference
  713. * in case it is a render array that needs to be rendered and typecast.
  714. * @param array $default
  715. * The default render array to return if no match is found.
  716. *
  717. * @return array
  718. * The Bootstrap icon matched against the value of $haystack or $default if
  719. * no match could be made.
  720. */
  721. public static function glyphiconFromString(&$value, array $default = []) {
  722. static $lang;
  723. if (!isset($lang)) {
  724. $lang = \Drupal::languageManager()->getCurrentLanguage()->getId();
  725. }
  726. $theme = static::getTheme();
  727. $texts = $theme->getCache('glyphiconFromString', [$lang]);
  728. // Ensure it's a string value that was passed.
  729. $string = static::toString($value);
  730. if ($texts->isEmpty()) {
  731. $data = [
  732. // Text that match these specific strings are checked first.
  733. 'matches' => [],
  734. // Text containing these words anywhere in the string are checked last.
  735. 'contains' => [
  736. t('Manage')->render() => 'cog',
  737. t('Configure')->render() => 'cog',
  738. t('Settings')->render() => 'cog',
  739. t('Download')->render() => 'download',
  740. t('Export')->render() => 'export',
  741. t('Filter')->render() => 'filter',
  742. t('Import')->render() => 'import',
  743. t('Save')->render() => 'ok',
  744. t('Update')->render() => 'ok',
  745. t('Edit')->render() => 'pencil',
  746. t('Uninstall')->render() => 'trash',
  747. t('Install')->render() => 'plus',
  748. t('Write')->render() => 'plus',
  749. t('Cancel')->render() => 'remove',
  750. t('Delete')->render() => 'trash',
  751. t('Remove')->render() => 'trash',
  752. t('Reset')->render() => 'trash',
  753. t('Search')->render() => 'search',
  754. t('Upload')->render() => 'upload',
  755. t('Preview')->render() => 'eye-open',
  756. t('Log in')->render() => 'log-in',
  757. ],
  758. ];
  759. // Allow sub-themes to alter this array of patterns.
  760. /** @var \Drupal\Core\Theme\ThemeManager $theme_manager */
  761. $theme_manager = \Drupal::service('theme.manager');
  762. $theme_manager->alter('bootstrap_iconize_text', $data);
  763. $texts->setMultiple($data);
  764. }
  765. // Iterate over the array.
  766. foreach ($texts as $pattern => $strings) {
  767. foreach ($strings as $text => $icon) {
  768. switch ($pattern) {
  769. case 'matches':
  770. if ($string === $text) {
  771. return self::glyphicon($icon, $default);
  772. }
  773. break;
  774. case 'contains':
  775. if (strpos(Unicode::strtolower($string), Unicode::strtolower($text)) !== FALSE) {
  776. return self::glyphicon($icon, $default);
  777. }
  778. break;
  779. }
  780. }
  781. }
  782. // Return a default icon if nothing was matched.
  783. return $default;
  784. }
  785. /**
  786. * Returns a list of available Bootstrap Framework Glyphicons.
  787. *
  788. * @param string $version
  789. * The specific version of glyphicons to return. If not set, the latest
  790. * BOOTSTRAP_VERSION will be used.
  791. *
  792. * @return array
  793. * An associative array of icons keyed by their classes.
  794. */
  795. public static function glyphicons($version = NULL) {
  796. static $versions;
  797. if (!isset($versions)) {
  798. $versions = [];
  799. $versions['3.0.0'] = [
  800. // Class => Name.
  801. 'glyphicon-adjust' => 'adjust',
  802. 'glyphicon-align-center' => 'align-center',
  803. 'glyphicon-align-justify' => 'align-justify',
  804. 'glyphicon-align-left' => 'align-left',
  805. 'glyphicon-align-right' => 'align-right',
  806. 'glyphicon-arrow-down' => 'arrow-down',
  807. 'glyphicon-arrow-left' => 'arrow-left',
  808. 'glyphicon-arrow-right' => 'arrow-right',
  809. 'glyphicon-arrow-up' => 'arrow-up',
  810. 'glyphicon-asterisk' => 'asterisk',
  811. 'glyphicon-backward' => 'backward',
  812. 'glyphicon-ban-circle' => 'ban-circle',
  813. 'glyphicon-barcode' => 'barcode',
  814. 'glyphicon-bell' => 'bell',
  815. 'glyphicon-bold' => 'bold',
  816. 'glyphicon-book' => 'book',
  817. 'glyphicon-bookmark' => 'bookmark',
  818. 'glyphicon-briefcase' => 'briefcase',
  819. 'glyphicon-bullhorn' => 'bullhorn',
  820. 'glyphicon-calendar' => 'calendar',
  821. 'glyphicon-camera' => 'camera',
  822. 'glyphicon-certificate' => 'certificate',
  823. 'glyphicon-check' => 'check',
  824. 'glyphicon-chevron-down' => 'chevron-down',
  825. 'glyphicon-chevron-left' => 'chevron-left',
  826. 'glyphicon-chevron-right' => 'chevron-right',
  827. 'glyphicon-chevron-up' => 'chevron-up',
  828. 'glyphicon-circle-arrow-down' => 'circle-arrow-down',
  829. 'glyphicon-circle-arrow-left' => 'circle-arrow-left',
  830. 'glyphicon-circle-arrow-right' => 'circle-arrow-right',
  831. 'glyphicon-circle-arrow-up' => 'circle-arrow-up',
  832. 'glyphicon-cloud' => 'cloud',
  833. 'glyphicon-cloud-download' => 'cloud-download',
  834. 'glyphicon-cloud-upload' => 'cloud-upload',
  835. 'glyphicon-cog' => 'cog',
  836. 'glyphicon-collapse-down' => 'collapse-down',
  837. 'glyphicon-collapse-up' => 'collapse-up',
  838. 'glyphicon-comment' => 'comment',
  839. 'glyphicon-compressed' => 'compressed',
  840. 'glyphicon-copyright-mark' => 'copyright-mark',
  841. 'glyphicon-credit-card' => 'credit-card',
  842. 'glyphicon-cutlery' => 'cutlery',
  843. 'glyphicon-dashboard' => 'dashboard',
  844. 'glyphicon-download' => 'download',
  845. 'glyphicon-download-alt' => 'download-alt',
  846. 'glyphicon-earphone' => 'earphone',
  847. 'glyphicon-edit' => 'edit',
  848. 'glyphicon-eject' => 'eject',
  849. 'glyphicon-envelope' => 'envelope',
  850. 'glyphicon-euro' => 'euro',
  851. 'glyphicon-exclamation-sign' => 'exclamation-sign',
  852. 'glyphicon-expand' => 'expand',
  853. 'glyphicon-export' => 'export',
  854. 'glyphicon-eye-close' => 'eye-close',
  855. 'glyphicon-eye-open' => 'eye-open',
  856. 'glyphicon-facetime-video' => 'facetime-video',
  857. 'glyphicon-fast-backward' => 'fast-backward',
  858. 'glyphicon-fast-forward' => 'fast-forward',
  859. 'glyphicon-file' => 'file',
  860. 'glyphicon-film' => 'film',
  861. 'glyphicon-filter' => 'filter',
  862. 'glyphicon-fire' => 'fire',
  863. 'glyphicon-flag' => 'flag',
  864. 'glyphicon-flash' => 'flash',
  865. 'glyphicon-floppy-disk' => 'floppy-disk',
  866. 'glyphicon-floppy-open' => 'floppy-open',
  867. 'glyphicon-floppy-remove' => 'floppy-remove',
  868. 'glyphicon-floppy-save' => 'floppy-save',
  869. 'glyphicon-floppy-saved' => 'floppy-saved',
  870. 'glyphicon-folder-close' => 'folder-close',
  871. 'glyphicon-folder-open' => 'folder-open',
  872. 'glyphicon-font' => 'font',
  873. 'glyphicon-forward' => 'forward',
  874. 'glyphicon-fullscreen' => 'fullscreen',
  875. 'glyphicon-gbp' => 'gbp',
  876. 'glyphicon-gift' => 'gift',
  877. 'glyphicon-glass' => 'glass',
  878. 'glyphicon-globe' => 'globe',
  879. 'glyphicon-hand-down' => 'hand-down',
  880. 'glyphicon-hand-left' => 'hand-left',
  881. 'glyphicon-hand-right' => 'hand-right',
  882. 'glyphicon-hand-up' => 'hand-up',
  883. 'glyphicon-hd-video' => 'hd-video',
  884. 'glyphicon-hdd' => 'hdd',
  885. 'glyphicon-header' => 'header',
  886. 'glyphicon-headphones' => 'headphones',
  887. 'glyphicon-heart' => 'heart',
  888. 'glyphicon-heart-empty' => 'heart-empty',
  889. 'glyphicon-home' => 'home',
  890. 'glyphicon-import' => 'import',
  891. 'glyphicon-inbox' => 'inbox',
  892. 'glyphicon-indent-left' => 'indent-left',
  893. 'glyphicon-indent-right' => 'indent-right',
  894. 'glyphicon-info-sign' => 'info-sign',
  895. 'glyphicon-italic' => 'italic',
  896. 'glyphicon-leaf' => 'leaf',
  897. 'glyphicon-link' => 'link',
  898. 'glyphicon-list' => 'list',
  899. 'glyphicon-list-alt' => 'list-alt',
  900. 'glyphicon-lock' => 'lock',
  901. 'glyphicon-log-in' => 'log-in',
  902. 'glyphicon-log-out' => 'log-out',
  903. 'glyphicon-magnet' => 'magnet',
  904. 'glyphicon-map-marker' => 'map-marker',
  905. 'glyphicon-minus' => 'minus',
  906. 'glyphicon-minus-sign' => 'minus-sign',
  907. 'glyphicon-move' => 'move',
  908. 'glyphicon-music' => 'music',
  909. 'glyphicon-new-window' => 'new-window',
  910. 'glyphicon-off' => 'off',
  911. 'glyphicon-ok' => 'ok',
  912. 'glyphicon-ok-circle' => 'ok-circle',
  913. 'glyphicon-ok-sign' => 'ok-sign',
  914. 'glyphicon-open' => 'open',
  915. 'glyphicon-paperclip' => 'paperclip',
  916. 'glyphicon-pause' => 'pause',
  917. 'glyphicon-pencil' => 'pencil',
  918. 'glyphicon-phone' => 'phone',
  919. 'glyphicon-phone-alt' => 'phone-alt',
  920. 'glyphicon-picture' => 'picture',
  921. 'glyphicon-plane' => 'plane',
  922. 'glyphicon-play' => 'play',
  923. 'glyphicon-play-circle' => 'play-circle',
  924. 'glyphicon-plus' => 'plus',
  925. 'glyphicon-plus-sign' => 'plus-sign',
  926. 'glyphicon-print' => 'print',
  927. 'glyphicon-pushpin' => 'pushpin',
  928. 'glyphicon-qrcode' => 'qrcode',
  929. 'glyphicon-question-sign' => 'question-sign',
  930. 'glyphicon-random' => 'random',
  931. 'glyphicon-record' => 'record',
  932. 'glyphicon-refresh' => 'refresh',
  933. 'glyphicon-registration-mark' => 'registration-mark',
  934. 'glyphicon-remove' => 'remove',
  935. 'glyphicon-remove-circle' => 'remove-circle',
  936. 'glyphicon-remove-sign' => 'remove-sign',
  937. 'glyphicon-repeat' => 'repeat',
  938. 'glyphicon-resize-full' => 'resize-full',
  939. 'glyphicon-resize-horizontal' => 'resize-horizontal',
  940. 'glyphicon-resize-small' => 'resize-small',
  941. 'glyphicon-resize-vertical' => 'resize-vertical',
  942. 'glyphicon-retweet' => 'retweet',
  943. 'glyphicon-road' => 'road',
  944. 'glyphicon-save' => 'save',
  945. 'glyphicon-saved' => 'saved',
  946. 'glyphicon-screenshot' => 'screenshot',
  947. 'glyphicon-sd-video' => 'sd-video',
  948. 'glyphicon-search' => 'search',
  949. 'glyphicon-send' => 'send',
  950. 'glyphicon-share' => 'share',
  951. 'glyphicon-share-alt' => 'share-alt',
  952. 'glyphicon-shopping-cart' => 'shopping-cart',
  953. 'glyphicon-signal' => 'signal',
  954. 'glyphicon-sort' => 'sort',
  955. 'glyphicon-sort-by-alphabet' => 'sort-by-alphabet',
  956. 'glyphicon-sort-by-alphabet-alt' => 'sort-by-alphabet-alt',
  957. 'glyphicon-sort-by-attributes' => 'sort-by-attributes',
  958. 'glyphicon-sort-by-attributes-alt' => 'sort-by-attributes-alt',
  959. 'glyphicon-sort-by-order' => 'sort-by-order',
  960. 'glyphicon-sort-by-order-alt' => 'sort-by-order-alt',
  961. 'glyphicon-sound-5-1' => 'sound-5-1',
  962. 'glyphicon-sound-6-1' => 'sound-6-1',
  963. 'glyphicon-sound-7-1' => 'sound-7-1',
  964. 'glyphicon-sound-dolby' => 'sound-dolby',
  965. 'glyphicon-sound-stereo' => 'sound-stereo',
  966. 'glyphicon-star' => 'star',
  967. 'glyphicon-star-empty' => 'star-empty',
  968. 'glyphicon-stats' => 'stats',
  969. 'glyphicon-step-backward' => 'step-backward',
  970. 'glyphicon-step-forward' => 'step-forward',
  971. 'glyphicon-stop' => 'stop',
  972. 'glyphicon-subtitles' => 'subtitles',
  973. 'glyphicon-tag' => 'tag',
  974. 'glyphicon-tags' => 'tags',
  975. 'glyphicon-tasks' => 'tasks',
  976. 'glyphicon-text-height' => 'text-height',
  977. 'glyphicon-text-width' => 'text-width',
  978. 'glyphicon-th' => 'th',
  979. 'glyphicon-th-large' => 'th-large',
  980. 'glyphicon-th-list' => 'th-list',
  981. 'glyphicon-thumbs-down' => 'thumbs-down',
  982. 'glyphicon-thumbs-up' => 'thumbs-up',
  983. 'glyphicon-time' => 'time',
  984. 'glyphicon-tint' => 'tint',
  985. 'glyphicon-tower' => 'tower',
  986. 'glyphicon-transfer' => 'transfer',
  987. 'glyphicon-trash' => 'trash',
  988. 'glyphicon-tree-conifer' => 'tree-conifer',
  989. 'glyphicon-tree-deciduous' => 'tree-deciduous',
  990. 'glyphicon-unchecked' => 'unchecked',
  991. 'glyphicon-upload' => 'upload',
  992. 'glyphicon-usd' => 'usd',
  993. 'glyphicon-user' => 'user',
  994. 'glyphicon-volume-down' => 'volume-down',
  995. 'glyphicon-volume-off' => 'volume-off',
  996. 'glyphicon-volume-up' => 'volume-up',
  997. 'glyphicon-warning-sign' => 'warning-sign',
  998. 'glyphicon-wrench' => 'wrench',
  999. 'glyphicon-zoom-in' => 'zoom-in',
  1000. 'glyphicon-zoom-out' => 'zoom-out',
  1001. ];
  1002. $versions['3.0.1'] = $versions['3.0.0'];
  1003. $versions['3.0.2'] = $versions['3.0.1'];
  1004. $versions['3.0.3'] = $versions['3.0.2'];
  1005. $versions['3.1.0'] = $versions['3.0.3'];
  1006. $versions['3.1.1'] = $versions['3.1.0'];
  1007. $versions['3.2.0'] = $versions['3.1.1'];
  1008. $versions['3.3.0'] = array_merge($versions['3.2.0'], [
  1009. 'glyphicon-eur' => 'eur',
  1010. ]);
  1011. $versions['3.3.1'] = $versions['3.3.0'];
  1012. $versions['3.3.2'] = array_merge($versions['3.3.1'], [
  1013. 'glyphicon-alert' => 'alert',
  1014. 'glyphicon-apple' => 'apple',
  1015. 'glyphicon-baby-formula' => 'baby-formula',
  1016. 'glyphicon-bed' => 'bed',
  1017. 'glyphicon-bishop' => 'bishop',
  1018. 'glyphicon-bitcoin' => 'bitcoin',
  1019. 'glyphicon-blackboard' => 'blackboard',
  1020. 'glyphicon-cd' => 'cd',
  1021. 'glyphicon-console' => 'console',
  1022. 'glyphicon-copy' => 'copy',
  1023. 'glyphicon-duplicate' => 'duplicate',
  1024. 'glyphicon-education' => 'education',
  1025. 'glyphicon-equalizer' => 'equalizer',
  1026. 'glyphicon-erase' => 'erase',
  1027. 'glyphicon-grain' => 'grain',
  1028. 'glyphicon-hourglass' => 'hourglass',
  1029. 'glyphicon-ice-lolly' => 'ice-lolly',
  1030. 'glyphicon-ice-lolly-tasted' => 'ice-lolly-tasted',
  1031. 'glyphicon-king' => 'king',
  1032. 'glyphicon-knight' => 'knight',
  1033. 'glyphicon-lamp' => 'lamp',
  1034. 'glyphicon-level-up' => 'level-up',
  1035. 'glyphicon-menu-down' => 'menu-down',
  1036. 'glyphicon-menu-hamburger' => 'menu-hamburger',
  1037. 'glyphicon-menu-left' => 'menu-left',
  1038. 'glyphicon-menu-right' => 'menu-right',
  1039. 'glyphicon-menu-up' => 'menu-up',
  1040. 'glyphicon-modal-window' => 'modal-window',
  1041. 'glyphicon-object-align-bottom' => 'object-align-bottom',
  1042. 'glyphicon-object-align-horizontal' => 'object-align-horizontal',
  1043. 'glyphicon-object-align-left' => 'object-align-left',
  1044. 'glyphicon-object-align-right' => 'object-align-right',
  1045. 'glyphicon-object-align-top' => 'object-align-top',
  1046. 'glyphicon-object-align-vertical' => 'object-align-vertical',
  1047. 'glyphicon-oil' => 'oil',
  1048. 'glyphicon-open-file' => 'open-file',
  1049. 'glyphicon-option-horizontal' => 'option-horizontal',
  1050. 'glyphicon-option-vertical' => 'option-vertical',
  1051. 'glyphicon-paste' => 'paste',
  1052. 'glyphicon-pawn' => 'pawn',
  1053. 'glyphicon-piggy-bank' => 'piggy-bank',
  1054. 'glyphicon-queen' => 'queen',
  1055. 'glyphicon-ruble' => 'ruble',
  1056. 'glyphicon-save-file' => 'save-file',
  1057. 'glyphicon-scale' => 'scale',
  1058. 'glyphicon-scissors' => 'scissors',
  1059. 'glyphicon-subscript' => 'subscript',
  1060. 'glyphicon-sunglasses' => 'sunglasses',
  1061. 'glyphicon-superscript' => 'superscript',
  1062. 'glyphicon-tent' => 'tent',
  1063. 'glyphicon-text-background' => 'text-background',
  1064. 'glyphicon-text-color' => 'text-color',
  1065. 'glyphicon-text-size' => 'text-size',
  1066. 'glyphicon-triangle-bottom' => 'triangle-bottom',
  1067. 'glyphicon-triangle-left' => 'triangle-left',
  1068. 'glyphicon-triangle-right' => 'triangle-right',
  1069. 'glyphicon-triangle-top' => 'triangle-top',
  1070. 'glyphicon-yen' => 'yen',
  1071. ]);
  1072. $versions['3.3.4'] = array_merge($versions['3.3.2'], [
  1073. 'glyphicon-btc' => 'btc',
  1074. 'glyphicon-jpy' => 'jpy',
  1075. 'glyphicon-rub' => 'rub',
  1076. 'glyphicon-xbt' => 'xbt',
  1077. ]);
  1078. $versions['3.3.5'] = $versions['3.3.4'];
  1079. $versions['3.3.6'] = $versions['3.3.5'];
  1080. $versions['3.3.7'] = $versions['3.3.6'];
  1081. $versions['3.4.0'] = $versions['3.3.7'];
  1082. $versions['3.4.1'] = $versions['3.4.0'];
  1083. }
  1084. // Return a specific versions icon set.
  1085. if (isset($version) && isset($versions[$version])) {
  1086. return $versions[$version];
  1087. }
  1088. // Return the latest version.
  1089. return $versions[self::FRAMEWORK_VERSION];
  1090. }
  1091. /**
  1092. * Determines if the "cache_context.url.path.is_front" service exists.
  1093. *
  1094. * @return bool
  1095. * TRUE or FALSE
  1096. *
  1097. * @see \Drupal\bootstrap\Bootstrap::isFront
  1098. * @see \Drupal\bootstrap\Bootstrap::preprocess
  1099. * @see https://www.drupal.org/node/2829588
  1100. */
  1101. public static function hasIsFrontCacheContext() {
  1102. static $has_is_front_cache_context;
  1103. if (!isset($has_is_front_cache_context)) {
  1104. $has_is_front_cache_context = \Drupal::getContainer()->has('cache_context.url.path.is_front');
  1105. }
  1106. return $has_is_front_cache_context;
  1107. }
  1108. /**
  1109. * Initializes the active theme.
  1110. */
  1111. final public static function initialize() {
  1112. static $initialized = FALSE;
  1113. if (!$initialized) {
  1114. // Initialize the active theme.
  1115. $active_theme = self::getTheme();
  1116. // Include deprecated functions.
  1117. foreach ($active_theme->getAncestry() as $ancestor) {
  1118. if ($ancestor->getSetting('include_deprecated')) {
  1119. $files = $ancestor->fileScan('/^deprecated\.php$/');
  1120. if ($file = reset($files)) {
  1121. $ancestor->includeOnce($file->uri, FALSE);
  1122. }
  1123. }
  1124. }
  1125. $initialized = TRUE;
  1126. }
  1127. }
  1128. /**
  1129. * Checks whether a user is an administrator.
  1130. *
  1131. * @param \Drupal\Core\Session\AccountInterface $account
  1132. * Optional. A specific account to check. If not set, the currently logged
  1133. * in user account will be used.
  1134. *
  1135. * @return bool
  1136. * TRUE or FALSE
  1137. */
  1138. public static function isAdmin(AccountInterface $account = NULL) {
  1139. static $admins = [];
  1140. // Use the currently logged in user if no account was explicitly specified.
  1141. if (!$account) {
  1142. $account = \Drupal::currentUser();
  1143. }
  1144. $id = (int) $account->id();
  1145. if (!isset($admins[$id])) {
  1146. $admins[$id] = $account->hasPermission('access administration pages');
  1147. }
  1148. return $admins[$id];
  1149. }
  1150. /**
  1151. * Determines if the current path is the "front" page.
  1152. *
  1153. * *Note:* This method will not return `TRUE` if there is not a proper
  1154. * "cache_context.url.path.is_front" service defined.
  1155. *
  1156. * *Note:* If using this method in preprocess/render array logic, the proper
  1157. * #cache context must also be defined:
  1158. *
  1159. * ```php
  1160. * $variables['#cache']['contexts'][] = 'url.path.is_front';
  1161. * ```
  1162. *
  1163. * @return bool
  1164. * TRUE or FALSE
  1165. *
  1166. * @see \Drupal\bootstrap\Bootstrap::hasIsFrontCacheContext
  1167. * @see \Drupal\bootstrap\Bootstrap::preprocess
  1168. * @see https://www.drupal.org/node/2829588
  1169. */
  1170. public static function isFront() {
  1171. static $is_front;
  1172. if (!isset($is_front)) {
  1173. try {
  1174. $is_front = static::hasIsFrontCacheContext() ? \Drupal::service('path.matcher')->isFrontPage() : FALSE;
  1175. }
  1176. catch (\Exception $e) {
  1177. $is_front = FALSE;
  1178. }
  1179. }
  1180. return $is_front;
  1181. }
  1182. /**
  1183. * Wrapper to use new Messenger service or the legacy procedural function.
  1184. *
  1185. * This is to help support older installations without trigger deprecation
  1186. * notices for newer installations.
  1187. *
  1188. * @param string|\Drupal\Component\Render\MarkupInterface $message
  1189. * (optional) The translated message to be displayed to the user. For
  1190. * consistency with other messages, it should begin with a capital letter
  1191. * and end with a period.
  1192. * @param string $type
  1193. * (optional) The message's type. Defaults to 'status'. These values are
  1194. * supported:
  1195. * - 'status'
  1196. * - 'warning'
  1197. * - 'error'
  1198. * @param bool $repeat
  1199. * (optional) If this is FALSE and the message is already set, then the
  1200. * message won't be repeated. Defaults to FALSE.
  1201. *
  1202. * @see \Drupal\Core\Messenger\MessengerInterface
  1203. * @see drupal_set_message()
  1204. * @see https://www.drupal.org/node/2774931
  1205. *
  1206. * @deprecated in 8.x-3.18 and will be removed in a future release.
  1207. * Use \Drupal\Core\Messenger\MessengerInterface::addMessage() instead.
  1208. */
  1209. public static function message($message, $type = 'status', $repeat = FALSE) {
  1210. if (!isset(static::$messenger)) {
  1211. static::$messenger = \Drupal::hasService('messenger') ? \Drupal::service('messenger') : FALSE;
  1212. }
  1213. if (static::$messenger) {
  1214. static::$messenger->addMessage($message, $type, $repeat);
  1215. }
  1216. else {
  1217. drupal_set_message($message, $type, $repeat);
  1218. }
  1219. }
  1220. /**
  1221. * Preprocess theme hook variables.
  1222. *
  1223. * @param array $variables
  1224. * The variables array, passed by reference.
  1225. * @param string $hook
  1226. * The name of the theme hook.
  1227. * @param array $info
  1228. * The theme hook info.
  1229. */
  1230. public static function preprocess(array &$variables, $hook, array $info) {
  1231. // Do not statically cache this as the active theme may change.
  1232. $theme = static::getTheme();
  1233. $theme_name = $theme->getName();
  1234. // Handle preprocess managers.
  1235. static $drupal_static_fast;
  1236. if (!isset($drupal_static_fast)) {
  1237. $drupal_static_fast['preprocess_managers'] = &drupal_static(__METHOD__ . '__preprocessManagers', []);
  1238. $drupal_static_fast['theme_info'] = &drupal_static(__METHOD__ . '__themeInfo', []);
  1239. }
  1240. /* @var \Drupal\bootstrap\Plugin\PreprocessManager[] $preprocess_managers */
  1241. $preprocess_managers = &$drupal_static_fast['preprocess_managers'];
  1242. if (!isset($preprocess_managers[$theme_name])) {
  1243. $preprocess_managers[$theme_name] = new PreprocessManager($theme);
  1244. }
  1245. // Retrieve the theme info that will be used in the variables.
  1246. $theme_info = &$drupal_static_fast['theme_info'];
  1247. if (!isset($theme_info[$theme_name])) {
  1248. $theme_info[$theme_name] = $theme->getInfo();
  1249. $theme_info[$theme_name]['dev'] = $theme->isDev();
  1250. $theme_info[$theme_name]['livereload'] = $theme->livereloadUrl();
  1251. $theme_info[$theme_name]['name'] = $theme->getName();
  1252. $theme_info[$theme_name]['path'] = $theme->getPath();
  1253. $theme_info[$theme_name]['title'] = $theme->getTitle();
  1254. $theme_info[$theme_name]['settings'] = $theme->settings()->get();
  1255. $theme_info[$theme_name]['has_glyphicons'] = $theme->hasGlyphicons();
  1256. $theme_info[$theme_name]['query_string'] = \Drupal::getContainer()->get('state')->get('system.css_js_query_string') ?: '0';
  1257. }
  1258. // Retrieve the preprocess manager for this theme.
  1259. $preprocess_manager = $preprocess_managers[$theme_name];
  1260. // Add a global "is_admin" variable back to all templates.
  1261. if (!isset($variables['is_admin'])) {
  1262. $variables['is_admin'] = static::isAdmin();
  1263. }
  1264. // Adds a global "is_front" variable back to all templates.
  1265. // @see https://www.drupal.org/node/2829585
  1266. if (!isset($variables['is_front'])) {
  1267. $variables['is_front'] = static::isFront();
  1268. if (static::hasIsFrontCacheContext()) {
  1269. $variables['#cache']['contexts'][] = 'url.path.is_front';
  1270. }
  1271. }
  1272. // Ensure that any default theme hook variables exist. Due to how theme
  1273. // hook suggestion alters work, the variables provided are from the
  1274. // original theme hook, not the suggestion.
  1275. if (isset($info['variables'])) {
  1276. $variables = NestedArray::mergeDeepArray([$info['variables'], $variables], TRUE);
  1277. }
  1278. // Add active theme context.
  1279. // @see https://www.drupal.org/node/2630870
  1280. if (!isset($variables['theme'])) {
  1281. $variables['theme'] = $theme_info[$theme_name];
  1282. }
  1283. // Invoke necessary preprocess plugin.
  1284. if (isset($info['bootstrap preprocess'])) {
  1285. if ($preprocess_manager->hasDefinition($info['bootstrap preprocess'])) {
  1286. $class = $preprocess_manager->createInstance($info['bootstrap preprocess'], ['theme' => $theme]);
  1287. /** @var \Drupal\bootstrap\Plugin\Preprocess\PreprocessInterface $class */
  1288. $class->preprocess($variables, $hook, $info);
  1289. }
  1290. }
  1291. }
  1292. /**
  1293. * Renders a custom Twig template not registered in the theme system.
  1294. *
  1295. * Note: any template ending in .html.twig will be registered with the theme
  1296. * system automatically (that is simply how it works). For HTML based
  1297. * standalone Twig templates, just use .twig (without the .html prefix). For
  1298. * other file types, you may still use a prefix for the IDE to recognize the
  1299. * file type (e.g. .css.twig).
  1300. *
  1301. * @param string $path
  1302. * The path to the template.
  1303. * @param array $variables
  1304. * The variables to pass to the template.
  1305. * @param \Drupal\Core\Render\RenderContext $renderContext
  1306. * Optional. A RenderContext object to pass to the renderer.
  1307. *
  1308. * @return \Drupal\Component\Render\MarkupInterface
  1309. * The rendered template.
  1310. *
  1311. * @throws \RuntimeException
  1312. * If $path does not exist.
  1313. * @throws \InvalidArgumentException
  1314. * If $path references a Twig template already registered in the theme
  1315. * system.
  1316. */
  1317. public static function renderCustomTemplate($path, array $variables = [], RenderContext $renderContext = NULL) {
  1318. $realpath = realpath($path);
  1319. if (!file_exists($realpath)) {
  1320. throw new \RuntimeException(sprintf('Template does not exist: %s', $realpath));
  1321. }
  1322. // Ensure provided template isn't actually registered in the theme system.
  1323. $registry = static::themeRegistry()->get();
  1324. foreach ($registry as $hook => $info) {
  1325. // Only process template based theme hooks.
  1326. if (!isset($info['path']) || !isset($info['template'])) {
  1327. continue;
  1328. }
  1329. $registered = realpath($info['path'] . '/' . $info['template'] . '.html.twig');
  1330. if ($registered === $realpath) {
  1331. $basename = basename($path);
  1332. $example = "\n\n\$build = [\n '#theme' => '$hook',\n /* Other properties */\n];\n\Drupal::service('renderer')->renderPlain(\$build);\n\n";
  1333. throw new \InvalidArgumentException(sprintf('The template provided is not a standalone Twig template: "%s". This template is already registered in Drupal\'s Theme System as "%s". If this template is intended to be truly standalone, you can change the file extension from ".html.twig" to just ".twig". Otherwise, if this is a properly registered template in the Theme System, you should render it using Drupal\'s existing Render API and not this method: %s', $basename, $hook, $example));
  1334. }
  1335. }
  1336. $template = file_get_contents($realpath);
  1337. if (!isset($renderContext)) {
  1338. $renderContext = new RenderContext();
  1339. }
  1340. // Render the template.
  1341. $output = static::renderer()->executeInRenderContext($renderContext, function () use ($template, $variables) {
  1342. return static::twig()->createTemplate($template)->render($variables);
  1343. });
  1344. return Markup::create($output);
  1345. }
  1346. /**
  1347. * Helper function for writing data to the file system.
  1348. *
  1349. * Note: this is specifically designed with replacing chunks of existing
  1350. * data in mind.
  1351. *
  1352. * @param string $path
  1353. * The path to the file where the data will be written.
  1354. * @param string $data
  1355. * The data to write to $file.
  1356. * @param string $start
  1357. * Optional. A marker determining where to begin injecting $data.
  1358. * Note: this value is used within a regular expression.
  1359. * @param string $end
  1360. * Optional. A marker determining where to stop injecting $data. This is
  1361. * primarily useful for replacing a "chunk" of data within a file.
  1362. * Note: this value is used within a regular expression.
  1363. *
  1364. * @return bool
  1365. * TRUE if the file was successfully written, FALSE otherwise.
  1366. */
  1367. public static function putContents($path, $data, $start = NULL, $end = NULL) {
  1368. $realpath = realpath($path) ?: $path;
  1369. // Markers used, build regular expression to split any existing content.
  1370. if ($start || $end) {
  1371. $regExp = [];
  1372. if ($start) {
  1373. $regExp[] = preg_quote($start, '/');
  1374. }
  1375. if ($end) {
  1376. $regExp[] = preg_quote($end, '/');
  1377. }
  1378. $regExp = implode('|', $regExp);
  1379. $parts = @preg_split("/$regExp/", @file_get_contents($realpath) ?: '') ?: [];
  1380. $replaced = isset($parts[0]) ? trim($parts[0]) . "\n" : '';
  1381. $replaced .= "$data\n";
  1382. $replaced .= isset($parts[2]) ? trim($parts[2]) . "\n" : '';
  1383. $data = $replaced;
  1384. }
  1385. return !!file_put_contents($realpath, $data) !== FALSE;
  1386. }
  1387. /**
  1388. * Retrieves the Renderer service.
  1389. *
  1390. * @return \Drupal\Core\Render\Renderer
  1391. * The Renderer service.
  1392. */
  1393. public static function renderer() {
  1394. if (!isset(static::$renderer)) {
  1395. static::$renderer = \Drupal::service('renderer');
  1396. }
  1397. return static::$renderer;
  1398. }
  1399. /**
  1400. * Retrieves the Theme Registry service.
  1401. *
  1402. * @return \Drupal\Core\Theme\Registry
  1403. * The Theme Registry service.
  1404. */
  1405. public static function themeRegistry() {
  1406. if (!isset(static::$themeRegistry)) {
  1407. static::$themeRegistry = \Drupal::service('theme.registry');
  1408. }
  1409. return static::$themeRegistry;
  1410. }
  1411. /**
  1412. * Ensures a value is typecast to a string, rendering an array if necessary.
  1413. *
  1414. * @param string|array $value
  1415. * The value to typecast, passed by reference.
  1416. *
  1417. * @return string
  1418. * The typecast string value.
  1419. */
  1420. public static function toString(&$value) {
  1421. return (string) (Element::isRenderArray($value) ? Element::create($value)->renderPlain() : $value);
  1422. }
  1423. /**
  1424. * Retrieves the Twig service.
  1425. *
  1426. * @return \Drupal\Core\Template\TwigEnvironment
  1427. * The Twig service.
  1428. */
  1429. public static function twig() {
  1430. if (!isset(static::$twig)) {
  1431. static::$twig = \Drupal::service('twig');
  1432. }
  1433. return static::$twig;
  1434. }
  1435. }

Classes

Name Description
Bootstrap The primary class for the Drupal Bootstrap base theme.