system.module 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525
  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\Queue\QueueGarbageCollectionInterface;
  11. use Drupal\Core\Database\Query\AlterableInterface;
  12. use Drupal\Core\Extension\Extension;
  13. use Drupal\Core\Extension\ExtensionDiscovery;
  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],
  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. ]);
  258. }
  259. /**
  260. * Implements hook_hook_info().
  261. */
  262. function system_hook_info() {
  263. $hooks['token_info'] = [
  264. 'group' => 'tokens',
  265. ];
  266. $hooks['token_info_alter'] = [
  267. 'group' => 'tokens',
  268. ];
  269. $hooks['tokens'] = [
  270. 'group' => 'tokens',
  271. ];
  272. $hooks['tokens_alter'] = [
  273. 'group' => 'tokens',
  274. ];
  275. return $hooks;
  276. }
  277. /**
  278. * Implements hook_theme_suggestions_HOOK().
  279. */
  280. function system_theme_suggestions_html(array $variables) {
  281. $path_args = explode('/', trim(\Drupal::service('path.current')->getPath(), '/'));
  282. return theme_get_suggestions($path_args, 'html');
  283. }
  284. /**
  285. * Implements hook_theme_suggestions_HOOK().
  286. */
  287. function system_theme_suggestions_page(array $variables) {
  288. $path_args = explode('/', trim(\Drupal::service('path.current')->getPath(), '/'));
  289. return theme_get_suggestions($path_args, 'page');
  290. }
  291. /**
  292. * Implements hook_theme_suggestions_HOOK().
  293. */
  294. function system_theme_suggestions_maintenance_page(array $variables) {
  295. $suggestions = [];
  296. // Dead databases will show error messages so supplying this template will
  297. // allow themers to override the page and the content completely.
  298. $offline = defined('MAINTENANCE_MODE');
  299. try {
  300. \Drupal::service('path.matcher')->isFrontPage();
  301. }
  302. catch (Exception $e) {
  303. // The database is not yet available.
  304. $offline = TRUE;
  305. }
  306. if ($offline) {
  307. $suggestions[] = 'maintenance_page__offline';
  308. }
  309. return $suggestions;
  310. }
  311. /**
  312. * Implements hook_theme_suggestions_HOOK().
  313. */
  314. function system_theme_suggestions_region(array $variables) {
  315. $suggestions = [];
  316. if (!empty($variables['elements']['#region'])) {
  317. $suggestions[] = 'region__' . $variables['elements']['#region'];
  318. }
  319. return $suggestions;
  320. }
  321. /**
  322. * Implements hook_theme_suggestions_HOOK().
  323. */
  324. function system_theme_suggestions_field(array $variables) {
  325. $suggestions = [];
  326. $element = $variables['element'];
  327. $suggestions[] = 'field__' . $element['#field_type'];
  328. $suggestions[] = 'field__' . $element['#field_name'];
  329. $suggestions[] = 'field__' . $element['#entity_type'] . '__' . $element['#bundle'];
  330. $suggestions[] = 'field__' . $element['#entity_type'] . '__' . $element['#field_name'];
  331. $suggestions[] = 'field__' . $element['#entity_type'] . '__' . $element['#field_name'] . '__' . $element['#bundle'];
  332. return $suggestions;
  333. }
  334. /**
  335. * Prepares variables for the list of available bundles.
  336. *
  337. * Default template: entity-add-list.html.twig.
  338. *
  339. * @param array $variables
  340. * An associative array containing:
  341. * - bundles: An array of bundles with the label, description, add_link keys.
  342. * - add_bundle_message: The message shown when there are no bundles. Only
  343. * available if the entity type uses bundle entities.
  344. */
  345. function template_preprocess_entity_add_list(&$variables) {
  346. foreach ($variables['bundles'] as $bundle_name => $bundle_info) {
  347. $variables['bundles'][$bundle_name]['description'] = [
  348. '#markup' => $bundle_info['description'],
  349. ];
  350. }
  351. }
  352. /**
  353. * @defgroup authorize Authorized operations
  354. * @{
  355. * Functions to run operations with elevated privileges via authorize.php.
  356. *
  357. * Because of the Update manager functionality included in Drupal core, there
  358. * is a mechanism for running operations with elevated file system privileges,
  359. * the top-level authorize.php script. This script runs at a reduced Drupal
  360. * bootstrap level so that it is not reliant on the entire site being
  361. * functional. The operations use a FileTransfer class to manipulate code
  362. * installed on the system as the user that owns the files, not the user that
  363. * the httpd is running as.
  364. *
  365. * The first setup is to define a callback function that should be authorized
  366. * to run with the elevated privileges. This callback should take a
  367. * FileTransfer as its first argument, although you can define an array of
  368. * other arguments it should be invoked with. The callback should be placed in
  369. * a separate .inc file that will be included by authorize.php.
  370. *
  371. * To run the operation, certain data must be saved into the SESSION, and then
  372. * the flow of control should be redirected to the authorize.php script. There
  373. * are two ways to do this, either to call system_authorized_run() directly,
  374. * or to call system_authorized_init() and then redirect to authorize.php,
  375. * using the URL from system_authorized_get_url(). Redirecting yourself is
  376. * necessary when your authorized operation is being triggered by a form
  377. * submit handler, since calling redirecting in a submit handler is a bad
  378. * idea, and you should instead use $form_state->setRedirect().
  379. *
  380. * Once the SESSION is setup for the operation and the user is redirected to
  381. * authorize.php, they will be prompted for their connection credentials (core
  382. * provides FTP and SSH by default, although other connection classes can be
  383. * added via contributed modules). With valid credentials, authorize.php will
  384. * instantiate the appropriate FileTransfer object, and then invoke the
  385. * desired operation passing in that object. The authorize.php script can act
  386. * as a Batch API processing page, if the operation requires a batch.
  387. *
  388. * @see authorize.php
  389. * @see \Drupal\Core\FileTransfer\FileTransfer
  390. * @see hook_filetransfer_info()
  391. */
  392. /**
  393. * Setup a given callback to run via authorize.php with elevated privileges.
  394. *
  395. * To use authorize.php, certain variables must be stashed into $_SESSION. This
  396. * function sets up all the necessary $_SESSION variables. The calling function
  397. * should then redirect to authorize.php, using the full path returned by
  398. * system_authorized_get_url(). That initiates the workflow that will eventually
  399. * lead to the callback being invoked. The callback will be invoked at a low
  400. * bootstrap level, without all modules being invoked, so it needs to be careful
  401. * not to assume any code exists. Example (system_authorized_run()):
  402. * @code
  403. * system_authorized_init($callback, $file, $arguments, $page_title);
  404. * return new RedirectResponse(system_authorized_get_url()->toString());
  405. * @endcode
  406. * Example (update_manager_install_form_submit()):
  407. * @code
  408. * system_authorized_init('update_authorize_run_install',
  409. * drupal_get_path('module', 'update') . '/update.authorize.inc',
  410. * $arguments, t('Update manager'));
  411. * $form_state->setRedirectUrl(system_authorized_get_url());
  412. * @endcode
  413. *
  414. * @param $callback
  415. * The name of the function to invoke once the user authorizes the operation.
  416. * @param $file
  417. * The full path to the file where the callback function is implemented.
  418. * @param $arguments
  419. * Optional array of arguments to pass into the callback when it is invoked.
  420. * Note that the first argument to the callback is always the FileTransfer
  421. * object created by authorize.php when the user authorizes the operation.
  422. * @param $page_title
  423. * Optional string to use as the page title once redirected to authorize.php.
  424. * @return
  425. * Nothing, this function just initializes variables in the user's session.
  426. */
  427. function system_authorized_init($callback, $file, $arguments = [], $page_title = NULL) {
  428. // First, figure out what file transfer backends the site supports, and put
  429. // all of those in the SESSION so that authorize.php has access to all of
  430. // them via the class autoloader, even without a full bootstrap.
  431. $_SESSION['authorize_filetransfer_info'] = drupal_get_filetransfer_info();
  432. // Now, define the callback to invoke.
  433. $_SESSION['authorize_operation'] = [
  434. 'callback' => $callback,
  435. 'file' => $file,
  436. 'arguments' => $arguments,
  437. ];
  438. if (isset($page_title)) {
  439. $_SESSION['authorize_page_title'] = $page_title;
  440. }
  441. }
  442. /**
  443. * Return the URL for the authorize.php script.
  444. *
  445. * @param array $options
  446. * Optional array of options to set on the \Drupal\Core\Url object.
  447. * @return \Drupal\Core\Url
  448. * The full URL to authorize.php, using HTTPS if available.
  449. *
  450. * @see system_authorized_init()
  451. */
  452. function system_authorized_get_url(array $options = []) {
  453. // core/authorize.php is an unrouted URL, so using the base: scheme is
  454. // the correct usage for this case.
  455. $url = Url::fromUri('base:core/authorize.php');
  456. $url_options = $url->getOptions();
  457. $url->setOptions($options + $url_options);
  458. return $url;
  459. }
  460. /**
  461. * Returns the URL for the authorize.php script when it is processing a batch.
  462. *
  463. * @param array $options
  464. * Optional array of options to set on the \Drupal\Core\Url object.
  465. *
  466. * @return \Drupal\Core\Url
  467. */
  468. function system_authorized_batch_processing_url(array $options = []) {
  469. $options['query'] = ['batch' => '1'];
  470. return system_authorized_get_url($options);
  471. }
  472. /**
  473. * Setup and invoke an operation using authorize.php.
  474. *
  475. * @see system_authorized_init()
  476. */
  477. function system_authorized_run($callback, $file, $arguments = [], $page_title = NULL) {
  478. system_authorized_init($callback, $file, $arguments, $page_title);
  479. return new RedirectResponse(system_authorized_get_url()->toString());
  480. }
  481. /**
  482. * Use authorize.php to run batch_process().
  483. *
  484. * @see batch_process()
  485. */
  486. function system_authorized_batch_process() {
  487. $finish_url = system_authorized_get_url();
  488. $process_url = system_authorized_batch_processing_url();
  489. return batch_process($finish_url->setAbsolute()->toString(), $process_url);
  490. }
  491. /**
  492. * @} End of "defgroup authorize".
  493. */
  494. /**
  495. * Implements hook_updater_info().
  496. */
  497. function system_updater_info() {
  498. return [
  499. 'module' => [
  500. 'class' => 'Drupal\Core\Updater\Module',
  501. 'name' => t('Update modules'),
  502. 'weight' => 0,
  503. ],
  504. 'theme' => [
  505. 'class' => 'Drupal\Core\Updater\Theme',
  506. 'name' => t('Update themes'),
  507. 'weight' => 0,
  508. ],
  509. ];
  510. }
  511. /**
  512. * Implements hook_filetransfer_info().
  513. */
  514. function system_filetransfer_info() {
  515. $backends = [];
  516. // This is the default, will be available on most systems.
  517. if (function_exists('ftp_connect')) {
  518. $backends['ftp'] = [
  519. 'title' => t('FTP'),
  520. 'class' => 'Drupal\Core\FileTransfer\FTP',
  521. 'weight' => 0,
  522. ];
  523. }
  524. // SSH2 lib connection is only available if the proper PHP extension is
  525. // installed.
  526. if (function_exists('ssh2_connect')) {
  527. $backends['ssh'] = [
  528. 'title' => t('SSH'),
  529. 'class' => 'Drupal\Core\FileTransfer\SSH',
  530. 'weight' => 20,
  531. ];
  532. }
  533. return $backends;
  534. }
  535. /**
  536. * Implements hook_page_attachments().
  537. *
  538. * @see template_preprocess_maintenance_page()
  539. * @see \Drupal\Core\EventSubscriber\ActiveLinkResponseFilter
  540. */
  541. function system_page_attachments(array &$page) {
  542. // Ensure the same CSS is loaded in template_preprocess_maintenance_page().
  543. $page['#attached']['library'][] = 'system/base';
  544. if (\Drupal::service('router.admin_context')->isAdminRoute()) {
  545. $page['#attached']['library'][] = 'system/admin';
  546. }
  547. // Attach libraries used by this theme.
  548. $active_theme = \Drupal::theme()->getActiveTheme();
  549. foreach ($active_theme->getLibraries() as $library) {
  550. $page['#attached']['library'][] = $library;
  551. }
  552. // Attach favicon.
  553. if (theme_get_setting('features.favicon')) {
  554. $favicon = theme_get_setting('favicon.url');
  555. $type = theme_get_setting('favicon.mimetype');
  556. $page['#attached']['html_head_link'][][] = [
  557. 'rel' => 'shortcut icon',
  558. 'href' => UrlHelper::stripDangerousProtocols($favicon),
  559. 'type' => $type,
  560. ];
  561. }
  562. // Get the major Drupal version.
  563. list($version,) = explode('.', \Drupal::VERSION);
  564. // Attach default meta tags.
  565. $meta_default = [
  566. // Make sure the Content-Type comes first because the IE browser may be
  567. // vulnerable to XSS via encoding attacks from any content that comes
  568. // before this META tag, such as a TITLE tag.
  569. 'system_meta_content_type' => [
  570. '#tag' => 'meta',
  571. '#attributes' => [
  572. 'charset' => 'utf-8',
  573. ],
  574. // Security: This always has to be output first.
  575. '#weight' => -1000,
  576. ],
  577. // Show Drupal and the major version number in the META GENERATOR tag.
  578. 'system_meta_generator' => [
  579. '#type' => 'html_tag',
  580. '#tag' => 'meta',
  581. '#attributes' => [
  582. 'name' => 'Generator',
  583. 'content' => 'Drupal ' . $version . ' (https://www.drupal.org)',
  584. ],
  585. ],
  586. // Attach default mobile meta tags for responsive design.
  587. 'MobileOptimized' => [
  588. '#tag' => 'meta',
  589. '#attributes' => [
  590. 'name' => 'MobileOptimized',
  591. 'content' => 'width',
  592. ],
  593. ],
  594. 'HandheldFriendly' => [
  595. '#tag' => 'meta',
  596. '#attributes' => [
  597. 'name' => 'HandheldFriendly',
  598. 'content' => 'true',
  599. ],
  600. ],
  601. 'viewport' => [
  602. '#tag' => 'meta',
  603. '#attributes' => [
  604. 'name' => 'viewport',
  605. 'content' => 'width=device-width, initial-scale=1.0',
  606. ],
  607. ],
  608. ];
  609. foreach ($meta_default as $key => $value) {
  610. $page['#attached']['html_head'][] = [$value, $key];
  611. }
  612. // Handle setting the "active" class on links by:
  613. // - loading the active-link library if the current user is authenticated;
  614. // - applying a response filter if the current user is anonymous.
  615. // @see \Drupal\Core\Link
  616. // @see \Drupal\Core\Utility\LinkGenerator::generate()
  617. // @see template_preprocess_links()
  618. // @see \Drupal\Core\EventSubscriber\ActiveLinkResponseFilter
  619. if (\Drupal::currentUser()->isAuthenticated()) {
  620. $page['#attached']['library'][] = 'core/drupal.active-link';
  621. }
  622. }
  623. /**
  624. * Implements hook_js_settings_build().
  625. *
  626. * Sets values for the core/drupal.ajax library, which just depends on the
  627. * active theme but no other request-dependent values.
  628. */
  629. function system_js_settings_build(&$settings, AttachedAssetsInterface $assets) {
  630. // Generate the values for the core/drupal.ajax library.
  631. // We need to send ajaxPageState settings for core/drupal.ajax if:
  632. // - ajaxPageState is being loaded in this Response, in which case it will
  633. // already exist at $settings['ajaxPageState'] (because the core/drupal.ajax
  634. // library definition specifies a placeholder 'ajaxPageState' setting).
  635. // - core/drupal.ajax already has been loaded and hence this is an AJAX
  636. // Response in which we must send the list of extra asset libraries that are
  637. // being added in this AJAX Response.
  638. /** @var \Drupal\Core\Asset\LibraryDependencyResolver $library_dependency_resolver */
  639. $library_dependency_resolver = \Drupal::service('library.dependency_resolver');
  640. if (isset($settings['ajaxPageState']) || in_array('core/drupal.ajax', $library_dependency_resolver->getLibrariesWithDependencies($assets->getAlreadyLoadedLibraries()))) {
  641. // Provide the page with information about the theme that's used, so that
  642. // a later AJAX request can be rendered using the same theme.
  643. // @see \Drupal\Core\Theme\AjaxBasePageNegotiator
  644. $theme_key = \Drupal::theme()->getActiveTheme()->getName();
  645. $settings['ajaxPageState']['theme'] = $theme_key;
  646. }
  647. }
  648. /**
  649. * Implements hook_js_settings_alter().
  650. *
  651. * Sets values which depend on the current request, like core/drupalSettings
  652. * as well as theme_token ajax state.
  653. */
  654. function system_js_settings_alter(&$settings, AttachedAssetsInterface $assets) {
  655. // As this is being output in the final response always use the master
  656. // request.
  657. $request = \Drupal::requestStack()->getMasterRequest();
  658. $current_query = $request->query->all();
  659. // Let output path processors set a prefix.
  660. /** @var \Drupal\Core\PathProcessor\OutboundPathProcessorInterface $path_processor */
  661. $path_processor = \Drupal::service('path_processor_manager');
  662. $options = ['prefix' => ''];
  663. $path_processor->processOutbound('/', $options);
  664. $pathPrefix = $options['prefix'];
  665. $route_match = \Drupal::routeMatch();
  666. if ($route_match instanceof StackedRouteMatchInterface) {
  667. $route_match = $route_match->getMasterRouteMatch();
  668. }
  669. $current_path = $route_match->getRouteName() ? Url::fromRouteMatch($route_match)->getInternalPath() : '';
  670. $current_path_is_admin = \Drupal::service('router.admin_context')->isAdminRoute($route_match->getRouteObject());
  671. $path_settings = [
  672. 'baseUrl' => $request->getBaseUrl() . '/',
  673. 'pathPrefix' => $pathPrefix,
  674. 'currentPath' => $current_path,
  675. 'currentPathIsAdmin' => $current_path_is_admin,
  676. 'isFront' => \Drupal::service('path.matcher')->isFrontPage(),
  677. 'currentLanguage' => \Drupal::languageManager()->getCurrentLanguage(LanguageInterface::TYPE_URL)->getId(),
  678. ];
  679. if (!empty($current_query)) {
  680. ksort($current_query);
  681. $path_settings['currentQuery'] = (object) $current_query;
  682. }
  683. // Only set core/drupalSettings values that haven't been set already.
  684. foreach ($path_settings as $key => $value) {
  685. if (!isset($settings['path'][$key])) {
  686. $settings['path'][$key] = $value;
  687. }
  688. }
  689. if (!isset($settings['pluralDelimiter'])) {
  690. $settings['pluralDelimiter'] = LOCALE_PLURAL_DELIMITER;
  691. }
  692. // Add the theme token to ajaxPageState, ensuring the database is available
  693. // before doing so. Also add the loaded libraries to ajaxPageState.
  694. /** @var \Drupal\Core\Asset\LibraryDependencyResolver $library_dependency_resolver */
  695. $library_dependency_resolver = \Drupal::service('library.dependency_resolver');
  696. if (isset($settings['ajaxPageState']) || in_array('core/drupal.ajax', $library_dependency_resolver->getLibrariesWithDependencies($assets->getAlreadyLoadedLibraries()))) {
  697. if (!defined('MAINTENANCE_MODE')) {
  698. // The theme token is only validated when the theme requested is not the
  699. // default, so don't generate it unless necessary.
  700. // @see \Drupal\Core\Theme\AjaxBasePageNegotiator::determineActiveTheme()
  701. $active_theme_key = \Drupal::theme()->getActiveTheme()->getName();
  702. if ($active_theme_key !== \Drupal::service('theme_handler')->getDefault()) {
  703. $settings['ajaxPageState']['theme_token'] = \Drupal::csrfToken()
  704. ->get($active_theme_key);
  705. }
  706. }
  707. // Provide the page with information about the individual asset libraries
  708. // used, information not otherwise available when aggregation is enabled.
  709. $minimal_libraries = $library_dependency_resolver->getMinimalRepresentativeSubset(array_merge(
  710. $assets->getLibraries(),
  711. $assets->getAlreadyLoadedLibraries()
  712. ));
  713. sort($minimal_libraries);
  714. $settings['ajaxPageState']['libraries'] = implode(',', $minimal_libraries);
  715. }
  716. }
  717. /**
  718. * Implements hook_form_alter().
  719. */
  720. function system_form_alter(&$form, FormStateInterface $form_state) {
  721. // If the page that's being built is cacheable, set the 'immutable' flag, to
  722. // ensure that when the form is used, a new form build ID is generated when
  723. // appropriate, to prevent information disclosure.
  724. // Note: This code just wants to know whether cache response headers are set,
  725. // not whether page_cache module will be active.
  726. // \Drupal\Core\EventSubscriber\FinishResponseSubscriber::onRespond will
  727. // send those headers, in case $request_policy->check($request) succeeds. In
  728. // that case we need to ensure that the immutable flag is sot, so future POST
  729. // request won't take over the form state of another user.
  730. /** @var \Drupal\Core\PageCache\RequestPolicyInterface $request_policy */
  731. $request_policy = \Drupal::service('page_cache_request_policy');
  732. $request = \Drupal::requestStack()->getCurrentRequest();
  733. $request_is_cacheable = $request_policy->check($request) === RequestPolicyInterface::ALLOW;
  734. if ($request_is_cacheable) {
  735. $form_state->addBuildInfo('immutable', TRUE);
  736. }
  737. }
  738. /**
  739. * Implements hook_form_FORM_ID_alter() for \Drupal\user\AccountForm.
  740. */
  741. function system_form_user_form_alter(&$form, FormStateInterface $form_state) {
  742. if (\Drupal::config('system.date')->get('timezone.user.configurable')) {
  743. system_user_timezone($form, $form_state);
  744. }
  745. }
  746. /**
  747. * Implements hook_form_FORM_ID_alter() for \Drupal\user\RegisterForm.
  748. */
  749. function system_form_user_register_form_alter(&$form, FormStateInterface $form_state) {
  750. $config = \Drupal::config('system.date');
  751. if ($config->get('timezone.user.configurable') && $config->get('timezone.user.default') == DRUPAL_USER_TIMEZONE_SELECT) {
  752. system_user_timezone($form, $form_state);
  753. }
  754. }
  755. /**
  756. * Implements hook_ENTITY_TYPE_presave() for user entities.
  757. */
  758. function system_user_presave(UserInterface $account) {
  759. $config = \Drupal::config('system.date');
  760. if ($config->get('timezone.user.configurable') && !$account->getTimeZone() && !$config->get('timezone.user.default')) {
  761. $account->timezone = $config->get('timezone.default');
  762. }
  763. }
  764. /**
  765. * Implements hook_user_login().
  766. */
  767. function system_user_login(UserInterface $account) {
  768. $config = \Drupal::config('system.date');
  769. // If the user has a NULL time zone, notify them to set a time zone.
  770. if (!$account->getTimezone() && $config->get('timezone.user.configurable') && $config->get('timezone.user.warn')) {
  771. drupal_set_message(t('Configure your <a href=":user-edit">account time zone setting</a>.', [':user-edit' => $account->url('edit-form', ['query' => \Drupal::destination()->getAsArray(), 'fragment' => 'edit-timezone'])]));
  772. }
  773. }
  774. /**
  775. * Add the time zone field to the user edit and register forms.
  776. */
  777. function system_user_timezone(&$form, FormStateInterface $form_state) {
  778. $user = \Drupal::currentUser();
  779. $account = $form_state->getFormObject()->getEntity();
  780. $form['timezone'] = [
  781. '#type' => 'details',
  782. '#title' => t('Locale settings'),
  783. '#open' => TRUE,
  784. '#weight' => 6,
  785. ];
  786. $form['timezone']['timezone'] = [
  787. '#type' => 'select',
  788. '#title' => t('Time zone'),
  789. '#default_value' => $account->getTimezone() ? $account->getTimezone() : \Drupal::config('system.date')->get('timezone.default'),
  790. '#options' => system_time_zones($account->id() != $user->id(), TRUE),
  791. '#description' => t('Select the desired local time and time zone. Dates and times throughout this site will be displayed using this time zone.'),
  792. ];
  793. $user_input = $form_state->getUserInput();
  794. if (!$account->getTimezone() && $account->id() == $user->id() && empty($user_input['timezone'])) {
  795. $form['timezone']['#attached']['library'][] = 'core/drupal.timezone';
  796. $form['timezone']['timezone']['#attributes'] = ['class' => ['timezone-detect']];
  797. }
  798. }
  799. /**
  800. * Implements hook_preprocess_HOOK() for block templates.
  801. */
  802. function system_preprocess_block(&$variables) {
  803. switch ($variables['base_plugin_id']) {
  804. case 'system_branding_block':
  805. $variables['site_logo'] = '';
  806. if ($variables['content']['site_logo']['#access'] && $variables['content']['site_logo']['#uri']) {
  807. $variables['site_logo'] = $variables['content']['site_logo']['#uri'];
  808. }
  809. $variables['site_name'] = '';
  810. if ($variables['content']['site_name']['#access'] && $variables['content']['site_name']['#markup']) {
  811. $variables['site_name'] = $variables['content']['site_name']['#markup'];
  812. }
  813. $variables['site_slogan'] = '';
  814. if ($variables['content']['site_slogan']['#access'] && $variables['content']['site_slogan']['#markup']) {
  815. $variables['site_slogan'] = [
  816. '#markup' => $variables['content']['site_slogan']['#markup'],
  817. ];
  818. }
  819. break;
  820. case 'system_powered_by_block':
  821. $variables['attributes']['role'] = 'complementary';
  822. break;
  823. }
  824. }
  825. /**
  826. * Checks the existence of the directory specified in $form_element.
  827. *
  828. * This function is called from the system_settings form to check all core
  829. * file directories (file_public_path, file_private_path, file_temporary_path).
  830. *
  831. * @param $form_element
  832. * The form element containing the name of the directory to check.
  833. * @param \Drupal\Core\Form\FormStateInterface $form_state
  834. * The current state of the form.
  835. */
  836. function system_check_directory($form_element, FormStateInterface $form_state) {
  837. $directory = $form_element['#value'];
  838. if (strlen($directory) == 0) {
  839. return $form_element;
  840. }
  841. $logger = \Drupal::logger('file system');
  842. if (!is_dir($directory) && !drupal_mkdir($directory, NULL, TRUE)) {
  843. // If the directory does not exists and cannot be created.
  844. $form_state->setErrorByName($form_element['#parents'][0], t('The directory %directory does not exist and could not be created.', ['%directory' => $directory]));
  845. $logger->error('The directory %directory does not exist and could not be created.', ['%directory' => $directory]);
  846. }
  847. if (is_dir($directory) && !is_writable($directory) && !drupal_chmod($directory)) {
  848. // If the directory is not writable and cannot be made so.
  849. $form_state->setErrorByName($form_element['#parents'][0], t('The directory %directory exists but is not writable and could not be made writable.', ['%directory' => $directory]));
  850. $logger->error('The directory %directory exists but is not writable and could not be made writable.', ['%directory' => $directory]);
  851. }
  852. elseif (is_dir($directory)) {
  853. if ($form_element['#name'] == 'file_public_path') {
  854. // Create public .htaccess file.
  855. file_save_htaccess($directory, FALSE);
  856. }
  857. else {
  858. // Create private .htaccess file.
  859. file_save_htaccess($directory);
  860. }
  861. }
  862. return $form_element;
  863. }
  864. /**
  865. * Returns an array of information about enabled modules or themes.
  866. *
  867. * This function returns the contents of the .info.yml file for each installed
  868. * module or theme.
  869. *
  870. * @param $type
  871. * Either 'module' or 'theme'.
  872. * @param $name
  873. * (optional) The name of a module or theme whose information shall be
  874. * returned. If omitted, all records for the provided $type will be returned.
  875. * If $name does not exist in the provided $type or is not enabled, an empty
  876. * array will be returned.
  877. *
  878. * @return
  879. * An associative array of module or theme information keyed by name, or only
  880. * information for $name, if given. If no records are available, an empty
  881. * array is returned.
  882. *
  883. * @see system_rebuild_module_data()
  884. * @see \Drupal\Core\Extension\ThemeHandlerInterface::rebuildThemeData()
  885. */
  886. function system_get_info($type, $name = NULL) {
  887. if ($type == 'module') {
  888. $info = &drupal_static(__FUNCTION__);
  889. if (!isset($info)) {
  890. if ($cache = \Drupal::cache()->get('system.module.info')) {
  891. $info = $cache->data;
  892. }
  893. else {
  894. $data = system_rebuild_module_data();
  895. foreach (\Drupal::moduleHandler()->getModuleList() as $module => $filename) {
  896. if (isset($data[$module])) {
  897. $info[$module] = $data[$module]->info;
  898. }
  899. }
  900. // Store the module information in cache. This cache is cleared by
  901. // calling system_rebuild_module_data(), for example, when listing
  902. // modules, (un)installing modules, importing configuration, updating
  903. // the site and when flushing all the caches.
  904. \Drupal::cache()->set('system.module.info', $info);
  905. }
  906. }
  907. }
  908. else {
  909. $info = [];
  910. $list = system_list($type);
  911. foreach ($list as $shortname => $item) {
  912. if (!empty($item->status)) {
  913. $info[$shortname] = $item->info;
  914. }
  915. }
  916. }
  917. if (isset($name)) {
  918. return isset($info[$name]) ? $info[$name] : [];
  919. }
  920. return $info;
  921. }
  922. /**
  923. * Helper function to scan and collect module .info.yml data.
  924. *
  925. * @return \Drupal\Core\Extension\Extension[]
  926. * An associative array of module information.
  927. */
  928. function _system_rebuild_module_data() {
  929. $listing = new ExtensionDiscovery(\Drupal::root());
  930. // Find installation profiles. This needs to happen before performing a
  931. // module scan as the module scan requires knowing what the active profile is.
  932. // @todo Remove as part of https://www.drupal.org/node/2186491.
  933. $profiles = $listing->scan('profile');
  934. $profile = drupal_get_profile();
  935. if ($profile && isset($profiles[$profile])) {
  936. // Prime the drupal_get_filename() static cache with the profile info file
  937. // location so we can use drupal_get_path() on the active profile during
  938. // the module scan.
  939. // @todo Remove as part of https://www.drupal.org/node/2186491.
  940. drupal_get_filename('profile', $profile, $profiles[$profile]->getPathname());
  941. }
  942. // Find modules.
  943. $modules = $listing->scan('module');
  944. // Include the installation profile in modules that are loaded.
  945. if ($profile) {
  946. $modules[$profile] = $profiles[$profile];
  947. // Installation profile hooks are always executed last.
  948. $modules[$profile]->weight = 1000;
  949. }
  950. // Set defaults for module info.
  951. $defaults = [
  952. 'dependencies' => [],
  953. 'description' => '',
  954. 'package' => 'Other',
  955. 'version' => NULL,
  956. 'php' => DRUPAL_MINIMUM_PHP,
  957. ];
  958. // Read info files for each module.
  959. foreach ($modules as $key => $module) {
  960. // Look for the info file.
  961. $module->info = \Drupal::service('info_parser')->parse($module->getPathname());
  962. // Add the info file modification time, so it becomes available for
  963. // contributed modules to use for ordering module lists.
  964. $module->info['mtime'] = $module->getMTime();
  965. // Merge in defaults and save.
  966. $modules[$key]->info = $module->info + $defaults;
  967. // Installation profiles are hidden by default, unless explicitly specified
  968. // otherwise in the .info.yml file.
  969. if ($key == $profile && !isset($modules[$key]->info['hidden'])) {
  970. $modules[$key]->info['hidden'] = TRUE;
  971. }
  972. // Invoke hook_system_info_alter() to give installed modules a chance to
  973. // modify the data in the .info.yml files if necessary.
  974. // @todo Remove $type argument, obsolete with $module->getType().
  975. $type = 'module';
  976. \Drupal::moduleHandler()->alter('system_info', $modules[$key]->info, $modules[$key], $type);
  977. }
  978. // It is possible that a module was marked as required by
  979. // hook_system_info_alter() and modules that it depends on are not required.
  980. foreach ($modules as $module) {
  981. _system_rebuild_module_data_ensure_required($module, $modules);
  982. }
  983. if ($profile && isset($modules[$profile])) {
  984. // The installation profile is required, if it's a valid module.
  985. $modules[$profile]->info['required'] = TRUE;
  986. // Add a default distribution name if the profile did not provide one.
  987. // @see install_profile_info()
  988. // @see drupal_install_profile_distribution_name()
  989. if (!isset($modules[$profile]->info['distribution']['name'])) {
  990. $modules[$profile]->info['distribution']['name'] = 'Drupal';
  991. }
  992. }
  993. return $modules;
  994. }
  995. /**
  996. * Ensures that dependencies of required modules are also required.
  997. *
  998. * @param \Drupal\Core\Extension\Extension $module
  999. * The module info.
  1000. * @param \Drupal\Core\Extension\Extension[] $modules
  1001. * The array of all module info.
  1002. */
  1003. function _system_rebuild_module_data_ensure_required($module, &$modules) {
  1004. if (!empty($module->info['required'])) {
  1005. foreach ($module->info['dependencies'] as $dependency) {
  1006. $dependency_name = ModuleHandler::parseDependency($dependency)['name'];
  1007. if (!isset($modules[$dependency_name]->info['required'])) {
  1008. $modules[$dependency_name]->info['required'] = TRUE;
  1009. $modules[$dependency_name]->info['explanation'] = t('Dependency of required module @module', ['@module' => $module->info['name']]);
  1010. // Ensure any dependencies it has are required.
  1011. _system_rebuild_module_data_ensure_required($modules[$dependency_name], $modules);
  1012. }
  1013. }
  1014. }
  1015. }
  1016. /**
  1017. * Rebuild, save, and return data about all currently available modules.
  1018. *
  1019. * @return \Drupal\Core\Extension\Extension[]
  1020. * Array of all available modules and their data.
  1021. */
  1022. function system_rebuild_module_data() {
  1023. $modules_cache = &drupal_static(__FUNCTION__);
  1024. // Only rebuild once per request. $modules and $modules_cache cannot be
  1025. // combined into one variable, because the $modules_cache variable is reset by
  1026. // reference from system_list_reset() during the rebuild.
  1027. if (!isset($modules_cache)) {
  1028. $modules = _system_rebuild_module_data();
  1029. $files = [];
  1030. ksort($modules);
  1031. // Add status, weight, and schema version.
  1032. $installed_modules = \Drupal::config('core.extension')->get('module') ?: [];
  1033. foreach ($modules as $name => $module) {
  1034. $module->weight = isset($installed_modules[$name]) ? $installed_modules[$name] : 0;
  1035. $module->status = (int) isset($installed_modules[$name]);
  1036. $module->schema_version = SCHEMA_UNINSTALLED;
  1037. $files[$name] = $module->getPathname();
  1038. }
  1039. $modules = \Drupal::moduleHandler()->buildModuleDependencies($modules);
  1040. $modules_cache = $modules;
  1041. // Store filenames to allow drupal_get_filename() to retrieve them without
  1042. // having to rebuild or scan the filesystem.
  1043. \Drupal::state()->set('system.module.files', $files);
  1044. // Clear the module info cache.
  1045. \Drupal::cache()->delete('system.module.info');
  1046. drupal_static_reset('system_get_info');
  1047. }
  1048. return $modules_cache;
  1049. }
  1050. /**
  1051. * Get a list of available regions from a specified theme.
  1052. *
  1053. * @param \Drupal\Core\Extension\Extension|string $theme
  1054. * A theme extension object, or the name of a theme.
  1055. * @param $show
  1056. * Possible values: REGIONS_ALL or REGIONS_VISIBLE. Visible excludes hidden
  1057. * regions.
  1058. * @return
  1059. * An array of regions in the form $region['name'] = 'description'.
  1060. */
  1061. function system_region_list($theme, $show = REGIONS_ALL) {
  1062. if (!$theme instanceof Extension) {
  1063. $themes = \Drupal::service('theme_handler')->listInfo();
  1064. if (!isset($themes[$theme])) {
  1065. return [];
  1066. }
  1067. $theme = $themes[$theme];
  1068. }
  1069. $list = [];
  1070. $info = $theme->info;
  1071. // If requested, suppress hidden regions. See block_admin_display_form().
  1072. foreach ($info['regions'] as $name => $label) {
  1073. if ($show == REGIONS_ALL || !isset($info['regions_hidden']) || !in_array($name, $info['regions_hidden'])) {
  1074. $list[$name] = t($label);
  1075. }
  1076. }
  1077. return $list;
  1078. }
  1079. /**
  1080. * Array sorting callback; sorts modules by their name.
  1081. */
  1082. function system_sort_modules_by_info_name($a, $b) {
  1083. return strcasecmp($a->info['name'], $b->info['name']);
  1084. }
  1085. /**
  1086. * Sorts themes by their names, with the default theme listed first.
  1087. *
  1088. * Callback for uasort() within
  1089. * \Drupal\system\Controller\SystemController::themesPage().
  1090. *
  1091. * @see system_sort_modules_by_info_name()
  1092. */
  1093. function system_sort_themes($a, $b) {
  1094. if ($a->is_default) {
  1095. return -1;
  1096. }
  1097. if ($b->is_default) {
  1098. return 1;
  1099. }
  1100. return strcasecmp($a->info['name'], $b->info['name']);
  1101. }
  1102. /**
  1103. * Implements hook_system_info_alter().
  1104. */
  1105. function system_system_info_alter(&$info, Extension $file, $type) {
  1106. // Remove page-top and page-bottom from the blocks UI since they are reserved for
  1107. // modules to populate from outside the blocks system.
  1108. if ($type == 'theme') {
  1109. $info['regions_hidden'][] = 'page_top';
  1110. $info['regions_hidden'][] = 'page_bottom';
  1111. }
  1112. }
  1113. /**
  1114. * Gets the name of the default region for a given theme.
  1115. *
  1116. * @param $theme
  1117. * The name of a theme.
  1118. * @return
  1119. * A string that is the region name.
  1120. */
  1121. function system_default_region($theme) {
  1122. $regions = array_keys(system_region_list($theme, REGIONS_VISIBLE));
  1123. return isset($regions[0]) ? $regions[0] : '';
  1124. }
  1125. /**
  1126. * Determines whether the current user is in compact mode.
  1127. *
  1128. * Compact mode shows certain administration pages with less description text,
  1129. * such as the configuration page and the permissions page.
  1130. *
  1131. * Whether the user is in compact mode is determined by a cookie, which is set
  1132. * for the user by \Drupal\system\Controller\SystemController::compactPage().
  1133. *
  1134. * If the user does not have the cookie, the default value is given by the
  1135. * configuration variable 'system.site.admin_compact_mode', which itself
  1136. * defaults to FALSE. This does not have a user interface to set it: it is a
  1137. * hidden variable which can be set in the settings.php file.
  1138. *
  1139. * @return bool
  1140. * TRUE when in compact mode, FALSE when in expanded mode.
  1141. */
  1142. function system_admin_compact_mode() {
  1143. // PHP converts dots into underscores in cookie names to avoid problems with
  1144. // its parser, so we use a converted cookie name.
  1145. return \Drupal::request()->cookies->get('Drupal_visitor_admin_compact_mode', \Drupal::config('system.site')->get('admin_compact_mode'));
  1146. }
  1147. /**
  1148. * Generate a list of tasks offered by a specified module.
  1149. *
  1150. * @param string $module
  1151. * Module name.
  1152. * @param array $info
  1153. * The module's information, as provided by system_get_info().
  1154. *
  1155. * @return array
  1156. * An array of task links.
  1157. */
  1158. function system_get_module_admin_tasks($module, array $info) {
  1159. $tree = &drupal_static(__FUNCTION__);
  1160. $menu_tree = \Drupal::menuTree();
  1161. if (!isset($tree)) {
  1162. $parameters = new MenuTreeParameters();
  1163. $parameters->setRoot('system.admin')->excludeRoot()->onlyEnabledLinks();
  1164. $tree = $menu_tree->load('system.admin', $parameters);
  1165. $manipulators = [
  1166. ['callable' => 'menu.default_tree_manipulators:checkAccess'],
  1167. ['callable' => 'menu.default_tree_manipulators:generateIndexAndSort'],
  1168. ['callable' => 'menu.default_tree_manipulators:flatten'],
  1169. ];
  1170. $tree = $menu_tree->transform($tree, $manipulators);
  1171. }
  1172. $admin_tasks = [];
  1173. foreach ($tree as $element) {
  1174. if (!$element->access->isAllowed()) {
  1175. // @todo Bubble cacheability metadata of both accessible and inaccessible
  1176. // links. Currently made impossible by the way admin tasks are rendered.
  1177. continue;
  1178. }
  1179. $link = $element->link;
  1180. if ($link->getProvider() != $module) {
  1181. continue;
  1182. }
  1183. $admin_tasks[] = [
  1184. 'title' => $link->getTitle(),
  1185. 'description' => $link->getDescription(),
  1186. 'url' => $link->getUrlObject(),
  1187. ];
  1188. }
  1189. // Append link for permissions.
  1190. /** @var \Drupal\user\PermissionHandlerInterface $permission_handler */
  1191. $permission_handler = \Drupal::service('user.permissions');
  1192. if ($permission_handler->moduleProvidesPermissions($module)) {
  1193. /** @var \Drupal\Core\Access\AccessManagerInterface $access_manager */
  1194. $access_manager = \Drupal::service('access_manager');
  1195. if ($access_manager->checkNamedRoute('user.admin_permissions', [], \Drupal::currentUser())) {
  1196. /** @var \Drupal\Core\Url $url */
  1197. $url = new Url('user.admin_permissions');
  1198. $url->setOption('fragment', 'module-' . $module);
  1199. $admin_tasks["user.admin_permissions.$module"] = [
  1200. 'title' => t('Configure @module permissions', ['@module' => $info['name']]),
  1201. 'description' => '',
  1202. 'url' => $url,
  1203. ];
  1204. }
  1205. }
  1206. return $admin_tasks;
  1207. }
  1208. /**
  1209. * Implements hook_cron().
  1210. *
  1211. * Remove older rows from flood, batch cache and expirable keyvalue tables.
  1212. */
  1213. function system_cron() {
  1214. // Clean up the flood.
  1215. \Drupal::flood()->garbageCollection();
  1216. foreach (Cache::getBins() as $cache_backend) {
  1217. $cache_backend->garbageCollection();
  1218. }
  1219. // Clean up the expirable key value database store.
  1220. if (\Drupal::service('keyvalue.expirable.database') instanceof KeyValueDatabaseExpirableFactory) {
  1221. \Drupal::service('keyvalue.expirable.database')->garbageCollection();
  1222. }
  1223. // Clean up any garbage in the queue service.
  1224. $queue_worker_manager = \Drupal::service('plugin.manager.queue_worker');
  1225. $queue_factory = \Drupal::service('queue');
  1226. foreach (array_keys($queue_worker_manager->getDefinitions()) as $queue_name) {
  1227. $queue = $queue_factory->get($queue_name);
  1228. if ($queue instanceof QueueGarbageCollectionInterface) {
  1229. $queue->garbageCollection();
  1230. }
  1231. }
  1232. // Clean up PHP storage.
  1233. PhpStorageFactory::get('container')->garbageCollection();
  1234. PhpStorageFactory::get('service_container')->garbageCollection();
  1235. }
  1236. /**
  1237. * Implements hook_mail().
  1238. */
  1239. function system_mail($key, &$message, $params) {
  1240. $token_service = \Drupal::token();
  1241. $context = $params['context'];
  1242. $subject = PlainTextOutput::renderFromHtml($token_service->replace($context['subject'], $context));
  1243. $body = $token_service->replace($context['message'], $context);
  1244. $message['subject'] .= str_replace(["\r", "\n"], '', $subject);
  1245. $message['body'][] = $body;
  1246. }
  1247. /**
  1248. * Generate an array of time zones and their local time&date.
  1249. *
  1250. * @param mixed $blank
  1251. * If evaluates true, prepend an empty time zone option to the array.
  1252. * @param bool $grouped
  1253. * (optional) Whether the timezones should be grouped by region.
  1254. *
  1255. * @return array
  1256. * An array or nested array containing time zones, keyed by the system name.
  1257. */
  1258. function system_time_zones($blank = NULL, $grouped = FALSE) {
  1259. $zonelist = timezone_identifiers_list();
  1260. $zones = $blank ? ['' => t('- None selected -')] : [];
  1261. foreach ($zonelist as $zone) {
  1262. // Because many time zones exist in PHP only for backward compatibility
  1263. // reasons and should not be used, the list is filtered by a regular
  1264. // expression.
  1265. if (preg_match('!^((Africa|America|Antarctica|Arctic|Asia|Atlantic|Australia|Europe|Indian|Pacific)/|UTC$)!', $zone)) {
  1266. $zones[$zone] = t('@zone', ['@zone' => t(str_replace('_', ' ', $zone))]);
  1267. }
  1268. }
  1269. // Sort the translated time zones alphabetically.
  1270. asort($zones);
  1271. if ($grouped) {
  1272. $grouped_zones = [];
  1273. foreach ($zones as $key => $value) {
  1274. $split = explode('/', $value);
  1275. $city = array_pop($split);
  1276. $region = array_shift($split);
  1277. if (!empty($region)) {
  1278. $grouped_zones[$region][$key] = empty($split) ? $city : $city . ' (' . implode('/', $split) . ')';
  1279. }
  1280. else {
  1281. $grouped_zones[$key] = $value;
  1282. }
  1283. }
  1284. foreach ($grouped_zones as $key => $value) {
  1285. if (is_array($grouped_zones[$key])) {
  1286. asort($grouped_zones[$key]);
  1287. }
  1288. }
  1289. $zones = $grouped_zones;
  1290. }
  1291. return $zones;
  1292. }
  1293. /**
  1294. * Attempts to get a file using Guzzle HTTP client and to store it locally.
  1295. *
  1296. * @param string $url
  1297. * The URL of the file to grab.
  1298. * @param string $destination
  1299. * Stream wrapper URI specifying where the file should be placed. If a
  1300. * directory path is provided, the file is saved into that directory under
  1301. * its original name. If the path contains a filename as well, that one will
  1302. * be used instead.
  1303. * If this value is omitted, the site's default files scheme will be used,
  1304. * usually "public://".
  1305. * @param bool $managed
  1306. * If this is set to TRUE, the file API hooks will be invoked and the file is
  1307. * registered in the database.
  1308. * @param int $replace
  1309. * Replace behavior when the destination file already exists:
  1310. * - FILE_EXISTS_REPLACE: Replace the existing file.
  1311. * - FILE_EXISTS_RENAME: Append _{incrementing number} until the filename is
  1312. * unique.
  1313. * - FILE_EXISTS_ERROR: Do nothing and return FALSE.
  1314. *
  1315. * @return mixed
  1316. * One of these possibilities:
  1317. * - If it succeeds and $managed is FALSE, the location where the file was
  1318. * saved.
  1319. * - If it succeeds and $managed is TRUE, a \Drupal\file\FileInterface
  1320. * object which describes the file.
  1321. * - If it fails, FALSE.
  1322. */
  1323. function system_retrieve_file($url, $destination = NULL, $managed = FALSE, $replace = FILE_EXISTS_RENAME) {
  1324. $parsed_url = parse_url($url);
  1325. if (!isset($destination)) {
  1326. $path = file_build_uri(drupal_basename($parsed_url['path']));
  1327. }
  1328. else {
  1329. if (is_dir(drupal_realpath($destination))) {
  1330. // Prevent URIs with triple slashes when glueing parts together.
  1331. $path = str_replace('///', '//', "$destination/") . drupal_basename($parsed_url['path']);
  1332. }
  1333. else {
  1334. $path = $destination;
  1335. }
  1336. }
  1337. try {
  1338. $data = (string) \Drupal::httpClient()
  1339. ->get($url)
  1340. ->getBody();
  1341. $local = $managed ? file_save_data($data, $path, $replace) : file_unmanaged_save_data($data, $path, $replace);
  1342. }
  1343. catch (RequestException $exception) {
  1344. drupal_set_message(t('Failed to fetch file due to error "%error"', ['%error' => $exception->getMessage()]), 'error');
  1345. return FALSE;
  1346. }
  1347. if (!$local) {
  1348. drupal_set_message(t('@remote could not be saved to @path.', ['@remote' => $url, '@path' => $path]), 'error');
  1349. }
  1350. return $local;
  1351. }
  1352. /**
  1353. * Implements hook_entity_type_build().
  1354. */
  1355. function system_entity_type_build(array &$entity_types) {
  1356. /** @var $entity_types \Drupal\Core\Entity\EntityTypeInterface[] */
  1357. $entity_types['date_format']
  1358. ->setFormClass('add', 'Drupal\system\Form\DateFormatAddForm')
  1359. ->setFormClass('edit', 'Drupal\system\Form\DateFormatEditForm')
  1360. ->setFormClass('delete', 'Drupal\system\Form\DateFormatDeleteForm')
  1361. ->setListBuilderClass('Drupal\system\DateFormatListBuilder')
  1362. ->setLinkTemplate('edit-form', '/admin/config/regional/date-time/formats/manage/{date_format}')
  1363. ->setLinkTemplate('delete-form', '/admin/config/regional/date-time/formats/manage/{date_format}/delete')
  1364. ->setLinkTemplate('collection', '/admin/config/regional/date-time/formats');
  1365. }
  1366. /**
  1367. * Implements hook_block_view_BASE_BLOCK_ID_alter().
  1368. */
  1369. function system_block_view_system_main_block_alter(array &$build, BlockPluginInterface $block) {
  1370. // Contextual links on the system_main block would basically duplicate the
  1371. // tabs/local tasks, so reduce the clutter.
  1372. unset($build['#contextual_links']);
  1373. }
  1374. /**
  1375. * Implements hook_path_update().
  1376. */
  1377. function system_path_update($path) {
  1378. $alias_manager = \Drupal::service('path.alias_manager');
  1379. $alias_manager->cacheClear($path['source']);
  1380. $alias_manager->cacheClear($path['original']['source']);
  1381. }
  1382. /**
  1383. * Implements hook_path_insert().
  1384. */
  1385. function system_path_insert($path) {
  1386. \Drupal::service('path.alias_manager')->cacheClear($path['source']);
  1387. }
  1388. /**
  1389. * Implements hook_path_delete().
  1390. */
  1391. function system_path_delete($path) {
  1392. \Drupal::service('path.alias_manager')->cacheClear($path['source']);
  1393. }
  1394. /**
  1395. * Implements hook_query_TAG_alter() for entity reference selection handlers.
  1396. */
  1397. function system_query_entity_reference_alter(AlterableInterface $query) {
  1398. $handler = $query->getMetadata('entity_reference_selection_handler');
  1399. $handler->entityQueryAlter($query);
  1400. }