Beispiel #1
0
 /**
  * {@inheritdoc}
  */
 public function form(array $form, FormStateInterface $form_state)
 {
     /* @var \Drupal\commerce_product\Entity\Product $product */
     $product = $this->entity;
     $form = parent::form($form, $form_state);
     $form['#tree'] = TRUE;
     $form['#theme'] = ['product_form'];
     $form['#attached']['library'][] = 'commerce_product/form';
     $form['#entity_builders']['update_status'] = [$this, 'updateStatus'];
     // Changed must be sent to the client, for later overwrite error checking.
     $form['changed'] = ['#type' => 'hidden', '#default_value' => $product->getChangedTime()];
     $last_saved = t('Not saved yet');
     if (!$product->isNew()) {
         $last_saved = $this->dateFormatter->format($product->getChangedTime(), 'short');
     }
     $form['meta'] = ['#attributes' => ['class' => ['entity-meta__header']], '#type' => 'container', '#group' => 'advanced', '#weight' => -100, 'published' => ['#type' => 'html_tag', '#tag' => 'h3', '#value' => $product->isPublished() ? $this->t('Published') : $this->t('Not published'), '#access' => !$product->isNew(), '#attributes' => ['class' => 'entity-meta__title']], 'changed' => ['#type' => 'item', '#wrapper_attributes' => ['class' => ['entity-meta__last-saved', 'container-inline']], '#markup' => '<h4 class="label inline">' . $this->t('Last saved') . '</h4> ' . $last_saved], 'author' => ['#type' => 'item', '#wrapper_attributes' => ['class' => ['author', 'container-inline']], '#markup' => '<h4 class="label inline">' . $this->t('Author') . '</h4> ' . $product->getOwner()->getDisplayName()]];
     $form['advanced'] = ['#type' => 'container', '#attributes' => ['class' => ['entity-meta']], '#weight' => 99];
     $form['path_settings'] = ['#type' => 'details', '#title' => t('URL path settings'), '#open' => !empty($form['path']['widget'][0]['alias']['#value']), '#group' => 'advanced', '#access' => !empty($form['path']['#access']) && $product->get('path')->access('edit'), '#attributes' => ['class' => ['path-form']], '#attached' => ['library' => ['path/drupal.path']], '#weight' => 30];
     $form['author'] = ['#type' => 'details', '#title' => t('Authoring information'), '#group' => 'advanced', '#attributes' => ['class' => ['product-form-author']], '#attached' => ['library' => ['commerce_product/drupal.commerce_product']], '#weight' => 90, '#optional' => TRUE];
     if (isset($form['uid'])) {
         $form['uid']['#group'] = 'author';
     }
     if (isset($form['created'])) {
         $form['created']['#group'] = 'author';
     }
     if (isset($form['path'])) {
         $form['path']['#group'] = 'path_settings';
     }
     return $form;
 }
 /**
  * {@inheritdoc}
  */
 public function form(array $form, FormStateInterface $form_state)
 {
     $form['label'] = array('#type' => 'textfield', '#title' => 'Name', '#maxlength' => 100, '#description' => t('Name of the date format'), '#default_value' => $this->entity->label());
     $form['id'] = array('#type' => 'machine_name', '#description' => t('A unique machine-readable name. Can only contain lowercase letters, numbers, and underscores.'), '#disabled' => !$this->entity->isNew(), '#default_value' => $this->entity->id(), '#machine_name' => array('exists' => array($this, 'exists'), 'replace_pattern' => '([^a-z0-9_]+)|(^custom$)', 'error' => $this->t('The machine-readable name must be unique, and can only contain lowercase letters, numbers, and underscores. Additionally, it can not be the reserved word "custom".')));
     $form['date_format_pattern'] = array('#type' => 'textfield', '#title' => t('Format string'), '#maxlength' => 100, '#description' => $this->t('A user-defined date format. See the <a href="http://php.net/manual/function.date.php">PHP manual</a> for available options.'), '#required' => TRUE, '#attributes' => ['data-drupal-date-formatter' => 'source'], '#field_suffix' => ' <small class="js-hide" data-drupal-date-formatter="preview">' . $this->t('Displayed as %date_format', ['%date_format' => '']) . '</small>');
     $form['langcode'] = array('#type' => 'language_select', '#title' => t('Language'), '#languages' => LanguageInterface::STATE_ALL, '#default_value' => $this->entity->language()->getId());
     $form['#attached']['drupalSettings']['dateFormats'] = $this->dateFormatter->getSampleDateFormats();
     $form['#attached']['library'][] = 'system/drupal.system.date';
     return parent::form($form, $form_state);
 }
Beispiel #3
0
 /**
  * {@inheritdoc}
  */
 public function buildForm(array $form, FormStateInterface $form_state)
 {
     $form['description'] = array('#markup' => '<p>' . t('Cron takes care of running periodic tasks like checking for updates and indexing content for search.') . '</p>');
     $form['run'] = array('#type' => 'submit', '#value' => t('Run cron'));
     $status = '<p>' . $this->t('Last run: %time ago.', array('%time' => $this->dateFormatter->formatTimeDiffSince($this->state->get('system.cron_last')))) . '</p>';
     $form['status'] = array('#markup' => $status);
     $cron_url = $this->url('system.cron', array('key' => $this->state->get('system.cron_key')), array('absolute' => TRUE));
     $form['cron_url'] = array('#markup' => '<p>' . t('To run cron from outside the site, go to <a href=":cron">@cron</a>', array(':cron' => $cron_url, '@cron' => $cron_url)) . '</p>');
     if (!$this->moduleHandler->moduleExists('automated_cron')) {
         $form['cron'] = array('#markup' => $this->t('Enable the <em>Automated Cron</em> module to allow cron execution at the end of a server response.'));
     }
     return $form;
 }
Beispiel #4
0
 /**
  * Return the default argument.
  */
 public function getArgument()
 {
     $argument = $this->argument;
     // The Date argument handlers provide their own format strings, otherwise
     // use a default.
     if ($argument instanceof \Drupal\calendar_datetime\Plugin\views\argument\Date) {
         /** @var \Drupal\views\Plugin\views\argument\Date $argument */
         $format = $argument->getArgFormat();
     } else {
         $format = 'Y-m-d';
     }
     $request_time = $this->request->server->get('REQUEST_TIME');
     return $this->dateFormatter->format($request_time, 'custom', $format);
 }
Beispiel #5
0
 /**
  * {@inheritdoc}
  */
 public function settingsForm(array $form, FormStateInterface $form_state)
 {
     $form['num'] = array('#type' => 'number', '#title' => $this->t('How many users would you like to generate?'), '#default_value' => $this->getSetting('num'), '#required' => TRUE, '#min' => 0);
     $form['kill'] = array('#type' => 'checkbox', '#title' => $this->t('Delete all users (except user id 1) before generating new users.'), '#default_value' => $this->getSetting('kill'));
     $options = user_role_names(TRUE);
     unset($options[DRUPAL_AUTHENTICATED_RID]);
     $form['roles'] = array('#type' => 'checkboxes', '#title' => $this->t('Which roles should the users receive?'), '#description' => $this->t('Users always receive the <em>authenticated user</em> role.'), '#options' => $options);
     $form['pass'] = array('#type' => 'textfield', '#title' => $this->t('Password to be set'), '#default_value' => $this->getSetting('pass'), '#size' => 32, '#description' => $this->t('Leave this field empty if you do not need to set a password'));
     $options = array(1 => $this->t('Now'));
     foreach (array(3600, 86400, 604800, 2592000, 31536000) as $interval) {
         $options[$interval] = $this->dateFormatter->formatInterval($interval, 1) . ' ' . $this->t('ago');
     }
     $form['time_range'] = array('#type' => 'select', '#title' => $this->t('How old should user accounts be?'), '#description' => $this->t('User ages will be distributed randomly from the current time, back to the selected time.'), '#options' => $options, '#default_value' => 604800);
     return $form;
 }
 /**
  * {@inheritdoc}
  */
 public function filter(DataDefinitionInterface $definition, $value, array $arguments, BubbleableMetadata $bubbleable_metadata = NULL)
 {
     if ($definition->getDataType() != 'timestamp') {
         // Convert the date to an timestamp.
         $value = $this->getTypedDataManager()->create($definition, $value)->getDateTime()->getTimestamp();
     }
     $arguments += [0 => 'medium', 1 => '', 2 => NULL, 3 => NULL];
     if ($arguments[0] != 'custom' && $bubbleable_metadata) {
         $config = $this->dateFormatStorage->load($arguments[0]);
         if (!$config) {
             throw new \InvalidArgumentException("Unknown date format {$arguments['0']} given.");
         }
         $bubbleable_metadata->addCacheableDependency($config);
     }
     return $this->dateFormatter->format($value, $arguments[0], $arguments[1], $arguments[2], $arguments[3]);
 }
Beispiel #7
0
 /**
  * Returns the user password reset form.
  *
  * @param \Symfony\Component\HttpFoundation\Request $request
  *   The request.
  * @param int $uid
  *   User ID of the user requesting reset.
  *
  * @return array|\Symfony\Component\HttpFoundation\RedirectResponse
  *   The form structure or a redirect response.
  *
  * @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
  *   If the pass_reset_timeout or pass_reset_hash are not available in the
  *   session. Or if $uid is for a blocked user or invalid user ID.
  */
 public function getResetPassForm(Request $request, $uid)
 {
     $session = $request->getSession();
     $timestamp = $session->get('pass_reset_timeout');
     $hash = $session->get('pass_reset_hash');
     // As soon as the session variables are used they are removed to prevent the
     // hash and timestamp from being leaked unexpectedly. This could occur if
     // the user does not click on the log in button on the form.
     $session->remove('pass_reset_timeout');
     $session->remove('pass_reset_hash');
     if (!$hash || !$timestamp) {
         throw new AccessDeniedHttpException();
     }
     /** @var \Drupal\user\UserInterface $user */
     $user = $this->userStorage->load($uid);
     if ($user === NULL || !$user->isActive()) {
         // Blocked or invalid user ID, so deny access. The parameters will be in
         // the watchdog's URL for the administrator to check.
         throw new AccessDeniedHttpException();
     }
     // Time out, in seconds, until login URL expires.
     $timeout = $this->config('user.settings')->get('password_reset_timeout');
     $expiration_date = $user->getLastLoginTime() ? $this->dateFormatter->format($timestamp + $timeout) : NULL;
     return $this->formBuilder()->getForm(UserPasswordResetForm::class, $user, $expiration_date, $timestamp, $hash);
 }
 /**
  * {@inheritdoc}
  */
 public function validateForm(array &$form, FormStateInterface $form_state)
 {
     // Replace all contiguous whitespaces (including tabs and newlines) with a
     // single plain space.
     $form_state->setValue(['date_format'], trim(preg_replace('/\\s+/', ' ', $form_state->getValue(['date_format']))));
     // Validate the letters used in the scheduler date format. All punctuation
     // is accepted, so remove everything except word characters then check that
     // there is nothing else which is not in the list of acceptable date/time
     // letters.
     $no_punctuation = preg_replace('/[^\\w+]/', '', $form_state->getValue(['date_format']));
     if (preg_match_all('/[^' . SCHEDULER_DATE_LETTERS . SCHEDULER_TIME_LETTERS . ']/', $no_punctuation, $extra)) {
         $form_state->setErrorByName('date_format', $this->t('You may only use the letters $date_letters for the date and $time_letters for the time. Remove the extra characters $extra', ['$date_letters' => SCHEDULER_DATE_LETTERS, '$time_letters' => SCHEDULER_TIME_LETTERS, '$extra' => implode(' ', $extra[0])]));
     }
     // If date-only is enabled then check if a valid default time was entered.
     // Leading zeros and seconds can be omitted, eg. 6:30 is considered valid.
     if ($form_state->getValue(['allow_date_only'])) {
         $default_time = date_parse($form_state->getValue(['default_time']));
         if ($default_time['error_count']) {
             $form_state->setErrorByName('default_time', $this->t('The default time should be in the format HH:MM:SS'));
         } else {
             // Insert any possibly omitted leading zeroes.
             $unix_time = mktime($default_time['hour'], $default_time['minute'], $default_time['second']);
             $form_state->setValue(['default_time'], $this->dateFormatter->format($unix_time, 'custom', 'H:i:s'));
         }
     }
     // Check that either the date format has a time part or the date-only option
     // is turned on.
     $time_format = $this->getTimeOnlyFormat($form_state->getValue(['date_format']));
     if ($time_format == '' && !$form_state->getValue(['allow_date_only'])) {
         $form_state->setErrorByName('date_format', $this->t('You must either include a time within the date format or enable the date-only option.'));
     }
 }
 /**
  * {@inheritdoc}
  */
 protected function getRevisionDescription(ContentEntityInterface $revision, $is_default = FALSE)
 {
     /** @var \Drupal\Core\Entity\ContentEntityInterface|\Drupal\user\EntityOwnerInterface|\Drupal\Core\Entity\RevisionLogInterface $revision */
     if ($revision instanceof RevisionLogInterface) {
         // Use revision link to link to revisions that are not active.
         $date = $this->dateFormatter->format($revision->getRevisionCreationTime(), 'short');
         $link = $revision->toLink($date, 'revision');
         // @todo: Simplify this when https://www.drupal.org/node/2334319 lands.
         $username = ['#theme' => 'username', '#account' => $revision->getRevisionUser()];
         $username = $this->renderer->render($username);
     } else {
         $link = $revision->toLink($revision->label(), 'revision');
         $username = '';
     }
     $markup = '';
     if ($revision instanceof RevisionLogInterface) {
         $markup = $revision->getRevisionLogMessage();
     }
     if ($username) {
         $template = '{% trans %}{{ date }} by {{ username }}{% endtrans %}{% if message %}<p class="revision-log">{{ message }}</p>{% endif %}';
     } else {
         $template = '{% trans %} {{ date }} {% endtrans %}{% if message %}<p class="revision-log">{{ message }}</p>{% endif %}';
     }
     $column = ['data' => ['#type' => 'inline_template', '#template' => $template, '#context' => ['date' => $link->toString(), 'username' => $username, 'message' => ['#markup' => $markup, '#allowed_tags' => Xss::getHtmlTagList()]]]];
     return $column;
 }
 /**
  * {@inheritdoc}
  */
 public function buildRow(EntityInterface $entity)
 {
     $row['username']['data'] = array('#theme' => 'username', '#account' => $entity);
     $row['status'] = $entity->isActive() ? $this->t('active') : $this->t('blocked');
     $roles = user_role_names(TRUE);
     unset($roles[RoleInterface::AUTHENTICATED_ID]);
     $users_roles = array();
     foreach ($entity->getRoles() as $role) {
         if (isset($roles[$role])) {
             $users_roles[] = $roles[$role];
         }
     }
     asort($users_roles);
     $row['roles']['data'] = array('#theme' => 'item_list', '#items' => $users_roles);
     $options = ['return_as_object' => TRUE];
     $row['member_for']['data'] = $this->dateFormatter->formatTimeDiffSince($entity->getCreatedTime(), $options)->toRenderable();
     $last_access = $this->dateFormatter->formatTimeDiffSince($entity->getLastAccessedTime(), $options);
     if ($entity->getLastAccessedTime()) {
         $row['access']['data']['#markup'] = $last_access->getString();
         CacheableMetadata::createFromObject($last_access)->applyTo($row['access']['data']);
     } else {
         $row['access']['data']['#markup'] = t('never');
     }
     return $row + parent::buildRow($entity);
 }
 /**
  * Displays the aggregator administration page.
  *
  * @return array
  *   A render array as expected by drupal_render().
  */
 public function adminOverview()
 {
     $entity_manager = $this->entityManager();
     $feeds = $entity_manager->getStorage('aggregator_feed')->loadMultiple();
     $header = array($this->t('Title'), $this->t('Items'), $this->t('Last update'), $this->t('Next update'), $this->t('Operations'));
     $rows = array();
     /** @var \Drupal\aggregator\FeedInterface[] $feeds */
     foreach ($feeds as $feed) {
         $row = array();
         $row[] = $feed->link();
         $row[] = $this->formatPlural($entity_manager->getStorage('aggregator_item')->getItemCount($feed), '1 item', '@count items');
         $last_checked = $feed->getLastCheckedTime();
         $refresh_rate = $feed->getRefreshRate();
         $row[] = $last_checked ? $this->t('@time ago', array('@time' => $this->dateFormatter->formatInterval(REQUEST_TIME - $last_checked))) : $this->t('never');
         if (!$last_checked && $refresh_rate) {
             $next_update = $this->t('imminently');
         } elseif ($last_checked && $refresh_rate) {
             $next_update = $next = $this->t('%time left', array('%time' => $this->dateFormatter->formatInterval($last_checked + $refresh_rate - REQUEST_TIME)));
         } else {
             $next_update = $this->t('never');
         }
         $row[] = $next_update;
         $links['edit'] = ['title' => $this->t('Edit'), 'url' => Url::fromRoute('entity.aggregator_feed.edit_form', ['aggregator_feed' => $feed->id()])];
         $links['delete'] = array('title' => $this->t('Delete'), 'url' => Url::fromRoute('entity.aggregator_feed.delete_form', ['aggregator_feed' => $feed->id()]));
         $links['delete_items'] = array('title' => $this->t('Delete items'), 'url' => Url::fromRoute('aggregator.feed_items_delete', ['aggregator_feed' => $feed->id()]));
         $links['update'] = array('title' => $this->t('Update items'), 'url' => Url::fromRoute('aggregator.feed_refresh', ['aggregator_feed' => $feed->id()]));
         $row[] = array('data' => array('#type' => 'operations', '#links' => $links));
         $rows[] = $row;
     }
     $build['feeds'] = array('#prefix' => '<h3>' . $this->t('Feed overview') . '</h3>', '#type' => 'table', '#header' => $header, '#rows' => $rows, '#empty' => $this->t('No feeds available. <a href=":link">Add feed</a>.', array(':link' => $this->url('aggregator.feed_add'))));
     return $build;
 }
Beispiel #12
0
 /**
  * {@inheritdoc}
  */
 public function settingsForm(array $form, FormStateInterface $form_state)
 {
     $types = $this->nodeTypeStorage->loadMultiple();
     if (empty($types)) {
         $create_url = $this->urlGenerator->generateFromRoute('node.type_add');
         $this->setMessage($this->t('You do not have any content types that can be generated. <a href=":create-type">Go create a new content type</a>', array(':create-type' => $create_url)), 'error', FALSE);
         return;
     }
     $options = array();
     foreach ($types as $type) {
         $options[$type->id()] = array('type' => array('#markup' => $type->label()));
         if ($this->commentManager) {
             $comment_fields = $this->commentManager->getFields('node');
             $map = array($this->t('Hidden'), $this->t('Closed'), $this->t('Open'));
             $fields = array();
             foreach ($comment_fields as $field_name => $info) {
                 // Find all comment fields for the bundle.
                 if (in_array($type->id(), $info['bundles'])) {
                     $instance = FieldConfig::loadByName('node', $type->id(), $field_name);
                     $default_value = $instance->getDefaultValueLiteral();
                     $default_mode = reset($default_value);
                     $fields[] = new FormattableMarkup('@field: @state', array('@field' => $instance->label(), '@state' => $map[$default_mode['status']]));
                 }
             }
             // @todo Refactor display of comment fields.
             if (!empty($fields)) {
                 $options[$type->id()]['comments'] = array('data' => array('#theme' => 'item_list', '#items' => $fields));
             } else {
                 $options[$type->id()]['comments'] = $this->t('No comment fields');
             }
         }
     }
     $header = array('type' => $this->t('Content type'));
     if ($this->commentManager) {
         $header['comments'] = array('data' => $this->t('Comments'), 'class' => array(RESPONSIVE_PRIORITY_MEDIUM));
     }
     $form['node_types'] = array('#type' => 'tableselect', '#header' => $header, '#options' => $options);
     $form['kill'] = array('#type' => 'checkbox', '#title' => $this->t('<strong>Delete all content</strong> in these content types before generating new content.'), '#default_value' => $this->getSetting('kill'));
     $form['num'] = array('#type' => 'number', '#title' => $this->t('How many nodes would you like to generate?'), '#default_value' => $this->getSetting('num'), '#required' => TRUE, '#min' => 0);
     $options = array(1 => $this->t('Now'));
     foreach (array(3600, 86400, 604800, 2592000, 31536000) as $interval) {
         $options[$interval] = $this->dateFormatter->formatInterval($interval, 1) . ' ' . $this->t('ago');
     }
     $form['time_range'] = array('#type' => 'select', '#title' => $this->t('How far back in time should the nodes be dated?'), '#description' => $this->t('Node creation dates will be distributed randomly from the current time, back to the selected time.'), '#options' => $options, '#default_value' => 604800);
     $form['max_comments'] = array('#type' => $this->moduleHandler->moduleExists('comment') ? 'number' : 'value', '#title' => $this->t('Maximum number of comments per node.'), '#description' => $this->t('You must also enable comments for the content types you are generating. Note that some nodes will randomly receive zero comments. Some will receive the max.'), '#default_value' => $this->getSetting('max_comments'), '#min' => 0, '#access' => $this->moduleHandler->moduleExists('comment'));
     $form['title_length'] = array('#type' => 'number', '#title' => $this->t('Maximum number of words in titles'), '#default_value' => $this->getSetting('title_length'), '#required' => TRUE, '#min' => 1, '#max' => 255);
     $form['add_alias'] = array('#type' => 'checkbox', '#disabled' => !$this->moduleHandler->moduleExists('path'), '#description' => $this->t('Requires path.module'), '#title' => $this->t('Add an url alias for each node.'), '#default_value' => FALSE);
     $form['add_statistics'] = array('#type' => 'checkbox', '#title' => $this->t('Add statistics for each node (node_counter table).'), '#default_value' => TRUE, '#access' => $this->moduleHandler->moduleExists('statistics'));
     $options = array();
     // We always need a language.
     $languages = $this->languageManager->getLanguages(LanguageInterface::STATE_ALL);
     foreach ($languages as $langcode => $language) {
         $options[$langcode] = $language->getName();
     }
     $form['add_language'] = array('#type' => 'select', '#title' => $this->t('Set language on nodes'), '#multiple' => TRUE, '#description' => $this->t('Requires locale.module'), '#options' => $options, '#default_value' => array($this->languageManager->getDefaultLanguage()->getId()));
     $form['#redirect'] = FALSE;
     return $form;
 }
 /**
  * Generates an overview table of older revisions of a node.
  *
  * @param \Drupal\node\NodeInterface $node
  *   A node object.
  *
  * @return array
  *   An array as expected by drupal_render().
  */
 public function revisionOverview(NodeInterface $node)
 {
     $account = $this->currentUser();
     $langcode = $node->language()->getId();
     $langname = $node->language()->getName();
     $languages = $node->getTranslationLanguages();
     $has_translations = count($languages) > 1;
     $node_storage = $this->entityManager()->getStorage('node');
     $type = $node->getType();
     $build['#title'] = $has_translations ? $this->t('@langname revisions for %title', ['@langname' => $langname, '%title' => $node->label()]) : $this->t('Revisions for %title', ['%title' => $node->label()]);
     $header = array($this->t('Revision'), $this->t('Operations'));
     $revert_permission = ($account->hasPermission("revert {$type} revisions") || $account->hasPermission('revert all revisions') || $account->hasPermission('administer nodes')) && $node->access('update');
     $delete_permission = ($account->hasPermission("delete {$type} revisions") || $account->hasPermission('delete all revisions') || $account->hasPermission('administer nodes')) && $node->access('delete');
     $rows = array();
     $vids = $node_storage->revisionIds($node);
     $latest_revision = TRUE;
     foreach (array_reverse($vids) as $vid) {
         /** @var \Drupal\node\NodeInterface $revision */
         $revision = $node_storage->loadRevision($vid);
         // Only show revisions that are affected by the language that is being
         // displayed.
         if ($revision->hasTranslation($langcode) && $revision->getTranslation($langcode)->isRevisionTranslationAffected()) {
             $username = ['#theme' => 'username', '#account' => $revision->getRevisionAuthor()];
             // Use revision link to link to revisions that are not active.
             $date = $this->dateFormatter->format($revision->revision_timestamp->value, 'short');
             if ($vid != $node->getRevisionId()) {
                 $link = $this->l($date, new Url('entity.node.revision', ['node' => $node->id(), 'node_revision' => $vid]));
             } else {
                 $link = $node->link($date);
             }
             $row = [];
             $column = ['data' => ['#type' => 'inline_template', '#template' => '{% trans %}{{ date }} by {{ username }}{% endtrans %}{% if message %}<p class="revision-log">{{ message }}</p>{% endif %}', '#context' => ['date' => $link, 'username' => $this->renderer->renderPlain($username), 'message' => ['#markup' => $revision->revision_log->value, '#allowed_tags' => Xss::getHtmlTagList()]]]];
             // @todo Simplify once https://www.drupal.org/node/2334319 lands.
             $this->renderer->addCacheableDependency($column['data'], $username);
             $row[] = $column;
             if ($latest_revision) {
                 $row[] = ['data' => ['#prefix' => '<em>', '#markup' => $this->t('Current revision'), '#suffix' => '</em>']];
                 foreach ($row as &$current) {
                     $current['class'] = ['revision-current'];
                 }
                 $latest_revision = FALSE;
             } else {
                 $links = [];
                 if ($revert_permission) {
                     $links['revert'] = ['title' => $this->t('Revert'), 'url' => $has_translations ? Url::fromRoute('node.revision_revert_translation_confirm', ['node' => $node->id(), 'node_revision' => $vid, 'langcode' => $langcode]) : Url::fromRoute('node.revision_revert_confirm', ['node' => $node->id(), 'node_revision' => $vid])];
                 }
                 if ($delete_permission) {
                     $links['delete'] = ['title' => $this->t('Delete'), 'url' => Url::fromRoute('node.revision_delete_confirm', ['node' => $node->id(), 'node_revision' => $vid])];
                 }
                 $row[] = ['data' => ['#type' => 'operations', '#links' => $links]];
             }
             $rows[] = $row;
         }
     }
     $build['node_revisions_table'] = array('#theme' => 'table', '#rows' => $rows, '#header' => $header, '#attached' => array('library' => array('node/drupal.node.admin')));
     return $build;
 }
 /**
  * Formats a timestamp.
  *
  * @param int $timestamp
  *   A UNIX timestamp to format.
  *
  * @return string
  *   The formatted timestamp string using the past or future format setting.
  */
 protected function formatTimestamp($timestamp)
 {
     $granularity = $this->getSetting('granularity');
     $options = ['granularity' => $granularity];
     if ($this->request->server->get('REQUEST_TIME') > $timestamp) {
         return SafeMarkup::format($this->getSetting('past_format'), ['@interval' => $this->dateFormatter->formatTimeDiffSince($timestamp, $options)]);
     } else {
         return SafeMarkup::format($this->getSetting('future_format'), ['@interval' => $this->dateFormatter->formatTimeDiffUntil($timestamp, $options)]);
     }
 }
Beispiel #15
0
 /**
  * Override parent method, which deals with dates as integers.
  */
 protected function opSimple($field)
 {
     $origin = !empty($this->value['type']) && $this->value['type'] == 'offset' ? $this->requestStack->getCurrentRequest()->server->get('REQUEST_TIME') : 0;
     $value = intval(strtotime($this->value['value'], $origin));
     // Convert to ISO. UTC is used since dates are stored in UTC.
     $value = $this->query->getDateFormat("'" . $this->dateFormatter->format($value, 'custom', DATETIME_DATETIME_STORAGE_FORMAT, DATETIME_STORAGE_TIMEZONE) . "'", $this->dateFormat, TRUE);
     // This is safe because we are manually scrubbing the value.
     $field = $this->query->getDateFormat($field, $this->dateFormat, TRUE);
     $this->query->addWhereExpression($this->options['group'], "{$field} {$this->operator} {$value}");
 }
Beispiel #16
0
 /**
  * {@inheritdoc}
  */
 public function form(array $form, FormStateInterface $form_state)
 {
     /* @var \Drupal\commerce_order\Entity\Order $order */
     $order = $this->entity;
     $form = parent::form($form, $form_state);
     $form['#tree'] = TRUE;
     $form['#theme'] = 'commerce_order_edit_form';
     $form['#attached']['library'][] = 'commerce_order/form';
     // Changed must be sent to the client, for later overwrite error checking.
     $form['changed'] = ['#type' => 'hidden', '#default_value' => $order->getChangedTime()];
     $last_saved = $this->dateFormatter->format($order->getChangedTime(), 'short');
     $form['advanced'] = ['#type' => 'container', '#attributes' => ['class' => ['entity-meta']], '#weight' => 99];
     $form['meta'] = ['#attributes' => ['class' => ['entity-meta__header']], '#type' => 'container', '#group' => 'advanced', '#weight' => -100, 'state' => ['#type' => 'html_tag', '#tag' => 'h3', '#value' => $order->getState()->getLabel(), '#attributes' => ['class' => 'entity-meta__title'], '#access' => empty($form['store_id'])], 'date' => NULL, 'changed' => $this->fieldAsReadOnly($this->t('Last saved'), $last_saved)];
     $form['customer'] = ['#type' => 'details', '#title' => t('Customer information'), '#group' => 'advanced', '#open' => TRUE, '#attributes' => ['class' => ['order-form-author']], '#weight' => 91];
     if ($placed_time = $order->getPlacedTime()) {
         $date = $this->dateFormatter->format($placed_time, 'short');
         $form['meta']['date'] = $this->fieldAsReadOnly($this->t('Placed'), $date);
     }
     // Show the order's store only if there are multiple available.
     $store_query = $this->entityManager->getStorage('commerce_store')->getQuery();
     $store_count = $store_query->count()->execute();
     if ($store_count > 1) {
         $store_link = $order->getStore()->toLink()->toString();
         $form['meta']['store'] = $this->fieldAsReadOnly($this->t('Store'), $store_link);
     }
     // Move uid/mail widgets to the sidebar, or provide read-only alternatives.
     if (isset($form['uid'])) {
         $form['uid']['#group'] = 'customer';
     } else {
         $user_link = $order->getOwner()->toLink()->toString();
         $form['customer']['uid'] = $this->fieldAsReadOnly($this->t('Customer'), $user_link);
     }
     if (isset($form['mail'])) {
         $form['mail']['#group'] = 'customer';
     } else {
         $form['customer']['mail'] = $this->fieldAsReadOnly($this->t('Contact email'), $order->getEmail());
     }
     // All additional customer information should come after uid/mail.
     $form['customer']['ip_address'] = $this->fieldAsReadOnly($this->t('IP address'), $order->getIpAddress());
     return $form;
 }
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     // The revision timestamp will be updated when the revision is saved. Keep
     // the original one for the confirmation message.
     $original_revision_timestamp = $this->revision->getRevisionCreationTime();
     $this->revision = $this->prepareRevertedRevision($this->revision, $form_state);
     $this->revision->revision_log = t('Copy of the revision from %date.', ['%date' => $this->dateFormatter->format($original_revision_timestamp)]);
     $this->revision->save();
     $this->logger('content')->notice('@type: reverted %title revision %revision.', ['@type' => $this->revision->bundle(), '%title' => $this->revision->label(), '%revision' => $this->revision->getRevisionId()]);
     drupal_set_message(t('@type %title has been reverted to the revision from %revision-date.', ['@type' => node_get_type_label($this->revision), '%title' => $this->revision->label(), '%revision-date' => $this->dateFormatter->format($original_revision_timestamp)]));
     $form_state->setRedirect('entity.node.version_history', array('node' => $this->revision->id()));
 }
Beispiel #18
0
 /**
  * Displays details about a specific database log message.
  *
  * @param int $event_id
  *   Unique ID of the database log message.
  *
  * @return array
  *   If the ID is located in the Database Logging table, a build array in the
  *   format expected by drupal_render();
  *
  */
 public function eventDetails($event_id)
 {
     $build = array();
     if ($dblog = $this->database->query('SELECT w.*, u.uid FROM {watchdog} w LEFT JOIN {users} u ON u.uid = w.uid WHERE w.wid = :id', array(':id' => $event_id))->fetchObject()) {
         $severity = RfcLogLevel::getLevels();
         $message = $this->formatMessage($dblog);
         $username = array('#theme' => 'username', '#account' => $dblog->uid ? $this->userStorage->load($dblog->uid) : User::getAnonymousUser());
         $rows = array(array(array('data' => $this->t('Type'), 'header' => TRUE), $this->t($dblog->type)), array(array('data' => $this->t('Date'), 'header' => TRUE), $this->dateFormatter->format($dblog->timestamp, 'long')), array(array('data' => $this->t('User'), 'header' => TRUE), array('data' => $username)), array(array('data' => $this->t('Location'), 'header' => TRUE), $this->l($dblog->location, $dblog->location ? Url::fromUri($dblog->location) : Url::fromRoute('<none>'))), array(array('data' => $this->t('Referrer'), 'header' => TRUE), $this->l($dblog->referer, $dblog->referer ? Url::fromUri($dblog->referer) : Url::fromRoute('<none>'))), array(array('data' => $this->t('Message'), 'header' => TRUE), $message), array(array('data' => $this->t('Severity'), 'header' => TRUE), $severity[$dblog->severity]), array(array('data' => $this->t('Hostname'), 'header' => TRUE), $dblog->hostname), array(array('data' => $this->t('Operations'), 'header' => TRUE), array('data' => array('#markup' => $dblog->link))));
         $build['dblog_table'] = array('#type' => 'table', '#rows' => $rows, '#attributes' => array('class' => array('dblog-event')), '#attached' => array('library' => array('dblog/drupal.dblog')));
     }
     return $build;
 }
Beispiel #19
0
 /**
  * {@inheritdoc}
  */
 public function buildRow(EntityInterface $entity)
 {
     /** @var \Drupal\node\NodeInterface $entity */
     $mark = array('#theme' => 'mark', '#mark_type' => node_mark($entity->id(), $entity->getChangedTime()));
     $langcode = $entity->language()->getId();
     $uri = $entity->urlInfo();
     $options = $uri->getOptions();
     $options += $langcode != LanguageInterface::LANGCODE_NOT_SPECIFIED && isset($languages[$langcode]) ? array('language' => $languages[$langcode]) : array();
     $uri->setOptions($options);
     $row['title']['data'] = array('#type' => 'link', '#title' => $entity->label(), '#suffix' => ' ' . drupal_render($mark), '#url' => $uri);
     $row['type'] = node_get_type_label($entity);
     $row['author']['data'] = array('#theme' => 'username', '#account' => $entity->getOwner());
     $row['status'] = $entity->isPublished() ? $this->t('published') : $this->t('not published');
     $row['changed'] = $this->dateFormatter->format($entity->getChangedTime(), 'short');
     $language_manager = \Drupal::languageManager();
     if ($language_manager->isMultilingual()) {
         $row['language_name'] = $language_manager->getLanguageName($langcode);
     }
     $row['operations']['data'] = $this->buildOperations($entity);
     return $row + parent::buildRow($entity);
 }
Beispiel #20
0
 /**
  * {@inheritdoc}
  */
 public function validateForm(array &$form, FormStateInterface $form_state)
 {
     $message = parent::validateForm($form, $form_state);
     // Check if flood control has been activated for sending emails.
     if (!$this->currentUser()->hasPermission('administer contact forms') && (!$message->isPersonal() || !$this->currentUser()->hasPermission('administer users'))) {
         $limit = $this->config('contact.settings')->get('flood.limit');
         $interval = $this->config('contact.settings')->get('flood.interval');
         if (!$this->flood->isAllowed('contact', $limit, $interval)) {
             $form_state->setErrorByName('', $this->t('You cannot send more than %limit messages in @interval. Try again later.', array('%limit' => $limit, '@interval' => $this->dateFormatter->formatInterval($interval))));
         }
     }
     return $message;
 }
 private function createUser($username, $password, $roles, $email = null, $status = null)
 {
     $password = $password ?: $this->generatePassword();
     $user = User::create(['name' => $username, 'mail' => $email ?: $username . '@example.com', 'pass' => $password, 'status' => $status, 'roles' => $roles, 'created' => REQUEST_TIME]);
     $result = [];
     try {
         $user->save();
         $result['success'] = ['user-id' => $user->id(), 'username' => $user->getUsername(), 'password' => $password, 'email' => $user->getEmail(), 'roles' => implode(', ', $roles), 'created' => $this->dateFormatter->format($user->getCreatedTime(), 'custom', 'Y-m-d h:i:s'), 'status' => $status];
     } catch (\Exception $e) {
         $result['error'] = ['vid' => $user->id(), 'name' => $user->get('name'), 'error' => 'Error: ' . get_class($e) . ', code: ' . $e->getCode() . ', message: ' . $e->getMessage()];
     }
     return $result;
 }
Beispiel #22
0
 /**
  * Form constructor for the comment overview administration form.
  *
  * @param array $form
  *   An associative array containing the structure of the form.
  * @param \Drupal\Core\Form\FormStateInterface $form_state
  *   The current state of the form.
  * @param string $type
  *   The type of the overview form ('approval' or 'new').
  *
  * @return array
  *   The form structure.
  */
 public function buildForm(array $form, FormStateInterface $form_state, $type = 'new')
 {
     // Build an 'Update options' form.
     $form['options'] = array('#type' => 'details', '#title' => $this->t('Update options'), '#open' => TRUE, '#attributes' => array('class' => array('container-inline')));
     if ($type == 'approval') {
         $options['publish'] = $this->t('Publish the selected comments');
     } else {
         $options['unpublish'] = $this->t('Unpublish the selected comments');
     }
     $options['delete'] = $this->t('Delete the selected comments');
     $form['options']['operation'] = array('#type' => 'select', '#title' => $this->t('Action'), '#title_display' => 'invisible', '#options' => $options, '#default_value' => 'publish');
     $form['options']['submit'] = array('#type' => 'submit', '#value' => $this->t('Update'));
     // Load the comments that need to be displayed.
     $status = $type == 'approval' ? CommentInterface::NOT_PUBLISHED : CommentInterface::PUBLISHED;
     $header = array('subject' => array('data' => $this->t('Subject'), 'specifier' => 'subject'), 'author' => array('data' => $this->t('Author'), 'specifier' => 'name', 'class' => array(RESPONSIVE_PRIORITY_MEDIUM)), 'posted_in' => array('data' => $this->t('Posted in'), 'class' => array(RESPONSIVE_PRIORITY_LOW)), 'changed' => array('data' => $this->t('Updated'), 'specifier' => 'changed', 'sort' => 'desc', 'class' => array(RESPONSIVE_PRIORITY_LOW)), 'operations' => $this->t('Operations'));
     $cids = $this->commentStorage->getQuery()->condition('status', $status)->tableSort($header)->pager(50)->execute();
     /** @var $comments \Drupal\comment\CommentInterface[] */
     $comments = $this->commentStorage->loadMultiple($cids);
     // Build a table listing the appropriate comments.
     $options = array();
     $destination = $this->getDestinationArray();
     $commented_entity_ids = array();
     $commented_entities = array();
     foreach ($comments as $comment) {
         $commented_entity_ids[$comment->getCommentedEntityTypeId()][] = $comment->getCommentedEntityId();
     }
     foreach ($commented_entity_ids as $entity_type => $ids) {
         $commented_entities[$entity_type] = $this->entityManager->getStorage($entity_type)->loadMultiple($ids);
     }
     foreach ($comments as $comment) {
         /** @var $commented_entity \Drupal\Core\Entity\EntityInterface */
         $commented_entity = $commented_entities[$comment->getCommentedEntityTypeId()][$comment->getCommentedEntityId()];
         $comment_permalink = $comment->permalink();
         if ($comment->hasField('comment_body') && ($body = $comment->get('comment_body')->value)) {
             $attributes = $comment_permalink->getOption('attributes') ?: array();
             $attributes += array('title' => Unicode::truncate($body, 128));
             $comment_permalink->setOption('attributes', $attributes);
         }
         $options[$comment->id()] = array('title' => array('data' => array('#title' => $comment->getSubject() ?: $comment->id())), 'subject' => array('data' => array('#type' => 'link', '#title' => $comment->getSubject(), '#url' => $comment_permalink)), 'author' => array('data' => array('#theme' => 'username', '#account' => $comment->getOwner())), 'posted_in' => array('data' => array('#type' => 'link', '#title' => $commented_entity->label(), '#access' => $commented_entity->access('view'), '#url' => $commented_entity->urlInfo())), 'changed' => $this->dateFormatter->format($comment->getChangedTimeAcrossTranslations(), 'short'));
         $comment_uri_options = $comment->urlInfo()->getOptions() + ['query' => $destination];
         $links = array();
         $links['edit'] = array('title' => $this->t('Edit'), 'url' => $comment->urlInfo('edit-form', $comment_uri_options));
         if ($this->moduleHandler->moduleExists('content_translation') && $this->moduleHandler->invoke('content_translation', 'translate_access', array($comment))->isAllowed()) {
             $links['translate'] = array('title' => $this->t('Translate'), 'url' => $comment->urlInfo('drupal:content-translation-overview', $comment_uri_options));
         }
         $options[$comment->id()]['operations']['data'] = array('#type' => 'operations', '#links' => $links);
     }
     $form['comments'] = array('#type' => 'tableselect', '#header' => $header, '#options' => $options, '#empty' => $this->t('No comments available.'));
     $form['pager'] = array('#type' => 'pager');
     return $form;
 }
 /**
  * Formats a timestamp.
  *
  * @param int $timestamp
  *   A UNIX timestamp to format.
  *
  * @return array
  *   The formatted timestamp string using the past or future format setting.
  */
 protected function formatTimestamp($timestamp)
 {
     $granularity = $this->getSetting('granularity');
     $options = ['granularity' => $granularity, 'return_as_object' => TRUE];
     if ($this->request->server->get('REQUEST_TIME') > $timestamp) {
         $result = $this->dateFormatter->formatTimeDiffSince($timestamp, $options);
         $build = ['#markup' => SafeMarkup::format($this->getSetting('past_format'), ['@interval' => $result->getString()])];
     } else {
         $result = $this->dateFormatter->formatTimeDiffUntil($timestamp, $options);
         $build = ['#markup' => SafeMarkup::format($this->getSetting('future_format'), ['@interval' => $result->getString()])];
     }
     CacheableMetadata::createFromObject($result)->applyTo($build);
     return $build;
 }
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     // The revision timestamp will be updated when the revision is saved. Keep
     // the original one for the confirmation message.
     $this->revision = $this->prepareRevision($this->revision);
     if ($this->revision instanceof RevisionLogInterface) {
         $original_revision_timestamp = $this->revision->getRevisionCreationTime();
         $this->revision->setRevisionLogMessage($this->t('Copy of the revision from %date.', ['%date' => $this->dateFormatter->format($original_revision_timestamp)]));
         drupal_set_message(t('@type %title has been reverted to the revision from %revision-date.', ['@type' => $this->getBundleLabel($this->revision), '%title' => $this->revision->label(), '%revision-date' => $this->dateFormatter->format($original_revision_timestamp)]));
     } else {
         drupal_set_message(t('@type %title has been reverted', ['@type' => $this->getBundleLabel($this->revision), '%title' => $this->revision->label()]));
     }
     $this->revision->save();
     $this->logger('content')->notice('@type: reverted %title revision %revision.', ['@type' => $this->revision->bundle(), '%title' => $this->revision->label(), '%revision' => $this->revision->getRevisionId()]);
     $form_state->setRedirect("entity.{$this->revision->getEntityTypeId()}.version_history", [$this->revision->getEntityTypeId() => $this->revision->id()]);
 }
Beispiel #25
0
 /**
  * {@inheritdoc}
  */
 public function viewElements(FieldItemListInterface $items, $langcode)
 {
     $elements = array();
     $date_format = $this->getSetting('date_format');
     $custom_date_format = '';
     $timezone = $this->getSetting('timezone') ?: NULL;
     $langcode = NULL;
     // If an RFC2822 date format is requested, then the month and day have to
     // be in English. @see http://www.faqs.org/rfcs/rfc2822.html
     if ($date_format === 'custom' && ($custom_date_format = $this->getSetting('custom_date_format')) === 'r') {
         $langcode = 'en';
     }
     foreach ($items as $delta => $item) {
         $elements[$delta] = ['#cache' => ['contexts' => ['timezone']], '#markup' => $this->dateFormatter->format($item->value, $date_format, $custom_date_format, $timezone, $langcode)];
     }
     return $elements;
 }
 /**
  * Generates an overview table of older revisions of a support ticket.
  *
  * @param \Drupal\support_ticket\SupportTicketInterface $support_ticket
  *   A support_ticket object.
  *
  * @return array
  *   An array as expected by drupal_render().
  */
 public function revisionOverview(SupportTicketInterface $support_ticket)
 {
     $account = $this->currentUser();
     $support_ticket_storage = $this->entityManager()->getStorage('support_ticket');
     $type = $support_ticket->getType();
     $build = array();
     $build['#title'] = $this->t('Revisions for %title', array('%title' => $support_ticket->label()));
     $header = array($this->t('Revision'), $this->t('Operations'));
     $revert_permission = ($account->hasPermission("revert {$type} revisions") || $account->hasPermission('revert all revisions') || $account->hasPermission('administer support tickets')) && $support_ticket->access('update');
     $delete_permission = ($account->hasPermission("delete {$type} revisions") || $account->hasPermission('delete all revisions') || $account->hasPermission('administer support tickets')) && $support_ticket->access('delete');
     $rows = array();
     $vids = $support_ticket_storage->revisionIds($support_ticket);
     foreach (array_reverse($vids) as $vid) {
         $revision = $support_ticket_storage->loadRevision($vid);
         $username = ['#theme' => 'username', '#account' => $revision->uid->entity];
         // Use revision link to link to revisions that are not active.
         $date = $this->dateFormatter->format($revision->revision_timestamp->value, 'short');
         if ($vid != $support_ticket->getRevisionId()) {
             $link = $this->l($date, new Url('entity.support_ticket.revision', ['support_ticket' => $support_ticket->id(), 'support_ticket_revision' => $vid]));
         } else {
             $link = $support_ticket->link($date);
         }
         $row = [];
         $column = ['data' => ['#type' => 'inline_template', '#template' => '{% trans %}{{ date }} by {{ username }}{% endtrans %}{% if message %}<p class="revision-log">{{ message }}</p>{% endif %}', '#context' => ['date' => $link, 'username' => $this->renderer->renderPlain($username), 'message' => ['#markup' => $revision->revision_log->value]]]];
         // @todo Simplify once https://www.drupal.org/node/2334319 lands.
         $this->renderer->addCacheableDependency($column['data'], $username);
         $row[] = $column;
         if ($vid == $support_ticket->getRevisionId()) {
             $row[0]['class'] = ['revision-current'];
             $row[] = ['data' => ['#prefix' => '<em>', '#markup' => $this->t('current revision'), '#suffix' => '</em>'], 'class' => ['revision-current']];
         } else {
             $links = [];
             if ($revert_permission) {
                 $links['revert'] = ['title' => $this->t('Revert'), 'url' => Url::fromRoute('support_ticket.revision_revert_confirm', ['support_ticket' => $support_ticket->id(), 'support_ticket_revision' => $vid])];
             }
             if ($delete_permission) {
                 $links['delete'] = ['title' => $this->t('Delete'), 'url' => Url::fromRoute('support_ticket.revision_delete_confirm', ['support_ticket' => $support_ticket->id(), 'support_ticket_revision' => $vid])];
             }
             $row[] = ['data' => ['#type' => 'operations', '#links' => $links]];
         }
         $rows[] = $row;
     }
     $build['support_ticket_revisions_table'] = array('#theme' => 'table', '#rows' => $rows, '#header' => $header, '#attached' => array('library' => array('support_ticket/drupal.support_ticket.admin')));
     return $build;
 }
Beispiel #27
0
 /**
  * {@inheritdoc}
  */
 public function buildRow(EntityInterface $entity)
 {
     $row['username']['data'] = array('#theme' => 'username', '#account' => $entity);
     $row['status'] = $entity->isActive() ? $this->t('active') : $this->t('blocked');
     $roles = user_role_names(TRUE);
     unset($roles[RoleInterface::AUTHENTICATED_ID]);
     $users_roles = array();
     foreach ($entity->getRoles() as $role) {
         if (isset($roles[$role])) {
             $users_roles[] = $roles[$role];
         }
     }
     asort($users_roles);
     $row['roles']['data'] = array('#theme' => 'item_list', '#items' => $users_roles);
     $row['member_for'] = $this->dateFormatter->formatTimeDiffSince($entity->getCreatedTime());
     $row['access'] = $entity->access ? $this->t('@time ago', array('@time' => $this->dateFormatter->formatTimeDiffSince($entity->getLastAccessedTime()))) : t('never');
     return $row + parent::buildRow($entity);
 }
 /**
  * Returns the user password reset page.
  *
  * @param int $uid
  *   UID of user requesting reset.
  * @param int $timestamp
  *   The current timestamp.
  * @param string $hash
  *   Login link hash.
  *
  * @return array|\Symfony\Component\HttpFoundation\RedirectResponse
  *   The form structure or a redirect response.
  *
  * @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
  *   If the login link is for a blocked user or invalid user ID.
  */
 public function resetPass($uid, $timestamp, $hash)
 {
     $account = $this->currentUser();
     $config = $this->config('user.settings');
     // When processing the one-time login link, we have to make sure that a user
     // isn't already logged in.
     if ($account->isAuthenticated()) {
         // The current user is already logged in.
         if ($account->id() == $uid) {
             user_logout();
         } else {
             if ($reset_link_user = $this->userStorage->load($uid)) {
                 drupal_set_message($this->t('Another user (%other_user) is already logged into the site on this computer, but you tried to use a one-time link for user %resetting_user. Please <a href=":logout">logout</a> and try using the link again.', array('%other_user' => $account->getUsername(), '%resetting_user' => $reset_link_user->getUsername(), ':logout' => $this->url('user.logout'))), 'warning');
             } else {
                 // Invalid one-time link specifies an unknown user.
                 drupal_set_message($this->t('The one-time login link you clicked is invalid.'), 'error');
             }
             return $this->redirect('<front>');
         }
     }
     // The current user is not logged in, so check the parameters.
     // Time out, in seconds, until login URL expires.
     $timeout = $config->get('password_reset_timeout');
     $current = REQUEST_TIME;
     /* @var \Drupal\user\UserInterface $user */
     $user = $this->userStorage->load($uid);
     // Verify that the user exists and is active.
     if ($user && $user->isActive()) {
         // No time out for first time login.
         if ($user->getLastLoginTime() && $current - $timestamp > $timeout) {
             drupal_set_message($this->t('You have tried to use a one-time login link that has expired. Please request a new one using the form below.'), 'error');
             return $this->redirect('user.pass');
         } elseif ($user->isAuthenticated() && $timestamp >= $user->getLastLoginTime() && $timestamp <= $current && Crypt::hashEquals($hash, user_pass_rehash($user, $timestamp))) {
             $expiration_date = $user->getLastLoginTime() ? $this->dateFormatter->format($timestamp + $timeout) : NULL;
             return $this->formBuilder()->getForm('Drupal\\user\\Form\\UserPasswordResetForm', $user, $expiration_date, $timestamp, $hash);
         } else {
             drupal_set_message($this->t('You have tried to use a one-time login link that has either been used or is no longer valid. Please request a new one using the form below.'), 'error');
             return $this->redirect('user.pass');
         }
     }
     // Blocked or invalid user ID, so deny access. The parameters will be in the
     // watchdog's URL for the administrator to check.
     throw new AccessDeniedHttpException();
 }
 /**
  * Builds the form presenting an overview of the migration process.
  *
  * @param array $form
  *   An associative array containing the structure of the form.
  * @param \Drupal\Core\Form\FormStateInterface $form_state
  *   The current state of the form.
  *
  * @return array
  *   The form structure.
  */
 public function buildOverviewForm(array $form, FormStateInterface $form_state)
 {
     $form['#title'] = $this->t('Drupal Upgrade');
     if ($date_performed = $this->state->get('migrate_upgrade.performed')) {
         $form['upgrade_option_item'] = ['#type' => 'item', '#prefix' => $this->t('<p>An upgrade has already been performed on this site.</p>'), '#description' => $this->t('<p>Last upgrade: @date</p>', ['@date' => $this->dateFormatter->format($date_performed)])];
         $form['upgrade_option'] = array('#type' => 'radios', '#title' => $this->t('You have two options:'), '#default_value' => static::MIGRATE_UPGRADE_INCREMENTAL, '#options' => [static::MIGRATE_UPGRADE_INCREMENTAL => $this->t('<strong>Rerun</strong>: Import additional configuration and content that was not available when running the upgrade previously.'), static::MIGRATE_UPGRADE_ROLLBACK => $this->t('<strong>Rollback</strong>: Remove content and configuration entities (such as fields and node types). Default values of other configuration will not be reverted (such as site name).')]);
         $validate = ['::validateCredentialForm'];
     } else {
         $form['info_header'] = ['#markup' => '<p>' . $this->t('Upgrade a Drupal site by importing it into a clean and empty new install of Drupal 8. You will lose any existing configuration once you import your site into it. See the <a href=":url">upgrading handbook</a> for more detailed information.', [':url' => 'https://www.drupal.org/upgrade/migrate'])];
         $info[] = $this->t('<strong>Back up the database for this site</strong>. Upgrade will change the database for this site.');
         $info[] = $this->t('Make sure that the host this site is on has access to the database for your previous site.');
         $info[] = $this->t('If your previous site has private files to be migrated, a copy of your files directory must be accessible on the host this site is on.');
         $info[] = $this->t('In general, enable all modules on this site that are enabled on the previous site. For example, if you have used the book module on the previous site then you must enable the book module on this site for that data to be available on this site.');
         $info[] = $this->t('Put this site into <a href=":url">maintenance mode</a>.', [':url' => Url::fromRoute('system.site_maintenance_mode')->toString(TRUE)->getGeneratedUrl()]);
         $form['info'] = ['#theme' => 'item_list', '#list_type' => 'ol', '#items' => $info];
         $form['info_footer'] = ['#markup' => '<p>' . $this->t('This upgrade can take a long time. It is better to import a local copy of your site instead of directly importing from your live site.')];
         $validate = [];
     }
     $form['actions'] = ['#type' => 'actions'];
     $form['actions']['save'] = ['#type' => 'submit', '#value' => $this->t('Continue'), '#button_type' => 'primary', '#validate' => $validate, '#submit' => ['::submitOverviewForm']];
     return $form;
 }
Beispiel #30
0
 /**
  * {@inheritdoc}
  */
 public function render(ResultRow $values)
 {
     $value = $this->getValue($values);
     $format = $this->options['date_format'];
     if (in_array($format, array('custom', 'raw time ago', 'time ago', 'raw time hence', 'time hence', 'raw time span', 'time span', 'raw time span', 'inverse time span', 'time span'))) {
         $custom_format = $this->options['custom_date_format'];
     }
     if ($value) {
         $timezone = !empty($this->options['timezone']) ? $this->options['timezone'] : NULL;
         $time_diff = REQUEST_TIME - $value;
         // will be positive for a datetime in the past (ago), and negative for a datetime in the future (hence)
         switch ($format) {
             case 'raw time ago':
                 return $this->dateFormatter->formatTimeDiffSince($value, array('granularity' => is_numeric($custom_format) ? $custom_format : 2));
             case 'time ago':
                 return $this->t('%time ago', array('%time' => $this->dateFormatter->formatTimeDiffSince($value, array('granularity' => is_numeric($custom_format) ? $custom_format : 2))));
             case 'raw time hence':
                 return $this->dateFormatter->formatTimeDiffUntil($value, array('granularity' => is_numeric($custom_format) ? $custom_format : 2));
             case 'time hence':
                 return $this->t('%time hence', array('%time' => $this->dateFormatter->formatTimeDiffUntil($value, array('granularity' => is_numeric($custom_format) ? $custom_format : 2))));
             case 'raw time span':
                 return ($time_diff < 0 ? '-' : '') . $this->dateFormatter->formatTimeDiffSince($value, array('strict' => FALSE, 'granularity' => is_numeric($custom_format) ? $custom_format : 2));
             case 'inverse time span':
                 return ($time_diff > 0 ? '-' : '') . $this->dateFormatter->formatTimeDiffSince($value, array('strict' => FALSE, 'granularity' => is_numeric($custom_format) ? $custom_format : 2));
             case 'time span':
                 $time = $this->dateFormatter->formatTimeDiffSince($value, array('strict' => FALSE, 'granularity' => is_numeric($custom_format) ? $custom_format : 2));
                 return $time_diff < 0 ? $this->t('%time hence', array('%time' => $time)) : $this->t('%time ago', array('%time' => $time));
             case 'custom':
                 if ($custom_format == 'r') {
                     return format_date($value, $format, $custom_format, $timezone, 'en');
                 }
                 return format_date($value, $format, $custom_format, $timezone);
             default:
                 return format_date($value, $format, '', $timezone);
         }
     }
 }