/** * {@inheritdoc} * * When the $operation is 'add' then the $entity is of type 'profile_type', * otherwise $entity is of type 'profile'. */ protected function checkAccess(EntityInterface $entity, $operation, AccountInterface $account) { $account = $this->prepareUser($account); $user_page = \Drupal::request()->attributes->get('user'); // Some times, operation edit is called update. // Use edit in any case. if ($operation == 'update') { $operation = 'edit'; } // Check that if profile type has require roles, the user the profile is // being added to has any of the required roles. if ($entity->getEntityTypeId() == 'profile') { $profile_roles = ProfileType::load($entity->bundle())->getRoles(); $user_roles = $entity->getOwner()->getRoles(TRUE); if (!empty(array_filter($profile_roles)) && !array_intersect($user_roles, $profile_roles)) { return AccessResult::forbidden(); } } elseif ($entity->getEntityTypeId() == 'profile_type') { $profile_roles = $entity->getRoles(); $user_roles = User::load($user_page->id())->getRoles(TRUE); if (!empty(array_filter($profile_roles)) && !array_intersect($user_roles, $profile_roles)) { return AccessResult::forbidden(); } } if ($account->hasPermission('bypass profile access')) { return AccessResult::allowed()->cachePerPermissions(); } elseif ($operation == 'add' && ($user_page->id() == $account->id() && $account->hasPermission($operation . ' own ' . $entity->id() . ' profile') || $account->hasPermission($operation . ' any ' . $entity->id() . ' profile')) || $operation != 'add' && ($entity->getOwnerId() == $account->id() && $account->hasPermission($operation . ' own ' . $entity->getType() . ' profile') || $account->hasPermission($operation . ' any ' . $entity->getType() . ' profile'))) { return AccessResult::allowed()->cachePerPermissions(); } else { return AccessResult::forbidden()->cachePerPermissions(); } }
/** * Test the WYSIWYG embed modal. */ public function testEmbedDialog() { // Use the modal to embed into a page. $this->drupalGet('node/add/page'); $this->find('.cke_button__video_embed')->click(); $this->assertSession()->assertWaitOnAjaxRequest(); // Assert all the form fields appear on the modal. $this->assertSession()->pageTextContains('Autoplay'); $this->assertSession()->pageTextContains('Responsive Video'); $this->assertSession()->pageTextContains('Width'); $this->assertSession()->pageTextContains('Height'); $this->assertSession()->pageTextContains('Video URL'); // Attempt to submit the modal with no values. $this->find('input[name="video_url"]')->setValue(''); $this->find('button.form-submit')->click(); $this->assertSession()->assertWaitOnAjaxRequest(); $this->assertSession()->pageTextContains('Video URL field is required.'); // Submit the form with an invalid video URL. $this->find('input[name="video_url"]')->setValue('http://example.com/'); $this->find('button.form-submit')->click(); $this->assertSession()->assertWaitOnAjaxRequest(); $this->assertSession()->pageTextContains('Could not find a video provider to handle the given URL.'); $this->assertContains('http://example.com/', $this->getSession()->getPage()->getHtml()); // Submit a valid URL. $this->find('input[name="video_url"]')->setValue('https://www.youtube.com/watch?v=iaf3Sl2r3jE&t=1553s'); $this->find('button.form-submit')->click(); $this->assertSession()->assertWaitOnAjaxRequest(); // View the source of the ckeditor and find the output. $this->find('.cke_button__source_label')->click(); $base_path = \Drupal::request()->getBasePath(); $this->assertEquals('<p>{"preview_thumbnail":"' . rtrim($base_path, '/') . '/' . $this->publicFilesDirectory . '/styles/video_embed_wysiwyg_preview/public/video_thumbnails/iaf3Sl2r3jE.jpg","video_url":"https://www.youtube.com/watch?v=iaf3Sl2r3jE&t=1553s","settings":{"responsive":1,"width":"854","height":"480","autoplay":1},"settings_summary":["Embedded Video (Responsive, autoplaying)."]}</p>', trim($this->getSession()->getPage()->find('css', '.cke_source')->getValue())); }
/** * Access callback for json() callback. */ public function access() { $request = \Drupal::request(); $nonce = $request->get('nonce', FALSE); $connector_config = $this->config('acquia_connector.settings'); // If we don't have all the query params, leave now. if (!$nonce) { return AccessResultForbidden::forbidden(); } $sub_data = $connector_config->get('subscription_data'); $sub_uuid = $this->getIdFromSub($sub_data); if (!empty($sub_uuid)) { $expected_hash = hash('sha1', "{$sub_uuid}:{$nonce}"); // If the generated hash matches the hash from $_GET['key'], we're good. if ($request->get('key', FALSE) === $expected_hash) { return AccessResultAllowed::allowed(); } } // Log the request if validation failed and debug is enabled. if ($connector_config->get('debug')) { $info = array('sub_data' => $sub_data, 'sub_uuid_from_data' => $sub_uuid, 'expected_hash' => $expected_hash, 'get' => $request->query->all(), 'server' => $request->server->all(), 'request' => $request->request->all()); \Drupal::logger('acquia_agent')->notice('Site status request: @data', array('@data' => var_export($info, TRUE))); } return AccessResultForbidden::forbidden(); }
/** * {inheritdoc} */ protected function prepareComponent($node, $component) { /** @var \Drupal\webform\ComponentInterface $loaded_component */ $loaded_component = $this->componentManager->createInstance($component); $loaded_component->setConfiguration(['type' => \Drupal::request()->query->get('type'), 'pid' => \Drupal::request()->query->get('pid'), 'weight' => \Drupal::request()->query->get('weight'), 'required' => \Drupal::request()->query->get('required'), 'name' => \Drupal::request()->query->get('name')]); return $loaded_component; }
/** * {@inheritdoc} */ public function preprocessVariables(Variables $variables) { $breadcrumb =& $variables['breadcrumb']; // Determine if breadcrumbs should be displayed. $breadcrumb_visibility = $this->theme->getSetting('breadcrumb'); if ($breadcrumb_visibility == 0 || $breadcrumb_visibility == 2 && \Drupal::service('router.admin_context')->isAdminRoute() || empty($breadcrumb)) { $breadcrumb = []; return; } // Optionally get rid of the homepage link. $show_breadcrumb_home = $this->theme->getSetting('breadcrumb_home'); if (!$show_breadcrumb_home) { array_shift($breadcrumb); } if ($this->theme->getSetting('breadcrumb_title') && !empty($breadcrumb)) { $request = \Drupal::request(); $route_match = \Drupal::routeMatch(); $page_title = \Drupal::service('title_resolver')->getTitle($request, $route_match->getRouteObject()); if (!empty($page_title)) { $breadcrumb[] = ['text' => $page_title, 'attributes' => new Attribute(['class' => ['active']])]; // Add cache context based on url. $variables->addCacheContexts(['url']); } } }
/** * {@inheritdoc} */ public function actions(array $form, FormStateInterface $form_state) { $actions = parent::actions($form, $form_state); if ($this->entity->isNew()) { $actions['submit']['#value'] = $this->t('Create Flagging'); } else { $actions['submit']['#value'] = $this->t('Update Flagging'); } // Customize the delete link. if (isset($actions['delete'])) { // @todo Why does the access call always fail? unset($actions['delete']['#access']); $actions['delete']['#title'] = $this->t('Delete Flagging'); // Build the delete url from route. We need to build this manually // otherwise Drupal will try to build the flagging entity's delete-form // link. Since that route doesn't use the flagging ID, Drupal can't build // the link for us. $route_params = [ 'flag' => $this->entity->getFlagId(), 'entity_id' => $this->entity->getFlaggableId(), 'destination' => \Drupal::request()->get('destination'), ]; $url = Url::fromRoute('flag.confirm_unflag', $route_params); $actions['delete']['#url'] = $url; } return $actions; }
/** * Overrides MollomDrupalTest::__construct(). */ public function __construct(ConfigFactory $config_factory, ClientInterface $http_client) { // Replace server/endpoint with our local fake server. $server = \Drupal::request()->getHttpHost() . '/mollom-test/rest'; $this->server = $server; parent::__construct($config_factory, $http_client); }
public function installIntegration($forumDirectoryPath) { try { //Using SMF native functions $smfSSI = DRUPAL_ROOT . '/' . $forumDirectoryPath . '/SSI.php'; if (file_exists($smfSSI)) { require_once $smfSSI; add_integration_function('integrate_pre_include', DRUPAL_ROOT . '/' . drupal_get_path('module', 'smfbridge') . '/src/Smf/Hooks.php'); add_integration_function('integrate_actions', 'Drupal\\smfbridge\\Smf\\Hooks::actions', TRUE); add_integration_function('integrate_menu_buttons', 'Drupal\\smfbridge\\Smf\\Hooks::smfMenuButtons', TRUE); //Use database driven sessions - on $this->updateSmfSettingsValues('databaseSession_enable', '1'); /** * @var \Drupal\Core\Session\SessionConfiguration $sessionConfiguration */ $sessionConfiguration = \Drupal::service('session_configuration'); $options = $sessionConfiguration->getOptions(\Drupal::request()); $this->updateSmfSettingsValues('databaseSession_lifetime', $options['gc_maxlifetime']); } else { throw new \Exception(t('Can\'t forum/SSI.php. Please, place SMF sources into DRUPAL_ROOT/forum folder.')); } return TRUE; } catch (\Exception $e) { $errorMsg = t('Error while enabling smfbridge. @message', ['@message' => $e->getMessage()]); \Drupal::logger('smfbridge')->error($errorMsg); drupal_set_message($errorMsg, 'error'); return FALSE; } }
public function content() { $lat = \Drupal::request()->get("lat"); $lon = \Drupal::request()->get("lon"); $json = $this->get_weather($lat, $lon); return new JsonResponse($json); }
/** * Tests the behavior of the theme registry class. */ function testRaceCondition() { // The theme registry is not marked as persistable in case we don't have a // proper request. \Drupal::request()->setMethod('GET'); $cid = 'test_theme_registry'; // Directly instantiate the theme registry, this will cause a base cache // entry to be written in __construct(). $cache = \Drupal::cache(); $lock_backend = \Drupal::lock(); $registry = new ThemeRegistry($cid, $cache, $lock_backend, array('theme_registry'), $this->container->get('module_handler')->isLoaded()); $this->assertTrue(\Drupal::cache()->get($cid), 'Cache entry was created.'); // Trigger a cache miss for an offset. $this->assertTrue($registry->get('theme_test_template_test'), 'Offset was returned correctly from the theme registry.'); // This will cause the ThemeRegistry class to write an updated version of // the cache entry when it is destroyed, usually at the end of the request. // Before that happens, manually delete the cache entry we created earlier // so that the new entry is written from scratch. \Drupal::cache()->delete($cid); // Destroy the class so that it triggers a cache write for the offset. $registry->destruct(); $this->assertTrue(\Drupal::cache()->get($cid), 'Cache entry was created.'); // Create a new instance of the class. Confirm that both the offset // requested previously, and one that has not yet been requested are both // available. $registry = new ThemeRegistry($cid, $cache, $lock_backend, array('theme_registry'), $this->container->get('module_handler')->isLoaded()); $this->assertTrue($registry->get('theme_test_template_test'), 'Offset was returned correctly from the theme registry'); $this->assertTrue($registry->get('theme_test_template_test_2'), 'Offset was returned correctly from the theme registry'); }
/** * Returns success only if this page is being accessed by HTTPS. * * @param \Symfony\Component\HttpFoundation\Request $request * The current request object. * * @return \Symfony\Component\HttpFoundation\Response|array * A \Symfony\Component\HttpFoundation\Response object or render array. */ public function testHttpsConnection(Request $request) { if (\Drupal::request()->isSecure()) { return new Response($this->t('HTTPS works!'), 200); } return new Response($this->t('HTTPS doesn\'t work'), 404); }
/** * Constructs a ThemeRegistry object. * * @param string $cid * The cid for the array being cached. * @param \Drupal\Core\Cache\CacheBackendInterface $cache * The cache backend. * @param \Drupal\Core\Lock\LockBackendInterface $lock * The lock backend. * @param array $tags * (optional) The tags to specify for the cache item. * @param bool $modules_loaded * Whether all modules have already been loaded. */ function __construct($cid, CacheBackendInterface $cache, LockBackendInterface $lock, $tags = array(), $modules_loaded = FALSE) { $this->cid = $cid; $this->cache = $cache; $this->lock = $lock; $this->tags = $tags; $this->persistable = $modules_loaded && \Drupal::hasRequest() && \Drupal::request()->isMethod('GET'); // @todo: Implement lazyload. $this->cacheLoaded = TRUE; if ($this->persistable && ($cached = $this->cache->get($this->cid))) { $this->storage = $cached->data; } else { // If there is no runtime cache stored, fetch the full theme registry, // but then initialize each value to NULL. This allows offsetExists() // to function correctly on non-registered theme hooks without triggering // a call to resolveCacheMiss(). $this->storage = $this->initializeRegistry(); foreach (array_keys($this->storage) as $key) { $this->persist($key); } // RegistryTest::testRaceCondition() ensures that the cache entry is // written on the initial construction of the theme registry. $this->updateCache(); } }
/** * Event callback to look for users expired password */ public function checkForUserPasswordExpiration(GetResponseEvent $event) { $account = \Drupal::currentUser(); // There needs to be an explicit check for non-anonymous or else // this will be tripped and a forced redirect will occur. if ($account->id() > 0) { /** @var $user \Drupal\user\UserInterface */ $user = entity_load('user', $account->id()); $route_name = \Drupal::request()->attributes->get(RouteObjectInterface::ROUTE_NAME); ///system/ajax $ignored_routes = array('entity.user.edit_form', 'system.ajax', 'user.logout'); $user_expired = FALSE; if ($user->get('field_password_expiration')->get(0)) { $user_expired = $user->get('field_password_expiration')->get(0)->getValue(); $user_expired = $user_expired['value']; } //TODO - Consider excluding admins here if ($user_expired and !in_array($route_name, $ignored_routes)) { $url = new Url('entity.user.edit_form', array('user' => $user->id())); $url = $url->toString(); $event->setResponse(new RedirectResponse($url)); drupal_set_message('Your password has expired, please update it', 'error'); } } }
/** * {@inheritdoc} */ public function buildForm(array $form, FormStateInterface $form_state, $entity_type_id = NULL, $bundle = NULL, $context = NULL) { if ($context == 'form') { $this->mode = \Drupal::request()->get('form_mode_name'); } else { $this->mode = \Drupal::request()->get('view_mode_name'); } if (empty($this->mode)) { $this->mode = 'default'; } if (!$form_state->get('context')) { $form_state->set('context', $context); } if (!$form_state->get('entity_type_id')) { $form_state->set('entity_type_id', $entity_type_id); } if (!$form_state->get('bundle')) { $form_state->set('bundle', $bundle); } if (!$form_state->get('step')) { $form_state->set('step', 'formatter'); } $this->entityTypeId = $form_state->get('entity_type_id'); $this->bundle = $form_state->get('bundle'); $this->context = $form_state->get('context'); $this->currentStep = $form_state->get('step'); if ($this->currentStep == 'formatter') { $this->buildFormatterSelectionForm($form, $form_state); } else { $this->buildConfigurationForm($form, $form_state); } return $form; }
/** * Gets the rules UI handler of the current route. * * @return \Drupal\rules\Ui\RulesUiHandlerInterface|null * The handler, or NULL if this is no rules_ui enabled route. */ public function getRulesUiHandler() { if (!isset($this->rulesUiHandler)) { $this->rulesUiHandler = \Drupal::request()->attributes->get('rules_ui_handler'); } return $this->rulesUiHandler; }
function testUserTokens() { // Add a user picture to the account. $image = current($this->drupalGetTestFiles('image')); $edit = array('files[user_picture_0]' => drupal_realpath($image->uri)); $this->drupalPostForm('user/' . $this->account->id() . '/edit', $edit, t('Save')); $storage = \Drupal::entityManager()->getStorage('user'); // Load actual user data from database. $storage->resetCache(); $this->account = $storage->load($this->account->id()); $this->assertTrue(!empty($this->account->user_picture->target_id), 'User picture uploaded.'); $picture = ['#theme' => 'user_picture', '#account' => $this->account]; /** @var \Drupal\Core\Render\RendererInterface $renderer */ $renderer = \Drupal::service('renderer'); $user_tokens = array('picture' => $renderer->render($picture), 'picture:fid' => $this->account->user_picture->target_id, 'picture:size-raw' => 125, 'ip-address' => NULL, 'roles' => implode(', ', $this->account->getRoles())); $this->assertTokens('user', array('user' => $this->account), $user_tokens); // Remove the simpletest-created user role. $roles = $this->account->getRoles(); $this->account->removeRole(end($roles)); $this->account->save(); // Remove the user picture field and reload the user. FieldStorageConfig::loadByName('user', 'user_picture')->delete(); $storage->resetCache(); $this->account = $storage->load($this->account->id()); $user_tokens = array('picture' => NULL, 'picture:fid' => NULL, 'ip-address' => NULL, 'roles' => 'authenticated', 'roles:keys' => (string) DRUPAL_AUTHENTICATED_RID); $this->assertTokens('user', array('user' => $this->account), $user_tokens); // The ip address token should work for the current user token type. $tokens = array('ip-address' => \Drupal::request()->getClientIp()); $this->assertTokens('current-user', array(), $tokens); $anonymous = new AnonymousUserSession(); $tokens = array('roles' => 'anonymous', 'roles:keys' => (string) DRUPAL_ANONYMOUS_RID); $this->assertTokens('user', array('user' => $anonymous), $tokens); }
/** * {@inheritdoc} */ public function build() { $request = \Drupal::request(); $route_match = \Drupal::routeMatch(); $title = \Drupal::service('title_resolver')->getTitle($request, $route_match->getRouteObject()); return array('#markup' => $title); }
/** * {@inheritdoc} */ public function form(array $form, FormStateInterface $form_state) { // Try to restore from temp store, this must be done before calling // parent::form(). $uuid = $this->entity->uuid(); $store = $this->tempStoreFactory->get('node_preview'); // If the user is creating a new node, the UUID is passed in the request. if ($request_uuid = \Drupal::request()->query->get('uuid')) { $uuid = $request_uuid; } if ($preview = $store->get($uuid)) { /** @var $preview \Drupal\Core\Form\FormStateInterface */ foreach ($preview->getValues() as $name => $value) { $form_state->setValue($name, $value); } // Rebuild the form. $form_state->setRebuild(); $this->entity = $preview->getFormObject()->getEntity(); $this->entity->in_preview = NULL; // Remove the stale temp store entry for existing nodes. if (!$this->entity->isNew()) { $store->delete($uuid); } $this->hasBeenPreviewed = TRUE; } /** @var \Drupal\node\NodeInterface $node */ $node = $this->entity; if ($this->operation == 'edit') { $form['#title'] = $this->t('<em>Edit @type</em> @title', array('@type' => node_get_type_label($node), '@title' => $node->label())); } $current_user = $this->currentUser(); // Changed must be sent to the client, for later overwrite error checking. $form['changed'] = array('#type' => 'hidden', '#default_value' => $node->getChangedTime()); $form['advanced'] = array('#type' => 'vertical_tabs', '#attributes' => array('class' => array('entity-meta')), '#weight' => 99); $form = parent::form($form, $form_state); // Add a revision_log field if the "Create new revision" option is checked, // or if the current user has the ability to check that option. $form['revision_information'] = array('#type' => 'details', '#group' => 'advanced', '#title' => t('Revision information'), '#open' => $node->isNewRevision(), '#attributes' => array('class' => array('node-form-revision-information')), '#attached' => array('library' => array('node/drupal.node')), '#weight' => 20, '#optional' => TRUE); $form['revision'] = array('#type' => 'checkbox', '#title' => t('Create new revision'), '#default_value' => $node->type->entity->isNewRevision(), '#access' => $current_user->hasPermission('administer nodes'), '#group' => 'revision_information'); $form['revision_log'] += array('#states' => array('visible' => array(':input[name="revision"]' => array('checked' => TRUE))), '#group' => 'revision_information'); // Node author information for administrators. $form['author'] = array('#type' => 'details', '#title' => t('Authoring information'), '#group' => 'advanced', '#attributes' => array('class' => array('node-form-author')), '#attached' => array('library' => array('node/drupal.node')), '#weight' => 90, '#optional' => TRUE); if (isset($form['uid'])) { $form['uid']['#group'] = 'author'; } if (isset($form['created'])) { $form['created']['#group'] = 'author'; } // Node options for administrators. $form['options'] = array('#type' => 'details', '#title' => t('Promotion options'), '#group' => 'advanced', '#attributes' => array('class' => array('node-form-options')), '#attached' => array('library' => array('node/drupal.node')), '#weight' => 95, '#optional' => TRUE); if (isset($form['promote'])) { $form['promote']['#group'] = 'options'; } if (isset($form['sticky'])) { $form['sticky']['#group'] = 'options'; } $form['#attached']['library'][] = 'node/form'; $form['#entity_builders']['update_status'] = [$this, 'updateStatus']; return $form; }
/** * Tests the entity reference revisions configuration. */ public function testEntityReferenceRevisions() { $admin_user = $this->drupalCreateUser(array('administer site configuration', 'administer nodes', 'create article content', 'administer content types', 'administer node fields', 'administer node display', 'administer node form display', 'edit any article content')); $this->drupalLogin($admin_user); // Create entity reference revisions field. static::fieldUIAddNewField('admin/structure/types/manage/entity_revisions', 'entity_reference_revisions', 'Entity reference revisions', 'entity_reference_revisions', array('settings[target_type]' => 'node', 'cardinality' => '-1'), array('settings[handler_settings][target_bundles][article]' => TRUE)); $this->assertText('Saved Entity reference revisions configuration.'); // Create an article. $title = $this->randomMachineName(); $edit = array('title[0][value]' => $title, 'body[0][value]' => 'Revision 1', 'revision' => TRUE); $this->drupalPostForm('node/add/article', $edit, t('Save and publish')); $this->assertText($title); $this->assertText('Revision 1'); $node = $this->drupalGetNodeByTitle($title); // Create entity revisions content that includes the above article. $err_title = 'Entity reference revision content'; $edit = array('title[0][value]' => $err_title, 'field_entity_reference_revisions[0][target_id]' => $node->label() . ' (' . $node->id() . ')'); $this->drupalPostForm('node/add/entity_revisions', $edit, t('Save and publish')); $this->assertText('Entity revisions Entity reference revision content has been created.'); $err_node = $this->drupalGetNodeByTitle($err_title); $this->assertText($err_title); $this->assertText($title); $this->assertText('Revision 1'); // Create 2nd revision of the article. $edit = array('body[0][value]' => 'Revision 2', 'revision' => TRUE); $this->drupalPostForm('node/' . $node->id() . '/edit', $edit, t('Save and keep published')); $serializer = $this->container->get('serializer'); $normalized = $serializer->normalize($err_node, 'hal_json'); $request = \Drupal::request(); $link_domain = $request->getSchemeAndHttpHost() . $request->getBasePath(); $this->assertEqual($err_node->field_entity_reference_revisions->target_revision_id, $normalized['_embedded'][$link_domain . '/rest/relation/node/entity_revisions/field_entity_reference_revisions'][0]['target_revision_id']); $new_err_node = $serializer->denormalize($normalized, Node::class, 'hal_json'); $this->assertEqual($err_node->field_entity_reference_revisions->target_revision_id, $new_err_node->field_entity_reference_revisions->target_revision_id); }
/** * {@inheritdoc} */ public function submitForm(array &$form, FormStateInterface $form_state) { $entity_type = \Drupal::request()->get('entity_type'); $bundle = \Drupal::request()->get('bundle'); $field_name = \Drupal::request()->get('field_name'); mailchimp_lists_update_member_merge_values($entity_type, $bundle, $field_name); drupal_set_message(t('Mergevars updated.')); }
/** * {@inheritdoc} */ public function build() { $build = []; $request = \Drupal::request(); $config = $this->getConfiguration(); $build[] = ["#theme" => "facebook_comment", "#pageUrl" => $request->getUri(), "#applicationCode" => isset($config['fc_applicationCode']) ? $config['fc_applicationCode'] : "", "#numPosts" => isset($config['fc_numPosts']) ? $config['fc_numPosts'] : "10", "#width" => isset($config['fc_width']) ? $config['fc_width'] : "100%", "#orderBy" => isset($config['fc_orderBy']) ? $config['fc_orderBy'] : "social", "#colorScheme" => isset($config['fc_colorScheme']) ? $config['fc_colorScheme'] : "light", "#attached" => ['library' => ["facebook_comment/fb-comment"]]]; return $build; }
/** * {@inheritdoc} */ public function buildForm(array $form, FormStateInterface $form_state) { // Log execution time. $start_time = microtime(TRUE); // Try to load the files count from cache. This function will accept two // arguments: // - cache object name (cid) // - cache bin, the (optional) cache bin (most often a database table) where // the object is to be saved. // // cache_get() returns the cached object or FALSE if object does not exist. if ($cache = \Drupal::cache()->get('cache_example_files_count')) { /* * Get cached data. Complex data types will be unserialized automatically. */ $files_count = $cache->data; } else { // If there was no cached data available we have to search filesystem. // Recursively get all files from Drupal's folder. $files_count = count(file_scan_directory('.', '/.*/')); // Since we have recalculated, we now need to store the new data into // cache. Complex data types will be automatically serialized before // being saved into cache. // Here we use the default setting and create an unexpiring cache item. // See below for an example that creates an expiring cache item. \Drupal::cache()->set('cache_example_files_count', $files_count, CacheBackendInterface::CACHE_PERMANENT); } $end_time = microtime(TRUE); $duration = $end_time - $start_time; // Format intro message. $intro_message = '<p>' . t('This example will search the entire drupal folder and display a count of the files in it.') . ' '; $intro_message .= t('This can take a while, since there are a lot of files to be searched.') . ' '; $intro_message .= t('We will search filesystem just once and save output to the cache. We will use cached data for later requests.') . '</p>'; $intro_message .= '<p>' . t('<a href="@url">Reload this page</a> to see cache in action.', array('@url' => \Drupal::request()->getRequestUri())) . ' '; $intro_message .= t('You can use the button below to remove cached data.') . '</p>'; $form['file_search'] = array('#type' => 'fieldset', '#title' => t('File search caching')); $form['file_search']['introduction'] = array('#markup' => $intro_message); $color = empty($cache) ? 'red' : 'green'; $retrieval = empty($cache) ? t('calculated by traversing the filesystem') : t('retrieved from cache'); $form['file_search']['statistics'] = array('#type' => 'item', '#markup' => t('%count files exist in this Drupal installation; @retrieval in @time ms. <br/>(Source: <span style="color:@color;">@source</span>)', array('%count' => $files_count, '@retrieval' => $retrieval, '@time' => number_format($duration * 1000, 2), '@color' => $color, '@source' => empty($cache) ? t('actual file search') : t('cached')))); $form['file_search']['remove_file_count'] = array('#type' => 'submit', '#submit' => array(array($this, 'expireFiles')), '#value' => t('Explicitly remove cached file count')); $form['expiration_demo'] = array('#type' => 'fieldset', '#title' => t('Cache expiration settings')); $form['expiration_demo']['explanation'] = array('#markup' => t('A cache item can be set as CACHE_PERMANENT, meaning that it will only be removed when explicitly cleared, or it can have an expiration time (a Unix timestamp).')); $item = \Drupal::cache()->get('cache_example_expiring_item', TRUE); if ($item == FALSE) { $item_status = t('Cache item does not exist'); } else { $item_status = $item->valid ? t('Cache item exists and is set to expire at %time', array('%time' => $item->data)) : t('Cache_item is invalid'); } $form['expiration_demo']['current_status'] = array('#type' => 'item', '#title' => t('Current status of cache item "cache_example_expiring_item"'), '#markup' => $item_status); $form['expiration_demo']['expiration'] = array('#type' => 'select', '#title' => t('Time before cache expiration'), '#options' => array('never_remove' => t('CACHE_PERMANENT'), -10 => t('Immediate expiration'), 10 => t('10 seconds from form submission'), 60 => t('1 minute from form submission'), 300 => t('5 minutes from form submission')), '#default_value' => -10, '#description' => t('Any cache item can be set to only expire when explicitly cleared, or to expire at a given time.')); $form['expiration_demo']['create_cache_item'] = array('#type' => 'submit', '#value' => t('Create a cache item with this expiration'), '#submit' => array(array($this, 'createExpiringItem'))); $form['cache_clearing'] = array('#type' => 'fieldset', '#title' => t('Expire and remove options'), '#description' => t("We have APIs to expire cached items and also to just remove them. Unfortunately, they're all the same API, cache_clear_all")); $form['cache_clearing']['cache_clear_type'] = array('#type' => 'radios', '#title' => t('Type of cache clearing to do'), '#options' => array('expire' => t('Remove items from the "cache" bin that have expired'), 'remove_all' => t('Remove all items from the "cache" bin regardless of expiration'), 'remove_tag' => t('Remove all items in the "cache" bin with the tag "cache_example" set to 1')), '#default_value' => 'expire'); // Submit button to clear cached data. $form['cache_clearing']['clear_expired'] = array('#type' => 'submit', '#value' => t('Clear or expire cache'), '#submit' => array(array($this, 'cacheClearing')), '#access' => \Drupal::currentUser()->hasPermission('administer site configuration')); return $form; }
/** * Downloads a tarball of the site configuration. */ public function downloadExport() { $session = \Drupal::request()->getSession(); if (isset($session)) { $archive_name = $session->get('features_download'); $request = new Request(array('file' => $archive_name)); return $this->fileDownloadController->download($request, 'temporary'); } }
/** * {@inheritdoc} */ public function form(array $form, FormStateInterface $form_state) { // Try to restore from temp store, this must be done before calling // parent::form(). $uuid = $this->entity->uuid(); $store = $this->tempStoreFactory->get('node_preview'); // If the user is creating a new node, the UUID is passed in the request. if ($request_uuid = \Drupal::request()->query->get('uuid')) { $uuid = $request_uuid; } if ($preview = $store->get($uuid)) { /** @var $preview \Drupal\Core\Form\FormStateInterface */ $form_state = $preview; // Rebuild the form. $form_state->setRebuild(); $this->entity = $preview->getFormObject()->getEntity(); unset($this->entity->in_preview); } /** @var \Drupal\node\NodeInterface $node */ $node = $this->entity; if ($this->operation == 'edit') { $form['#title'] = $this->t('<em>Edit @type</em> @title', array('@type' => node_get_type_label($node), '@title' => $node->label())); } $current_user = $this->currentUser(); // Override the default CSS class name, since the user-defined node type // name in 'TYPE-node-form' potentially clashes with third-party class // names. $form['#attributes']['class'][0] = Html::getClass('node-' . $node->getType() . '-form'); // Changed must be sent to the client, for later overwrite error checking. $form['changed'] = array('#type' => 'hidden', '#default_value' => $node->getChangedTime()); $language_configuration = \Drupal::moduleHandler()->invoke('language', 'get_default_configuration', array('node', $node->getType())); $form['langcode'] = array('#title' => t('Language'), '#type' => 'language_select', '#default_value' => $node->getUntranslated()->language()->getId(), '#languages' => LanguageInterface::STATE_ALL, '#access' => isset($language_configuration['language_show']) && $language_configuration['language_show']); $form['advanced'] = array('#type' => 'vertical_tabs', '#attributes' => array('class' => array('entity-meta')), '#weight' => 99); $form = parent::form($form, $form_state); // Add a revision_log field if the "Create new revision" option is checked, // or if the current user has the ability to check that option. $form['revision_information'] = array('#type' => 'details', '#group' => 'advanced', '#title' => t('Revision information'), '#open' => $node->isNewRevision(), '#attributes' => array('class' => array('node-form-revision-information')), '#attached' => array('library' => array('node/drupal.node')), '#weight' => 20, '#optional' => TRUE); $form['revision'] = array('#type' => 'checkbox', '#title' => t('Create new revision'), '#default_value' => $node->type->entity->isNewRevision(), '#access' => $current_user->hasPermission('administer nodes'), '#group' => 'revision_information'); $form['revision_log'] += array('#states' => array('visible' => array(':input[name="revision"]' => array('checked' => TRUE))), '#group' => 'revision_information'); // Node author information for administrators. $form['author'] = array('#type' => 'details', '#title' => t('Authoring information'), '#group' => 'advanced', '#attributes' => array('class' => array('node-form-author')), '#attached' => array('library' => array('node/drupal.node')), '#weight' => 90, '#optional' => TRUE); if (isset($form['uid'])) { $form['uid']['#group'] = 'author'; } if (isset($form['created'])) { $form['created']['#group'] = 'author'; } // Node options for administrators. $form['options'] = array('#type' => 'details', '#title' => t('Promotion options'), '#group' => 'advanced', '#attributes' => array('class' => array('node-form-options')), '#attached' => array('library' => array('node/drupal.node')), '#weight' => 95, '#optional' => TRUE); if (isset($form['promote'])) { $form['promote']['#group'] = 'options'; } if (isset($form['sticky'])) { $form['sticky']['#group'] = 'options'; } return $form; }
/** * {@inheritdoc} */ public function getQuestion() { $person = \Drupal::request()->get('person'); if (!empty($person)) { return $this->t('Are you sure you want to delete @nickname @firstname @lastnames?', array('@nickname' => $person->nickname, '@firstname' => $person->firstname, '@lastnames' => $person->lastnames)); } else { return $this->t('Person not found'); } }
/** * Tests that the status page shows the trusted patterns from settings.php. */ public function testStatusPageWithConfiguration() { $settings['settings']['trusted_host_patterns'] = (object) array('value' => array('^' . preg_quote(\Drupal::request()->getHost()) . '$'), 'required' => TRUE); $this->writeSettings($settings); $this->drupalGet('admin/reports/status'); $this->assertResponse(200, 'The status page is reachable.'); $this->assertRaw(t('Trusted Host Settings')); $this->assertRaw(t('The trusted_host_patterns setting is set to allow')); }
public function reload_page() { $request = \Drupal::request(); if ($request->server->get('HTTP_REFERER')) { return $request->server->get('HTTP_REFERER'); } else { return '/'; } }
/** * {@inheritdoc} */ protected function setUp($import_test_views = TRUE) { parent::setUp($import_test_views); $this->installEntitySchema('node'); $this->installEntitySchema('taxonomy_term'); $this->installEntitySchema('user'); // Setup the current time properly. \Drupal::request()->server->set('REQUEST_TIME', time()); }
/** * {@inheritdoc} */ public function getNextParameters($cached_values) { $params = parent::getNextParameters($cached_values); $params['js'] = 'ajax'; // Merge route parameters into the cached values. $attributes = \Drupal::request()->attributes->all()['_raw_variables']->all(); $params = array_merge($attributes, $params); return $params; }
/** * {@inheritdoc} */ public function buildForm(array $form, FormStateInterface $form_state) { $destination = drupal_get_destination(); $search = $this->getRequest()->get('search'); $form['#attributes'] = array('class' => array('search-form')); // The following requires the dblog module. If it's not available, provide a message. if (!\Drupal::moduleHandler()->moduleExists('dblog')) { $form['message'] = ['#type' => 'markup', '#markup' => t('This page requires the Database Logging (dblog) module, which is currently not installed.')]; return $form; } $form['basic'] = array('#type' => 'fieldset', '#title' => t('Filter 404s'), '#attributes' => array('class' => array('container-inline'))); $form['basic']['filter'] = array('#type' => 'textfield', '#title' => '', '#default_value' => $search, '#maxlength' => 128, '#size' => 25); $form['basic']['submit'] = array('#type' => 'submit', '#value' => t('Filter'), '#action' => 'filter'); if ($search) { $form['basic']['reset'] = array('#type' => 'submit', '#value' => t('Reset'), '#action' => 'reset'); } $header = array(array('data' => t('Page'), 'field' => 'message'), array('data' => t('Count'), 'field' => 'count', 'sort' => 'desc'), array('data' => t('Last accessed'), 'field' => 'timestamp'), array('data' => t('Operations'))); $count_query = db_select('watchdog', 'w'); $count_query->addExpression('COUNT(DISTINCT(w.message))'); $count_query->leftJoin('redirect', 'r', 'w.message = r.redirect_source__path'); $count_query->condition('w.type', 'page not found'); $count_query->isNull('r.rid'); $this->filterQuery($count_query, array('w.message'), $search); $query = db_select('watchdog', 'w')->extend('Drupal\\Core\\Database\\Query\\TableSortExtender')->orderByHeader($header)->extend('Drupal\\Core\\Database\\Query\\PagerSelectExtender')->limit(25); $query->fields('w', array('message', 'variables')); $query->addExpression('COUNT(wid)', 'count'); $query->addExpression('MAX(timestamp)', 'timestamp'); $query->leftJoin('redirect', 'r', 'w.message = r.redirect_source__path'); $query->isNull('r.rid'); $query->condition('w.type', 'page not found'); $query->groupBy('w.message'); $query->groupBy('w.variables'); $this->filterQuery($query, array('w.message'), $search); $query->setCountQuery($count_query); $results = $query->execute(); $rows = array(); foreach ($results as $result) { // @todo Detect the language from the url. $url = SafeMarkup::format($result->message, unserialize($result->variables)); $request = Request::create($url, 'GET', [], [], [], \Drupal::request()->server->all()); $path = ltrim($request->getPathInfo(), '/'); $row = array(); $row['source'] = \Drupal::l($url, Url::fromUri('base:' . $path, array('query' => $destination))); $row['count'] = $result->count; $row['timestamp'] = format_date($result->timestamp, 'short'); $operations = array(); if (\Drupal::entityManager()->getAccessControlHandler('redirect')->createAccess()) { $operations['add'] = array('title' => t('Add redirect'), 'url' => Url::fromRoute('redirect.add', [], ['query' => array('source' => $path) + $destination])); } $row['operations'] = array('data' => array('#theme' => 'links', '#links' => $operations, '#attributes' => array('class' => array('links', 'inline', 'nowrap')))); $rows[] = $row; } $form['redirect_404_table'] = array('#theme' => 'table', '#header' => $header, '#rows' => $rows, '#empty' => t('No 404 pages without redirects found.')); $form['redirect_404_pager'] = array('#type' => 'pager'); return $form; }