system.module 62 KB

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