sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
public function getQueryParams()
{
$queryParams = $this->serverRequest->getQueryParams();
if (is_array($queryParams) && !empty($queryParams)) {
return $queryParams;
}
$parsedQueryParams = [];
parse_str($this->serverRequest->getUri()->getQuery(), $parsedQueryParams);
return $parsedQueryParams;
}
|
Retrieve query string arguments.
Retrieves the deserialized query string arguments, if any.
Note: the query params might not be in sync with the URI or server
params. If you need to ensure you are only getting the original
values, you may need to parse the query string from `getUri()->getQuery()`
or from the `QUERY_STRING` server param.
@return array
|
entailment
|
public function withAddedHeader($name, $value)
{
$serverRequest = $this->serverRequest->withAddedHeader($name, $value);
return new static($serverRequest);
}
|
Return an instance with the specified header appended with the given value.
Existing values for the specified header will be maintained. The new
value(s) will be appended to the existing list. If the header did not
exist previously, it will be added.
This method MUST be implemented in such a way as to retain the
immutability of the message, and MUST return an instance that has the
new header and/or value.
@param string $name Case-insensitive header field name to add.
@param string|string[] $value Header value(s).
@return static
@throws InvalidArgumentException for invalid header names or values.
|
entailment
|
public function withAttribute($name, $value)
{
$serverRequest = $this->serverRequest->withAttribute($name, $value);
return new static($serverRequest);
}
|
Return an instance with the specified derived request attribute.
This method allows setting a single derived request attribute as
described in getAttributes().
This method MUST be implemented in such a way as to retain the
immutability of the message, and MUST return an instance that has the
updated attribute.
@see getAttributes()
@param string $name The attribute name.
@param mixed $value The value of the attribute.
@return static
|
entailment
|
public function withAttributes(array $attributes)
{
$serverRequest = $this->serverRequest;
foreach ($attributes as $attribute => $value) {
$serverRequest = $serverRequest->withAttribute($attribute, $value);
}
return new static($serverRequest);
}
|
Create a new instance with the specified derived request attributes.
Note: This method is not part of the PSR-7 standard.
This method allows setting all new derived request attributes as
described in getAttributes().
This method MUST be implemented in such a way as to retain the
immutability of the message, and MUST return a new instance that has the
updated attributes.
@param array $attributes New attributes
@return static
|
entailment
|
public function withHeader($name, $value)
{
$serverRequest = $this->serverRequest->withHeader($name, $value);
return new static($serverRequest);
}
|
Return an instance with the provided value replacing the specified header.
While header names are case-insensitive, the casing of the header will
be preserved by this function, and returned from getHeaders().
This method MUST be implemented in such a way as to retain the
immutability of the message, and MUST return an instance that has the
new and/or updated header and value.
@param string $name Case-insensitive header field name.
@param string|string[] $value Header value(s).
@return static
@throws InvalidArgumentException for invalid header names or values.
|
entailment
|
public function getContentLength(): ?int
{
$result = $this->serverRequest->getHeader('Content-Length');
return $result ? (int) $result[0] : null;
}
|
Get serverRequest content length, if known.
Note: This method is not part of the PSR-7 standard.
@return int|null
|
entailment
|
public function getCookieParam($key, $default = null)
{
$cookies = $this->serverRequest->getCookieParams();
$result = $default;
if (isset($cookies[$key])) {
$result = $cookies[$key];
}
return $result;
}
|
Fetch cookie value from cookies sent by the client to the server.
Note: This method is not part of the PSR-7 standard.
@param string $key The attribute name.
@param mixed $default Default value to return if the attribute does not exist.
@return mixed
|
entailment
|
public function getServerParam($key, $default = null)
{
$serverParams = $this->serverRequest->getServerParams();
return isset($serverParams[$key]) ? $serverParams[$key] : $default;
}
|
Retrieve a server parameter.
Note: This method is not part of the PSR-7 standard.
@param string $key
@param mixed $default
@return mixed
|
entailment
|
public function registerMediaTypeParser($mediaType, callable $callable): ServerRequestInterface
{
if ($callable instanceof Closure) {
$callable = $callable->bindTo($this);
}
$this->bodyParsers[$mediaType] = $callable;
return $this;
}
|
Register media type parser.
Note: This method is not part of the PSR-7 standard.
@param string $mediaType A HTTP media type (excluding content-type params).
@param callable $callable A callable that returns parsed contents for media type.
@return static
|
entailment
|
public function withHeader($name, $value)
{
$response = $this->response->withHeader($name, $value);
return new static($response, $this->streamFactory);
}
|
Return an instance with the provided value replacing the specified header.
While header names are case-insensitive, the casing of the header will
be preserved by this function, and returned from getHeaders().
This method MUST be implemented in such a way as to retain the
immutability of the message, and MUST return an instance that has the
new and/or updated header and value.
@param string $name Case-insensitive header field name.
@param string|string[] $value Header value(s).
@return static
@throws InvalidArgumentException for invalid header names or values.
|
entailment
|
public function withoutHeader($name)
{
$response = $this->response->withoutHeader($name);
return new static($response, $this->streamFactory);
}
|
Return an instance without the specified header.
Header resolution MUST be done without case-sensitivity.
This method MUST be implemented in such a way as to retain the
immutability of the message, and MUST return an instance that removes
the named header.
@param string $name Case-insensitive header field name to remove.
@return static
|
entailment
|
public function withProtocolVersion($version)
{
$response = $this->response->withProtocolVersion($version);
return new static($response, $this->streamFactory);
}
|
Return an instance with the specified HTTP protocol version.
The version string MUST contain only the HTTP version number (e.g.,
"1.1", "1.0").
This method MUST be implemented in such a way as to retain the
immutability of the message, and MUST return an instance that has the
new protocol version.
@param string $version HTTP protocol version
@return static
|
entailment
|
public function withRedirect(string $url, $status = null): ResponseInterface
{
$response = $this->response->withHeader('Location', $url);
if ($status === null) {
$status = 302;
}
$response = $response->withStatus($status);
return new static($response, $this->streamFactory);
}
|
Redirect.
Note: This method is not part of the PSR-7 standard.
This method prepares the response object to return an HTTP Redirect
response to the client.
@param string $url The redirect destination.
@param int|null $status The redirect HTTP status code.
@return static
|
entailment
|
public function macro_hint_link($__hints__ = null, ...$__varargs__)
{
$context = $this->env->mergeGlobals(array(
"hints" => $__hints__,
"varargs" => $__varargs__,
));
$blocks = array();
ob_start();
try {
// line 28
$context["__internal_824d04c288835948ab7fb794708239ecd8b80d4f15cc6d1e31ffce8e0e773f62"] = $this;
// line 30
if ((isset($context["hints"]) || array_key_exists("hints", $context) ? $context["hints"] : (function () { throw new Twig_Error_Runtime('Variable "hints" does not exist.', 30, $this->getSourceContext()); })())) {
// line 31
$context['_parent'] = $context;
$context['_seq'] = twig_ensure_traversable((isset($context["hints"]) || array_key_exists("hints", $context) ? $context["hints"] : (function () { throw new Twig_Error_Runtime('Variable "hints" does not exist.', 31, $this->getSourceContext()); })()));
$context['loop'] = array(
'parent' => $context['_parent'],
'index0' => 0,
'index' => 1,
'first' => true,
);
if (is_array($context['_seq']) || (is_object($context['_seq']) && $context['_seq'] instanceof Countable)) {
$length = count($context['_seq']);
$context['loop']['revindex0'] = $length - 1;
$context['loop']['revindex'] = $length;
$context['loop']['length'] = $length;
$context['loop']['last'] = 1 === $length;
}
foreach ($context['_seq'] as $context["_key"] => $context["hint"]) {
// line 32
if (twig_get_attribute($this->env, $this->getSourceContext(), $context["hint"], "class", array())) {
// line 33
echo $context["__internal_824d04c288835948ab7fb794708239ecd8b80d4f15cc6d1e31ffce8e0e773f62"]->macro_class_link(twig_get_attribute($this->env, $this->getSourceContext(), $context["hint"], "name", array()));
} elseif (twig_get_attribute($this->env, $this->getSourceContext(), // line 34
$context["hint"], "name", array())) {
// line 35
echo $this->env->getExtension('Sami\Renderer\TwigExtension')->abbrClass(twig_get_attribute($this->env, $this->getSourceContext(), $context["hint"], "name", array()));
}
// line 37
if (twig_get_attribute($this->env, $this->getSourceContext(), $context["hint"], "array", array())) {
echo "[]";
}
// line 38
if ( !twig_get_attribute($this->env, $this->getSourceContext(), $context["loop"], "last", array())) {
echo "|";
}
++$context['loop']['index0'];
++$context['loop']['index'];
$context['loop']['first'] = false;
if (isset($context['loop']['length'])) {
--$context['loop']['revindex0'];
--$context['loop']['revindex'];
$context['loop']['last'] = 0 === $context['loop']['revindex0'];
}
}
$_parent = $context['_parent'];
unset($context['_seq'], $context['_iterated'], $context['_key'], $context['hint'], $context['_parent'], $context['loop']);
$context = array_intersect_key($context, $_parent) + $_parent;
}
return ('' === $tmp = ob_get_contents()) ? '' : new Twig_Markup($tmp, $this->env->getCharset());
} finally {
ob_end_clean();
}
}
|
line 27
|
entailment
|
public function macro_method_parameters_signature($__method__ = null, ...$__varargs__)
{
$context = $this->env->mergeGlobals(array(
"method" => $__method__,
"varargs" => $__varargs__,
));
$blocks = array();
ob_start();
try {
// line 62
$context["__internal_806fca29b59d4cf118e51ec3e5465eab7af3126032bd74c60f49bb656e285786"] = $this->loadTemplate("macros.twig", "macros.twig", 62);
// line 63
echo "(";
// line 64
$context['_parent'] = $context;
$context['_seq'] = twig_ensure_traversable(twig_get_attribute($this->env, $this->getSourceContext(), (isset($context["method"]) || array_key_exists("method", $context) ? $context["method"] : (function () { throw new Twig_Error_Runtime('Variable "method" does not exist.', 64, $this->getSourceContext()); })()), "parameters", array()));
$context['loop'] = array(
'parent' => $context['_parent'],
'index0' => 0,
'index' => 1,
'first' => true,
);
if (is_array($context['_seq']) || (is_object($context['_seq']) && $context['_seq'] instanceof Countable)) {
$length = count($context['_seq']);
$context['loop']['revindex0'] = $length - 1;
$context['loop']['revindex'] = $length;
$context['loop']['length'] = $length;
$context['loop']['last'] = 1 === $length;
}
foreach ($context['_seq'] as $context["_key"] => $context["parameter"]) {
// line 65
if (twig_get_attribute($this->env, $this->getSourceContext(), $context["parameter"], "hashint", array())) {
echo $context["__internal_806fca29b59d4cf118e51ec3e5465eab7af3126032bd74c60f49bb656e285786"]->macro_hint_link(twig_get_attribute($this->env, $this->getSourceContext(), $context["parameter"], "hint", array()));
echo " ";
}
// line 66
echo "\$";
echo twig_get_attribute($this->env, $this->getSourceContext(), $context["parameter"], "name", array());
// line 67
if (twig_get_attribute($this->env, $this->getSourceContext(), $context["parameter"], "default", array())) {
echo " = ";
echo twig_escape_filter($this->env, twig_get_attribute($this->env, $this->getSourceContext(), $context["parameter"], "default", array()), "html", null, true);
}
// line 68
if ( !twig_get_attribute($this->env, $this->getSourceContext(), $context["loop"], "last", array())) {
echo ", ";
}
++$context['loop']['index0'];
++$context['loop']['index'];
$context['loop']['first'] = false;
if (isset($context['loop']['length'])) {
--$context['loop']['revindex0'];
--$context['loop']['revindex'];
$context['loop']['last'] = 0 === $context['loop']['revindex0'];
}
}
$_parent = $context['_parent'];
unset($context['_seq'], $context['_iterated'], $context['_key'], $context['parameter'], $context['_parent'], $context['loop']);
$context = array_intersect_key($context, $_parent) + $_parent;
// line 70
echo ")";
return ('' === $tmp = ob_get_contents()) ? '' : new Twig_Markup($tmp, $this->env->getCharset());
} finally {
ob_end_clean();
}
}
|
line 61
|
entailment
|
public static function get($key)
{
$key = strtoupper($key);
$list = static::loadConstants();
if(array_key_exists($key,$list))
return static::loadConstants()[$key];
if(static::exist($key))
return $key;
// Throw exception.
static::invalidType();
}
|
Get the constant value from a passed report type.
@param $key
@return mixed
@throws ReportFormat
|
entailment
|
public static function exist($value)
{
$list = static::loadConstants();
return in_array($value,$list) || in_array(strtoupper($value),$list) ;
}
|
Check if a passed value is available as report type.
@param $value
@return bool
|
entailment
|
public function block_page_content($context, array $blocks = array())
{
// line 7
echo " <div class=\"page-header\">
<h1>Interfaces</h1>
</div>
";
// line 11
echo $context["__internal_489fc7173b64d75db52ff7dfbddff6202b25e76cb4ce6bc764856d1454be0973"]->macro_render_classes((isset($context["interfaces"]) || array_key_exists("interfaces", $context) ? $context["interfaces"] : (function () { throw new Twig_Error_Runtime('Variable "interfaces" does not exist.', 11, $this->getSourceContext()); })()));
echo "
";
}
|
line 6
|
entailment
|
public function where($condition)
{
$this->where = ! $this->where ? $condition : $this->where . ' AND ' . $condition;
return $this;
}
|
Set where condition
@param $condition
@return $this
|
entailment
|
public function get($fields = [])
{
$fields = empty($fields) ? $this->fields : $fields;
$this->haveFields($fields);
$query = $this->createQuery($fields);
return new ServiceCollection($this->getService(), $this->service->query($query)->getEntries());
}
|
Get all items.
@param array $fields
@return ServiceCollection
E.g. => Campaign | AdGroup | AdGroupAd | ...
|
entailment
|
private function setService($service)
{
try {
$this->service = $this->adWordsServices->get($this->session, $service);
} catch (\Exception $e) {
throw new \Edujugon\GoogleAds\Exceptions\Service("The service '$service' is not available. Please pass a valid service");
}
}
|
Set the service
@param $service
@throws \Edujugon\GoogleAds\Exceptions\Service
|
entailment
|
public function register()
{
// Console commands
$this->commands([
RefreshTokenCommand::class,
]);
$this->app->bind(GoogleAds::class, function ($app) {
return new GoogleAds();
});
}
|
Register the application services.
@return void
|
entailment
|
public function of($reportType)
{
$this->validateReportType($reportType);
$this->reportDefinitionFields = $this->reportDefinitionService->getReportFields($reportType);
$this->obj = $this->createObj($this->reportDefinitionFields);
return $this;
}
|
Load the fields of the passed reportType
@param $reportType
@return $this
|
entailment
|
public function except(array $list)
{
foreach ($list as $field)
{
if(property_exists($this->obj,$field))
unset($this->obj->$field);
}
return $this;
}
|
Pull fields from the list.
@param array $list
@return $this
|
entailment
|
private function createObj($reportDefinitionFields)
{
$obj = new \stdClass();
foreach ($reportDefinitionFields as $reportDefinitionField) {
$name = $reportDefinitionField->getFieldName();
$obj->$name = [
'type' => $reportDefinitionField->getFieldType(),
'values' => ($reportDefinitionField->getEnumValues() !== null) ? $reportDefinitionField->getEnumValues() : null,
];
}
return $obj;
}
|
Create a stdClass object with filter data.
@param $reportDefinitionFields
@return \stdClass
|
entailment
|
public function handle()
{
$oAth2 = (new OAuth2())->build();
$authorizationUrl = $oAth2->buildFullAuthorizationUri();
// Show authorization URL
$this->line(sprintf(
"Log into the Google account you use for AdWords and visit the following URL:\n%s",
$authorizationUrl
));
// Retrieve token
$accessToken = $this->ask('After approving the token enter the authorization code here:');
$oAth2->setCode($accessToken);
$authToken = $oAth2->fetchAuthToken();
if (!array_key_exists('refresh_token', $authToken)) {
$this->error('Couldn\'t find refresh_token key in the response.');
$this->comment('Below you can check the whole response:');
$this->line(json_encode($authToken));
return;
}
$this->comment('Copy the refresh token in your googleads configuration file (config/google-ads.php)');
// Print refresh token
$this->line(sprintf(
'Refresh token: "%s"',
$authToken['refresh_token']
));
}
|
Generate refresh token
|
entailment
|
public function userCredentials(array $data = [])
{
$data = $this->mergeData($data);
$refreshCredentials = new OAuth2TokenBuilder();
return $refreshCredentials->withClientId($data['clientId'])
->withClientSecret($data['clientSecret'])
->withRefreshToken($data['refreshToken'])
->build();
}
|
UserRefreshCredentials
Generate a refreshable OAuth2 credential for authentication.
Parameters:
$data: [$clientId => '',$clientSecret => '',$refreshToken => '']
@param array $data
@return \Google\Auth\Credentials\UserRefreshCredentials
|
entailment
|
public function where($field, $value,$opposite = false)
{
return $this->filter(function ($item) use($field,$value,$opposite){
$method = $this->concatGet($field);
$pass = $item->$method() == $value;
return $opposite ? !$pass : $pass;
});
}
|
search the value in the collection in a specific field.
@param $field
@param $value
@param bool $opposite
@return ServiceCollection
|
entailment
|
public function set($field, $value)
{
return $this->map(function ($item) use($field,$value) {
$method = $this->concatSet($field);
return $item->$method($value);
});
}
|
Set the value in the specific field.
@param $field
@param $value
@return ServiceCollection
|
entailment
|
public function save()
{
$operations = [];
$this->items->each(function ($item) use(&$operations) {
$operation = $this->setOperator();
$operation->setOperand($item);
$operation->setOperator('SET');
$operations[] = $operation;
});
if(empty($operations))
return false;
return $this->adWordsServices->mutate($operations)->getValue();
}
|
Persist values in google.
@return false|mixed
|
entailment
|
public function macro_element($__tree__ = null, $__opened__ = null, $__depth__ = null, ...$__varargs__)
{
$context = $this->env->mergeGlobals(array(
"tree" => $__tree__,
"opened" => $__opened__,
"depth" => $__depth__,
"varargs" => $__varargs__,
));
$blocks = array();
ob_start();
try {
// line 226
echo " ";
$context["__internal_142ae502b5e16351d8341c4131a7cddf80b73f32c0cd1f5736568e36957bbd5e"] = $this;
// line 227
echo "
<ul>";
// line 229
$context['_parent'] = $context;
$context['_seq'] = twig_ensure_traversable((isset($context["tree"]) || array_key_exists("tree", $context) ? $context["tree"] : (function () { throw new Twig_Error_Runtime('Variable "tree" does not exist.', 229, $this->getSourceContext()); })()));
foreach ($context['_seq'] as $context["_key"] => $context["element"]) {
// line 230
if (twig_get_attribute($this->env, $this->getSourceContext(), $context["element"], 2, array(), "array")) {
// line 231
echo " <li data-name=\"namespace:";
echo twig_replace_filter(twig_get_attribute($this->env, $this->getSourceContext(), $context["element"], 1, array(), "array"), array("\\" => "_"));
echo "\" ";
if (((isset($context["depth"]) || array_key_exists("depth", $context) ? $context["depth"] : (function () { throw new Twig_Error_Runtime('Variable "depth" does not exist.', 231, $this->getSourceContext()); })()) < (isset($context["opened"]) || array_key_exists("opened", $context) ? $context["opened"] : (function () { throw new Twig_Error_Runtime('Variable "opened" does not exist.', 231, $this->getSourceContext()); })()))) {
echo "class=\"opened\"";
}
echo ">
<div style=\"padding-left:";
// line 232
echo ((isset($context["depth"]) || array_key_exists("depth", $context) ? $context["depth"] : (function () { throw new Twig_Error_Runtime('Variable "depth" does not exist.', 232, $this->getSourceContext()); })()) * 18);
echo "px\" class=\"hd\">
<span class=\"glyphicon glyphicon-play\"></span>";
// line 233
if ( !twig_get_attribute($this->env, $this->getSourceContext(), (isset($context["project"]) || array_key_exists("project", $context) ? $context["project"] : (function () { throw new Twig_Error_Runtime('Variable "project" does not exist.', 233, $this->getSourceContext()); })()), "config", array(0 => "simulate_namespaces"), "method")) {
echo "<a href=\"";
echo $this->env->getExtension('Sami\Renderer\TwigExtension')->pathForNamespace($context, twig_get_attribute($this->env, $this->getSourceContext(), $context["element"], 1, array(), "array"));
echo "\">";
}
echo twig_get_attribute($this->env, $this->getSourceContext(), $context["element"], 0, array(), "array");
if ( !twig_get_attribute($this->env, $this->getSourceContext(), (isset($context["project"]) || array_key_exists("project", $context) ? $context["project"] : (function () { throw new Twig_Error_Runtime('Variable "project" does not exist.', 233, $this->getSourceContext()); })()), "config", array(0 => "simulate_namespaces"), "method")) {
echo "</a>";
}
// line 234
echo " </div>
<div class=\"bd\">
";
// line 236
echo $context["__internal_142ae502b5e16351d8341c4131a7cddf80b73f32c0cd1f5736568e36957bbd5e"]->macro_element(twig_get_attribute($this->env, $this->getSourceContext(), $context["element"], 2, array(), "array"), (isset($context["opened"]) || array_key_exists("opened", $context) ? $context["opened"] : (function () { throw new Twig_Error_Runtime('Variable "opened" does not exist.', 236, $this->getSourceContext()); })()), ((isset($context["depth"]) || array_key_exists("depth", $context) ? $context["depth"] : (function () { throw new Twig_Error_Runtime('Variable "depth" does not exist.', 236, $this->getSourceContext()); })()) + 1));
// line 237
echo "</div>
</li>
";
} else {
// line 240
echo " <li data-name=\"class:";
echo twig_escape_filter($this->env, twig_replace_filter(twig_get_attribute($this->env, $this->getSourceContext(), twig_get_attribute($this->env, $this->getSourceContext(), $context["element"], 1, array(), "array"), "name", array()), array("\\" => "_")), "html", null, true);
echo "\" ";
if (((isset($context["depth"]) || array_key_exists("depth", $context) ? $context["depth"] : (function () { throw new Twig_Error_Runtime('Variable "depth" does not exist.', 240, $this->getSourceContext()); })()) < (isset($context["opened"]) || array_key_exists("opened", $context) ? $context["opened"] : (function () { throw new Twig_Error_Runtime('Variable "opened" does not exist.', 240, $this->getSourceContext()); })()))) {
echo "class=\"opened\"";
}
echo ">
<div style=\"padding-left:";
// line 241
echo twig_escape_filter($this->env, (8 + ((isset($context["depth"]) || array_key_exists("depth", $context) ? $context["depth"] : (function () { throw new Twig_Error_Runtime('Variable "depth" does not exist.', 241, $this->getSourceContext()); })()) * 18)), "html", null, true);
echo "px\" class=\"hd leaf\">
<a href=\"";
// line 242
echo $this->env->getExtension('Sami\Renderer\TwigExtension')->pathForClass($context, twig_get_attribute($this->env, $this->getSourceContext(), $context["element"], 1, array(), "array"));
echo "\">";
echo twig_escape_filter($this->env, twig_get_attribute($this->env, $this->getSourceContext(), $context["element"], 0, array(), "array"), "html", null, true);
echo "</a>
</div>
</li>
";
}
}
$_parent = $context['_parent'];
unset($context['_seq'], $context['_iterated'], $context['_key'], $context['element'], $context['_parent'], $context['loop']);
$context = array_intersect_key($context, $_parent) + $_parent;
// line 247
echo " </ul>
";
return ('' === $tmp = ob_get_contents()) ? '' : new Twig_Markup($tmp, $this->env->getCharset());
} finally {
ob_end_clean();
}
}
|
line 225
|
entailment
|
public function block_below_menu($context, array $blocks = array())
{
// line 8
echo " ";
if (twig_get_attribute($this->env, $this->getSourceContext(), (isset($context["class"]) || array_key_exists("class", $context) ? $context["class"] : (function () { throw new Twig_Error_Runtime('Variable "class" does not exist.', 8, $this->getSourceContext()); })()), "namespace", array())) {
// line 9
echo " <div class=\"namespace-breadcrumbs\">
<ol class=\"breadcrumb\">
<li><span class=\"label label-default\">";
// line 11
echo twig_get_attribute($this->env, $this->getSourceContext(), (isset($context["class"]) || array_key_exists("class", $context) ? $context["class"] : (function () { throw new Twig_Error_Runtime('Variable "class" does not exist.', 11, $this->getSourceContext()); })()), "categoryName", array());
echo "</span></li>
";
// line 12
echo $context["__internal_c3e02cbf21b415a504b5c5536156934c225c78f939c0acb972d28e16dd434727"]->macro_breadcrumbs(twig_get_attribute($this->env, $this->getSourceContext(), (isset($context["class"]) || array_key_exists("class", $context) ? $context["class"] : (function () { throw new Twig_Error_Runtime('Variable "class" does not exist.', 12, $this->getSourceContext()); })()), "namespace", array()));
// line 13
echo "<li>";
echo twig_get_attribute($this->env, $this->getSourceContext(), (isset($context["class"]) || array_key_exists("class", $context) ? $context["class"] : (function () { throw new Twig_Error_Runtime('Variable "class" does not exist.', 13, $this->getSourceContext()); })()), "shortname", array());
echo "</li>
</ol>
</div>
";
}
}
|
line 7
|
entailment
|
public function block_page_content($context, array $blocks = array())
{
// line 20
echo "
<div class=\"page-header\">
<h1>
";
// line 23
echo twig_last($this->env, twig_split_filter($this->env, twig_get_attribute($this->env, $this->getSourceContext(), (isset($context["class"]) || array_key_exists("class", $context) ? $context["class"] : (function () { throw new Twig_Error_Runtime('Variable "class" does not exist.', 23, $this->getSourceContext()); })()), "name", array()), "\\"));
echo "
";
// line 24
echo $context["__internal_c3e02cbf21b415a504b5c5536156934c225c78f939c0acb972d28e16dd434727"]->macro_deprecated((isset($context["class"]) || array_key_exists("class", $context) ? $context["class"] : (function () { throw new Twig_Error_Runtime('Variable "class" does not exist.', 24, $this->getSourceContext()); })()));
echo "
</h1>
</div>
<p>";
// line 28
$this->displayBlock("class_signature", $context, $blocks);
echo "</p>
";
// line 30
echo $context["__internal_c3e02cbf21b415a504b5c5536156934c225c78f939c0acb972d28e16dd434727"]->macro_deprecations((isset($context["class"]) || array_key_exists("class", $context) ? $context["class"] : (function () { throw new Twig_Error_Runtime('Variable "class" does not exist.', 30, $this->getSourceContext()); })()));
echo "
";
// line 32
if ((twig_get_attribute($this->env, $this->getSourceContext(), (isset($context["class"]) || array_key_exists("class", $context) ? $context["class"] : (function () { throw new Twig_Error_Runtime('Variable "class" does not exist.', 32, $this->getSourceContext()); })()), "shortdesc", array()) || twig_get_attribute($this->env, $this->getSourceContext(), (isset($context["class"]) || array_key_exists("class", $context) ? $context["class"] : (function () { throw new Twig_Error_Runtime('Variable "class" does not exist.', 32, $this->getSourceContext()); })()), "longdesc", array()))) {
// line 33
echo " <div class=\"description\">
";
// line 34
if (twig_get_attribute($this->env, $this->getSourceContext(), (isset($context["class"]) || array_key_exists("class", $context) ? $context["class"] : (function () { throw new Twig_Error_Runtime('Variable "class" does not exist.', 34, $this->getSourceContext()); })()), "shortdesc", array())) {
// line 35
echo "<p>";
echo $this->env->getExtension('Sami\Renderer\TwigExtension')->parseDesc($context, twig_get_attribute($this->env, $this->getSourceContext(), (isset($context["class"]) || array_key_exists("class", $context) ? $context["class"] : (function () { throw new Twig_Error_Runtime('Variable "class" does not exist.', 35, $this->getSourceContext()); })()), "shortdesc", array()), (isset($context["class"]) || array_key_exists("class", $context) ? $context["class"] : (function () { throw new Twig_Error_Runtime('Variable "class" does not exist.', 35, $this->getSourceContext()); })()));
echo "</p>";
}
// line 37
echo " ";
if (twig_get_attribute($this->env, $this->getSourceContext(), (isset($context["class"]) || array_key_exists("class", $context) ? $context["class"] : (function () { throw new Twig_Error_Runtime('Variable "class" does not exist.', 37, $this->getSourceContext()); })()), "longdesc", array())) {
// line 38
echo "<p>";
echo $this->env->getExtension('Sami\Renderer\TwigExtension')->parseDesc($context, twig_get_attribute($this->env, $this->getSourceContext(), (isset($context["class"]) || array_key_exists("class", $context) ? $context["class"] : (function () { throw new Twig_Error_Runtime('Variable "class" does not exist.', 38, $this->getSourceContext()); })()), "longdesc", array()), (isset($context["class"]) || array_key_exists("class", $context) ? $context["class"] : (function () { throw new Twig_Error_Runtime('Variable "class" does not exist.', 38, $this->getSourceContext()); })()));
echo "</p>";
}
// line 40
echo " ";
if ((twig_get_attribute($this->env, $this->getSourceContext(), (isset($context["project"]) || array_key_exists("project", $context) ? $context["project"] : (function () { throw new Twig_Error_Runtime('Variable "project" does not exist.', 40, $this->getSourceContext()); })()), "config", array(0 => "insert_todos"), "method") == true)) {
// line 41
echo " ";
echo $context["__internal_c3e02cbf21b415a504b5c5536156934c225c78f939c0acb972d28e16dd434727"]->macro_todos((isset($context["class"]) || array_key_exists("class", $context) ? $context["class"] : (function () { throw new Twig_Error_Runtime('Variable "class" does not exist.', 41, $this->getSourceContext()); })()));
echo "
";
}
// line 43
echo " </div>
";
}
// line 45
echo "
";
// line 46
if ((isset($context["traits"]) || array_key_exists("traits", $context) ? $context["traits"] : (function () { throw new Twig_Error_Runtime('Variable "traits" does not exist.', 46, $this->getSourceContext()); })())) {
// line 47
echo " <h2>Traits</h2>
";
// line 49
echo $context["__internal_c3e02cbf21b415a504b5c5536156934c225c78f939c0acb972d28e16dd434727"]->macro_render_classes((isset($context["traits"]) || array_key_exists("traits", $context) ? $context["traits"] : (function () { throw new Twig_Error_Runtime('Variable "traits" does not exist.', 49, $this->getSourceContext()); })()));
echo "
";
}
// line 51
echo "
";
// line 52
if ((isset($context["constants"]) || array_key_exists("constants", $context) ? $context["constants"] : (function () { throw new Twig_Error_Runtime('Variable "constants" does not exist.', 52, $this->getSourceContext()); })())) {
// line 53
echo " <h2>Constants</h2>
";
// line 55
$this->displayBlock("constants", $context, $blocks);
echo "
";
}
// line 57
echo "
";
// line 58
if ((isset($context["properties"]) || array_key_exists("properties", $context) ? $context["properties"] : (function () { throw new Twig_Error_Runtime('Variable "properties" does not exist.', 58, $this->getSourceContext()); })())) {
// line 59
echo " <h2>Properties</h2>
";
// line 61
$this->displayBlock("properties", $context, $blocks);
echo "
";
}
// line 63
echo "
";
// line 64
if ((isset($context["methods"]) || array_key_exists("methods", $context) ? $context["methods"] : (function () { throw new Twig_Error_Runtime('Variable "methods" does not exist.', 64, $this->getSourceContext()); })())) {
// line 65
echo " <h2>Methods</h2>
";
// line 67
$this->displayBlock("methods", $context, $blocks);
echo "
<h2>Details</h2>
";
// line 71
$this->displayBlock("methods_details", $context, $blocks);
echo "
";
}
// line 73
echo "
";
}
|
line 19
|
entailment
|
public function block_return($context, array $blocks = array())
{
// line 122
echo " <table class=\"table table-condensed\">
<tr>
<td>";
// line 124
echo $context["__internal_c3e02cbf21b415a504b5c5536156934c225c78f939c0acb972d28e16dd434727"]->macro_hint_link(twig_get_attribute($this->env, $this->getSourceContext(), (isset($context["method"]) || array_key_exists("method", $context) ? $context["method"] : (function () { throw new Twig_Error_Runtime('Variable "method" does not exist.', 124, $this->getSourceContext()); })()), "hint", array()));
echo "</td>
<td>";
// line 125
echo $this->env->getExtension('Sami\Renderer\TwigExtension')->parseDesc($context, twig_get_attribute($this->env, $this->getSourceContext(), (isset($context["method"]) || array_key_exists("method", $context) ? $context["method"] : (function () { throw new Twig_Error_Runtime('Variable "method" does not exist.', 125, $this->getSourceContext()); })()), "hintDesc", array()), (isset($context["class"]) || array_key_exists("class", $context) ? $context["class"] : (function () { throw new Twig_Error_Runtime('Variable "class" does not exist.', 125, $this->getSourceContext()); })()));
echo "</td>
</tr>
</table>
";
}
|
line 121
|
entailment
|
public function service($service,$session = null)
{
$this->service = (new Service($service,$session ?: $this->session));
return $this->service;
}
|
Set the google adwords service.
@param \Google\AdsApi\AdWords\v201809\cm\* $service
@param \Google\AdsApi\AdWords\AdWordsSession|null $session
@return Service
|
entailment
|
private function loadData($my_std_class,$property,$subProperty)
{
if(property_exists($my_std_class,$property))
{
return $my_std_class->$property->{'@attributes'}->$subProperty;
}
}
|
Load the report name.
@param $my_std_class
@param $property
@param $subProperty
@return mixed
|
entailment
|
private function loadFields($my_std_class)
{
if(property_exists($my_std_class->table,'columns'))
{
foreach ($my_std_class->table->columns->column as $column)
{
$this->fields->push($this->convertToStdClass($column));
}
}
}
|
Load the report columns
@param $my_std_class
|
entailment
|
private function loadResults($my_std_class)
{
if(property_exists($my_std_class->table,'row'))
{
foreach ($my_std_class->table->row as $row)
{
$this->result->push($this->convertToStdClass($row));
}
}
}
|
Load the report rows
@param $my_std_class
|
entailment
|
public function block_page_content($context, array $blocks = array())
{
// line 7
echo "
<div class=\"page-header\">
<h1>Index</h1>
</div>
<ul class=\"pagination\">
";
// line 13
$context['_parent'] = $context;
$context['_seq'] = twig_ensure_traversable(range("A", "Z"));
foreach ($context['_seq'] as $context["_key"] => $context["letter"]) {
// line 14
echo " ";
if ((twig_get_attribute($this->env, $this->getSourceContext(), ($context["items"] ?? null), $context["letter"], array(), "array", true, true) && (twig_length_filter($this->env, twig_get_attribute($this->env, $this->getSourceContext(), (isset($context["items"]) || array_key_exists("items", $context) ? $context["items"] : (function () { throw new Twig_Error_Runtime('Variable "items" does not exist.', 14, $this->getSourceContext()); })()), $context["letter"], array(), "array")) > 1))) {
// line 15
echo " <li><a href=\"#letter";
echo $context["letter"];
echo "\">";
echo $context["letter"];
echo "</a></li>
";
} else {
// line 17
echo " <li class=\"disabled\"><a href=\"#letter";
echo $context["letter"];
echo "\">";
echo $context["letter"];
echo "</a></li>
";
}
// line 19
echo " ";
}
$_parent = $context['_parent'];
unset($context['_seq'], $context['_iterated'], $context['_key'], $context['letter'], $context['_parent'], $context['loop']);
$context = array_intersect_key($context, $_parent) + $_parent;
// line 20
echo " </ul>
";
// line 22
$context['_parent'] = $context;
$context['_seq'] = twig_ensure_traversable((isset($context["items"]) || array_key_exists("items", $context) ? $context["items"] : (function () { throw new Twig_Error_Runtime('Variable "items" does not exist.', 22, $this->getSourceContext()); })()));
foreach ($context['_seq'] as $context["letter"] => $context["elements"]) {
// line 23
echo "<h2 id=\"letter";
echo $context["letter"];
echo "\">";
echo $context["letter"];
echo "</h2>
<dl id=\"index\">";
// line 25
$context['_parent'] = $context;
$context['_seq'] = twig_ensure_traversable($context["elements"]);
foreach ($context['_seq'] as $context["_key"] => $context["element"]) {
// line 26
$context["type"] = twig_get_attribute($this->env, $this->getSourceContext(), $context["element"], 0, array(), "array");
// line 27
$context["value"] = twig_get_attribute($this->env, $this->getSourceContext(), $context["element"], 1, array(), "array");
// line 28
if (("class" == (isset($context["type"]) || array_key_exists("type", $context) ? $context["type"] : (function () { throw new Twig_Error_Runtime('Variable "type" does not exist.', 28, $this->getSourceContext()); })()))) {
// line 29
echo "<dt>";
echo $context["__internal_434f759af01c8cf4d7724fc6a375f1d077a7c773ee38bb417bfc9b1879a2a7e5"]->macro_class_link((isset($context["value"]) || array_key_exists("value", $context) ? $context["value"] : (function () { throw new Twig_Error_Runtime('Variable "value" does not exist.', 29, $this->getSourceContext()); })()));
if ((isset($context["has_namespaces"]) || array_key_exists("has_namespaces", $context) ? $context["has_namespaces"] : (function () { throw new Twig_Error_Runtime('Variable "has_namespaces" does not exist.', 29, $this->getSourceContext()); })())) {
echo " — <em>Class in namespace ";
echo $context["__internal_434f759af01c8cf4d7724fc6a375f1d077a7c773ee38bb417bfc9b1879a2a7e5"]->macro_namespace_link(twig_get_attribute($this->env, $this->getSourceContext(), (isset($context["value"]) || array_key_exists("value", $context) ? $context["value"] : (function () { throw new Twig_Error_Runtime('Variable "value" does not exist.', 29, $this->getSourceContext()); })()), "namespace", array()));
}
echo "</em></dt>
<dd>";
// line 30
echo $this->env->getExtension('Sami\Renderer\TwigExtension')->parseDesc($context, twig_get_attribute($this->env, $this->getSourceContext(), (isset($context["value"]) || array_key_exists("value", $context) ? $context["value"] : (function () { throw new Twig_Error_Runtime('Variable "value" does not exist.', 30, $this->getSourceContext()); })()), "shortdesc", array()), (isset($context["value"]) || array_key_exists("value", $context) ? $context["value"] : (function () { throw new Twig_Error_Runtime('Variable "value" does not exist.', 30, $this->getSourceContext()); })()));
echo "</dd>";
} elseif (("method" == // line 31
(isset($context["type"]) || array_key_exists("type", $context) ? $context["type"] : (function () { throw new Twig_Error_Runtime('Variable "type" does not exist.', 31, $this->getSourceContext()); })()))) {
// line 32
echo "<dt>";
echo $context["__internal_434f759af01c8cf4d7724fc6a375f1d077a7c773ee38bb417bfc9b1879a2a7e5"]->macro_method_link((isset($context["value"]) || array_key_exists("value", $context) ? $context["value"] : (function () { throw new Twig_Error_Runtime('Variable "value" does not exist.', 32, $this->getSourceContext()); })()));
echo "() — <em>Method in class ";
echo $context["__internal_434f759af01c8cf4d7724fc6a375f1d077a7c773ee38bb417bfc9b1879a2a7e5"]->macro_class_link(twig_get_attribute($this->env, $this->getSourceContext(), (isset($context["value"]) || array_key_exists("value", $context) ? $context["value"] : (function () { throw new Twig_Error_Runtime('Variable "value" does not exist.', 32, $this->getSourceContext()); })()), "class", array()));
echo "</em></dt>
<dd>";
// line 33
echo $this->env->getExtension('Sami\Renderer\TwigExtension')->parseDesc($context, twig_get_attribute($this->env, $this->getSourceContext(), (isset($context["value"]) || array_key_exists("value", $context) ? $context["value"] : (function () { throw new Twig_Error_Runtime('Variable "value" does not exist.', 33, $this->getSourceContext()); })()), "shortdesc", array()), twig_get_attribute($this->env, $this->getSourceContext(), (isset($context["value"]) || array_key_exists("value", $context) ? $context["value"] : (function () { throw new Twig_Error_Runtime('Variable "value" does not exist.', 33, $this->getSourceContext()); })()), "class", array()));
echo "</dd>";
} elseif (("property" == // line 34
(isset($context["type"]) || array_key_exists("type", $context) ? $context["type"] : (function () { throw new Twig_Error_Runtime('Variable "type" does not exist.', 34, $this->getSourceContext()); })()))) {
// line 35
echo "<dt>\$";
echo $context["__internal_434f759af01c8cf4d7724fc6a375f1d077a7c773ee38bb417bfc9b1879a2a7e5"]->macro_property_link((isset($context["value"]) || array_key_exists("value", $context) ? $context["value"] : (function () { throw new Twig_Error_Runtime('Variable "value" does not exist.', 35, $this->getSourceContext()); })()));
echo " — <em>Property in class ";
echo $context["__internal_434f759af01c8cf4d7724fc6a375f1d077a7c773ee38bb417bfc9b1879a2a7e5"]->macro_class_link(twig_get_attribute($this->env, $this->getSourceContext(), (isset($context["value"]) || array_key_exists("value", $context) ? $context["value"] : (function () { throw new Twig_Error_Runtime('Variable "value" does not exist.', 35, $this->getSourceContext()); })()), "class", array()));
echo "</em></dt>
<dd>";
// line 36
echo $this->env->getExtension('Sami\Renderer\TwigExtension')->parseDesc($context, twig_get_attribute($this->env, $this->getSourceContext(), (isset($context["value"]) || array_key_exists("value", $context) ? $context["value"] : (function () { throw new Twig_Error_Runtime('Variable "value" does not exist.', 36, $this->getSourceContext()); })()), "shortdesc", array()), twig_get_attribute($this->env, $this->getSourceContext(), (isset($context["value"]) || array_key_exists("value", $context) ? $context["value"] : (function () { throw new Twig_Error_Runtime('Variable "value" does not exist.', 36, $this->getSourceContext()); })()), "class", array()));
echo "</dd>";
}
}
$_parent = $context['_parent'];
unset($context['_seq'], $context['_iterated'], $context['_key'], $context['element'], $context['_parent'], $context['loop']);
$context = array_intersect_key($context, $_parent) + $_parent;
// line 39
echo " </dl>";
}
$_parent = $context['_parent'];
unset($context['_seq'], $context['_iterated'], $context['letter'], $context['elements'], $context['_parent'], $context['loop']);
$context = array_intersect_key($context, $_parent) + $_parent;
}
|
line 6
|
entailment
|
public function format($format)
{
if(Format::exist($format))
$this->format = Format::get($format);
else
Format::invalidType();
return $this;
}
|
Set the format for the report.
@param $format
@return $this
|
entailment
|
public function from($reportType)
{
if(!ReportTypes::exist($reportType))
ReportTypes::invalidType();
$this->type = ReportTypes::get($reportType);
return $this;
}
|
Set the report type
@param $reportType
@return $this
|
entailment
|
public function during($starting,$ending)
{
if(! is_numeric($starting) || ! is_numeric($ending))
throw new \Edujugon\GoogleAds\Exceptions\Report('During clause only accepts the following date format: "Ymd" => e.g. 20170112');
$this->during = [$starting,$ending];
return $this;
}
|
Set the starting and ending dates for the report.
dates format 'Ymd' => e.g. 20170112,20171020
@param $starting
@param $ending
@return $this
@throws \Edujugon\GoogleAds\Exceptions\Report
|
entailment
|
public function getAsSimpleXMLObj()
{
$this->format(Format::get('xml'));
$this->run();
return simplexml_load_string($this->data->getAsString());
}
|
Get the report as a SimpleXMLObj
@return \SimpleXMLElement
|
entailment
|
public function getAsObj()
{
$this->format(Format::get('xml'));
$this->run();
return (new MyReport(simplexml_load_string($this->data->getAsString())));
}
|
Get the report as an object
@return \Edujugon\GoogleAds\Reports\MyReport
|
entailment
|
public function saveToFile($filePath,$format = 'csvforexcel')
{
$this->format(Format::get($format));
$this->run();
$this->data->saveToFile($filePath);
return true;
}
|
Save the report in a file.
@param $filePath
@param string $format
@return bool
|
entailment
|
private function run()
{
if($this->magicSelect){
$this->selectAllFields();
$this->magicRun();
}
$query = $this->createQuery();
$this->data = $this->reportDownloader->downloadReportWithAwql(
$query, $this->format);
}
|
Run the AWQL
|
entailment
|
private function magicRun()
{
$query = $this->createQuery();
try{
$this->data = $this->reportDownloader->downloadReportWithAwql(
$query, $this->format);
}catch(ApiException $e)
{
$field = $e->getErrors()[0]->getFieldPath();
if(!empty($field)){
$this->except($field);
$this->magicRun();
}else
var_dump($e->getMessage());
}
}
|
Magic Run the AWQL
Will try to download the report and if fails,
It pulls out the conflicted field and try again the download.
|
entailment
|
public function except($excepts)
{
$excepts = is_array($excepts) ? $excepts : func_get_args();
$this->fields = array_filter($this->fields,function($field) use($excepts){
return !in_array($field,$excepts);
});
return $this;
}
|
Pull fields out of fields list.
@param $excepts
@return $this
|
entailment
|
public function oAuth($env = null, $data = [])
{
$this->oAuth2Credential = (new OAuth2($env))->userCredentials($data);
return $this;
}
|
Create OAuth2 credential
@param null $env
@param array|null $data
@return $this
|
entailment
|
public function build(array $data = [])
{
if(!$this->oAuth2Credential)
$this->oAuth();
$data = $this->mergeData($data);
$adwordsSession = new AdWordsSessionBuilder();
return $adwordsSession->withDeveloperToken($data['developerToken'])
->withClientCustomerId($data['clientCustomerId'])
->withOAuth2Credential($this->oAuth2Credential)
->build();
}
|
Construct an API session configured from global config data file or passed data
@param array $data
@return mixed
|
entailment
|
public function buildWithOAuth($developerToken, $oAuth2Credential)
{
$adwordsSession = new AdWordsSessionBuilder();
return $adwordsSession->withDeveloperToken($developerToken)
->withOAuth2Credential($oAuth2Credential)
->build();
}
|
Construct an API session from OAuth2
@param string $developerToken
@param \Google\Auth\Credentials\UserRefreshCredentials $oAuth2Credential
@return mixed
|
entailment
|
public function setProtection($permissions, $userPass = '', $ownerPass = null, $revision = 3)
{
if ($revision < 2 || $revision > 3) {
throw new \InvalidArgumentException('Only revision 2 or 3 are supported.');
}
if ($revision === 3) {
$this->setMinPdfVersion('1.4');
}
$this->pValue = $this->sanitizePermissionsValue($permissions, $revision);
if ($ownerPass === null || $ownerPass === '') {
$ownerPass = function_exists('random_bytes') ? \random_bytes(32) : uniqid(rand());
}
$this->encrypted = true;
$this->revision = $revision;
$this->keyLength = $revision === 3 ? 16 : 5;
$this->padding = "\x28\xBF\x4E\x5E\x4E\x75\x8A\x41\x64\x00\x4E\x56\xFF\xFA\x01\x08"
. "\x2E\x2E\x00\xB6\xD0\x68\x3E\x80\x2F\x0C\xA9\xFE\x64\x53\x69\x7A";
$this->oValue = $this->computeOValue($userPass, $ownerPass);
$this->encryptionKey = $this->computeEncryptionKey($userPass);
$this->uValue = $this->computeUValue($this->encryptionKey);
return $ownerPass;
}
|
Set permissions as well as user and owner passwords
@param int|array $permissions An array of permission values (see class constants) or the sum of the constant
values. If a value is present it means that the permission is granted.
@param string $userPass If a user password is set, user will be prompted before document is opened.
@param null $ownerPass If an owner password is set, document can be opened in privilege mode with no
restriction if that password is entered.
@param int $revision The revision number of the security handler (2 = RC4-40bits, 3 = RC4-128bits)
@return string The owner password
|
entailment
|
public function sanitizePermissionsValue($permissions, $revision)
{
if (is_array($permissions)) {
$legacyOptions = ['print' => 4, 'modify' => 8, 'copy' => 16, 'annot-forms' => 32];
foreach ($permissions as $key => $value) {
if (isset($legacyOptions[$value])) {
$permissions[$key] = $legacyOptions[$value];
} elseif (!is_int($value)) {
throw new \InvalidArgumentException(
sprintf('Invalid permission value: %s', $value)
);
}
}
$permissions = array_sum($permissions);
}
$permissions = (int)$permissions;
$allowed = self::PERM_PRINT
| self::PERM_MODIFY
| self::PERM_COPY
| self::PERM_ANNOT;
if ($revision > 2) {
$allowed |= self::PERM_FILL_FORM
| self::PERM_ACCESSIBILITY
| self::PERM_ASSEMBLE
| self::PERM_DIGITAL_PRINT;
}
if (($allowed & $permissions) !== $permissions) {
throw new \InvalidArgumentException(
sprintf(
'Permission flags (%s) are not allowed for this security handler revision %s.',
$permissions,
$revision
)
);
}
$permissions = 61632 | 0xFFFF0000 | $permissions;
if ($revision < 3) {
// 3840 = bit 9 to 12 to 1 - we are < revision 3
$permissions |= 3840;
}
// PDF integer are 32 bit integers. Ensure this.
if (PHP_INT_SIZE === 4 || ($permissions) < (2147483647)) {
return $permissions;
}
return ($permissions | (4294967295 << 32));
}
|
Ensures a valid permission value.
@param int[]|int$permissions
@param int $revision
@return int
|
entailment
|
protected function computeOValue($userPassword, $ownerPassword = '')
{
$revision = $this->revision;
// Algorithm 3: Computing the encryption dictionary’s O (owner password) value
// a) Pad or truncate the owner password string as described in step (a) of
// "Algorithm 2: Computing an encryption key". If there is no owner password,
// use the user password instead.
if ('' === $ownerPassword)
$ownerPassword = $userPassword;
$s = substr($ownerPassword . $this->padding, 0, 32);
// b) Initialize the MD5 hash function and pass the result of step (a) as input to
// this function.
$s = md5($s, true);
// c) (Security handlers of revision 3 or greater) Do the following 50 times:
// Take the output from the previous MD5 hash and pass it as input into a new MD5 hash.
if ($revision >= 3) {
for ($i = 0; $i < 50; $i++)
$s = md5($s, true);
}
// d) Create an RC4 encryption key using the first n bytes of the output from the
// final MD5 hash, where n shall always be 5 for security handlers of revision 2
// but, for security handlers of revision 3 or greater, shall depend on the value
// of the encryption dictionary’s Length entry.
$encryptionKey = substr($s, 0, $this->keyLength);
// e) Pad or truncate the user password string as described in step (a) of
// "Algorithm 2: Computing an encryption key".
$s = substr($userPassword . $this->padding, 0, 32);
// f) Encrypt the result of step (e), using an RC4 encryption function with
// the encryption key obtained in step (d).
$s = $this->arcfour($encryptionKey, $s);
// g) (Security handlers of revision 3 or greater) Do the following 19 times:
// Take the output from the previous invocation of the RC4 function and pass
// it as input to a new invocation of the function; use an encryption key
// generated by taking each byte of the encryption key obtained in step (d)
// and performing an XOR (exclusive or) operation between that byte and the
// single-byte value of the iteration counter (from 1 to 19).
if ($revision >= 3) {
for ($i = 1; $i <= 19; $i++) {
$tmp = array();
for ($j = 0; $j < $this->keyLength; $j++) {
$tmp[$j] = ord($encryptionKey[$j]) ^ $i;
$tmp[$j] = chr($tmp[$j]);
}
$s = $this->arcfour(join('', $tmp), $s);
}
}
// h) Store the output from the final invocation of the RC4 function as the value
// of the O entry in the encryption dictionary.
return $s;
}
|
Compute the O value.
@param string $userPassword
@param string $ownerPassword
@return string
|
entailment
|
protected function computeEncryptionKey($password = '')
{
$revision = $this->revision;
// TODO: The password string is generated from OS codepage characters by first
// converting the string to PDFDocEncoding. If the input is Unicode, first convert
// to a codepage encoding, and then to PDFDocEncoding for backward compatibility.
// Algorithm 2: Computing an encryption key
// a) Pad or truncate the password string to exactly 32 bytes.
// b) Initialize the MD5 hash function and pass the result of step (a) as input to this function.
$s = substr($password . $this->padding, 0, 32);
// c) Pass the value of the encryption dictionary’s O entry to the MD5 hash function.
// ("Algorithm 3: Computing the encryption dictionary’s O (owner password) value" shows how the O value is computed.)
$s .= $this->oValue;
// d) Convert the integer value of the P entry to a 32-bit unsigned binary number and pass these
// bytes to the MD5 hash function, low-order byte first.
$pValue = (int)(float)$this->pValue;
$s .= pack("V", $pValue);
// e) Pass the first element of the file’s file identifier array (the value of the ID
// entry in the document’s trailer dictionary; see Table 15) to the MD5 hash function.
$s .= $this->fileIdentifier;
// f) (Security handlers of revision 4 or greater) If document metadata is not
// being encrypted, pass 4 bytes with the value 0xFFFFFFFF to the MD5 hash function.
// ...
// g) Finish the hash.
$s = md5($s, true);
// h) (Security handlers of revision 3 or greater) Do the following 50 times:
// Take the output from the previous MD5 hash and pass the first n bytes of
// the output as input into a new MD5 hash, where n is the number of bytes
// of the encryption key as defined by the value of the encryption dictionary’s
// Length entry.
if ($revision >= 3) {
for ($i = 0; $i < 50; $i++)
$s = md5(substr($s, 0, $this->keyLength), true);
}
// i) Set the encryption key to the first n bytes of the output from the final
// MD5 hash, where n shall always be 5 for security handlers of revision 2 but,
// for security handlers of revision 3 or greater, shall depend on the value of
// the encryption dictionary’s Length entry.
return substr($s, 0, $this->keyLength); // key length is calculated automatically if it is missing (5)
}
|
Compute the encryption key based on a password.
@param string $password
@return string
|
entailment
|
protected function computeUValue($encryptionKey)
{
$revision = $this->revision;
// Algorithm 4: Computing the encryption dictionary’s U (user password)
// value (Security handlers of revision 2)
if ($revision < 3) {
return $this->arcfour($encryptionKey, $this->padding);
}
// Algorithm 5: Computing the encryption dictionary’s U (user password)
// value (Security handlers of revision 3 or greater)
// a) Create an encryption key based on the user password string, as described
// in "Algorithm 2: Computing an encryption key".
// passed through $encryptionKey-parameter
// b) Initialize the MD5 hash function and pass the 32-byte padding string shown
// in step (a) of "Algorithm 2: Computing an encryption key" as input to
// this function.
$s = $this->padding;
// c) Pass the first element of the file’s file identifier array (the value of
// the ID entry in the document’s trailer dictionary; see Table 15) to the
// hash function and finish the hash.
$s .= $this->fileIdentifier;
$s = md5($s, true);
// d) Encrypt the 16-byte result of the hash, using an RC4 encryption function
// with the encryption key from step (a).
$s = $this->arcfour($encryptionKey, $s);
// e) Do the following 19 times: Take the output from the previous invocation
// of the RC4 function and pass it as input to a new invocation of the function;
// use an encryption key generated by taking each byte of the original encryption
// key obtained in step (a) and performing an XOR (exclusive or) operation
// between that byte and the single-byte value of the iteration counter (from 1 to 19).
$length = strlen($encryptionKey);
for($i = 1; $i <= 19; $i++) {
$tmp = array();
for($j = 0; $j < $length; $j++) {
$tmp[$j] = ord($encryptionKey[$j]) ^ $i;
$tmp[$j] = chr($tmp[$j]);
}
$s = $this->arcfour(join('', $tmp), $s);
}
// f) Append 16 bytes of arbitrary padding to the output from the final invocation
// of the RC4 function and store the 32-byte result as the value of the U entry
// in the encryption dictionary.
return $s . str_repeat("\0", 16);
}
|
Compute the U value.
@param string $encryptionKey
@return string
|
entailment
|
protected function writePdfType(PdfType $value)
{
if (!$this->encrypted) {
parent::writePdfType($value);
return;
}
if ($value instanceof PdfString) {
$string = PdfString::unescape($value->value);
$string = $this->arcfour($this->getEncryptionKeyByObjectNumber($this->currentObjectNumber), $string);
$value->value = $this->_escape($string);
} elseif ($value instanceof PdfHexString) {
$filter = new AsciiHex();
$string = $filter->decode($value->value);
$string = $this->arcfour($this->getEncryptionKeyByObjectNumber($this->currentObjectNumber), $string);
$value->value = $filter->encode($string, true);
} elseif ($value instanceof PdfStream) {
$stream = $value->getStream();
$stream = $this->arcfour($this->getEncryptionKeyByObjectNumber($this->currentObjectNumber), $stream);
$dictionary = $value->value;
$dictionary->value['Length'] = PdfNumeric::create(strlen($stream));
$value = PdfStream::create($dictionary, $stream);
}
parent::writePdfType($value);
}
|
Writes a PdfType object to the resulting buffer.
@param PdfType $value
|
entailment
|
protected function getEncryptionKeyByObjectNumber($objectNumber)
{
return substr(
substr(
md5($this->encryptionKey . pack('VXxx', $objectNumber), true),
0,
$this->keyLength + 5
),
0,
16
);
}
|
Computes the encryption key by an object number
@param int $objectNumber
@return bool|string
|
entailment
|
protected function _putencryption()
{
$this->_put('/Filter /Standard');
$this->_put('/V ' . ($this->revision === 3 ? '2' : '1'));
$this->_put('/R ' . ($this->revision === 3 ? '3' : '2'));
if ($this->revision === 3) {
$this->_put('/Length 128');
}
$this->_put('/O (' . $this->_escape($this->oValue) . ')');
$this->_put('/U (' . $this->_escape($this->uValue) . ')');
$this->_put('/P ' . $this->pValue);
}
|
Writes the values of the encryption dictionary.
|
entailment
|
protected function configure()
{
parent::configure();
$this->configFile = "{$this->root}/resources/assets/config.json";
$this->config = json_decode(file_get_contents($this->configFile), true);
$this->addOption(
'url',
null,
InputOption::VALUE_REQUIRED,
"Local development URL of WP site <comment>[default: \"{$this->config['devUrl']}\"]</comment>",
null
);
$this->addOption(
'path',
null,
InputOption::VALUE_REQUIRED,
'Path to theme directory (e.g., /wp-content/themes/'.basename($this->root).') '
."<comment>[default: \"{$this->config['publicPath']}\"]</comment>",
null
);
}
|
{@inheritdoc}
|
entailment
|
protected function interact(InputInterface $input, OutputInterface $output)
{
$url = $this->option('url')
?: $this->ask('Local development URL of WP site', $this->config['devUrl']);
$path = $this->option('path')
?: $this->ask(
'Path to theme directory (e.g., /wp-content/themes/'.basename($this->root).')',
$this->config['publicPath']
);
$this->config['devUrl'] = rtrim($url, '/');
$this->config['publicPath'] = rtrim($path, '/');
}
|
{@inheritdoc}
|
entailment
|
protected function execute(InputInterface $input, OutputInterface $output)
{
file_put_contents(
$this->configFile,
preg_replace_callback('/^ +/m', function ($matches) {
return str_repeat(' ', strlen($matches[0]) / 2);
}, json_encode($this->config, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT).PHP_EOL)
);
}
|
{@inheritdoc}
|
entailment
|
protected function configure()
{
parent::configure();
$this->themeHeaders = new ThemeHeaders("{$this->root}/resources/style.css");
$this->gatherOptionsData();
$this->addOptions();
}
|
{@inheritdoc}
|
entailment
|
protected function interact(InputInterface $input, OutputInterface $output)
{
$this->options->map(function ($data) {
extract($data);
$data['header']['value'] = $this->option($option) === $default
? $this->ask($question, $default)
: $this->option($option);
return $data;
});
}
|
{@inheritdoc}
|
entailment
|
protected function execute(InputInterface $input, OutputInterface $output)
{
$headers = $this->options
->pluck('header')
->flatMap(function ($header) {
extract($header->all());
return [$key => $value];
});
$this->themeHeaders->replaceHeaders($headers);
}
|
{@inheritdoc}
|
entailment
|
public function filesToOverwrite()
{
$files = new Filesystem;
$stubs = array_map(function (SplFileInfo $file) {
return $file->getRelativePathname();
}, $files->allFiles("{$this->sageRoot}/resources/assets"));
return array_intersect($stubs, $this->getFileList());
}
|
List of files that will be overwritten
@return array
|
entailment
|
public function getFileList()
{
$files = new Filesystem;
return array_map(function (SplFileInfo $file) {
return $file->getRelativePathname();
}, $files->allFiles($this->stubDirectory));
}
|
List of files to be copied
@return array
|
entailment
|
public function handle()
{
$this->makeDirectories();
if (!$this->addOn) {
$this->removePresets();
}
$this->copyFiles();
$this->updatePackages();
$this->removeNodeModules();
}
|
Preset handler
Call this method to run the preset
@return void
|
entailment
|
protected function removePresets()
{
$files = new Filesystem;
$files->delete("{$this->sageRoot}/resources/assets/styles/autoload/_tachyons.scss");
$files->delete("{$this->sageRoot}/resources/assets/styles/autoload/_bootstrap.scss");
$files->delete("{$this->sageRoot}/resources/assets/styles/autoload/_bulma.scss");
$files->delete("{$this->sageRoot}/resources/assets/styles/autoload/_foundation.scss");
$files->delete("{$this->sageRoot}/resources/assets/scripts/autoload/_bootstrap.js");
$files->delete("{$this->sageRoot}/resources/assets/scripts/autoload/_foundation.js");
$files->delete("{$this->sageRoot}/resources/assets/build/webpack.config.preset.js");
$files->delete("{$this->sageRoot}/resources/assets/styles/tailwind.config.js");
}
|
Remove presets
Removes previously loaded presets from the autoload, build, and styles folder
@return void
|
entailment
|
protected function copyFiles()
{
$files = new Filesystem;
array_map(function ($file) use ($files) {
$files->copy("{$this->stubDirectory}/{$file}", "{$this->sageRoot}/resources/assets/{$file}");
}, $this->getFileList());
}
|
Copy files from stubs directory to theme
@return void
|
entailment
|
protected function updatePackages($packagesFile = '')
{
$packagesFile = $packagesFile ?: "{$this->sageRoot}/package.json";
$packages = json_decode(file_get_contents($packagesFile), true);
if (!$this->addOn) {
$packages = $this->removePresetsFromPackagesArray($packages);
}
$packages = $this->updatePackagesArray($packages);
ksort($packages['devDependencies']);
ksort($packages['dependencies']);
file_put_contents(
$packagesFile,
preg_replace_callback('/^ +/m', function ($matches) {
return str_repeat(' ', strlen($matches[0]) / 2);
}, json_encode($packages, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT).PHP_EOL)
);
}
|
Update package.json
@param string $packagesFile Location of package.json
@return void
|
entailment
|
protected function execute(InputInterface $input, OutputInterface $output)
{
if (!in_array($this->argument('framework'), $this->presets->slugs())) {
throw new InvalidArgumentException('Invalid preset.');
}
$preset = $this->presets[$this->argument('framework')];
if (!$this->confirmOverwrite($preset->filesToOverwrite())) {
$this->info('No actions were taken.');
return;
}
$preset->handle();
$this->info(' Done.');
// phpcs:disable
if ($this->confirm("Send anonymous usage data? \n<comment> We are only sending your framework selection and OS</comment>\n\n")) {
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'https://stats.roots.io/i?device_id='.Uuid::uuid4().'&app_key=fd022e092a7ff07e996ca3cec86847bf1baf0879&begin_session=1&events=[{"key":"framework_selected","count":1,"segmentation":{"framework":"'.$this->argument('framework').'"}}]&metrics={"_os":"'.PHP_OS.'","_browser":"null","_browser_version":"0","_device":"null"}&end_session=1&session_duration=30',
CURLOPT_USERAGENT => 'sage-installer-composer'
]);
$resp = curl_exec($curl);
curl_close($curl);
}
// phpcs:enable
$this->comment('Please run `yarn && yarn build` to compile your fresh scaffolding.');
$this->comment('');
$this->comment('Help support our open-source development efforts by contributing to Sage via Patreon:');
$this->comment('https://www.patreon.com/rootsdev');
$this->comment('Join us on the Roots Slack when you become a supporter!');
}
|
{@inheritdoc}
|
entailment
|
protected function confirmOverwrite(array $files = [])
{
if (!$files || $this->option('overwrite')) {
return true;
}
$files = implode("\n - ", $files);
return $this->confirm(
"Are you sure you want to overwrite the following files?\n<comment> - {$files}</comment>\n\n"
);
}
|
Confirm overwriting files
@return bool
|
entailment
|
public function run(InputInterface $input, OutputInterface $output)
{
try {
$this->validate();
} catch (ConfigureCommandException $error) {
$output->block(explode("\n", $error), null, 'error', ' ', true);
die();
}
parent::run($input, $output);
}
|
{@inheritdoc}
|
entailment
|
public function offsetSet($key, $value)
{
if (is_null($key)) {
$this->presets[] = $value;
} else {
$this->presets[$key] = $value;
}
}
|
{@inheritdoc}
|
entailment
|
public function load($resource, $type = null)
{
$collection = new RouteCollection();
$collection->addCollection(
$this->yamlFileLoader->import(__DIR__.'/../Resources/config/routing.yml')
);
return $collection;
}
|
{@inheritdoc}
|
entailment
|
public function execute($commandString)
{
$input = new StringInput($commandString);
$output = new StringOutput();
$application = $this->getApplication($input);
$formatter = $output->getFormatter();
$kernel = $application->getKernel();
chdir($kernel->getRootDir().'/..');
$input->setInteractive(false);
$formatter->setDecorated(true);
$output->setFormatter(new HtmlOutputFormatterDecorator($formatter));
$application->setAutoExit(false);
$errorCode = $application->run($input, $output);
return [
'input' => $commandString,
'output' => $output->getBuffer(),
'environment' => $kernel->getEnvironment(),
'error_code' => $errorCode,
];
}
|
{@inheritdoc}
|
entailment
|
public function format($message)
{
if (!$this->isDecorated()) {
return $message;
}
$formatted = $this->formatter->format($message);
$escaped = htmlspecialchars($formatted, ENT_QUOTES, 'UTF-8');
$converted = preg_replace_callback(self::CLI_COLORS_PATTERN, function ($matches) {
return $this->replaceFormat($matches);
}, $escaped);
return $converted;
}
|
{@inheritdoc}
|
entailment
|
public static function getModules() {
$req = new GetModulesRequest();
$resp = new GetModulesResponse();
ApiProxy::makeSyncCall('modules', 'GetModules', $req, $resp);
return $resp->getModuleList();
}
|
Gets an array of all the modules for the application.
@return string[] An array of string containing the names of the modules
associated with the application. The 'default' module will be included if
it exists, as will the name of the module that is associated with the
instance that calls this function.
|
entailment
|
public static function getVersions($module = null) {
$req = new GetVersionsRequest();
$resp = new GetVersionsResponse();
if ($module !== null) {
if (!is_string($module)) {
throw new \InvalidArgumentException(
'$module must be a string. Actual type: ' . gettype($module));
}
$req->setModule($module);
}
try {
ApiProxy::makeSyncCall('modules', 'GetVersions', $req, $resp);
} catch (ApplicationError $e) {
throw errorCodeToException($e->getApplicationError());
}
return $resp->getVersionList();
}
|
Get an array of all versions associated with a module.
@param string $module The name of the module to retrieve the versions for.
If null then the versions for the current module will be retrieved.
@return string[] An array of strings containing the names of versions
associated with the module. The current version will also be included in
this list.
@throws \InvalidArgumentException If $module is not a string.
@throws ModulesException If the given $module isn't valid.
@throws TransientModulesException if there is an issue fetching the
information.
|
entailment
|
public static function getDefaultVersion($module = null) {
$req = new GetDefaultVersionRequest();
$resp = new GetDefaultVersionResponse();
if ($module !== null) {
if (!is_string($module)) {
throw new \InvalidArgumentException(
'$module must be a string. Actual type: ' . gettype($module));
}
$req->setModule($module);
}
try {
ApiProxy::makeSyncCall('modules', 'GetDefaultVersion', $req, $resp);
} catch (ApplicationError $e) {
throw errorCodeToException($e->getApplicationError());
}
return $resp->getVersion();
}
|
Get the default version of a module.
@param string $module The name of the module to retrieve the default
versions for. If null then the default versions for the current module
will be retrieved.
@return string The default version of the module.
@throws \InvalidArgumentException If $module is not a string.
@throws ModulesException If the given $module is invalid or if no default
version could be found.
|
entailment
|
public static function getNumInstances($module = null, $version = null) {
$req = new GetNumInstancesRequest();
$resp = new GetNumInstancesResponse();
if ($module !== null) {
if (!is_string($module)) {
throw new \InvalidArgumentException(
'$module must be a string. Actual type: ' . gettype($module));
}
$req->setModule($module);
}
if ($version !== null) {
if (!is_string($version)) {
throw new \InvalidArgumentException(
'$version must be a string. Actual type: ' . gettype($version));
}
$req->setVersion($version);
}
try {
ApiProxy::makeSyncCall('modules', 'GetNumInstances', $req, $resp);
} catch (ApplicationError $e) {
throw self::errorCodeToException($e->getApplicationError());
}
return (int) $resp->getInstances();
}
|
Get the number of instances set for a version of a module.
This function does not work on automatically-scaled modules.
@param string $module The name of the module to retrieve the count for. If
null then the count for the current module will be retrieved.
@param string $version The version of the module to retrieve the count for.
If null then the count for the version of the current instance will be
retrieved.
@return integer The number of instances set for the current module
version.
@throws \InvalidArgumentException If $module or $version is not a string.
@throws ModulesException if the given combination of $module and $version
is invalid.
|
entailment
|
public static function setNumInstances($instances,
$module = null,
$version = null) {
$req = new SetNumInstancesRequest();
$resp = new SetNumInstancesResponse();
if (!is_int($instances)) {
throw new \InvalidArgumentException(
'$instances must be an integer. Actual type: ' . gettype($instances));
}
$req->setInstances($instances);
if ($module !== null) {
if (!is_string($module)) {
throw new \InvalidArgumentException(
'$module must be a string. Actual type: ' . gettype($module));
}
$req->setModule($module);
}
if ($version !== null) {
if (!is_string($version)) {
throw new \InvalidArgumentException(
'$version must be a string. Actual type: ' . gettype($version));
}
$req->setVersion($version);
}
try {
ApiProxy::makeSyncCall('modules', 'SetNumInstances', $req, $resp);
} catch (ApplicationError $e) {
throw self::errorCodeToException($e->getApplicationError());
}
}
|
Set the number of instances for a version of a module.
This function does not work on automatically-scaled modules.
@param string $module The name of the module to set the instance count for.
If null then the instance count for the current module will be set.
@param string $version The version of the module to set the instance count
for. If null then the count for the version of the current instance will
be set.
@throws \InvalidArgumentException If $instances is not an integer or if
$module or $version is not a string.
@throws ModulesException if the given combination of $module and $version
is invalid.
@throws TransientModulesException if there is an issue setting the
instance count.
|
entailment
|
public static function startVersion($module, $version) {
$req = new StartModuleRequest();
$resp = new StartModuleResponse();
if (!is_string($module)) {
throw new \InvalidArgumentException(
'$module must be a string. Actual type: ' . gettype($module));
}
$req->setModule($module);
if (!is_string($version)) {
throw new \InvalidArgumentException(
'$version must be a string. Actual type: ' . gettype($version));
}
$req->setVersion($version);
try {
ApiProxy::makeSyncCall('modules', 'StartModule', $req, $resp);
} catch (ApplicationError $e) {
throw self::errorCodeToException($e->getApplicationError());
}
}
|
Starts all instances of the given version of a module.
*
@param string $module The name of the module to start.
@param string $version The version of the module to start.
@throws \InvalidArgumentException If $module or $version is not a string.
@throws ModulesException if the given combination of $module and $version
is invalid.
@throws InvalidModuleStateException if the given $version is already
started or cannot be started.
@throws TransientModulesException if there is an issue starting the module
version.
|
entailment
|
public static function stopVersion($module = null, $version = null) {
$req = new StopModuleRequest();
$resp = new StopModuleResponse();
if ($module !== null) {
if (!is_string($module)) {
throw new \InvalidArgumentException(
'$module must be a string. Actual type: ' . gettype($module));
}
$req->setModule($module);
}
if ($version !== null) {
if (!is_string($version)) {
throw new \InvalidArgumentException(
'$version must be a string. Actual type: ' . gettype($version));
}
$req->setVersion($version);
}
try {
ApiProxy::makeSyncCall('modules', 'StopModule', $req, $resp);
} catch (ApplicationError $e) {
throw self::errorCodeToException($e->getApplicationError());
}
}
|
Stops all instances of the given version of a module.
*
@param string $module The name of the module to stop. If null then the
current module will be stopped.
@param string $version The version of the module to stop. If null then the
current version will be stopped.
@throws \InvalidArgumentException If $module or $version is not a string.
@throws ModulesException if the given combination of $module and $version
instance is invalid.
@throws InvalidModuleStateException if the given $version is already
stopped or cannot be stopped.
@throws TransientModulesException if there is an issue stopping the module
version.
|
entailment
|
public static function getHostname($module = null,
$version = null,
$instance = null) {
$req = new GetHostnameRequest();
$resp = new GetHostnameResponse();
if ($module !== null) {
if (!is_string($module)) {
throw new \InvalidArgumentException(
'$module must be a string. Actual type: ' . gettype($module));
}
$req->setModule($module);
}
if ($version !== null) {
if (!is_string($version)) {
throw new \InvalidArgumentException(
'$version must be a string. Actual type: ' . gettype($version));
}
$req->setVersion($version);
}
if ($instance !== null) {
if (!is_int($instance) && !is_string($instance)) {
throw new \InvalidArgumentException(
'$instance must be an integer or string. Actual type: ' .
gettype($instance));
}
$req->setInstance((string) $instance);
}
try {
ApiProxy::makeSyncCall('modules', 'GetHostname', $req, $resp);
} catch (ApplicationError $e) {
throw self::errorCodeToException($e->getApplicationError());
}
return $resp->getHostname();
}
|
Returns the hostname to use when contacting a module.
*
@param string $module The name of the module whose hostname should be
returned. If null then the hostname of the current module will be returned.
@param string $version The version of the module whose hostname should be
returned. If null then the hostname for the version of the current
instance will be returned.
@param string $instance The instance whose hostname should be returned. If
null then the load balanced hostname for the module will be returned. If
the module is not a fixed module then the instance parameter is ignored.
@return string The valid canonical hostname that can be used to communicate
with the given module/version/instance e.g.
"0.version1.module5.myapp.appspot.com".
@throws \InvalidArgumentException If $module or $version is not a string
or if $instance is not a string or integer.
@throws ModulesException if the given combination of $module and $instance
is invalid.
|
entailment
|
public function addTasks($tasks) {
if (!is_array($tasks)) {
throw new \InvalidArgumentException(
'$tasks must be an array. Actual type: ' . gettype($tasks));
}
if (empty($tasks)) {
return [];
}
if (count($tasks) > self::MAX_TASKS_PER_ADD) {
throw new \InvalidArgumentException(
'$tasks must contain at most ' . self::MAX_TASKS_PER_ADD .
' tasks. Actual size: ' . count($tasks));
}
$req = new TaskQueueBulkAddRequest();
$resp = new TaskQueueBulkAddResponse();
$names = [];
$current_time = microtime(true);
foreach ($tasks as $task) {
if (!($task instanceof PushTask)) {
throw new \InvalidArgumentException(
'All values in $tasks must be instances of PushTask. ' .
'Actual type: ' . gettype($task));
}
$names[] = $task->getName();
$add = $req->addAddRequest();
$add->setQueueName($this->name);
$add->setTaskName($task->getName());
$add->setEtaUsec(($current_time + $task->getDelaySeconds()) * 1e6);
$add->setMethod(self::$methods[$task->getMethod()]);
$add->setUrl($task->getUrl());
foreach ($task->getHeaders() as $header) {
$pair = explode(':', $header, 2);
$header_pb = $add->addHeader();
$header_pb->setKey(trim($pair[0]));
$header_pb->setValue(trim($pair[1]));
}
// TODO: Replace getQueryData() with getBody() and simplify the following
// block.
if ($task->getMethod() == 'POST' || $task->getMethod() == 'PUT') {
if ($task->getQueryData()) {
$add->setBody(http_build_query($task->getQueryData()));
}
}
if ($add->byteSizePartial() > PushTask::MAX_TASK_SIZE_BYTES) {
throw new TaskQueueException('Task greater than maximum size of ' .
PushTask::MAX_TASK_SIZE_BYTES . '. size: ' .
$add->byteSizePartial());
}
}
try {
ApiProxy::makeSyncCall('taskqueue', 'BulkAdd', $req, $resp);
} catch (ApplicationError $e) {
throw self::errorCodeToException($e->getApplicationError());
}
// Update $names with any generated task names. Also, check if there are any
// error responses.
$results = $resp->getTaskResultList();
$exception = null;
foreach ($results as $index => $task_result) {
if ($task_result->hasChosenTaskName()) {
$names[$index] = $task_result->getChosenTaskName();
}
if ($task_result->getResult() != ErrorCode::OK) {
$exception = self::errorCodeToException($task_result->getResult());
// Other exceptions take precedence over TaskAlreadyExistsException.
if (!($exception instanceof TaskAlreadyExistsException)) {
throw $exception;
}
}
}
if (isset($exception)) {
throw $exception;
}
return $names;
}
|
Add tasks to the queue.
@param PushTask[] $tasks The tasks to be added to the queue.
@return An array containing the name of each task added, with the same
ordering as $tasks.
@throws TaskAlreadyExistsException if a task of the same name already
exists in the queue.
If this exception is raised, the caller can be guaranteed that all tasks
were successfully added either by this call or a previous call. Another way
to express it is that, if any task failed to be added for a different
reason, a different exception will be thrown.
@throws TaskQueueException if there was a problem using the service.
|
entailment
|
public function rename() {
$token_header = $this->getOAuthTokenHeader(parent::WRITE_SCOPE);
if ($token_header === false) {
if (!$this->quiet) {
trigger_error("Unable to acquire OAuth token.", E_USER_WARNING);
}
return false;
}
// Stat the from object to get the etag and content-type
$http_response = $this->makeHttpRequest($this->url, "HEAD", $token_header);
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::OK) {
trigger_error(sprintf("Unable to rename: %s. Cloud Storage Error: %s",
sprintf("gs://%s%s",
$this->to_bucket,
$this->to_object),
HttpResponse::getStatusMessage($status_code)),
E_USER_WARNING);
return false;
}
$copy_headers = [
'x-goog-copy-source' =>
sprintf("/%s%s", $this->from_bucket, $this->from_object),
'x-goog-copy-source-if-match' =>
$this->getHeaderValue('ETag', $http_response['headers']),
];
// TODO: b/13132830: Remove once feature releases.
if (!ini_get('google_app_engine.enable_additional_cloud_storage_headers')) {
foreach (static::$METADATA_HEADERS as $key) {
// Leave Content-Type since it has been supported.
if ($key != 'Content-Type') {
unset($this->context_options[$key]);
}
}
}
// Check if any metadata context options have been set and only copy values
// below if one option needs to be changed.
$is_meta = isset($this->context_options['metadata']);
foreach (static::$METADATA_HEADERS as $key) {
// Stop after first meta option found.
$is_meta = $is_meta ?: isset($this->context_options[$key]);
if ($is_meta) {
break;
}
}
// Metadata-directive applies to headers outside of x-goog-meta-* like
// Content-Type. If any metadata changes are included in context then all
// other meta data must be filled in since the metadata-directive will be
// set to REPLACE and non-passed in values should remain the same.
if ($is_meta) {
$copy_headers['x-goog-metadata-directive'] = 'REPLACE';
// Copy all meta data fields to preserve values when using REPLACE
// directive. If a value exists in context_options it is given preference.
foreach (static::$METADATA_HEADERS as $key) {
if (isset($this->context_options[$key])) {
$copy_headers[$key] = $this->context_options[$key];
} else {
$value = $this->getHeaderValue($key, $http_response['headers']);
if ($value !== null) {
$copy_headers[$key] = $value;
}
}
}
// Special case since metadata option converts to multiple headers, this
// also handles copying over previous values if no new ones speicified.
$metadata = isset($this->context_options['metadata']) ?
$this->context_options['metadata'] :
static::extractMetaData($http_response['headers']);
foreach ($metadata as $key => $value) {
$copy_headers['x-goog-meta-' . $key] = $value;
}
} else {
$copy_headers['x-goog-metadata-directive'] = 'COPY';
}
if (array_key_exists("acl", $this->context_options)) {
$acl = $this->context_options["acl"];
if (in_array($acl, parent::$valid_acl_values)) {
$copy_headers["x-goog-acl"] = $acl;
} else {
trigger_error(sprintf("Invalid ACL value: %s", $acl), E_USER_WARNING);
return false;
}
}
$to_url = $this->createObjectUrl($this->to_bucket, $this->to_object);
$http_response = $this->makeHttpRequest($to_url, "PUT",
array_merge($token_header, $copy_headers));
if ($http_response === false) {
trigger_error("Unable to copy source to destination.", E_USER_WARNING);
return false;
}
$status_code = $http_response['status_code'];
if ($status_code != HttpResponse::OK) {
trigger_error(sprintf("Error copying to %s. Cloud Storage Error: %s",
sprintf("gs://%s%s",
$this->to_bucket,
$this->to_object),
HttpResponse::getStatusMessage($status_code)),
E_USER_WARNING);
return false;
}
// Unlink the original file.
$http_response = $this->makeHttpRequest($this->url,
"DELETE",
$token_header);
if ($http_response === false) {
trigger_error("Failed to delete the from cloud storage object.",
E_USER_WARNING);
return false;
}
$status_code = $http_response['status_code'];
if ($status_code !== HttpResponse::NO_CONTENT) {
trigger_error(sprintf("Unable to unlink: %s. Cloud Storage Error: %s",
sprintf("gs://%s%s",
$this->from_bucket,
$this->from_object),
HttpResponse::getStatusMessage($status_code)),
E_USER_WARNING);
return false;
}
clearstatcache(true, $this->createGcsFilename($this->from_bucket,
$this->from_object));
clearstatcache(true, $this->createGcsFilename($this->to_bucket,
$this->to_object));
return true;
}
|
Perform the actual rename of a GCS storage object.
Renaming an object has the following steps.
1. stat the 'from' object to get the ETag and content type.
2. Use x-goog-copy-source-if-match to copy the object.
3. Delete the original object.
|
entailment
|
public function stat() {
$prefix = $this->prefix;
if (StringUtil::endsWith($prefix, parent::DELIMITER)) {
$prefix = substr($prefix, 0, strlen($prefix) - 1);
}
if (ini_get("google_app_engine.enable_gcs_stat_cache") &&
$this->tryGetFromStatCache($stat_result)) {
return $stat_result;
}
if (isset($prefix)) {
$result = $this->headObject($prefix);
if ($result !== false) {
$mode = parent::S_IFREG;
$mtime = $result['mtime'];
$size = $result['size'];
} else {
// Object doesn't exisit, check and see if it's a directory.
do {
$results = $this->listBucket($prefix);
if (false === $results) {
return false;
}
// If there are no results then we're done
if (empty($results)) {
return false;
}
// If there is an entry that contains object_name_$folder$ or
// object_name/ then we have a 'directory'.
$object_name_folder = $prefix . parent::FOLDER_SUFFIX;
$object_name_delimiter = $prefix . parent::DELIMITER;
foreach ($results as $result) {
if ($result['name'] === $object_name_folder ||
$result['name'] === $object_name_delimiter) {
$mode = parent::S_IFDIR;
break;
}
}
} while (!isset($mode) && isset($this->next_marker));
}
} else {
// We are now just checking that the bucket exists, as there was no
// object prefix supplied
$results = $this->listBucket();
if ($results !== false) {
$mode = parent::S_IFDIR;
} else {
return false;
}
}
// If mode is not set, then there was no object that matched the criteria.
if (!isset($mode)) {
return false;
}
// If the app could stat the file, then it must be readable. As different
// PHP internal APIs check the access mode, we'll set them all to readable.
$mode |= parent::S_IRUSR | parent::S_IRGRP | parent::S_IROTH;
if ($this->isBucketWritable($this->bucket_name)) {
$mode |= parent::S_IWUSR | parent::S_IWGRP | parent::S_IWOTH;
}
$stat_args["mode"] = $mode;
if (isset($mtime)) {
$unix_time = strtotime($mtime);
if ($unix_time !== false) {
$stat_args["mtime"] = $unix_time;
}
}
if (isset($size)) {
$stat_args["size"] = intval($size);
}
$stat_result = $this->createStatArray($stat_args);
$this->addToStatCache($stat_result);
return $stat_result;
}
|
The stat function uses GET requests to the bucket to try and determine if
the object is a 'file' or a 'directory', by listing the contents of the
bucket and then matching the results against the supplied object name.
If a file ends with "/ then Google Cloud Console will show it as a 'folder'
in the UI tool, so we consider an object that ends in "/" as a directory
as well. For backward compatibility, we also treat files with the
"_$folder$" suffix as folders.
|
entailment
|
private function headObject($object_name) {
$headers = $this->getOAuthTokenHeader(parent::READ_SCOPE);
if ($headers === false) {
if (!$this->quiet) {
trigger_error("Unable to acquire OAuth token.", E_USER_WARNING);
}
return false;
}
$url = $this->createObjectUrl($this->bucket_name, $object_name);
$http_response = $this->makeHttpRequest($url, "HEAD", $headers);
if ($http_response === false) {
if (!$this->quiet) {
trigger_error('Unable to connect to the Cloud Storage Service.',
E_USER_WARNING);
}
return false;
}
$status_code = $http_response['status_code'];
if (HttpResponse::OK !== $status_code) {
if (!$this->quiet && HttpResponse::NOT_FOUND !== $status_code) {
trigger_error($this->getErrorMessage($http_response['status_code'],
$http_response['body']),
E_USER_WARNING);
}
return false;
}
$headers = $http_response['headers'];
return ['size' => $this->getHeaderValue('x-goog-stored-content-length',
$headers),
'mtime' => $this->getHeaderValue('Last-Modified', $headers)];
}
|
Perform a HEAD request on an object to get size & mtime info.
|
entailment
|
private function listBucket($object_prefix = null) {
$headers = $this->getOAuthTokenHeader(parent::READ_SCOPE);
if ($headers === false) {
if (!$this->quiet) {
trigger_error("Unable to acquire OAuth token.", E_USER_WARNING);
}
return false;
}
$query_arr = [
'delimiter' => parent::DELIMITER,
'max-keys' => self::MAX_KEYS,
];
if (isset($object_prefix)) {
$query_arr['prefix'] = $object_prefix;
}
if (isset($this->next_marker)) {
$query_arr['marker'] = $this->next_marker;
}
$url = $this->createObjectUrl($this->bucket_name);
$query_str = http_build_query($query_arr);
$http_response = $this->makeHttpRequest(sprintf("%s?%s", $url, $query_str),
"GET",
$headers);
if ($http_response === false) {
if (!$this->quiet) {
trigger_error('Unable to connect to the Cloud Storage Service.',
E_USER_WARNING);
}
return false;
}
if (HttpResponse::OK !== $http_response['status_code']) {
if (!$this->quiet) {
trigger_error($this->getErrorMessage($http_response['status_code'],
$http_response['body']),
E_USER_WARNING);
}
return false;
}
// Extract the files into the result array.
$xml = simplexml_load_string($http_response['body']);
if (isset($xml->NextMarker)) {
$this->next_marker = (string) $xml->NextMarker;
} else {
$this->next_marker = null;
}
$results = [];
foreach($xml->Contents as $content) {
$results [] = [
'name' => (string) $content->Key,
'size' => (string) $content->Size,
'mtime' => (string) $content->LastModified,
];
}
// Subdirectories will be returned in the CommonPrefixes section. Refer to
// https://developers.google.com/storage/docs/reference-methods#getbucket
foreach($xml->CommonPrefixes as $common_prefix) {
$results[] = [
'name' => (string) $common_prefix->Prefix,
];
}
return $results;
}
|
Perform a GET request on a bucket, with the optional $object_prefix. This
is similar to how CloudStorgeDirectoryClient works, except that it is
targeting a specific file rather than trying to enumerate of the files in
a given bucket with a common prefix.
|
entailment
|
private function isBucketWritable($bucket) {
$cache_key_name = sprintf(parent::WRITABLE_MEMCACHE_KEY_FORMAT, $bucket);
$memcache = new \Memcache();
$result = $memcache->get($cache_key_name);
if ($result) {
return $result['is_writable'];
}
// We determine if the bucket is writable by trying to start a resumable
// upload. GCS will cleanup the abandoned upload after 7 days, and it will
// not be charged to the bucket owner.
$token_header = $this->getOAuthTokenHeader(parent::WRITE_SCOPE);
if ($token_header === false) {
return false;
}
$headers = array_merge(parent::$upload_start_header, $token_header);
$url = parent::createObjectUrl($bucket, parent::WRITABLE_TEMP_FILENAME);
$http_response = $this->makeHttpRequest($url,
"POST",
$headers);
if ($http_response === false) {
return false;
}
$status_code = $http_response['status_code'];
$is_writable = $status_code == HttpResponse::CREATED;
$memcache->set($cache_key_name,
['is_writable' => $is_writable],
null,
$this->context_options['writable_cache_expiry_seconds']);
return $is_writable;
}
|
Test if a given bucket is writable. We will cache results in memcache as
this is an expensive operation. This might lead to incorrect results being
returned for this call for a short period while the result remains in the
cache.
|
entailment
|
public function makeSyncCall(
$package,
$call_name,
$request,
$response,
$deadline = null) {
if ($deadline === null) {
$deadline = 5;
}
$remote_request = new Request();
$remote_request->setServiceName($package);
$remote_request->setMethod($call_name);
$remote_request->setRequest($request->serializeToString());
$remote_request->setRequestId($this->requestId);
$serialized_remote_request = $remote_request->serializeToString();
$opts = array(
'http' => array(
'method' => 'POST',
'header' =>
"Content-type: application/octet-stream\r\n" .
'Content-Length: ' . strlen($serialized_remote_request) . "\r\n",
'content' => $serialized_remote_request
)
);
$context = stream_context_create($opts);
$serialized_remote_respone = file_get_contents(
'http://' . $this->apiHost . ':' . $this->apiPort, false, $context);
$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));
}
$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
|
entailment
|
public static function createUploadUrl($success_path, $options = array()) {
$req = new CreateUploadURLRequest();
$resp = new CreateUploadURLResponse();
if (!is_string($success_path)) {
throw new \InvalidArgumentException('$success_path must be a string');
}
$req->setSuccessPath($success_path);
$max_upload_size_ini = self::getUploadMaxFileSizeInBytes();
if (array_key_exists('max_bytes_per_blob', $options)) {
$val = $options['max_bytes_per_blob'];
if (!is_int($val)) {
throw new \InvalidArgumentException(
'max_bytes_per_blob must be an integer');
}
if ($val < 1) {
throw new \InvalidArgumentException(
'max_bytes_per_blob must be positive.');
}
$req->setMaxUploadSizePerBlobBytes($val);
} else if ($max_upload_size_ini > 0) {
$req->setMaxUploadSizePerBlobBytes($max_upload_size_ini);
}
if (array_key_exists('max_bytes_total', $options)) {
$val = $options['max_bytes_total'];
if (!is_int($val)) {
throw new \InvalidArgumentException(
'max_bytes_total must be an integer');
}
if ($val < 1) {
throw new \InvalidArgumentException(
'max_bytes_total must be positive.');
}
$req->setMaxUploadSizeBytes($val);
}
if (array_key_exists('url_expiry_time_seconds', $options)) {
$val = $options['url_expiry_time_seconds'];
if (!is_int($val)) {
throw new \InvalidArgumentException(
'url_expiry_time_seconds must be an integer');
}
if ($val < 1) {
throw new \InvalidArgumentException(
'url_expiry_time_seconds must be positive.');
}
if ($val > self::MAX_URL_EXPIRY_TIME_SECONDS) {
throw new \InvalidArgumentException(
'url_expiry_time_seconds must not exceed ' .
self::MAX_URL_EXPIRY_TIME_SECONDS);
}
$req->setUrlExpiryTimeSeconds($val);
}
if (array_key_exists('gs_bucket_name', $options)) {
$val = $options['gs_bucket_name'];
if (!is_string($val)) {
throw new \InvalidArgumentException('gs_bucket_name must be a string');
}
$req->setGsBucketName($val);
} else {
$bucket = self::getDefaultGoogleStorageBucketName();
if (!$bucket) {
throw new \InvalidArgumentException(
'Application does not have a default Cloud Storage Bucket, ' .
'gs_bucket_name must be specified');
}
$req->setGsBucketName($bucket);
}
$extra_options = array_diff(array_keys($options),
self::$create_upload_url_options);
if (!empty($extra_options)) {
throw new \InvalidArgumentException('Invalid options supplied: ' .
htmlspecialchars(implode(',', $extra_options)));
}
try {
ApiProxy::makeSyncCall('blobstore', 'CreateUploadURL', $req, $resp);
} catch (ApplicationError $e) {
throw self::applicationErrorToException($e);
}
return $resp->getUrl();
}
|
Create an absolute URL that can be used by a user to asynchronously upload
a large blob. Upon completion of the upload, a callback is made to the
specified URL.
@param string $success_path A relative URL which will be invoked after the
user successfully uploads a blob.
@param mixed[] $options A key value pair array of upload options. Valid
options are:<ul>
<li>'max_bytes_per_blob': integer The value of the largest size that any
one uploaded blob may be. Default value: unlimited.
<li>'max_bytes_total': integer The value that is the total size that sum of
all uploaded blobs may be. Default value: unlimited.
<li>'gs_bucket_name': string The name of a Google Cloud Storage
bucket that the blobs should be uploaded to. Not specifying a value
will result in the blob being uploaded to the application's default
bucket.
<li>'url_expiry_time_seconds': integer The number of seconds that the
generated URL can be used for to upload files to Google Cloud Storage.
Once this timeout expires, the URL is no longer valid and any attempts
to upload using the URL will fail. Must be a positive integer, maximum
value is one day (86400 seconds). Default Value: 600 seconds.
</ul>
@return string The upload URL.
@throws \InvalidArgumentException If $success_path is not valid, or one of
the options is not valid.
@throws CloudStorageException Thrown when there is a failure using the
blobstore service.
|
entailment
|
public static function getImageServingUrl($gs_filename, $options = []) {
$blob_key = self::createGsKey($gs_filename);
if (!is_array($options)) {
throw new \InvalidArgumentException('$options must be an array. ' .
'Actual type: ' . gettype($options));
}
$extra_options = array_diff(array_keys($options), array_keys(
self::$get_image_serving_url_default_options));
if (!empty($extra_options)) {
throw new \InvalidArgumentException('Invalid options supplied: ' .
htmlspecialchars(implode(',', $extra_options)));
}
$options = array_merge(self::$get_image_serving_url_default_options,
$options);
# Validate options.
if (!is_bool($options['crop'])) {
throw new \InvalidArgumentException(
'$options[\'crop\'] must be a boolean. ' .
'Actual type: ' . gettype($options['crop']));
}
if ($options['crop'] && is_null($options['size'])) {
throw new \InvalidArgumentException(
'$options[\'size\'] must be set because $options[\'crop\'] is true.');
}
if (!is_null($options['size'])) {
$size = $options['size'];
if (!is_int($size)) {
throw new \InvalidArgumentException(
'$options[\'size\'] must be an integer. ' .
'Actual type: ' . gettype($size));
}
if ($size < 0 || $size > self::MAX_IMAGE_SERVING_SIZE) {
throw new \InvalidArgumentException(
'$options[\'size\'] must be >= 0 and <= ' .
self::MAX_IMAGE_SERVING_SIZE . '. Actual value: ' . $size);
}
}
if (!is_bool($options['secure_url'])) {
throw new \InvalidArgumentException(
'$options[\'secure_url\'] must be a boolean. ' .
'Actual type: ' . gettype($options['secure_url']));
}
$req = new ImagesGetUrlBaseRequest();
$resp = new ImagesGetUrlBaseResponse();
$req->setBlobKey($blob_key);
$req->setCreateSecureUrl($options['secure_url']);
try {
ApiProxy::makeSyncCall('images',
'GetUrlBase',
$req,
$resp);
} catch (ApplicationError $e) {
throw self::imagesApplicationErrorToException($e);
}
$url = $resp->getUrl();
if (!is_null($options['size'])) {
$url .= ('=s' . $options['size']);
if ($options['crop']) {
$url .= '-c';
}
}
return $url;
}
|
Returns a URL that serves an image.
@param string $gs_filename The name of the Google Cloud Storage object to
serve. In the format gs://bucket_name/object_name
@param mixed[] $options Array of additional options for serving the object.
Valid options are:
<ul>
<li>'crop': boolean Whether the image should be cropped. If set to true, a
size must also be supplied. Default value: false.
<li>'secure_url': boolean Whether to request an https URL. Default value:
false.
<li>'size': integer The size of the longest dimension of the resulting
image. Size must be in the range 0 to 1600, with 0 specifying the size of
the original image. The aspect ratio is preserved unless 'crop' is
specified.
</ul>
@return string The image serving URL.
@throws \InvalidArgumentException if any of the arguments are not valid.
@throws CloudStorageException If there was a problem contacting the
service.
|
entailment
|
public static function deleteImageServingUrl($gs_filename) {
$blob_key = self::createGsKey($gs_filename);
$req = new ImagesDeleteUrlBaseRequest();
$resp = new ImagesDeleteUrlBaseResponse();
$req->setBlobKey($blob_key);
try {
ApiProxy::makeSyncCall('images',
'DeleteUrlBase',
$req,
$resp);
} catch (ApplicationError $e) {
throw self::imagesApplicationErrorToException($e);
}
}
|
Deletes an image serving URL that was created using getImageServingUrl.
@param string $gs_filename The name of the Google Cloud Storage object
that has an existing URL to delete. In the format
gs://bucket_name/object_name
@throws \InvalidArgumentException if any of the arguments are not valid.
@throws CloudStorageException If there was a problem contacting the
service.
|
entailment
|
public static function getPublicUrl($gs_filename, $use_https) {
if (!is_bool($use_https)) {
throw new \InvalidArgumentException(
'Parameter $use_https must be boolean but was ' .
typeOrClass($use_https));
}
if (!self::parseFilename($gs_filename, $bucket, $object)) {
throw new \InvalidArgumentException(
sprintf('Invalid Google Cloud Storage filename: %s',
htmlspecialchars($gs_filename)));
}
if (self::isDevelServer()) {
$scheme = 'http';
$host = getenv('HTTP_HOST');
$path = sprintf('%s/%s%s', self::LOCAL_ENDPOINT, $bucket, $object);
} else {
// Use path format for HTTPS URL when the bucket name contains "." to
// avoid SSL certificate validation issue.
if ($use_https && strpos($bucket, '.') !== false) {
$host = self::PRODUCTION_HOST_PATH_FORMAT;
$path = sprintf('/%s%s', $bucket, $object);
} else {
$host = sprintf(self::PRODUCTION_HOST_SUBDOMAIN_FORMAT, $bucket);
$path = strlen($object) > 0 ? $object : '/';
}
$scheme = $use_https ? 'https' : 'http';
}
return sprintf('%s://%s%s',
$scheme,
$host,
strtr($path, self::$url_path_translation_map));
}
|
Get the public URL for a Google Cloud Storage filename.
@param string $gs_filename The Google Cloud Storage filename, in the
format gs://bucket_name/object_name.
@param boolean $use_https If True then return a HTTPS URL. Note that the
development server ignores this argument and returns only HTTP URLs.
@return string The public URL.
@throws \InvalidArgumentException if the filename is not in the correct
format or $use_https is not a boolean.
|
entailment
|
public static function getFilename($bucket, $object) {
if (self::validateBucketName($bucket) === false) {
throw new \InvalidArgumentException(
sprintf('Invalid cloud storage bucket name \'%s\'',
htmlspecialchars($bucket)));
}
if (self::validateObjectName($object) === false) {
throw new \InvalidArgumentException(
sprintf('Invalid cloud storage object name \'%s\'',
htmlspecialchars($object)));
}
return sprintf(self::GS_FILENAME_FORMAT, $bucket, $object);
}
|
Get the filename of a Google Cloud Storage object.
@param string $bucket The Google Cloud Storage bucket name.
@param string $object The Google Cloud Stroage object name.
@return string The filename in the format gs://bucket_name/object_name.
@throws \InvalidArgumentException if bucket or object name is invalid.
|
entailment
|
public static function parseFilename($filename, &$bucket, &$object) {
$bucket = null;
$object = null;
// $filename may contain nasty characters like # and ? that can throw off
// parse_url(). It is best to do a manual parse here.
$gs_prefix_len = strlen(self::GS_PREFIX);
if (!StringUtil::startsWith($filename, self::GS_PREFIX)) {
return false;
}
$first_slash_pos = strpos($filename, '/', $gs_prefix_len);
if ($first_slash_pos === false) {
$bucket = substr($filename, $gs_prefix_len);
} else {
$bucket = substr($filename, $gs_prefix_len,
$first_slash_pos - $gs_prefix_len);
// gs://bucket_name/ is treated the same as gs://bucket_name where
// $object should be set to null.
if ($first_slash_pos != strlen($filename) - 1) {
$object = substr($filename, $first_slash_pos);
}
}
if (strlen($bucket) == 0) {
return false;
}
// Substitute default bucket name.
if (ini_get('google_app_engine.gcs_default_keyword')) {
if ($bucket === self::GS_DEFAULT_BUCKET_KEYWORD) {
$bucket = self::getDefaultGoogleStorageBucketName();
if (!$bucket) {
throw new \InvalidArgumentException(
'Application does not have a default Cloud Storage Bucket, ' .
'must specify a bucket name');
}
}
}
// Validate bucket & object names.
if (self::validateBucketName($bucket) === false) {
trigger_error(sprintf('Invalid cloud storage bucket name \'%s\'',
$bucket), E_USER_ERROR);
return false;
}
if (isset($object) && self::validateObjectName($object) === false) {
trigger_error(sprintf('Invalid cloud storage object name \'%s\'',
$object), E_USER_ERROR);
return false;
}
return true;
}
|
Parse and extract the bucket and object names from the supplied filename.
@param string $filename The filename in the format gs://bucket_name or
gs://bucket_name/object_name.
@param string &$bucket The extracted bucket.
@param string &$object The extracted object. Can be null if the filename
contains only bucket name.
@return bool true if the filename is successfully parsed, false otherwise.
|
entailment
|
private static function validateBucketName($bucket_name) {
$valid_bucket_regex = '/^[a-z0-9]+[a-z0-9\.\-_]+[a-z0-9]+$/';
if (preg_match($valid_bucket_regex, $bucket_name) === 0) {
return false;
}
if (strpos($bucket_name, 'goog') === 0) {
return false;
}
if (filter_var($bucket_name, FILTER_VALIDATE_IP) !== false) {
return false;
}
$parts = explode('.', $bucket_name);
if (count($parts) > 1) {
if (strlen($bucket_name) > 222) {
return false;
}
}
foreach ($parts as $part) {
if (strlen($part) > 63) {
return false;
}
}
return true;
}
|
Validate the bucket name according to the rules stated at
https://developers.google.com/storage/docs/bucketnaming.
@param string $bucket_name The Google Cloud Storage bucket name.
@access private
|
entailment
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.