Drupal investigation

system.module 61KB

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