/** * Determines if redirect may be performed. * * @param Request $request * The current request object. * @param string $route_name * The current route name. * * @return bool * TRUE if redirect may be performed. */ public function canRedirect(Request $request, $route_name = NULL) { $can_redirect = TRUE; if (isset($route_name)) { $route = $this->routeProvider->getRouteByName($route_name); if ($this->config->get('access_check')) { // Do not redirect if is a protected page. $can_redirect &= $this->accessManager->check($route, $request, $this->account); } } else { $route = $request->attributes->get(RouteObjectInterface::ROUTE_OBJECT); } if (strpos($request->getScriptName(), 'index.php') === FALSE) { // Do not redirect if the root script is not /index.php. $can_redirect = FALSE; } elseif (!($request->isMethod('GET') || $request->isMethod('HEAD'))) { // Do not redirect if this is other than GET request. $can_redirect = FALSE; } elseif ($this->state->get('system.maintenance_mode') || defined('MAINTENANCE_MODE')) { // Do not redirect in offline or maintenance mode. $can_redirect = FALSE; } elseif ($this->config->get('ignore_admin_path') && isset($route)) { // Do not redirect on admin paths. $can_redirect &= !(bool) $route->getOption('_admin_route'); } return $can_redirect; }
/** * {@inheritdoc} */ public function build(RouteMatchInterface $route_match) { $breadcrumb[] = Link::createFromRoute($this->t('Home'), '<front>'); $vocabulary = $this->entityManager->getStorage('taxonomy_vocabulary')->load($this->config->get('vocabulary')); $breadcrumb[] = Link::createFromRoute($vocabulary->label(), 'forum.index'); return $breadcrumb; }
/** * {@inheritdoc} */ public function get($key, $defaultValue = NULL) { $value = $this->config->get('settings.' . $key); if ($value == NULL) { return $defaultValue; } return $value; }
/** * {@inheritdoc} */ public function build() { if ($this->sharethisSettings->get('location') === 'block') { $st_js = $this->sharethisManager->sharethisIncludeJs(); $markup = $this->sharethisManager->blockContents(); return ['#theme' => 'sharethis_block', '#content' => $markup, '#attached' => array('library' => array('sharethis/sharethispickerexternalbuttonsws', 'sharethis/sharethispickerexternalbuttons', 'sharethis/sharethis'), 'drupalSettings' => array('sharethis' => $st_js))]; } }
/** * {@inheritdoc} */ public function refresh(FeedInterface $feed) { // Store feed URL to track changes. $feed_url = $feed->getUrl(); // Fetch the feed. try { $success = $this->fetcherManager->createInstance($this->config->get('fetcher'))->fetch($feed); } catch (PluginException $e) { $success = FALSE; watchdog_exception('aggregator', $e); } // Store instances in an array so we dont have to instantiate new objects. $processor_instances = array(); foreach ($this->config->get('processors') as $processor) { try { $processor_instances[$processor] = $this->processorManager->createInstance($processor); } catch (PluginException $e) { watchdog_exception('aggregator', $e); } } // We store the hash of feed data in the database. When refreshing a // feed we compare stored hash and new hash calculated from downloaded // data. If both are equal we say that feed is not updated. $hash = hash('sha256', $feed->source_string); $has_new_content = $success && $feed->getHash() != $hash; if ($has_new_content) { // Parse the feed. try { if ($this->parserManager->createInstance($this->config->get('parser'))->parse($feed)) { if (!$feed->getWebsiteUrl()) { $feed->setWebsiteUrl($feed->getUrl()); } $feed->setHash($hash); // Update feed with parsed data. $feed->save(); // Log if feed URL has changed. if ($feed->getUrl() != $feed_url) { $this->logger->notice('Updated URL for feed %title to %url.', array('%title' => $feed->label(), '%url' => $feed->getUrl())); } $this->logger->notice('There is new syndicated content from %site.', array('%site' => $feed->label())); // If there are items on the feed, let enabled processors process them. if (!empty($feed->items)) { foreach ($processor_instances as $instance) { $instance->process($feed); } } } } catch (PluginException $e) { watchdog_exception('aggregator', $e); } } // Processing is done, call postProcess on enabled processors. foreach ($processor_instances as $instance) { $instance->postProcess($feed); } return $has_new_content; }
/** * Constructs a ImageEffectsPluginBase object. * * @param array $configuration * A configuration array containing information about the plugin instance. * @param string $plugin_id * The plugin_id for the plugin instance. * @param mixed $plugin_definition * The plugin implementation definition. * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory * The configuration factory. * @param \Drupal\Core\Routing\UrlGeneratorInterface $url_generator * The URL generator. * @param \Psr\Log\LoggerInterface $logger * The image_effects logger. */ public function __construct(array $configuration, $plugin_id, $plugin_definition, ConfigFactoryInterface $config_factory, UrlGeneratorInterface $url_generator, LoggerInterface $logger) { $this->config = $config_factory->getEditable('image_effects.settings'); parent::__construct($configuration, $plugin_id, $plugin_definition); $this->pluginType = $configuration['plugin_type']; $config = $this->config->get($this->pluginType . '.plugin_settings.' . $plugin_id); $this->setConfiguration(array_merge($this->defaultConfiguration(), is_array($config) ? $config : array())); $this->urlGenerator = $url_generator; $this->logger = $logger; }
/** * Run the automated cron if enabled. * * @param \Symfony\Component\HttpKernel\Event\PostResponseEvent $event * The Event to process. */ public function onTerminate(PostResponseEvent $event) { $interval = $this->config->get('interval'); if ($interval > 0) { $cron_next = $this->state->get('system.cron_last', 0) + $interval; if ((int) $event->getRequest()->server->get('REQUEST_TIME') > $cron_next) { $this->cron->run(); } } }
/** * {@inheritdoc} */ public function build(RouteMatchInterface $route_match) { $breadcrumb = new Breadcrumb(); $breadcrumb->addCacheContexts(['route']); $links[] = Link::createFromRoute($this->t('Home'), '<front>'); $vocabulary = $this->entityManager->getStorage('taxonomy_vocabulary')->load($this->config->get('vocabulary')); $breadcrumb->addCacheableDependency($vocabulary); $links[] = Link::createFromRoute($vocabulary->label(), 'forum.index'); return $breadcrumb->setLinks($links); }
/** * {@inheritdoc} */ public function log($level, $message, array $context = array()) { global $base_url; // Ensure we have a connection available. $this->openConnection(); // Populate the message placeholders and then replace them in the message. $message_placeholders = $this->parser->parseMessagePlaceholders($message, $context); $message = empty($message_placeholders) ? $message : strtr($message, $message_placeholders); $entry = strtr($this->config->get('format'), array('!base_url' => $base_url, '!timestamp' => $context['timestamp'], '!type' => $context['channel'], '!ip' => $context['ip'], '!request_uri' => $context['request_uri'], '!referer' => $context['referer'], '!uid' => $context['uid'], '!link' => strip_tags($context['link']), '!message' => strip_tags($message))); syslog($level, $entry); }
public function getPlugin($plugin_id = NULL) { $plugin_id = $plugin_id ?: $this->config->get($this->getType() . '.plugin_id'); $plugins = $this->getAvailablePlugins(); // Check if plugin is available. if (!isset($plugins[$plugin_id]) || !class_exists($plugins[$plugin_id]['class'])) { trigger_error("image_effects " . $this->getType() . " handling plugin '{$plugin_id}' is no longer available.", E_USER_ERROR); $plugin_id = NULL; } return $this->createInstance($plugin_id, array('plugin_type' => $this->getType())); }
/** * Checks access to the route. * * @param string $route_name * The current route name. * @param \Symfony\Component\HttpFoundation\Request $request * The current request. * * @return bool * TRUE if access is granted. */ public function canRedirect($route_name, Request $request) { $do_redirect = TRUE; /** @var \Symfony\Component\Routing\Route $route */ $route = $this->routeProvider->getRouteByName($route_name); if ($this->config->get('access_check')) { $do_redirect &= $this->accessManager->check($route, $request, $this->account); } if ($this->config->get('ignore_admin_path')) { $do_redirect &= !(bool) $route->getOption('_admin_route'); } return $do_redirect; }
/** * Run the automated cron if enabled. * * @param Symfony\Component\HttpKernel\Event\PostResponseEvent $event * The Event to process. */ public function onTerminate(PostResponseEvent $event) { // If the site is not fully installed, suppress the automated cron run. // Otherwise it could be triggered prematurely by Ajax requests during // installation. if ($this->state->get('install_task') == 'done') { $threshold = $this->config->get('threshold.autorun'); if ($threshold > 0) { $cron_next = $this->state->get('system.cron_last', 0) + $threshold; if (REQUEST_TIME > $cron_next) { $this->cron->run(); } } } }
/** * {@inheritdoc} */ function render(ResultRow $values) { // Ensure Disqus comments are available on the entity and user has access to edit this entity. $entity = $this->getEntity($values); if (!$entity) { return; } $field = $this->disqusManager->getFields($entity->getEntityTypeId()); if (!$entity->hasField(key($field))) { return; } if ($entity->get(key($field))->status && $this->currentUser->hasPermission('view disqus comments')) { // Build a renderable array for the link. $links['disqus_comments_num'] = array('title' => t('Comments'), 'url' => $entity->urlInfo(), 'fragment' => 'disqus_thread', 'attributes' => array('data-disqus-identifier' => "{$entity->getEntityTypeId()}/{$entity->id()}")); $content = array('#theme' => 'links', '#links' => $links, '#attributes' => array('class' => array('links', 'inline'))); /** * This attaches disqus.js specified in the disqus.libraries.yml file, * which will look for the DOM variable disqusComments which is set below. * When found, the disqus javascript api replaces the html element with * the attribute: "data-disqus-identifier" and replaces the element with * the number of comments on the entity. */ $content['#attached']['library'][] = 'disqus/disqus'; $content['#attached']['drupalSettings']['disqusComments'] = $this->config->get('disqus_domain'); return $content; } }
/** * {@inheritdoc} */ public function forbiddenMessage(EntityInterface $entity, $field_name) { if (!isset($this->authenticatedCanPostComments)) { // We only output a link if we are certain that users will get the // permission to post comments by logging in. $this->authenticatedCanPostComments = $this->entityManager->getStorage('user_role')->load(RoleInterface::AUTHENTICATED_ID)->hasPermission('post comments'); } if ($this->authenticatedCanPostComments) { // We cannot use the redirect.destination service here because these links // sometimes appear on /node and taxonomy listing pages. if ($entity->get($field_name)->getFieldDefinition()->getSetting('form_location') == CommentItemInterface::FORM_SEPARATE_PAGE) { $comment_reply_parameters = ['entity_type' => $entity->getEntityTypeId(), 'entity' => $entity->id(), 'field_name' => $field_name]; $destination = array('destination' => $this->url('comment.reply', $comment_reply_parameters, array('fragment' => 'comment-form'))); } else { $destination = array('destination' => $entity->url('canonical', array('fragment' => 'comment-form'))); } if ($this->userConfig->get('register') != USER_REGISTER_ADMINISTRATORS_ONLY) { // Users can register themselves. return $this->t('<a href=":login">Log in</a> or <a href=":register">register</a> to post comments', array(':login' => $this->urlGenerator->generateFromRoute('user.login', array(), array('query' => $destination)), ':register' => $this->urlGenerator->generateFromRoute('user.register', array(), array('query' => $destination)))); } else { // Only admins can add new users, no public registration. return $this->t('<a href=":login">Log in</a> to post comments', array(':login' => $this->urlGenerator->generateFromRoute('user.login', array(), array('query' => $destination)))); } } return ''; }
/** * {@inheritdoc} */ public function initializeIterator() { if ($disqus = disqus_api()) { try { $posts = $disqus->forums->listPosts(array('forum' => $this->config->get('disqus_domain'))); } catch (\Exception $exception) { drupal_set_message(t('There was an error loading the forum details. Please check you API keys and try again.', 'error')); $this->logger->error('Error loading the Disqus PHP API. Check your forum name.', array()); return FALSE; } $items = array(); foreach ($posts as $post) { $id = $post['id']; $items[$id]['id'] = $id; $items[$id]['pid'] = $post['parent']; $thread = $disqus->threads->details(array('thread' => $post['thread'])); $items[$id]['identifier'] = $thread['identifier']; $items[$id]['name'] = $post['author']['name']; $items[$id]['email'] = $post['author']['email']; $items[$id]['user_id'] = $post['author']['id']; $items[$id]['url'] = $post['author']['url']; $items[$id]['ipAddress'] = $post['ipAddress']; $items[$id]['isAnonymous'] = $post['author']['isAnonymous']; $items[$id]['createdAt'] = $post['createdAt']; $items[$id]['comment'] = $post['message']; $items[$id]['isEdited'] = $post['isEdited']; } } return new \ArrayIterator($items); }
/** * Add Cache-Control and Expires headers to a cacheable response. * * @param \Symfony\Component\HttpFoundation\Response $response * A response object. * @param \Symfony\Component\HttpFoundation\Request $request * A request object. */ protected function setResponseCacheable(Response $response, Request $request) { // HTTP/1.0 proxies do not support the Vary header, so prevent any caching // by sending an Expires date in the past. HTTP/1.1 clients ignore the // Expires header if a Cache-Control: max-age directive is specified (see // RFC 2616, section 14.9.3). if (!$response->headers->has('Expires')) { $this->setExpiresNoCache($response); } $max_age = $this->config->get('cache.page.max_age'); $response->headers->set('Cache-Control', 'public, max-age=' . $max_age); // In order to support HTTP cache-revalidation, ensure that there is a // Last-Modified and an ETag header on the response. if (!$response->headers->has('Last-Modified')) { $timestamp = REQUEST_TIME; $response->setLastModified(new \DateTime(gmdate(DateTimePlus::RFC7231, REQUEST_TIME))); } else { $timestamp = $response->getLastModified()->getTimestamp(); } $response->setEtag($timestamp); // Allow HTTP proxies to cache pages for anonymous users without a session // cookie. The Vary header is used to indicates the set of request-header // fields that fully determines whether a cache is permitted to use the // response to reply to a subsequent request for a given URL without // revalidation. if (!$response->hasVary() && !Settings::get('omit_vary_cookie')) { $response->setVary('Cookie', FALSE); } }
/** * Overrides PluginManagerBase::getInstance(). * * Returns an instance of the mail plugin to use for a given message ID. * * The selection of a particular implementation is controlled via the config * 'system.mail.interface', which is a keyed array. The default * implementation is the mail plugin whose ID is the value of 'default' key. A * more specific match first to key and then to module will be used in * preference to the default. To specify a different plugin for all mail sent * by one module, set the plugin ID as the value for the key corresponding to * the module name. To specify a plugin for a particular message sent by one * module, set the plugin ID as the value for the array key that is the * message ID, which is "${module}_${key}". * * For example to debug all mail sent by the user module by logging it to a * file, you might set the variable as something like: * * @code * array( * 'default' => 'php_mail', * 'user' => 'devel_mail_log', * ); * @endcode * * Finally, a different system can be specified for a specific message ID (see * the $key param), such as one of the keys used by the contact module: * * @code * array( * 'default' => 'php_mail', * 'user' => 'devel_mail_log', * 'contact_page_autoreply' => 'null_mail', * ); * @endcode * * Other possible uses for system include a mail-sending plugin that actually * sends (or duplicates) each message to SMS, Twitter, instant message, etc, * or a plugin that queues up a large number of messages for more efficient * bulk sending or for sending via a remote gateway so as to reduce the load * on the local server. * * @param array $options * An array with the following key/value pairs: * - module: (string) The module name which was used by drupal_mail() to * invoke hook_mail(). * - key: (string) A key to identify the email sent. The final message ID * is a string represented as {$module}_{$key}. * * @return \Drupal\Core\Mail\MailInterface * A mail plugin instance. * * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException */ public function getInstance(array $options) { $module = $options['module']; $key = $options['key']; $message_id = $module . '_' . $key; $configuration = $this->mailConfig->get('interface'); // Look for overrides for the default mail plugin, starting from the most // specific message_id, and falling back to the module name. if (isset($configuration[$message_id])) { $plugin_id = $configuration[$message_id]; } elseif (isset($configuration[$module])) { $plugin_id = $configuration[$module]; } else { $plugin_id = $configuration['default']; } if (empty($this->instances[$plugin_id])) { $plugin = $this->createInstance($plugin_id); if (is_subclass_of($plugin, '\\Drupal\\Core\\Mail\\MailInterface')) { $this->instances[$plugin_id] = $plugin; } else { throw new InvalidPluginDefinitionException($plugin_id, String::format('Class %class does not implement interface %interface', array('%class' => get_class($plugin), '%interface' => 'Drupal\\Core\\Mail\\MailInterface'))); } } return $this->instances[$plugin_id]; }
/** * {@inheritdoc} */ public function forbiddenMessage(EntityInterface $entity, $field_name) { if (!isset($this->authenticatedCanPostComments)) { // We only output a link if we are certain that users will get the // permission to post comments by logging in. $this->authenticatedCanPostComments = $this->entityManager->getStorage('user_role')->load(DRUPAL_AUTHENTICATED_RID)->hasPermission('post comments'); } if ($this->authenticatedCanPostComments) { // We cannot use drupal_get_destination() because these links // sometimes appear on /node and taxonomy listing pages. if ($entity->get($field_name)->getFieldDefinition()->getSetting('form_location') == CommentItemInterface::FORM_SEPARATE_PAGE) { $destination = array('destination' => 'comment/reply/' . $entity->getEntityTypeId() . '/' . $entity->id() . '/' . $field_name . '#comment-form'); } else { $destination = array('destination' => $entity->getSystemPath() . '#comment-form'); } if ($this->userConfig->get('register') != USER_REGISTER_ADMINISTRATORS_ONLY) { // Users can register themselves. return $this->t('<a href="@login">Log in</a> or <a href="@register">register</a> to post comments', array('@login' => $this->urlGenerator->generateFromRoute('user.login', array(), array('query' => $destination)), '@register' => $this->urlGenerator->generateFromRoute('user.register', array(), array('query' => $destination)))); } else { // Only admins can add new users, no public registration. return $this->t('<a href="@login">Log in</a> to post comments', array('@login' => $this->urlGenerator->generateFromRoute('user.login', array(), array('query' => $destination)))); } } return ''; }
/** * Processes asset libraries into render arrays. * * @param array $attached * The attachments to process. * @param array $placeholders * The placeholders that exist in the response. * * @return array * An array keyed by asset type, with keys: * - styles * - scripts * - scripts_bottom */ protected function processAssetLibraries(array $attached, array $placeholders) { $all_attached = ['#attached' => $attached]; $assets = AttachedAssets::createFromRenderArray($all_attached); // Take Ajax page state into account, to allow for something like Turbolinks // to be implemented without altering core. // @see https://github.com/rails/turbolinks/ // @todo https://www.drupal.org/node/2497115 - Below line is broken due to ->request. $ajax_page_state = $this->requestStack->getCurrentRequest()->request->get('ajax_page_state'); $assets->setAlreadyLoadedLibraries(isset($ajax_page_state) ? explode(',', $ajax_page_state['libraries']) : []); $variables = []; // Print styles - if present. if (isset($placeholders['styles'])) { // Optimize CSS if necessary, but only during normal site operation. $optimize_css = !defined('MAINTENANCE_MODE') && $this->config->get('css.preprocess'); $variables['styles'] = $this->cssCollectionRenderer->render($this->assetResolver->getCssAssets($assets, $optimize_css)); } // Print scripts - if any are present. if (isset($placeholders['scripts']) || isset($placeholders['scripts_bottom'])) { // Optimize JS if necessary, but only during normal site operation. $optimize_js = !defined('MAINTENANCE_MODE') && !\Drupal::state()->get('system.maintenance_mode') && $this->config->get('js.preprocess'); list($js_assets_header, $js_assets_footer) = $this->assetResolver->getJsAssets($assets, $optimize_js); $variables['scripts'] = $this->jsCollectionRenderer->render($js_assets_header); $variables['scripts_bottom'] = $this->jsCollectionRenderer->render($js_assets_footer); } return $variables; }
/** * Retrieves a configuration object. * * This is the main entry point to the configuration API. Calling * @code $this->config('book.admin') @endcode will return a configuration * object in which the book module can store its administrative settings. * * @param string $name * The name of the configuration object to retrieve. The name corresponds to * a configuration file. For @code \Drupal::config('book.admin') @endcode, * the config object returned will contain the contents of book.admin * configuration file. * * @return \Drupal\Core\Config\Config * A configuration object. */ protected function config($name) { if (!$this->configFactory) { $this->configFactory = $this->container()->get('config.factory'); } return $this->configFactory->get($name); }
/** * Returns the timestamp the check was last skipped on, or 0 if it hasn't been * skipped yet. * * @return int * The UNIX timestamp the check was last skipped on (or 0). */ public function skippedOn() { $skippedOn = $this->config->get('skipped_on'); if (!is_int($skippedOn)) { return 0; } return $skippedOn; }
/** * {@inheritdoc} */ public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) { $timezone = NULL; if ($row->hasSourceProperty('timezone_name')) { if (isset(static::$timezones[$row->getSourceProperty('timezone_name')])) { $timezone = $row->getSourceProperty('timezone_name'); } } if (!$timezone && $row->hasSourceProperty('event_timezone')) { if (isset(static::$timezones[$row->getSourceProperty('event_timezone')])) { $timezone = $row->getSourceProperty('event_timezone'); } } if ($timezone === NULL) { $timezone = $this->dateConfig->get('timezone.default'); } return $timezone; }
/** * {@inheritdoc} */ public function updateIndex() { // Interpret the cron limit setting as the maximum number of nodes to index // per cron run. $limit = (int)$this->searchSettings->get('index.cron_limit'); $language = \Drupal::languageManager()->getCurrentLanguage()->getId(); $topics = $this->getSids($this->advancedHelp->getTopics()); // If we got interrupted by limit, this will contain the last module // and topic we looked at. $last = \Drupal::state()->get($this->getPluginId() . '.last_cron', ['time' => 0]); $count = 0; foreach ($topics as $module => $module_topics) { // Fast forward if necessary. if (!empty($last['module']) && $last['module'] != $module) { continue; } foreach ($module_topics as $topic => $info) { // Fast forward if necessary. if (!empty($last['topic']) && $last['topic'] != $topic) { continue; } //If we've been looking to catch up, and we have, reset so we // stop fast forwarding. if (!empty($last['module'])) { unset($last['topic']); unset($last['module']); } $file = $this->advancedHelp->getTopicFileName($module, $topic); if ($file && (empty($info['sid']) || filemtime($file) > $last['time'])) { if (empty($info['sid'])) { $info['sid'] = $this->database->insert('advanced_help_index') ->fields([ 'module' => $module, 'topic' => $topic, 'langcode' => $language ]) ->execute(); } } // Update index, using search index "type" equal to the plugin ID. search_index($this->getPluginId(), $info['sid'], $language, file_get_contents($file)); $count++; if ($count >= $limit) { $last['module'] = $module; $last['topic'] = $topic; \Drupal::state()->set($this->getPluginId() . '.last_cron', $last); return; } } } \Drupal::state()->set($this->getPluginId() . '.last_cron', ['time' => time()]); }
/** * {@inheritdoc} */ public function importDelete($name, Config $new_config, Config $old_config) { // If the field has been deleted in the same import, the instance will be // deleted by then, and there is nothing left to do. Just return TRUE so // that the file does not get written to active store. if (!$old_config->get()) { return TRUE; } return parent::importDelete($name, $new_config, $old_config); }
/** * Prepares the AJAX commands to attach assets. * * @param \Drupal\Core\Ajax\AjaxResponse $response * The AJAX response to update. * @param \Symfony\Component\HttpFoundation\Request $request * The request object that the AJAX is responding to. * * @return array * An array of commands ready to be returned as JSON. */ protected function buildAttachmentsCommands(AjaxResponse $response, Request $request) { $ajax_page_state = $request->request->get('ajax_page_state'); // Aggregate CSS/JS if necessary, but only during normal site operation. $optimize_css = !defined('MAINTENANCE_MODE') && $this->config->get('css.preprocess'); $optimize_js = !defined('MAINTENANCE_MODE') && $this->config->get('js.preprocess'); $attachments = $response->getAttachments(); // Resolve the attached libraries into asset collections. $assets = new AttachedAssets(); $assets->setLibraries(isset($attachments['library']) ? $attachments['library'] : [])->setAlreadyLoadedLibraries(isset($ajax_page_state['libraries']) ? explode(',', $ajax_page_state['libraries']) : [])->setSettings(isset($attachments['drupalSettings']) ? $attachments['drupalSettings'] : []); $css_assets = $this->assetResolver->getCssAssets($assets, $optimize_css); list($js_assets_header, $js_assets_footer) = $this->assetResolver->getJsAssets($assets, $optimize_js); // Render the HTML to load these files, and add AJAX commands to insert this // HTML in the page. Settings are handled separately, afterwards. $settings = []; if (isset($js_assets_header['drupalSettings'])) { $settings = $js_assets_header['drupalSettings']['data']; unset($js_assets_header['drupalSettings']); } if (isset($js_assets_footer['drupalSettings'])) { $settings = $js_assets_footer['drupalSettings']['data']; unset($js_assets_footer['drupalSettings']); } // Prepend commands to add the assets, preserving their relative order. $resource_commands = array(); if ($css_assets) { $css_render_array = $this->cssCollectionRenderer->render($css_assets); $resource_commands[] = new AddCssCommand((string) $this->renderer->renderPlain($css_render_array)); } if ($js_assets_header) { $js_header_render_array = $this->jsCollectionRenderer->render($js_assets_header); $resource_commands[] = new PrependCommand('head', (string) $this->renderer->renderPlain($js_header_render_array)); } if ($js_assets_footer) { $js_footer_render_array = $this->jsCollectionRenderer->render($js_assets_footer); $resource_commands[] = new AppendCommand('body', (string) $this->renderer->renderPlain($js_footer_render_array)); } foreach (array_reverse($resource_commands) as $resource_command) { $response->addCommand($resource_command, TRUE); } // Prepend a command to merge changes and additions to drupalSettings. if (!empty($settings)) { // During Ajax requests basic path-specific settings are excluded from // new drupalSettings values. The original page where this request comes // from already has the right values. An Ajax request would update them // with values for the Ajax request and incorrectly override the page's // values. // @see system_js_settings_alter() unset($settings['path']); $response->addCommand(new SettingsCommand($settings, TRUE), TRUE); } $commands = $response->getCommands(); $this->moduleHandler->alter('ajax_render', $commands); return $commands; }
/** * {@inheritdoc} */ public function getDerivativeDefinitions($base_plugin_definition) { $default_theme = $this->config->get('default'); foreach ($this->themeHandler->listInfo() as $theme_name => $theme) { if ($theme->status) { $this->derivatives[$theme_name] = $base_plugin_definition; $this->derivatives[$theme_name]['title'] = $theme->info['name']; $this->derivatives[$theme_name]['route_parameters'] = array('theme' => $theme_name); } // Default task! if ($default_theme == $theme_name) { $this->derivatives[$theme_name]['route_name'] = 'block.admin_display'; // Emulate default logic because without the base plugin id we can't // change the base_route. $this->derivatives[$theme_name]['weight'] = -10; unset($this->derivatives[$theme_name]['route_parameters']); } } return $this->derivatives; }
/** * Builds a language negotiation method configuration table. * * @param array $form * The language negotiation configuration form. * @param string $type * The language type to generate the table for. */ protected function configureFormTable(array &$form, $type) { $info = $form['#language_types_info'][$type]; $table_form = array('#title' => $this->t('@type language detection', array('@type' => $info['name'])), '#tree' => TRUE, '#description' => $info['description'], '#language_negotiation_info' => array(), '#show_operations' => FALSE, 'weight' => array('#tree' => TRUE)); // Only show configurability checkbox for the unlocked language types. if (empty($info['locked'])) { $configurable = $this->languageTypes->get('configurable'); $table_form['configurable'] = array('#type' => 'checkbox', '#title' => $this->t('Customize %language_name language detection to differ from Interface text language detection settings', array('%language_name' => $info['name'])), '#default_value' => in_array($type, $configurable), '#attributes' => array('class' => array('language-customization-checkbox')), '#attached' => array('library' => array('language/drupal.language.admin'))); } $negotiation_info = $form['#language_negotiation_info']; $enabled_methods = $this->languageTypes->get('negotiation.' . $type . '.enabled') ?: array(); $methods_weight = $this->languageTypes->get('negotiation.' . $type . '.method_weights') ?: array(); // Add missing data to the methods lists. foreach ($negotiation_info as $method_id => $method) { if (!isset($methods_weight[$method_id])) { $methods_weight[$method_id] = isset($method['weight']) ? $method['weight'] : 0; } } // Order methods list by weight. asort($methods_weight); foreach ($methods_weight as $method_id => $weight) { // A language method might be no more available if the defining module has // been disabled after the last configuration saving. if (!isset($negotiation_info[$method_id])) { continue; } $enabled = isset($enabled_methods[$method_id]); $method = $negotiation_info[$method_id]; // List the method only if the current type is defined in its 'types' key. // If it is not defined default to all the configurable language types. $types = array_flip(isset($method['types']) ? $method['types'] : $form['#language_types']); if (isset($types[$type])) { $table_form['#language_negotiation_info'][$method_id] = $method; $method_name = SafeMarkup::checkPlain($method['name']); $table_form['weight'][$method_id] = array('#type' => 'weight', '#title' => $this->t('Weight for !title language detection method', array('!title' => Unicode::strtolower($method_name))), '#title_display' => 'invisible', '#default_value' => $weight, '#attributes' => array('class' => array("language-method-weight-{$type}")), '#delta' => 20); $table_form['title'][$method_id] = array('#markup' => $method_name); $table_form['enabled'][$method_id] = array('#type' => 'checkbox', '#title' => $this->t('Enable !title language detection method', array('!title' => Unicode::strtolower($method_name))), '#title_display' => 'invisible', '#default_value' => $enabled); if ($method_id === LanguageNegotiationSelected::METHOD_ID) { $table_form['enabled'][$method_id]['#default_value'] = TRUE; $table_form['enabled'][$method_id]['#attributes'] = array('disabled' => 'disabled'); } $table_form['description'][$method_id] = array('#markup' => Xss::filterAdmin($method['description'])); $config_op = array(); if (isset($method['config_route_name'])) { $config_op['configure'] = array('title' => $this->t('Configure'), 'url' => Url::fromRoute($method['config_route_name'])); // If there is at least one operation enabled show the operation // column. $table_form['#show_operations'] = TRUE; } $table_form['operation'][$method_id] = array('#type' => 'operations', '#links' => $config_op); } } $form[$type] = $table_form; }
/** * {@inheritdoc} */ public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) { list($theme, $default_theme, $admin_theme) = $value; // If the source theme exists on the destination, we're good. if (isset($this->themes[$theme])) { return $theme; } // If the source block is assigned to a region in the source default theme, // then assign it to the destination default theme. if (strtolower($theme) == strtolower($default_theme)) { return $this->themeConfig->get('default'); } // If the source block is assigned to a region in the source admin theme, // then assign it to the destination admin theme. if (strtolower($theme) == strtolower($admin_theme)) { return $this->themeConfig->get('admin'); } // We couldn't map it to a D8 theme so just return the incoming theme. return $theme; }
/** * Redirects forum taxonomy terms to correct forum path. * * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event */ public function globalredirectForum(GetResponseEvent $event) { $request = $event->getRequest(); if ($event->getRequestType() != HttpKernelInterface::MASTER_REQUEST || !$this->config->get('term_path_handler') || !$this->moduleHandler->moduleExists('forum') || !preg_match('/taxonomy\\/term\\/([0-9]+)$/', $request->getUri(), $matches)) { return; } $term = $this->entityManager->getStorage('taxonomy_term')->load($matches[1]); if (!empty($term) && $term->url() != $request->getPathInfo()) { $this->setResponse($event, Url::fromUri('entity:taxonomy_term/' . $term->id())); } }
/** * Filters data in the override based on what is currently in configuration. * * @param \Drupal\Core\Config\Config $config * Current configuration object. * @param \Drupal\Core\Config\StorableConfigBase $override * Override object corresponding to the configuration to filter data in. */ protected function filterOverride(Config $config, StorableConfigBase $override) { $override_data = $override->get(); $this->filterNestedArray($config->get(), $override_data); if (empty($override_data)) { // If no override values are left that would apply, remove the override. $override->delete(); } else { // Otherwise set the filtered override values back. $override->setData($override_data)->save(); } }