Exemple #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;
 }
Exemple #2
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);
 }
 /**
  * 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}
  */
 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]);
 }
 /**
  * {@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;
 }
 /**
  * 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;
 }
Exemple #8
0
 /**
  * {@inheritdoc}
  */
 public function buildOptionsForm(&$form, FormStateInterface $form_state)
 {
     $date_formats = array();
     foreach ($this->dateFormatStorage->loadMultiple() as $machine_name => $value) {
         $date_formats[$machine_name] = $this->t('@name format: @date', array('@name' => $value->label(), '@date' => $this->dateFormatter->format(REQUEST_TIME, $machine_name)));
     }
     $form['date_format'] = array('#type' => 'select', '#title' => $this->t('Date format'), '#options' => $date_formats + array('custom' => $this->t('Custom'), 'raw time ago' => $this->t('Time ago'), 'time ago' => $this->t('Time ago (with "ago" appended)'), 'raw time hence' => $this->t('Time hence'), 'time hence' => $this->t('Time hence (with "hence" appended)'), 'raw time span' => $this->t('Time span (future dates have "-" prepended)'), 'inverse time span' => $this->t('Time span (past dates have "-" prepended)'), 'time span' => $this->t('Time span (with "ago/hence" appended)')), '#default_value' => isset($this->options['date_format']) ? $this->options['date_format'] : 'small');
     $form['custom_date_format'] = array('#type' => 'textfield', '#title' => $this->t('Custom date format'), '#description' => $this->t('If "Custom", see <a href="http://us.php.net/manual/en/function.date.php" target="_blank">the PHP docs</a> for date formats. Otherwise, enter the number of different time units to display, which defaults to 2.'), '#default_value' => isset($this->options['custom_date_format']) ? $this->options['custom_date_format'] : '');
     // Setup #states for all possible date_formats on the custom_date_format form element.
     foreach (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') as $custom_date_possible) {
         $form['custom_date_format']['#states']['visible'][] = array(':input[name="options[date_format]"]' => array('value' => $custom_date_possible));
     }
     $form['timezone'] = array('#type' => 'select', '#title' => $this->t('Timezone'), '#description' => $this->t('Timezone to be used for date output.'), '#options' => array('' => $this->t('- Default site/user timezone -')) + system_time_zones(FALSE), '#default_value' => $this->options['timezone']);
     foreach (array_merge(array('custom'), array_keys($date_formats)) as $timezone_date_formats) {
         $form['timezone']['#states']['visible'][] = array(':input[name="options[date_format]"]' => array('value' => $timezone_date_formats));
     }
     parent::buildOptionsForm($form, $form_state);
 }
Exemple #9
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}");
 }
Exemple #10
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;
 }
Exemple #11
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;
 }
 /**
  * {@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()));
 }
 /**
  * {@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);
 }
 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;
 }
 /**
  * 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;
 }
 /**
  * {@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()]);
 }
Exemple #17
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;
 }
 /**
  * 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;
 }
 private function getAllEvents(DrupalStyle $io, $eventType, $eventSeverity, $userId, $asc, $offset, $limit)
 {
     $userStorage = $this->entityTypeManager->getStorage('user');
     $severity = RfcLogLevel::getLevels();
     $query = $this->database->select('watchdog', 'w');
     $query->fields('w', ['wid', 'uid', 'severity', 'type', 'timestamp', 'message', 'variables']);
     if ($eventType) {
         $query->condition('type', $eventType);
     }
     if ($eventSeverity) {
         if (!in_array($eventSeverity, $severity)) {
             $io->error(sprintf($this->trans('commands.database.log.debug.messages.invalid-severity'), $eventSeverity));
             return false;
         }
         $query->condition('severity', array_search($eventSeverity, $severity));
     }
     if ($userId) {
         $query->condition('uid', $userId);
     }
     if ($asc) {
         $query->orderBy('wid', 'ASC');
     } else {
         $query->orderBy('wid', 'DESC');
     }
     if ($limit) {
         $query->range($offset, $limit);
     }
     $result = $query->execute();
     $tableHeader = [$this->trans('commands.database.log.debug.messages.event-id'), $this->trans('commands.database.log.debug.messages.type'), $this->trans('commands.database.log.debug.messages.date'), $this->trans('commands.database.log.debug.messages.message'), $this->trans('commands.database.log.debug.messages.user'), $this->trans('commands.database.log.debug.messages.severity')];
     $tableRows = [];
     foreach ($result as $dblog) {
         $user = $userStorage->load($dblog->uid);
         $tableRows[] = [$dblog->wid, $dblog->type, $this->dateFormatter->format($dblog->timestamp, 'short'), Unicode::truncate(Html::decodeEntities(strip_tags($this->formatMessage($dblog))), 56, true, true), $user->getUsername() . ' (' . $user->id() . ')', $severity[$dblog->severity]];
     }
     $io->table($tableHeader, $tableRows);
     return true;
 }
 /**
  * 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('Upgrade');
     if ($date_performed = $this->state->get('migrate_drupal_ui.performed')) {
         // @todo Add back support for rollbacks and incremental migrations.
         //   https://www.drupal.org/node/2687843
         //   https://www.drupal.org/node/2687849
         $form['upgrade_option_item'] = ['#type' => 'item', '#prefix' => $this->t('An upgrade has already been performed on this site. To perform a new migration, create a clean and empty new install of Drupal 8. Rollbacks and incremental migrations are not yet supported through the user interface. For more information, see the <a href=":url">upgrading handbook</a>.', [':url' => 'https://www.drupal.org/upgrade/migrate']), '#description' => $this->t('<p>Last upgrade: @date</p>', ['@date' => $this->dateFormatter->format($date_performed)])];
         return $form;
     } else {
         $form['info_header'] = ['#markup' => '<p>' . $this->t('Upgrade a 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">online documentation for Drupal site upgrades</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;
 }
 /**
  * Builds the response.
  */
 public function build()
 {
     $build['content'] = ['#type' => 'item', '#title' => t('Content'), '#markup' => t('Hello world!')];
     $build['date'] = ['#type' => 'item', '#title' => t('Date'), '#markup' => $this->dateFormatter->format(REQUEST_TIME)];
     return $build;
 }
 /**
  * {@inheritdoc}
  */
 public function buildRow(EntityInterface $entity)
 {
     $row['label'] = $entity->label();
     $row['pattern'] = $this->dateFormatter->format(REQUEST_TIME, $entity->id());
     return $row + parent::buildRow($entity);
 }
Exemple #25
0
 /**
  * Format date.
  *
  * @param \Drupal\Core\Entity\EntityInterface $entity
  * @param string $field_name
  * @param string $format
  */
 protected function formatDate(EntityInterface $entity, $field_name, $format)
 {
     $timestamp = $entity->get($field_name)->value;
     return $this->dateFormatter->format($timestamp, $format);
 }
 /**
  * {@inheritdoc}
  */
 public function getQuestion()
 {
     return t('Are you sure you want to delete the format %name : %format?', array('%name' => $this->entity->label(), '%format' => $this->dateFormatter->format(REQUEST_TIME, $this->entity->id())));
 }