public function content() { $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id()); $userId = $user->get('uid')->value; $data = array(array('job_title' => '', 'job_path' => '', 'company_name' => '', 'application_date' => '')); $appliedJobs = db_select('user_job_application', 'uja')->condition('uja.user_id', $userId, '=')->fields('uja', array('job_id', 'date'))->orderBy('uja.date', 'DESC')->execute()->fetchAll(); if ($appliedJobs) { $x = 0; foreach ($appliedJobs as $appliedJob) { $jobNode = \Drupal\node\Entity\Node::load($appliedJob->job_id); $jobTitle = $jobNode->getTitle(); $jobPathAlias = \Drupal::service('path.alias_manager')->getAliasByPath('/node/' . $appliedJob->job_id); $companyNodeEntity = $jobNode->get('field_company'); $companyNode = \Drupal\node\Entity\Node::load($companyNodeEntity->entity->id()); $companyName = $companyNode->getTitle(); $data[$x]['job_title'] = $jobTitle; $data[$x]['job_path'] = $jobPathAlias; $data[$x]['company_name'] = $companyName; $data[$x]['application_date'] = $appliedJob->date; $x++; } } $markUp = $this->createMarkUp($data); return array('#type' => 'markup', '#markup' => $markUp); }
/** * Checks configuration permission. * * @param AccountInterface $account * (optional) The user for which to check access, or NULL to check access * for the current user. Defaults to NULL. * @param bool $return_as_object * (optional) Defaults to FALSE. * * @return bool|\Drupal\Core\Access\AccessResultInterface * The access result. Returns a boolean if $return_as_object is FALSE (this * is the default) and otherwise an AccessResultInterface object. * When a boolean is returned, the result of AccessInterface::isAllowed() is * returned, i.e. TRUE means access is explicitly allowed, FALSE means * access is either explicitly forbidden or "no opinion". */ public function checkConfigurationAccess(AccountInterface $account = NULL, $return_as_object = FALSE) { if (!$account) { $account = \Drupal::currentUser(); } // We treat these as our "super-user" accesses. We let the reaction // rule and component permissions control the main admin UI. $admin_perms = ['administer rules', 'bypass rules access']; $access = FALSE; foreach ($admin_perms as $perm) { if ($account->hasPermission($perm)) { $access = TRUE; break; } } if (!$access) { // See if the plugin has a configuration_access annotation. $definition = $this->getPluginDefinition(); if (!empty($definition['configure_permissions']) && is_array($definition['configure_permissions'])) { foreach ($definition['configure_permissions'] as $perm) { if ($account->hasPermission($perm)) { $access = TRUE; break; } } } } if ($return_as_object) { return $access ? AccessResult::allowed() : AccessResult::neutral(); } return $access; }
/** * 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'); } } }
/** * Constructs the file manager. * * @param array $conf * File manager configuration * @param \Drupal\Core\Session\AccountProxyInterface $user * The active user * @param \Symfony\Component\HttpFoundation\Request $request * The active request that contains parameters for file manager operations */ public function __construct(array $conf, AccountProxyInterface $user = NULL, Request $request = NULL) { $this->conf = $conf; $this->user = $user ?: \Drupal::currentUser(); $this->request = $request; $this->init(); }
/** * {@inheritdoc} */ public function submitForm(OrderInterface $order, array &$form, FormStateInterface $form_state) { if (!$form_state->isValueEmpty('admin_comment')) { $uid = \Drupal::currentUser()->id(); uc_order_comment_save($form_state->getValue('order_id'), $uid, $form_state->getValue('admin_comment')); } }
/** * {@inheritdoc} */ public function submitForm(array &$form, FormStateInterface $form_state) { //TODO v2 Send Email via Cron not on Submit $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id()); $username = $user->get('name')->value; $userId = $user->get('uid')->value; $mailManager = \Drupal::service('plugin.manager.mail'); $jobNode = \Drupal::routeMatch()->getParameter('node'); $jobNodeTitle = $jobNode->getTitle(); $companyNodeEntity = $jobNode->get('field_company'); $companyNode = \Drupal\node\Entity\Node::load($companyNodeEntity->entity->id()); $companyEmail = $companyNode->field_email->value; $resumeFileId = $form_state->getValue('resume'); $resumeFile = db_select('file_managed', 'f')->condition('f.fid', $resumeFileId, '=')->fields('f', array('uri'))->execute()->fetchField(); $atttachment = array('filepath' => $resumeFile); $module = 'job_mailer'; $key = 'apply_job'; $params['job_title'] = $jobNodeTitle; $params['message'] = "<html>\n <p>Please see attached resume for user: {$username}\n </html>"; $params['attachment'] = $atttachment; $langcode = \Drupal::currentUser()->getPreferredLangcode(); $send = true; $reply = \Drupal::config('system.site')->get('mail'); $result = $mailManager->mail($module, $key, $companyEmail, $langcode, $params, $reply, $send); db_insert('user_job_application')->fields(array('job_id' => $jobNode->id(), 'user_id' => $userId, 'date' => date('Y-m-d H:i:s')))->execute(); drupal_set_message('Your application has been sent.'); }
/** * {@inheritdoc} */ public function view(OrderInterface $order, $view_mode) { $build = array('#type' => 'table', '#attributes' => array('class' => array('order-pane-table')), '#header' => array('qty' => array('data' => $this->t('Quantity'), 'class' => array('qty')), 'product' => array('data' => $this->t('Product'), 'class' => array('product')), 'model' => array('data' => $this->t('SKU'), 'class' => array('sku', RESPONSIVE_PRIORITY_LOW)), 'cost' => array('data' => $this->t('Cost'), 'class' => array('cost', RESPONSIVE_PRIORITY_LOW)), 'price' => array('data' => $this->t('Price'), 'class' => array('price')), 'total' => array('data' => $this->t('Total'), 'class' => array('price'))), '#empty' => $this->t('This order contains no products.')); $account = \Drupal::currentUser(); if (!$account->hasPermission('administer products')) { unset($build['#header']['cost']); } // @todo Replace with Views. foreach ($order->products as $id => $product) { $build[$id]['qty'] = array('#theme' => 'uc_qty', '#qty' => $product->qty->value, '#cell_attributes' => array('class' => array('qty'))); if ($product->nid->entity && $product->nid->entity->access('view')) { $title = Link::createFromRoute($product->title->value, 'entity.node.canonical', ['node' => $product->nid->target_id])->toString(); } else { $title = $product->title->value; } $build[$id]['product'] = array('#markup' => $title . uc_product_get_description($product), '#cell_attributes' => array('class' => array('product'))); $build[$id]['model'] = array('#markup' => $product->model->value, '#cell_attributes' => array('class' => array('sku'))); if ($account->hasPermission('administer products')) { $build[$id]['cost'] = array('#theme' => 'uc_price', '#price' => $product->cost->value, '#cell_attributes' => array('class' => array('cost'))); } $build[$id]['price'] = array('#theme' => 'uc_price', '#price' => $product->price->value, '#suffixes' => array(), '#cell_attributes' => array('class' => array('price'))); $build[$id]['total'] = array('#theme' => 'uc_price', '#price' => $product->price->value * $product->qty->value, '#suffixes' => array(), '#cell_attributes' => array('class' => array('total'))); // $build[$id][$field]['#wrapper_attributes']['class'] = $build['#header'][$field]['class']; } return $build; }
public static function attach_file($uri) { $user = \Drupal::currentUser(); $file = entity_create('file', array('uri' => $uri, 'uid' => $user->id(), 'status' => FILE_STATUS_PERMANENT)); $file->save(); return $file; }
/** * {@inheritdoc} */ protected function setUp() { parent::setUp(); $this->drupalPlaceBlock('local_tasks_block'); $this->drupalPlaceBlock('local_actions_block'); $this->drupalPlaceBlock('page_title_block'); $this->adminUser = $this->drupalCreateUser([ 'administer products', 'administer product types', 'administer commerce_product fields', 'access administration pages', 'administer commerce_product_variation fields' ]); $this->drupalLogin($this->adminUser); $storeType = $this->createEntity('commerce_store_type', [ 'id' => strtolower($this->randomMachineName(8)), 'label' => $this->randomMachineName(8), ]); $this->stores = []; for ($i = 0; $i < 3; $i++) { $this->stores[] = $this->createEntity('commerce_store', [ 'type' => $storeType->id(), 'name' => $this->randomMachineName(8), 'mail' => \Drupal::currentUser()->getEmail(), 'default_currency' => 'EUR', ]); } }
/** * {@inheritdoc} */ protected function chargeCard($order, $amount, $txn_type, $reference = NULL) { $user = \Drupal::currentUser(); // cc_exp_month and cc_exp_year are also validated by // _uc_credit_valid_card_expiration() on the checkout form. $month = $order->payment_details['cc_exp_month']; $year = $order->payment_details['cc_exp_year']; if ($year < 100) { $year = $year + 2000; } // Card is expired at 0:00 on the first day of the next month. $expiration_date = mktime(0, 0, 0, $month + 1, 1, $year); // Conditions for failure are described in file documentation block above. // All other transactions will succeed. if ($order->payment_details['cc_number'] == '0000000000000000' || isset($order->payment_details['cc_cvv']) && $order->payment_details['cc_cvv'] == '000' || $expiration_date - REQUEST_TIME <= 0 || $amount == 12.34 || $order->billing_first_name == 'Fictitious' || $order->billing_phone == '8675309') { $success = FALSE; } else { $success = TRUE; } // The information for the payment is in the $order->payment_details array. if ($this->configuration['debug']) { \Drupal::logger('uc_credit')->notice('Test gateway payment details @details.', ['@details' => print_r($order->payment_details, TRUE)]); } if ($success) { $message = $this->t('Credit card charged: @amount', ['@amount' => uc_currency_format($amount)]); uc_order_comment_save($order->id(), $user->id(), $message, 'admin'); } else { $message = $this->t('Credit card charge failed.'); uc_order_comment_save($order->id(), $user->id(), $message, 'admin'); } $result = array('success' => $success, 'comment' => $this->t('Card charged, resolution code: 0022548315'), 'message' => $success ? $this->t('Credit card payment processed successfully.') : $this->t('Credit card charge failed.'), 'uid' => $user->id()); return $result; }
/** * {@inheritdoc} */ public function allowed(WorkflowTransition $transition, WorkflowInterface $workflow, EntityInterface $entity) { $to_state = $transition->getToState()->getId(); // Disable virtual state. if ($to_state == self::NON_STATE) { return FALSE; } $from_state = $this->getState($entity); // Allowed transitions are already filtered so we only need to check // for the transitions defined in the settings if they include a role the // user has. // @see: solution.settings.yml $allowed_conditions = \Drupal::config('solution.settings')->get('transitions'); if (\Drupal::currentUser()->hasPermission('bypass node access')) { return TRUE; } // Check if the user has one of the allowed system roles. $authorized_roles = isset($allowed_conditions[$to_state][$from_state]) ? $allowed_conditions[$to_state][$from_state] : []; $user = $this->workflowUserProvider->getUser(); if (array_intersect($authorized_roles, $user->getRoles())) { return TRUE; } // Check if the user has one of the allowed group roles. $membership = Og::getMembership($entity, $user); return $membership && array_intersect($authorized_roles, $membership->getRolesIds()); }
/** * Overrides Drupal\Core\Entity\EntityForm::form(). */ public function form(array $form, array &$form_state) { $user = $this->currentUser(); /** @var \Drupal\user\UserInterface $account */ $account = $this->entity; $admin = $user->hasPermission('administer users'); // Pass access information to the submit handler. Running an access check // inside the submit function interferes with form processing and breaks // hook_form_alter(). $form['administer_users'] = array('#type' => 'value', '#value' => $admin); // If we aren't admin but already logged on, go to the user page instead. if (!$admin && $user->isAuthenticated()) { return new RedirectResponse(url('user/' . \Drupal::currentUser()->id(), array('absolute' => TRUE))); } $form['#attached']['library'][] = 'core/jquery.cookie'; $form['#attributes']['class'][] = 'user-info-from-cookie'; // Because the user status has security implications, users are blocked by // default when created programmatically and need to be actively activated // if needed. When administrators create users from the user interface, // however, we assume that they should be created as activated by default. if ($admin) { $account->activate(); } // Start with the default user account fields. $form = parent::form($form, $form_state, $account); if ($admin) { // Redirect back to page which initiated the create request; usually // admin/people/create. $form_state['redirect'] = current_path(); } return $form; }
/** * Create new registration via UI. * * Enable registrations for an event and submit new registration form. */ function testRegistration() { // Event $base_url = 'node/1'; $this->drupalGet($base_url . ''); $this->assertResponse(200); $this->drupalGet($base_url . '/event'); $this->assertResponse(200); $this->assertNoLinkByHref($base_url . '/register'); $this->drupalGet($base_url . '/register'); $this->assertResponse(403); // Settings $edit = ['rng_status[value]' => TRUE, 'rng_registration_type[' . $this->registration_type->id() . ']' => TRUE, 'rng_capacity[0][unlimited_number][unlimited_number]' => 'limited', 'rng_capacity[0][unlimited_number][number]' => '1']; $this->drupalPostForm($base_url . '/event', $edit, t('Save')); $this->assertRaw(t('Event settings updated.')); // Register tab appears. $this->assertLinkByHref($base_url . '/register'); // Registration form. $this->drupalGet($base_url . '/register'); $this->assertResponse(200); $this->assertRaw(t('My account: %username', ['%username' => \Drupal::currentUser()->getAccountName()])); $edit = ['identity' => 'user:'******'/register', $edit, t('Save')); $this->assertRaw(t('Registration has been created.')); }
/** * {@inheritdoc} */ protected function actions(array $form, FormStateInterface $form_state) { $actions = parent::actions($form, $form_state); $actions['submit']['#value'] = $this->t('Save task'); $actions['submit']['#access'] = \Drupal::currentUser()->hasPermission('administer tmgmt') || \Drupal::currentUser()->hasPermission('administer translation tasks'); return $actions; }
/** * Tests the handlers. */ public function testHandlers() { $nodes = array(); $nodes[] = $this->drupalCreateNode(); $nodes[] = $this->drupalCreateNode(); $account = $this->drupalCreateUser(); $this->drupalLogin($account); \Drupal::currentUser()->setAccount($account); db_insert('history')->fields(array('uid' => $account->id(), 'nid' => $nodes[0]->id(), 'timestamp' => REQUEST_TIME - 100))->execute(); db_insert('history')->fields(array('uid' => $account->id(), 'nid' => $nodes[1]->id(), 'timestamp' => REQUEST_TIME + 100))->execute(); $column_map = array('nid' => 'nid'); // Test the history field. $view = Views::getView('test_history'); $view->setDisplay('page_1'); $this->executeView($view); $this->assertEqual(count($view->result), 2); $output = $view->preview(); $this->setRawContent(\Drupal::service('renderer')->renderRoot($output)); $result = $this->xpath('//span[@class=:class]', array(':class' => 'marker')); $this->assertEqual(count($result), 1, 'Just one node is marked as new'); // Test the history filter. $view = Views::getView('test_history'); $view->setDisplay('page_2'); $this->executeView($view); $this->assertEqual(count($view->result), 1); $this->assertIdenticalResultset($view, array(array('nid' => $nodes[0]->id())), $column_map); }
/** * Gets the current active user. * * @todo: https://drupal.org/node/2105123 put this method in * \Drupal\Core\Plugin\PluginBase instead. * * @return \Drupal\Core\Session\AccountInterface */ protected function currentUser() { if (!$this->currentUser) { $this->currentUser = \Drupal::currentUser(); } return $this->currentUser; }
/** * Login the User creating a new session. * * @return \Symfony\Component\HttpFoundation\JsonResponse * Response represents an HTTP response in JSON format. */ public function login() { return $this->handler('\\Drupal\\user\\Form\\UserLoginForm', function (&$data) { // Preprocess response. $data = array('uid' => \Drupal::currentUser()->id()); }); }
/** * Creates an order for the specified user, and redirects to the edit page. * * @param \Drupal\user\UserInterface $user * The user to create the order for. */ public function createForUser(UserInterface $user) { $order = Order::create(['uid' => $user->id(), 'order_status' => uc_order_state_default('post_checkout')]); $order->save(); uc_order_comment_save($order->id(), \Drupal::currentUser()->id(), $this->t('Order created by the administration.'), 'admin'); return $this->redirect('entity.uc_order.edit_form', ['uc_order' => $order->id()]); }
/** * Tests the form cache with a logged-in user. */ function testCacheToken() { \Drupal::currentUser()->setAccount(new UserSession(array('uid' => 1))); \Drupal::formBuilder()->setCache($this->formBuildId, $this->form, $this->formState); $cached_form_state = new FormState(); $cached_form = \Drupal::formBuilder()->getCache($this->formBuildId, $cached_form_state); $this->assertEqual($this->form['#property'], $cached_form['#property']); $this->assertTrue(!empty($cached_form['#cache_token']), 'Form has a cache token'); $this->assertEqual($this->formState->get('example'), $cached_form_state->get('example')); // Test that the form cache isn't loaded when the session/token has changed. // Change the private key. (We cannot change the session ID because this // will break the parent site test runner batch.) \Drupal::state()->set('system.private_key', 'invalid'); $cached_form_state = new FormState(); $cached_form = \Drupal::formBuilder()->getCache($this->formBuildId, $cached_form_state); $this->assertFalse($cached_form, 'No form returned from cache'); $cached_form_state_example = $cached_form_state->get('example'); $this->assertTrue(empty($cached_form_state_example)); // Test that loading the cache with a different form_id fails. $wrong_form_build_id = $this->randomMachineName(9); $cached_form_state = new FormState(); $this->assertFalse(\Drupal::formBuilder()->getCache($wrong_form_build_id, $cached_form_state), 'No form returned from cache'); $cached_form_state_example = $cached_form_state->get('example'); $this->assertTrue(empty($cached_form_state_example), 'Cached form state was not loaded'); }
/** * Alter the URL to a file. * * This hook is called from file_create_url(), and is called fairly * frequently (10+ times per page), depending on how many files there are in a * given page. * If CSS and JS aggregation are disabled, this can become very frequently * (50+ times per page) so performance is critical. * * This function should alter the URI, if it wants to rewrite the file URL. * * @param $uri * The URI to a file for which we need an external URL, or the path to a * shipped file. */ function hook_file_url_alter(&$uri) { $user = \Drupal::currentUser(); // User 1 will always see the local file in this example. if ($user->id() == 1) { return; } $cdn1 = 'http://cdn1.example.com'; $cdn2 = 'http://cdn2.example.com'; $cdn_extensions = array('css', 'js', 'gif', 'jpg', 'jpeg', 'png'); // Most CDNs don't support private file transfers without a lot of hassle, // so don't support this in the common case. $schemes = array('public'); $scheme = file_uri_scheme($uri); // Only serve shipped files and public created files from the CDN. if (!$scheme || in_array($scheme, $schemes)) { // Shipped files. if (!$scheme) { $path = $uri; } else { $wrapper = \Drupal::service('stream_wrapper_manager')->getViaScheme($scheme); $path = $wrapper->getDirectoryPath() . '/' . file_uri_target($uri); } // Clean up Windows paths. $path = str_replace('\\', '/', $path); // Serve files with one of the CDN extensions from CDN 1, all others from // CDN 2. $pathinfo = pathinfo($path); if (isset($pathinfo['extension']) && in_array($pathinfo['extension'], $cdn_extensions)) { $uri = $cdn1 . '/' . $path; } else { $uri = $cdn2 . '/' . $path; } } }
/** * Test the Who's Online block. */ function testWhosOnlineBlock() { $block = $this->drupalPlaceBlock('views_block:who_s_online-who_s_online_block'); // Generate users. $user1 = $this->drupalCreateUser(array('access user profiles')); $user2 = $this->drupalCreateUser(array()); $user3 = $this->drupalCreateUser(array()); // Update access of two users to be within the active timespan. $this->updateAccess($user1->id()); $this->updateAccess($user2->id(), REQUEST_TIME + 1); // Insert an inactive user who should not be seen in the block, and ensure // that the admin user used in setUp() does not appear. $inactive_time = REQUEST_TIME - 15 * 60 - 1; $this->updateAccess($user3->id(), $inactive_time); $this->updateAccess($this->adminUser->id(), $inactive_time); // Test block output. \Drupal::currentUser()->setAccount($user1); $content = entity_view($block, 'block'); $this->drupalSetContent(render($content)); $this->assertRaw(t('2 users'), 'Correct number of online users (2 users).'); $this->assertText($user1->getUsername(), 'Active user 1 found in online list.'); $this->assertText($user2->getUsername(), 'Active user 2 found in online list.'); $this->assertNoText($user3->getUsername(), 'Inactive user not found in online list.'); $this->assertTrue(strpos($this->drupalGetContent(), $user1->getUsername()) > strpos($this->drupalGetContent(), $user2->getUsername()), 'Online users are ordered correctly.'); }
/** * Tests the handlers. */ public function testHandlers() { $nodes = array(); $nodes[] = $this->drupalCreateNode(); $nodes[] = $this->drupalCreateNode(); $account = $this->drupalCreateUser(); $this->drupalLogin($account); \Drupal::currentUser()->setAccount($account); db_insert('history')->fields(array('uid' => $account->id(), 'nid' => $nodes[0]->id(), 'timestamp' => REQUEST_TIME - 100))->execute(); db_insert('history')->fields(array('uid' => $account->id(), 'nid' => $nodes[1]->id(), 'timestamp' => REQUEST_TIME + 100))->execute(); $column_map = array('nid' => 'nid'); // Test the history field. $view = Views::getView('test_history'); $view->setDisplay('page_1'); $this->executeView($view); $this->assertEqual(count($view->result), 2); $output = $view->preview(); $this->setRawContent(\Drupal::service('renderer')->renderRoot($output)); $result = $this->xpath('//span[@class=:class]', array(':class' => 'marker')); $this->assertEqual(count($result), 1, 'Just one node is marked as new'); // Test the history filter. $view = Views::getView('test_history'); $view->setDisplay('page_2'); $this->executeView($view); $this->assertEqual(count($view->result), 1); $this->assertIdenticalResultset($view, array(array('nid' => $nodes[0]->id())), $column_map); // Install Comment module and make sure that content types without comment // field will not break the view. // See \Drupal\history\Plugin\views\filter\HistoryUserTimestamp::query() \Drupal::service('module_installer')->install(['comment']); $view = Views::getView('test_history'); $view->setDisplay('page_2'); $this->executeView($view); }
/** * {@inheritdoc} */ public function form(array $form, FormStateInterface $form_state) { $user = $this->currentUser(); /** @var \Drupal\user\UserInterface $account */ $account = $this->entity; $admin = $user->hasPermission('administer users'); // Pass access information to the submit handler. Running an access check // inside the submit function interferes with form processing and breaks // hook_form_alter(). $form['administer_users'] = array('#type' => 'value', '#value' => $admin); // If we aren't admin but already logged on, go to the user page instead. if (!$admin && $user->isAuthenticated()) { return new RedirectResponse($this->url('entity.user.canonical', ['user' => \Drupal::currentUser()->id()], array('absolute' => TRUE))); } $form['#attached']['library'][] = 'core/drupal.form'; // For non-admin users, populate the form fields using data from the // browser. if (!$admin) { $form['#attributes']['data-user-info-from-browser'] = TRUE; } // Because the user status has security implications, users are blocked by // default when created programmatically and need to be actively activated // if needed. When administrators create users from the user interface, // however, we assume that they should be created as activated by default. if ($admin) { $account->activate(); } // Start with the default user account fields. $form = parent::form($form, $form_state, $account); return $form; }
public function query() { // This can only work if we're authenticated in. if (!\Drupal::currentUser()->isAuthenticated()) { return; } // Don't filter if we're exposed and the checkbox isn't selected. if (!empty($this->options['exposed']) && empty($this->value)) { return; } // Hey, Drupal kills old history, so nodes that haven't been updated // since HISTORY_READ_LIMIT are bzzzzzzzt outta here! $limit = REQUEST_TIME - HISTORY_READ_LIMIT; $this->ensureMyTable(); $field = "{$this->tableAlias}.{$this->realField}"; $node = $this->query->ensureTable('node_field_data', $this->relationship); $clause = ''; $clause2 = ''; if (\Drupal::moduleHandler()->moduleExists('comment')) { $ces = $this->query->ensureTable('comment_entity_statistics', $this->relationship); $clause = "OR {$ces}.last_comment_timestamp > (***CURRENT_TIME*** - {$limit})"; $clause2 = "OR {$field} < {$ces}.last_comment_timestamp"; } // NULL means a history record doesn't exist. That's clearly new content. // Unless it's very very old content. Everything in the query is already // type safe cause none of it is coming from outside here. $this->query->addWhereExpression($this->options['group'], "({$field} IS NULL AND ({$node}.changed > (***CURRENT_TIME*** - {$limit}) {$clause})) OR {$field} < {$node}.changed {$clause2}"); }
/** * Adds linkit custom autocomplete functionality to elements. * * Instead of using the core autocomplete, we use our own. * * {@inheritdoc} * * @see \Drupal\Core\Render\Element\FormElement::processAutocomplete */ public static function processLinkitAutocomplete(&$element, FormStateInterface $form_state, &$complete_form) { $url = NULL; $access = FALSE; if (!empty($element['#autocomplete_route_name'])) { $parameters = isset($element['#autocomplete_route_parameters']) ? $element['#autocomplete_route_parameters'] : array(); $url = Url::fromRoute($element['#autocomplete_route_name'], $parameters)->toString(TRUE); /** @var \Drupal\Core\Access\AccessManagerInterface $access_manager */ $access_manager = \Drupal::service('access_manager'); $access = $access_manager->checkNamedRoute($element['#autocomplete_route_name'], $parameters, \Drupal::currentUser(), TRUE); } if ($access) { $metadata = BubbleableMetadata::createFromRenderArray($element); if ($access->isAllowed()) { $element['#attributes']['class'][] = 'form-linkit-autocomplete'; $metadata->addAttachments(['library' => ['linkit/linkit.autocomplete']]); // Provide a data attribute for the JavaScript behavior to bind to. $element['#attributes']['data-autocomplete-path'] = $url->getGeneratedUrl(); $metadata = $metadata->merge($url); } $metadata ->merge(BubbleableMetadata::createFromObject($access)) ->applyTo($element); } return $element; }
/** * {@inheritdoc} */ public function validate($value, Constraint $constraint) { $typed_data = $this->context->getMetadata()->getTypedData(); if ($typed_data instanceof AllowedValuesInterface) { $account = \Drupal::currentUser(); $allowed_values = $typed_data->getSettableValues($account); $constraint->choices = $allowed_values; // If the data is complex, we have to validate its main property. if ($typed_data instanceof ComplexDataInterface) { $name = $typed_data->getDataDefinition()->getMainPropertyName(); if (!isset($name)) { throw new \LogicException('Cannot validate allowed values for complex data without a main property.'); } $value = $typed_data->get($name)->getValue(); } } // The parent implementation ignores values that are not set, but makes // sure some choices are available firstly. However, we want to support // empty choices for undefined values, e.g. if a term reference field // points to an empty vocabulary. if (!isset($value)) { return; } parent::validate($value, $constraint); }
function testGoogleAnalyticsCustomDimensions() { $ua_code = 'UA-123456-3'; $this->config('google_analytics.settings')->set('account', $ua_code)->save(); $node = $this->drupalCreateNode(['type' => 'article']); // Basic test if the feature works. $google_analytics_custom_dimension = [1 => ['index' => 1, 'value' => 'Bar 1'], 2 => ['index' => 2, 'value' => 'Bar 2'], 3 => ['index' => 3, 'value' => 'Bar 3'], 4 => ['index' => 4, 'value' => 'Bar 4'], 5 => ['index' => 5, 'value' => 'Bar 5']]; $this->config('google_analytics.settings')->set('custom.dimension', $google_analytics_custom_dimension)->save(); $this->drupalGet(''); foreach ($google_analytics_custom_dimension as $dimension) { $this->assertRaw('ga("set", ' . Json::encode('dimension' . $dimension['index']) . ', ' . Json::encode($dimension['value']) . ');', '[testGoogleAnalyticsCustomDimensionsAndMetrics]: Dimension #' . $dimension['index'] . ' is shown.'); } // Test whether tokens are replaced in custom dimension values. $site_slogan = $this->randomMachineName(16); $this->config('system.site')->set('slogan', $site_slogan)->save(); $google_analytics_custom_dimension = [1 => ['index' => 1, 'value' => 'Value: [site:slogan]'], 2 => ['index' => 2, 'value' => $this->randomMachineName(16)], 3 => ['index' => 3, 'value' => ''], 4 => ['index' => 4, 'value' => '0'], 5 => ['index' => 5, 'value' => '[node:type]'], 6 => ['index' => 6, 'value' => '[current-user:role-names]'], 7 => ['index' => 7, 'value' => '[current-user:role-ids]']]; $this->config('google_analytics.settings')->set('custom.dimension', $google_analytics_custom_dimension)->save(); $this->verbose('<pre>' . print_r($google_analytics_custom_dimension, TRUE) . '</pre>'); // Test on frontpage $this->drupalGet(''); $this->assertRaw('ga("set", ' . Json::encode('dimension1') . ', ' . Json::encode("Value: {$site_slogan}") . ');', '[testGoogleAnalyticsCustomDimensionsAndMetrics]: Tokens have been replaced in dimension value.'); $this->assertRaw('ga("set", ' . Json::encode('dimension2') . ', ' . Json::encode($google_analytics_custom_dimension['2']['value']) . ');', '[testGoogleAnalyticsCustomDimensionsAndMetrics]: Random value is shown.'); $this->assertNoRaw('ga("set", ' . Json::encode('dimension3') . ', ' . Json::encode('') . ');', '[testGoogleAnalyticsCustomDimensionsAndMetrics]: Empty value is not shown.'); $this->assertRaw('ga("set", ' . Json::encode('dimension4') . ', ' . Json::encode('0') . ');', '[testGoogleAnalyticsCustomDimensionsAndMetrics]: Value 0 is shown.'); $this->assertNoRaw('ga("set", ' . Json::encode('dimension5') . ', ' . Json::encode('article') . ');', '[testGoogleAnalyticsCustomDimensionsAndMetrics]: Node tokens are shown.'); $this->assertRaw('ga("set", ' . Json::encode('dimension6') . ', ' . Json::encode(implode(',', \Drupal::currentUser()->getRoles())) . ');', '[testGoogleAnalyticsCustomDimensionsAndMetrics]: List of roles shown.'); $this->assertRaw('ga("set", ' . Json::encode('dimension7') . ', ' . Json::encode(implode(',', array_keys(\Drupal::currentUser()->getRoles()))) . ');', '[testGoogleAnalyticsCustomDimensionsAndMetrics]: List of role IDs shown.'); // Test on a node. $this->drupalGet('node/' . $node->id()); $this->assertText($node->getTitle()); $this->assertRaw('ga("set", ' . Json::encode('dimension5') . ', ' . Json::encode('article') . ');', '[testGoogleAnalyticsCustomDimensionsAndMetrics]: Node tokens are shown.'); }
/** * @param array $form * @param \Drupal\user\UserInterface $user * @return array */ public static function addRoleDelegationElement(array $form, UserInterface $user) { $current_user = \Drupal::currentUser(); $roles_current = $user->getRoles(TRUE); $roles_delegate = array(); $roles = user_roles(TRUE); unset($roles[AccountInterface::AUTHENTICATED_ROLE]); unset($roles['administrator']); foreach ($roles as $rid => $role) { if ($current_user->hasPermission('assign all roles') || $current_user->hasPermission("assign {$role->get('id')} role")) { $roles_delegate[$rid] = isset($form['account']['roles']['#options'][$rid]) ? $form['account']['roles']['#options'][$rid] : $role->get('id'); } } if (empty($roles_delegate)) { // No role can be assigned. return $form; } if (!isset($form['account'])) { $form['account'] = array('#type' => 'value', '#value' => $user); } $default_options = array(); foreach ($roles_current as $role) { if (in_array($role, $roles_delegate)) { $default_options[$role] = $role; } } // Generate the form items. $form['account']['roles_change'] = array('#type' => 'checkboxes', '#title' => isset($form['account']['roles']['#title']) ? $form['account']['roles']['#title'] : t('Roles'), '#options' => $roles_delegate, '#default_value' => array_keys(array_intersect_key(array_flip($roles_current), $roles_delegate)), '#description' => isset($form['account']['roles']['#description']) ? $form['account']['roles']['#description'] : t('Change roles assigned to user.')); return $form; }
/** * Set the current user in Drupal. * * @param \Drupal\Core\Session\AccountInterface $account */ public function setCurrentUser($account) { // Some parts of Drupal still rely on a global user object. // @todo remove once https://www.drupal.org/node/2163205 is in. global $user; $user = $account; \Drupal::currentUser()->setAccount($account); }
/** * {@inheritdoc} */ public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $form_state) { $form = []; $form['library'] = ['#type' => 'fieldset', '#title' => 'Library', '#tree' => FALSE]; // Debug mode toggle. $form['library']['flexslider_debug'] = ['#type' => 'checkbox', '#title' => $this->t('Enable debug mode'), '#description' => $this->t('Load the human-readable version of the FlexSlider library.'), '#default_value' => \Drupal::config('flexslider.settings')->get('flexslider_debug'), '#access' => \Drupal::currentUser()->hasPermission('administer flexslider')]; return parent::buildForm($form, $form_state); }