/** * {@inheritdoc} */ public function validate($items, Constraint $constraint) { if (!isset($items)) { return; } /* @var \Drupal\Core\Field\FieldItemListInterface $items */ $field = $items->getFieldDefinition(); /* @var \Drupal\user\UserInterface $account */ $account = $items->getEntity(); if (!isset($account) || !empty($account->_skipProtectedUserFieldConstraint)) { // Looks like we are validating a field not being part of a user, or the // constraint should be skipped, so do nothing. return; } // Only validate for existing entities and if this is the current user. if (!$account->isNew() && $account->id() == $this->currentUser->id()) { /* @var \Drupal\user\UserInterface $account_unchanged */ $account_unchanged = $this->userStorage->loadUnchanged($account->id()); $changed = FALSE; // Special case for the password, it being empty means that the existing // password should not be changed, ignore empty password fields. $value = $items->value; if ($field->getName() != 'pass' || !empty($value)) { // Compare the values of the field this is being validated on. $changed = $items->getValue() != $account_unchanged->get($field->getName())->getValue(); } if ($changed && !$account->checkExistingPassword($account_unchanged)) { $this->context->addViolation($constraint->message, array('%name' => $field->getLabel())); } } }
/** * Adds in the current user as a context. * * @param \Drupal\page_manager\Event\PageManagerContextEvent $event * The page entity context event. */ public function onPageContext(PageManagerContextEvent $event) { $id = $this->account->id(); $current_user = $this->userStorage->load($id); $context = new Context(new ContextDefinition('entity:user', $this->t('Current user'))); $context->setContextValue($current_user); $event->getPageExecutable()->addContext('current_user', $context); }
/** * Adds in the current user as a context. * * @param \Drupal\page_manager\Event\PageManagerContextEvent $event * The page entity context event. */ public function onPageContext(PageManagerContextEvent $event) { $id = $this->account->id(); $current_user = $this->userStorage->load($id); $context = new Context(new ContextDefinition('entity:user', $this->t('Current user')), $current_user); $cacheability = new CacheableMetadata(); $cacheability->setCacheContexts(['user']); $context->addCacheableDependency($cacheability); $event->getPage()->addContext('current_user', $context); }
/** * Authenticates user on request. * * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event * The request event. * * @see \Drupal\Core\Authentication\AuthenticationProviderInterface::authenticate() */ public function onKernelRequestAuthenticate(GetResponseEvent $event) { if ($event->getRequestType() === HttpKernelInterface::MASTER_REQUEST) { $request = $event->getRequest(); if ($this->authenticationProvider->applies($request)) { $account = $this->authenticationProvider->authenticate($request); if ($account) { $this->accountProxy->setAccount($account); } } } }
/** * {@inheritdoc} */ protected function setUp() { parent::setUp(); $this->keyValue = $this->getMock('Drupal\\Core\\KeyValueStore\\KeyValueStoreExpirableInterface'); $this->lock = $this->getMock('Drupal\\Core\\Lock\\LockBackendInterface'); $this->currentUser = $this->getMock('Drupal\\Core\\Session\\AccountProxyInterface'); $this->currentUser->expects($this->any())->method('id')->willReturn(1); $this->requestStack = new RequestStack(); $this->tempStore = new PrivateTempStore($this->keyValue, $this->lock, $this->currentUser, $this->requestStack, 604800); $this->ownObject = (object) array('data' => 'test_data', 'owner' => $this->currentUser->id(), 'updated' => REQUEST_TIME); // Clone the object but change the owner. $this->otherObject = clone $this->ownObject; $this->otherObject->owner = 2; }
/** * Authenticates user on request. * * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event * The request event. * * @see \Drupal\Core\Authentication\AuthenticationProviderInterface::authenticate() */ public function onKernelRequestAuthenticate(GetResponseEvent $event) { if ($event->getRequestType() === HttpKernelInterface::MASTER_REQUEST) { $request = $event->getRequest(); if ($this->authenticationProvider->applies($request)) { $account = $this->authenticationProvider->authenticate($request); if ($account) { $this->accountProxy->setAccount($account); return; } } // No account has been set explicitly, initialize the timezone here. date_default_timezone_set(drupal_get_user_timezone()); } }
/** * {@inheritdoc} */ public function validate($value, Constraint $constraint) { if (isset($value)) { try { $url = $value->getUrl(); } catch (\InvalidArgumentException $e) { return; } // Disallow URLs if the current user doesn't have the 'link to any page' // permission nor can access this URI. $allowed = $this->current_user->hasPermission('link to any page') || $url->access(); if (!$allowed) { $this->context->addViolation($constraint->message, array('@uri' => $value->uri)); } } }
/** * Builds file manager page. */ public function buildPage() { $page = array(); $page['#attached']['library'][] = 'imce/drupal.imce'; // Add meta for robots. $robots = array('#tag' => 'meta', '#attributes' => array('name' => 'robots', 'content' => 'noindex,nofollow')); $page['#attached']['html_head'][] = array($robots, 'robots'); // Disable cache $page['#cache']['max-age'] = 0; // Run builders of available plugins \Drupal::service('plugin.manager.imce.plugin')->buildPage($page, $this); // Add active path to the conf. $conf = $this->conf; if (!isset($conf['active_path'])) { if ($folder = $this->activeFolder) { $conf['active_path'] = $folder->getPath(); } elseif ($this->user->isAuthenticated() && $this->request && ($path = $this->request->getSession()->get('imce_active_path'))) { if ($this->checkFolder($path)) { $conf['active_path'] = $path; } } } // Set initial messages. if ($messages = $this->getMessages()) { $conf['messages'] = $messages; } $page['#attached']['drupalSettings']['imce'] = $conf; return $page; }
/** * {@inheritdoc} */ public function completeSale($order, $login = FALSE) { // Empty that cart... $this->emptyCart(); // Force the order to load from the DB instead of the entity cache. // @todo Remove this once uc_payment_enter() can modify order objects? // @todo Should we be overwriting $order with this newly-loaded db_order? $db_order = \Drupal::entityTypeManager()->getStorage('uc_order')->loadUnchanged($order->id()); $order->data = $db_order->data; // Ensure that user creation and triggers are only run once. if (empty($order->data->complete_sale)) { $this->completeSaleAccount($order); // Move an order's status from "In checkout" to "Pending". if ($order->getStateId() == 'in_checkout') { $order->setStatusId(uc_order_state_default('post_checkout')); } $order->save(); // Invoke the checkout complete trigger and hook. $account = $order->getOwner(); \Drupal::moduleHandler()->invokeAll('uc_checkout_complete', array($order, $account)); // rules_invoke_event('uc_checkout_complete', $order); } $type = $order->data->complete_sale; // Log in new users, if requested. if ($type == 'new_user' && $login && $this->currentUser->isAnonymous()) { $type = 'new_user_logged_in'; user_login_finalize($order->getOwner()); } $message = \Drupal::config('uc_cart.messages')->get($type); $message = \Drupal::token()->replace($message, array('uc_order' => $order)); $variables['!new_username'] = isset($order->data->new_user_name) ? $order->data->new_user_name : ''; $variables['!new_password'] = isset($order->password) ? $order->password : t('Your password'); $message = strtr($message, $variables); return array('#theme' => 'uc_cart_complete_sale', '#message' => array('#markup' => $message), '#order' => $order); }
/** * {@inheritdoc} */ public function access($storage_type, $id, $op, AccountInterface $account = NULL) { if ($account === NULL) { $account = $this->currentUser->getAccount(); } return $this->getStorage($storage_type)->access($id, $op, $account); }
/** * {@inheritdoc} */ public function run() { // Allow execution to continue even if the request gets cancelled. @ignore_user_abort(TRUE); // Prevent session information from being saved while cron is running. $original_session_saving = $this->sessionManager->isEnabled(); $this->sessionManager->disable(); // Force the current user to anonymous to ensure consistent permissions on // cron runs. $original_user = $this->currentUser->getAccount(); $this->currentUser->setAccount(new AnonymousUserSession()); // Try to allocate enough time to run all the hook_cron implementations. drupal_set_time_limit(240); $return = FALSE; // Try to acquire cron lock. if (!$this->lock->acquire('cron', 900.0)) { // Cron is still running normally. $this->logger->warning('Attempting to re-run cron while it is already running.'); } else { $this->invokeCronHandlers(); $this->setCronLastTime(); // Release cron lock. $this->lock->release('cron'); // Return TRUE so other functions can check if it did run successfully $return = TRUE; } // Process cron queues. $this->processQueues(); // Restore the user. $this->currentUser->setAccount($original_user); if ($original_session_saving) { $this->sessionManager->enable(); } return $return; }
/** * Test the buildCommentedEntityLinks method. * * @param \Drupal\node\NodeInterface|\PHPUnit_Framework_MockObject_MockObject $node * Mock node. * @param array $context * Context for the links. * @param bool $has_access_comments * TRUE if the user has 'access comments' permission. * @param bool $history_exists * TRUE if the history module exists. * @param bool $has_post_comments * TRUE if the use has 'post comments' permission. * @param bool $is_anonymous * TRUE if the user is anonymous. * @param array $expected * Array of expected links keyed by link ID. Can be either string (link * title) or array of link properties. * * @dataProvider getLinkCombinations * * @covers ::buildCommentedEntityLinks */ public function testCommentLinkBuilder(NodeInterface $node, $context, $has_access_comments, $history_exists, $has_post_comments, $is_anonymous, $expected) { $this->moduleHandler->expects($this->any())->method('moduleExists')->with('history')->willReturn($history_exists); $this->currentUser->expects($this->any())->method('hasPermission')->willReturnMap(array(array('access comments', $has_access_comments), array('post comments', $has_post_comments))); $this->currentUser->expects($this->any())->method('isAuthenticated')->willReturn(!$is_anonymous); $this->currentUser->expects($this->any())->method('isAnonymous')->willReturn($is_anonymous); $links = $this->commentLinkBuilder->buildCommentedEntityLinks($node, $context); if (!empty($expected)) { if (!empty($links)) { foreach ($expected as $link => $detail) { if (is_array($detail)) { // Array of link attributes. foreach ($detail as $key => $value) { $this->assertEquals($value, $links['comment__comment']['#links'][$link][$key]); } } else { // Just the title. $this->assertEquals($detail, $links['comment__comment']['#links'][$link]['title']); } } } else { $this->fail('Expected links but found none.'); } } else { $this->assertSame($links, $expected); } }
/** * {@inheritdoc} */ public function switchBack() { // Restore the previous account from the stack. if (!empty($this->accountStack)) { $this->currentUser->setAccount(array_pop($this->accountStack)); } else { throw new \RuntimeException('No more accounts to revert to.'); } // Restore original session saving status if all account switches are // reverted. if (empty($this->accountStack)) { if ($this->originalSessionSaving) { $this->writeSafeHandler->setSessionWritable(TRUE); } } return $this; }
/** * {@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 = $this->cacheBackend->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. $this->cacheBackend->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>' . $this->t('This example will search the entire drupal folder and display a count of the files in it.') . ' '; $intro_message .= $this->t('This can take a while, since there are a lot of files to be searched.') . ' '; $intro_message .= $this->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>' . $this->t('<a href="@url">Reload this page</a> to see cache in action.', array('@url' => $this->getRequest()->getRequestUri())) . ' '; $intro_message .= $this->t('You can use the button below to remove cached data.') . '</p>'; $form['file_search'] = array('#type' => 'fieldset', '#title' => $this->t('File search caching')); $form['file_search']['introduction'] = array('#markup' => $intro_message); $color = empty($cache) ? 'red' : 'green'; $retrieval = empty($cache) ? $this->t('calculated by traversing the filesystem') : $this->t('retrieved from cache'); $form['file_search']['statistics'] = array('#type' => 'item', '#markup' => $this->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) ? $this->t('actual file search') : $this->t('cached')))); $form['file_search']['remove_file_count'] = array('#type' => 'submit', '#submit' => array(array($this, 'expireFiles')), '#value' => $this->t('Explicitly remove cached file count')); $form['expiration_demo'] = array('#type' => 'fieldset', '#title' => $this->t('Cache expiration settings')); $form['expiration_demo']['explanation'] = array('#markup' => $this->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 = $this->cacheBackend->get('cache_example_expiring_item', TRUE); if ($item == FALSE) { $item_status = $this->t('Cache item does not exist'); } else { $item_status = $item->valid ? $this->t('Cache item exists and is set to expire at %time', array('%time' => $item->data)) : $this->t('Cache_item is invalid'); } $form['expiration_demo']['current_status'] = array('#type' => 'item', '#title' => $this->t('Current status of cache item "cache_example_expiring_item"'), '#markup' => $item_status); $form['expiration_demo']['expiration'] = array('#type' => 'select', '#title' => $this->t('Time before cache expiration'), '#options' => array('never_remove' => $this->t('CACHE_PERMANENT'), -10 => $this->t('Immediate expiration'), 10 => $this->t('10 seconds from form submission'), 60 => $this->t('1 minute from form submission'), 300 => $this->t('5 minutes from form submission')), '#default_value' => -10, '#description' => $this->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' => $this->t('Create a cache item with this expiration'), '#submit' => array(array($this, 'createExpiringItem'))); $form['cache_clearing'] = array('#type' => 'fieldset', '#title' => $this->t('Expire and remove options'), '#description' => $this->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' => $this->t('Type of cache clearing to do'), '#options' => array('expire' => $this->t('Remove items from the "cache" bin that have expired'), 'remove_all' => $this->t('Remove all items from the "cache" bin regardless of expiration'), 'remove_tag' => $this->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' => $this->t('Clear or expire cache'), '#submit' => array(array($this, 'cacheClearing')), '#access' => $this->currentUser->hasPermission('administer site configuration')); return $form; }
public function get($entity = NULL) { if ($entity) { $permission = 'Administer content types'; if (!$this->currentUser->hasPermission($permission)) { throw new AccessDeniedHttpException(); } $bundles_entities = \Drupal::entityManager()->getStorage($entity . '_type')->loadMultiple(); $bundles = array(); foreach ($bundles_entities as $entity) { $bundles[$entity->id()] = $entity->label(); } if (!empty($bundles)) { return new ResourceResponse($bundles); } throw new NotFoundHttpException(t('Bundles for entity @entity were not found', array('@entity' => $entity))); } throw new HttpException(t('Entity wasn\'t provided')); }
/** * {@inheritdoc} */ public function enhance(array $defaults, Request $request) { $auth_provider_triggered = $request->attributes->get('_authentication_provider'); if (!empty($auth_provider_triggered)) { $route = isset($defaults[RouteObjectInterface::ROUTE_OBJECT]) ? $defaults[RouteObjectInterface::ROUTE_OBJECT] : NULL; $auth_providers = $route && $route->getOption('_auth') ? $route->getOption('_auth') : array($this->manager->defaultProviderId()); // If the request was authenticated with a non-permitted provider, // force the user back to anonymous. if (!in_array($auth_provider_triggered, $auth_providers)) { $anonymous_user = new AnonymousUserSession(); $this->currentUser->setAccount($anonymous_user); // The global $user object is included for backward compatibility only // and should be considered deprecated. // @todo Remove this line once global $user is no longer used. $GLOBALS['user'] = $anonymous_user; } } return $defaults; }
/** * The controller for the meteor.whoami route. * * @return \Symfony\Component\HttpFoundation\Response * A JSON response. */ public function whoami() { $account = $this->accountProxy->getAccount(); $uid = $account->id(); $name = $account->getAccountName(); $display_name = $account->getDisplayName(); $roles = $this->accountProxy->getRoles(); $result = $this->serializer->serialize(['uid' => $uid, 'name' => $name, 'displayName' => $display_name, 'roles' => $roles], 'json'); $response = new Response($result, Response::HTTP_OK); $response->headers->set('Content-type', 'application/json'); return $response; }
/** * {@inheritdoc} */ public function preprocessIndexItems(array &$items) { // Change the current user to our dummy implementation to ensure we are // using the configured roles. $original_user = $this->currentUser->getAccount(); // @todo Why not just use \Drupal\Core\Session\UserSession directly here? $this->currentUser->setAccount(new UserSession(array('roles' => $this->configuration['roles']))); // Count of items that don't have a view mode. $unset_view_modes = 0; // Annoyingly, this doc comment is needed for PHPStorm. See // http://youtrack.jetbrains.com/issue/WI-23586 /** @var \Drupal\search_api\Item\ItemInterface $item */ foreach ($items as $item) { if (!($field = $item->getField('rendered_item'))) { continue; } $datasource_id = $item->getDatasourceId(); $datasource = $item->getDatasource(); $bundle = $datasource->getItemBundle($item->getOriginalObject()); if (empty($this->configuration['view_mode'][$datasource_id][$bundle])) { if (!isset($this->configuration['view_mode'][$datasource_id][$bundle])) { ++$unset_view_modes; } continue; } else { $view_mode = (string) $this->configuration['view_mode'][$datasource_id][$bundle]; } $build = $datasource->viewItem($item->getOriginalObject(), $view_mode); $value = (string) $this->getRenderer()->renderPlain($build); if ($value) { $field->addValue($value); } } if ($unset_view_modes > 0) { $context = array( '%index' => $this->index->label(), '%processor' => $this->label(), '@count' => $unset_view_modes, ); $this->getLogger()->warning('Warning: While indexing items on search index %index, @count item(s) did not have a view mode configured for the %processor processor.', $context); } // Restore the original user. $this->currentUser->setAccount($original_user); }
/** * Responds to GET requests. * * Returns a list of bundles for specified entity. * * @return \Drupal\rest\ResourceResponse * The response containing a reponse HTML. * * @throws \Symfony\Component\HttpKernel\Exception\HttpException */ public function get($entity = NULL, $bundle = NULL) { if ($entity && $bundle) { $permission = 'Administer content types'; if (!$this->currentUser->hasPermission($permission)) { throw new AccessDeniedHttpException(); } // Query by filtering on the ID by entity and bundle. $ids = \Drupal::entityQuery('field_config')->condition('id', $entity . '.' . $bundle . '.', 'STARTS_WITH')->execute(); // Fetch all fields and key them by field name. $field_configs = FieldConfig::loadMultiple($ids); $fields = array(); foreach ($field_configs as $field_instance) { $fields[$field_instance->getName()] = $field_instance; } if (!empty($fields)) { return new ResourceResponse($fields); } throw new NotFoundHttpException(t('Field for entity @entity and bundle @bundle were not found', array('@entity' => $entity, '@bundle' => $bundle))); } // Throw an exception if it is required. throw new HttpException(t('Entity and Bundle weren\'t provided')); }
public function get($entity = NULL, $bundle = NULL) { if ($entity && $bundle) { $permission = 'Administer content types'; if (!$this->currentUser->hasPermission($permission)) { throw new AccessDeniedHttpException(); } $entity_view_display = $this->entityManager->getDefinition('entity_view_display'); $config_prefix = $entity_view_display->getConfigPrefix(); $list = $this->configFactory->listAll($config_prefix . '.' . $entity . '.' . $bundle . '.'); $view_modes = array(); foreach ($list as $view_mode) { $view_mode_machine_id = str_replace($config_prefix . '.', '', $view_mode); list(, , $view_mode_label) = explode('.', $view_mode_machine_id); $view_modes[$view_mode_machine_id] = $view_mode_label; } if (!empty($view_modes)) { return new ResourceResponse($view_modes); } throw new NotFoundHttpException(t('Views modes for @entity and @bundle were not found', array('@entity' => $entity, '@bundle' => $bundle))); } throw new HttpException(t('Entity or Bundle weren\'t provided')); }
/** * {@inheritdoc} */ public function process($text, $langcode) { $response = new FilterProcessResult($text); // Use a look ahead to match the capture groups in any order. if (preg_match_all('/(<p>)?(?<json>{(?=.*preview_thumbnail\\b)(?=.*settings\\b)(?=.*video_url\\b)(?=.*settings_summary)(.*)})(<\\/p>)?/', $text, $matches)) { foreach ($matches['json'] as $delta => $match) { // Ensure the JSON string is valid. $embed_data = json_decode($match, TRUE); if (!is_array($embed_data)) { continue; } // If the URL can't matched to a provider or the settings are invalid, // ignore it. $provider = $this->providerManager->loadProviderFromInput($embed_data['video_url']); if (!$provider || !$this->validSettings($embed_data['settings'])) { continue; } $autoplay = $this->currentUser->hasPermission('never autoplay videos') ? FALSE : $embed_data['settings']['autoplay']; $embed_code = $provider->renderEmbedCode($embed_data['settings']['width'], $embed_data['settings']['height'], $autoplay); // Add the container to make the video responsive if it's been // configured as such. This usually is attached to field output in the // case of a formatter, but a custom container must be used where one is // not present. if ($embed_data['settings']['responsive']) { $embed_code = ['#type' => 'container', '#attributes' => ['class' => ['video-embed-field-responsive-video']], 'children' => $embed_code]; } // Replace the JSON settings with a video. $text = str_replace($matches[0][$delta], $this->renderer->renderRoot($embed_code), $text); } } // Add the required responsive video library and update the response text. $response->setProcessedText($text); $response->addAttachments(['library' => ['video_embed_field/responsive-video']]); $response->setCacheContexts(['user.permissions']); return $response; }
/** * Responds to node status PATCH requests and updates node status. * * @param string $id * Node id. * * @return \Drupal\rest\ResourceResponse * The HTTP response object. * * @throws \Symfony\Component\HttpKernel\Exception\HttpException * Throws exception expected. */ public function patch($id = NULL) { if (!$this->currentUser->hasPermission('restful patch node_status_resource')) { throw new AccessDeniedHttpException('Access denied'); } // Check whether parameters are passed. if (empty($id)) { throw new HttpException('Parameters not passed'); } $node = Node::load($id); // Check whether valid node is present for the given parameter. if (!$node) { throw new HttpException('Node not present for this parameter'); } return new ResourceResponse("Implement REST State POST!"); }
/** * Switches to a different user. * * We don't call session_save_session() because we really want to change users. * Usually unsafe! * * @param string $name * The username to switch to, or NULL to log out. * * @return \Symfony\Component\HttpFoundation\RedirectResponse * A redirect response object. * * @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException */ public function switchUser($name = NULL) { if (empty($name) || !($account = $this->userStorage->loadByProperties(['name' => $name]))) { throw new AccessDeniedHttpException(); } $account = reset($account); // Call logout hooks when switching from original user. $this->moduleHandler->invokeAll('user_logout', [$this->account]); // Regenerate the session ID to prevent against session fixation attacks. $this->sessionManager->regenerate(); // Based off masquarade module as: // https://www.drupal.org/node/218104 doesn't stick and instead only // keeps context until redirect. $this->account->setAccount($account); $this->session->set('uid', $account->id()); // Call all login hooks when switching to masquerading user. $this->moduleHandler->invokeAll('user_login', [$account]); return $this->redirect('<front>'); }
/** * Processes raw profile configuration of a user. */ public static function processUserConf(array $conf, AccountProxyInterface $user) { // Convert MB to bytes $conf['maxsize'] *= 1048576; $conf['quota'] *= 1048576; // Set root uri and url $conf['root_uri'] = $conf['scheme'] . '://'; // file_create_url requires a filepath for some schemes like private:// $conf['root_url'] = preg_replace('@/(?:%2E|\\.)$@i', '', file_create_url($conf['root_uri'] . '.')); // Convert to relative if (!\Drupal::config('imce.settings')->get('abs_urls')) { $conf['root_url'] = file_url_transform_relative($conf['root_url']); } $conf['token'] = $user->isAnonymous() ? 'anon' : \Drupal::csrfToken()->get('imce'); // Process folders $conf['folders'] = static::processUserFolders($conf['folders'], $user); // Call plugin processors \Drupal::service('plugin.manager.imce.plugin')->processUserConf($conf, $user); return $conf; }
/** * {@inheritdoc} */ public function preprocessIndexItems(array &$items) { // Change the current user to our dummy implementation to ensure we are // using the configured roles. $original_user = $this->currentUser->getAccount(); // @todo Why not just use \Drupal\Core\Session\UserSession directly here? $this->currentUser->setAccount(new UserSession(array('roles' => $this->configuration['roles']))); // Annoyingly, this doc comment is needed for PHPStorm. See // http://youtrack.jetbrains.com/issue/WI-23586 /** @var \Drupal\search_api\Item\ItemInterface $item */ foreach ($items as $item) { if (empty($this->configuration['view_mode'][$item->getDatasourceId()])) { continue; } if (!($field = $item->getField('rendered_item'))) { continue; } $build = $item->getDatasource()->viewItem($item->getOriginalObject(), $this->configuration['view_mode'][$item->getDatasourceId()]); $field->addValue($this->getRenderer()->renderPlain($build)); } // Restore the original user. $this->currentUser->setAccount($original_user); }
/** * Switching back to previous user. * * @return bool * TRUE when switched back, FALSE otherwise. */ public function switchBack() { if (empty($_SESSION['masquerading'])) { return FALSE; } $new_user = $this->entityTypeManager->getStorage('user')->load($_SESSION['masquerading']); // Ensure the flag is cleared. unset($_SESSION['masquerading']); if (!$new_user) { return FALSE; } $account = $this->currentUser; // Call logout hooks when switching from masquerading user. $this->moduleHandler->invokeAll('user_logout', [$account]); // Regenerate the session ID to prevent against session fixation attacks. // @todo Maybe session service migrate. $this->sessionManager->regenerate(); $this->currentUser->setAccount($new_user); \Drupal::service('session')->set('uid', $new_user->id()); // Call all login hooks when switching back to original user. $this->moduleHandler->invokeAll('user_login', [$new_user]); $this->logger->info('User %username stopped masquerading as %old_username.', array('%username' => $new_user->getDisplayName(), '%old_username' => $account->getDisplayName(), 'link' => $this->l($this->t('view'), $new_user->toUrl()))); return TRUE; }
/** * Checks whether a user has access to devel information. * * @return bool * TRUE if the user has the permission, FALSE otherwise. */ protected function hasAccessToDevelInformation() { return $this->account && $this->account->hasPermission('access devel information'); }
/** * Gets the current owner based on the current user or the session ID. * * @return string * The owner. */ protected function getOwner() { return $this->currentUser->id() ?: $this->requestStack->getCurrentRequest()->getSession()->getId(); }
/** * {@inheritdoc} */ public function fileEntityFromUri($uri, AccountProxyInterface $user) { $uri = file_stream_wrapper_uri_normalize($uri); $file_info = new \SplFileInfo($uri); // Begin building file entity. $values = ['uid' => $user->id(), 'status' => 0, 'filename' => $file_info->getFilename(), 'uri' => $uri, 'filesize' => $file_info->getSize(), 'filemime' => $this->mimeTypeGuesser->guess($uri)]; /** @var \Drupal\file\FileInterface $file */ $file = $this->entityManager->getStorage('file')->create($values); return $file; }