system.module 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449
  1. <?php
  2. /**
  3. * @file
  4. * Configuration system that lets administrators modify the workings of the site.
  5. */
  6. use Drupal\Component\Render\PlainTextOutput;
  7. use Drupal\Component\Utility\UrlHelper;
  8. use Drupal\Core\Asset\AttachedAssetsInterface;
  9. use Drupal\Core\Cache\Cache;
  10. use Drupal\Core\Extension\Exception\UnknownExtensionException;
  11. use Drupal\Core\Queue\QueueGarbageCollectionInterface;
  12. use Drupal\Core\Database\Query\AlterableInterface;
  13. use Drupal\Core\Extension\Extension;
  14. use Drupal\Core\Form\FormStateInterface;
  15. use Drupal\Core\KeyValueStore\KeyValueDatabaseExpirableFactory;
  16. use Drupal\Core\PageCache\RequestPolicyInterface;
  17. use Drupal\Core\PhpStorage\PhpStorageFactory;
  18. use Drupal\Core\Routing\RouteMatchInterface;
  19. use Drupal\Core\Routing\StackedRouteMatchInterface;
  20. use Drupal\Core\Language\LanguageInterface;
  21. use Drupal\Core\Menu\MenuTreeParameters;
  22. use Drupal\Core\Extension\ModuleHandler;
  23. use Drupal\Core\Url;
  24. use Drupal\Core\Block\BlockPluginInterface;
  25. use Drupal\user\UserInterface;
  26. use Symfony\Component\HttpFoundation\RedirectResponse;
  27. use GuzzleHttp\Exception\RequestException;
  28. /**
  29. * New users will be set to the default time zone at registration.
  30. *
  31. * @deprecated in Drupal 8.3.x and will be removed before Drupal 9.0.0.
  32. * Use \Drupal\user\UserInterface::TIMEZONE_DEFAULT instead.
  33. *
  34. * @see https://www.drupal.org/node/2831620
  35. */
  36. const DRUPAL_USER_TIMEZONE_DEFAULT = 0;
  37. /**
  38. * New users will get an empty time zone at registration.
  39. *
  40. * @deprecated in Drupal 8.3.x and will be removed before Drupal 9.0.0.
  41. * Use \Drupal\user\UserInterface::TIMEZONE_EMPTY instead.
  42. *
  43. * @see https://www.drupal.org/node/2831620
  44. */
  45. const DRUPAL_USER_TIMEZONE_EMPTY = 1;
  46. /**
  47. * New users will select their own timezone at registration.
  48. *
  49. * @deprecated in Drupal 8.3.x and will be removed before Drupal 9.0.0.
  50. * Use \Drupal\user\UserInterface::TIMEZONE_SELECT instead.
  51. *
  52. * @see https://www.drupal.org/node/2831620
  53. */
  54. const DRUPAL_USER_TIMEZONE_SELECT = 2;
  55. /**
  56. * Disabled option on forms and settings
  57. */
  58. const DRUPAL_DISABLED = 0;
  59. /**
  60. * Optional option on forms and settings
  61. */
  62. const DRUPAL_OPTIONAL = 1;
  63. /**
  64. * Required option on forms and settings
  65. */
  66. const DRUPAL_REQUIRED = 2;
  67. /**
  68. * Return only visible regions.
  69. *
  70. * @deprecated in Drupal 8.3.x and will be removed before Drupal 9.0.0.
  71. * Use \Drupal\block\BlockRepositoryInterface::REGIONS_VISIBLE instead.
  72. *
  73. * @see system_region_list()
  74. * @see https://www.drupal.org/node/2831620
  75. */
  76. const REGIONS_VISIBLE = 'visible';
  77. /**
  78. * Return all regions.
  79. *
  80. * @deprecated in Drupal 8.3.x and will be removed before Drupal 9.0.0.
  81. * Use \Drupal\block\BlockRepositoryInterface::REGIONS_ALL instead.
  82. *
  83. * @see system_region_list()
  84. * @see https://www.drupal.org/node/2831620
  85. */
  86. const REGIONS_ALL = 'all';
  87. /**
  88. * Implements hook_help().
  89. */
  90. function system_help($route_name, RouteMatchInterface $route_match) {
  91. switch ($route_name) {
  92. case 'help.page.system':
  93. $output = '';
  94. $output .= '<h3>' . t('About') . '</h3>';
  95. $output .= '<p>' . t('The System module is integral to the site: it provides user interfaces for many core systems and settings, as well as the basic administrative menu structure. For more information, see the <a href=":system">online documentation for the System module</a>.', [':system' => 'https://www.drupal.org/documentation/modules/system']) . '</p>';
  96. $output .= '<h3>' . t('Uses') . '</h3>';
  97. $output .= '<dl>';
  98. $output .= '<dt>' . t('Managing modules') . '</dt>';
  99. $output .= '<dd>' . t('Users with appropriate permission can install and uninstall modules from the <a href=":modules">Extend page</a>. Depending on which distribution or installation profile you choose when you install your site, several modules are installed and others are provided but not installed. Each module provides a discrete set of features; modules may be installed or uninstalled depending on the needs of the site. Many additional modules contributed by members of the Drupal community are available for download from the <a href=":drupal-modules">Drupal.org module page</a>. Note that uninstalling a module is a destructive action: when you uninstall a module, you will permanently lose all data connected to the module.', [':modules' => \Drupal::url('system.modules_list'), ':drupal-modules' => 'https://www.drupal.org/project/modules']) . '</dd>';
  100. $output .= '<dt>' . t('Managing themes') . '</dt>';
  101. $output .= '<dd>' . t('Users with appropriate permission can install and uninstall themes on the <a href=":themes">Appearance page</a>. Themes determine the design and presentation of your site. Depending on which distribution or installation profile you choose when you install your site, a default theme is installed, and possibly a different theme for administration pages. Other themes are provided but not installed, and additional contributed themes are available at the <a href=":drupal-themes">Drupal.org theme page</a>.', [':themes' => \Drupal::url('system.themes_page'), ':drupal-themes' => 'https://www.drupal.org/project/themes']) . '</dd>';
  102. $output .= '<dt>' . t('Disabling drag-and-drop functionality') . '</dt>';
  103. $output .= '<dd>' . t('The default drag-and-drop user interface for ordering tables in the administrative interface presents a challenge for some users, including users of screen readers and other assistive technology. The drag-and-drop interface can be disabled in a table by clicking a link labeled "Show row weights" above the table. The replacement interface allows users to order the table by choosing numerical weights instead of dragging table rows.') . '</dd>';
  104. $output .= '<dt>' . t('Configuring basic site settings') . '</dt>';
  105. $output .= '<dd>' . t('The System module provides pages for managing basic site configuration, including <a href=":date-time-settings">Date and time formats</a> and <a href=":site-info">Basic site settings</a> (site name, email address to send mail from, home page, and error pages). Additional configuration pages are listed on the main <a href=":config">Configuration page</a>.', [':date-time-settings' => \Drupal::url('entity.date_format.collection'), ':site-info' => \Drupal::url('system.site_information_settings'), ':config' => \Drupal::url('system.admin_config')]) . '</dd>';
  106. $output .= '<dt>' . t('Checking site status') . '</dt>';
  107. $output .= '<dd>' . t('The <a href=":status">Status report</a> provides an overview of the configuration, status, and health of your site. Review this report to make sure there are not any problems to address, and to find information about the software your site and web server are using.', [':status' => \Drupal::url('system.status')]) . '</dd>';
  108. $output .= '<dt>' . t('Using maintenance mode') . '</dt>';
  109. $output .= '<dd>' . t('When you are performing site maintenance, you can prevent non-administrative users (including anonymous visitors) from viewing your site by putting it in <a href=":maintenance-mode">Maintenance mode</a>. This will prevent unauthorized users from making changes to the site while you are performing maintenance, or from seeing a broken site while updates are in progress.', [':maintenance-mode' => \Drupal::url('system.site_maintenance_mode')]) . '</dd>';
  110. $output .= '<dt>' . t('Configuring for performance') . '</dt>';
  111. $output .= '<dd>' . t('On the <a href=":performance-page">Performance page</a>, the site can be configured to aggregate CSS and JavaScript files, making the total request size smaller. Note that, for small- to medium-sized websites, the <a href=":page-cache">Internal Page Cache module</a> should be installed so that pages are efficiently cached and reused for anonymous users. Finally, for websites of all sizes, the <a href=":dynamic-page-cache">Dynamic Page Cache module</a> should also be installed so that the non-personalized parts of pages are efficiently cached (for all users).', [':performance-page' => \Drupal::url('system.performance_settings'), ':page-cache' => (\Drupal::moduleHandler()->moduleExists('page_cache')) ? \Drupal::url('help.page', ['name' => 'page_cache']) : '#', ':dynamic-page-cache' => (\Drupal::moduleHandler()->moduleExists('dynamic_page_cache')) ? \Drupal::url('help.page', ['name' => 'dynamic_page_cache']) : '#']) . '</dd>';
  112. $output .= '<dt>' . t('Configuring cron') . '</dt>';
  113. $output .= '<dd>' . t('In order for the site and its modules to continue to operate well, a set of routine administrative operations must run on a regular basis; these operations are known as <em>cron</em> tasks. On the <a href=":cron">Cron page</a>, you can configure cron to run periodically as part of server responses by installing the <em>Automated Cron</em> module, or you can turn this off and trigger cron from an outside process on your web server. You can verify the status of cron tasks by visiting the <a href=":status">Status report page</a>. For more information, see the <a href=":handbook">online documentation for configuring cron jobs</a>.', [':status' => \Drupal::url('system.status'), ':handbook' => 'https://www.drupal.org/cron', ':cron' => \Drupal::url('system.cron_settings')]) . '</dd>';
  114. $output .= '<dt>' . t('Configuring the file system') . '</dt>';
  115. $output .= '<dd>' . t('Your site has several file directories, which are used to store and process uploaded and generated files. The <em>public</em> file directory, which is configured in your settings.php file, is the default place for storing uploaded files. Links to files in this directory contain the direct file URL, so when the files are requested, the web server will send them directly without invoking your site code. This means that the files can be downloaded by anyone with the file URL, so requests are not access-controlled but they are efficient. The <em>private</em> file directory, also configured in your settings.php file and ideally located outside the site web root, is access controlled. Links to files in this directory are not direct, so requests to these files are mediated by your site code. This means that your site can check file access permission for each file before deciding to fulfill the request, so the requests are more secure, but less efficient. You should only use the private storage for files that need access control, not for files like your site logo and background images used on every page. The <em>temporary</em> file directory is used internally by your site code for various operations, and is configured on the <a href=":file-system">File system settings</a> page. You can also see the configured public and private file directories on this page, and choose whether public or private should be the default for uploaded files.', [':file-system' => \Drupal::url('system.file_system_settings')]) . '</dd>';
  116. $output .= '<dt>' . t('Configuring the image toolkit') . '</dt>';
  117. $output .= '<dd>' . t('On the <a href=":toolkit">Image toolkit page</a>, you can select and configure the PHP toolkit used to manipulate images. Depending on which distribution or installation profile you choose when you install your site, the GD2 toolkit and possibly others are included; other toolkits may be provided by contributed modules.', [':toolkit' => \Drupal::url('system.image_toolkit_settings')]) . '</dd>';
  118. $output .= '</dl>';
  119. return $output;
  120. case 'system.admin_index':
  121. return '<p>' . t('This page shows you all available administration tasks for each module.') . '</p>';
  122. case 'system.themes_page':
  123. $output = '<p>' . t('Set and configure the default theme for your website. Alternative <a href=":themes">themes</a> are available.', [':themes' => 'https://www.drupal.org/project/themes']) . '</p>';
  124. if (\Drupal::moduleHandler()->moduleExists('block')) {
  125. $output .= '<p>' . t('You can place blocks for each theme on the <a href=":blocks">block layout</a> page.', [':blocks' => \Drupal::url('block.admin_display')]) . '</p>';
  126. }
  127. return $output;
  128. case 'system.theme_settings_theme':
  129. $theme_list = \Drupal::service('theme_handler')->listInfo();
  130. $theme = $theme_list[$route_match->getParameter('theme')];
  131. return '<p>' . t('These options control the display settings for the %name theme. When your site is displayed using this theme, these settings will be used.', ['%name' => $theme->info['name']]) . '</p>';
  132. case 'system.theme_settings':
  133. return '<p>' . t('Control default display settings for your site, across all themes. Use theme-specific settings to override these defaults.') . '</p>';
  134. case 'system.modules_list':
  135. $output = '<p>' . t('Download additional <a href=":modules">contributed modules</a> to extend your site\'s functionality.', [':modules' => 'https://www.drupal.org/project/modules']) . '</p>';
  136. if (!\Drupal::moduleHandler()->moduleExists('update')) {
  137. $output .= '<p>' . t('Regularly review available updates to maintain a secure and current site. Always run the <a href=":update-php">update script</a> each time a module is updated. Enable the <a href=":update-manager">Update Manager module</a> to update and install modules and themes.', [':update-php' => \Drupal::url('system.db_update'), ':update-manager' => \Drupal::url('system.modules_list', [], ['fragment' => 'module-update'])]) . '</p>';
  138. }
  139. return $output;
  140. case 'system.modules_uninstall':
  141. return '<p>' . t('The uninstall process removes all data related to a module.') . '</p>';
  142. case 'entity.block.edit_form':
  143. if (($block = $route_match->getParameter('block')) && $block->getPluginId() == 'system_powered_by_block') {
  144. return '<p>' . t('The <em>Powered by Drupal</em> block is an optional link to the home page of the Drupal project. While there is absolutely no requirement that sites feature this link, it may be used to show support for Drupal.') . '</p>';
  145. }
  146. break;
  147. case 'block.admin_add':
  148. if ($route_match->getParameter('plugin_id') == 'system_powered_by_block') {
  149. return '<p>' . t('The <em>Powered by Drupal</em> block is an optional link to the home page of the Drupal project. While there is absolutely no requirement that sites feature this link, it may be used to show support for Drupal.') . '</p>';
  150. }
  151. break;
  152. case 'system.site_maintenance_mode':
  153. if (\Drupal::currentUser()->id() == 1) {
  154. return '<p>' . t('Use maintenance mode when making major updates, particularly if the updates could disrupt visitors or the update process. Examples include upgrading, importing or exporting content, modifying a theme, modifying content types, and making backups.') . '</p>';
  155. }
  156. break;
  157. case 'system.status':
  158. return '<p>' . t("Here you can find a short overview of your site's parameters as well as any problems detected with your installation. It may be useful to copy and paste this information into support requests filed on Drupal.org's support forums and project issue queues. Before filing a support request, ensure that your web server meets the <a href=\":system-requirements\">system requirements.</a>", [':system-requirements' => 'https://www.drupal.org/requirements']) . '</p>';
  159. }
  160. }
  161. /**
  162. * Implements hook_theme().
  163. */
  164. function system_theme() {
  165. return array_merge(drupal_common_theme(), [
  166. // Normally theme suggestion templates are only picked up when they are in
  167. // themes. We explicitly define theme suggestions here so that the block
  168. // templates in core/modules/system/templates are picked up.
  169. 'block__system_branding_block' => [
  170. 'render element' => 'elements',
  171. 'base hook' => 'block',
  172. ],
  173. 'block__system_messages_block' => [
  174. 'base hook' => 'block',
  175. ],
  176. 'block__system_menu_block' => [
  177. 'render element' => 'elements',
  178. 'base hook' => 'block',
  179. ],
  180. 'system_themes_page' => [
  181. 'variables' => [
  182. 'theme_groups' => [],
  183. 'theme_group_titles' => [],
  184. ],
  185. 'file' => 'system.admin.inc',
  186. ],
  187. 'system_config_form' => [
  188. 'render element' => 'form',
  189. ],
  190. 'confirm_form' => [
  191. 'render element' => 'form',
  192. ],
  193. 'system_modules_details' => [
  194. 'render element' => 'form',
  195. 'file' => 'system.admin.inc',
  196. ],
  197. 'system_modules_uninstall' => [
  198. 'render element' => 'form',
  199. 'file' => 'system.admin.inc',
  200. ],
  201. 'status_report_page' => [
  202. 'variables' => [
  203. 'counters' => [],
  204. 'general_info' => [],
  205. 'requirements' => NULL,
  206. ],
  207. ],
  208. 'status_report' => [
  209. 'variables' => [
  210. 'grouped_requirements' => NULL,
  211. 'requirements' => NULL,
  212. ],
  213. ],
  214. 'status_report_grouped' => [
  215. 'variables' => [
  216. 'grouped_requirements' => NULL,
  217. 'requirements' => NULL,
  218. ],
  219. ],
  220. 'status_report_counter' => [
  221. 'variables' => ['amount' => NULL, 'text' => NULL, 'severity' => NULL],
  222. ],
  223. 'status_report_general_info' => [
  224. 'variables' => [
  225. 'drupal' => [],
  226. 'cron' => [],
  227. 'database_system' => [],
  228. 'database_system_version' => [],
  229. 'php' => [],
  230. 'php_memory_limit' => [],
  231. 'webserver' => [],
  232. ],
  233. ],
  234. 'admin_page' => [
  235. 'variables' => ['blocks' => NULL],
  236. 'file' => 'system.admin.inc',
  237. ],
  238. 'admin_block' => [
  239. 'variables' => ['block' => NULL, 'attributes' => []],
  240. 'file' => 'system.admin.inc',
  241. ],
  242. 'admin_block_content' => [
  243. 'variables' => ['content' => NULL],
  244. 'file' => 'system.admin.inc',
  245. ],
  246. 'system_admin_index' => [
  247. 'variables' => ['menu_items' => NULL],
  248. 'file' => 'system.admin.inc',
  249. ],
  250. 'entity_add_list' => [
  251. 'variables' => [
  252. 'bundles' => [],
  253. 'add_bundle_message' => NULL,
  254. ],
  255. 'template' => 'entity-add-list',
  256. ],
  257. 'off_canvas_page_wrapper' => [
  258. 'variables' => ['children' => NULL],
  259. ],
  260. ]);
  261. }
  262. /**
  263. * Implements hook_hook_info().
  264. */
  265. function system_hook_info() {
  266. $hooks['token_info'] = [
  267. 'group' => 'tokens',
  268. ];
  269. $hooks['token_info_alter'] = [
  270. 'group' => 'tokens',
  271. ];
  272. $hooks['tokens'] = [
  273. 'group' => 'tokens',
  274. ];
  275. $hooks['tokens_alter'] = [
  276. 'group' => 'tokens',
  277. ];
  278. return $hooks;
  279. }
  280. /**
  281. * Implements hook_theme_suggestions_HOOK().
  282. */
  283. function system_theme_suggestions_html(array $variables) {
  284. $path_args = explode('/', trim(\Drupal::service('path.current')->getPath(), '/'));
  285. return theme_get_suggestions($path_args, 'html');
  286. }
  287. /**
  288. * Implements hook_theme_suggestions_HOOK().
  289. */
  290. function system_theme_suggestions_page(array $variables) {
  291. $path_args = explode('/', trim(\Drupal::service('path.current')->getPath(), '/'));
  292. return theme_get_suggestions($path_args, 'page');
  293. }
  294. /**
  295. * Implements hook_theme_suggestions_HOOK().
  296. */
  297. function system_theme_suggestions_maintenance_page(array $variables) {
  298. $suggestions = [];
  299. // Dead databases will show error messages so supplying this template will
  300. // allow themers to override the page and the content completely.
  301. $offline = defined('MAINTENANCE_MODE');
  302. try {
  303. \Drupal::service('path.matcher')->isFrontPage();
  304. }
  305. catch (Exception $e) {
  306. // The database is not yet available.
  307. $offline = TRUE;
  308. }
  309. if ($offline) {
  310. $suggestions[] = 'maintenance_page__offline';
  311. }
  312. return $suggestions;
  313. }
  314. /**
  315. * Implements hook_theme_suggestions_HOOK().
  316. */
  317. function system_theme_suggestions_region(array $variables) {
  318. $suggestions = [];
  319. if (!empty($variables['elements']['#region'])) {
  320. $suggestions[] = 'region__' . $variables['elements']['#region'];
  321. }
  322. return $suggestions;
  323. }
  324. /**
  325. * Implements hook_theme_suggestions_HOOK().
  326. */
  327. function system_theme_suggestions_field(array $variables) {
  328. $suggestions = [];
  329. $element = $variables['element'];
  330. $suggestions[] = 'field__' . $element['#field_type'];
  331. $suggestions[] = 'field__' . $element['#field_name'];
  332. $suggestions[] = 'field__' . $element['#entity_type'] . '__' . $element['#bundle'];
  333. $suggestions[] = 'field__' . $element['#entity_type'] . '__' . $element['#field_name'];
  334. $suggestions[] = 'field__' . $element['#entity_type'] . '__' . $element['#field_name'] . '__' . $element['#bundle'];
  335. return $suggestions;
  336. }
  337. /**
  338. * Prepares variables for the list of available bundles.
  339. *
  340. * Default template: entity-add-list.html.twig.
  341. *
  342. * @param array $variables
  343. * An associative array containing:
  344. * - bundles: An array of bundles with the label, description, add_link keys.
  345. * - add_bundle_message: The message shown when there are no bundles. Only
  346. * available if the entity type uses bundle entities.
  347. */
  348. function template_preprocess_entity_add_list(&$variables) {
  349. foreach ($variables['bundles'] as $bundle_name => $bundle_info) {
  350. $variables['bundles'][$bundle_name]['description'] = [
  351. '#markup' => $bundle_info['description'],
  352. ];
  353. }
  354. }
  355. /**
  356. * @defgroup authorize Authorized operations
  357. * @{
  358. * Functions to run operations with elevated privileges via authorize.php.
  359. *
  360. * Because of the Update manager functionality included in Drupal core, there
  361. * is a mechanism for running operations with elevated file system privileges,
  362. * the top-level authorize.php script. This script runs at a reduced Drupal
  363. * bootstrap level so that it is not reliant on the entire site being
  364. * functional. The operations use a FileTransfer class to manipulate code
  365. * installed on the system as the user that owns the files, not the user that
  366. * the httpd is running as.
  367. *
  368. * The first setup is to define a callback function that should be authorized
  369. * to run with the elevated privileges. This callback should take a
  370. * FileTransfer as its first argument, although you can define an array of
  371. * other arguments it should be invoked with. The callback should be placed in
  372. * a separate .inc file that will be included by authorize.php.
  373. *
  374. * To run the operation, certain data must be saved into the SESSION, and then
  375. * the flow of control should be redirected to the authorize.php script. There
  376. * are two ways to do this, either to call system_authorized_run() directly,
  377. * or to call system_authorized_init() and then redirect to authorize.php,
  378. * using the URL from system_authorized_get_url(). Redirecting yourself is
  379. * necessary when your authorized operation is being triggered by a form
  380. * submit handler, since calling redirecting in a submit handler is a bad
  381. * idea, and you should instead use $form_state->setRedirect().
  382. *
  383. * Once the SESSION is setup for the operation and the user is redirected to
  384. * authorize.php, they will be prompted for their connection credentials (core
  385. * provides FTP and SSH by default, although other connection classes can be
  386. * added via contributed modules). With valid credentials, authorize.php will
  387. * instantiate the appropriate FileTransfer object, and then invoke the
  388. * desired operation passing in that object. The authorize.php script can act
  389. * as a Batch API processing page, if the operation requires a batch.
  390. *
  391. * @see authorize.php
  392. * @see \Drupal\Core\FileTransfer\FileTransfer
  393. * @see hook_filetransfer_info()
  394. */
  395. /**
  396. * Setup a given callback to run via authorize.php with elevated privileges.
  397. *
  398. * To use authorize.php, certain variables must be stashed into $_SESSION. This
  399. * function sets up all the necessary $_SESSION variables. The calling function
  400. * should then redirect to authorize.php, using the full path returned by
  401. * system_authorized_get_url(). That initiates the workflow that will eventually
  402. * lead to the callback being invoked. The callback will be invoked at a low
  403. * bootstrap level, without all modules being invoked, so it needs to be careful
  404. * not to assume any code exists. Example (system_authorized_run()):
  405. * @code
  406. * system_authorized_init($callback, $file, $arguments, $page_title);
  407. * return new RedirectResponse(system_authorized_get_url()->toString());
  408. * @endcode
  409. * Example (update_manager_install_form_submit()):
  410. * @code
  411. * system_authorized_init('update_authorize_run_install',
  412. * drupal_get_path('module', 'update') . '/update.authorize.inc',
  413. * $arguments, t('Update manager'));
  414. * $form_state->setRedirectUrl(system_authorized_get_url());
  415. * @endcode
  416. *
  417. * @param callable $callback
  418. * The name of the function to invoke once the user authorizes the operation.
  419. * @param $file
  420. * The full path to the file where the callback function is implemented.
  421. * @param $arguments
  422. * Optional array of arguments to pass into the callback when it is invoked.
  423. * Note that the first argument to the callback is always the FileTransfer
  424. * object created by authorize.php when the user authorizes the operation.
  425. * @param $page_title
  426. * Optional string to use as the page title once redirected to authorize.php.
  427. * @return
  428. * Nothing, this function just initializes variables in the user's session.
  429. */
  430. function system_authorized_init($callback, $file, $arguments = [], $page_title = NULL) {
  431. // First, figure out what file transfer backends the site supports, and put
  432. // all of those in the SESSION so that authorize.php has access to all of
  433. // them via the class autoloader, even without a full bootstrap.
  434. $_SESSION['authorize_filetransfer_info'] = drupal_get_filetransfer_info();
  435. // Now, define the callback to invoke.
  436. $_SESSION['authorize_operation'] = [
  437. 'callback' => $callback,
  438. 'file' => $file,
  439. 'arguments' => $arguments,
  440. ];
  441. if (isset($page_title)) {
  442. $_SESSION['authorize_page_title'] = $page_title;
  443. }
  444. }
  445. /**
  446. * Return the URL for the authorize.php script.
  447. *
  448. * @param array $options
  449. * Optional array of options to set on the \Drupal\Core\Url object.
  450. * @return \Drupal\Core\Url
  451. * The full URL to authorize.php, using HTTPS if available.
  452. *
  453. * @see system_authorized_init()
  454. */
  455. function system_authorized_get_url(array $options = []) {
  456. // core/authorize.php is an unrouted URL, so using the base: scheme is
  457. // the correct usage for this case.
  458. $url = Url::fromUri('base:core/authorize.php');
  459. $url_options = $url->getOptions();
  460. $url->setOptions($options + $url_options);
  461. return $url;
  462. }
  463. /**
  464. * Returns the URL for the authorize.php script when it is processing a batch.
  465. *
  466. * @param array $options
  467. * Optional array of options to set on the \Drupal\Core\Url object.
  468. *
  469. * @return \Drupal\Core\Url
  470. */
  471. function system_authorized_batch_processing_url(array $options = []) {
  472. $options['query'] = ['batch' => '1'];
  473. return system_authorized_get_url($options);
  474. }
  475. /**
  476. * Setup and invoke an operation using authorize.php.
  477. *
  478. * @see system_authorized_init()
  479. */
  480. function system_authorized_run($callback, $file, $arguments = [], $page_title = NULL) {
  481. system_authorized_init($callback, $file, $arguments, $page_title);
  482. return new RedirectResponse(system_authorized_get_url()->toString());
  483. }
  484. /**
  485. * Use authorize.php to run batch_process().
  486. *
  487. * @see batch_process()
  488. */
  489. function system_authorized_batch_process() {
  490. $finish_url = system_authorized_get_url();
  491. $process_url = system_authorized_batch_processing_url();
  492. return batch_process($finish_url->setAbsolute()->toString(), $process_url);
  493. }
  494. /**
  495. * @} End of "defgroup authorize".
  496. */
  497. /**
  498. * Implements hook_updater_info().
  499. */
  500. function system_updater_info() {
  501. return [
  502. 'module' => [
  503. 'class' => 'Drupal\Core\Updater\Module',
  504. 'name' => t('Update modules'),
  505. 'weight' => 0,
  506. ],
  507. 'theme' => [
  508. 'class' => 'Drupal\Core\Updater\Theme',
  509. 'name' => t('Update themes'),
  510. 'weight' => 0,
  511. ],
  512. ];
  513. }
  514. /**
  515. * Implements hook_filetransfer_info().
  516. */
  517. function system_filetransfer_info() {
  518. $backends = [];
  519. // This is the default, will be available on most systems.
  520. if (function_exists('ftp_connect')) {
  521. $backends['ftp'] = [
  522. 'title' => t('FTP'),
  523. 'class' => 'Drupal\Core\FileTransfer\FTP',
  524. 'weight' => 0,
  525. ];
  526. }
  527. // SSH2 lib connection is only available if the proper PHP extension is
  528. // installed.
  529. if (function_exists('ssh2_connect')) {
  530. $backends['ssh'] = [
  531. 'title' => t('SSH'),
  532. 'class' => 'Drupal\Core\FileTransfer\SSH',
  533. 'weight' => 20,
  534. ];
  535. }
  536. return $backends;
  537. }
  538. /**
  539. * Implements hook_page_attachments().
  540. *
  541. * @see template_preprocess_maintenance_page()
  542. * @see \Drupal\Core\EventSubscriber\ActiveLinkResponseFilter
  543. */
  544. function system_page_attachments(array &$page) {
  545. // Ensure the same CSS is loaded in template_preprocess_maintenance_page().
  546. $page['#attached']['library'][] = 'system/base';
  547. if (\Drupal::service('router.admin_context')->isAdminRoute()) {
  548. $page['#attached']['library'][] = 'system/admin';
  549. }
  550. // Attach libraries used by this theme.
  551. $active_theme = \Drupal::theme()->getActiveTheme();
  552. foreach ($active_theme->getLibraries() as $library) {
  553. $page['#attached']['library'][] = $library;
  554. }
  555. // Attach favicon.
  556. if (theme_get_setting('features.favicon')) {
  557. $favicon = theme_get_setting('favicon.url');
  558. $type = theme_get_setting('favicon.mimetype');
  559. $page['#attached']['html_head_link'][][] = [
  560. 'rel' => 'shortcut icon',
  561. 'href' => UrlHelper::stripDangerousProtocols($favicon),
  562. 'type' => $type,
  563. ];
  564. }
  565. // Get the major Drupal version.
  566. list($version,) = explode('.', \Drupal::VERSION);
  567. // Attach default meta tags.
  568. $meta_default = [
  569. // Make sure the Content-Type comes first because the IE browser may be
  570. // vulnerable to XSS via encoding attacks from any content that comes
  571. // before this META tag, such as a TITLE tag.
  572. 'system_meta_content_type' => [
  573. '#tag' => 'meta',
  574. '#attributes' => [
  575. 'charset' => 'utf-8',
  576. ],
  577. // Security: This always has to be output first.
  578. '#weight' => -1000,
  579. ],
  580. // Show Drupal and the major version number in the META GENERATOR tag.
  581. 'system_meta_generator' => [
  582. '#type' => 'html_tag',
  583. '#tag' => 'meta',
  584. '#attributes' => [
  585. 'name' => 'Generator',
  586. 'content' => 'Drupal ' . $version . ' (https://www.drupal.org)',
  587. ],
  588. ],
  589. // Attach default mobile meta tags for responsive design.
  590. 'MobileOptimized' => [
  591. '#tag' => 'meta',
  592. '#attributes' => [
  593. 'name' => 'MobileOptimized',
  594. 'content' => 'width',
  595. ],
  596. ],
  597. 'HandheldFriendly' => [
  598. '#tag' => 'meta',
  599. '#attributes' => [
  600. 'name' => 'HandheldFriendly',
  601. 'content' => 'true',
  602. ],
  603. ],
  604. 'viewport' => [
  605. '#tag' => 'meta',
  606. '#attributes' => [
  607. 'name' => 'viewport',
  608. 'content' => 'width=device-width, initial-scale=1.0',
  609. ],
  610. ],
  611. ];
  612. foreach ($meta_default as $key => $value) {
  613. $page['#attached']['html_head'][] = [$value, $key];
  614. }
  615. // Handle setting the "active" class on links by:
  616. // - loading the active-link library if the current user is authenticated;
  617. // - applying a response filter if the current user is anonymous.
  618. // @see \Drupal\Core\Link
  619. // @see \Drupal\Core\Utility\LinkGenerator::generate()
  620. // @see template_preprocess_links()
  621. // @see \Drupal\Core\EventSubscriber\ActiveLinkResponseFilter
  622. if (\Drupal::currentUser()->isAuthenticated()) {
  623. $page['#attached']['library'][] = 'core/drupal.active-link';
  624. }
  625. }
  626. /**
  627. * Implements hook_js_settings_build().
  628. *
  629. * Sets values for the core/drupal.ajax library, which just depends on the
  630. * active theme but no other request-dependent values.
  631. */
  632. function system_js_settings_build(&$settings, AttachedAssetsInterface $assets) {
  633. // Generate the values for the core/drupal.ajax library.
  634. // We need to send ajaxPageState settings for core/drupal.ajax if:
  635. // - ajaxPageState is being loaded in this Response, in which case it will
  636. // already exist at $settings['ajaxPageState'] (because the core/drupal.ajax
  637. // library definition specifies a placeholder 'ajaxPageState' setting).
  638. // - core/drupal.ajax already has been loaded and hence this is an AJAX
  639. // Response in which we must send the list of extra asset libraries that are
  640. // being added in this AJAX Response.
  641. /** @var \Drupal\Core\Asset\LibraryDependencyResolver $library_dependency_resolver */
  642. $library_dependency_resolver = \Drupal::service('library.dependency_resolver');
  643. if (isset($settings['ajaxPageState']) || in_array('core/drupal.ajax', $library_dependency_resolver->getLibrariesWithDependencies($assets->getAlreadyLoadedLibraries()))) {
  644. // Provide the page with information about the theme that's used, so that
  645. // a later AJAX request can be rendered using the same theme.
  646. // @see \Drupal\Core\Theme\AjaxBasePageNegotiator
  647. $theme_key = \Drupal::theme()->getActiveTheme()->getName();
  648. $settings['ajaxPageState']['theme'] = $theme_key;
  649. }
  650. }
  651. /**
  652. * Implements hook_js_settings_alter().
  653. *
  654. * Sets values which depend on the current request, like core/drupalSettings
  655. * as well as theme_token ajax state.
  656. */
  657. function system_js_settings_alter(&$settings, AttachedAssetsInterface $assets) {
  658. // As this is being output in the final response always use the master
  659. // request.
  660. $request = \Drupal::requestStack()->getMasterRequest();
  661. $current_query = $request->query->all();
  662. // Let output path processors set a prefix.
  663. /** @var \Drupal\Core\PathProcessor\OutboundPathProcessorInterface $path_processor */
  664. $path_processor = \Drupal::service('path_processor_manager');
  665. $options = ['prefix' => ''];
  666. $path_processor->processOutbound('/', $options);
  667. $pathPrefix = $options['prefix'];
  668. $route_match = \Drupal::routeMatch();
  669. if ($route_match instanceof StackedRouteMatchInterface) {
  670. $route_match = $route_match->getMasterRouteMatch();
  671. }
  672. $current_path = $route_match->getRouteName() ? Url::fromRouteMatch($route_match)->getInternalPath() : '';
  673. $current_path_is_admin = \Drupal::service('router.admin_context')->isAdminRoute($route_match->getRouteObject());
  674. $path_settings = [
  675. 'baseUrl' => $request->getBaseUrl() . '/',
  676. 'pathPrefix' => $pathPrefix,
  677. 'currentPath' => $current_path,
  678. 'currentPathIsAdmin' => $current_path_is_admin,
  679. 'isFront' => \Drupal::service('path.matcher')->isFrontPage(),
  680. 'currentLanguage' => \Drupal::languageManager()->getCurrentLanguage(LanguageInterface::TYPE_URL)->getId(),
  681. ];
  682. if (!empty($current_query)) {
  683. ksort($current_query);
  684. $path_settings['currentQuery'] = (object) $current_query;
  685. }
  686. // Only set core/drupalSettings values that haven't been set already.
  687. foreach ($path_settings as $key => $value) {
  688. if (!isset($settings['path'][$key])) {
  689. $settings['path'][$key] = $value;
  690. }
  691. }
  692. if (!isset($settings['pluralDelimiter'])) {
  693. $settings['pluralDelimiter'] = LOCALE_PLURAL_DELIMITER;
  694. }
  695. // Add the theme token to ajaxPageState, ensuring the database is available
  696. // before doing so. Also add the loaded libraries to ajaxPageState.
  697. /** @var \Drupal\Core\Asset\LibraryDependencyResolver $library_dependency_resolver */
  698. $library_dependency_resolver = \Drupal::service('library.dependency_resolver');
  699. if (isset($settings['ajaxPageState']) || in_array('core/drupal.ajax', $library_dependency_resolver->getLibrariesWithDependencies($assets->getAlreadyLoadedLibraries()))) {
  700. if (!defined('MAINTENANCE_MODE')) {
  701. // The theme token is only validated when the theme requested is not the
  702. // default, so don't generate it unless necessary.
  703. // @see \Drupal\Core\Theme\AjaxBasePageNegotiator::determineActiveTheme()
  704. $active_theme_key = \Drupal::theme()->getActiveTheme()->getName();
  705. if ($active_theme_key !== \Drupal::service('theme_handler')->getDefault()) {
  706. $settings['ajaxPageState']['theme_token'] = \Drupal::csrfToken()
  707. ->get($active_theme_key);
  708. }
  709. }
  710. // Provide the page with information about the individual asset libraries
  711. // used, information not otherwise available when aggregation is enabled.
  712. $minimal_libraries = $library_dependency_resolver->getMinimalRepresentativeSubset(array_unique(array_merge(
  713. $assets->getLibraries(),
  714. $assets->getAlreadyLoadedLibraries()
  715. )));
  716. sort($minimal_libraries);
  717. $settings['ajaxPageState']['libraries'] = implode(',', $minimal_libraries);
  718. }
  719. }
  720. /**
  721. * Implements hook_form_alter().
  722. */
  723. function system_form_alter(&$form, FormStateInterface $form_state) {
  724. // If the page that's being built is cacheable, set the 'immutable' flag, to
  725. // ensure that when the form is used, a new form build ID is generated when
  726. // appropriate, to prevent information disclosure.
  727. // Note: This code just wants to know whether cache response headers are set,
  728. // not whether page_cache module will be active.
  729. // \Drupal\Core\EventSubscriber\FinishResponseSubscriber::onRespond will
  730. // send those headers, in case $request_policy->check($request) succeeds. In
  731. // that case we need to ensure that the immutable flag is sot, so future POST
  732. // request won't take over the form state of another user.
  733. /** @var \Drupal\Core\PageCache\RequestPolicyInterface $request_policy */
  734. $request_policy = \Drupal::service('page_cache_request_policy');
  735. $request = \Drupal::requestStack()->getCurrentRequest();
  736. $request_is_cacheable = $request_policy->check($request) === RequestPolicyInterface::ALLOW;
  737. if ($request_is_cacheable) {
  738. $form_state->addBuildInfo('immutable', TRUE);
  739. }
  740. }
  741. /**
  742. * Implements hook_form_FORM_ID_alter() for \Drupal\user\AccountForm.
  743. */
  744. function system_form_user_form_alter(&$form, FormStateInterface $form_state) {
  745. if (\Drupal::config('system.date')->get('timezone.user.configurable')) {
  746. system_user_timezone($form, $form_state);
  747. }
  748. }
  749. /**
  750. * Implements hook_form_FORM_ID_alter() for \Drupal\user\RegisterForm.
  751. */
  752. function system_form_user_register_form_alter(&$form, FormStateInterface $form_state) {
  753. $config = \Drupal::config('system.date');
  754. if ($config->get('timezone.user.configurable') && $config->get('timezone.user.default') == DRUPAL_USER_TIMEZONE_SELECT) {
  755. system_user_timezone($form, $form_state);
  756. }
  757. }
  758. /**
  759. * Implements hook_ENTITY_TYPE_presave() for user entities.
  760. */
  761. function system_user_presave(UserInterface $account) {
  762. $config = \Drupal::config('system.date');
  763. if ($config->get('timezone.user.configurable') && !$account->getTimeZone() && !$config->get('timezone.user.default')) {
  764. $account->timezone = $config->get('timezone.default');
  765. }
  766. }
  767. /**
  768. * Implements hook_user_login().
  769. */
  770. function system_user_login(UserInterface $account) {
  771. $config = \Drupal::config('system.date');
  772. // If the user has a NULL time zone, notify them to set a time zone.
  773. if (!$account->getTimezone() && $config->get('timezone.user.configurable') && $config->get('timezone.user.warn')) {
  774. \Drupal::messenger()
  775. ->addStatus(t('Configure your <a href=":user-edit">account time zone setting</a>.', [
  776. ':user-edit' => $account->url('edit-form', [
  777. 'query' => \Drupal::destination()->getAsArray(),
  778. 'fragment' => 'edit-timezone',
  779. ]),
  780. ]));
  781. }
  782. }
  783. /**
  784. * Add the time zone field to the user edit and register forms.
  785. */
  786. function system_user_timezone(&$form, FormStateInterface $form_state) {
  787. $user = \Drupal::currentUser();
  788. $account = $form_state->getFormObject()->getEntity();
  789. $form['timezone'] = [
  790. '#type' => 'details',
  791. '#title' => t('Locale settings'),
  792. '#open' => TRUE,
  793. '#weight' => 6,
  794. ];
  795. $form['timezone']['timezone'] = [
  796. '#type' => 'select',
  797. '#title' => t('Time zone'),
  798. '#default_value' => $account->getTimezone() ? $account->getTimezone() : \Drupal::config('system.date')->get('timezone.default'),
  799. '#options' => system_time_zones($account->id() != $user->id(), TRUE),
  800. '#description' => t('Select the desired local time and time zone. Dates and times throughout this site will be displayed using this time zone.'),
  801. ];
  802. $user_input = $form_state->getUserInput();
  803. if (!$account->getTimezone() && $account->id() == $user->id() && empty($user_input['timezone'])) {
  804. $form['timezone']['#attached']['library'][] = 'core/drupal.timezone';
  805. $form['timezone']['timezone']['#attributes'] = ['class' => ['timezone-detect']];
  806. }
  807. }
  808. /**
  809. * Implements hook_preprocess_HOOK() for block templates.
  810. */
  811. function system_preprocess_block(&$variables) {
  812. switch ($variables['base_plugin_id']) {
  813. case 'system_branding_block':
  814. $variables['site_logo'] = '';
  815. if ($variables['content']['site_logo']['#access'] && $variables['content']['site_logo']['#uri']) {
  816. $variables['site_logo'] = $variables['content']['site_logo']['#uri'];
  817. }
  818. $variables['site_name'] = '';
  819. if ($variables['content']['site_name']['#access'] && $variables['content']['site_name']['#markup']) {
  820. $variables['site_name'] = $variables['content']['site_name']['#markup'];
  821. }
  822. $variables['site_slogan'] = '';
  823. if ($variables['content']['site_slogan']['#access'] && $variables['content']['site_slogan']['#markup']) {
  824. $variables['site_slogan'] = [
  825. '#markup' => $variables['content']['site_slogan']['#markup'],
  826. ];
  827. }
  828. break;
  829. case 'system_powered_by_block':
  830. $variables['attributes']['role'] = 'complementary';
  831. break;
  832. }
  833. }
  834. /**
  835. * Checks the existence of the directory specified in $form_element.
  836. *
  837. * This function is called from the system_settings form to check all core
  838. * file directories (file_public_path, file_private_path, file_temporary_path).
  839. *
  840. * @param $form_element
  841. * The form element containing the name of the directory to check.
  842. * @param \Drupal\Core\Form\FormStateInterface $form_state
  843. * The current state of the form.
  844. */
  845. function system_check_directory($form_element, FormStateInterface $form_state) {
  846. $directory = $form_element['#value'];
  847. if (strlen($directory) == 0) {
  848. return $form_element;
  849. }
  850. $logger = \Drupal::logger('file system');
  851. if (!is_dir($directory) && !drupal_mkdir($directory, NULL, TRUE)) {
  852. // If the directory does not exist and cannot be created.
  853. $form_state->setErrorByName($form_element['#parents'][0], t('The directory %directory does not exist and could not be created.', ['%directory' => $directory]));
  854. $logger->error('The directory %directory does not exist and could not be created.', ['%directory' => $directory]);
  855. }
  856. if (is_dir($directory) && !is_writable($directory) && !drupal_chmod($directory)) {
  857. // If the directory is not writable and cannot be made so.
  858. $form_state->setErrorByName($form_element['#parents'][0], t('The directory %directory exists but is not writable and could not be made writable.', ['%directory' => $directory]));
  859. $logger->error('The directory %directory exists but is not writable and could not be made writable.', ['%directory' => $directory]);
  860. }
  861. elseif (is_dir($directory)) {
  862. if ($form_element['#name'] == 'file_public_path') {
  863. // Create public .htaccess file.
  864. file_save_htaccess($directory, FALSE);
  865. }
  866. else {
  867. // Create private .htaccess file.
  868. file_save_htaccess($directory);
  869. }
  870. }
  871. return $form_element;
  872. }
  873. /**
  874. * Returns an array of information about enabled modules or themes.
  875. *
  876. * This function returns the contents of the .info.yml file for each installed
  877. * module or theme.
  878. *
  879. * @param $type
  880. * Either 'module' or 'theme'.
  881. * @param $name
  882. * (optional) The name of a module or theme whose information shall be
  883. * returned. If omitted, all records for the provided $type will be returned.
  884. * If $name does not exist in the provided $type or is not enabled, an empty
  885. * array will be returned.
  886. *
  887. * @return
  888. * An associative array of module or theme information keyed by name, or only
  889. * information for $name, if given. If no records are available, an empty
  890. * array is returned.
  891. *
  892. * @see system_rebuild_module_data()
  893. * @see \Drupal\Core\Extension\ThemeHandlerInterface::rebuildThemeData()
  894. */
  895. function system_get_info($type, $name = NULL) {
  896. if ($type == 'module') {
  897. /** @var \Drupal\Core\Extension\ModuleExtensionList $module_list */
  898. $module_list = \Drupal::service('extension.list.module');
  899. if (isset($name)) {
  900. try {
  901. return $module_list->getExtensionInfo($name);
  902. }
  903. catch (UnknownExtensionException $e) {
  904. return [];
  905. }
  906. }
  907. else {
  908. return $module_list->getAllInstalledInfo();
  909. }
  910. }
  911. else {
  912. // @todo move into ThemeExtensionList https://www.drupal.org/node/2659940
  913. $info = [];
  914. $list = system_list($type);
  915. foreach ($list as $shortname => $item) {
  916. if (!empty($item->status)) {
  917. $info[$shortname] = $item->info;
  918. }
  919. }
  920. if (isset($name)) {
  921. return isset($info[$name]) ? $info[$name] : [];
  922. }
  923. return $info;
  924. }
  925. }
  926. /**
  927. * Ensures that dependencies of required modules are also required.
  928. *
  929. * @param \Drupal\Core\Extension\Extension $module
  930. * The module info.
  931. * @param \Drupal\Core\Extension\Extension[] $modules
  932. * The array of all module info.
  933. *
  934. * @deprecated in Drupal 8.5.0 and will be removed before Drupal 9.0.0. This
  935. * function is no longer used in Drupal core.
  936. *
  937. * @see https://www.drupal.org/node/2709919
  938. */
  939. function _system_rebuild_module_data_ensure_required($module, &$modules) {
  940. @trigger_error("_system_rebuild_module_data_ensure_required() is deprecated in Drupal 8.5.0 and will be removed before Drupal 9.0.0. This function is no longer used in Drupal core. See https://www.drupal.org/node/2709919", E_USER_DEPRECATED);
  941. if (!empty($module->info['required'])) {
  942. foreach ($module->info['dependencies'] as $dependency) {
  943. $dependency_name = ModuleHandler::parseDependency($dependency)['name'];
  944. if (!isset($modules[$dependency_name]->info['required'])) {
  945. $modules[$dependency_name]->info['required'] = TRUE;
  946. $modules[$dependency_name]->info['explanation'] = t('Dependency of required module @module', ['@module' => $module->info['name']]);
  947. // Ensure any dependencies it has are required.
  948. _system_rebuild_module_data_ensure_required($modules[$dependency_name], $modules);
  949. }
  950. }
  951. }
  952. }
  953. /**
  954. * Helper function to scan and collect module .info.yml data.
  955. *
  956. * @return \Drupal\Core\Extension\Extension[]
  957. * An associative array of module information.
  958. *
  959. * @deprecated in Drupal 8.5.0 and will be removed before Drupal 9.0.0.
  960. * Use \Drupal::service('extension.list.module')->reset()->getList()
  961. * instead. Note: You probably don't need the reset() method.
  962. *
  963. * @see https://www.drupal.org/node/2709919
  964. */
  965. function _system_rebuild_module_data() {
  966. @trigger_error("_system_rebuild_module_data() is deprecated in Drupal 8.5.0 and will be removed before Drupal 9.0.0. Instead, you should use \\Drupal::service('extension.list.module')->reset()->getList(). See https://www.drupal.org/node/2709919", E_USER_DEPRECATED);
  967. return \Drupal::service('extension.list.module')->reset()->getList();
  968. }
  969. /**
  970. * Rebuild, save, and return data about all currently available modules.
  971. *
  972. * @return \Drupal\Core\Extension\Extension[]
  973. * Array of all available modules and their data.
  974. */
  975. function system_rebuild_module_data() {
  976. return \Drupal::service('extension.list.module')->reset()->getList();
  977. }
  978. /**
  979. * Get a list of available regions from a specified theme.
  980. *
  981. * @param \Drupal\Core\Extension\Extension|string $theme
  982. * A theme extension object, or the name of a theme.
  983. * @param $show
  984. * Possible values: REGIONS_ALL or REGIONS_VISIBLE. Visible excludes hidden
  985. * regions.
  986. * @return
  987. * An array of regions in the form $region['name'] = 'description'.
  988. */
  989. function system_region_list($theme, $show = REGIONS_ALL) {
  990. if (!$theme instanceof Extension) {
  991. $themes = \Drupal::service('theme_handler')->listInfo();
  992. if (!isset($themes[$theme])) {
  993. return [];
  994. }
  995. $theme = $themes[$theme];
  996. }
  997. $list = [];
  998. $info = $theme->info;
  999. // If requested, suppress hidden regions. See block_admin_display_form().
  1000. foreach ($info['regions'] as $name => $label) {
  1001. if ($show == REGIONS_ALL || !isset($info['regions_hidden']) || !in_array($name, $info['regions_hidden'])) {
  1002. $list[$name] = t($label);
  1003. }
  1004. }
  1005. return $list;
  1006. }
  1007. /**
  1008. * Array sorting callback; sorts modules by their name.
  1009. */
  1010. function system_sort_modules_by_info_name($a, $b) {
  1011. return strcasecmp($a->info['name'], $b->info['name']);
  1012. }
  1013. /**
  1014. * Sorts themes by their names, with the default theme listed first.
  1015. *
  1016. * Callback for uasort() within
  1017. * \Drupal\system\Controller\SystemController::themesPage().
  1018. *
  1019. * @see system_sort_modules_by_info_name()
  1020. */
  1021. function system_sort_themes($a, $b) {
  1022. if ($a->is_default) {
  1023. return -1;
  1024. }
  1025. if ($b->is_default) {
  1026. return 1;
  1027. }
  1028. return strcasecmp($a->info['name'], $b->info['name']);
  1029. }
  1030. /**
  1031. * Implements hook_system_info_alter().
  1032. */
  1033. function system_system_info_alter(&$info, Extension $file, $type) {
  1034. // Remove page-top and page-bottom from the blocks UI since they are reserved for
  1035. // modules to populate from outside the blocks system.
  1036. if ($type == 'theme') {
  1037. $info['regions_hidden'][] = 'page_top';
  1038. $info['regions_hidden'][] = 'page_bottom';
  1039. }
  1040. }
  1041. /**
  1042. * Gets the name of the default region for a given theme.
  1043. *
  1044. * @param $theme
  1045. * The name of a theme.
  1046. * @return
  1047. * A string that is the region name.
  1048. */
  1049. function system_default_region($theme) {
  1050. $regions = array_keys(system_region_list($theme, REGIONS_VISIBLE));
  1051. return isset($regions[0]) ? $regions[0] : '';
  1052. }
  1053. /**
  1054. * Determines whether the current user is in compact mode.
  1055. *
  1056. * Compact mode shows certain administration pages with less description text,
  1057. * such as the configuration page and the permissions page.
  1058. *
  1059. * Whether the user is in compact mode is determined by a cookie, which is set
  1060. * for the user by \Drupal\system\Controller\SystemController::compactPage().
  1061. *
  1062. * If the user does not have the cookie, the default value is given by the
  1063. * configuration variable 'system.site.admin_compact_mode', which itself
  1064. * defaults to FALSE. This does not have a user interface to set it: it is a
  1065. * hidden variable which can be set in the settings.php file.
  1066. *
  1067. * @return bool
  1068. * TRUE when in compact mode, FALSE when in expanded mode.
  1069. */
  1070. function system_admin_compact_mode() {
  1071. // PHP converts dots into underscores in cookie names to avoid problems with
  1072. // its parser, so we use a converted cookie name.
  1073. return \Drupal::request()->cookies->get('Drupal_visitor_admin_compact_mode', \Drupal::config('system.site')->get('admin_compact_mode'));
  1074. }
  1075. /**
  1076. * Generate a list of tasks offered by a specified module.
  1077. *
  1078. * @param string $module
  1079. * Module name.
  1080. * @param array $info
  1081. * The module's information, as provided by system_get_info().
  1082. *
  1083. * @return array
  1084. * An array of task links.
  1085. */
  1086. function system_get_module_admin_tasks($module, array $info) {
  1087. $tree = &drupal_static(__FUNCTION__);
  1088. $menu_tree = \Drupal::menuTree();
  1089. if (!isset($tree)) {
  1090. $parameters = new MenuTreeParameters();
  1091. $parameters->setRoot('system.admin')->excludeRoot()->onlyEnabledLinks();
  1092. $tree = $menu_tree->load('system.admin', $parameters);
  1093. $manipulators = [
  1094. ['callable' => 'menu.default_tree_manipulators:checkAccess'],
  1095. ['callable' => 'menu.default_tree_manipulators:generateIndexAndSort'],
  1096. ['callable' => 'menu.default_tree_manipulators:flatten'],
  1097. ];
  1098. $tree = $menu_tree->transform($tree, $manipulators);
  1099. }
  1100. $admin_tasks = [];
  1101. foreach ($tree as $element) {
  1102. if (!$element->access->isAllowed()) {
  1103. // @todo Bubble cacheability metadata of both accessible and inaccessible
  1104. // links. Currently made impossible by the way admin tasks are rendered.
  1105. continue;
  1106. }
  1107. $link = $element->link;
  1108. if ($link->getProvider() != $module) {
  1109. continue;
  1110. }
  1111. $admin_tasks[] = [
  1112. 'title' => $link->getTitle(),
  1113. 'description' => $link->getDescription(),
  1114. 'url' => $link->getUrlObject(),
  1115. ];
  1116. }
  1117. // Append link for permissions.
  1118. /** @var \Drupal\user\PermissionHandlerInterface $permission_handler */
  1119. $permission_handler = \Drupal::service('user.permissions');
  1120. if ($permission_handler->moduleProvidesPermissions($module)) {
  1121. /** @var \Drupal\Core\Access\AccessManagerInterface $access_manager */
  1122. $access_manager = \Drupal::service('access_manager');
  1123. if ($access_manager->checkNamedRoute('user.admin_permissions', [], \Drupal::currentUser())) {
  1124. /** @var \Drupal\Core\Url $url */
  1125. $url = new Url('user.admin_permissions');
  1126. $url->setOption('fragment', 'module-' . $module);
  1127. $admin_tasks["user.admin_permissions.$module"] = [
  1128. 'title' => t('Configure @module permissions', ['@module' => $info['name']]),
  1129. 'description' => '',
  1130. 'url' => $url,
  1131. ];
  1132. }
  1133. }
  1134. return $admin_tasks;
  1135. }
  1136. /**
  1137. * Implements hook_cron().
  1138. *
  1139. * Remove older rows from flood, batch cache and expirable keyvalue tables.
  1140. */
  1141. function system_cron() {
  1142. // Clean up the flood.
  1143. \Drupal::flood()->garbageCollection();
  1144. foreach (Cache::getBins() as $cache_backend) {
  1145. $cache_backend->garbageCollection();
  1146. }
  1147. // Clean up the expirable key value database store.
  1148. if (\Drupal::service('keyvalue.expirable.database') instanceof KeyValueDatabaseExpirableFactory) {
  1149. \Drupal::service('keyvalue.expirable.database')->garbageCollection();
  1150. }
  1151. // Clean up any garbage in the queue service.
  1152. $queue_worker_manager = \Drupal::service('plugin.manager.queue_worker');
  1153. $queue_factory = \Drupal::service('queue');
  1154. foreach (array_keys($queue_worker_manager->getDefinitions()) as $queue_name) {
  1155. $queue = $queue_factory->get($queue_name);
  1156. if ($queue instanceof QueueGarbageCollectionInterface) {
  1157. $queue->garbageCollection();
  1158. }
  1159. }
  1160. // Clean up PHP storage.
  1161. PhpStorageFactory::get('container')->garbageCollection();
  1162. PhpStorageFactory::get('service_container')->garbageCollection();
  1163. }
  1164. /**
  1165. * Implements hook_mail().
  1166. */
  1167. function system_mail($key, &$message, $params) {
  1168. $token_service = \Drupal::token();
  1169. $context = $params['context'];
  1170. $subject = PlainTextOutput::renderFromHtml($token_service->replace($context['subject'], $context));
  1171. $body = $token_service->replace($context['message'], $context);
  1172. $message['subject'] .= str_replace(["\r", "\n"], '', $subject);
  1173. $message['body'][] = $body;
  1174. }
  1175. /**
  1176. * Generate an array of time zones and their local time&date.
  1177. *
  1178. * @param mixed $blank
  1179. * If evaluates true, prepend an empty time zone option to the array.
  1180. * @param bool $grouped
  1181. * (optional) Whether the timezones should be grouped by region.
  1182. *
  1183. * @return array
  1184. * An array or nested array containing time zones, keyed by the system name.
  1185. */
  1186. function system_time_zones($blank = NULL, $grouped = FALSE) {
  1187. $zonelist = timezone_identifiers_list();
  1188. $zones = $blank ? ['' => t('- None selected -')] : [];
  1189. foreach ($zonelist as $zone) {
  1190. // Because many time zones exist in PHP only for backward compatibility
  1191. // reasons and should not be used, the list is filtered by a regular
  1192. // expression.
  1193. if (preg_match('!^((Africa|America|Antarctica|Arctic|Asia|Atlantic|Australia|Europe|Indian|Pacific)/|UTC$)!', $zone)) {
  1194. $zones[$zone] = t('@zone', ['@zone' => t(str_replace('_', ' ', $zone))]);
  1195. }
  1196. }
  1197. // Sort the translated time zones alphabetically.
  1198. asort($zones);
  1199. if ($grouped) {
  1200. $grouped_zones = [];
  1201. foreach ($zones as $key => $value) {
  1202. $split = explode('/', $value);
  1203. $city = array_pop($split);
  1204. $region = array_shift($split);
  1205. if (!empty($region)) {
  1206. $grouped_zones[$region][$key] = empty($split) ? $city : $city . ' (' . implode('/', $split) . ')';
  1207. }
  1208. else {
  1209. $grouped_zones[$key] = $value;
  1210. }
  1211. }
  1212. foreach ($grouped_zones as $key => $value) {
  1213. if (is_array($grouped_zones[$key])) {
  1214. asort($grouped_zones[$key]);
  1215. }
  1216. }
  1217. $zones = $grouped_zones;
  1218. }
  1219. return $zones;
  1220. }
  1221. /**
  1222. * Attempts to get a file using Guzzle HTTP client and to store it locally.
  1223. *
  1224. * @param string $url
  1225. * The URL of the file to grab.
  1226. * @param string $destination
  1227. * Stream wrapper URI specifying where the file should be placed. If a
  1228. * directory path is provided, the file is saved into that directory under
  1229. * its original name. If the path contains a filename as well, that one will
  1230. * be used instead.
  1231. * If this value is omitted, the site's default files scheme will be used,
  1232. * usually "public://".
  1233. * @param bool $managed
  1234. * If this is set to TRUE, the file API hooks will be invoked and the file is
  1235. * registered in the database.
  1236. * @param int $replace
  1237. * Replace behavior when the destination file already exists:
  1238. * - FILE_EXISTS_REPLACE: Replace the existing file.
  1239. * - FILE_EXISTS_RENAME: Append _{incrementing number} until the filename is
  1240. * unique.
  1241. * - FILE_EXISTS_ERROR: Do nothing and return FALSE.
  1242. *
  1243. * @return mixed
  1244. * One of these possibilities:
  1245. * - If it succeeds and $managed is FALSE, the location where the file was
  1246. * saved.
  1247. * - If it succeeds and $managed is TRUE, a \Drupal\file\FileInterface
  1248. * object which describes the file.
  1249. * - If it fails, FALSE.
  1250. */
  1251. function system_retrieve_file($url, $destination = NULL, $managed = FALSE, $replace = FILE_EXISTS_RENAME) {
  1252. $parsed_url = parse_url($url);
  1253. if (!isset($destination)) {
  1254. $path = file_build_uri(drupal_basename($parsed_url['path']));
  1255. }
  1256. else {
  1257. if (is_dir(\Drupal::service('file_system')->realpath($destination))) {
  1258. // Prevent URIs with triple slashes when glueing parts together.
  1259. $path = str_replace('///', '//', "$destination/") . drupal_basename($parsed_url['path']);
  1260. }
  1261. else {
  1262. $path = $destination;
  1263. }
  1264. }
  1265. try {
  1266. $data = (string) \Drupal::httpClient()
  1267. ->get($url)
  1268. ->getBody();
  1269. $local = $managed ? file_save_data($data, $path, $replace) : file_unmanaged_save_data($data, $path, $replace);
  1270. }
  1271. catch (RequestException $exception) {
  1272. \Drupal::messenger()->addError(t('Failed to fetch file due to error "%error"', ['%error' => $exception->getMessage()]));
  1273. return FALSE;
  1274. }
  1275. if (!$local) {
  1276. \Drupal::messenger()->addError(t('@remote could not be saved to @path.', ['@remote' => $url, '@path' => $path]));
  1277. }
  1278. return $local;
  1279. }
  1280. /**
  1281. * Implements hook_entity_type_build().
  1282. */
  1283. function system_entity_type_build(array &$entity_types) {
  1284. /** @var $entity_types \Drupal\Core\Entity\EntityTypeInterface[] */
  1285. $entity_types['date_format']
  1286. ->setFormClass('add', 'Drupal\system\Form\DateFormatAddForm')
  1287. ->setFormClass('edit', 'Drupal\system\Form\DateFormatEditForm')
  1288. ->setFormClass('delete', 'Drupal\system\Form\DateFormatDeleteForm')
  1289. ->setListBuilderClass('Drupal\system\DateFormatListBuilder')
  1290. ->setLinkTemplate('edit-form', '/admin/config/regional/date-time/formats/manage/{date_format}')
  1291. ->setLinkTemplate('delete-form', '/admin/config/regional/date-time/formats/manage/{date_format}/delete')
  1292. ->setLinkTemplate('collection', '/admin/config/regional/date-time/formats');
  1293. }
  1294. /**
  1295. * Implements hook_block_view_BASE_BLOCK_ID_alter().
  1296. */
  1297. function system_block_view_system_main_block_alter(array &$build, BlockPluginInterface $block) {
  1298. // Contextual links on the system_main block would basically duplicate the
  1299. // tabs/local tasks, so reduce the clutter.
  1300. unset($build['#contextual_links']);
  1301. }
  1302. /**
  1303. * Implements hook_path_update().
  1304. */
  1305. function system_path_update($path) {
  1306. $alias_manager = \Drupal::service('path.alias_manager');
  1307. $alias_manager->cacheClear($path['source']);
  1308. $alias_manager->cacheClear($path['original']['source']);
  1309. }
  1310. /**
  1311. * Implements hook_path_insert().
  1312. */
  1313. function system_path_insert($path) {
  1314. \Drupal::service('path.alias_manager')->cacheClear($path['source']);
  1315. }
  1316. /**
  1317. * Implements hook_path_delete().
  1318. */
  1319. function system_path_delete($path) {
  1320. \Drupal::service('path.alias_manager')->cacheClear($path['source']);
  1321. }
  1322. /**
  1323. * Implements hook_query_TAG_alter() for entity reference selection handlers.
  1324. */
  1325. function system_query_entity_reference_alter(AlterableInterface $query) {
  1326. $handler = $query->getMetadata('entity_reference_selection_handler');
  1327. $handler->entityQueryAlter($query);
  1328. }
  1329. /**
  1330. * Implements hook_element_info_alter().
  1331. */
  1332. function system_element_info_alter(&$type) {
  1333. if (isset($type['page'])) {
  1334. $type['page']['#theme_wrappers']['off_canvas_page_wrapper'] = ['#weight' => -1000];
  1335. }
  1336. }