/**
  * {@inheritdoc}
  */
 public function read($sid)
 {
     // @todo Remove global in https://www.drupal.org/node/2228393
     global $_session_user;
     // Handle the case of first time visitors and clients that don't store
     // cookies (eg. web crawlers).
     $cookies = $this->requestStack->getCurrentRequest()->cookies;
     if (empty($sid) || !$cookies->has($this->getName())) {
         $_session_user = new UserSession();
         return '';
     }
     $values = $this->connection->query("SELECT u.*, s.* FROM {users_field_data} u INNER JOIN {sessions} s ON u.uid = s.uid WHERE u.default_langcode = 1 AND s.sid = :sid", array(':sid' => Crypt::hashBase64($sid)))->fetchAssoc();
     // We found the client's session record and they are an authenticated,
     // active user.
     if ($values && $values['uid'] > 0 && $values['status'] == 1) {
         // Add roles element to $user.
         $rids = $this->connection->query("SELECT ur.roles_target_id as rid FROM {user__roles} ur WHERE ur.entity_id = :uid", array(':uid' => $values['uid']))->fetchCol();
         $values['roles'] = array_merge(array(AccountInterface::AUTHENTICATED_ROLE), $rids);
         $_session_user = new UserSession($values);
     } elseif ($values) {
         // The user is anonymous or blocked. Only preserve two fields from the
         // {sessions} table.
         $_session_user = new UserSession(array('session' => $values['session'], 'access' => $values['access']));
     } else {
         // The session has expired.
         $_session_user = new UserSession();
     }
     return $_session_user->session;
 }
Beispiel #2
0
 /**
  * {@inheritdoc}
  */
 public function save($source, $alias, $langcode = LanguageInterface::LANGCODE_NOT_SPECIFIED, $pid = NULL)
 {
     if ($source[0] !== '/') {
         throw new \InvalidArgumentException(sprintf('Source path %s has to start with a slash.', $source));
     }
     if ($alias[0] !== '/') {
         throw new \InvalidArgumentException(sprintf('Alias path %s has to start with a slash.', $alias));
     }
     $fields = array('source' => $source, 'alias' => $alias, 'langcode' => $langcode);
     // Insert or update the alias.
     if (empty($pid)) {
         $query = $this->connection->insert('url_alias')->fields($fields);
         $pid = $query->execute();
         $fields['pid'] = $pid;
         $operation = 'insert';
     } else {
         // Fetch the current values so that an update hook can identify what
         // exactly changed.
         $original = $this->connection->query('SELECT source, alias, langcode FROM {url_alias} WHERE pid = :pid', array(':pid' => $pid))->fetchAssoc();
         $fields['pid'] = $pid;
         $query = $this->connection->update('url_alias')->fields($fields)->condition('pid', $pid);
         $pid = $query->execute();
         $fields['original'] = $original;
         $operation = 'update';
     }
     if ($pid) {
         // @todo Switch to using an event for this instead of a hook.
         $this->moduleHandler->invokeAll('path_' . $operation, array($fields));
         Cache::invalidateTags(['route_match']);
         return $fields;
     }
     return FALSE;
 }
Beispiel #3
0
 /**
  * Gets a redirect for given path, query and language.
  *
  * @param string $source_path
  *   The redirect source path.
  * @param array $query
  *   The redirect source path query.
  * @param $language
  *   The language for which is the redirect.
  *
  * @return \Drupal\redirect\Entity\Redirect
  *   The matched redirect entity.
  *
  * @throws \Drupal\redirect\Exception\RedirectLoopException
  */
 public function findMatchingRedirect($source_path, array $query = [], $language = Language::LANGCODE_NOT_SPECIFIED)
 {
     $hashes = [Redirect::generateHash($source_path, $query, $language)];
     if ($language != Language::LANGCODE_NOT_SPECIFIED) {
         $hashes[] = Redirect::generateHash($source_path, $query, Language::LANGCODE_NOT_SPECIFIED);
     }
     // Add a hash without the query string if using passthrough querystrings.
     if (!empty($query) && $this->config->get('passthrough_querystring')) {
         $hashes[] = Redirect::generateHash($source_path, [], $language);
         if ($language != Language::LANGCODE_NOT_SPECIFIED) {
             $hashes[] = Redirect::generateHash($source_path, [], Language::LANGCODE_NOT_SPECIFIED);
         }
     }
     // Load redirects by hash. A direct query is used to improve performance.
     $rid = $this->connection->query('SELECT rid FROM {redirect} WHERE hash IN (:hashes[]) ORDER BY LENGTH(redirect_source__query) DESC', [':hashes[]' => $hashes])->fetchField();
     if (!empty($rid)) {
         // Check if this is a loop.
         if (in_array($rid, $this->foundRedirects)) {
             throw new RedirectLoopException('/' . $source_path, $rid);
         }
         $this->foundRedirects[] = $rid;
         $redirect = $this->load($rid);
         // Find chained redirects.
         if ($recursive = $this->findByRedirect($redirect, $language)) {
             // Reset found redirects.
             $this->foundRedirects = [];
             return $recursive;
         }
         return $redirect;
     }
     return NULL;
 }
Beispiel #4
0
 /**
  * {@inheritdoc}
  */
 public function getMultiple(&$cids, $allow_invalid = FALSE)
 {
     $cid_mapping = array();
     foreach ($cids as $cid) {
         $cid_mapping[$this->normalizeCid($cid)] = $cid;
     }
     // When serving cached pages, the overhead of using ::select() was found
     // to add around 30% overhead to the request. Since $this->bin is a
     // variable, this means the call to ::query() here uses a concatenated
     // string. This is highly discouraged under any other circumstances, and
     // is used here only due to the performance overhead we would incur
     // otherwise. When serving an uncached page, the overhead of using
     // ::select() is a much smaller proportion of the request.
     $result = array();
     try {
         $result = $this->connection->query('SELECT cid, data, created, expire, serialized, tags, checksum FROM {' . $this->connection->escapeTable($this->bin) . '} WHERE cid IN ( :cids[] ) ORDER BY cid', array(':cids[]' => array_keys($cid_mapping)));
     } catch (\Exception $e) {
         // Nothing to do.
     }
     $cache = array();
     foreach ($result as $item) {
         // Map the cache ID back to the original.
         $item->cid = $cid_mapping[$item->cid];
         $item = $this->prepareItem($item, $allow_invalid);
         if ($item) {
             $cache[$item->cid] = $item;
         }
     }
     $cids = array_diff($cids, array_keys($cache));
     return $cache;
 }
Beispiel #5
0
 public function preRender(&$values)
 {
     $uids = array();
     $this->items = array();
     foreach ($values as $result) {
         $uids[] = $this->getValue($result);
     }
     if ($uids) {
         $roles = user_roles();
         $result = $this->database->query('SELECT u.entity_id as uid, u.roles_target_id as rid FROM {user__roles} u WHERE u.entity_id IN ( :uids[] ) AND u.roles_target_id IN ( :rids[] )', array(':uids[]' => $uids, ':rids[]' => array_keys($roles)));
         foreach ($result as $role) {
             $this->items[$role->uid][$role->rid]['role'] = $roles[$role->rid]->label();
             $this->items[$role->uid][$role->rid]['rid'] = $role->rid;
         }
         // Sort the roles for each user by role weight.
         $ordered_roles = array_flip(array_keys($roles));
         foreach ($this->items as &$user_roles) {
             // Create an array of rids that the user has in the role weight order.
             $sorted_keys = array_intersect_key($ordered_roles, $user_roles);
             // Merge with the unsorted array of role information which has the
             // effect of sorting it.
             $user_roles = array_merge($sorted_keys, $user_roles);
         }
     }
 }
Beispiel #6
0
 /**
  * {@inheritdoc}
  */
 public function load($id)
 {
     $batch = $this->connection->query("SELECT batch FROM {batch} WHERE bid = :bid AND token = :token", array(':bid' => $id, ':token' => \Drupal::csrfToken()->get($id)))->fetchField();
     if ($batch) {
         return unserialize($batch);
     }
     return FALSE;
 }
Beispiel #7
0
 /**
  * {@inheritdoc}
  */
 public function load($id)
 {
     // Ensure that a session is started before using the CSRF token generator.
     $this->session->start();
     $batch = $this->connection->query("SELECT batch FROM {batch} WHERE bid = :bid AND token = :token", array(':bid' => $id, ':token' => $this->csrfToken->get($id)))->fetchField();
     if ($batch) {
         return unserialize($batch);
     }
     return FALSE;
 }
 /**
  * {@inheritdoc}
  */
 public function buildForm(array $form, FormStateInterface $form_state)
 {
     $num_nodes = $this->database->query("SELECT COUNT(*) FROM {crm_core_contact} WHERE type = :type", array(':type' => $this->entity->id()))->fetchField();
     if ($num_nodes) {
         $caption = \Drupal::translation()->formatPlural($num_nodes, '%type is used by one contact on your site. You can not remove this contact type until you have removed all of the %type contacts.', '%type is used by @count contacts on your site. You may not remove %type until you have removed all of the %type contacts.', array('%type' => $this->entity->label()));
         $form['#title'] = $this->getQuestion();
         $form['description'] = array('#markup' => '<p>' . $caption . '</p>');
         return $form;
     }
     return parent::buildForm($form, $form_state);
 }
 /**
  * {@inheritdoc}
  */
 public function buildForm(array $form, FormStateInterface $form_state)
 {
     $num_nodes = $this->database->query("SELECT COUNT(*) FROM {node} WHERE type = :type", array(':type' => $this->entity->id()))->fetchField();
     if ($num_nodes) {
         $caption = '<p>' . format_plural($num_nodes, '%type is used by 1 piece of content on your site. You can not remove this content type until you have removed all of the %type content.', '%type is used by @count pieces of content on your site. You may not remove %type until you have removed all of the %type content.', array('%type' => $this->entity->label())) . '</p>';
         $form['#title'] = $this->getQuestion();
         $form['description'] = array('#markup' => $caption);
         return $form;
     }
     return parent::buildForm($form, $form_state);
 }
Beispiel #10
0
 function title()
 {
     if (!$this->argument) {
         $title = \Drupal::config('user.settings')->get('anonymous');
     } else {
         $title = $this->database->query('SELECT u.name FROM {users} u WHERE u.uid = :uid', array(':uid' => $this->argument))->fetchField();
     }
     if (empty($title)) {
         return t('No user');
     }
     return String::checkPlain($title);
 }
Beispiel #11
0
 /**
  * {@inheritdoc}
  */
 public function save($source, $alias, $langcode = LanguageInterface::LANGCODE_NOT_SPECIFIED, $pid = NULL)
 {
     if ($source[0] !== '/') {
         throw new \InvalidArgumentException(sprintf('Source path %s has to start with a slash.', $source));
     }
     if ($alias[0] !== '/') {
         throw new \InvalidArgumentException(sprintf('Alias path %s has to start with a slash.', $alias));
     }
     $fields = array('source' => $source, 'alias' => $alias, 'langcode' => $langcode);
     // Insert or update the alias.
     if (empty($pid)) {
         $try_again = FALSE;
         try {
             $query = $this->connection->insert(static::TABLE)->fields($fields);
             $pid = $query->execute();
         } catch (\Exception $e) {
             // If there was an exception, try to create the table.
             if (!($try_again = $this->ensureTableExists())) {
                 // If the exception happened for other reason than the missing table,
                 // propagate the exception.
                 throw $e;
             }
         }
         // Now that the table has been created, try again if necessary.
         if ($try_again) {
             $query = $this->connection->insert(static::TABLE)->fields($fields);
             $pid = $query->execute();
         }
         $fields['pid'] = $pid;
         $operation = 'insert';
     } else {
         // Fetch the current values so that an update hook can identify what
         // exactly changed.
         try {
             $original = $this->connection->query('SELECT source, alias, langcode FROM {url_alias} WHERE pid = :pid', array(':pid' => $pid))->fetchAssoc();
         } catch (\Exception $e) {
             $this->catchException($e);
             $original = FALSE;
         }
         $fields['pid'] = $pid;
         $query = $this->connection->update(static::TABLE)->fields($fields)->condition('pid', $pid);
         $pid = $query->execute();
         $fields['original'] = $original;
         $operation = 'update';
     }
     if ($pid) {
         // @todo Switch to using an event for this instead of a hook.
         $this->moduleHandler->invokeAll('path_' . $operation, array($fields));
         Cache::invalidateTags(['route_match']);
         return $fields;
     }
     return FALSE;
 }
Beispiel #12
0
 function title()
 {
     if (!$this->argument) {
         $title = \Drupal::config('user.settings')->get('anonymous');
     } else {
         $title = $this->database->query('SELECT name FROM {users_field_data} WHERE uid = :uid AND default_langcode = 1', array(':uid' => $this->argument))->fetchField();
     }
     if (empty($title)) {
         return $this->t('No user');
     }
     return $title;
 }
 /**
  * @param Profile $profile
  * @param int $qid
  *
  * @return JsonResponse
  */
 public function explainAction(Profile $profile, $qid)
 {
     $query = $this->getQuery($profile, $qid);
     $data = [];
     $result = $this->database->query('EXPLAIN ' . $query['query'], (array) $query['args'])->fetchAllAssoc('table');
     $i = 1;
     foreach ($result as $row) {
         foreach ($row as $key => $value) {
             $data[$i][$key] = $value;
         }
         $i++;
     }
     return new JsonResponse(['data' => $data]);
 }
Beispiel #14
0
 /**
  * {@inheritdoc}
  */
 public function updateIndex(NodeInterface $node)
 {
     $nid = $node->id();
     $count = $this->database->query("SELECT COUNT(cid) FROM {comment_field_data} c INNER JOIN {forum_index} i ON c.entity_id = i.nid WHERE c.entity_id = :nid AND c.field_name = 'comment_forum' AND c.entity_type = 'node' AND c.status = :status AND c.default_langcode = 1", array(':nid' => $nid, ':status' => CommentInterface::PUBLISHED))->fetchField();
     if ($count > 0) {
         // Comments exist.
         $last_reply = $this->database->queryRange("SELECT cid, name, created, uid FROM {comment_field_data} WHERE entity_id = :nid AND field_name = 'comment_forum' AND entity_type = 'node' AND status = :status AND default_langcode = 1 ORDER BY cid DESC", 0, 1, array(':nid' => $nid, ':status' => CommentInterface::PUBLISHED))->fetchObject();
         $this->database->update('forum_index')->fields(array('comment_count' => $count, 'last_comment_timestamp' => $last_reply->created))->condition('nid', $nid)->execute();
     } else {
         // Comments do not exist.
         // @todo This should be actually filtering on the desired node language
         $this->database->update('forum_index')->fields(array('comment_count' => 0, 'last_comment_timestamp' => $node->getCreatedTime()))->condition('nid', $nid)->execute();
     }
 }
Beispiel #15
0
 /**
  * {@inheritdoc}
  */
 public function read($sid)
 {
     global $user;
     // Handle the case of first time visitors and clients that don't store
     // cookies (eg. web crawlers).
     $insecure_session_name = $this->sessionManager->getInsecureName();
     $cookies = $this->requestStack->getCurrentRequest()->cookies;
     if (!$cookies->has($this->getName()) && !$cookies->has($insecure_session_name)) {
         $user = new UserSession();
         return '';
     }
     // Otherwise, if the session is still active, we have a record of the
     // client's session in the database. If it's HTTPS then we are either have a
     // HTTPS session or we are about to log in so we check the sessions table
     // for an anonymous session with the non-HTTPS-only cookie. The session ID
     // that is in the user's cookie is hashed before being stored in the
     // database as a security measure. Thus, we have to hash it to match the
     // database.
     if ($this->requestStack->getCurrentRequest()->isSecure()) {
         // Try to load a session using the HTTPS-only secure session id.
         $values = $this->connection->query("SELECT u.*, s.* FROM {users} u INNER JOIN {sessions} s ON u.uid = s.uid WHERE s.ssid = :ssid", array(':ssid' => Crypt::hashBase64($sid)))->fetchAssoc();
         if (!$values) {
             // Fallback and try to load the anonymous non-HTTPS session. Use the
             // non-HTTPS session id as the key.
             if ($cookies->has($insecure_session_name)) {
                 $values = $this->connection->query("SELECT u.*, s.* FROM {users} u INNER JOIN {sessions} s ON u.uid = s.uid WHERE s.sid = :sid AND s.uid = 0", array(':sid' => Crypt::hashBase64($cookies->get($insecure_session_name))))->fetchAssoc();
             }
         }
     } else {
         // Try to load a session using the non-HTTPS session id.
         $values = $this->connection->query("SELECT u.*, s.* FROM {users} u INNER JOIN {sessions} s ON u.uid = s.uid WHERE s.sid = :sid", array(':sid' => Crypt::hashBase64($sid)))->fetchAssoc();
     }
     // We found the client's session record and they are an authenticated,
     // active user.
     if ($values && $values['uid'] > 0 && $values['status'] == 1) {
         // Add roles element to $user.
         $rids = $this->connection->query("SELECT ur.rid FROM {users_roles} ur WHERE ur.uid = :uid", array(':uid' => $values['uid']))->fetchCol();
         $values['roles'] = array_merge(array(DRUPAL_AUTHENTICATED_RID), $rids);
         $user = new UserSession($values);
     } elseif ($values) {
         // The user is anonymous or blocked. Only preserve two fields from the
         // {sessions} table.
         $user = new UserSession(array('session' => $values['session'], 'access' => $values['access']));
     } else {
         // The session has expired.
         $user = new UserSession();
     }
     return $user->session;
 }
Beispiel #16
0
 /**
  * Override the behavior of title(). Get the title of the revision.
  */
 public function titleQuery()
 {
     $titles = array();
     $results = $this->database->query('SELECT nr.vid, nr.nid, npr.title FROM {node_revision} nr WHERE nr.vid IN ( :vids[] )', array(':vids[]' => $this->value))->fetchAllAssoc('vid', PDO::FETCH_ASSOC);
     $nids = array();
     foreach ($results as $result) {
         $nids[] = $result['nid'];
     }
     $nodes = $this->nodeStorage->loadMultiple(array_unique($nids));
     foreach ($results as $result) {
         $nodes[$result['nid']]->set('title', $result['title']);
         $titles[] = String::checkPlain($nodes[$result['nid']]->label());
     }
     return $titles;
 }
Beispiel #17
0
 /**
  * Override the behavior of title(). Get the title of the revision.
  */
 public function titleQuery()
 {
     $titles = array();
     $results = $this->database->query('SELECT nr.vid, nr.stid, npr.title FROM {support_ticket_revision} nr WHERE nr.vid IN ( :vids[] )', array(':vids[]' => $this->value))->fetchAllAssoc('vid', PDO::FETCH_ASSOC);
     $stids = array();
     foreach ($results as $result) {
         $stids[] = $result['stid'];
     }
     $support_tickets = $this->supportTicketStorage->loadMultiple(array_unique($stids));
     foreach ($results as $result) {
         $support_tickets[$result['stid']]->set('title', $result['title']);
         $titles[] = SafeMarkup::checkPlain($support_tickets[$result['stid']]->label());
     }
     return $titles;
 }
 public function preRender(&$values)
 {
     $user = \Drupal::currentUser();
     if ($user->isAnonymous() || empty($values)) {
         return;
     }
     $nids = array();
     $ids = array();
     foreach ($values as $id => $result) {
         $nids[] = $result->{$this->aliases['nid']};
         $values[$id]->{$this->field_alias} = 0;
         // Create a reference so we can find this record in the values again.
         if (empty($ids[$result->{$this->aliases['nid']}])) {
             $ids[$result->{$this->aliases['nid']}] = array();
         }
         $ids[$result->{$this->aliases['nid']}][] = $id;
     }
     if ($nids) {
         $result = $this->database->query("SELECT n.nid, COUNT(c.cid) as num_comments FROM {node} n INNER JOIN {comment_field_data} c ON n.nid = c.entity_id AND c.entity_type = 'node' AND c.default_langcode = 1\n        LEFT JOIN {history} h ON h.nid = n.nid AND h.uid = :h_uid WHERE n.nid IN (:nids)\n        AND c.changed > GREATEST(COALESCE(h.timestamp, :timestamp), :timestamp) AND c.status = :status GROUP BY n.nid", array(':status' => CommentInterface::PUBLISHED, ':h_uid' => $user->id(), ':nids' => $nids, ':timestamp' => HISTORY_READ_LIMIT));
         foreach ($result as $node) {
             foreach ($ids[$node->id()] as $id) {
                 $values[$id]->{$this->field_alias} = $node->num_comments;
             }
         }
     }
 }
 /**
  * Implements Drupal\Core\Lock\LockBackedInterface::lockMayBeAvailable().
  */
 public function lockMayBeAvailable($name)
 {
     $lock = $this->database->query('SELECT expire, value FROM {semaphore} WHERE name = :name', array(':name' => $name))->fetchAssoc();
     if (!$lock) {
         return TRUE;
     }
     $expire = (double) $lock['expire'];
     $now = microtime(TRUE);
     if ($now > $expire) {
         // We check two conditions to prevent a race condition where another
         // request acquired the lock and set a new expire time. We add a small
         // number to $expire to avoid errors with float to string conversion.
         return (bool) $this->database->delete('semaphore')->condition('name', $name)->condition('value', $lock['value'])->condition('expire', 0.0001 + $expire, '<=')->execute();
     }
     return FALSE;
 }
 /**
  * {@inheritdoc}
  */
 public function getAllCollectionNames()
 {
     try {
         return $this->connection->query('SELECT DISTINCT collection FROM {' . $this->connection->escapeTable($this->table) . '} WHERE collection <> :collection ORDER by collection', array(':collection' => StorageInterface::DEFAULT_COLLECTION))->fetchCol();
     } catch (\Exception $e) {
         return array();
     }
 }
 /**
  * {@inheritdoc}
  */
 public function buildConfigurationForm(array $form, FormStateInterface $form_state)
 {
     $description = t('The username of the user to which you would like to assign ownership.');
     $count = $this->connection->query("SELECT COUNT(*) FROM {users}")->fetchField();
     // Use dropdown for fewer than 200 users; textbox for more than that.
     if (intval($count) < 200) {
         $options = array();
         $result = $this->connection->query("SELECT uid, name FROM {users_field_data} WHERE uid > 0 AND default_langcode = 1 ORDER BY name");
         foreach ($result as $data) {
             $options[$data->uid] = $data->name;
         }
         $form['owner_uid'] = array('#type' => 'select', '#title' => t('Username'), '#default_value' => $this->configuration['owner_uid'], '#options' => $options, '#description' => $description);
     } else {
         $form['owner_uid'] = array('#type' => 'entity_autocomplete', '#title' => t('Username'), '#target_type' => 'user', '#selection_setttings' => array('include_anonymous' => FALSE), '#default_value' => User::load($this->configuration['owner_uid']), '#validate_reference' => FALSE, '#size' => '6', '#maxlength' => '60', '#description' => $description);
     }
     return $form;
 }
 /**
  * Loads record from database.
  *
  * @param int $id
  *   The ID of the record.
  *
  * @return array
  *   The database record.
  *
  * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
  */
 protected function loadRecord($id)
 {
     $record = $this->dbConnection->query('SELECT * FROM {example_foo} WHERE id = :id', [':id' => $id])->fetchAssoc();
     if (!$record) {
         throw new NotFoundHttpException('The record was not found.');
     }
     return $record;
 }
Beispiel #23
0
 /**
  * Returns the UserSession object for the given session.
  *
  * @param \Symfony\Component\HttpFoundation\Session\SessionInterface $session
  *   The session.
  *
  * @return \Drupal\Core\Session\AccountInterface|NULL
  *   The UserSession object for the current user, or NULL if this is an
  *   anonymous session.
  */
 protected function getUserFromSession(SessionInterface $session)
 {
     if ($uid = $session->get('uid')) {
         // @todo Load the User entity in SessionHandler so we don't need queries.
         // @see https://www.drupal.org/node/2345611
         $values = $this->connection->query('SELECT * FROM {users_field_data} u WHERE u.uid = :uid AND u.default_langcode = 1', [':uid' => $uid])->fetchAssoc();
         // Check if the user data was found and the user is active.
         if (!empty($values) && $values['status'] == 1) {
             // Add the user's roles.
             $rids = $this->connection->query('SELECT roles_target_id FROM {user__roles} WHERE entity_id = :uid', [':uid' => $values['uid']])->fetchCol();
             $values['roles'] = array_merge([AccountInterface::AUTHENTICATED_ROLE], $rids);
             return new UserSession($values);
         }
     }
     // This is an anonymous session.
     return NULL;
 }
Beispiel #24
0
 /**
  * {@inheritdoc}
  */
 public function numberOfItems()
 {
     try {
         return $this->connection->query('SELECT COUNT(item_id) FROM {' . static::TABLE_NAME . '} WHERE name = :name', array(':name' => $this->name))->fetchField();
     } catch (\Exception $e) {
         $this->catchException($e);
         // If there is no table there cannot be any items.
         return 0;
     }
 }
Beispiel #25
0
 /**
  * Create a new table from a Drupal table definition.
  *
  * @param $name
  *   The name of the table to create.
  * @param $table
  *   A Schema API table definition array.
  *
  * @throws \Drupal\Core\Database\SchemaObjectExistsException
  *   If the specified table already exists.
  */
 public function createTable($name, $table)
 {
     if ($this->tableExists($name)) {
         throw new SchemaObjectExistsException(t('Table @name already exists.', array('@name' => $name)));
     }
     $statements = $this->createTableSql($name, $table);
     foreach ($statements as $statement) {
         $this->connection->query($statement);
     }
 }
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     $this->nodeStorage->deleteRevision($this->revision->getRevisionId());
     $this->logger('content')->notice('@type: deleted %title revision %revision.', array('@type' => $this->revision->bundle(), '%title' => $this->revision->label(), '%revision' => $this->revision->getRevisionId()));
     $node_type = $this->nodeTypeStorage->load($this->revision->bundle())->label();
     drupal_set_message(t('Revision from %revision-date of @type %title has been deleted.', array('%revision-date' => format_date($this->revision->getRevisionCreationTime()), '@type' => $node_type, '%title' => $this->revision->label())));
     $form_state->setRedirect('entity.node.canonical', array('node' => $this->revision->id()));
     if ($this->connection->query('SELECT COUNT(DISTINCT vid) FROM {node_field_revision} WHERE nid = :nid', array(':nid' => $this->revision->id()))->fetchField() > 1) {
         $form_state->setRedirect('entity.node.version_history', array('node' => $this->revision->id()));
     }
 }
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, array &$form_state)
 {
     $this->nodeStorage->deleteRevision($this->revision->getRevisionId());
     watchdog('content', '@type: deleted %title revision %revision.', array('@type' => $this->revision->bundle(), '%title' => $this->revision->label(), '%revision' => $this->revision->getRevisionId()));
     $node_type = $this->nodeTypeStorage->load($this->revision->bundle())->label();
     drupal_set_message(t('Revision from %revision-date of @type %title has been deleted.', array('%revision-date' => format_date($this->revision->getRevisionCreationTime()), '@type' => $node_type, '%title' => $this->revision->label())));
     $form_state['redirect_route'] = array('route_name' => 'node.view', 'route_parameters' => array('node' => $this->revision->id()));
     if ($this->connection->query('SELECT COUNT(DISTINCT vid) FROM {node_field_revision} WHERE nid = :nid', array(':nid' => $this->revision->id()))->fetchField() > 1) {
         $form_state['redirect_route']['route_name'] = 'node.revision_overview';
     }
 }
 /**
  * Implements Drupal\Core\KeyValueStore\KeyValueStoreInterface::getAll().
  */
 public function getAll()
 {
     $result = $this->connection->query('SELECT name, value FROM {' . $this->connection->escapeTable($this->table) . '} WHERE collection = :collection', array(':collection' => $this->collection));
     $values = array();
     foreach ($result as $item) {
         if ($item) {
             $values[$item->name] = $this->serializer->decode($item->value);
         }
     }
     return $values;
 }
Beispiel #29
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.name, u.uid FROM {watchdog} w INNER JOIN {users} u ON w.uid = u.uid WHERE w.wid = :id', array(':id' => $event_id))->fetchObject()) {
         $severity = watchdog_severity_levels();
         $message = $this->formatMessage($dblog);
         $username = array('#theme' => 'username', '#account' => user_load($dblog->uid));
         $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), l($dblog->location, $dblog->location)), array(array('data' => $this->t('Referrer'), 'header' => TRUE), l($dblog->referer, $dblog->referer)), 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), String::checkPlain($dblog->hostname)), array(array('data' => $this->t('Operations'), 'header' => TRUE), $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 #30
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), SafeMarkup::checkPlain($dblog->hostname)), array(array('data' => $this->t('Operations'), 'header' => TRUE), SafeMarkup::checkAdminXss($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;
 }