/** * {@inheritdoc} */ public function getOperations(EntityInterface $entity) { $operations = parent::getOperations($entity); $destination = drupal_get_destination(); $default = $entity->isDefault(); $id = $entity->id(); // Get CSRF token service. $token_generator = \Drupal::csrfToken(); // @TODO: permission checks. if ($entity->status() && !$default) { $operations['disable'] = array('title' => $this->t('Disable'), 'url' => Url::fromRoute('domain.inline_action', array('op' => 'disable', 'domain' => $id)), 'weight' => 50); } elseif (!$default) { $operations['enable'] = array('title' => $this->t('Enable'), 'url' => Url::fromRoute('domain.inline_action', array('op' => 'enable', 'domain' => $id)), 'weight' => 40); } if (!$default) { $operations['default'] = array('title' => $this->t('Make default'), 'url' => Url::fromRoute('domain.inline_action', array('op' => 'default', 'domain' => $id)), 'weight' => 30); $operations['delete'] = array('title' => $this->t('Delete'), 'url' => Url::fromRoute('entity.domain.delete_form', array('domain' => $id)), 'weight' => 20); } // @TODO: inject this service? $operations += \Drupal::moduleHandler()->invokeAll('domain_operations', array($entity)); foreach ($operations as $key => $value) { if (isset($value['query']['token'])) { $operations[$key]['query'] += $destination; } } $default = \Drupal::service('domain.loader')->loadDefaultDomain(); // Deleting the site default domain is not allowed. if ($id == $default->id()) { unset($operations['delete']); } return $operations; }
/** * Prepares the link pointing for approving the comment. * * @param \Drupal\Core\Entity\EntityInterface $data * The comment entity. * @param \Drupal\views\ResultRow $values * The values retrieved from a single row of a view's query result. * * @return string * Returns a string for the link text. */ protected function renderLink($data, ResultRow $values) { $status = $this->getValue($values, 'status'); // Don't show an approve link on published comment. if ($status == CommentInterface::PUBLISHED) { return; } $text = !empty($this->options['text']) ? $this->options['text'] : $this->t('Approve'); $comment = $this->get_entity($values); $this->options['alter']['make_link'] = TRUE; $this->options['alter']['url'] = Url::fromRoute('comment.approve', ['comment' => $comment->id()]); $this->options['alter']['query'] = $this->getDestinationArray() + array('token' => \Drupal::csrfToken()->get($this->options['alter']['url']->toString())); return $text; }
/** * Checks access. * * @param \Symfony\Component\HttpFoundation\Request $request * The request object. * @param \Drupal\Core\Session\AccountInterface $account * The currently logged in account. * * @return \Drupal\Core\Access\AccessResultInterface * The access result. */ public function access(Request $request, AccountInterface $account) { $method = $request->getMethod(); // This check only applies if // 1. this is a write operation // 2. the user was successfully authenticated and // 3. the request comes with a session cookie. if (!in_array($method, array('GET', 'HEAD', 'OPTIONS', 'TRACE')) && $account->isAuthenticated() && $this->sessionConfiguration->hasSession($request)) { $csrf_token = $request->headers->get('X-CSRF-Token'); if (!\Drupal::csrfToken()->validate($csrf_token, 'rest')) { return AccessResult::forbidden()->setCacheMaxAge(0); } } // Let other access checkers decide if the request is legit. return AccessResult::allowed()->setCacheMaxAge(0); }
/** * Checks access. * * @param \Symfony\Component\HttpFoundation\Request $request * The request object. * @param \Drupal\Core\Session\AccountInterface $account * The currently logged in account. * * @return string * A \Drupal\Core\Access\AccessInterface constant value. */ public function access(Request $request, AccountInterface $account) { $method = $request->getMethod(); $cookie = $request->attributes->get('_authentication_provider') == 'cookie'; // This check only applies if // 1. this is a write operation // 2. the user was successfully authenticated and // 3. the request comes with a session cookie. if (!in_array($method, array('GET', 'HEAD', 'OPTIONS', 'TRACE')) && $account->isAuthenticated() && $cookie) { $csrf_token = $request->headers->get('X-CSRF-Token'); if (!\Drupal::csrfToken()->validate($csrf_token, 'rest')) { return static::KILL; } } // Let other access checkers decide if the request is legit. return static::ALLOW; }
/** * Generates a CSRF protecting session token. * * @return \Symfony\Component\HttpFoundation\Response * The response object. */ public function csrfToken() { return new Response(\Drupal::csrfToken()->get('rest'), 200, array('Content-Type' => 'text/plain')); }
/** * Disables a resource. * * @param string $resource_id * The identifier or the REST resource. * @param \Symfony\Component\HttpFoundation\Request $request * The current request. * * @return \Drupal\Core\Ajax\AjaxResponse|\Symfony\Component\HttpFoundation\RedirectResponse * Redirects back to the listing page. * * @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException */ public function disable($resource_id, Request $request) { if (!\Drupal::csrfToken()->validate($request->query->get('token'), 'restui_disable')) { // Throw an access denied exception if the token is invalid or missing. throw new AccessDeniedHttpException(); } $config = \Drupal::configFactory()->getEditable('rest.settings'); $resources = $config->get('resources') ?: array(); $plugin = $this->resourcePluginManager->getInstance(array('id' => $resource_id)); if (!empty($plugin)) { // disable the resource. unset($resources[$resource_id]); $config->set('resources', $resources); $config->save(); // Rebuild routing cache. $this->routeBuilder->rebuild(); drupal_set_message(t('The resource was disabled successfully.')); } // Redirect back to the page. return new RedirectResponse($this->urlGenerator->generate('restui.list', array(), TRUE)); }
/** * Validate a preview token. * * @param string $token * A drupal generated token. * * @return bool * True if the token is valid. * * @codeCoverageIgnore */ public static function validatePreviewToken($token) { return \Drupal::csrfToken()->validate($token, self::PREVIEW_TOKEN_NAME); }
/** * Tests the csrfToken() method. * * @covers ::csrfToken */ public function testCsrfToken() { $this->setMockContainerService('csrf_token'); $this->assertNotNull(\Drupal::csrfToken()); }
/** * Provides an overview of the Drupal database update. * * This page provides cautionary suggestions that should happen before * proceeding with the update to ensure data integrity. * * @return * Rendered HTML form. */ function update_info_page() { // Change query-strings on css/js files to enforce reload for all users. _drupal_flush_css_js(); // Flush the cache of all data for the update status module. $keyvalue = \Drupal::service('keyvalue.expirable'); $keyvalue->get('update')->deleteAll(); $keyvalue->get('update_available_release')->deleteAll(); $token = \Drupal::csrfToken()->get('update'); $output = '<p>Use this utility to update your database whenever a new release of Drupal or a module is installed.</p><p>For more detailed information, see the <a href="http://drupal.org/upgrade">upgrading handbook</a>. If you are unsure what these terms mean you should probably contact your hosting provider.</p>'; $output .= "<ol>\n"; $output .= "<li><strong>Back up your code</strong>. Hint: when backing up module code, do not leave that backup in the 'modules' or 'sites/*/modules' directories as this may confuse Drupal's auto-discovery mechanism.</li>\n"; $output .= '<li>Put your site into <a href="' . base_path() . '?q=admin/config/development/maintenance">maintenance mode</a>.</li>' . "\n"; $output .= "<li><strong>Back up your database</strong>. This process will change your database values and in case of emergency you may need to revert to a backup.</li>\n"; $output .= "<li>Install your new files in the appropriate location, as described in the handbook.</li>\n"; $output .= "</ol>\n"; $output .= "<p>When you have performed the steps above, you may proceed.</p>\n"; $form_action = check_url(drupal_current_script_url(array('op' => 'selection', 'token' => $token))); $output .= '<form method="post" action="' . $form_action . '"><div class="form-actions form-wrapper" id="edit-actions"><input type="submit" value="Continue" class="button button--primary form-submit" /></div></form>'; $output .= "\n"; $build = array('#title' => 'Drupal database update', '#markup' => $output); return $build; }
/** * 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 submitForm(array &$form, FormStateInterface $form_state) { // Check to see if we need to create an encryption key file. if ($form_state->getValue('update_cc_encrypt_dir')) { $key_path = $form_state->getValue('uc_credit_encryption_path'); $key_file = $key_path . '/' . UC_CREDIT_KEYFILE_NAME; if (!file_exists($key_file)) { if (!($file = fopen($key_file, 'wb'))) { drupal_set_message($this->t('Credit card encryption key file creation failed for file @file. Check your filepath settings and directory permissions.', ['@file' => $key_file]), 'error'); $this->logger('uc_credit')->error('Credit card encryption key file creation failed for file @file. Check your filepath settings and directory permissions.', ['@file' => $key_file]); } else { // Replacement key generation suggested by Barry Jaspan // for increased security. fwrite($file, md5(\Drupal::csrfToken()->get(serialize($_REQUEST) . serialize($_SERVER) . REQUEST_TIME))); fclose($file); drupal_set_message($this->t('Credit card encryption key file generated. Card data will now be encrypted.')); $this->logger('uc_credit')->notice('Credit card encryption key file generated. Card data will now be encrypted.'); } } } // Need to use configFactory() and getEditable() here, because this form is // wrapped by PaymentMethodSettingsForm so $this->getEditableConfigNames() // never gets called $credit_config = \Drupal::configFactory()->getEditable('uc_credit.settings'); $credit_config->set('validate_numbers', $form_state->getValue('uc_credit_validate_numbers'))->set('encryption_path', $form_state->getValue('uc_credit_encryption_path'))->set('cvv_enabled', $form_state->getValue('uc_credit_cvv_enabled'))->set('owner_enabled', $form_state->getValue('uc_credit_owner_enabled'))->set('start_enabled', $form_state->getValue('uc_credit_start_enabled'))->set('issue_enabled', $form_state->getValue('uc_credit_issue_enabled'))->set('bank_enabled', $form_state->getValue('uc_credit_bank_enabled'))->set('type_enabled', $form_state->getValue('uc_credit_type_enabled'))->set('policy', $form_state->getValue('uc_credit_policy'))->set('accepted_types', explode("\r\n", $form_state->getValue('uc_credit_accepted_types')))->save(); }
/** * {@inheritdoc} */ public function submitForm(array &$form, FormStateInterface $form_state) { parent::submitForm($form, $form_state); // Check to see if we need to create an encryption key file. if ($form_state->getValue('update_cc_encrypt_dir')) { $key_path = $form_state->getValue('uc_credit_encryption_path'); $key_file = $key_path . '/' . UC_CREDIT_KEYFILE_NAME; if (!file_exists($key_file)) { if (!($file = fopen($key_file, 'wb'))) { drupal_set_message($this->t('Credit card encryption key file creation failed for file @file. Check your filepath settings and directory permissions.', ['@file' => $key_file]), 'error'); $this->logger('uc_credit')->error('Credit card encryption key file creation failed for file @file. Check your filepath settings and directory permissions.', ['@file' => $key_file]); } else { // Replacement key generation suggested by Barry Jaspan // for increased security. fwrite($file, md5(\Drupal::csrfToken()->get(serialize($_REQUEST) . serialize($_SERVER) . REQUEST_TIME))); fclose($file); drupal_set_message($this->t('Credit card encryption key file generated. Card data will now be encrypted.')); $this->logger('uc_credit')->notice('Credit card encryption key file generated. Card data will now be encrypted.'); } } } $this->config('uc_credit.settings')->set('encryption_path', $form_state->getValue('uc_credit_encryption_path'))->set('visa', $form_state->getValue('uc_credit_visa'))->set('mastercard', $form_state->getValue('uc_credit_mastercard'))->set('discover', $form_state->getValue('uc_credit_discover'))->set('amex', $form_state->getValue('uc_credit_amex'))->save(); }
/** * Render API callback: Hides display of the upload or remove controls. * * Upload controls are hidden when a file is already uploaded. Remove controls * are hidden when there is no file attached. Controls are hidden here instead * of in \Drupal\file\Element\ManagedFile::processManagedFile(), because * #access for these buttons depends on the managed_file element's #value. See * the documentation of \Drupal\Core\Form\FormBuilderInterface::doBuildForm() * for more detailed information about the relationship between #process, * #value, and #access. * * Because #access is set here, it affects display only and does not prevent * JavaScript or other untrusted code from submitting the form as though * access were enabled. The form processing functions for these elements * should not assume that the buttons can't be "clicked" just because they are * not displayed. * * @see \Drupal\file\Element\ManagedFile::processManagedFile() * @see \Drupal\Core\Form\FormBuilderInterface::doBuildForm() * * Note: based on plupload_element_pre_render(). */ public static function preRenderPlUploadFile($element) { $settings = isset($element['#plupload_settings']) ? $element['#plupload_settings'] : array(); // Set upload URL. if (empty($settings['url'])) { $settings['url'] = Url::fromRoute('plupload.upload', array(), array('query' => array('token' => \Drupal::csrfToken()->get('plupload-handle-uploads'))))->toString(); } // The Plupload library supports client-side validation of file extension, so // pass along the information for it to do that. However, as with all client- // side validation, this is a UI enhancement only, and not a replacement for // server-side validation. if (empty($settings['filters']) && isset($element['#upload_validators']['file_validate_extensions'][0])) { $settings['filters'][] = array('title' => t('Allowed files'), 'extensions' => str_replace(' ', ',', $element['#upload_validators']['file_validate_extensions'][0])); } // Check for autoupload and autosubmit settings and add appropriate callback. if (!empty($element['#autoupload'])) { $settings['init']['FilesAdded'] = 'Drupal.plupload.filesAddedCallback'; if (!empty($element['#autosubmit'])) { $settings['init']['UploadComplete'] = 'Drupal.plupload.uploadCompleteCallback'; } } // Add a specific submit element that we want to click if one is specified. if (!empty($element['#submit_element'])) { $settings['submit_element'] = $element['#submit_element']; } // Check if there are event callbacks and append them to current ones, if any. if (!empty($element['#event_callbacks'])) { // array_merge() only accepts parameters of type array. if (!isset($settings['init'])) { $settings['init'] = array(); } $settings['init'] = array_merge($settings['init'], $element['#event_callbacks']); } if (empty($element['#description'])) { $element['#description'] = ''; } $element['#description'] = array('#theme' => 'file_upload_help', '#description' => $element['#description'], '#upload_validators' => $element['#upload_validators']); // Global settings $library_discovery = \Drupal::service('library.discovery'); $library = $library_discovery->getLibraryByName('plupload', 'plupload'); $element['#attached']['drupalSettings']['plupload'] = array('_default' => $library['settings']['plupload']['_default'], $element['#id'] => $settings); return $element; }
/** * {@inheritdoc} */ function create(array $batch) { $this->connection->insert('batch')->fields(array('bid' => $batch['id'], 'timestamp' => REQUEST_TIME, 'token' => \Drupal::csrfToken()->get($batch['id']), 'batch' => serialize($batch)))->execute(); }
/** * Processes a file download. * * @param $file_user * @param $ip */ protected function logDownload($file_user, $ip) { // Add the address if it doesn't exist. $addresses = $file_user->addresses; if (!in_array($ip, $addresses)) { $addresses[] = $ip; } $file_user->addresses = $addresses; // Accessed again. $file_user->accessed++; // Calculate hash $file_user->file_key = \Drupal::csrfToken()->get(serialize($file_user)); $key = NULL; if (isset($file_user['fuid'])) { $key = $file_user['fuid']; } // Insert or update (if $key is already in table) uc_file_users table. db_merge('uc_file_users')->key(['fuid' => $key])->fields($file_user)->execute(); }
/** * Prepares the link pointing for approving the comment. * * @param \Drupal\Core\Entity\EntityInterface $data * The comment entity. * @param \Drupal\views\ResultRow $values * The values retrieved from a single row of a view's query result. * * @return string * Returns a string for the link text. */ protected function renderLink($data, ResultRow $values) { $status = $this->getValue($values, 'status'); // Don't show an approve link on published comment. if ($status == CommentInterface::PUBLISHED) { return; } $text = !empty($this->options['text']) ? $this->options['text'] : $this->t('Approve'); $comment = $this->get_entity($values); $this->options['alter']['make_link'] = TRUE; $this->options['alter']['path'] = "comment/" . $comment->id() . "/approve"; $this->options['alter']['query'] = drupal_get_destination() + array('token' => \Drupal::csrfToken()->get($this->options['alter']['path'])); return $text; }