/** * @inheritdoc */ public function save(UserInterface $account, $provider, $authname, $data = NULL) { if (!is_scalar($data)) { $data = serialize($data); } $this->connection->merge('authmap')->keys(array('uid' => $account->id(), 'provider' => $provider))->fields(array('authname' => $authname, 'data' => $data))->execute(); }
/** * Implements \Drupal\user\UserDataInterface::set(). */ public function set($module, $uid, $name, $value) { $serialized = 0; if (!is_scalar($value)) { $value = serialize($value); $serialized = 1; } $this->connection->merge('users_data')->keys(array('uid' => $uid, 'module' => $module, 'name' => $name))->fields(array('value' => $value, 'serialized' => $serialized))->execute(); }
/** * {@inheritdoc} */ public function write($sid, $value) { $user = \Drupal::currentUser(); // The exception handler is not active at this point, so we need to do it // manually. try { $fields = array('uid' => $user->id(), 'hostname' => $this->requestStack->getCurrentRequest()->getClientIP(), 'session' => $value, 'timestamp' => REQUEST_TIME); $this->connection->merge('sessions')->keys(array('sid' => Crypt::hashBase64($sid)))->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)) { /** @var \Drupal\user\UserStorageInterface $storage */ $storage = \Drupal::entityManager()->getStorage('user'); $storage->updateLastAccessTimestamp($user, REQUEST_TIME); } 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; } }
/** * {@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())); }
/** * {@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'] = $key['sid']; // 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(); $cookies = $this->requestStack->getCurrentRequest()->cookies; 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(); // Remove obsolete sessions. $this->cleanupObsoleteSessions(); // 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)) { /** @var \Drupal\user\UserStorageInterface $storage */ $storage = \Drupal::entityManager()->getStorage('user'); $storage->updateLastAccessTimestamp($user, REQUEST_TIME); } 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; } }
/** * {@inheritdoc} */ public function write($sid, $value) { // The exception handler is not active at this point, so we need to do it // manually. try { $request = $this->requestStack->getCurrentRequest(); $fields = array('uid' => $request->getSession()->get('uid', 0), 'hostname' => $request->getClientIP(), 'session' => $value, 'timestamp' => REQUEST_TIME); $this->connection->merge('sessions')->keys(array('sid' => Crypt::hashBase64($sid)))->fields($fields)->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; } }
/** * {@inheritdoc} */ public function invalidateTags(array $tags) { try { foreach ($tags as $tag) { // Only invalidate tags once per request unless they are written again. if (isset($this->invalidatedTags[$tag])) { continue; } $this->invalidatedTags[$tag] = TRUE; unset($this->tagCache[$tag]); $this->connection->merge('cachetags')->insertFields(array('invalidations' => 1))->expression('invalidations', 'invalidations + 1')->key('tag', $tag)->execute(); } } catch (\Exception $e) { // Create the cache table, which will be empty. This fixes cases during // core install where cache tags are invalidated before the table is // created. if (!$this->ensureTableExists()) { $this->catchException($e); } } }
/** * Actually set the cache. */ protected function doSet($cid, $data, $expire, $tags) { $fields = array('created' => round(microtime(TRUE), 3), 'expire' => $expire, 'tags' => implode(' ', $tags), 'checksum' => $this->checksumProvider->getCurrentChecksum($tags)); if (!is_string($data)) { $fields['data'] = serialize($data); $fields['serialized'] = 1; } else { $fields['data'] = $data; $fields['serialized'] = 0; } $this->connection->merge($this->bin)->key('cid', $this->normalizeCid($cid))->fields($fields)->execute(); }
/** * Updates string object in the database. * * @param \Drupal\locale\StringInterface $string * The string object. * * @return bool|int * If the record update failed, returns FALSE. If it succeeded, returns * SAVED_NEW or SAVED_UPDATED. * * @throws \Drupal\locale\StringStorageException * If the string is not suitable for this storage, an exception is thrown. */ protected function dbStringUpdate($string) { if ($string->isSource()) { $values = $string->getValues(array('source', 'context', 'version')); } elseif ($string->isTranslation()) { $values = $string->getValues(array('translation', 'customized')); } if (!empty($values) && ($keys = $this->dbStringKeys($string))) { return $this->connection->merge($this->dbStringTable($string), $this->options)->keys($keys)->fields($values)->execute(); } else { throw new StringStorageException('The string cannot be updated: ' . $string->getString()); } }
/** * {@inheritdoc} */ public function submitForm(array &$form, FormStateInterface $form_state) { try { $name = $form_state->getValue('name'); $result = $this->connection->merge('phonebook')->key('pbid', $form_state->getValue('pbid'))->insertFields(['created' => REQUEST_TIME])->fields(['changed' => REQUEST_TIME, 'name' => $name, 'phone' => $form_state->getValue('phone')])->execute(); if ($result === Merge::STATUS_INSERT) { drupal_set_message($this->t('New entry added for %name.', ['%name' => $name])); } elseif ($result === Merge::STATUS_UPDATE) { drupal_set_message($this->t('Updated entry for %name.', ['%name' => $name])); } } catch (\Exception $e) { drupal_set_message($this->t('Something went wrong, please try again later!'), 'error'); } $form_state->setRedirect('d8phonebook.index'); }
/** * Increments count of flagged entities. * * @param \Drupal\flag\Event\FlaggingEvent $event * The flagging event. */ public function incrementFlagCounts(FlaggingEvent $event) { $this->connection->merge('flag_counts') ->key([ 'flag_id' => $event->getFlag()->id(), 'entity_id' => $event->getEntity()->id(), 'entity_type' => $event->getEntity()->getEntityTypeId(), ]) ->fields([ 'last_updated' => REQUEST_TIME, 'count' => 1, ]) ->expression('count', 'count + :inc', [':inc' => 1]) ->execute(); $this->resetLoadedCounts($event->getEntity(), $event->getFlag()); }
/** * Implements Drupal\Core\Cache\CacheBackendInterface::invalidateTags(). */ public function invalidateTags(array $tags) { try { $tag_cache =& drupal_static('Drupal\\Core\\Cache\\CacheBackendInterface::tagCache', array()); $invalidated_tags =& drupal_static('Drupal\\Core\\Cache\\DatabaseBackend::invalidatedTags', array()); foreach ($this->flattenTags($tags) as $tag) { // Only invalidate tags once per request unless they are written again. if (isset($invalidated_tags[$tag])) { continue; } $invalidated_tags[$tag] = TRUE; unset($tag_cache[$tag]); $this->connection->merge('cachetags')->insertFields(array('invalidations' => 1))->expression('invalidations', 'invalidations + 1')->key('tag', $tag)->execute(); } } catch (\Exception $e) { $this->catchException($e, 'cachetags'); } }
/** * Records the latest revision of a given entity. * * @param string $entity_type_id * The machine name of the type of entity. * @param string $entity_id * The Entity ID in question. * @param string $langcode * The langcode of the revision we're saving. Each language has its own * effective tree of entity revisions, so in different languages * different revisions will be "latest". * @param int $revision_id * The revision ID that is now the latest revision. * * @return int * One of the valid returns from a merge query's execute method. */ protected function recordLatestRevision($entity_type_id, $entity_id, $langcode, $revision_id) { return $this->connection->merge($this->tableName)->keys(['entity_type' => $entity_type_id, 'entity_id' => $entity_id, 'langcode' => $langcode])->fields(['revision_id' => $revision_id])->execute(); }
/** * Sets a module version and status. * * @param $module * @param $version * @param int $status */ public function setModuleVersion($module, $version, $status = 1) { $this->createTable('system'); $this->database->merge('system')->key(array('filename' => "modules/{$module}"))->fields(array('type' => 'module', 'name' => $module, 'schema_version' => $version, 'status' => $status))->execute(); }
/** * Helper method so we can re-try a write. * * @param string $name * The config name. * @param string $data * The config data, already dumped to a string. * * @return bool */ protected function doWrite($name, $data) { $options = array('return' => Database::RETURN_AFFECTED) + $this->options; return (bool) $this->connection->merge($this->table, $options)->keys(array('collection', 'name'), array($this->collection, $name))->fields(array('data' => $data))->execute(); }
/** * Implements Drupal\file\FileUsage\FileUsageInterface::add(). */ public function add(FileInterface $file, $module, $type, $id, $count = 1) { $this->connection->merge($this->tableName)->keys(array('fid' => $file->id(), 'module' => $module, 'type' => $type, 'id' => $id))->fields(array('count' => $count))->expression('count', 'count + :count', array(':count' => $count))->execute(); parent::add($file, $module, $type, $id, $count); }
/** * Implements Drupal\Core\KeyValueStore\KeyValueStoreInterface::setIfNotExists(). */ public function setIfNotExists($key, $value) { $result = $this->connection->merge($this->table)->insertFields(array('collection' => $this->collection, 'name' => $key, 'value' => $this->serializer->encode($value)))->condition('collection', $this->collection)->condition('name', $key)->execute(); return $result == Merge::STATUS_INSERT; }
/** * {@inheritdoc} */ public function banIp($ip) { $this->connection->merge('ban_ip')->key(array('ip' => $ip))->fields(array('ip' => $ip))->execute(); }