' . t('About') . ''; $output .= '

' . 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 online documentation for the System module.', array('!system' => 'https://www.drupal.org/documentation/modules/system')) . '

'; $output .= '

' . t('Uses') . '

'; $output .= '
'; $output .= '
' . t('Managing modules') . '
'; $output .= '
' . t('Users with appropriate permission can install and uninstall modules from the Extend page. 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 Drupal.org module page. Note that uninstalling a module is a destructive action: when you uninstall a module, you will permanently lose all data connected to the module.', array('!modules' => \Drupal::url('system.modules_list'), '!drupal-modules' => 'https://www.drupal.org/project/modules')) . '
'; $output .= '
' . t('Managing themes') . '
'; $output .= '
' . t('Users with appropriate permission can install and uninstall themes on the Appearance page. 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 Drupal.org theme page.', array('!themes' => \Drupal::url('system.themes_page'), '!drupal-themes' => 'https://www.drupal.org/project/themes')) . '
'; $output .= '
' . t('Disabling drag-and-drop functionality') . '
'; $output .= '
' . 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.') . '
'; $output .= '
' . t('Configuring basic site settings') . '
'; $output .= '
' . t('The System module provides pages for managing basic site configuration, including Date and time formats and basic Site information (site name, email address to send mail from, home page, and error pages). Additional configuration pages are listed on the main Configuration page.', array('!date-time-settings' => \Drupal::url('entity.date_format.collection'), '!site-info' => \Drupal::url('system.site_information_settings'), '!config' => \Drupal::url('system.admin_config'))) . '
'; $output .= '
' . t('Using maintenance mode') . '
'; $output .= '
' . t('When you are performing site maintenance, you can prevent non-administrative users (including anonymous visitors) from viewing your site by putting it in Maintenance mode. 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.', array('!maintenance-mode' => \Drupal::url('system.site_maintenance_mode'))) . '
'; $output .= '
' . t('Managing the cache') . '
'; $output .= '
' . t('Users with appropriate permission can manage the system cache on the Performance page. If enabled, the cache system will re-use previously-built pages for anonymous page requests, instead of building them again. The site can also be configured to aggregate CSS and JavaScript files, making the total request size smaller. Depending on your site configuration and the amount of web traffic from anonymous visitors, the cache system may significantly increase the speed of your site.', array('!cache-settings' => \Drupal::url('system.performance_settings'))) . '
'; $output .= '
' . t('Configuring cron') . '
'; $output .= '
' . 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 cron tasks. On the Cron page, you can configure cron to run periodically as part of normal page requests, 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 Status report page. For more information, see the online documentation for configuring cron jobs.', array('!status' => \Drupal::url('system.status'), '!handbook' => 'https://www.drupal.org/cron', '!cron' => \Drupal::url('system.cron_settings'))) . '
'; $output .= '
' . t('Configuring the file system') . '
'; $output .= '
' . t('Your site has several file directories, which are used to store and process uploaded and generated files. The public 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 private 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 temporary file directory is used internally by your site code for various operations, and is configured on the File system settings 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.', array('!file-system' => \Drupal::url('system.file_system_settings'))) . '
'; $output .= '
' . t('Configuring the image toolkit') . '
'; $output .= '
' . t('On the Image toolkit page, 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.', array('!toolkit' => \Drupal::url('system.image_toolkit_settings'))) . '
'; $output .= '
'; return $output; case 'system.admin_index': return '

' . t('This page shows you all available administration tasks for each module.') . '

'; case 'system.themes_page': $output = '

' . t('Set and configure the default theme for your website. Alternative themes are available.', array('!themes' => 'https://www.drupal.org/project/themes')) . '

'; return $output; case 'system.theme_settings_theme': $theme_list = \Drupal::service('theme_handler')->listInfo(); $theme = $theme_list[$route_match->getParameter('theme')]; return '

' . t('These options control the display settings for the %name theme. When your site is displayed using this theme, these settings will be used.', array('%name' => $theme->info['name'])) . '

'; case 'system.theme_settings': return '

' . t('These options control the default display settings for your entire site, across all themes. Unless they have been overridden by a specific theme, these settings will be used.') . '

'; case 'system.modules_list': $output = '

' . t('Download additional contributed modules to extend your site\'s functionality.', array('!modules' => 'http://drupal.org/project/modules')) . '

'; if (\Drupal::moduleHandler()->moduleExists('update')) { if (update_manager_access()) { $output .= '

' . t('Regularly review and install available updates to maintain a secure and current site. Always run the update script each time a module is updated.', array('!update-php' => \Drupal::url('system.db_update'), '!updates' => \Drupal::url('update.status'))) . '

'; } else { $output .= '

' . t('Regularly review available updates to maintain a secure and current site. Always run the update script each time a module is updated.', array('!update-php' => \Drupal::url('system.db_update'), '!updates' => \Drupal::url('update.status'))) . '

'; } } else { $output .= '

' . t('Regularly review available updates to maintain a secure and current site. Always run the update script each time a module is updated. Enable the Update Manager module to update and install modules and themes.', array('!update-php' => \Drupal::url('system.db_update'))) . '

'; } return $output; case 'system.modules_uninstall': return '

' . t('The uninstall process removes all data related to a module.') . '

'; case 'entity.block.edit_form': if (($block = $route_match->getParameter('block')) && $block->getPluginId() == 'system_powered_by_block') { return '

' . t('The Powered by Drupal 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.') . '

'; } break; case 'block.admin_add': if ($route_match->getParameter('plugin_id') == 'system_powered_by_block') { return '

' . t('The Powered by Drupal 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.') . '

'; } break; case 'system.site_maintenance_mode': if (\Drupal::currentUser()->id() == 1) { return '

' . 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.') . '

'; } break; case 'system.status': return '

' . 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 system requirements.", array('!system-requirements' => 'https://www.drupal.org/requirements')) . '

'; } } /** * Implements hook_theme(). */ function system_theme() { return array_merge(drupal_common_theme(), array( // Normally theme suggestion templates are only picked up when they are in // themes. We explicitly define theme suggestions here so that the block // templates in core/modules/system/templates are picked up. 'block__system_branding_block' => array( 'render element' => 'elements', 'base hook' => 'block', ), 'block__system_messages_block' => array( 'base hook' => 'block', ), 'block__system_menu_block' => array( 'render element' => 'elements', 'base hook' => 'block', ), 'system_themes_page' => array( 'variables' => array( 'theme_groups' => array(), 'theme_group_titles' => array(), ), 'file' => 'system.admin.inc', ), 'system_config_form' => array( 'render element' => 'form', ), 'confirm_form' => array( 'render element' => 'form', ), 'system_modules_details' => array( 'render element' => 'form', 'file' => 'system.admin.inc', 'function' => 'theme_system_modules_details', ), 'system_modules_uninstall' => array( 'render element' => 'form', 'file' => 'system.admin.inc', 'function' => 'theme_system_modules_uninstall', ), 'status_report' => array( 'variables' => array('requirements' => NULL), 'file' => 'system.admin.inc', ), 'admin_page' => array( 'variables' => array('blocks' => NULL), 'file' => 'system.admin.inc', ), 'admin_block' => array( 'variables' => array('block' => NULL), 'file' => 'system.admin.inc', ), 'admin_block_content' => array( 'variables' => array('content' => NULL), 'file' => 'system.admin.inc', ), 'system_admin_index' => array( 'variables' => array('menu_items' => NULL), 'file' => 'system.admin.inc', ), )); } /** * Implements hook_hook_info(). */ function system_hook_info() { $hooks['token_info'] = array( 'group' => 'tokens', ); $hooks['token_info_alter'] = array( 'group' => 'tokens', ); $hooks['tokens'] = array( 'group' => 'tokens', ); $hooks['tokens_alter'] = array( 'group' => 'tokens', ); return $hooks; } /** * Implements hook_theme_suggestions_HOOK(). */ function system_theme_suggestions_html(array $variables) { if (\Drupal::service('path.matcher')->isFrontPage()) { $path_args = ['']; } else { $path_args = explode('/', Url::fromRoute('')->getInternalPath()); } return theme_get_suggestions($path_args, 'html'); } /** * Implements hook_theme_suggestions_HOOK(). */ function system_theme_suggestions_page(array $variables) { if (\Drupal::service('path.matcher')->isFrontPage()) { $path_args = ['']; } else { $path_args = explode('/', Url::fromRoute('')->getInternalPath()); } return theme_get_suggestions($path_args, 'page'); } /** * Implements hook_theme_suggestions_HOOK(). */ function system_theme_suggestions_maintenance_page(array $variables) { $suggestions = array(); // Dead databases will show error messages so supplying this template will // allow themers to override the page and the content completely. $offline = defined('MAINTENANCE_MODE'); try { \Drupal::service('path.matcher')->isFrontPage(); } catch (Exception $e) { // The database is not yet available. $offline = TRUE; } if ($offline) { $suggestions[] = 'maintenance_page__offline'; } return $suggestions; } /** * Implements hook_theme_suggestions_HOOK(). */ function system_theme_suggestions_region(array $variables) { $suggestions = array(); if (!empty($variables['elements']['#region'])) { $suggestions[] = 'region__' . $variables['elements']['#region']; } return $suggestions; } /** * Implements hook_theme_suggestions_HOOK(). */ function system_theme_suggestions_field(array $variables) { $suggestions = array(); $element = $variables['element']; $suggestions[] = 'field__' . $element['#field_type']; $suggestions[] = 'field__' . $element['#field_name']; $suggestions[] = 'field__' . $element['#entity_type'] . '__' . $element['#bundle']; $suggestions[] = 'field__' . $element['#entity_type'] . '__' . $element['#field_name']; $suggestions[] = 'field__' . $element['#entity_type'] . '__' . $element['#field_name'] . '__' . $element['#bundle']; return $suggestions; } /** * @defgroup authorize Authorized operations * @{ * Functions to run operations with elevated privileges via authorize.php. * * Because of the Update manager functionality included in Drupal core, there * is a mechanism for running operations with elevated file system privileges, * the top-level authorize.php script. This script runs at a reduced Drupal * bootstrap level so that it is not reliant on the entire site being * functional. The operations use a FileTransfer class to manipulate code * installed on the system as the user that owns the files, not the user that * the httpd is running as. * * The first setup is to define a callback function that should be authorized * to run with the elevated privileges. This callback should take a * FileTransfer as its first argument, although you can define an array of * other arguments it should be invoked with. The callback should be placed in * a separate .inc file that will be included by authorize.php. * * To run the operation, certain data must be saved into the SESSION, and then * the flow of control should be redirected to the authorize.php script. There * are two ways to do this, either to call system_authorized_run() directly, * or to call system_authorized_init() and then redirect to authorize.php, * using the URL from system_authorized_get_url(). Redirecting yourself is * necessary when your authorized operation is being triggered by a form * submit handler, since calling redirecting in a submit handler is a bad * idea, and you should instead use $form_state->setRedirect(). * * Once the SESSION is setup for the operation and the user is redirected to * authorize.php, they will be prompted for their connection credentials (core * provides FTP and SSH by default, although other connection classes can be * added via contributed modules). With valid credentials, authorize.php will * instantiate the appropriate FileTransfer object, and then invoke the * desired operation passing in that object. The authorize.php script can act * as a Batch API processing page, if the operation requires a batch. * * @see authorize.php * @see \Drupal\Core\FileTransfer\FileTransfer * @see hook_filetransfer_info() */ /** * Setup a given callback to run via authorize.php with elevated privileges. * * To use authorize.php, certain variables must be stashed into $_SESSION. This * function sets up all the necessary $_SESSION variables. The calling function * should then redirect to authorize.php, using the full path returned by * system_authorized_get_url(). That initiates the workflow that will eventually * lead to the callback being invoked. The callback will be invoked at a low * bootstrap level, without all modules being invoked, so it needs to be careful * not to assume any code exists. Example (system_authorized_run()): * @code * system_authorized_init($callback, $file, $arguments, $page_title); * return new RedirectResponse(system_authorized_get_url()->toString()); * @endcode * Example (update_manager_install_form_submit()): * @code * system_authorized_init('update_authorize_run_install', * drupal_get_path('module', 'update') . '/update.authorize.inc', * $arguments, t('Update manager')); * $form_state->setRedirectUrl(system_authorized_get_url()); * @endcode * * @param $callback * The name of the function to invoke once the user authorizes the operation. * @param $file * The full path to the file where the callback function is implemented. * @param $arguments * Optional array of arguments to pass into the callback when it is invoked. * Note that the first argument to the callback is always the FileTransfer * object created by authorize.php when the user authorizes the operation. * @param $page_title * Optional string to use as the page title once redirected to authorize.php. * @return * Nothing, this function just initializes variables in the user's session. */ function system_authorized_init($callback, $file, $arguments = array(), $page_title = NULL) { // First, figure out what file transfer backends the site supports, and put // all of those in the SESSION so that authorize.php has access to all of // them via the class autoloader, even without a full bootstrap. $_SESSION['authorize_filetransfer_info'] = drupal_get_filetransfer_info(); // Now, define the callback to invoke. $_SESSION['authorize_operation'] = array( 'callback' => $callback, 'file' => $file, 'arguments' => $arguments, ); if (isset($page_title)) { $_SESSION['authorize_page_title'] = $page_title; } } /** * Return the URL for the authorize.php script. * * @param array $options * Optional array of options to pass to url(). * @return \Drupal\Core\Url * The full URL to authorize.php, using HTTPS if available. * * @see system_authorized_init() */ function system_authorized_get_url(array $options = array()) { // core/authorize.php is an unrouted URL, so using the base: scheme is // the correct usage for this case. $url = Url::fromUri('base:core/authorize.php'); $url_options = $url->getOptions(); $url->setOptions($options + $url_options); return $url; } /** * Returns the URL for the authorize.php script when it is processing a batch. * * @param array $options * Optional array of options to pass to url(). * * @return \Drupal\Core\Url */ function system_authorized_batch_processing_url(array $options = array()) { $options['query'] = array('batch' => '1'); return system_authorized_get_url($options); } /** * Setup and invoke an operation using authorize.php. * * @see system_authorized_init() */ function system_authorized_run($callback, $file, $arguments = array(), $page_title = NULL) { system_authorized_init($callback, $file, $arguments, $page_title); return new RedirectResponse(system_authorized_get_url()->toString()); } /** * Use authorize.php to run batch_process(). * * @see batch_process() */ function system_authorized_batch_process() { $finish_url = system_authorized_get_url(); $process_url = system_authorized_batch_processing_url(); return batch_process($finish_url->toString(), $process_url); } /** * @} End of "defgroup authorize". */ /** * Implements hook_updater_info(). */ function system_updater_info() { return array( 'module' => array( 'class' => 'Drupal\Core\Updater\Module', 'name' => t('Update modules'), 'weight' => 0, ), 'theme' => array( 'class' => 'Drupal\Core\Updater\Theme', 'name' => t('Update themes'), 'weight' => 0, ), ); } /** * Implements hook_filetransfer_info(). */ function system_filetransfer_info() { $backends = array(); // This is the default, will be available on most systems. if (function_exists('ftp_connect')) { $backends['ftp'] = array( 'title' => t('FTP'), 'class' => 'Drupal\Core\FileTransfer\FTP', 'weight' => 0, ); } // SSH2 lib connection is only available if the proper PHP extension is // installed. if (function_exists('ssh2_connect')) { $backends['ssh'] = array( 'title' => t('SSH'), 'class' => 'Drupal\Core\FileTransfer\SSH', 'weight' => 20, ); } return $backends; } /** * Implements hook_page_attachments(). * * @see template_preprocess_maintenance_page() * @see \Drupal\system\Controller\SystemController::setLinkActiveClass() */ function system_page_attachments(array &$page) { // Ensure the same CSS is loaded in template_preprocess_maintenance_page(). $page['#attached']['library'][] = 'core/normalize'; $page['#attached']['library'][] = 'system/base'; if (\Drupal::service('router.admin_context')->isAdminRoute()) { $page['#attached']['library'][] = 'system/admin'; } // Attach libraries used by this theme. $active_theme = \Drupal::theme()->getActiveTheme(); foreach ($active_theme->getLibraries() as $library) { $page['#attached']['library'][] = $library; } // Attach favicon. if (theme_get_setting('features.favicon')) { $favicon = theme_get_setting('favicon.url'); $type = theme_get_setting('favicon.mimetype'); $page['#attached']['html_head_link'][][] = array( 'rel' => 'shortcut icon', 'href' => UrlHelper::stripDangerousProtocols($favicon), 'type' => $type, ); } // Get the major Drupal version. list($version, ) = explode('.', \Drupal::VERSION); // Attach default meta tags. $meta_default = array( // Make sure the Content-Type comes first because the IE browser may be // vulnerable to XSS via encoding attacks from any content that comes // before this META tag, such as a TITLE tag. 'system_meta_content_type' => array( '#tag' => 'meta', '#attributes' => array( 'charset' => 'utf-8', ), // Security: This always has to be output first. '#weight' => -1000, ), // Show Drupal and the major version number in the META GENERATOR tag. 'system_meta_generator' => array( '#type' => 'html_tag', '#tag' => 'meta', '#attributes' => array( 'name' => 'Generator', 'content' => 'Drupal ' . $version . ' (http://drupal.org)', ), ), // Attach default mobile meta tags for responsive design. 'MobileOptimized' => array( '#tag' => 'meta', '#attributes' => array( 'name' => 'MobileOptimized', 'content' => 'width', ), ), 'HandheldFriendly' => array( '#tag' => 'meta', '#attributes' => array( 'name' => 'HandheldFriendly', 'content' => 'true', ), ), 'viewport' => array( '#tag' => 'meta', '#attributes' => array( 'name' => 'viewport', 'content' => 'width=device-width, initial-scale=1.0', ), ), ); foreach ($meta_default as $key => $value) { $page['#attached']['html_head'][] = [$value, $key]; } // Handle setting the "active" class on links by: // - loading the active-link library if the current user is authenticated; // - applying a post-render cache callback if the current user is anonymous. // @see l() // @see \Drupal\Core\Utility\LinkGenerator::generate() // @see template_preprocess_links() // @see \Drupal\system\Controller\SystemController::setLinkActiveClass if (\Drupal::currentUser()->isAuthenticated()) { $page['#attached']['library'][] = 'core/drupal.active-link'; } else { $page['#post_render_cache']['\Drupal\system\Controller\SystemController::setLinkActiveClass'] = array( // Collect the current state that determines whether a link is active. array( 'path' => \Drupal::routeMatch()->getRouteName() ? Url::fromRouteMatch(\Drupal::routeMatch())->getInternalPath() : '', 'front' => \Drupal::service('path.matcher')->isFrontPage(), 'language' => \Drupal::languageManager()->getCurrentLanguage(LanguageInterface::TYPE_URL)->getId(), 'query' => \Drupal::request()->query->all(), ) ); } } /** * Implements hook_js_settings_alter(). * * Sets values for the core/drupalSettings and core/drupal.ajax libraries. */ function system_js_settings_alter(&$settings, AttachedAssetsInterface $assets) { // url() generates the script and prefix using hook_url_outbound_alter(). // Instead of running the hook_url_outbound_alter() again here, extract // them from url(). // @todo Make this less hacky: http://drupal.org/node/1547376. $request = \Drupal::request(); $scriptPath = $request->getScriptName(); $pathPrefix = ''; $current_query = $request->query->all(); Url::fromRoute('', [], array('script' => &$scriptPath, 'prefix' => &$pathPrefix))->toString(); $current_path = \Drupal::routeMatch()->getRouteName() ? Url::fromRouteMatch(\Drupal::routeMatch())->getInternalPath() : ''; $current_path_is_admin = \Drupal::service('router.admin_context')->isAdminRoute(); $path_settings = [ 'baseUrl' => $request->getBaseUrl() . '/', 'scriptPath' => $scriptPath, 'pathPrefix' => $pathPrefix, 'currentPath' => $current_path, 'currentPathIsAdmin' => $current_path_is_admin, 'isFront' => \Drupal::service('path.matcher')->isFrontPage(), 'currentLanguage' => \Drupal::languageManager()->getCurrentLanguage(LanguageInterface::TYPE_URL)->getId(), ]; if (!empty($current_query)) { ksort($current_query); $path_settings['currentQuery'] = (object) $current_query; } // Only set core/drupalSettings values that haven't been set already. foreach ($path_settings as $key => $value) { if (!isset($settings['path'][$key])) { $settings['path'][$key] = $value; } } if (!isset($settings['pluralDelimiter'])) { $settings['pluralDelimiter'] = LOCALE_PLURAL_DELIMITER; } // Now generate the values for the core/drupal.ajax library. // We need to send ajaxPageState settings for core/drupal.ajax if: // - ajaxPageState is being loaded in this Response, in which case it will // already exist at $settings['ajaxPageState'] (because the core/drupal.ajax // library definition specifies a placeholder 'ajaxPageState' setting). // - core/drupal.ajax already has been loaded and hence this is an AJAX // Response in which we must send the list of extra asset libraries that are // being added in this AJAX Response. /** @var \Drupal\Core\Asset\LibraryDependencyResolver $library_dependency_resolver */ $library_dependency_resolver = \Drupal::service('library.dependency_resolver'); if (isset($settings['ajaxPageState']) || in_array('core/drupal.ajax', $library_dependency_resolver->getLibrariesWithDependencies($assets->getAlreadyLoadedLibraries()))) { // Provide the page with information about the theme that's used, so that // a later AJAX request can be rendered using the same theme. // @see \Drupal\Core\Theme\AjaxBasePageNegotiator $theme_key = \Drupal::theme()->getActiveTheme()->getName(); $settings['ajaxPageState']['theme'] = $theme_key; // Checks that the DB is available before filling theme_token. if (!defined('MAINTENANCE_MODE')) { $settings['ajaxPageState']['theme_token'] = \Drupal::csrfToken()->get($theme_key); } // Provide the page with information about the individual asset libraries // used, information not otherwise available when aggregation is enabled. $minimal_libraries = $library_dependency_resolver->getMinimalRepresentativeSubset(array_merge( $assets->getLibraries(), $assets->getAlreadyLoadedLibraries() )); sort($minimal_libraries); $settings['ajaxPageState']['libraries'] = implode(',', $minimal_libraries); } } /** * Implements hook_form_FORM_ID_alter(). */ function system_form_user_form_alter(&$form, FormStateInterface $form_state) { if (\Drupal::config('system.date')->get('timezone.user.configurable')) { system_user_timezone($form, $form_state); } } /** * Implements hook_form_FORM_ID_alter(). */ function system_form_user_register_form_alter(&$form, FormStateInterface $form_state) { $config = \Drupal::config('system.date'); if ($config->get('timezone.user.configurable') && $config->get('timezone.user.default') == DRUPAL_USER_TIMEZONE_SELECT) { system_user_timezone($form, $form_state); } } /** * Implements hook_ENTITY_TYPE_presave() for user entities. */ function system_user_presave(UserInterface $account) { $config = \Drupal::config('system.date'); if ($config->get('timezone.user.configurable') && !$account->getTimeZone() && !$config->get('timezone.user.default')) { $account->timezone = $config->get('timezone.default'); } } /** * Implements hook_user_login(). */ function system_user_login(UserInterface $account) { $config = \Drupal::config('system.date'); // If the user has a NULL time zone, notify them to set a time zone. if (!$account->getTimezone() && $config->get('timezone.user.configurable') && $config->get('timezone.user.warn')) { drupal_set_message(t('Configure your account time zone setting.', array('@user-edit' => $account->url('edit-form', array('query' => drupal_get_destination(), 'fragment' => 'edit-timezone'))))); } } /** * Add the time zone field to the user edit and register forms. */ function system_user_timezone(&$form, FormStateInterface $form_state) { $user = \Drupal::currentUser(); $account = $form_state->getFormObject()->getEntity(); $form['timezone'] = array( '#type' => 'details', '#title' => t('Locale settings'), '#open' => TRUE, '#weight' => 6, ); $form['timezone']['timezone'] = array( '#type' => 'select', '#title' => t('Time zone'), '#default_value' => $account->getTimezone() ? $account->getTimezone() : \Drupal::config('system.date')->get('timezone.default'), '#options' => system_time_zones($account->id() != $user->id()), '#description' => t('Select the desired local time and time zone. Dates and times throughout this site will be displayed using this time zone.'), ); $user_input = $form_state->getUserInput(); if (!$account->getTimezone() && $account->id() == $user->id() && empty($user_input['timezone'])) { $form['timezone']['#attached']['library'][] = 'core/drupal.timezone'; $form['timezone']['timezone']['#attributes'] = array('class' => array('timezone-detect')); } } /** * Implements hook_preprocess_HOOK() for block templates. */ function system_preprocess_block(&$variables) { switch ($variables['base_plugin_id']) { case 'system_branding_block': $variables['site_logo'] = ''; if ($variables['content']['site_logo']['#access'] && $variables['content']['site_logo']['#uri']) { $variables['site_logo'] = $variables['content']['site_logo']['#uri']; } $variables['site_name'] = ''; if ($variables['content']['site_name']['#access'] && $variables['content']['site_name']['#markup']) { $variables['site_name'] = $variables['content']['site_name']['#markup']; } $variables['site_slogan'] = ''; if ($variables['content']['site_slogan']['#access'] && $variables['content']['site_slogan']['#markup']) { $variables['site_slogan'] = $variables['content']['site_slogan']['#markup']; } break; case 'system_powered_by_block': $variables['attributes']['role'] = 'complementary'; break; } } /** * Checks the existence of the directory specified in $form_element. * * This function is called from the system_settings form to check all core * file directories (file_public_path, file_private_path, file_temporary_path). * * @param $form_element * The form element containing the name of the directory to check. * @param \Drupal\Core\Form\FormStateInterface $form_state * The current state of the form. */ function system_check_directory($form_element, FormStateInterface $form_state) { $directory = $form_element['#value']; if (strlen($directory) == 0) { return $form_element; } $logger = \Drupal::logger('file system'); if (!is_dir($directory) && !drupal_mkdir($directory, NULL, TRUE)) { // If the directory does not exists and cannot be created. $form_state->setErrorByName($form_element['#parents'][0], t('The directory %directory does not exist and could not be created.', array('%directory' => $directory))); $logger->error('The directory %directory does not exist and could not be created.', array('%directory' => $directory)); } if (is_dir($directory) && !is_writable($directory) && !drupal_chmod($directory)) { // If the directory is not writable and cannot be made so. $form_state->setErrorByName($form_element['#parents'][0], t('The directory %directory exists but is not writable and could not be made writable.', array('%directory' => $directory))); $logger->error('The directory %directory exists but is not writable and could not be made writable.', array('%directory' => $directory)); } elseif (is_dir($directory)) { if ($form_element['#name'] == 'file_public_path') { // Create public .htaccess file. file_save_htaccess($directory, FALSE); } else { // Create private .htaccess file. file_save_htaccess($directory); } } return $form_element; } /** * Returns an array of information about enabled modules or themes. * * This function returns the contents of the .info.yml file for each installed * module or theme. * * @param $type * Either 'module' or 'theme'. * @param $name * (optional) The name of a module or theme whose information shall be * returned. If omitted, all records for the provided $type will be returned. * If $name does not exist in the provided $type or is not enabled, an empty * array will be returned. * * @return * An associative array of module or theme information keyed by name, or only * information for $name, if given. If no records are available, an empty * array is returned. * * @see system_rebuild_module_data() * @see \Drupal\Core\Extension\ThemeHandlerInterface::rebuildThemeData() */ function system_get_info($type, $name = NULL) { $info = array(); if ($type == 'module') { $data = system_rebuild_module_data(); foreach (\Drupal::moduleHandler()->getModuleList() as $module => $filename) { if (isset($data[$module])) { $info[$module] = $data[$module]->info; } } } else { $list = system_list($type); foreach ($list as $shortname => $item) { if (!empty($item->status)) { $info[$shortname] = $item->info; } } } if (isset($name)) { return isset($info[$name]) ? $info[$name] : array(); } return $info; } /** * Helper function to scan and collect module .info.yml data. * * @return \Drupal\Core\Extension\Extension[] * An associative array of module information. */ function _system_rebuild_module_data() { $listing = new ExtensionDiscovery(\Drupal::root()); // Find modules $modules = $listing->scan('module'); // Find installation profiles. $profiles = $listing->scan('profile'); // Include the installation profile in modules that are loaded. if ($profile = drupal_get_profile()) { $modules[$profile] = $profiles[$profile]; // Installation profile hooks are always executed last. $modules[$profile]->weight = 1000; } // Set defaults for module info. $defaults = array( 'dependencies' => array(), 'description' => '', 'package' => 'Other', 'version' => NULL, 'php' => DRUPAL_MINIMUM_PHP, ); // Read info files for each module. foreach ($modules as $key => $module) { // Look for the info file. $module->info = \Drupal::service('info_parser')->parse($module->getPathname()); // Add the info file modification time, so it becomes available for // contributed modules to use for ordering module lists. $module->info['mtime'] = $module->getMTime(); // Merge in defaults and save. $modules[$key]->info = $module->info + $defaults; // Installation profiles are hidden by default, unless explicitly specified // otherwise in the .info.yml file. if ($key == $profile && !isset($modules[$key]->info['hidden'])) { $modules[$key]->info['hidden'] = TRUE; } // Invoke hook_system_info_alter() to give installed modules a chance to // modify the data in the .info.yml files if necessary. // @todo Remove $type argument, obsolete with $module->getType(). $type = 'module'; \Drupal::moduleHandler()->alter('system_info', $modules[$key]->info, $modules[$key], $type); } // It is possible that a module was marked as required by // hook_system_info_alter() and modules that it depends on are not required. foreach ($modules as $module) { _system_rebuild_module_data_ensure_required($module, $modules); } if ($profile && isset($modules[$profile])) { // The installation profile is required, if it's a valid module. $modules[$profile]->info['required'] = TRUE; // Add a default distribution name if the profile did not provide one. // @see install_profile_info() // @see drupal_install_profile_distribution_name() if (!isset($modules[$profile]->info['distribution']['name'])) { $modules[$profile]->info['distribution']['name'] = 'Drupal'; } } return $modules; } /** * Ensures that dependencies of required modules are also required. * * @param \Drupal\Core\Extension\Extension $module * The module info. * @param \Drupal\Core\Extension\Extension[] $modules * The array of all module info. */ function _system_rebuild_module_data_ensure_required($module, &$modules) { if (!empty($module->info['required'])) { foreach ($module->info['dependencies'] as $dependency) { $dependency_name = ModuleHandler::parseDependency($dependency)['name']; if (!isset($modules[$dependency_name]->info['required'])) { $modules[$dependency_name]->info['required'] = TRUE; $modules[$dependency_name]->info['explanation'] = t('Dependency of required module @module', array('@module' => $module->info['name'])); // Ensure any dependencies it has are required. _system_rebuild_module_data_ensure_required($modules[$dependency_name], $modules); } } } } /** * Rebuild, save, and return data about all currently available modules. * * @return \Drupal\Core\Extension\Extension[] * Array of all available modules and their data. */ function system_rebuild_module_data() { $modules_cache = &drupal_static(__FUNCTION__); // Only rebuild once per request. $modules and $modules_cache cannot be // combined into one variable, because the $modules_cache variable is reset by // reference from system_list_reset() during the rebuild. if (!isset($modules_cache)) { $modules = _system_rebuild_module_data(); $files = array(); ksort($modules); // Add status, weight, and schema version. $installed_modules = \Drupal::config('core.extension')->get('module') ?: array(); foreach ($modules as $name => $module) { $module->weight = isset($installed_modules[$name]) ? $installed_modules[$name] : 0; $module->status = (int) isset($installed_modules[$name]); $module->schema_version = SCHEMA_UNINSTALLED; $files[$name] = $module->getPathname(); } $modules = \Drupal::moduleHandler()->buildModuleDependencies($modules); $modules_cache = $modules; // Store filenames to allow system_list() and drupal_get_filename() to // retrieve them without having to rebuild or scan the filesystem. \Drupal::state()->set('system.module.files', $files); } return $modules_cache; } /** * Returns an array of default theme features. */ function _system_default_theme_features() { return array( 'logo', 'favicon', 'name', 'slogan', 'node_user_picture', 'comment_user_picture', 'comment_user_verification', ); } /** * Get a list of available regions from a specified theme. * * @param \Drupal\Core\Extension\Extension|string $theme * A theme extension object, or the name of a theme. * @param $show * Possible values: REGIONS_ALL or REGIONS_VISIBLE. Visible excludes hidden * regions. * @return * An array of regions in the form $region['name'] = 'description'. */ function system_region_list($theme, $show = REGIONS_ALL) { if (!$theme instanceof Extension) { $themes = \Drupal::service('theme_handler')->listInfo(); if (!isset($themes[$theme])) { return array(); } $theme = $themes[$theme]; } $list = array(); $info = $theme->info; // If requested, suppress hidden regions. See block_admin_display_form(). foreach ($info['regions'] as $name => $label) { if ($show == REGIONS_ALL || !isset($info['regions_hidden']) || !in_array($name, $info['regions_hidden'])) { $list[$name] = t($label); } } return $list; } /** * Array sorting callback; sorts modules by their name. */ function system_sort_modules_by_info_name($a, $b) { return strcasecmp($a->info['name'], $b->info['name']); } /** * Sorts themes by their names, with the default theme listed first. * * Callback for uasort() within * \Drupal\system\Controller\SystemController::themesPage(). * * @see system_sort_modules_by_info_name(). */ function system_sort_themes($a, $b) { if ($a->is_default) { return -1; } if ($b->is_default) { return 1; } return strcasecmp($a->info['name'], $b->info['name']); } /** * Implements hook_system_info_alter(). */ function system_system_info_alter(&$info, Extension $file, $type) { // Remove page-top and page-bottom from the blocks UI since they are reserved for // modules to populate from outside the blocks system. if ($type == 'theme') { $info['regions_hidden'][] = 'page_top'; $info['regions_hidden'][] = 'page_bottom'; } } /** * Gets the name of the default region for a given theme. * * @param $theme * The name of a theme. * @return * A string that is the region name. */ function system_default_region($theme) { $regions = array_keys(system_region_list($theme, REGIONS_VISIBLE)); return isset($regions[0]) ? $regions[0] : ''; } /** * Determines whether the current user is in compact mode. * * Compact mode shows certain administration pages with less description text, * such as the configuration page and the permissions page. * * Whether the user is in compact mode is determined by a cookie, which is set * for the user by \Drupal\system\Controller\SystemController::compactPage(). * * If the user does not have the cookie, the default value is given by the * system variable 'admin_compact_mode', which itself defaults to FALSE. This * does not have a user interface to set it: it is a hidden variable which can * be set in the settings.php file. * * @return bool * TRUE when in compact mode, FALSE when in expanded mode. */ function system_admin_compact_mode() { // PHP converts dots into underscores in cookie names to avoid problems with // its parser, so we use a converted cookie name. return \Drupal::request()->cookies->get('Drupal_visitor_admin_compact_mode', \Drupal::config('system.site')->get('admin_compact_mode')); } /** * Generate a list of tasks offered by a specified module. * * @param string $module * Module name. * @param array $info * The module's information, as provided by system_get_info(). * * @return array * An array of task links. */ function system_get_module_admin_tasks($module, array $info) { $tree = &drupal_static(__FUNCTION__); $menu_tree = \Drupal::menuTree(); if (!isset($tree)) { $parameters = new MenuTreeParameters(); $parameters->setRoot('system.admin')->excludeRoot()->onlyEnabledLinks(); $tree = $menu_tree->load('system.admin', $parameters); $manipulators = array( array('callable' => 'menu.default_tree_manipulators:checkAccess'), array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'), array('callable' => 'menu.default_tree_manipulators:flatten'), ); $tree = $menu_tree->transform($tree, $manipulators); } $admin_tasks = array(); foreach ($tree as $element) { $link = $element->link; if ($link->getProvider() != $module) { continue; } $admin_tasks[] = array( 'title' => $link->getTitle(), 'description' => $link->getDescription(), 'url' => $link->getUrlObject(), ); } // Append link for permissions. /** @var \Drupal\user\PermissionHandlerInterface $permission_handler */ $permission_handler = \Drupal::service('user.permissions'); if ($permission_handler->moduleProvidesPermissions($module)) { /** @var \Drupal\Core\Access\AccessManagerInterface $access_manager */ $access_manager = \Drupal::service('access_manager'); if ($access_manager->checkNamedRoute('user.admin_permissions', array(), \Drupal::currentUser())) { /** @var \Drupal\Core\Url $url */ $url = new \Drupal\Core\Url('user.admin_permissions'); $url->setOption('fragment', 'module-' . $module); $admin_tasks["user.admin_permissions.$module"] = array( 'title' => t('Configure @module permissions', array('@module' => $info['name'])), 'description' => '', 'url' => $url, ); } } return $admin_tasks; } /** * Implements hook_cron(). * * Remove older rows from flood, batch cache and expirable keyvalue tables. */ function system_cron() { // Clean up the flood. \Drupal::flood()->garbageCollection(); foreach (Cache::getBins() as $cache_backend) { $cache_backend->garbageCollection(); } // Clean up the expirable key value database store. if (\Drupal::service('keyvalue.expirable.database') instanceof KeyValueDatabaseExpirableFactory) { \Drupal::service('keyvalue.expirable.database')->garbageCollection(); } // Clean up the queue for failed batches. db_delete('queue') ->condition('created', REQUEST_TIME - 864000, '<') ->condition('name', 'drupal_batch:%', 'LIKE') ->execute(); // Reset expired items in the default queue implementation table. If that's // not used, this will simply be a no-op. db_update('queue') ->fields(array( 'expire' => 0, )) ->condition('expire', 0, '<>') ->condition('expire', REQUEST_TIME, '<') ->execute(); } /** * Implements hook_mail(). */ function system_mail($key, &$message, $params) { $token_service = \Drupal::token(); $context = $params['context']; $subject = $token_service->replace($context['subject'], $context); $body = $token_service->replace($context['message'], $context); $message['subject'] .= str_replace(array("\r", "\n"), '', $subject); $message['body'][] = $body; } /** * Generate an array of time zones and their local time&date. * * @param $blank * If evaluates true, prepend an empty time zone option to the array. */ function system_time_zones($blank = NULL) { $zonelist = timezone_identifiers_list(); $zones = $blank ? array('' => t('- None selected -')) : array(); foreach ($zonelist as $zone) { // Because many time zones exist in PHP only for backward compatibility // reasons and should not be used, the list is filtered by a regular // expression. if (preg_match('!^((Africa|America|Antarctica|Arctic|Asia|Atlantic|Australia|Europe|Indian|Pacific)/|UTC$)!', $zone)) { $zones[$zone] = t('@zone', array('@zone' => t(str_replace('_', ' ', $zone)))); } } // Sort the translated time zones alphabetically. asort($zones); return $zones; } /** * Attempts to get a file using Guzzle HTTP client and to store it locally. * * @param string $url * The URL of the file to grab. * @param string $destination * Stream wrapper URI specifying where the file should be placed. If a * directory path is provided, the file is saved into that directory under * its original name. If the path contains a filename as well, that one will * be used instead. * If this value is omitted, the site's default files scheme will be used, * usually "public://". * @param bool $managed * If this is set to TRUE, the file API hooks will be invoked and the file is * registered in the database. * @param int $replace * Replace behavior when the destination file already exists: * - FILE_EXISTS_REPLACE: Replace the existing file. * - FILE_EXISTS_RENAME: Append _{incrementing number} until the filename is * unique. * - FILE_EXISTS_ERROR: Do nothing and return FALSE. * * @return mixed * One of these possibilities: * - If it succeeds and $managed is FALSE, the location where the file was * saved. * - If it succeeds and $managed is TRUE, a \Drupal\file\FileInterface * object which describes the file. * - If it fails, FALSE. */ function system_retrieve_file($url, $destination = NULL, $managed = FALSE, $replace = FILE_EXISTS_RENAME) { $parsed_url = parse_url($url); if (!isset($destination)) { $path = file_build_uri(drupal_basename($parsed_url['path'])); } else { if (is_dir(drupal_realpath($destination))) { // Prevent URIs with triple slashes when glueing parts together. $path = str_replace('///', '//', "$destination/") . drupal_basename($parsed_url['path']); } else { $path = $destination; } } try { $data = \Drupal::httpClient() ->get($url) ->getBody(TRUE); $local = $managed ? file_save_data($data, $path, $replace) : file_unmanaged_save_data($data, $path, $replace); } catch (RequestException $exception) { drupal_set_message(t('Failed to fetch file due to error "%error"', array('%error' => $exception->getMessage())), 'error'); return FALSE; } if (!$local) { drupal_set_message(t('@remote could not be saved to @path.', array('@remote' => $url, '@path' => $path)), 'error'); } return $local; } /** * Implements hook_entity_type_build(). */ function system_entity_type_build(array &$entity_types) { /** @var $entity_types \Drupal\Core\Entity\EntityTypeInterface[] */ $entity_types['date_format'] ->setFormClass('add', 'Drupal\system\Form\DateFormatAddForm') ->setFormClass('edit', 'Drupal\system\Form\DateFormatEditForm') ->setFormClass('delete', 'Drupal\system\Form\DateFormatDeleteForm') ->setListBuilderClass('Drupal\system\DateFormatListBuilder') ->setLinkTemplate('edit-form', '/admin/config/regional/date-time/formats/manage/{date_format}') ->setLinkTemplate('delete-form', '/admin/config/regional/date-time/formats/manage/{date_format}/delete') ->setLinkTemplate('collection', '/admin/config/regional/date-time/formats'); } /** * Implements hook_block_view_BASE_BLOCK_ID_alter(). */ function system_block_view_system_main_block_alter(array &$build, BlockPluginInterface $block) { // Contextual links on the system_main block would basically duplicate the // tabs/local tasks, so reduce the clutter. unset($build['#contextual_links']); } /** * Implements hook_path_update(). */ function system_path_update() { \Drupal::service('path.alias_manager')->cacheClear(); } /** * Implements hook_path_insert(). */ function system_path_insert() { \Drupal::service('path.alias_manager')->cacheClear(); } /** * Implements hook_path_delete(). */ function system_path_delete($path) { \Drupal::service('path.alias_manager')->cacheClear(); }