コード例 #1
0
ファイル: AliasStorage.php プロジェクト: ddrozdik/dmaps
 /**
  * {@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;
 }
コード例 #2
0
ファイル: BatchStorage.php プロジェクト: aWEBoLabs/taxi
 /**
  * {@inheritdoc}
  */
 public function update(array $batch)
 {
     try {
         $this->connection->update('batch')->fields(array('batch' => serialize($batch)))->condition('bid', $batch['id'])->execute();
     } catch (\Exception $e) {
         $this->catchException($e);
     }
 }
コード例 #3
0
 /**
  * {@inheritdoc}
  */
 public function update($entry)
 {
     $count = NULL;
     try {
         $count = $this->connection->update('dbtng_example')->fields($entry)->condition('pid', $entry['pid'])->execute();
     } catch (\Exception $e) {
         drupal_set_message(t('db_update failed. Message = %message, query= %query', array('%message' => $e->getMessage(), '%query' => $e->query_string)), 'error');
     }
     return $count;
 }
コード例 #4
0
ファイル: ForumIndexStorage.php プロジェクト: aWEBoLabs/taxi
 /**
  * {@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();
     }
 }
コード例 #5
0
  /**
   * Decrements count of flagged entities.
   *
   * @param \Drupal\flag\Event\FlaggingEvent $event
   *   The flagging Event.
   */
  public function decrementFlagCounts(FlaggingEvent $event) {

    /* @var \Drupal\flag\FlaggingInterface flag */
    $flag = $event->getFlag();
    /* @var \Drupal\Core\Entity\EntityInterface $entity */
    $entity = $event->getEntity();

    $count_result = $this->connection->select('flag_counts')
      ->fields(NULL, ['flag_id', 'entity_id', 'entity_type', 'count'])
      ->condition('flag_id', $flag->id())
      ->condition('entity_id', $entity->id())
      ->condition('entity_type', $entity->getEntityTypeId())
      ->execute()
      ->fetchAll();
    if ($count_result[0]->count == '1') {
      $this->connection->delete('flag_counts')
        ->condition('flag_id', $flag->id())
        ->condition('entity_id', $entity->id())
        ->condition('entity_type', $entity->getEntityTypeId())
        ->execute();
    }
    else {
      $this->connection->update('flag_counts')
        ->expression('count', 'count - 1')
        ->condition('flag_id', $flag->id())
        ->condition('entity_id', $entity->id())
        ->condition('entity_type', $entity->getEntityTypeId())
        ->execute();
    }
    $this->resetLoadedCounts($entity, $flag);
  }
コード例 #6
0
 /**
  * Checks whether the string version matches a given version, fix it if not.
  *
  * @param \Drupal\locale\StringInterface $string
  *   The string object.
  * @param string $version
  *   Drupal version to check against.
  */
 protected function checkVersion($string, $version)
 {
     if ($string->getId() && $string->getVersion() != $version) {
         $string->setVersion($version);
         $this->connection->update('locales_source', $this->options)->condition('lid', $string->getId())->fields(array('version' => $version))->execute();
     }
 }
コード例 #7
0
 /**
  * {@inheritdoc}
  */
 public function update(CommentInterface $comment)
 {
     // Allow bulk updates and inserts to temporarily disable the maintenance of
     // the {comment_entity_statistics} table.
     if (!$this->state->get('comment.maintain_entity_statistics')) {
         return;
     }
     $query = $this->database->select('comment_field_data', 'c');
     $query->addExpression('COUNT(cid)');
     $count = $query->condition('c.entity_id', $comment->getCommentedEntityId())->condition('c.entity_type', $comment->getCommentedEntityTypeId())->condition('c.field_name', $comment->getFieldName())->condition('c.status', CommentInterface::PUBLISHED)->condition('default_langcode', 1)->execute()->fetchField();
     if ($count > 0) {
         // Comments exist.
         $last_reply = $this->database->select('comment_field_data', 'c')->fields('c', array('cid', 'name', 'changed', 'uid'))->condition('c.entity_id', $comment->getCommentedEntityId())->condition('c.entity_type', $comment->getCommentedEntityTypeId())->condition('c.field_name', $comment->getFieldName())->condition('c.status', CommentInterface::PUBLISHED)->condition('default_langcode', 1)->orderBy('c.created', 'DESC')->range(0, 1)->execute()->fetchObject();
         // Use merge here because entity could be created before comment field.
         $this->database->merge('comment_entity_statistics')->fields(array('cid' => $last_reply->cid, 'comment_count' => $count, 'last_comment_timestamp' => $last_reply->changed, 'last_comment_name' => $last_reply->uid ? '' : $last_reply->name, 'last_comment_uid' => $last_reply->uid))->keys(array('entity_id' => $comment->getCommentedEntityId(), 'entity_type' => $comment->getCommentedEntityTypeId(), 'field_name' => $comment->getFieldName()))->execute();
     } else {
         // Comments do not exist.
         $entity = $comment->getCommentedEntity();
         // Get the user ID from the entity if it's set, or default to the
         // currently logged in user.
         if ($entity instanceof EntityOwnerInterface) {
             $last_comment_uid = $entity->getOwnerId();
         }
         if (!isset($last_comment_uid)) {
             // Default to current user when entity does not implement
             // EntityOwnerInterface or author is not set.
             $last_comment_uid = $this->currentUser->id();
         }
         $this->database->update('comment_entity_statistics')->fields(array('cid' => 0, 'comment_count' => 0, 'last_comment_timestamp' => $entity instanceof EntityChangedInterface ? $entity->getChangedTime() : REQUEST_TIME, 'last_comment_name' => '', 'last_comment_uid' => $last_comment_uid))->condition('entity_id', $comment->getCommentedEntityId())->condition('entity_type', $comment->getCommentedEntityTypeId())->condition('field_name', $comment->getFieldName())->execute();
     }
     // Reset the cache of the commented entity so that when the entity is loaded
     // the next time, the statistics will be loaded again.
     $this->entityManager->getStorage($comment->getCommentedEntityTypeId())->resetCache(array($comment->getCommentedEntityId()));
 }
コード例 #8
0
 /**
  * {@inheritdoc}
  */
 public function acquire($name, $timeout = 30.0)
 {
     // Insure that the timeout is at least 1 ms.
     $timeout = max($timeout, 0.001);
     $expire = microtime(TRUE) + $timeout;
     if (isset($this->locks[$name])) {
         // Try to extend the expiration of a lock we already acquired.
         $success = (bool) $this->database->update('semaphore')->fields(array('expire' => $expire))->condition('name', $name)->condition('value', $this->getLockId())->execute();
         if (!$success) {
             // The lock was broken.
             unset($this->locks[$name]);
         }
         return $success;
     } else {
         // Optimistically try to acquire the lock, then retry once if it fails.
         // The first time through the loop cannot be a retry.
         $retry = FALSE;
         // We always want to do this code at least once.
         do {
             try {
                 $this->database->insert('semaphore')->fields(array('name' => $name, 'value' => $this->getLockId(), 'expire' => $expire))->execute();
                 // We track all acquired locks in the global variable.
                 $this->locks[$name] = TRUE;
                 // We never need to try again.
                 $retry = FALSE;
             } catch (IntegrityConstraintViolationException $e) {
                 // Suppress the error. If this is our first pass through the loop,
                 // then $retry is FALSE. In this case, the insert failed because some
                 // other request acquired the lock but did not release it. We decide
                 // whether to retry by checking lockMayBeAvailable(). This will clear
                 // the offending row from the database table in case it has expired.
                 $retry = $retry ? FALSE : $this->lockMayBeAvailable($name);
             } catch (\Exception $e) {
                 // Create the semaphore table if it does not exist and retry.
                 if ($this->ensureTableExists()) {
                     // Retry only once.
                     $retry = !$retry;
                 } else {
                     throw $e;
                 }
             }
             // We only retry in case the first attempt failed, but we then broke
             // an expired lock.
         } while ($retry);
     }
     return isset($this->locks[$name]);
 }
コード例 #9
0
 /**
  * Implements Drupal\Core\Cache\CacheBackendInterface::invalidateAll().
  */
 public function invalidateAll()
 {
     try {
         $this->connection->update($this->bin)->fields(array('expire' => REQUEST_TIME - 1))->execute();
     } catch (\Exception $e) {
         $this->catchException($e);
     }
 }
コード例 #10
0
 /**
  * Tests that exceptions thrown by workers are handled properly.
  */
 public function testExceptions()
 {
     // Get the queue to test the normal Exception.
     $queue = $this->container->get('queue')->get('cron_queue_test_exception');
     // Enqueue an item for processing.
     $queue->createItem(array($this->randomMachineName() => $this->randomMachineName()));
     // Run cron; the worker for this queue should throw an exception and handle
     // it.
     $this->cron->run();
     $this->assertEqual(\Drupal::state()->get('cron_queue_test_exception'), 1);
     // The item should be left in the queue.
     $this->assertEqual($queue->numberOfItems(), 1, 'Failing item still in the queue after throwing an exception.');
     // Expire the queue item manually. system_cron() relies in REQUEST_TIME to
     // find queue items whose expire field needs to be reset to 0. This is a
     // Kernel test, so REQUEST_TIME won't change when cron runs.
     // @see system_cron()
     // @see \Drupal\Core\Cron::processQueues()
     $this->connection->update('queue')->condition('name', 'cron_queue_test_exception')->fields(['expire' => REQUEST_TIME - 1])->execute();
     $this->cron->run();
     $this->assertEqual(\Drupal::state()->get('cron_queue_test_exception'), 2);
     $this->assertEqual($queue->numberOfItems(), 0, 'Item was processed and removed from the queue.');
     // Get the queue to test the specific SuspendQueueException.
     $queue = $this->container->get('queue')->get('cron_queue_test_broken_queue');
     // Enqueue several item for processing.
     $queue->createItem('process');
     $queue->createItem('crash');
     $queue->createItem('ignored');
     // Run cron; the worker for this queue should process as far as the crashing
     // item.
     $this->cron->run();
     // Only one item should have been processed.
     $this->assertEqual($queue->numberOfItems(), 2, 'Failing queue stopped processing at the failing item.');
     // Check the items remaining in the queue. The item that throws the
     // exception gets released by cron, so we can claim it again to check it.
     $item = $queue->claimItem();
     $this->assertEqual($item->data, 'crash', 'Failing item remains in the queue.');
     $item = $queue->claimItem();
     $this->assertEqual($item->data, 'ignored', 'Item beyond the failing item remains in the queue.');
     // Test the requeueing functionality.
     $queue = $this->container->get('queue')->get('cron_queue_test_requeue_exception');
     $queue->createItem([]);
     $this->cron->run();
     $this->assertEqual(\Drupal::state()->get('cron_queue_test_requeue_exception'), 2);
     $this->assertFalse($queue->numberOfItems());
 }
コード例 #11
0
 /**
  * {@inheritdoc}
  */
 public function write(Profile $profile)
 {
     $args = ['token' => $profile->getToken(), 'parent' => $profile->getParentToken(), 'data' => base64_encode(serialize($profile->getCollectors())), 'ip' => $profile->getIp(), 'method' => $profile->getMethod(), 'url' => $profile->getUrl(), 'time' => $profile->getTime(), 'created_at' => time()];
     try {
         $query = $this->database->select('webprofiler', 'w')->fields('w', ['token']);
         $query->condition('token', $profile->getToken());
         $count = $query->countQuery()->execute()->fetchAssoc();
         if ($count['expression']) {
             $this->database->update('webprofiler')->fields($args)->condition('token', $profile->getToken())->execute();
         } else {
             $this->database->insert('webprofiler')->fields($args)->execute();
         }
         $status = TRUE;
     } catch (\Exception $e) {
         $status = FALSE;
     }
     return $status;
 }
コード例 #12
0
 /**
  * {@inheritdoc}
  */
 public function regenerate($destroy = FALSE, $lifetime = NULL)
 {
     global $user;
     // Nothing to do if we are not allowed to change the session.
     if (!$this->isEnabled() || $this->isCli()) {
         return;
     }
     // We do not support the optional $destroy and $lifetime parameters as long
     // as #2238561 remains open.
     if ($destroy || isset($lifetime)) {
         throw new \InvalidArgumentException('The optional parameters $destroy and $lifetime of SessionManager::regenerate() are not supported currently');
     }
     $is_https = $this->requestStack->getCurrentRequest()->isSecure();
     $cookies = $this->requestStack->getCurrentRequest()->cookies;
     if ($is_https && $this->isMixedMode()) {
         $insecure_session_name = $this->getInsecureName();
         $params = session_get_cookie_params();
         $session_id = Crypt::randomBytesBase64();
         // If a session cookie lifetime is set, the session will expire
         // $params['lifetime'] seconds from the current request. If it is not set,
         // it will expire when the browser is closed.
         $expire = $params['lifetime'] ? REQUEST_TIME + $params['lifetime'] : 0;
         setcookie($insecure_session_name, $session_id, $expire, $params['path'], $params['domain'], FALSE, $params['httponly']);
         $cookies->set($insecure_session_name, $session_id);
     }
     if ($this->isStarted()) {
         $old_session_id = $this->getId();
     }
     session_id(Crypt::randomBytesBase64());
     $this->getMetadataBag()->clearCsrfTokenSeed();
     if (isset($old_session_id)) {
         $params = session_get_cookie_params();
         $expire = $params['lifetime'] ? REQUEST_TIME + $params['lifetime'] : 0;
         setcookie($this->getName(), $this->getId(), $expire, $params['path'], $params['domain'], $params['secure'], $params['httponly']);
         $fields = array('sid' => Crypt::hashBase64($this->getId()));
         if ($is_https) {
             $fields['ssid'] = Crypt::hashBase64($this->getId());
             // If the "secure pages" setting is enabled, use the newly-created
             // insecure session identifier as the regenerated sid.
             if ($this->isMixedMode()) {
                 $fields['sid'] = Crypt::hashBase64($session_id);
             }
         }
         $this->connection->update('sessions')->fields($fields)->condition($is_https ? 'ssid' : 'sid', Crypt::hashBase64($old_session_id))->execute();
     }
     if (!$this->isStarted()) {
         // Start the session when it doesn't exist yet.
         // Preserve the logged in user, as it will be reset to anonymous
         // by \Drupal\Core\Session\SessionHandler::read().
         $account = $user;
         $this->startNow();
         $user = $account;
     }
     date_default_timezone_set(drupal_get_user_timezone());
 }
コード例 #13
0
ファイル: DatabaseQueue.php プロジェクト: aWEBoLabs/taxi
 /**
  * {@inheritdoc}
  */
 public function garbageCollection()
 {
     try {
         // Clean up the queue for failed batches.
         $this->connection->delete(static::TABLE_NAME)->condition('created', REQUEST_TIME - 864000, '<')->condition('name', 'drupal_batch:%', 'LIKE')->execute();
         // Reset expired items in the default queue implementation table. If that's
         // not used, this will simply be a no-op.
         $this->connection->update(static::TABLE_NAME)->fields(array('expire' => 0))->condition('expire', 0, '<>')->condition('expire', REQUEST_TIME, '<')->execute();
     } catch (\Exception $e) {
         $this->catchException($e);
     }
 }
コード例 #14
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;
 }
コード例 #15
0
ファイル: AliasStorage.php プロジェクト: anatalsceo/en-classe
 /**
  * {@inheritdoc}
  */
 public function save($source, $alias, $langcode = LanguageInterface::LANGCODE_NOT_SPECIFIED, $pid = NULL)
 {
     $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 {
         $fields['pid'] = $pid;
         $query = $this->connection->update('url_alias')->fields($fields)->condition('pid', $pid);
         $pid = $query->execute();
         $operation = 'update';
     }
     if ($pid) {
         // @todo Switch to using an event for this instead of a hook.
         $this->moduleHandler->invokeAll('path_' . $operation, array($fields));
         return $fields;
     }
     return FALSE;
 }
コード例 #16
0
 /**
  * Implements Drupal\file\FileUsage\FileUsageInterface::delete().
  */
 public function delete(FileInterface $file, $module, $type = NULL, $id = NULL, $count = 1)
 {
     // Delete rows that have a exact or less value to prevent empty rows.
     $query = $this->connection->delete($this->tableName)->condition('module', $module)->condition('fid', $file->id());
     if ($type && $id) {
         $query->condition('type', $type)->condition('id', $id);
     }
     if ($count) {
         $query->condition('count', $count, '<=');
     }
     $result = $query->execute();
     // If the row has more than the specified count decrement it by that number.
     if (!$result && $count > 0) {
         $query = $this->connection->update($this->tableName)->condition('module', $module)->condition('fid', $file->id());
         if ($type && $id) {
             $query->condition('type', $type)->condition('id', $id);
         }
         $query->expression('count', 'count - :count', array(':count' => $count));
         $query->execute();
     }
     parent::delete($file, $module, $type, $id, $count);
 }
コード例 #17
0
ファイル: MenuTreeStorage.php プロジェクト: ddrozdik/dmaps
 /**
  * Sets has_children for the link's parent if it has visible children.
  *
  * @param array $link
  *   The link to get a parent ID from.
  */
 protected function updateParentalStatus(array $link)
 {
     // If parent is empty, there is nothing to update.
     if (!empty($link['parent'])) {
         // Check if at least one visible child exists in the table.
         $query = $this->connection->select($this->table, $this->options);
         $query->addExpression('1');
         $query->range(0, 1);
         $query->condition('menu_name', $link['menu_name'])->condition('parent', $link['parent'])->condition('enabled', 1);
         $parent_has_children = (bool) $query->execute()->fetchField() ? 1 : 0;
         $this->connection->update($this->table, $this->options)->fields(array('has_children' => $parent_has_children))->condition('id', $link['parent'])->execute();
     }
 }
コード例 #18
0
ファイル: Subscription.php プロジェクト: alnutile/drunatra
 /**
  * {@inheritdoc}
  */
 public function setSubscription(array &$data)
 {
     if (isset($data['lease']) && is_numeric($data['lease'])) {
         $data['expires'] = (int) REQUEST_TIME + $data['lease'];
     } else {
         // @todo Change schema to allow NULL values.
         $data['lease'] = 0;
         $data['expires'] = 0;
     }
     // Updating an existing subscription.
     if ($this->hasSubscription($data['id'])) {
         unset($data['created']);
         $this->connection->update($this->table)->fields($data)->condition('id', $data['id'])->execute();
         return FALSE;
     } else {
         $data['secret'] = Crypt::randomStringHashed(55);
         $data['token'] = Crypt::randomStringHashed(55);
         $data['created'] = REQUEST_TIME;
         $this->connection->insert($this->table)->fields($data)->execute();
         return TRUE;
     }
 }
コード例 #19
0
 /**
  * {@inheritdoc}
  */
 public function write($sid, $value)
 {
     global $user;
     // The exception handler is not active at this point, so we need to do it
     // manually.
     try {
         if (!$this->sessionManager->isEnabled()) {
             // We don't have anything to do if we are not allowed to save the
             // session.
             return TRUE;
         }
         // Either ssid or sid or both will be added from $key below.
         $fields = array('uid' => $user->id(), 'hostname' => $this->requestStack->getCurrentRequest()->getClientIP(), 'session' => $value, 'timestamp' => REQUEST_TIME);
         // Use the session ID as 'sid' and an empty string as 'ssid' by default.
         // read() does not allow empty strings so that's a safe default.
         $key = array('sid' => Crypt::hashBase64($sid), 'ssid' => '');
         // On HTTPS connections, use the session ID as both 'sid' and 'ssid'.
         if ($this->requestStack->getCurrentRequest()->isSecure()) {
             $key['ssid'] = Crypt::hashBase64($sid);
             $cookies = $this->requestStack->getCurrentRequest()->cookies;
             // The "secure pages" setting allows a site to simultaneously use both
             // secure and insecure session cookies. If enabled and both cookies
             // are presented then use both keys. The session ID from the cookie is
             // hashed before being stored in the database as a security measure.
             if ($this->sessionManager->isMixedMode()) {
                 $insecure_session_name = $this->sessionManager->getInsecureName();
                 if ($cookies->has($insecure_session_name)) {
                     $key['sid'] = Crypt::hashBase64($cookies->get($insecure_session_name));
                 }
             }
         } elseif ($this->sessionManager->isMixedMode()) {
             unset($key['ssid']);
         }
         $this->connection->merge('sessions')->keys($key)->fields($fields)->execute();
         // Likewise, do not update access time more than once per 180 seconds.
         if ($user->isAuthenticated() && REQUEST_TIME - $user->getLastAccessedTime() > Settings::get('session_write_interval', 180)) {
             $this->connection->update('users')->fields(array('access' => REQUEST_TIME))->condition('uid', $user->id())->execute();
         }
         return TRUE;
     } catch (\Exception $exception) {
         require_once DRUPAL_ROOT . '/core/includes/errors.inc';
         // If we are displaying errors, then do so with no possibility of a
         // further uncaught exception being thrown.
         if (error_displayable()) {
             print '<h1>Uncaught exception thrown in session handler.</h1>';
             print '<p>' . Error::renderExceptionSafe($exception) . '</p><hr />';
         }
         return FALSE;
     }
 }
コード例 #20
0
 /**
  * Updates record.
  *
  * @param int $id
  *   The ID of the record.
  * @param array $record
  *   The record to validate.
  * @param array $defaults
  *   (optional) Default values for the record.
  *
  * @return \Drupal\rest\ModifiedResourceResponse
  *   The HTTP response object.
  */
 protected function updateRecord($id, $record, $defaults = [])
 {
     // Make sure the record already exists.
     $this->loadRecord($id);
     $this->validate($record);
     $record += $defaults;
     // Record ID should never be changed.
     unset($record['id']);
     $this->dbConnection->update('example_foo')->fields($record)->condition('id', $id)->execute();
     $this->logger->notice('Record @id has been updated', ['@id' => $id]);
     // Return the updated record in the response body.
     $updated_record = $this->loadRecord($id);
     return new ModifiedResourceResponse($updated_record, 200);
 }
コード例 #21
0
ファイル: BookOutlineStorage.php プロジェクト: ddrozdik/dmaps
 /**
  * {@inheritdoc}
  */
 public function updateMovedChildren($bid, $original, $expressions, $shift)
 {
     $query = $this->connection->update('book');
     $query->fields(array('bid' => $bid));
     foreach ($expressions as $expression) {
         $query->expression($expression[0], $expression[1], $expression[2]);
     }
     $query->expression('depth', 'depth + :depth', array(':depth' => $shift));
     $query->condition('bid', $original['bid']);
     $p = 'p1';
     for ($i = 1; !empty($original[$p]); $p = 'p' . ++$i) {
         $query->condition($p, $original[$p]);
     }
     return $query->execute();
 }
コード例 #22
0
ファイル: BookManager.php プロジェクト: anatalsceo/en-classe
 /**
  * Updates the has_children flag of the parent of the original node.
  *
  * This method is called when a book link is moved or deleted. So we want to
  * update the has_children flag of the parent node.
  *
  * @param array $original
  *   The original link whose parent we want to update.
  *
  * @return bool
  *   TRUE if the update was successful (either there was no original parent to
  *   update, or the original parent was updated successfully), FALSE on
  *   failure.
  */
 protected function updateOriginalParent(array $original)
 {
     if ($original['pid'] == 0) {
         // There were no parents of this link. Nothing to update.
         return TRUE;
     }
     // Check if $original had at least one child.
     $original_number_of_children = $this->connection->select('book', 'b')->condition('bid', $original['bid'])->condition('pid', $original['pid'])->condition('nid', $original['nid'], '<>')->countQuery()->execute()->fetchField();
     $parent_has_children = (bool) $original_number_of_children ? 1 : 0;
     // Update the parent. If the original link did not have children, then the
     // parent now does not have children. If the original had children, then the
     // the parent has children now (still).
     $query = $this->connection->update('book');
     $query->fields(array('has_children' => $parent_has_children))->condition('nid', $original['pid']);
     return $query->execute();
 }
コード例 #23
0
 /**
  * {@inheritdoc}
  */
 public function rename($key, $new_key)
 {
     $this->connection->update($this->table)->fields(array('name' => $new_key))->condition('collection', $this->collection)->condition('name', $key)->execute();
 }
コード例 #24
0
ファイル: SessionManager.php プロジェクト: ddrozdik/dmaps
 /**
  * Migrates the current session to a new session id.
  *
  * @param string $old_session_id
  *   The old session id. The new session id is $this->getId() unless
  *   $new_insecure_session_id is not empty.
  */
 protected function migrateStoredSession($old_session_id)
 {
     $fields = array('sid' => Crypt::hashBase64($this->getId()));
     $this->connection->update('sessions')->fields($fields)->condition('sid', Crypt::hashBase64($old_session_id))->execute();
 }
コード例 #25
0
 /**
  * Fixes anonymous user on MySQL.
  *
  * MySQL import might have set the uid of the anonymous user to autoincrement
  * value. Let's try fixing it. See http://drupal.org/node/204411
  */
 public function fixAnonymousUid()
 {
     $this->database->update('users')->expression('uid', 'uid - uid')->condition('name', '')->condition('pass', '')->condition('status', 0)->execute();
 }
コード例 #26
0
 /**
  * {@inheritdoc}
  */
 public function onFieldDefinitionDelete(FieldDefinitionInterface $field_definition)
 {
     $table_mapping = $this->getTableMapping();
     $storage_definition = $field_definition->getFieldStorageDefinition();
     // Mark field data as deleted.
     if ($table_mapping->requiresDedicatedTableStorage($storage_definition)) {
         $table_name = $table_mapping->getDedicatedDataTableName($storage_definition);
         $revision_name = $table_mapping->getDedicatedRevisionTableName($storage_definition);
         $this->database->update($table_name)->fields(array('deleted' => 1))->condition('bundle', $field_definition->getTargetBundle())->execute();
         if ($this->entityType->isRevisionable()) {
             $this->database->update($revision_name)->fields(array('deleted' => 1))->condition('bundle', $field_definition->getTargetBundle())->execute();
         }
     }
 }
コード例 #27
0
ファイル: DatabaseQueue.php プロジェクト: ddrozdik/dmaps
 /**
  * {@inheritdoc}
  */
 public function releaseItem($item)
 {
     $update = $this->connection->update('queue')->fields(array('expire' => 0))->condition('item_id', $item->item_id);
     return $update->execute();
 }
コード例 #28
0
 /**
  * {@inheritdoc}
  */
 public function onBundleRename($bundle, $bundle_new)
 {
     // The method runs before the field definitions are updated, so we use the
     // old bundle name.
     $field_definitions = $this->entityManager->getFieldDefinitions($this->entityTypeId, $bundle);
     // We need to handle deleted fields too. For now, this only makes sense for
     // configurable fields, so we use the specific API.
     // @todo Use the unified store of deleted field definitions instead in
     //   https://www.drupal.org/node/2282119
     $field_definitions += entity_load_multiple_by_properties('field_instance_config', array('entity_type' => $this->entityTypeId, 'bundle' => $bundle, 'deleted' => TRUE, 'include_deleted' => TRUE));
     foreach ($field_definitions as $field_definition) {
         $storage_definition = $field_definition->getFieldStorageDefinition();
         if ($this->usesDedicatedTable($storage_definition)) {
             $is_deleted = $this->storageDefinitionIsDeleted($storage_definition);
             $table_name = static::_fieldTableName($storage_definition, $is_deleted);
             $revision_name = static::_fieldRevisionTableName($storage_definition, $is_deleted);
             $this->database->update($table_name)->fields(array('bundle' => $bundle_new))->condition('bundle', $bundle)->execute();
             $this->database->update($revision_name)->fields(array('bundle' => $bundle_new))->condition('bundle', $bundle)->execute();
         }
     }
 }
コード例 #29
0
 /**
  * {@inheritdoc}
  */
 public function releaseClaim($payment_id, $acquisition_code)
 {
     return (bool) $this->database->update('payment_queue', array('return' => Database::RETURN_AFFECTED))->condition('payment_id', $payment_id)->condition('acquisition_code', $acquisition_code)->condition('queue_id', $this->queueId)->fields(array('claimed' => 0))->execute();
 }
コード例 #30
0
 /**
  * {@inheritdoc}
  */
 public function updateMails($msids, array $data)
 {
     $this->connection->update('simplenews_mail_spool')->condition('msid', (array) $msids, 'IN')->fields(array('status' => $data['status'], 'error' => isset($result['error']) ? (int) $data['error'] : 0, 'timestamp' => REQUEST_TIME))->execute();
 }