/** * {@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 buildForm(array $form, FormStateInterface $form_state) { $config = $this->configFactory->get('examples.cron'); $form['status'] = ['#type' => 'details', '#title' => $this->t('Cron status information'), '#open' => TRUE]; $form['status']['intro'] = ['#type' => 'item', '#markup' => $this->t('The cron example demonstrates hook_cron() and hook_queue_info() processing. If you have administrative privileges you can run cron from this page and see the results.')]; $next_execution = $config->get('next_execution'); $next_execution = !empty($next_execution) ? $next_execution : REQUEST_TIME; $args = ['%time' => date_iso8601($config->get('next_execution')), '%seconds' => $next_execution - REQUEST_TIME]; $form['status']['last'] = ['#type' => 'item', '#markup' => $this->t('cron_example_cron() will next execute the first time cron runs after %time (%seconds seconds from now)', $args)]; if ($this->currentUser->hasPermission('administer site configuration')) { $form['cron_run'] = ['#type' => 'details', '#title' => $this->t('Run cron manually'), '#open' => TRUE]; $form['cron_run']['cron_reset'] = ['#type' => 'checkbox', '#title' => $this->t('Run cron_example\'s cron regardless of whether interval has expired.'), '#default_value' => FALSE]; $form['cron_run']['cron_trigger']['actions'] = ['#type' => 'actions']; $form['cron_run']['cron_trigger']['actions']['sumbit'] = ['#type' => 'submit', '#value' => $this->t('Run cron now'), '#submit' => [[$this, 'cronRun']]]; } $form['cron_queue_setup'] = ['#type' => 'details', '#title' => $this->t('Cron queue setup (for hook_cron_queue_info(), etc.)'), '#open' => TRUE]; $queue_1 = $this->queue->get('cron_example_queue_1'); $queue_2 = $this->queue->get('cron_example_queue_2'); $args = ['%queue_1' => $queue_1->numberOfItems(), '%queue_2' => $queue_2->numberOfItems()]; $form['cron_queue_setup']['current_cron_queue_status'] = ['#type' => 'item', '#markup' => $this->t('There are currently %queue_1 items in queue 1 and %queue_2 items in queue 2', $args)]; $form['cron_queue_setup']['num_items'] = ['#type' => 'select', '#title' => $this->t('Number of items to add to queue'), '#options' => array_combine([1, 5, 10, 100, 1000], [1, 5, 10, 100, 1000]), '#default_value' => 5]; $form['cron_queue_setup']['queue'] = ['#type' => 'radios', '#title' => $this->t('Queue to add items to'), '#options' => ['cron_example_queue_1' => $this->t('Queue 1'), 'cron_example_queue_2' => $this->t('Queue 2')], '#default_value' => 'cron_example_queue_1']; $form['cron_queue_setup']['actions'] = ['#type' => 'actions']; $form['cron_queue_setup']['actions']['submit'] = ['#type' => 'submit', '#value' => $this->t('Add jobs to queue'), '#submit' => [[$this, 'addItems']]]; $form['configuration'] = ['#type' => 'details', '#title' => $this->t('Configuration of cron_example_cron()'), '#open' => TRUE]; $form['configuration']['cron_example_interval'] = ['#type' => 'select', '#title' => $this->t('Cron interval'), '#description' => $this->t('Time after which cron_example_cron will respond to a processing request.'), '#default_value' => $config->get('interval'), '#options' => [60 => $this->t('1 minute'), 300 => $this->t('5 minutes'), 3600 => $this->t('1 hour'), 86400 => $this->t('1 day')]]; return parent::buildForm($form, $form_state); }
/** * Checks access to the given user's contact page. * * @param \Drupal\user\UserInterface $user * The user being contacted. * @param \Drupal\Core\Session\AccountInterface $account * The currently logged in account. * * @return string * A \Drupal\Core\Access\AccessInterface constant value. */ public function access(UserInterface $user, AccountInterface $account) { $contact_account = $user; // Anonymous users cannot have contact forms. if ($contact_account->isAnonymous()) { return static::DENY; } // Users may not contact themselves. if ($account->id() == $contact_account->id()) { return static::DENY; } // User administrators should always have access to personal contact forms. if ($account->hasPermission('administer users')) { return static::ALLOW; } // If requested user has been blocked, do not allow users to contact them. if ($contact_account->isBlocked()) { return static::DENY; } // If the requested user has disabled their contact form, do not allow users // to contact them. $account_data = $this->userData->get('contact', $contact_account->id(), 'enabled'); if (isset($account_data) && empty($account_data)) { return static::DENY; } else { if (!$this->configFactory->get('contact.settings')->get('user_default_enabled')) { return static::DENY; } } return $account->hasPermission('access user contact forms') ? static::ALLOW : static::DENY; }
protected function checkAccess(ContentEntityInterface $entity, AccountInterface $account, $operation = 'view') { $entity_type = $entity->getEntityType(); $entity_type_id = $entity->getEntityTypeId(); $entity_access = $this->entityTypeManager->getAccessControlHandler($entity_type_id); /** @var \Drupal\Core\Entity\EntityStorageInterface $entity_storage */ $entity_storage = $this->entityTypeManager->getStorage($entity_type_id); $map = ['view' => "view all {$entity_type_id} revisions", 'update' => "revert all {$entity_type_id} revisions", 'delete' => "delete all {$entity_type_id} revisions"]; $bundle = $entity->bundle(); $type_map = ['view' => "view {$entity_type_id} {$bundle} revisions", 'update' => "revert {$entity_type_id} {$bundle} revisions", 'delete' => "delete {$entity_type_id} {$bundle} revisions"]; if (!$entity || !isset($map[$operation]) || !isset($type_map[$operation])) { // If there was no node to check against, or the $op was not one of the // supported ones, we return access denied. return FALSE; } // Statically cache access by revision ID, language code, user account ID, // and operation. $langcode = $entity->language()->getId(); $cid = $entity->getRevisionId() . ':' . $langcode . ':' . $account->id() . ':' . $operation; if (!isset($this->accessCache[$cid])) { // Perform basic permission checks first. if (!$account->hasPermission($map[$operation]) && !$account->hasPermission($type_map[$operation]) && !$account->hasPermission('administer nodes')) { $this->accessCache[$cid] = FALSE; return FALSE; } if (($admin_permission = $entity_type->getAdminPermission()) && $account->hasPermission($admin_permission)) { $this->accessCache[$cid] = TRUE; } else { // First check the access to the default revision and finally, if the // node passed in is not the default revision then access to that, too. $this->accessCache[$cid] = $entity_access->access($entity_storage->load($entity->id()), $operation, $account) && ($entity->isDefaultRevision() || $entity_access->access($entity, $operation, $account)); } } return $this->accessCache[$cid]; }
/** * {@inheritdoc} */ public function defaultAccess($operation = 'view', AccountInterface $account = NULL) { if ($operation == 'view') { return TRUE; } return $account->hasPermission('create url aliases') || $account->hasPermission('administer url aliases'); }
/** * {@inheritdoc} */ public function viewElements(FieldItemListInterface $items, $langcode) { $element = []; if ($items->status == 1 && $this->currentUser->hasPermission('view disqus comments')) { $element[] = ['#type' => 'disqus', '#url' => $items->getEntity()->toUrl('canonical', ['absolute' => TRUE])->toString(), '#title' => (string) $items->getEntity()->label(), '#identifier' => $items->identifier ?: "{$items->getEntity()->getEntityTypeId()}/{$items->getEntity()->id()}"]; } return $element; }
/** * Selects the block place override of the block page display variant. * * @param \Drupal\Core\Render\PageDisplayVariantSelectionEvent $event * The event to process. */ public function onBlockPageDisplayVariantSelected(PageDisplayVariantSelectionEvent $event) { if ($event->getPluginId() === 'block_page') { if ($this->requestStack->getCurrentRequest()->query->has('block-place') && $this->account->hasPermission('administer blocks')) { $event->setPluginId('block_place_page'); } $event->addCacheContexts(['user.permissions', 'url.query_args']); } }
/** * {@inheritdoc} */ public function isApplicable() { // Remove on Admin routes. $is_admin_route = $this->adminContext->isAdminRoute(); // Remove on Block Demo page. $is_admin_demo_route = $this->routeMatch->getRouteName() === 'block.admin_demo'; // @todo Check if there is actually a different admin theme. // https://www.drupal.org/node/2784853 return $this->account->hasPermission('administer blocks') && !$is_admin_route && !$is_admin_demo_route; }
/** * {@inheritdoc} */ protected function checkAccess(EntityInterface $entity, $operation, AccountInterface $account) { if ($operation == 'view' || $operation == 'update') { if ($account->hasPermission('administer tmgmt') || $account->hasPermission('administer translation tasks')) { // Administrators can do everything. return AccessResult::allowed()->cachePerPermissions(); } return AccessResult::allowedIf($entity->getTask()->tuid->target_id == $account->id() && $account->hasPermission('provide translation services')); } return $entity->getTask()->access($operation, $account, TRUE); }
/** * {@inheritdoc} */ protected function checkAccess(EntityInterface $entity, $operation, AccountInterface $account) { switch ($operation) { case 'view': // Check for status and set 'published' or 'unpublished'. $status = $entity->status->value ? 'published' : 'unpublished'; return AccessResult::allowedIf($account->hasPermission('access content') && $account->hasPermission('view ' . $status . ' terms in ' . $entity->bundle())); default: return parent::checkAccess($entity, $operation, $account); } }
/** * {@inheritdoc} */ protected function checkCreateAccess(AccountInterface $account, array $context, $entity_bundle = NULL) { if ($account->hasPermission('administer shortcuts')) { return TRUE; } if (!$account->hasPermission('access shortcuts')) { return FALSE; } if ($account->hasPermission('customize shortcut links')) { return TRUE; } }
/** * Initializes devel module requirements. */ public function onRequest(GetResponseEvent $event) { if (!devel_silent()) { if ($this->account->hasPermission('access devel information')) { devel_set_handler(devel_get_handlers()); // We want to include the class early so that anyone may call krumo() // as needed. See http://krumo.sourceforge.net/ has_krumo(); // See http://www.firephp.org/HQ/Install.htm $path = NULL; if (@(include_once 'fb.php') || @(include_once 'FirePHPCore/fb.php')) { // FirePHPCore is in include_path. Probably a PEAR installation. $path = ''; } elseif ($this->moduleHandler->moduleExists('libraries')) { // Support Libraries API - http://drupal.org/project/libraries $firephp_path = libraries_get_path('FirePHPCore'); $firephp_path = $firephp_path ? $firephp_path . '/lib/FirePHPCore/' : ''; $chromephp_path = libraries_get_path('chromephp'); } else { $firephp_path = DRUPAL_ROOT . '/libraries/FirePHPCore/lib/FirePHPCore/'; $chromephp_path = './' . drupal_get_path('module', 'devel') . '/chromephp'; } // Include FirePHP if it exists. if (!empty($firephp_path) && file_exists($firephp_path . 'fb.php')) { include_once $firephp_path . 'fb.php'; include_once $firephp_path . 'FirePHP.class.php'; } // Include ChromePHP if it exists. if (!empty($chromephp_path) && file_exists($chromephp_path .= '/ChromePhp.php')) { include_once $chromephp_path; } } } if ($this->config->get('rebuild_theme')) { drupal_theme_rebuild(); // Ensure that the active theme object is cleared. $theme_name = \Drupal::theme()->getActiveTheme()->getName(); \Drupal::state()->delete('theme.active_theme.' . $theme_name); \Drupal::theme()->resetActiveTheme(); /** @var \Drupal\Core\Extension\ThemeHandlerInterface $theme_handler*/ $theme_handler = \Drupal::service('theme_handler'); $theme_handler->refreshInfo(); // @todo This is not needed after https://www.drupal.org/node/2330755 $list = $theme_handler->listInfo(); $theme_handler->addTheme($list[$theme_name]); if (\Drupal::service('flood')->isAllowed('devel.rebuild_theme_warning', 1)) { \Drupal::service('flood')->register('devel.rebuild_theme_warning'); if (!devel_silent() && $this->account->hasPermission('access devel information')) { drupal_set_message(t('The theme information is being rebuilt on every request. Remember to <a href=":url">turn off</a> this feature on production websites.', array(':url' => $this->urlGenerator->generateFromRoute('devel.admin_settings')))); } } } }
/** * {@inheritdoc} */ public function checkAccess(EntityInterface $entity, $operation, $langcode, AccountInterface $account) { if ($operation == 'view') { // Do not allow access personal category via site-wide route. return $account->hasPermission('access site-wide contact form') && $entity->id() !== 'personal'; } elseif ($operation == 'delete' || $operation == 'update') { // Do not allow the 'personal' category to be deleted, as it's used for // the personal contact form. return $account->hasPermission('administer contact forms') && $entity->id() !== 'personal'; } return parent::checkAccess($entity, $operation, $langcode, $account); }
/** * {@inheritdoc} */ protected function checkAccess(EntityInterface $entity, $operation, AccountInterface $account) { switch ($operation) { case 'update': return AccessResult::allowedIf($account->hasPermission('administer grade letters'))->cachePerPermissions()->cacheUntilEntityChanges($entity); case 'delete': return AccessResult::allowedIf($account->hasPermission('administer grade letters') && $entity->getGradeLetterSet() != 'default')->cachePerPermissions(); default: // No opinion. return AccessResult::neutral(); } }
/** * {@inheritdoc} */ public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) { $element['status'] = ['#type' => 'checkbox', '#title' => t('Disqus Comments'), '#description' => t('Users can post comments using <a href=":disqus">Disqus</a>.', [':disqus' => 'http://disqus.com']), '#default_value' => isset($items->status) ? $items->status : TRUE, '#access' => $this->currentUser->hasPermission('toggle disqus comments')]; $element['identifier'] = ['#type' => 'textfield', '#title' => $this->t('Disqus identifier'), '#description' => $this->t('Unique identifier of the Disqus thread. "[entity-type]/[entity-id]" is used if not set. Changing this might cause comments to disappear. Use extreme caution!'), '#default_value' => isset($items->identifier) ? $items->identifier : '', '#access' => $this->currentUser->hasPermission('administer disqus')]; // If the advanced settings tabs-set is available (normally rendered in the // second column on wide-resolutions), place the field as a details element // in this tab-set. if (isset($form['advanced'])) { $element += array('#type' => 'details', '#group' => 'advanced'); } return $element; }
/** * {@inheritdoc} */ protected function checkAccess(EntityInterface $entity, $operation, AccountInterface $account) { if ($operation == 'view') { // Do not allow access personal form via site-wide route. return AccessResult::allowedIf($account->hasPermission('access site-wide contact form') && $entity->id() !== 'personal')->cachePerPermissions(); } elseif ($operation == 'delete' || $operation == 'update') { // Do not allow the 'personal' form to be deleted, as it's used for // the personal contact form. return AccessResult::allowedIf($account->hasPermission('administer contact forms') && $entity->id() !== 'personal')->cachePerPermissions(); } return parent::checkAccess($entity, $operation, $account); }
/** * {@inheritdoc} */ protected function checkFieldAccess($operation, FieldDefinitionInterface $field_definition, AccountInterface $account, FieldItemListInterface $items = NULL) { // Fields that are not implicitly allowed to administrative users. $explicit_check_fields = array('pass'); // Administrative users are allowed to edit and view all fields. if (!in_array($field_definition->getName(), $explicit_check_fields) && $account->hasPermission('administer users')) { return AccessResult::allowed()->cachePerPermissions(); } // Flag to indicate if this user entity is the own user account. $is_own_account = $items ? $items->getEntity()->id() == $account->id() : FALSE; switch ($field_definition->getName()) { case 'name': // Allow view access to anyone with access to the entity. Anonymous // users should be able to access the username field during the // registration process, otherwise the username and email constraints // are not checked. if ($operation == 'view' || $items && $account->isAnonymous() && $items->getEntity()->isAnonymous()) { return AccessResult::allowed()->cachePerPermissions(); } // Allow edit access for the own user name if the permission is // satisfied. if ($is_own_account && $account->hasPermission('change own username')) { return AccessResult::allowed()->cachePerPermissions()->cachePerUser(); } else { return AccessResult::forbidden(); } case 'preferred_langcode': case 'preferred_admin_langcode': case 'timezone': case 'mail': // Allow view access to own mail address and other personalization // settings. if ($operation == 'view') { return $is_own_account ? AccessResult::allowed()->cachePerUser() : AccessResult::forbidden(); } // Anyone that can edit the user can also edit this field. return AccessResult::allowed()->cachePerPermissions(); case 'pass': // Allow editing the password, but not viewing it. return $operation == 'edit' ? AccessResult::allowed() : AccessResult::forbidden(); case 'created': // Allow viewing the created date, but not editing it. return $operation == 'view' ? AccessResult::allowed() : AccessResult::forbidden(); case 'roles': case 'status': case 'access': case 'login': case 'init': return AccessResult::forbidden(); } return parent::checkFieldAccess($operation, $field_definition, $account, $items); }
/** * Initializes devel module requirements. */ public function onRequest(GetResponseEvent $event) { if (!devel_silent()) { if ($this->config->get('memory')) { global $memory_init; $memory_init = memory_get_usage(); } if (devel_query_enabled()) { Database::startLog('devel'); } if ($this->account->hasPermission('access devel information')) { devel_set_handler(devel_get_handlers()); // We want to include the class early so that anyone may call krumo() // as needed. See http://krumo.sourceforge.net/ has_krumo(); // See http://www.firephp.org/HQ/Install.htm $path = NULL; if (@(include_once 'fb.php') || @(include_once 'FirePHPCore/fb.php')) { // FirePHPCore is in include_path. Probably a PEAR installation. $path = ''; } elseif ($this->moduleHandler->moduleExists('libraries')) { // Support Libraries API - http://drupal.org/project/libraries $firephp_path = libraries_get_path('FirePHPCore'); $firephp_path = $firephp_path ? $firephp_path . '/lib/FirePHPCore/' : ''; $chromephp_path = libraries_get_path('chromephp'); } else { $firephp_path = DRUPAL_ROOT . '/libraries/FirePHPCore/lib/FirePHPCore/'; $chromephp_path = './' . drupal_get_path('module', 'devel') . '/chromephp'; } // Include FirePHP if it exists. if (!empty($firephp_path) && file_exists($firephp_path . 'fb.php')) { include_once $firephp_path . 'fb.php'; include_once $firephp_path . 'FirePHP.class.php'; } // Include ChromePHP if it exists. if (!empty($chromephp_path) && file_exists($chromephp_path .= '/ChromePhp.php')) { include_once $chromephp_path; } } } if ($this->config->get('rebuild_theme_registry')) { drupal_theme_rebuild(); if (\Drupal::service('flood')->isAllowed('devel.rebuild_registry_warning', 1)) { \Drupal::service('flood')->register('devel.rebuild_registry_warning'); if (!devel_silent() && $this->account->hasPermission('access devel information')) { drupal_set_message(t('The theme registry is being rebuilt on every request. Remember to <a href="!url">turn off</a> this feature on production websites.', array("!url" => url('admin/config/development/devel')))); } } } drupal_register_shutdown_function('devel_shutdown'); }
/** * {@inheritdoc} */ public function addMessage($message, $op = NULL) { if (!isset($this->isVerbose)) { $config = $this->configFactory->get('pathauto.settings'); $this->isVerbose = $config->get('verbose') && $this->account->hasPermission('notify of path changes'); } if (!$this->isVerbose || isset($op) && in_array($op, array('bulkupdate', 'return'))) { return FALSE; } if ($message) { drupal_set_message($message); } return TRUE; }
/** * Check view access. * * See EntityAccessControllerInterface::view() for parameters. */ protected function viewAccess(EntityInterface $entity, $langcode, AccountInterface $account) { // Never allow access to view the anonymous user account. if ($entity->id()) { // Admins can view all, users can view own profiles at all times. if ($account->id() == $entity->id() || $account->hasPermission('administer users')) { return TRUE; } elseif ($account->hasPermission('access user profiles')) { // Only allow view access if the account is active. return $entity->status->value; } } return FALSE; }
/** * {@inheritdoc} */ public function viewElements(FieldItemListInterface $items, $langcode) { $element = []; // As the Field API only applies the "field default value" to newly created // entities, we'll apply the default value for existing entities. if ($items->count() == 0) { $field_default_value = $items->getFieldDefinition()->getDefaultValue($items->getEntity()); $items->status = $field_default_value[0]['status']; } if ($items->status == 1 && $this->currentUser->hasPermission('view disqus comments')) { $element[] = ['#type' => 'disqus', '#url' => $items->getEntity()->toUrl('canonical', ['absolute' => TRUE])->toString(), '#title' => (string) $items->getEntity()->label(), '#identifier' => $items->identifier ?: "{$items->getEntity()->getEntityTypeId()}/{$items->getEntity()->id()}"]; } return $element; }
/** * @param \Symfony\Component\HttpKernel\Event\FilterResponseEvent $event */ public function onKernelResponse(FilterResponseEvent $event) { $response = $event->getResponse(); $request = $event->getRequest(); if ($response->headers->has('X-Debug-Token') && NULL !== $this->urlGenerator) { $response->headers->set('X-Debug-Token-Link', $this->urlGenerator->generate('webprofiler.dashboard', ['profile' => $response->headers->get('X-Debug-Token')])); } // do not capture redirects or modify XML HTTP Requests if ($request->isXmlHttpRequest()) { return; } if ($this->currentUser->hasPermission('view webprofiler toolbar')) { $this->injectToolbar($response); } }
/** * {@inheritdoc} */ public function viewElements(FieldItemListInterface $items, $langcode) { $element = []; foreach ($items as $delta => $item) { $provider = $this->providerManager->loadProviderFromInput($item->value); $autoplay = $this->currentUser->hasPermission('never autoplay videos') ? FALSE : $this->getSetting('autoplay'); $element[$delta] = $provider->renderEmbedCode($this->getSetting('width'), $this->getSetting('height'), $autoplay); $element[$delta]['#cache']['contexts'][] = 'user.permissions'; // For responsive videos, wrap each field item in it's own container. if ($this->getSetting('responsive')) { $element[$delta] = ['#type' => 'container', '#attached' => ['library' => ['video_embed_field/responsive-video']], '#attributes' => ['class' => ['video-embed-field-responsive-video']], 'children' => $element[$delta]]; } } return $element; }
/** * Checks translation access for the entity and operation on the given route. * * @param \Symfony\Component\Routing\Route $route * The route to check against. * @param \Drupal\Core\Routing\RouteMatchInterface $route_match * The parametrized route. * @param \Drupal\Core\Session\AccountInterface $account * The currently logged in account. * @param string $source * (optional) For a create operation, the language code of the source. * @param string $target * (optional) For a create operation, the language code of the translation. * @param string $language * (optional) For an update or delete operation, the language code of the * translation being updated or deleted. * @param string $entity_type_id * (optional) The entity type ID. * * @return \Drupal\Core\Access\AccessResultInterface * The access result. */ public function access(Route $route, RouteMatchInterface $route_match, AccountInterface $account, $source = NULL, $target = NULL, $language = NULL, $entity_type_id = NULL) { /* @var \Drupal\Core\Entity\ContentEntityInterface $entity */ if ($entity = $route_match->getParameter($entity_type_id)) { if ($account->hasPermission('translate any entity')) { return AccessResult::allowed()->cachePerRole(); } $operation = $route->getRequirement('_access_content_translation_manage'); /* @var \Drupal\content_translation\ContentTranslationHandlerInterface $handler */ $handler = $this->entityManager->getHandler($entity->getEntityTypeId(), 'translation'); // Load translation. $translations = $entity->getTranslationLanguages(); $languages = $this->languageManager->getLanguages(); switch ($operation) { case 'create': $source_language = $this->languageManager->getLanguage($source) ?: $entity->language(); $target_language = $this->languageManager->getLanguage($target) ?: $this->languageManager->getCurrentLanguage(LanguageInterface::TYPE_CONTENT); $is_new_translation = $source_language->getId() != $target_language->getId() && isset($languages[$source_language->getId()]) && isset($languages[$target_language->getId()]) && !isset($translations[$target_language->getId()]); return AccessResult::allowedIf($is_new_translation)->cachePerRole()->cacheUntilEntityChanges($entity)->andIf($handler->getTranslationAccess($entity, $operation)); case 'update': case 'delete': $language = $this->languageManager->getLanguage($language) ?: $this->languageManager->getCurrentLanguage(LanguageInterface::TYPE_CONTENT); $has_translation = isset($languages[$language->getId()]) && $language->getId() != $entity->getUntranslated()->language()->getId() && isset($translations[$language->getId()]); return AccessResult::allowedIf($has_translation)->cachePerRole()->cacheUntilEntityChanges($entity)->andIf($handler->getTranslationAccess($entity, $operation)); } } // No opinion. return AccessResult::neutral(); }
/** * Returns the site maintenance page if the site is offline. * * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event * The event to process. */ public function onKernelRequestMaintenance(GetResponseEvent $event) { $route_match = RouteMatch::createFromRequest($event->getRequest()); if ($this->maintenanceMode->applies($route_match)) { // Don't cache maintenance mode pages. \Drupal::service('page_cache_kill_switch')->trigger(); if (!$this->maintenanceMode->exempt($this->account)) { // Deliver the 503 page if the site is in maintenance mode and the // logged in user is not allowed to bypass it. drupal_maintenance_theme(); $content = Xss::filterAdmin(SafeMarkup::format($this->config->get('system.maintenance')->get('message'), array('@site' => $this->config->get('system.site')->get('name')))); $output = $this->bareHtmlPageRenderer->renderBarePage(['#markup' => $content], $this->t('Site under maintenance'), 'maintenance_page'); $response = new Response($output, 503); $event->setResponse($response); } else { // Display a message if the logged in user has access to the site in // maintenance mode. However, suppress it on the maintenance mode // settings page. if ($route_match->getRouteName() != 'system.site_maintenance_mode') { if ($this->account->hasPermission('administer site configuration')) { $this->drupalSetMessage($this->t('Operating in maintenance mode. <a href="@url">Go online.</a>', array('@url' => $this->urlGenerator->generate('system.site_maintenance_mode'))), 'status', FALSE); } else { $this->drupalSetMessage($this->t('Operating in maintenance mode.'), 'status', FALSE); } } } } }
/** * {@inheritdoc} */ public function searchFormAlter(array &$form, FormStateInterface $form_state) { // Add advanced search keyword-related boxes. $form['advanced'] = array('#type' => 'details', '#title' => t('Advanced search'), '#attributes' => array('class' => array('search-advanced')), '#access' => $this->account && $this->account->hasPermission('use advanced search')); $form['advanced']['keywords-fieldset'] = array('#type' => 'fieldset', '#title' => t('Keywords')); $form['advanced']['keywords'] = array('#prefix' => '<div class="criterion">', '#suffix' => '</div>'); $form['advanced']['keywords-fieldset']['keywords']['or'] = array('#type' => 'textfield', '#title' => t('Containing any of the words'), '#size' => 30, '#maxlength' => 255); $form['advanced']['keywords-fieldset']['keywords']['phrase'] = array('#type' => 'textfield', '#title' => t('Containing the phrase'), '#size' => 30, '#maxlength' => 255); $form['advanced']['keywords-fieldset']['keywords']['negative'] = array('#type' => 'textfield', '#title' => t('Containing none of the words'), '#size' => 30, '#maxlength' => 255); // Add node types. $types = array_map(array('\\Drupal\\Component\\Utility\\String', 'checkPlain'), node_type_get_names()); $form['advanced']['types-fieldset'] = array('#type' => 'fieldset', '#title' => t('Types')); $form['advanced']['types-fieldset']['type'] = array('#type' => 'checkboxes', '#title' => t('Only of the type(s)'), '#prefix' => '<div class="criterion">', '#suffix' => '</div>', '#options' => $types); $form['advanced']['submit'] = array('#type' => 'submit', '#value' => t('Advanced search'), '#prefix' => '<div class="action">', '#suffix' => '</div>', '#weight' => 100); // Add languages. $language_options = array(); $language_list = $this->languageManager->getLanguages(LanguageInterface::STATE_ALL); foreach ($language_list as $langcode => $language) { // Make locked languages appear special in the list. $language_options[$langcode] = $language->isLocked() ? t('- @name -', array('@name' => $language->getName())) : $language->getName(); } if (count($language_options) > 1) { $form['advanced']['lang-fieldset'] = array('#type' => 'fieldset', '#title' => t('Languages')); $form['advanced']['lang-fieldset']['language'] = array('#type' => 'checkboxes', '#title' => t('Languages'), '#prefix' => '<div class="criterion">', '#suffix' => '</div>', '#options' => $language_options); } }
/** * {@inheritdoc} */ protected function checkAccess(EntityInterface $entity, $operation, $langcode, AccountInterface $account) { if ($operation == 'delete' && $entity->getFieldStorageDefinition()->isLocked()) { return FALSE; } return $account->hasPermission('administer ' . $entity->entity_type . ' fields'); }
/** * Clone multiple fields on the Clone Field Page. * * @param $type_id * @param array $fields * * @throws \Exception */ protected function cloneFields($type_id, array $fields) { $this->gotoURLIfNot("admin/config/workflow/scheduled-update-type/$type_id/clone-fields"); $edit = []; foreach ($fields as $input_name => $field_info) { // Check the field label exists. $this->assertText( $field_info['label'], new FormattableMarkup('Field label %label displayed.', ['%label' => $field_info['label']]) ); // Add to post data. $edit[$input_name] = $field_info['input_value']; } $this->drupalPostForm(NULL, $edit, t('Clone Fields')); if ($this->adminUser->hasPermission('administer scheduled_update form display')) { // Should be redirected to form display after cloning fields $this->assertUrl("admin/config/workflow/scheduled-update-type/$type_id/form-display"); $this->checkFieldLabels($fields); } else { // @todo Does it make any sense for admin to be able to add update types without Field UI permissions // Enforce Field UI permissions to add scheduled update type? $this->assertText('You do not have permission to administer fields on Scheduled Updates.'); } }
/** * {@inheritdoc} */ public function query() { $this->ensureMyTable(); // Try to find an entity queue relationship in this view, and pick the first // one available. foreach ($this->view->relationship as $id => $relationship) { if ($relationship instanceof EntityQueueRelationship) { $this->options['relationship'] = $id; $this->setRelationship(); break; } } if (isset($this->relationship) && ($subqueue_items_table_alias = $this->query->ensureTable($this->definition['field table'], $this->relationship))) { $field_field = $this->definition['field field']; $operator = $this->value ? 'IS NOT NULL' : 'IS NULL'; $condition = "$subqueue_items_table_alias.$field_field $operator"; $this->query->addWhereExpression($this->options['group'], $condition); // Limit to a specific queue if the relationship specifies it. if (isset($relationship) && !empty($relationship->options['limit_queue'])) { $column = "$subqueue_items_table_alias.bundle"; $this->query->addWhere($this->options['group'], $column, $relationship->options['limit_queue'], '='); } } else { if ($this->currentUser->hasPermission('administer views')) { drupal_set_message($this->t('In order to sort by the queue position, you need to add the Entityqueue: Queue relationship on View: @view with display: @display', ['@view' => $this->view->storage->label(), '@display' => $this->view->current_display]), 'error'); } } }
/** * Returns the site maintenance page if the site is offline. * * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event * The event to process. */ public function onKernelRequestMaintenance(GetResponseEvent $event) { $request = $event->getRequest(); $route_match = RouteMatch::createFromRequest($request); if ($this->maintenanceMode->applies($route_match)) { // Don't cache maintenance mode pages. \Drupal::service('page_cache_kill_switch')->trigger(); if (!$this->maintenanceMode->exempt($this->account)) { // Deliver the 503 page if the site is in maintenance mode and the // logged in user is not allowed to bypass it. // If the request format is not 'html' then show default maintenance // mode page else show a text/plain page with maintenance message. if ($request->getRequestFormat() !== 'html') { $response = new Response($this->getSiteMaintenanceMessage(), 503, array('Content-Type' => 'text/plain')); $event->setResponse($response); return; } drupal_maintenance_theme(); $response = $this->bareHtmlPageRenderer->renderBarePage(['#markup' => $this->getSiteMaintenanceMessage()], $this->t('Site under maintenance'), 'maintenance_page'); $response->setStatusCode(503); $event->setResponse($response); } else { // Display a message if the logged in user has access to the site in // maintenance mode. However, suppress it on the maintenance mode // settings page. if ($route_match->getRouteName() != 'system.site_maintenance_mode') { if ($this->account->hasPermission('administer site configuration')) { $this->drupalSetMessage($this->t('Operating in maintenance mode. <a href=":url">Go online.</a>', array(':url' => $this->urlGenerator->generate('system.site_maintenance_mode'))), 'status', FALSE); } else { $this->drupalSetMessage($this->t('Operating in maintenance mode.'), 'status', FALSE); } } } } }