sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
public function read($count_bytes) {
// If we have data in the read_buffer then use it.
$readBuffer_size = strlen($this->read_buffer);
$bytes_available = $readBuffer_size - $this->buffer_read_position;
// If there are no more bytes available then get some.
if ($bytes_available === 0 && !$this->eof) {
// If we know the object size, check it first.
$object_bytes_read = $this->object_block_start_position +
$this->buffer_read_position;
if ($object_bytes_read === $this->object_total_length ||
!isset($this->next_read_position)) {
$this->eof = true;
return false;
}
if (!$this->fillReadBuffer($this->next_read_position)) {
return false;
}
// Re-calculate the number of bytes we can serve.
$readBuffer_size = strlen($this->read_buffer);
$bytes_available = $readBuffer_size - $this->buffer_read_position;
}
if ($bytes_available > 0) {
$bytes_to_read = min($bytes_available, $count_bytes);
$current_buffer_position = $this->buffer_read_position;
$this->buffer_read_position += $bytes_to_read;
return substr($this->read_buffer,
$current_buffer_position,
$bytes_to_read);
}
return false;
}
|
Read at most $count_bytes from the file.
If we have reached the end of the buffered amount, and there is more
data in the file then retreive more bytes from storage.
|
entailment
|
public function seek($offset, $whence) {
if ($whence == SEEK_END) {
if (isset($this->object_total_length)) {
$whence = SEEK_SET;
$offset = $this->object_total_length + $offset;
} else {
trigger_error("Unable to seek from end for objects with unknown size",
E_USER_WARNING);
return false;
}
}
if ($whence != SEEK_SET) {
trigger_error(sprintf("Unsupported seek mode: %d", $whence),
E_USER_WARNING);
return false;
}
// If we know the size, then make sure they are only seeking within it.
if (isset($this->object_total_length) &&
$offset >= $this->object_total_length) {
return false;
}
if ($offset < 0) {
return false;
}
// Clear EOF and work it out next time they read.
$this->eof = false;
// Check if we can seek inside the current buffer
$block_start = $this->object_block_start_position;
$buffer_end = $block_start + strlen($this->read_buffer);
if ($block_start <= $offset && $offset < $buffer_end) {
$this->buffer_read_position = $offset - $block_start;
} else {
$this->read_buffer = "";
$this->buffer_read_position = 0;
$this->next_read_position = $offset;
}
return true;
}
|
Seek within the current file. We expect the upper layers of PHP to convert
SEEK_CUR to SEEK_SET.
|
entailment
|
public function tell() {
if (strlen($this->read_buffer) == 0) {
return $this->next_read_position;
} else {
return $this->buffer_read_position + $this->object_block_start_position;
}
}
|
Having tell() at this level in the stack seems bonkers.
|
entailment
|
protected function makeHttpRequest($url, $method, $headers, $body = null) {
if (!$this->context_options['enable_cache']) {
return parent::makeHttpRequest($url, $method, $headers, $body);
}
$cache_key = static::getReadMemcacheKey($url, $headers['Range']);
$cache_obj = $this->memcache_client->get($cache_key);
if (false !== $cache_obj) {
if ($this->context_options['enable_optimistic_cache']) {
return $cache_obj;
} else {
$cache_etag = $this->getHeaderValue('ETag', $cache_obj['headers']);
if (array_key_exists('If-Match', $headers)) {
// We will perform a If-None-Match to validate the cache object, only
// if it has the same ETag value as what we are asking for.
if ($headers['If-Match'] === $cache_etag) {
unset($headers['If-Match']);
} else {
// We are asking for a different object that what is in the cache.
$cache_etag = null;
}
}
}
if (isset($cache_etag)) {
$headers['If-None-Match'] = $cache_etag;
}
}
$result = parent::makeHttpRequest($url, $method, $headers, $body);
if (false === $result) {
return false;
}
$status_code = $result['status_code'];
if (HttpResponse::NOT_MODIFIED === $result['status_code']) {
return $cache_obj;
}
if (in_array($status_code, self::$valid_status_codes)) {
$this->memcache_client->set($cache_key, $result, 0,
$this->context_options['read_cache_expiry_seconds']);
}
return $result;
}
|
Override the makeHttpRequest function so we can implement caching.
If caching is enabled then we try and retrieve a matching request for the
object name and range from memcache.
If we find a result in memcache, and optimistic caching is enabled then
we return that result immediately without checking if the object has
changed in GCS. Otherwise, we will issue a 'If-None-Match' request with
the ETag of the object to ensure it is still current.
Optimisitic caching is best suited when the application is soley updating
objects in cloud storage, as the cache can be invalidated when the object
is updated by the application.
|
entailment
|
private function fillReadBuffer($read_position) {
$headers = $this->getOAuthTokenHeader(parent::READ_SCOPE);
if ($headers === false) {
trigger_error("Unable to acquire OAuth token.", E_USER_WARNING);
return false;
}
$end_range = $read_position + parent::DEFAULT_READ_SIZE - 1;
$range = $this->getRangeHeader($read_position, $end_range);
$headers = array_merge($headers, $range);
// If we have an ETag from the first read then use it to ensure we are
// retrieving the same object.
if (isset($this->object_etag)) {
$headers["If-Match"] = $this->object_etag;
}
$http_response = $this->makeHttpRequest($this->url,
"GET",
$headers);
if ($http_response === false) {
trigger_error("Unable to connect to Google Cloud Storage Service.",
E_USER_WARNING);
return false;
}
$status_code = $http_response['status_code'];
if ($status_code === HttpResponse::NOT_FOUND) {
return false;
}
if ($status_code === HttpResponse::PRECONDITION_FAILED) {
trigger_error("Object content has changed.", E_USER_WARNING);
return false;
}
if (!in_array($status_code, self::$valid_status_codes)) {
trigger_error($this->getErrorMessage($status_code,
$http_response['body']),
E_USER_WARNING);
return false;
}
$this->read_buffer = $http_response['body'];
$this->buffer_read_position = 0;
$this->object_block_start_position = $read_position;
// If we got the complete object in the response then use the
// Content-Length
if ($status_code == HttpResponse::OK) {
$content_length = $this->getHeaderValue('Content-Length',
$http_response['headers']);
assert(isset($content_length));
$this->object_total_length = intval($content_length);
$this->next_read_position = null;
} else if ($status_code == HttpResponse::RANGE_NOT_SATISFIABLE) {
// We've read past the end of the object ... no more data.
$this->read_buffer = "";
$this->eof = true;
$this->next_read_position = null;
if (!isset($this->object_total_length)) {
$this->object_total_length = 0;
}
} else {
$content_range = $this->getHeaderValue('Content-Range',
$http_response['headers']);
assert(isset($content_range));
if (preg_match(parent::CONTENT_RANGE_REGEX, $content_range, $m) === 1) {
$this->next_read_position = intval($m[2]) + 1;
$this->object_total_length = intval($m[3]);
}
}
$this->metadata = self::extractMetaData($http_response['headers']);
$this->content_type = $this->getHeaderValue('Content-Type',
$http_response['headers']);
$this->object_etag =
$this->getHeaderValue('ETag', $http_response['headers']);
if (empty($this->stat_result)) {
$stat_args = ['size' => $this->object_total_length,
'mode' => parent::S_IFREG];
$last_modified = $this->getHeaderValue('Last-Modified',
$http_response['headers']);
if (isset($last_modified)) {
$unix_time = strtotime($last_modified);
if ($unix_time !== false) {
$stat_args["mtime"] = $unix_time;
}
}
$this->stat_result = $this->createStatArray($stat_args);
}
return true;
}
|
Fill our internal buffer with data, by making a http request to Google
Cloud Storage.
|
entailment
|
public static function getUserEnvironmentVariable($var_name) {
$result = getenv($var_name);
if ($result === false) {
$result = getenv(self::HTTP_X_APPENGINE . $var_name);
}
return $result;
}
|
Retrieve an environment variable specifically for the UserService.
Under managed VMs, the UserService environment variables are sent as
HTTP headers with the prefix 'HTTP_X_APPENGINE_'. This function first
checks if the environment variable is set, and if not checks if it is
set with the prefix string.
@param string $var_name The variable name to check.
@return The environment value, or false if not found.
|
entailment
|
public function write($id, $data) {
// TODO: Implement locking. b/7701850
return $this->memcacheContainer->set(
self::SESSION_PREFIX . $id, $data, $this->expire);
}
|
Write an element to Memcache with the given ID and data.
@param string $id Session ID associated with the data to be stored
@param string $data Data to be stored
@return bool true if successful, false otherwise
|
entailment
|
public static function configure($memcacheContainer = null) {
$handler = new MemcacheSessionHandler($memcacheContainer);
session_set_save_handler($handler, true);
/**
* Set so that it is clear that Memcache is being used for session handling,
* as retrieving session.save_handler just returns "user".
*/
session_save_path("Memcache");
}
|
Configure the session handler to use the Memcache API.
@param MemcacheContainer $memcacheContainer Optional, for mocking in tests
|
entailment
|
public static function signForApp($bytes_to_sign) {
$req = new SignForAppRequest();
$resp = new SignForAppResponse();
if (!is_string($bytes_to_sign)) {
throw new \InvalidArgumentException('$bytes_to_sign must be a string.');
}
$req->setBytesToSign($bytes_to_sign);
try {
ApiProxy::makeSyncCall(self::PACKAGE_NAME, 'SignForApp', $req, $resp);
} catch (ApplicationError $e) {
throw self::applicationErrorToException($e);
}
return [
'key_name' => $resp->getKeyName(),
'signature' => $resp->getSignatureBytes(),
];
}
|
Signs arbitrary byte array using per app private key.
@param string $bytes_to_sign The bytes to generate the signature for.
@throws \InvalidArgumentException If $bytes_to_sign is not a string.
@throws AppIdentityException If there is an error using the AppIdentity
service.
@return array An array containing the elements
'key_name' - the name of the key used to sign the bytes
'signature' - the signature of the bytes.
|
entailment
|
public static function getServiceAccountName() {
$req = new GetServiceAccountNameRequest();
$resp = new GetServiceAccountNameResponse();
try {
ApiProxy::makeSyncCall(self::PACKAGE_NAME, 'GetServiceAccountName', $req,
$resp);
} catch (ApplicationError $e) {
throw self::applicationErrorToException($e);
}
return $resp->getServiceAccountName();
}
|
Get the service account name for the application.
@throws AppIdentityException If there is an error using the AppIdentity
service.
@return string The service account name.
|
entailment
|
public static function getPublicCertificates() {
$req = new GetPublicCertificateForAppRequest();
$resp = new GetPublicCertificateForAppResponse();
try {
ApiProxy::makeSyncCall(self::PACKAGE_NAME, 'GetPublicCertificatesForApp',
$req, $resp);
} catch (ApplicationError $e) {
throw self::applicationErrorToException($e);
}
$result = [];
foreach ($resp->getPublicCertificateListList() as $cert) {
$result[] = new PublicCertificate($cert->getKeyName(),
$cert->getX509CertificatePem());
}
return $result;
}
|
Get the list of public certifates for the application.
@throws AppIdentityException If there is an error using the AppIdentity
service.
@return PublicCertificate[] An array of the applications public
certificates.
|
entailment
|
public static function getAccessToken($scopes) {
$cache_key = self::MEMCACHE_KEY_PREFIX . self::DOMAIN_SEPARATOR;
if (is_string($scopes)) {
$cache_key .= $scopes;
} else if (is_array($scopes)) {
$cache_key .= implode(self::DOMAIN_SEPARATOR, $scopes);
} else {
throw new \InvalidArgumentException(
'Invalid scope ' . htmlspecialchars($scopes));
}
$result = self::getTokenFromCache($cache_key);
if ($result === false) {
$result = self::getAccessTokenUncached($scopes);
// Cache the token.
self::putTokenInCache($cache_key,
$result,
$result['expiration_time']);
}
return $result;
}
|
Gets an OAuth2 access token for the application's service account from
the cache or generates and caches one by calling
getAccessTokenUncached($scopes)
Each application has an associated Google account. This function returns
OAuth2 access token corresponding to the running app. Access tokens are
safe to cache and reuse until they expire.
@param array $scopes The scopes to acquire the access token for.
Can be either a single string or an array of strings.
@throws \InvalidArgumentException If $scopes is not a string or an array of
strings.
@throws AppIdentityException If there is an error using the AppIdentity
service.
@return array An array with the following key/value pairs.
'access_token' - The access token for the application.
'expiration_time' - The expiration time for the access token.
|
entailment
|
private static function getAccessTokenUncached($scopes) {
$req = new GetAccessTokenRequest();
$resp = new GetAccessTokenResponse();
if (is_string($scopes)) {
$req->addScope($scopes);
} else if (is_array($scopes)) {
foreach($scopes as $scope) {
if (is_string($scope)) {
$req->addScope($scope);
} else {
throw new \InvalidArgumentException(
'Invalid scope ' . htmlspecialchars($scope));
}
}
} else {
throw new \InvalidArgumentException(
'Invalid scope ' . htmlspecialchars($scopes));
}
try {
ApiProxy::makeSyncCall(self::PACKAGE_NAME, 'GetAccessToken', $req, $resp);
} catch (ApplicationError $e) {
throw self::applicationErrorToException($e);
}
return [
'access_token' => $resp->getAccessToken(),
'expiration_time' => $resp->getExpirationTime(),
];
}
|
Get an OAuth2 access token for the applications service account without
caching the result. Usually getAccessToken($scopes) should be used instead
which calls this method and caches the result.
@param array $scopes The scopes to acquire the access token for.
Can be either a single string or an array of strings.
@throws InvalidArgumentException If $scopes is not a string or an array of
strings.
@throws AppIdentityException If there is an error using the AppIdentity
service.
@return array An array with the following key/value pairs.
'access_token' - The access token for the application.
'expiration_time' - The expiration time for the access token.
|
entailment
|
public static function getApplicationId() {
$app_id = getenv("APPLICATION_ID");
$psep = strpos($app_id, self::PARTITION_SEPARATOR);
if ($psep > 0) {
$app_id = substr($app_id, $psep + 1);
}
return $app_id;
}
|
Get the application id of an app.
@return string The application id of the app.
|
entailment
|
private static function putTokenInCache($name, $value, $expiry_secs) {
$expiry_time_from_epoch = $expiry_secs - self::EXPIRY_SAFETY_MARGIN_SECS -
self::EXPIRY_SHORT_MARGIN_SECS;
$memcache = new \Memcache();
$memcache->set($name, $value, null, $expiry_time_from_epoch);
// Record the expiry time in the object being cached, so we can check it
// when read from APC.
self::putTokenInApc($name, $value, $expiry_secs);
}
|
Add an access token to the cache.
@param string $name The name of the token to add to the cache.
@param mixed $value An assoicative array containing the token and the
expiration time.
@param int $expiry_secs The unix time since epoch when the value should
expire.
@access private
|
entailment
|
private static function putTokenInApc($name, $value, $expiry_secs) {
$expiry_time_from_epoch = $expiry_secs - self::EXPIRY_SAFETY_MARGIN_SECS -
self::EXPIRY_SHORT_MARGIN_SECS;
$cache_ttl = self::getTTLForToken($expiry_time_from_epoch);
$value['eviction_time_epoch'] = $cache_ttl['eviction_time_epoch'];
apc_store($name, $value, $cache_ttl['apc_ttl_in_seconds']);
}
|
Put an access token into the in process cache.
@param string $name The name of the token to add to the cache.
@param mixed $value An assoicative array containing the token and the
expiration time.
@param int $expiry_secs The unix time since epoch when the value should
expire.
@access private
|
entailment
|
private static function getTokenFromCache($name) {
$success = false;
$result = apc_fetch($name, $success);
if ($success && time() < $result['eviction_time_epoch']) {
unset($result['eviction_time_epoch']);
return $result;
}
$memcache = new \Memcache();
$result = $memcache->get($name);
// If there was a result in memcache but not in apc we can add using a
// short timeout.
if ($result !== false) {
self::putTokenInApc($name, $result, $result['expiration_time']);
}
return $result;
}
|
Retrieve an access token from the cache.
@param $name String name of the token to retrieve.
@return mixed The value of the token if it is stored in the cache,
otherise false.
@access private
|
entailment
|
private static function applicationErrorToException($application_error) {
switch ($application_error->getApplicationError()) {
case ErrorCode::UNKNOWN_SCOPE:
return new \InvalidArgumentException('An unknown scope was supplied.');
case ErrorCode::BLOB_TOO_LARGE:
return new \InvalidArgumentException('The supplied blob was too long.');
case ErrorCode::DEADLINE_EXCEEDED:
return new AppIdentityException(
'The deadline for the call was exceeded.');
case ErrorCode::NOT_A_VALID_APP:
return new AppIdentityException('The application is not valid.');
case ErrorCode::UNKNOWN_ERROR:
return new AppIdentityException(
'There was an unknown error using the AppIdentity service.');
case ErrorCode::GAIAMINT_NOT_INITIAILIZED:
return new AppIdentityException(
'There was a GAIA error using the AppIdentity service.');
case ErrorCode::NOT_ALLOWED:
return new AppIdentityException('The call is not allowed.');
default:
return new AppIdentityException(
'The AppIdentity service threw an unexpected error.');
}
}
|
Converts an application error to the service specific exception.
@param ApplicationError $application_error The application error
@return mixed An exception that corresponds to the application error.
@access private
|
entailment
|
public static function move_uploaded_file($filename, $destination,
array $context_options = null) {
// move_uploaded_file() does not support moving a file between two different
// stream wrappers. Other file handling functions like rename() have the
// same problem, but copy() works since it explicitly sends the contents to
// the new source. As such move_uploaded_file() is replaced by
// is_uploaded_file(), copy(), and unlink() the old file.
//
// This also supports upload proxying during which the file may be remotely
// located and referenced by a stream wrapper. In that case $filename may be
// something like gs://... and $destination public://... which may end up on
// the same remote filesystem, but PHP does not make the distinction. Of
// course, this also means the file can be moved between two different file
// systems.
//
// In the simple case gs:// to gs:// rename() will be called first and
// invoke the more performant operation.
if (is_uploaded_file($filename)) {
// Either use the user provided context options, otherwise use the default
// context with the Content-Type overridden.
if ($context_options !== null) {
$context = stream_context_create($context_options);
} else {
// Default to content type provided in $_FILES array.
$context = stream_context_get_default([
'gs' => ['Content-Type' => static::lookupContentType($filename)],
]);
}
// Attempt rename() which is less expensive if the origin and destination
// use the same stream wrapper, otherwise perform copy() and unlink().
if (@rename($filename, $destination, $context)) {
static::removeUploadedFile($filename);
return true;
}
if (copy($filename, $destination, $context) &&
unlink($filename, $context)) {
static::removeUploadedFile($filename);
return true;
}
}
return false;
}
|
Moves an uploaded file to a new location.
@param string $filename
The filename of the uploaded file.
@param string $destination
The destination of the moved file.
@param array $context_options
An associative array of stream context options. The options will be
merged with defaults and passed to stream_context_create().
@see http://php.net/move_uploaded_file
|
entailment
|
private static function lookupContentType($filename) {
foreach ($_FILES as $file) {
if ($file['tmp_name'] == $filename) {
return $file['type'] ?: static::DEFAULT_CONTENT_TYPE;
}
}
return static::DEFAULT_CONTENT_TYPE;
}
|
Lookup the content type associated with an uploaded file.
@param string $filename
The filename of the uploaded file.
@return
Content type associated with filename, otherwise DEFAULT_CONTENT_TYPE.
|
entailment
|
public static function tempnam($dir, $prefix) {
// Force $dir into a VFS temp path if it's not already one.
$temp_root = static::sys_get_temp_dir();
if (!StringUtil::startsWith($dir, $temp_root)) {
$dir = $temp_root . '/' . str_replace('\\', '/', $dir);
}
// Create all intermediate directories if needed.
@mkdir($dir, 0777, true);
// Generate a unique non-existing file name.
for ($retry = 0; $retry < 10 || file_exists($filename); $retry++) {
$filename = $dir . '/' . uniqid($prefix, true);
}
if (file_exists($filename)) {
trigger_error('Fail to generate a unique name for the temporary file',
E_USER_ERROR);
return false;
}
// tempnam requires the file to be created with permission set to 0600.
if (touch($filename) === false ||
chmod($filename, static::DEFAULT_TMPFILE_MODE) === false) {
trigger_error('Fail to create and change permission of temporary file ' .
$filename, E_USER_ERROR);
return false;
}
return $filename;
}
|
Create file with unique file name.
@param string $dir
The directory where the temporary filename will be created.
@param string $prefix
The prefix of the generated temporary filename.
@return bool|string
a string with the new temporary file name on success, otherwise FALSE.
@see http://php.net/manual/en/function.tempnam.php
|
entailment
|
public function addByKey($server_key,
$key,
$value,
$expiration = 0) {
return $this->add($key, $value, $expiration);
}
|
Memcached::addByKey() is functionally equivalent to Memcached::add(),
except that the free-form server_key can be used to map the key to a
specific server. This is useful if you need to keep a bunch of related keys
on a certain server.
@see Memcached::add()
@param string $server_key This parameter is ignored.
@param string $key The key under which to store the value.
@param mixed $value The value to store.
@param int $expiration The expiration time, defaults to 0.
@return bool true on success, false on failure.
|
entailment
|
public function appendByKey(string $server_key, string $key, string $value) {
return $this->append($key, $value);
}
|
@see Memcached::append().
@param string $server_key This parameter is ignored.
@param string $key The key under which to append the value.
@param string $value The value to append
@result bool Returns true on success or false on failure.
|
entailment
|
public function cas($cas_token, $key, $value, $expiration = 0) {
$key = $this->getPrefixKey($key);
$request = new MemcacheSetRequest();
$response = new MemcacheSetResponse();
$memcache_flag = 0;
$serialized_value = MemcacheUtils::serializeValue($value, $memcache_flag);
$item = $request->addItem();
$item->setKey($key);
$item->setValue($serialized_value);
$item->setFlags($memcache_flag);
$item->setSetPolicy(SetPolicy::CAS);
$item->setCasId($cas_token);
$item->setExpirationTime($expiration);
try {
ApiProxy::makeSyncCall('memcache', 'Set', $request, $response);
} catch (Error $e) {
$this->result_code = self::RES_FAILURE;
return false;
}
switch ($response->getSetStatusList()[0]) {
case SetStatusCode::STORED:
$this->result_code = self::RES_SUCCESS;
return true;
case SetStatusCode::NOT_STORED:
$this->result_code = self::RES_NOTSTORED;
return false;
case SetStatusCode::EXISTS:
$this->result_code = self::RES_DATA_EXISTS;
return false;
default:
$this->result_code = self::RES_FAILURE;
return false;
}
}
|
Performs a set and check operation, so that the item will be stored only
if no other client has updated it since it was last fetched by this
client.
@param mixed $cas_token Unique memcached assigned value.
@param string $key The key under which to store the value.
@param mixed $value The value to store.
@param int $expiration The expiration time, defaults to 0.
@return bool True on success, or false on failure.
|
entailment
|
public function casByKey($cas_token,
$server_key,
$key,
$value,
$expiration = 0) {
return cas($cas_token, $key, $value, $expiration);
}
|
@see Memcached::cas().
@param mixed $cas_token Unique memcached assigned value.
@param string $server_key Ignored.
@param string $key The key under which to store the value.
@param mixed $value The value to store.
@param int $expiration The expiration time, defaults to 0.
@return bool True on success, or false on failure.
|
entailment
|
public function decrement($key,
$offset = 1,
$initial_value = 0,
$expiration = 0) {
return $this->incrementInternal($key, $offset, $initial_value, $expiration,
false);
}
|
Decrements a numeric item's value by $offset.
@param string $key The key under which to store the value.
@param int $offset The amount by which to decrement the item's value.
@param int $initial_value The value to set the item to if it does not
currently exist.
@param int $expiration The expiration time, defaults to 0.
@return bool True on success, or false on failure.
|
entailment
|
public function decrementByKey($server_key,
$key,
$offset = 1,
$initial_value = 0,
$expiration = 0) {
return $this->incrementInternal($key, $offset, $initial_value, $expiration,
false);
}
|
@see Memcached::decrement().
@param string $server_key This parameter is ignored.
@param string $key The key under which to store the value.
@param int $offset The amount by which to decrement the item's value.
@param int $initial_value The value to set the item to if it does not
currently exist.
@param int $expiration The expiration time, defaults to 0.
@return bool True on success, or false on failure.
|
entailment
|
public function deleteMulti($keys, $time = 0) {
$request = new MemcacheDeleteRequest();
$response = new MemcacheDeleteResponse();
foreach($keys as $key) {
$key = $this->getPrefixKey($key);
$item = $request->addItem();
$item->setKey($key);
$item->setDeleteTime($time);
}
try {
ApiProxy::makeSyncCall('memcache', 'Delete', $request, $response);
} catch (Error $e) {
$this->result_code = self::RES_FAILURE;
return false;
}
foreach($response->getDeleteStatusList() as $status) {
if ($status == DeleteStatusCode::NOT_FOUND) {
$this->result_code = self::RES_NOTFOUND;
return false;
}
}
$this->result_code = self::RES_SUCCESS;
return true;
}
|
deletes an array of $keys from the server.
@param array $keys The keys to delete from the server.
@param int $time The time parameter is the amount of time in seconds the
client wishes the server to refuse add and replace commands for this key.
@return bool true on success or false on failure.
|
entailment
|
public function fetchAll() {
if (!empty($this->delayed_results)) {
$result = $this->delayed_results;
$this->delayed_results = array();
return $result;
} else {
return false;
}
}
|
Fetch all of the remaining results from the last getDelayed() request.
Note that currently getDelayed is a synchronous call.
@return array The remaining results, or false if there are no results.
|
entailment
|
public function flush($delay = 0) {
$result = $this->memcache->flush();
$this->result_code = $result ? self::RES_SUCCESS : self::RES_NOTSTORED;
return $result;
}
|
Invalidates all existing cache items immediately.
@param int $delay This parameter is ignored.
@return bool true on success, or false on failure.
|
entailment
|
public function get($key, $cache_cb = null, &$cas_token = null) {
// Not re-using getMulti to avoid messing with multiple result arrays for
// cas tokens.
$request = new MemcacheGetRequest();
$response = new MemcacheGetResponse();
$key = $this->getPrefixKey($key);
$request->addKey($key);
// Only way to check if we were passed a $cas_token is checking the number
// of passed in arguments.
if (func_num_args() == 3) {
$request->setForCas(true);
}
try {
ApiProxy::makeSyncCall('memcache', 'Get', $request, $response);
} catch (Error $e) {
$this->result_code = self::RES_FAILURE;
return false;
}
$result = $response->getItemList();
// If the get failed, and if a read through cache callback has been set
// then call it now. $result is pass-by-ref and will contain the new value.
if (empty($result) && !is_null($cache_cb) && is_null($cas_token)) {
$cb_result = $cache_cb($this, $key, $new_result);
if ($cb_result) {
// TODO: What to do if this set fails?
$this->memcache->set($key, $new_result);
$this->result_code = self::RES_SUCCESS;
return $new_result;
} else {
$this->result_code = self::RES_FAILURE;
return false;
}
} else if (!empty($result)) {
$item = $result[0];
if ($item->hasCasId()) {
$cas_token = $item->getCasId();
}
$this->result_code = self::RES_SUCCESS;
try {
return MemcacheUtils::deserializeValue($item->getValue(),
$item->getFlags());
} catch (\UnexpectedValueException $e) {
$this->result_code = self::RES_NOTFOUND;
return false;
}
} else {
$this->result_code = self::RES_NOTFOUND;
return false;
}
}
|
Returns the item that was previously stored under the $key.
@param string $key The key under which to store the value.
@param callable $cache_cb Read through caching callback.
@param mixed $cas_token The variable to store the CAS token in. This value
is opaque to the application.
@return the value stored in the cache of false if there was a failure.
|
entailment
|
public function getByKey($server_key, $key, $cache_cb, &$cas_token) {
return $this->get($key, $cache_cb, $cas_token);
}
|
@see Memcache::get().
@param string $server_key This parameter is ignored.
@param string $key The key under which to store the value.
@param callable $cache_cb Read through caching callback.
@param mixed $cas_token The variable to store the CAS token in. This value
is opaque to the application.
@return the value stored in the cache of false if there was a failure.
|
entailment
|
public function getDelayed($keys, $with_cas=false, $value_cb=null) {
// Clear any previous delayed results.
$this->delayed_results = array();
$cas_tokens = null;
if ($with_cas) {
$results = $this->getMulti($keys, $cas_tokens);
} else {
$results = $this->getMulti($keys);
}
if (!$results) {
return false;
}
foreach($results as $key => $value) {
$val = ['key' => $key, 'value' => $value];
if (!empty($cas_tokens)) {
$cas = array_shift($cas_tokens);
$val['cas'] = $cas;
}
$this->delayed_results[] = $val;
}
if (isset($value_cb)) {
foreach($this->delayed_results as $result) {
$value_cb($result);
}
}
return true;
}
|
Issues a request to memcache for multiple items the keys of which are
specified in the keys array.
Currently this method executes synchronously.
@param array $keys Array of keys to retrieve.
@param bool $with_cas If true, retrieve the CAS tokens for the keys.
@param callable $value_cb The result callback.
@return bool true on success, or false on failure.
|
entailment
|
public function getDelayedByKey($server_key,
$keys,
$with_cas = false,
$value_cb = null) {
return $this->getDelayed($keys, $with_cas, $value_cb);
}
|
@see getDelayedByKey.
@param string $server_key This parameter is ignored.
@param array $keys Array of keys to retrieve.
@param bool $with_cas If true, retrieve the CAS tokens for the keys.
@param callable $value_cb The result callback.
@return bool true on success, or false on failure.
|
entailment
|
public function getMulti($keys, &$cas_tokens = null, $flags = 0) {
$request = new MemcacheGetRequest();
$response = new MemcacheGetResponse();
foreach ($keys as $key) {
$key = $this->getPrefixKey($key);
$request->addKey($key);
}
// Need to check the number of arguments passed to the function to see if
// the user wants cas_tokens.
if (func_num_args() > 1) {
$request->setForCas(true);
}
try {
ApiProxy::makeSyncCall('memcache', 'Get', $request, $response);
} catch (Error $e) {
$this->result_code = self::RES_FAILURE;
return false;
}
$return_value = array();
foreach ($response->getItemList() as $item) {
try {
$return_value[$item->getKey()] = MemcacheUtils::deserializeValue(
$item->getValue(), $item->getFlags());
} catch (\UnexpectedValueException $e) {
// Skip entries that cannot be deserialized.
continue;
}
if ($item->hasCasId()) {
$cas_tokens[$item->getKey()] = $item->getCasId();
}
}
// If GET_PRESERVE_ORDER was set then we need to ensure that
// a. Keys are returned in the order that they we asked for.
// b. If a key has no value then return null for that key.
if ($flags == self::GET_PRESERVE_ORDER) {
$ordered_result = [];
$ordered_cas_tokens = [];
foreach ($keys as $key) {
if (array_key_exists($key, $return_value)) {
$ordered_result[$key] = $return_value[$key];
if (array_key_exists($key, $cas_tokens)) {
$ordered_cas_tokens[$key] = $cas_tokens[$key];
} else {
$ordered_cas_tokens[$key] = null;
}
} else {
$ordered_result[$key] = null;
$ordered_cas_tokens[$key] = null;
}
}
$return_value = $ordered_result;
if (func_num_args() > 1) {
$cas_tokens = $ordered_cas_tokens;
}
}
return $return_value;
}
|
Similar to Memcached::get(), but instead of a single key item, it retrieves
multiple items the keys of which are specified in the keys array.
@see Memcached::get()
@param array $keys Array of keys to retrieve.
@param array $cas_tokens The variable to store the CAS tokens for found
items.
@param int $flags The flags for the get operation.
@return array The array of found items for false on failure.
|
entailment
|
public function getMultiByKey($server_key,
$keys,
$with_cas = false,
$value_cb = null) {
return $this->getMulti($keys, $with_cas, $value_cb);
}
|
@see Memcached::getMulti()
@param string $server_key This parameter is ignored.
@param array $keys Array of keys to retrieve.
@param array $cas_tokens The variable to store the CAS tokens for found
items.
@param int $flags The flags for the get operation.
@return array The array of found items for false on failure.
|
entailment
|
public function getResultMessage() {
// We're only handling the results that our code actually generates.
switch ($this->result_code) {
case self::RES_SUCCESS:
return "SUCCESS";
case self::RES_FAILURE:
return "FAILURE";
case self::RES_NOTSTORED:
return "NOT STORED";
case self::RES_NOTFOUND:
return "NOT FOUND";
}
return "UNKNOWN";
}
|
Return the message describing the result of the last operation.
@return string Message describing the result of the last operation.
|
entailment
|
public function increment($key,
$offset = 1,
$initial_value = 0,
$expiry = 0) {
return $this->incrementInternal($key, $offset, $initial_value, $expiry,
true);
}
|
Increments a numeric item's value by the specified offset. If the item's
value is not numeric, and error will result.
@param string $key The key of the item to increment
@param int $offset The amount by which to increment the item's value
@param int $initial_value The value to set the item to if it doesn't exist.
@param int $expiry The expiry time to set on the item.
@return The new item's value on success or false on failure.
|
entailment
|
public function incrementByKey($server_key,
$key,
$offset = 1,
$initial_value = 0,
$expiry = 0) {
return $this->incrementInternal($key, $offset, $initial_value, $expiry,
true);
}
|
@see Memcached::increment()
@param string $server_key This parameter is ignored.
@param string $key The key of the item to increment
@param int $offset The amount by which to increment the item's value
@param int $initial_value The value to set the item to if it doesn't exist.
@param int $expiry The expiry time to set on the item.
@return The new item's value on success or false on failure.
|
entailment
|
private function incrementInternal($key,
$offset,
$initial_value,
$expiry,
$is_incr) {
// Sending of a key of 'null' or an unset value is a failure.
if (is_null($key)) {
return false;
}
$key = $this->getPrefixKey($key);
$request = new MemcacheIncrementRequest();
$response = new MemcacheIncrementResponse();
$request->setKey($key);
$request->setDelta($offset);
$request->setInitialValue($initial_value);
if (!$is_incr) {
$request->setDirection(MemcacheIncrementRequest\Direction::DECREMENT);
}
try {
ApiProxy::makeSyncCall('memcache', 'Increment', $request, $response);
} catch (Error $e) {
$this->result_code = self::RES_FAILURE;
return false;
}
if ($response->hasNewValue()) {
$this->result_code = self::RES_SUCCESS;
return $response->getNewValue();
} else {
$this->result_code = self::RES_NOTSTORED;
return false;
}
}
|
Internal implementation of increment (and decrement).
@param string $key The key of the item to increment
@param int $offset The amount by which to increment the item's value
@param int $initial_value The value to set the item to if it doesn't exist.
@param int $expiry The expiry time to set on the item.
@param bool $is_incr Whether to perform an increment or decrement.
@return The new item's value on success or false on failure.
|
entailment
|
public function prepend($key, $value) {
do {
$result = $this->get($key, null, $cas_token);
if (!$result || !is_string($result)) {
$this->result_code = self::RES_NOTSTORED;
return false;
}
$result = $value . $result;
$result = $this->cas($cas_token, $key, $result);
} while (!$result && $this->result_code == self::RES_DATA_EXISTS);
$this->result_code = $result ? self::RES_SUCCESS : self::RES_NOTSTORED;
return $result;
}
|
Prepends the given value string to an existing item.
@param string $key The key under which to store the value.
@param string $value The string to prepend.
@return true on success or false on failure.
|
entailment
|
public function replace($key, $value, $expiration = 0) {
$key = $this->getPrefixKey($key);
$result = $this->memcache->replace($key, $value, null, $expiration);
$this->result_code = $result ? self::RES_SUCCESS : self::RES_NOTSTORED;
return $result;
}
|
Replace is similar to Memcache::set(), but the operation will fail if the
key is not found on the server.
@param string $key The key under which to store the value.
@param mixed $value The value to store.
@param int $expiration The expiration time, defaults to 0.
@return true if the method succeeds, false on failure.
|
entailment
|
public function replaceByKey($server_key, $key, $value, $expiration = 0) {
return $this->replace($key, $value, $expiration);
}
|
@see Memcached::replace()
@param string $server_key This parameter is ignored.
@param string $key The key under which to store the value.
@param mixed $value The value to store.
@param int $expiration The expiration time, defaults to 0.
@return true if the method succeeds, false on failure.
|
entailment
|
public function set($key, $value, $expiration = 0) {
$key = $this->getPrefixKey($key);
$result = $this->memcache->set($key, $value, null, $expiration);
$this->result_code = $result ? self::RES_SUCCESS : self::RES_FAILURE;
return $result;
}
|
Stores the value on a memcache server under the specified key. The
expiration parameters can be used to control when the value is considered
expired.
@param string $key The key under which to store the value.
@param mixed $value The value to store.
@param int $expiration The expiration time, defaults to 0.
@return true if the method succeeds, false on failure.
|
entailment
|
public function setByKey($server_key, $key, $value, $expiration = 0) {
return $this->set($key, $value, $expiration);
}
|
@see Memcached::set()
@param string $server_key This parameter is ignored.
@param string $key The key under which to store the value.
@param mixed $value The value to store.
@param int $expiration The expiration time, defaults to 0.
@return true if the method succeeds, false on failure.
|
entailment
|
public function setMulti($items, $expiration = 0) {
if (array_key_exists(self::OPT_PREFIX_KEY, $this->options)) {
$new_items = array();
foreach($items as $key => $value) {
$new_items[$this->getPrefixKey($key)] = $value;
}
$items = $new_items;
}
try {
$set_results = MemcacheUtils::setMultiWithPolicy($items,
$expiration,
SetPolicy::SET);
} catch (Exception $e) {
$this->result_code = self::RES_FAILURE;
return false;
}
// If any fail, report this method as failed.
foreach($set_results as $result) {
if ($result != SetStatusCode::STORED) {
$this->result_code = self::RES_NOTSTORED;
return false;
}
}
$this->result_code = self::RES_SUCCESS;
return true;
}
|
Is similar to Memcached::set(), but instead of a single key/value item, it
works on multiple items specified in items.
@see Memcached::set()
@param array $items An array of key value pairs to set.
@param int $expiration The expiration time to set for the value.
returns bool true if the call succeeds, false otherwise.
|
entailment
|
public function setOption($option, $value) {
// The only option we allow to be changed is OPT_PREFIX_KEY
if ($option == self::OPT_PREFIX_KEY) {
$this->options[$option] = $value;
return true;
}
return false;
}
|
This method sets the vaue of a memcached option.
@param int $option The option to set.
@param mixed $value The value to set the option to.
@return bool true if the call succeeds, false otherwise.
|
entailment
|
public function setOptions($options) {
$result = true;
foreach($options as $option => $value) {
$result |= $this->setOption($option, $value);
}
return $result;
}
|
This is a varion of Memcached::setOption() that takes an array of options
to be set.
@param mixed $options An associated array of options.
@return bool true if the call succeeds, false otherwise.
|
entailment
|
public function touch($key, $expiration = 0) {
$result = $this->get($key, null, $cas_token);
if ($result) {
$result = $this->cas($cas_token, $key, $result, $expiration);
}
$this->result_code = $result ? self::RES_SUCCESS : self::RES_FAILURE;
return $result;
}
|
Sets a new expiration time on an item.
@param string $key The key under which to append the value.
@param int $expiration The expiration time, defaults to 0.
@return bool true on success or false on failure.
|
entailment
|
public static function getStatusMessage($code) {
if (array_key_exists($code, self::$status_messages)) {
return self::$status_messages[$code];
}
return sprintf("Unknown Code %d", $code);
}
|
Get the status message string for a given HTTP response code.
@param int $code The HTTP response code.
@returns string The string representation of the status code.
|
entailment
|
public function makeSyncCall(
$package,
$call_name,
$request,
$response,
$deadline = null) {
if ($deadline === null) {
$deadline = self::DEFAULT_TIMEOUT_SEC;
}
$ticket = getenv(self::TICKET_HEADER);
if ($ticket === false) {
$ticket = getenv(self::DEV_TICKET_HEADER);
if ($ticket === false) {
$ticket = $this->getDefaultTicket();
}
}
$remote_request = new Request();
$remote_request->setServiceName($package);
$remote_request->setMethod($call_name);
$remote_request->setRequest($request->serializeToString());
$remote_request->setRequestId($ticket);
$serialized_remote_request = $remote_request->serializeToString();
$headers = [
self::SERVICE_DEADLINE_HEADER => $deadline,
self::SERVICE_ENDPOINT_HEADER => self::SERVICE_ENDPOINT_NAME,
self::SERVICE_METHOD_HEADER => self::APIHOST_METHOD,
'Content-Type' => self::RPC_CONTENT_TYPE,
];
$dapper_header_value = getenv(self::DAPPER_ENV_KEY);
if ($dapper_header_value !== false) {
$headers[self::DAPPER_HEADER] = $dapper_header_value;
}
// Headers are sorted so we can do a string comparison in the unit test.
ksort($headers);
$header_str = "";
foreach($headers as $k => $v) {
$header_str .= sprintf("%s: %s\r\n", $k, $v);
}
$opts = [
'http' => [
'method' => 'POST',
'header' => $header_str,
'content' => $serialized_remote_request,
'timeout' => $deadline + self::DEADLINE_DELTA_SECONDS,
],
];
$context = stream_context_create($opts);
$api_host = static::getEnvOrDefault('API_HOST', self::SERVICE_BRIDGE_HOST);
$api_port = static::getEnvOrDefault('API_PORT', self::API_PORT);
$endpoint_url = sprintf("http://%s:%s%s",
$api_host,
$api_port,
self::PROXY_PATH);
// We silence the error here to prevent spamming the users application.
// @codingStandardsIgnoreStart
$serialized_remote_respone = @file_get_contents($endpoint_url,
false,
$context);
// @codingStandardsIgnoreEnd
if ($serialized_remote_respone === false) {
throw new RPCFailedError(sprintf('Remote implementation for %s.%s failed',
$package,
$call_name));
}
$remote_response = new Response();
$remote_response->parseFromString($serialized_remote_respone);
if ($remote_response->hasApplicationError()) {
throw new ApplicationError(
$remote_response->getApplicationError()->getCode(),
$remote_response->getApplicationError()->getDetail());
}
if ($remote_response->hasException() ||
$remote_response->hasJavaException()) {
// This indicates a bug in the remote implementation.
throw new RPCFailedError(sprintf('Remote implementation for %s.%s failed',
$package,
$call_name));
}
if ($remote_response->hasRpcError()) {
$rpc_error = $remote_response->getRpcError();
throw self::getRpcErrorFromException($rpc_error->getCode(),
$package,
$call_name);
}
$response->parseFromString($remote_response->getResponse());
}
|
Makes a synchronous RPC call.
@param string $package Package to call
@param string $call_name Specific RPC call to make
@param string $request Request proto, serialised to string
@param string $response Response proto string to populate
@param double $deadline Optional deadline for the RPC call in seconds.
|
entailment
|
private static function getRpcErrorFromException($error_no, $package, $call) {
if (isset(self::$exceptionLookupTable[$error_no])) {
$res = self::$exceptionLookupTable[$error_no];
return new $res[0](sprintf($res[1], $package, $call));
}
return new RPCFailedError(sprintf('Remote implementation for %s.%s failed',
$package,
$call));
}
|
Create a runtime exception from an RPC Error Code.
@param int $error_no The RPC error code.
@param string $package The package name of the RPC call.
@param string $call The call name of the RPC call.
|
entailment
|
public static function arrayMergeIgnoreCase() {
if (func_num_args() < 2) {
throw new \InvalidArgumentException(
"At least two arrays must be supplied.");
}
$result = [];
$key_mapping = [];
$input_args = func_get_args();
foreach($input_args as $args) {
if (!is_array($args)) {
throw new \InvalidArgumentException(
"Arguments are expected to be arrays, found " . gettype($arg));
}
foreach($args as $key => $val) {
$lower_case_key = strtolower($key);
if (array_key_exists($lower_case_key, $key_mapping)) {
$result[$key_mapping[$lower_case_key]] = $val;
} else {
$key_mapping[$lower_case_key] = $key;
$result[$key] = $val;
}
}
}
return $result;
}
|
Merge a number of arrays using a case insensitive comparison for the array
keys.
@param mixed array Two or more arrays to merge.
@returns array The merged array.
@throws InvalidArgumentException If less than two arrays are passed to
the function, or one of the arguments is not an array.
|
entailment
|
public static function isAssociative(array $arr) {
$size = count($arr);
$keys = array_keys($arr);
return $keys !== range(0, $size - 1);
}
|
Checks whether an array's keys are associative. An array's keys are
associate if they are not values 0 to count(array) - 1.
@param $arr array The array whos keys will be checked.
@return bool True if the array's keys are associative. Also true in the
case of an empty array.
|
entailment
|
public static function allInstanceOf(array $array, $class) {
if(!is_string($class)) {
throw new \InvalidArgumentException('$class must be a string.');
}
if(!class_exists($class)) {
throw new \InvalidArgumentException("Class with name $class not found.");
}
foreach($array as $val) {
if(!self::instanceOfClass($val, $class)) {
return false;
}
}
return true;
}
|
Checks whether every value in an array is an instance of a class.
@param $array array The array to test.
@param $class The fully qualified class name to check every array value
with.
@return bool Whether every value in the array is an instance of $class.
@throw \InvalidArgumentException if no class with name $class is found.
|
entailment
|
public function add($key, $value, $flag = null, $expire = 0) {
// Sending of a key of 'null' or an unset value is a failure.
if (is_null($key)) {
return false;
}
try {
$set_results = MemcacheUtils::setMultiWithPolicy(array($key => $value),
$expire,
SetPolicy::ADD);
} catch (Error $e) {
return false;
}
return $set_results[0] == SetStatusCode::STORED;
}
|
Adds a new item to the cache. Will fail if the key is already present in
the cache.
@param string $key The key associated with the value added to the cache.
@param mixed $value The value to add to the cache.
@param int $flag This parameter is present only for compatibility and is
ignored.
@param int $expire The delay before the item is removed from the cache. If
$expire <= 2592000 then it is interpreted as the number
of seconds from the time of the call to wait before
removing the item from the cache. If $expire > 2592000
then it is interpreted as the absolute Unix epoch time
when the value will expire.
@return bool true if the item was successfully added to the cache, false
otherwise.
|
entailment
|
public function delete($key) {
// Sending of a key of 'null' or an unset value is a failure.
if (is_null($key)) {
return false;
}
$request = new MemcacheDeleteRequest();
$response = new MemcacheDeleteResponse();
$request->addItem()->setKey($key);
try {
ApiProxy::makeSyncCall('memcache', 'Delete', $request, $response);
} catch (Error $e) {
return false;
}
$status_list = $response->getDeleteStatusList();
return $status_list[0] == DeleteStatusCode::DELETED;
}
|
Deletes an item from the cache.
@param string $key The key associated with the item to delete.
@return bool true if the item was successfully deleted from the cache,
false otherwise. Note that this will return false if $key is
not present in the cache.
|
entailment
|
public function flush() {
$request = new MemcacheFlushRequest();
$response = new MemcacheFlushResponse();
try {
ApiProxy::makeSyncCall('memcache', 'FlushAll', $request, $response);
} catch (Error $e) {
return false;
}
return true;
}
|
Removes all items from cache.
@return bool true if all items were removed, false otherwise.
|
entailment
|
public function get($keys, $flags = null) {
if (is_array($keys)) {
$return_value = $this->getMulti($keys, $flags);
if (empty($return_value)) {
return false;
} else {
return $return_value;
}
} else {
try {
$return_value = $this->getMulti(array($keys), array($flags));
} catch (Error $e) {
return false;
}
if (array_key_exists($keys, $return_value)) {
return $return_value[$keys];
} else {
return false;
}
}
}
|
Fetches previously stored data from the cache.
@param string|string[] $keys The key associated with the value to fetch, or
an array of keys if fetching multiple values.
@param int $flags This parameter is present only for compatibility and is
ignored. It should return the stored flag value.
@return mixed On success, the string associated with the key, or an array
of key-value pairs when $keys is an array. On failure, false
is returned.
|
entailment
|
private function incrementInternal($key, $value, $is_incr) {
// Sending of a key of 'null' or an unset value is a failure.
if (is_null($key)) {
return false;
}
$request = new MemcacheIncrementRequest();
$response = new MemcacheIncrementResponse();
$request->setKey($key);
$request->setDelta($value);
if (!$is_incr) {
$request->setDirection(MemcacheIncrementRequest\Direction::DECREMENT);
}
try {
ApiProxy::makeSyncCall('memcache', 'Increment', $request, $response);
} catch (Exception $e) {
return false;
}
if ($response->hasNewValue()) {
return $response->getNewValue();
} else {
return false;
}
}
|
Internal implementation of increment (and decrement).
@param string $key The key associated with the value to increment.
@param int $value The amount to increment the value.
@param bool $is_incr Whether to perform an increment or decrement.
@return mixed On success, the new value of the item is returned. On
failure, false is returned.
|
entailment
|
public function replace($key, $value, $flag = null, $expire = 0) {
// Sending of a key of 'null' or an unset value is a failure.
if (is_null($key)) {
return false;
}
try {
$set_results = MemcacheUtils::setMultiWithPolicy(array($key => $value),
$expire,
SetPolicy::REPLACE);
} catch (Error $e) {
return false;
}
return $set_results[0] == SetStatusCode::STORED;
}
|
Replaces an existing item in the cache. Will fail if the key is not already
present in the cache.
@param string $key The key associated with the value that will be replaced
in the cache.
@param mixed $value The new cache value.
@param int $flag This parameter is present only for compatibility and is
ignored.
@param int $expire The delay before the item is removed from the cache. If
$expire <= 2592000 then it is interpreted as the number
of seconds from the time of the call to wait before
removing the item from the cache. If $expire > 2592000
then it is interpreted as the absolute Unix epoch time
when the value will expire.
@return bool true if the item was successfully replaced in the cache,
false otherwise.
|
entailment
|
public function set($key, $value, $flag = null, $expire = 0) {
// Sending of a key of 'null' or an unset value is a failure.
if (is_null($key)) {
return false;
}
try {
$set_results = MemcacheUtils::setMultiWithPolicy(array($key => $value),
$expire,
SetPolicy::SET);
} catch (Error $e) {
return false;
}
return $set_results[0] == SetStatusCode::STORED;
}
|
Sets the value of a key in the cache regardless of whether it is currently
present or not.
@param string $key The key associated with the value that will be replaced
in the cache.
@param mixed $value The new cache value.
@param int $flag This parameter is present only for compatibility and is
ignored.
@param int $expire The delay before the item is removed from the cache. If
$expire <= 2592000 then it is interpreted as the number
of seconds from the time of the call to wait before
removing the item from the cache. If $expire > 2592000
then it is interpreted as the absolute Unix epoch time
when the value will expire.
@return bool true if the item was successfully replaced the cache, false
otherwise.
|
entailment
|
public function addContent($campaignId, $contentData = [], $params = [])
{
$endpoint = $this->endpoint . '/' . $campaignId . '/content';
$response = $this->restClient->put($endpoint, $contentData);
return $response['body'];
}
|
Add custom html to campaign
@param int $campaignId
@param array $contentData
@param array $params
@return [type]
|
entailment
|
public function send($campaignId, $settingsData = [])
{
$endpoint = $this->endpoint . '/' . $campaignId . '/actions/send';
$response = $this->restClient->post($endpoint, $settingsData);
return $response['body'];
}
|
Trigger action: send
@param int $campaignId
@param array $settingsData
@return [type]
|
entailment
|
public function cancel($campaignId)
{
$endpoint = $this->endpoint . '/' . $campaignId . '/actions/cancel';
$response = $this->restClient->post($endpoint);
return $response['body'];
}
|
Trigger action: cancel
@param int $campaignId
@return [type]
|
entailment
|
public function get($type = 'sent', $fields = ['*'])
{
// filter anything that is not an available type
$type = in_array($type, ['sent', 'draft', 'outbox']) ? $type : 'sent';
$params = $this->prepareParams();
if ( ! empty($fields) && is_array($fields) && $fields != ['*']) {
$params['fields'] = $fields;
}
$response = $this->restClient->get($this->endpoint . '/' . $type, $params);
$entities = $this->generateCollection($response['body']);
return $entities;
}
|
Get collection of items
@param array $fields
@return [type]
|
entailment
|
protected function send($method, $endpointUri, $body = null, array $headers = [])
{
$headers = array_merge($headers, self::getDefaultHeaders());
$endpointUrl = $this->baseUrl . $endpointUri;
$request = new Request($method, $endpointUrl, $headers, json_encode($body));
$response = $this->getHttpClient()->sendRequest($request);
return $this->handleResponse($response);
}
|
Execute HTTP request
@param string $method
@param string $endpointUri
@param string $body
@param array $headers
@return [type]
|
entailment
|
protected function handleResponse(ResponseInterface $response)
{
$status = $response->getStatusCode();
$data = (string) $response->getBody();
$jsonResponseData = json_decode($data, false);
$body = $data && $jsonResponseData === null ? $data : $jsonResponseData;
return ['status_code' => $status, 'body' => $body];
}
|
Handle HTTP response
@param ResponseInterface $response
@return [type]
|
entailment
|
public function find($id)
{
if (empty($id)) {
throw new \Exception('ID must be set');
}
$response = $this->restClient->get($this->endpoint . '/' . $id);
return $response['body'];
}
|
Get single item
@param int|string $id Id can be Subscribers ID or his email address
@return [type]
|
entailment
|
public function create($data)
{
$response = $this->restClient->post($this->endpoint, $data);
return $response['body'];
}
|
Create new item
@param array $data
@return [type]
|
entailment
|
public function update($id, $data)
{
$response = $this->restClient->put($this->endpoint . '/' . $id, $data);
return $response['body'];
}
|
Update an item
@param int $id
@param array $data
@return [type]
|
entailment
|
public function delete($id)
{
$response = $this->restClient->delete($this->endpoint . '/' . $id);
return $response['body'];
}
|
Delete an item
@param int $id
@return [type]
|
entailment
|
public function where(
$column,
$operator = null,
$value = null,
$boolean = 'and'
) {
if (is_array($column)) {
$this->_where = $column;
}
return $this;
}
|
Set where conditions
@param [type] $column
@param [type] $operator
@param [type] $value
@param string $boolean
@return [type]
|
entailment
|
protected function prepareParams()
{
$params = [];
if ( ! empty($this->_where) && is_array($this->_where)) {
$params['filters'] = $this->_where;
}
if ( ! empty($this->_offset)) {
$params['offset'] = $this->_offset;
}
if ( ! empty($this->_limit)) {
$params['limit'] = $this->_limit;
}
if ( ! empty($this->_orders) && is_array($this->_orders)) {
foreach ($this->_orders as $field => $order) {
$params['order_by'][$field] = $order;
}
}
return $params;
}
|
Prepare query parameters
@return [type]
|
entailment
|
public function setConsumerData( $consumerKey, $consumerSecret, $store, $apiKey, $currency )
{
$endpoint = $this->endpoint . '/consumer_data';
$params = array_merge($this->prepareParams(), ['consumer_key' => $consumerKey, 'consumer_secret' => $consumerSecret, 'store' => $store, 'api_key' => $apiKey, 'currency' => $currency] );
$response = $this->restClient->post( $endpoint, $params );
return $response['body'];
}
|
Sends shop data to our api to be saved(or updated) in the db
|
entailment
|
public function setWebhooks($shop)
{
$endpoint = $this->endpoint.'/webhooks';
$params = array_merge($this->prepareParams(), ['shop' => $shop] );
return $this->restClient->post( $endpoint, $params );
}
|
Currenty not in use as this is meant to save webhooks for created and updated orders
however, now we're instead listening for the event in the plugin so no need for webhooks
|
entailment
|
public function saveOrder($orderData, $shop)
{
$endpoint = 'woocommerce/alternative_save_order';
$params = array_merge($this->prepareParams(), ['order_data' => $orderData, 'shop' => $shop] );
return $this->restClient->post( $endpoint, $params );
}
|
Sends the completed order data to the api
|
entailment
|
public function toggleShopConnection($shop, $activeState)
{
$shopName = parse_url($shop, PHP_URL_HOST);
$endpoint = 'woocommerce/toggle_shop_connection';
$params = array_merge($this->prepareParams(), ['active_state' => $activeState, 'shop' => $shopName] );
return $this->restClient->post( $endpoint, $params );
}
|
Calls api endpoint that will toggle shop's active state
in our db
|
entailment
|
public static function make($items)
{
if (is_null($items)) {
return new static;
}
if ($items instanceof Collection) {
return $items;
}
return new static(is_array($items) ? $items : [$items]);
}
|
Create a new collection instance if the value isn't one already.
@param mixed $items
@return static
|
entailment
|
public function toArray()
{
return array_map(
function ($value) {
return $value instanceof Entity ? $value->toArray() : $value;
}, $this->items
);
}
|
Get the collection of items as a plain array.
@return array
|
entailment
|
public function getSubscribers($groupId, $type = null, $params = [])
{
$endpoint = $this->endpoint . '/' . $groupId . '/subscribers';
if ($type !== null) {
$endpoint .= '/' . $type;
}
$params = array_merge($this->prepareParams(), $params);
$response = $this->restClient->get($endpoint, $params);
return $response['body'];
}
|
Get subscribers from group
@param int $groupId
@param string $type
@param array $params
@return [type]
|
entailment
|
public function getSubscriber($groupId, $subscriberId)
{
$endpoint = $this->endpoint . '/' . $groupId . '/subscribers/' . urlencode($subscriberId);
$response = $this->restClient->get($endpoint);
return $response['body'];
}
|
Get single subscriber from group
@param $groupId
@param $subscriberId
@return mixed
|
entailment
|
public function addSubscriber($groupId, $subscriberData = [], $params = [])
{
$endpoint = $this->endpoint . '/' . $groupId . '/subscribers';
$response = $this->restClient->post($endpoint, $subscriberData);
return $response['body'];
}
|
Add single subscriber to group
@param int $groupId
@param array $subscriberData
@param array $params
@return [type]
|
entailment
|
public function removeSubscriber($groupId, $subscriberId)
{
$endpoint = $this->endpoint . '/' . $groupId . '/subscribers/' . urlencode($subscriberId);
$response = $this->restClient->delete($endpoint);
return $response['body'];
}
|
Remove subscriber from group
@param int $groupId
@param int $subscriberId
@return [type]
|
entailment
|
public function importSubscribers(
$groupId,
$subscribers,
$options = [
'resubscribe' => false,
'autoresponders' => false
]
) {
$endpoint = $this->endpoint . '/' . $groupId . '/subscribers/import';
$response = $this->restClient->post($endpoint, array_merge(['subscribers' => $subscribers], $options));
return $response['body'];
}
|
Batch add subscribers to group
@param int $groupId
@param array $subscribers
@param array $options
@return [type]
|
entailment
|
public function getGroups($subscriberId, $params = [])
{
$endpoint = $this->endpoint . '/' . urlencode($subscriberId) . '/groups';
$params = array_merge($this->prepareParams(), $params);
$response = $this->restClient->get($endpoint, $params);
return $response['body'];
}
|
Get groups subscriber belongs to
@param int $subscriberId
@param array $params
@return [type]
|
entailment
|
public function getActivity($subscriberId, $type = null, $params = [])
{
$endpoint = $this->endpoint . '/' . urlencode($subscriberId) . '/activity';
if ($type !== null) {
$endpoint .= '/' . $type;
}
$params = array_merge($this->prepareParams(), $params);
$response = $this->restClient->get($endpoint, $params);
return $response['body'];
}
|
Get activity of subscriber
@param int $subscriberId
@param string $type
@param array $params
@return [type]
|
entailment
|
public function search($query)
{
$endpoint = $this->endpoint . '/search';
$params = array_merge($this->prepareParams(), ['query' => $query]);
$response = $this->restClient->get($endpoint, $params);
return $response['body'];
}
|
Seach for a subscriber by email or custom field value
@param string $query
@return [type]
|
entailment
|
public function getDoubleOptin()
{
$endpoint = $this->endpoint . '/double_optin';
$response = $this->restClient->get( $endpoint );
return $response['body'];
}
|
Retrieve double opt in status
@return mixed
|
entailment
|
public function index()
{
$this->loadModel('Taxonomy.Vocabularies');
$vocabularies = $this->Vocabularies
->find()
->order(['ordering' => 'ASC'])
->all();
$this->title(__d('taxonomy', 'Vocabularies'));
$this->set(compact('vocabularies'));
$this->Breadcrumb
->push('/admin/system/structure')
->push(__d('taxonomy', 'Taxonomy'), '/admin/taxonomy/manage')
->push(__d('taxonomy', 'Vocabularies'), '#');
}
|
Shows a list of all vocabularies.
@return void
|
entailment
|
public function add()
{
$this->loadModel('Taxonomy.Vocabularies');
$vocabulary = $this->Vocabularies->newEntity();
if ($this->request->data()) {
$vocabulary = $this->Vocabularies->patchEntity($vocabulary, $this->request->data, [
'fieldList' => [
'name',
'description',
],
]);
if ($this->Vocabularies->save($vocabulary, ['atomic' => true])) {
$this->Flash->success(__d('taxonomy', 'Vocabulary has been created, now you can start adding terms!'));
$this->redirect(['plugin' => 'Taxonomy', 'controller' => 'terms', 'action' => 'add', $vocabulary->id]);
} else {
$this->Flash->danger(__d('taxonomy', 'Vocabulary could not be created, please check your information'));
}
}
$this->title(__d('taxonomy', 'Create New Vocabulary'));
$this->set('vocabulary', $vocabulary);
$this->Breadcrumb
->push('/admin/system/structure')
->push(__d('taxonomy', 'Taxonomy'), '/admin/taxonomy/manage')
->push(__d('taxonomy', 'Vocabularies'), ['plugin' => 'Taxonomy', 'controller' => 'vocabularies', 'action' => 'index'])
->push(__d('taxonomy', 'Crating new vocabulary'), '#');
}
|
Adds a new menu.
@return void
|
entailment
|
public function edit($id)
{
$this->loadModel('Taxonomy.Vocabularies');
$vocabulary = $this->Vocabularies->get($id);
if ($this->request->data()) {
$vocabulary = $this->Vocabularies->patchEntity($vocabulary, $this->request->data, [
'fieldList' => [
'name',
'description',
],
]);
if ($this->Vocabularies->save($vocabulary, ['atomic' => true])) {
$this->Flash->success(__d('taxonomy', 'Vocabulary has been saved!'));
$this->redirect($this->referer());
} else {
$this->Flash->danger(__d('taxonomy', 'Vocabulary could not be saved, please check your information'));
}
}
$this->title(__d('taxonomy', 'Editing Vocabulary'));
$this->set('vocabulary', $vocabulary);
$this->Breadcrumb
->push('/admin/system/structure')
->push(__d('taxonomy', 'Taxonomy'), '/admin/taxonomy/manage')
->push(__d('taxonomy', 'Vocabularies'), ['plugin' => 'Taxonomy', 'controller' => 'vocabularies', 'action' => 'index'])
->push(__d('taxonomy', 'Editing vocabulary'), '#');
}
|
Edits the given vocabulary by ID.
@param int $id Vocabulary's ID
@return void
|
entailment
|
public function delete($id)
{
$this->loadModel('Taxonomy.Vocabularies');
$vocabulary = $this->Vocabularies->get($id, [
'conditions' => [
'locked' => 0
]
]);
if ($this->Vocabularies->delete($vocabulary)) {
$this->Flash->success(__d('taxonomy', 'Vocabulary has been successfully deleted!'));
} else {
$this->Flash->danger(__d('taxonomy', 'Vocabulary could not be deleted, please try again'));
}
$this->title(__d('taxonomy', 'Delete Vocabulary'));
$this->redirect($this->referer());
}
|
Removes the given vocabulary by ID.
@param int $id Vocabulary's ID
@return void Redirects to previous page
|
entailment
|
public function home()
{
$this->loadModel('Content.Contents');
$contents = $this->Contents
->find('all')
->where([
'Contents.promote' => 1,
'Contents.status >' => 0,
'Contents.language IN' => ['', null, I18n::locale()]
])
->order(['Contents.sticky' => 'DESC', 'Contents.created' => 'DESC'])
->limit((int)option('site_contents_home'));
$this->set('contents', $contents);
$this->viewMode('teaser');
}
|
Site's home page.
Gets a list of all promoted contents, so themes may render them in their
front-page layout. The view-variable `contents` holds all promoted contents,
themes might render this contents using this variable.
@return void
|
entailment
|
public function details($contentTypeSlug, $contentSlug)
{
$this->loadModel('Content.Contents');
$conditions = [
'Contents.slug' => $contentSlug,
'Contents.content_type_slug' => $contentTypeSlug,
];
if (!$this->request->is('userAdmin')) {
$conditions['Contents.status >'] = 0;
}
$content = $this->Contents->find()
->where($conditions)
->contain(['ContentTypes', 'Roles'])
->first();
if (!$content) {
throw new ContentNotFoundException(__d('content', 'The requested page was not found.'));
} elseif (!$content->isAccessibleByUser()) {
throw new ForbiddenException(__d('content', 'You have not sufficient permissions to see this page.'));
}
if (!empty($content->language) && $content->language != I18n::locale()) {
if ($redirect = $this->_calculateRedirection($content)) {
$this->redirect($redirect);
return $this->response;
}
throw new ContentNotFoundException(__d('content', 'The requested page was not found.'));
}
// Post new comment logic
if ($content->comment_status > 0) {
$content->set('comments', $this->Contents->find('comments', ['for' => $content->id]));
$this->Comment->config('visibility', $content->comment_status);
$this->Comment->post($content);
}
$this->set('content', $content);
$this->viewMode('full');
}
|
Content's detail page.
@param string $contentTypeSlug Content's type-slug. e.g. `article`, `basic-page`
@param string $contentSlug Content's slug. e.g. `this-is-an-article`
@return \Cake\Network\Response|null
@throws \Content\Error\ContentNotFoundException When content is not found
@throws \Cake\Network\Exception\ForbiddenException When user can't access
this content due to role restrictions
|
entailment
|
public function search($criteria)
{
$this->loadModel('Content.Contents');
try {
$contents = $this->Contents->search($criteria);
if ($contents->clause('limit')) {
$this->paginate['limit'] = $contents->clause('limit');
}
// TO-DO: ask search-engine for operator presence
if (strpos($criteria, 'language:') === false) {
$contents = $contents->where([
'Contents.status >' => 0,
'Contents.language IN' => ['', null, I18n::locale()] // any or concrete
]);
}
$contents = $this->paginate($contents);
} catch (\Exception $e) {
$contents = new Collection([]);
}
$this->set(compact('contents', 'criteria'));
$this->viewMode('search-result');
}
|
Contents search engine page.
@param string $criteria A search criteria. e.g.: `"this phrase" -"but not this" OR -hello`
@return void
|
entailment
|
public function rss($criteria)
{
$this->loadModel('Content.Contents');
try {
$contents = $this->Contents
->search($criteria)
->limit(10);
} catch (\Exception $e) {
$contents = [];
}
$this->set(compact('contents', 'criteria'));
$this->viewMode('rss');
$this->RequestHandler->renderAs($this, 'rss');
$this->RequestHandler->respondAs('xml');
}
|
RSS feeder.
Similar to `ServeController::search()` but it uses `rss` layout instead of
default layout.
@param string $criteria A search criteria. e.g.: `"this phrase" -"but not this" OR -hello`
@return void
|
entailment
|
protected function _calculateRedirection(EntityInterface $content)
{
foreach (['translation', 'parent'] as $method) {
if ($has = $content->{$method}()) {
return option('url_locale_prefix') ? '/' . $has->get('language') . stripLanguagePrefix($has->get('url')) : $has->get('url');
}
}
return '';
}
|
Calculates the URL to which visitor should be redirected according to
content's & visitor's language.
@param \Cake\Datasource\EntityInterface $content Content to inspect
@return string Redirection URL, empty on error
|
entailment
|
public function beforeFilter(Event $event)
{
$requestParams = $event->subject()->request->params;
if (empty($this->_manageTable) ||
!($this->_table = TableRegistry::get($this->_manageTable))
) {
throw new ForbiddenException(__d('field', 'FieldUIControllerTrait: The property $_manageTable was not found or is empty.'));
} elseif (!($this instanceof Controller)) {
throw new ForbiddenException(__d('field', 'FieldUIControllerTrait: This trait must be used on instances of Cake\Controller\Controller.'));
} elseif (!isset($requestParams['prefix']) || strtolower($requestParams['prefix']) !== 'admin') {
throw new ForbiddenException(__d('field', 'FieldUIControllerTrait: This trait must be used on backend-controllers only.'));
}
$this->_tableAlias = Inflector::underscore($this->_table->alias());
}
|
Validation rules.
@param \Cake\Event\Event $event The event instance.
@return void
@throws \Cake\Network\Exception\ForbiddenException When
- $_manageTable is not defined.
- trait is used in non-controller classes.
- the controller is not a backend controller.
|
entailment
|
public function index()
{
$this->loadModel('Field.FieldInstances');
$instances = $this->_getInstances();
if (count($instances) == 0) {
$this->Flash->warning(__d('field', 'There are no field attached yet.'));
}
$this->title(__d('field', 'Fields List'));
$this->set('instances', $instances);
}
|
Field UI main action.
Shows all the fields attached to the Table being managed.
@return void
|
entailment
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.