���� JFIF    �� �        "" $(4,$&1'-=-157:::#+?D?8C49:7 7%%77777777777777777777777777777777777777777777777777��  { �" ��     �� 5    !1AQa"q�2��BR��#b�������  ��  ��   ? ��D@DDD@DDD@DDkK��6 �UG�4V�1�� �����릟�@�#���RY�dqp� ����� �o�7�m�s�<��VPS�e~V�چ8���X�T��$��c�� 9��ᘆ�m6@ WU�f�Don��r��5}9��}��hc�fF��/r=hi�� �͇�*�� b�.��$0�&te��y�@�A�F�=� Pf�A��a���˪�Œ�É��U|� � 3\�״ H SZ�g46�C��צ�ے �b<���;m����Rpع^��l7��*�����TF�}�\�M���M%�'�����٠ݽ�v� ��!-�����?�N!La��A+[`#���M����'�~oR�?��v^)��=��h����A��X�.���˃����^Ə��ܯsO"B�c>; �e�4��5�k��/CB��.  �J?��;�҈�������������������~�<�VZ�ꭼ2/)Í”jC���ע�V�G�!���!�F������\�� Kj�R�oc�h���:Þ I��1"2�q×°8��Р@ז���_C0�ր��A��lQ��@纼�!7��F�� �]�sZ B�62r�v�z~�K�7�c��5�.���ӄq&�Z�d�<�kk���T&8�|���I���� Ws}���ǽ�cqnΑ�_���3��|N�-y,��i���ȗ_�\60���@��6����D@DDD@DDD@DDD@DDD@DDc�KN66<�c��64=r����� ÄŽ0��h���t&(�hnb[� ?��^��\��â|�,�/h�\��R��5�? �0�!צ܉-����G����٬��Q�zA���1�����V��� �:R���`�$��ik��H����D4�����#dk����� h�}����7���w%�������*o8wG�LycuT�.���ܯ7��I��u^���)��/c�,s�Nq�ۺ�;�ך�YH2���.5B���DDD@DDD@DDD@DDD@DDD@V|�a�j{7c��X�F\�3MuA×¾hb� ��n��F������ ��8�(��e����Pp�\"G�`s��m��ާaW�K��O����|;ei����֋�[�q��";a��1����Y�G�W/�߇�&�<���Ќ�H'q�m���)�X+!���=�m�ۚ丷~6a^X�)���,�>#&6G���Y��{����"" """ """ """ """ ""��at\/�a�8 �yp%�lhl�n����)���i�t��B�������������?��modskinlienminh.com - WSOX ENC PK!j@U**true/punycode/src/Punycode.phpnu[ 0, 'b' => 1, 'c' => 2, 'd' => 3, 'e' => 4, 'f' => 5, 'g' => 6, 'h' => 7, 'i' => 8, 'j' => 9, 'k' => 10, 'l' => 11, 'm' => 12, 'n' => 13, 'o' => 14, 'p' => 15, 'q' => 16, 'r' => 17, 's' => 18, 't' => 19, 'u' => 20, 'v' => 21, 'w' => 22, 'x' => 23, 'y' => 24, 'z' => 25, '0' => 26, '1' => 27, '2' => 28, '3' => 29, '4' => 30, '5' => 31, '6' => 32, '7' => 33, '8' => 34, '9' => 35); /** * Character encoding * * @param string */ protected $encoding; /** * Constructor * * @param string $encoding Character encoding */ public function __construct($encoding = 'UTF-8') { $this->encoding = $encoding; } /** * Encode a domain to its Punycode version * * @param string $input Domain name in Unicode to be encoded * @return string Punycode representation in ASCII */ public function encode($input) { $input = \mb_strtolower($input, $this->encoding); $parts = \explode('.', $input); foreach ($parts as &$part) { $length = \strlen($part); if ($length < 1) { throw new \Google\Site_Kit_Dependencies\TrueBV\Exception\LabelOutOfBoundsException(\sprintf('The length of any one label is limited to between 1 and 63 octets, but %s given.', $length)); } $part = $this->encodePart($part); } $output = \implode('.', $parts); $length = \strlen($output); if ($length > 255) { throw new \Google\Site_Kit_Dependencies\TrueBV\Exception\DomainOutOfBoundsException(\sprintf('A full domain name is limited to 255 octets (including the separators), %s given.', $length)); } return $output; } /** * Encode a part of a domain name, such as tld, to its Punycode version * * @param string $input Part of a domain name * @return string Punycode representation of a domain part */ protected function encodePart($input) { $codePoints = $this->listCodePoints($input); $n = static::INITIAL_N; $bias = static::INITIAL_BIAS; $delta = 0; $h = $b = \count($codePoints['basic']); $output = ''; foreach ($codePoints['basic'] as $code) { $output .= $this->codePointToChar($code); } if ($input === $output) { return $output; } if ($b > 0) { $output .= static::DELIMITER; } $codePoints['nonBasic'] = \array_unique($codePoints['nonBasic']); \sort($codePoints['nonBasic']); $i = 0; $length = \mb_strlen($input, $this->encoding); while ($h < $length) { $m = $codePoints['nonBasic'][$i++]; $delta = $delta + ($m - $n) * ($h + 1); $n = $m; foreach ($codePoints['all'] as $c) { if ($c < $n || $c < static::INITIAL_N) { $delta++; } if ($c === $n) { $q = $delta; for ($k = static::BASE;; $k += static::BASE) { $t = $this->calculateThreshold($k, $bias); if ($q < $t) { break; } $code = $t + ($q - $t) % (static::BASE - $t); $output .= static::$encodeTable[$code]; $q = ($q - $t) / (static::BASE - $t); } $output .= static::$encodeTable[$q]; $bias = $this->adapt($delta, $h + 1, $h === $b); $delta = 0; $h++; } } $delta++; $n++; } $out = static::PREFIX . $output; $length = \strlen($out); if ($length > 63 || $length < 1) { throw new \Google\Site_Kit_Dependencies\TrueBV\Exception\LabelOutOfBoundsException(\sprintf('The length of any one label is limited to between 1 and 63 octets, but %s given.', $length)); } return $out; } /** * Decode a Punycode domain name to its Unicode counterpart * * @param string $input Domain name in Punycode * @return string Unicode domain name */ public function decode($input) { $input = \strtolower($input); $parts = \explode('.', $input); foreach ($parts as &$part) { $length = \strlen($part); if ($length > 63 || $length < 1) { throw new \Google\Site_Kit_Dependencies\TrueBV\Exception\LabelOutOfBoundsException(\sprintf('The length of any one label is limited to between 1 and 63 octets, but %s given.', $length)); } if (\strpos($part, static::PREFIX) !== 0) { continue; } $part = \substr($part, \strlen(static::PREFIX)); $part = $this->decodePart($part); } $output = \implode('.', $parts); $length = \strlen($output); if ($length > 255) { throw new \Google\Site_Kit_Dependencies\TrueBV\Exception\DomainOutOfBoundsException(\sprintf('A full domain name is limited to 255 octets (including the separators), %s given.', $length)); } return $output; } /** * Decode a part of domain name, such as tld * * @param string $input Part of a domain name * @return string Unicode domain part */ protected function decodePart($input) { $n = static::INITIAL_N; $i = 0; $bias = static::INITIAL_BIAS; $output = ''; $pos = \strrpos($input, static::DELIMITER); if ($pos !== \false) { $output = \substr($input, 0, $pos++); } else { $pos = 0; } $outputLength = \strlen($output); $inputLength = \strlen($input); while ($pos < $inputLength) { $oldi = $i; $w = 1; for ($k = static::BASE;; $k += static::BASE) { $digit = static::$decodeTable[$input[$pos++]]; $i = $i + $digit * $w; $t = $this->calculateThreshold($k, $bias); if ($digit < $t) { break; } $w = $w * (static::BASE - $t); } $bias = $this->adapt($i - $oldi, ++$outputLength, $oldi === 0); $n = $n + (int) ($i / $outputLength); $i = $i % $outputLength; $output = \mb_substr($output, 0, $i, $this->encoding) . $this->codePointToChar($n) . \mb_substr($output, $i, $outputLength - 1, $this->encoding); $i++; } return $output; } /** * Calculate the bias threshold to fall between TMIN and TMAX * * @param integer $k * @param integer $bias * @return integer */ protected function calculateThreshold($k, $bias) { if ($k <= $bias + static::TMIN) { return static::TMIN; } elseif ($k >= $bias + static::TMAX) { return static::TMAX; } return $k - $bias; } /** * Bias adaptation * * @param integer $delta * @param integer $numPoints * @param boolean $firstTime * @return integer */ protected function adapt($delta, $numPoints, $firstTime) { $delta = (int) ($firstTime ? $delta / static::DAMP : $delta / 2); $delta += (int) ($delta / $numPoints); $k = 0; while ($delta > (static::BASE - static::TMIN) * static::TMAX / 2) { $delta = (int) ($delta / (static::BASE - static::TMIN)); $k = $k + static::BASE; } $k = $k + (int) ((static::BASE - static::TMIN + 1) * $delta / ($delta + static::SKEW)); return $k; } /** * List code points for a given input * * @param string $input * @return array Multi-dimension array with basic, non-basic and aggregated code points */ protected function listCodePoints($input) { $codePoints = array('all' => array(), 'basic' => array(), 'nonBasic' => array()); $length = \mb_strlen($input, $this->encoding); for ($i = 0; $i < $length; $i++) { $char = \mb_substr($input, $i, 1, $this->encoding); $code = $this->charToCodePoint($char); if ($code < 128) { $codePoints['all'][] = $codePoints['basic'][] = $code; } else { $codePoints['all'][] = $codePoints['nonBasic'][] = $code; } } return $codePoints; } /** * Convert a single or multi-byte character to its code point * * @param string $char * @return integer */ protected function charToCodePoint($char) { $code = \ord($char[0]); if ($code < 128) { return $code; } elseif ($code < 224) { return ($code - 192) * 64 + (\ord($char[1]) - 128); } elseif ($code < 240) { return ($code - 224) * 4096 + (\ord($char[1]) - 128) * 64 + (\ord($char[2]) - 128); } else { return ($code - 240) * 262144 + (\ord($char[1]) - 128) * 4096 + (\ord($char[2]) - 128) * 64 + (\ord($char[3]) - 128); } } /** * Convert a code point to its single or multi-byte character * * @param integer $code * @return string */ protected function codePointToChar($code) { if ($code <= 0x7f) { return \chr($code); } elseif ($code <= 0x7ff) { return \chr(($code >> 6) + 192) . \chr(($code & 63) + 128); } elseif ($code <= 0xffff) { return \chr(($code >> 12) + 224) . \chr(($code >> 6 & 63) + 128) . \chr(($code & 63) + 128); } else { return \chr(($code >> 18) + 240) . \chr(($code >> 12 & 63) + 128) . \chr(($code >> 6 & 63) + 128) . \chr(($code & 63) + 128); } } } PK!~$$9true/punycode/src/Exception/LabelOutOfBoundsException.phpnu[ */ class LabelOutOfBoundsException extends \Google\Site_Kit_Dependencies\TrueBV\Exception\OutOfBoundsException { } PK!#׿&&:true/punycode/src/Exception/DomainOutOfBoundsException.phpnu[ */ class DomainOutOfBoundsException extends \Google\Site_Kit_Dependencies\TrueBV\Exception\OutOfBoundsException { } PK!C!4true/punycode/src/Exception/OutOfBoundsException.phpnu[ */ class OutOfBoundsException extends \RuntimeException { } PK!  "guzzlehttp/promises/src/Create.phpnu[then([$promise, 'resolve'], [$promise, 'reject']); return $promise; } return new \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\FulfilledPromise($value); } /** * Creates a rejected promise for a reason if the reason is not a promise. * If the provided reason is a promise, then it is returned as-is. * * @param mixed $reason Promise or reason. * * @return PromiseInterface */ public static function rejectionFor($reason) { if ($reason instanceof \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\PromiseInterface) { return $reason; } return new \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\RejectedPromise($reason); } /** * Create an exception for a rejected promise value. * * @param mixed $reason * * @return \Exception|\Throwable */ public static function exceptionFor($reason) { if ($reason instanceof \Exception || $reason instanceof \Throwable) { return $reason; } return new \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\RejectionException($reason); } /** * Returns an iterator for the given value. * * @param mixed $value * * @return \Iterator */ public static function iterFor($value) { if ($value instanceof \Iterator) { return $value; } if (\is_array($value)) { return new \ArrayIterator($value); } return new \ArrayIterator([$value]); } } PK!Tv1guzzlehttp/promises/src/CancellationException.phpnu[ $onFulfilled, 'rejected' => $onRejected]))->promise(); } /** * Like of, but only allows a certain number of outstanding promises at any * given time. * * $concurrency may be an integer or a function that accepts the number of * pending promises and returns a numeric concurrency limit value to allow * for dynamic a concurrency size. * * @param mixed $iterable * @param int|callable $concurrency * @param callable $onFulfilled * @param callable $onRejected * * @return PromiseInterface */ public static function ofLimit($iterable, $concurrency, callable $onFulfilled = null, callable $onRejected = null) { return (new \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\EachPromise($iterable, ['fulfilled' => $onFulfilled, 'rejected' => $onRejected, 'concurrency' => $concurrency]))->promise(); } /** * Like limit, but ensures that no promise in the given $iterable argument * is rejected. If any promise is rejected, then the aggregate promise is * rejected with the encountered rejection. * * @param mixed $iterable * @param int|callable $concurrency * @param callable $onFulfilled * * @return PromiseInterface */ public static function ofLimitAll($iterable, $concurrency, callable $onFulfilled = null) { return each_limit($iterable, $concurrency, $onFulfilled, function ($reason, $idx, \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\PromiseInterface $aggregate) { $aggregate->reject($reason); }); } } PK!Zsª.guzzlehttp/promises/src/AggregateException.phpnu[run(); */ class TaskQueue implements \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\TaskQueueInterface { private $enableShutdown = \true; private $queue = []; public function __construct($withShutdown = \true) { if ($withShutdown) { \register_shutdown_function(function () { if ($this->enableShutdown) { // Only run the tasks if an E_ERROR didn't occur. $err = \error_get_last(); if (!$err || $err['type'] ^ \E_ERROR) { $this->run(); } } }); } } public function isEmpty() { return !$this->queue; } public function add(callable $task) { $this->queue[] = $task; } public function run() { while ($task = \array_shift($this->queue)) { /** @var callable $task */ $task(); } } /** * The task queue will be run and exhausted by default when the process * exits IFF the exit is not the result of a PHP E_ERROR error. * * You can disable running the automatic shutdown of the queue by calling * this function. If you disable the task queue shutdown process, then you * MUST either run the task queue (as a result of running your event loop * or manually using the run() method) or wait on each outstanding promise. * * Note: This shutdown will occur before any destructors are triggered. */ public function disableShutdown() { $this->enableShutdown = \false; } } PK!guzzlehttp/promises/src/Is.phpnu[getState() === \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\PromiseInterface::PENDING; } /** * Returns true if a promise is fulfilled or rejected. * * @return bool */ public static function settled(\Google\Site_Kit_Dependencies\GuzzleHttp\Promise\PromiseInterface $promise) { return $promise->getState() !== \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\PromiseInterface::PENDING; } /** * Returns true if a promise is fulfilled. * * @return bool */ public static function fulfilled(\Google\Site_Kit_Dependencies\GuzzleHttp\Promise\PromiseInterface $promise) { return $promise->getState() === \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\PromiseInterface::FULFILLED; } /** * Returns true if a promise is rejected. * * @return bool */ public static function rejected(\Google\Site_Kit_Dependencies\GuzzleHttp\Promise\PromiseInterface $promise) { return $promise->getState() === \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\PromiseInterface::REJECTED; } } PK!y6,6,%guzzlehttp/promises/src/functions.phpnu[ * while ($eventLoop->isRunning()) { * GuzzleHttp\Promise\queue()->run(); * } * * * @param TaskQueueInterface $assign Optionally specify a new queue instance. * * @return TaskQueueInterface * * @deprecated queue will be removed in guzzlehttp/promises:2.0. Use Utils::queue instead. */ function queue(\Google\Site_Kit_Dependencies\GuzzleHttp\Promise\TaskQueueInterface $assign = null) { return \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Utils::queue($assign); } /** * Adds a function to run in the task queue when it is next `run()` and returns * a promise that is fulfilled or rejected with the result. * * @param callable $task Task function to run. * * @return PromiseInterface * * @deprecated task will be removed in guzzlehttp/promises:2.0. Use Utils::task instead. */ function task(callable $task) { return \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Utils::task($task); } /** * Creates a promise for a value if the value is not a promise. * * @param mixed $value Promise or value. * * @return PromiseInterface * * @deprecated promise_for will be removed in guzzlehttp/promises:2.0. Use Create::promiseFor instead. */ function promise_for($value) { return \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Create::promiseFor($value); } /** * Creates a rejected promise for a reason if the reason is not a promise. If * the provided reason is a promise, then it is returned as-is. * * @param mixed $reason Promise or reason. * * @return PromiseInterface * * @deprecated rejection_for will be removed in guzzlehttp/promises:2.0. Use Create::rejectionFor instead. */ function rejection_for($reason) { return \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Create::rejectionFor($reason); } /** * Create an exception for a rejected promise value. * * @param mixed $reason * * @return \Exception|\Throwable * * @deprecated exception_for will be removed in guzzlehttp/promises:2.0. Use Create::exceptionFor instead. */ function exception_for($reason) { return \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Create::exceptionFor($reason); } /** * Returns an iterator for the given value. * * @param mixed $value * * @return \Iterator * * @deprecated iter_for will be removed in guzzlehttp/promises:2.0. Use Create::iterFor instead. */ function iter_for($value) { return \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Create::iterFor($value); } /** * Synchronously waits on a promise to resolve and returns an inspection state * array. * * Returns a state associative array containing a "state" key mapping to a * valid promise state. If the state of the promise is "fulfilled", the array * will contain a "value" key mapping to the fulfilled value of the promise. If * the promise is rejected, the array will contain a "reason" key mapping to * the rejection reason of the promise. * * @param PromiseInterface $promise Promise or value. * * @return array * * @deprecated inspect will be removed in guzzlehttp/promises:2.0. Use Utils::inspect instead. */ function inspect(\Google\Site_Kit_Dependencies\GuzzleHttp\Promise\PromiseInterface $promise) { return \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Utils::inspect($promise); } /** * Waits on all of the provided promises, but does not unwrap rejected promises * as thrown exception. * * Returns an array of inspection state arrays. * * @see inspect for the inspection state array format. * * @param PromiseInterface[] $promises Traversable of promises to wait upon. * * @return array * * @deprecated inspect will be removed in guzzlehttp/promises:2.0. Use Utils::inspectAll instead. */ function inspect_all($promises) { return \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Utils::inspectAll($promises); } /** * Waits on all of the provided promises and returns the fulfilled values. * * Returns an array that contains the value of each promise (in the same order * the promises were provided). An exception is thrown if any of the promises * are rejected. * * @param iterable $promises Iterable of PromiseInterface objects to wait on. * * @return array * * @throws \Exception on error * @throws \Throwable on error in PHP >=7 * * @deprecated unwrap will be removed in guzzlehttp/promises:2.0. Use Utils::unwrap instead. */ function unwrap($promises) { return \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Utils::unwrap($promises); } /** * Given an array of promises, return a promise that is fulfilled when all the * items in the array are fulfilled. * * The promise's fulfillment value is an array with fulfillment values at * respective positions to the original array. If any promise in the array * rejects, the returned promise is rejected with the rejection reason. * * @param mixed $promises Promises or values. * @param bool $recursive If true, resolves new promises that might have been added to the stack during its own resolution. * * @return PromiseInterface * * @deprecated all will be removed in guzzlehttp/promises:2.0. Use Utils::all instead. */ function all($promises, $recursive = \false) { return \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Utils::all($promises, $recursive); } /** * Initiate a competitive race between multiple promises or values (values will * become immediately fulfilled promises). * * When count amount of promises have been fulfilled, the returned promise is * fulfilled with an array that contains the fulfillment values of the winners * in order of resolution. * * This promise is rejected with a {@see AggregateException} if the number of * fulfilled promises is less than the desired $count. * * @param int $count Total number of promises. * @param mixed $promises Promises or values. * * @return PromiseInterface * * @deprecated some will be removed in guzzlehttp/promises:2.0. Use Utils::some instead. */ function some($count, $promises) { return \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Utils::some($count, $promises); } /** * Like some(), with 1 as count. However, if the promise fulfills, the * fulfillment value is not an array of 1 but the value directly. * * @param mixed $promises Promises or values. * * @return PromiseInterface * * @deprecated any will be removed in guzzlehttp/promises:2.0. Use Utils::any instead. */ function any($promises) { return \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Utils::any($promises); } /** * Returns a promise that is fulfilled when all of the provided promises have * been fulfilled or rejected. * * The returned promise is fulfilled with an array of inspection state arrays. * * @see inspect for the inspection state array format. * * @param mixed $promises Promises or values. * * @return PromiseInterface * * @deprecated settle will be removed in guzzlehttp/promises:2.0. Use Utils::settle instead. */ function settle($promises) { return \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Utils::settle($promises); } /** * Given an iterator that yields promises or values, returns a promise that is * fulfilled with a null value when the iterator has been consumed or the * aggregate promise has been fulfilled or rejected. * * $onFulfilled is a function that accepts the fulfilled value, iterator index, * and the aggregate promise. The callback can invoke any necessary side * effects and choose to resolve or reject the aggregate if needed. * * $onRejected is a function that accepts the rejection reason, iterator index, * and the aggregate promise. The callback can invoke any necessary side * effects and choose to resolve or reject the aggregate if needed. * * @param mixed $iterable Iterator or array to iterate over. * @param callable $onFulfilled * @param callable $onRejected * * @return PromiseInterface * * @deprecated each will be removed in guzzlehttp/promises:2.0. Use Each::of instead. */ function each($iterable, callable $onFulfilled = null, callable $onRejected = null) { return \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Each::of($iterable, $onFulfilled, $onRejected); } /** * Like each, but only allows a certain number of outstanding promises at any * given time. * * $concurrency may be an integer or a function that accepts the number of * pending promises and returns a numeric concurrency limit value to allow for * dynamic a concurrency size. * * @param mixed $iterable * @param int|callable $concurrency * @param callable $onFulfilled * @param callable $onRejected * * @return PromiseInterface * * @deprecated each_limit will be removed in guzzlehttp/promises:2.0. Use Each::ofLimit instead. */ function each_limit($iterable, $concurrency, callable $onFulfilled = null, callable $onRejected = null) { return \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Each::ofLimit($iterable, $concurrency, $onFulfilled, $onRejected); } /** * Like each_limit, but ensures that no promise in the given $iterable argument * is rejected. If any promise is rejected, then the aggregate promise is * rejected with the encountered rejection. * * @param mixed $iterable * @param int|callable $concurrency * @param callable $onFulfilled * * @return PromiseInterface * * @deprecated each_limit_all will be removed in guzzlehttp/promises:2.0. Use Each::ofLimitAll instead. */ function each_limit_all($iterable, $concurrency, callable $onFulfilled = null) { return \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Each::ofLimitAll($iterable, $concurrency, $onFulfilled); } /** * Returns true if a promise is fulfilled. * * @return bool * * @deprecated is_fulfilled will be removed in guzzlehttp/promises:2.0. Use Is::fulfilled instead. */ function is_fulfilled(\Google\Site_Kit_Dependencies\GuzzleHttp\Promise\PromiseInterface $promise) { return \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Is::fulfilled($promise); } /** * Returns true if a promise is rejected. * * @return bool * * @deprecated is_rejected will be removed in guzzlehttp/promises:2.0. Use Is::rejected instead. */ function is_rejected(\Google\Site_Kit_Dependencies\GuzzleHttp\Promise\PromiseInterface $promise) { return \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Is::rejected($promise); } /** * Returns true if a promise is fulfilled or rejected. * * @return bool * * @deprecated is_settled will be removed in guzzlehttp/promises:2.0. Use Is::settled instead. */ function is_settled(\Google\Site_Kit_Dependencies\GuzzleHttp\Promise\PromiseInterface $promise) { return \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Is::settled($promise); } /** * Create a new coroutine. * * @see Coroutine * * @return PromiseInterface * * @deprecated coroutine will be removed in guzzlehttp/promises:2.0. Use Coroutine::of instead. */ function coroutine(callable $generatorFn) { return \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Coroutine::of($generatorFn); } PK!ͅ.guzzlehttp/promises/src/RejectionException.phpnu[reason = $reason; $message = 'The promise was rejected'; if ($description) { $message .= ' with reason: ' . $description; } elseif (\is_string($reason) || \is_object($reason) && \method_exists($reason, '__toString')) { $message .= ' with reason: ' . $this->reason; } elseif ($reason instanceof \JsonSerializable) { $message .= ' with reason: ' . \json_encode($this->reason, \JSON_PRETTY_PRINT); } parent::__construct($message); } /** * Returns the rejection reason. * * @return mixed */ public function getReason() { return $this->reason; } } PK!NOj$j$!guzzlehttp/promises/src/Utils.phpnu[ * while ($eventLoop->isRunning()) { * GuzzleHttp\Promise\Utils::queue()->run(); * } * * * @param TaskQueueInterface $assign Optionally specify a new queue instance. * * @return TaskQueueInterface */ public static function queue(\Google\Site_Kit_Dependencies\GuzzleHttp\Promise\TaskQueueInterface $assign = null) { static $queue; if ($assign) { $queue = $assign; } elseif (!$queue) { $queue = new \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\TaskQueue(); } return $queue; } /** * Adds a function to run in the task queue when it is next `run()` and * returns a promise that is fulfilled or rejected with the result. * * @param callable $task Task function to run. * * @return PromiseInterface */ public static function task(callable $task) { $queue = self::queue(); $promise = new \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Promise([$queue, 'run']); $queue->add(function () use($task, $promise) { try { if (\Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Is::pending($promise)) { $promise->resolve($task()); } } catch (\Throwable $e) { $promise->reject($e); } catch (\Exception $e) { $promise->reject($e); } }); return $promise; } /** * Synchronously waits on a promise to resolve and returns an inspection * state array. * * Returns a state associative array containing a "state" key mapping to a * valid promise state. If the state of the promise is "fulfilled", the * array will contain a "value" key mapping to the fulfilled value of the * promise. If the promise is rejected, the array will contain a "reason" * key mapping to the rejection reason of the promise. * * @param PromiseInterface $promise Promise or value. * * @return array */ public static function inspect(\Google\Site_Kit_Dependencies\GuzzleHttp\Promise\PromiseInterface $promise) { try { return ['state' => \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\PromiseInterface::FULFILLED, 'value' => $promise->wait()]; } catch (\Google\Site_Kit_Dependencies\GuzzleHttp\Promise\RejectionException $e) { return ['state' => \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\PromiseInterface::REJECTED, 'reason' => $e->getReason()]; } catch (\Throwable $e) { return ['state' => \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\PromiseInterface::REJECTED, 'reason' => $e]; } catch (\Exception $e) { return ['state' => \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\PromiseInterface::REJECTED, 'reason' => $e]; } } /** * Waits on all of the provided promises, but does not unwrap rejected * promises as thrown exception. * * Returns an array of inspection state arrays. * * @see inspect for the inspection state array format. * * @param PromiseInterface[] $promises Traversable of promises to wait upon. * * @return array */ public static function inspectAll($promises) { $results = []; foreach ($promises as $key => $promise) { $results[$key] = inspect($promise); } return $results; } /** * Waits on all of the provided promises and returns the fulfilled values. * * Returns an array that contains the value of each promise (in the same * order the promises were provided). An exception is thrown if any of the * promises are rejected. * * @param iterable $promises Iterable of PromiseInterface objects to wait on. * * @return array * * @throws \Exception on error * @throws \Throwable on error in PHP >=7 */ public static function unwrap($promises) { $results = []; foreach ($promises as $key => $promise) { $results[$key] = $promise->wait(); } return $results; } /** * Given an array of promises, return a promise that is fulfilled when all * the items in the array are fulfilled. * * The promise's fulfillment value is an array with fulfillment values at * respective positions to the original array. If any promise in the array * rejects, the returned promise is rejected with the rejection reason. * * @param mixed $promises Promises or values. * @param bool $recursive If true, resolves new promises that might have been added to the stack during its own resolution. * * @return PromiseInterface */ public static function all($promises, $recursive = \false) { $results = []; $promise = \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Each::of($promises, function ($value, $idx) use(&$results) { $results[$idx] = $value; }, function ($reason, $idx, \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Promise $aggregate) { $aggregate->reject($reason); })->then(function () use(&$results) { \ksort($results); return $results; }); if (\true === $recursive) { $promise = $promise->then(function ($results) use($recursive, &$promises) { foreach ($promises as $promise) { if (\Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Is::pending($promise)) { return self::all($promises, $recursive); } } return $results; }); } return $promise; } /** * Initiate a competitive race between multiple promises or values (values * will become immediately fulfilled promises). * * When count amount of promises have been fulfilled, the returned promise * is fulfilled with an array that contains the fulfillment values of the * winners in order of resolution. * * This promise is rejected with a {@see AggregateException} if the number * of fulfilled promises is less than the desired $count. * * @param int $count Total number of promises. * @param mixed $promises Promises or values. * * @return PromiseInterface */ public static function some($count, $promises) { $results = []; $rejections = []; return \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Each::of($promises, function ($value, $idx, \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\PromiseInterface $p) use(&$results, $count) { if (\Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Is::settled($p)) { return; } $results[$idx] = $value; if (\count($results) >= $count) { $p->resolve(null); } }, function ($reason) use(&$rejections) { $rejections[] = $reason; })->then(function () use(&$results, &$rejections, $count) { if (\count($results) !== $count) { throw new \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\AggregateException('Not enough promises to fulfill count', $rejections); } \ksort($results); return \array_values($results); }); } /** * Like some(), with 1 as count. However, if the promise fulfills, the * fulfillment value is not an array of 1 but the value directly. * * @param mixed $promises Promises or values. * * @return PromiseInterface */ public static function any($promises) { return self::some(1, $promises)->then(function ($values) { return $values[0]; }); } /** * Returns a promise that is fulfilled when all of the provided promises have * been fulfilled or rejected. * * The returned promise is fulfilled with an array of inspection state arrays. * * @see inspect for the inspection state array format. * * @param mixed $promises Promises or values. * * @return PromiseInterface */ public static function settle($promises) { $results = []; return \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Each::of($promises, function ($value, $idx) use(&$results) { $results[$idx] = ['state' => \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\PromiseInterface::FULFILLED, 'value' => $value]; }, function ($reason, $idx) use(&$results) { $results[$idx] = ['state' => \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\PromiseInterface::REJECTED, 'reason' => $reason]; })->then(function () use(&$results) { \ksort($results); return $results; }); } } PK!kP.guzzlehttp/promises/src/TaskQueueInterface.phpnu[value = $value; } public function then(callable $onFulfilled = null, callable $onRejected = null) { // Return itself if there is no onFulfilled function. if (!$onFulfilled) { return $this; } $queue = \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Utils::queue(); $p = new \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Promise([$queue, 'run']); $value = $this->value; $queue->add(static function () use($p, $value, $onFulfilled) { if (\Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Is::pending($p)) { try { $p->resolve($onFulfilled($value)); } catch (\Throwable $e) { $p->reject($e); } catch (\Exception $e) { $p->reject($e); } } }); return $p; } public function otherwise(callable $onRejected) { return $this->then(null, $onRejected); } public function wait($unwrap = \true, $defaultDelivery = null) { return $unwrap ? $this->value : null; } public function getState() { return self::FULFILLED; } public function resolve($value) { if ($value !== $this->value) { throw new \LogicException("Cannot resolve a fulfilled promise"); } } public function reject($reason) { throw new \LogicException("Cannot reject a fulfilled promise"); } public function cancel() { // pass } } PK!w|QQ'guzzlehttp/promises/src/EachPromise.phpnu[iterable = \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Create::iterFor($iterable); if (isset($config['concurrency'])) { $this->concurrency = $config['concurrency']; } if (isset($config['fulfilled'])) { $this->onFulfilled = $config['fulfilled']; } if (isset($config['rejected'])) { $this->onRejected = $config['rejected']; } } /** @psalm-suppress InvalidNullableReturnType */ public function promise() { if ($this->aggregate) { return $this->aggregate; } try { $this->createPromise(); /** @psalm-assert Promise $this->aggregate */ $this->iterable->rewind(); $this->refillPending(); } catch (\Throwable $e) { $this->aggregate->reject($e); } catch (\Exception $e) { $this->aggregate->reject($e); } /** * @psalm-suppress NullableReturnStatement * @phpstan-ignore-next-line */ return $this->aggregate; } private function createPromise() { $this->mutex = \false; $this->aggregate = new \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Promise(function () { if ($this->checkIfFinished()) { return; } \reset($this->pending); // Consume a potentially fluctuating list of promises while // ensuring that indexes are maintained (precluding array_shift). while ($promise = \current($this->pending)) { \next($this->pending); $promise->wait(); if (\Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Is::settled($this->aggregate)) { return; } } }); // Clear the references when the promise is resolved. $clearFn = function () { $this->iterable = $this->concurrency = $this->pending = null; $this->onFulfilled = $this->onRejected = null; $this->nextPendingIndex = 0; }; $this->aggregate->then($clearFn, $clearFn); } private function refillPending() { if (!$this->concurrency) { // Add all pending promises. while ($this->addPending() && $this->advanceIterator()) { } return; } // Add only up to N pending promises. $concurrency = \is_callable($this->concurrency) ? \call_user_func($this->concurrency, \count($this->pending)) : $this->concurrency; $concurrency = \max($concurrency - \count($this->pending), 0); // Concurrency may be set to 0 to disallow new promises. if (!$concurrency) { return; } // Add the first pending promise. $this->addPending(); // Note this is special handling for concurrency=1 so that we do // not advance the iterator after adding the first promise. This // helps work around issues with generators that might not have the // next value to yield until promise callbacks are called. while (--$concurrency && $this->advanceIterator() && $this->addPending()) { } } private function addPending() { if (!$this->iterable || !$this->iterable->valid()) { return \false; } $promise = \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Create::promiseFor($this->iterable->current()); $key = $this->iterable->key(); // Iterable keys may not be unique, so we use a counter to // guarantee uniqueness $idx = $this->nextPendingIndex++; $this->pending[$idx] = $promise->then(function ($value) use($idx, $key) { if ($this->onFulfilled) { \call_user_func($this->onFulfilled, $value, $key, $this->aggregate); } $this->step($idx); }, function ($reason) use($idx, $key) { if ($this->onRejected) { \call_user_func($this->onRejected, $reason, $key, $this->aggregate); } $this->step($idx); }); return \true; } private function advanceIterator() { // Place a lock on the iterator so that we ensure to not recurse, // preventing fatal generator errors. if ($this->mutex) { return \false; } $this->mutex = \true; try { $this->iterable->next(); $this->mutex = \false; return \true; } catch (\Throwable $e) { $this->aggregate->reject($e); $this->mutex = \false; return \false; } catch (\Exception $e) { $this->aggregate->reject($e); $this->mutex = \false; return \false; } } private function step($idx) { // If the promise was already resolved, then ignore this step. if (\Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Is::settled($this->aggregate)) { return; } unset($this->pending[$idx]); // Only refill pending promises if we are not locked, preventing the // EachPromise to recursively invoke the provided iterator, which // cause a fatal error: "Cannot resume an already running generator" if ($this->advanceIterator() && !$this->checkIfFinished()) { // Add more pending promises if possible. $this->refillPending(); } } private function checkIfFinished() { if (!$this->pending && !$this->iterable->valid()) { // Resolve the promise if there's nothing left to do. $this->aggregate->resolve(null); return \true; } return \false; } } PK!du-guzzlehttp/promises/src/functions_include.phpnu[reason = $reason; } public function then(callable $onFulfilled = null, callable $onRejected = null) { // If there's no onRejected callback then just return self. if (!$onRejected) { return $this; } $queue = \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Utils::queue(); $reason = $this->reason; $p = new \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Promise([$queue, 'run']); $queue->add(static function () use($p, $reason, $onRejected) { if (\Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Is::pending($p)) { try { // Return a resolved promise if onRejected does not throw. $p->resolve($onRejected($reason)); } catch (\Throwable $e) { // onRejected threw, so return a rejected promise. $p->reject($e); } catch (\Exception $e) { // onRejected threw, so return a rejected promise. $p->reject($e); } } }); return $p; } public function otherwise(callable $onRejected) { return $this->then(null, $onRejected); } public function wait($unwrap = \true, $defaultDelivery = null) { if ($unwrap) { throw \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Create::exceptionFor($this->reason); } return null; } public function getState() { return self::REJECTED; } public function resolve($value) { throw new \LogicException("Cannot resolve a rejected promise"); } public function reject($reason) { if ($reason !== $this->reason) { throw new \LogicException("Cannot reject a rejected promise"); } } public function cancel() { // pass } } PK!y.-guzzlehttp/promises/src/PromisorInterface.phpnu[$$#guzzlehttp/promises/src/Promise.phpnu[waitFn = $waitFn; $this->cancelFn = $cancelFn; } public function then(callable $onFulfilled = null, callable $onRejected = null) { if ($this->state === self::PENDING) { $p = new \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Promise(null, [$this, 'cancel']); $this->handlers[] = [$p, $onFulfilled, $onRejected]; $p->waitList = $this->waitList; $p->waitList[] = $this; return $p; } // Return a fulfilled promise and immediately invoke any callbacks. if ($this->state === self::FULFILLED) { $promise = \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Create::promiseFor($this->result); return $onFulfilled ? $promise->then($onFulfilled) : $promise; } // It's either cancelled or rejected, so return a rejected promise // and immediately invoke any callbacks. $rejection = \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Create::rejectionFor($this->result); return $onRejected ? $rejection->then(null, $onRejected) : $rejection; } public function otherwise(callable $onRejected) { return $this->then(null, $onRejected); } public function wait($unwrap = \true) { $this->waitIfPending(); if ($this->result instanceof \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\PromiseInterface) { return $this->result->wait($unwrap); } if ($unwrap) { if ($this->state === self::FULFILLED) { return $this->result; } // It's rejected so "unwrap" and throw an exception. throw \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Create::exceptionFor($this->result); } } public function getState() { return $this->state; } public function cancel() { if ($this->state !== self::PENDING) { return; } $this->waitFn = $this->waitList = null; if ($this->cancelFn) { $fn = $this->cancelFn; $this->cancelFn = null; try { $fn(); } catch (\Throwable $e) { $this->reject($e); } catch (\Exception $e) { $this->reject($e); } } // Reject the promise only if it wasn't rejected in a then callback. /** @psalm-suppress RedundantCondition */ if ($this->state === self::PENDING) { $this->reject(new \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\CancellationException('Promise has been cancelled')); } } public function resolve($value) { $this->settle(self::FULFILLED, $value); } public function reject($reason) { $this->settle(self::REJECTED, $reason); } private function settle($state, $value) { if ($this->state !== self::PENDING) { // Ignore calls with the same resolution. if ($state === $this->state && $value === $this->result) { return; } throw $this->state === $state ? new \LogicException("The promise is already {$state}.") : new \LogicException("Cannot change a {$this->state} promise to {$state}"); } if ($value === $this) { throw new \LogicException('Cannot fulfill or reject a promise with itself'); } // Clear out the state of the promise but stash the handlers. $this->state = $state; $this->result = $value; $handlers = $this->handlers; $this->handlers = null; $this->waitList = $this->waitFn = null; $this->cancelFn = null; if (!$handlers) { return; } // If the value was not a settled promise or a thenable, then resolve // it in the task queue using the correct ID. if (!\is_object($value) || !\method_exists($value, 'then')) { $id = $state === self::FULFILLED ? 1 : 2; // It's a success, so resolve the handlers in the queue. \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Utils::queue()->add(static function () use($id, $value, $handlers) { foreach ($handlers as $handler) { self::callHandler($id, $value, $handler); } }); } elseif ($value instanceof \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Promise && \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Is::pending($value)) { // We can just merge our handlers onto the next promise. $value->handlers = \array_merge($value->handlers, $handlers); } else { // Resolve the handlers when the forwarded promise is resolved. $value->then(static function ($value) use($handlers) { foreach ($handlers as $handler) { self::callHandler(1, $value, $handler); } }, static function ($reason) use($handlers) { foreach ($handlers as $handler) { self::callHandler(2, $reason, $handler); } }); } } /** * Call a stack of handlers using a specific callback index and value. * * @param int $index 1 (resolve) or 2 (reject). * @param mixed $value Value to pass to the callback. * @param array $handler Array of handler data (promise and callbacks). */ private static function callHandler($index, $value, array $handler) { /** @var PromiseInterface $promise */ $promise = $handler[0]; // The promise may have been cancelled or resolved before placing // this thunk in the queue. if (\Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Is::settled($promise)) { return; } try { if (isset($handler[$index])) { /* * If $f throws an exception, then $handler will be in the exception * stack trace. Since $handler contains a reference to the callable * itself we get a circular reference. We clear the $handler * here to avoid that memory leak. */ $f = $handler[$index]; unset($handler); $promise->resolve($f($value)); } elseif ($index === 1) { // Forward resolution values as-is. $promise->resolve($value); } else { // Forward rejections down the chain. $promise->reject($value); } } catch (\Throwable $reason) { $promise->reject($reason); } catch (\Exception $reason) { $promise->reject($reason); } } private function waitIfPending() { if ($this->state !== self::PENDING) { return; } elseif ($this->waitFn) { $this->invokeWaitFn(); } elseif ($this->waitList) { $this->invokeWaitList(); } else { // If there's no wait function, then reject the promise. $this->reject('Cannot wait on a promise that has ' . 'no internal wait function. You must provide a wait ' . 'function when constructing the promise to be able to ' . 'wait on a promise.'); } \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Utils::queue()->run(); /** @psalm-suppress RedundantCondition */ if ($this->state === self::PENDING) { $this->reject('Invoking the wait callback did not resolve the promise'); } } private function invokeWaitFn() { try { $wfn = $this->waitFn; $this->waitFn = null; $wfn(\true); } catch (\Exception $reason) { if ($this->state === self::PENDING) { // The promise has not been resolved yet, so reject the promise // with the exception. $this->reject($reason); } else { // The promise was already resolved, so there's a problem in // the application. throw $reason; } } } private function invokeWaitList() { $waitList = $this->waitList; $this->waitList = null; foreach ($waitList as $result) { do { $result->waitIfPending(); $result = $result->result; } while ($result instanceof \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Promise); if ($result instanceof \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\PromiseInterface) { $result->wait(\false); } } } } PK!/C2%guzzlehttp/promises/src/Coroutine.phpnu[then(function ($v) { echo $v; }); * * @param callable $generatorFn Generator function to wrap into a promise. * * @return Promise * * @link https://github.com/petkaantonov/bluebird/blob/master/API.md#generators inspiration */ final class Coroutine implements \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\PromiseInterface { /** * @var PromiseInterface|null */ private $currentPromise; /** * @var Generator */ private $generator; /** * @var Promise */ private $result; public function __construct(callable $generatorFn) { $this->generator = $generatorFn(); $this->result = new \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Promise(function () { while (isset($this->currentPromise)) { $this->currentPromise->wait(); } }); try { $this->nextCoroutine($this->generator->current()); } catch (\Exception $exception) { $this->result->reject($exception); } catch (\Throwable $throwable) { $this->result->reject($throwable); } } /** * Create a new coroutine. * * @return self */ public static function of(callable $generatorFn) { return new self($generatorFn); } public function then(callable $onFulfilled = null, callable $onRejected = null) { return $this->result->then($onFulfilled, $onRejected); } public function otherwise(callable $onRejected) { return $this->result->otherwise($onRejected); } public function wait($unwrap = \true) { return $this->result->wait($unwrap); } public function getState() { return $this->result->getState(); } public function resolve($value) { $this->result->resolve($value); } public function reject($reason) { $this->result->reject($reason); } public function cancel() { $this->currentPromise->cancel(); $this->result->cancel(); } private function nextCoroutine($yielded) { $this->currentPromise = \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Create::promiseFor($yielded)->then([$this, '_handleSuccess'], [$this, '_handleFailure']); } /** * @internal */ public function _handleSuccess($value) { unset($this->currentPromise); try { $next = $this->generator->send($value); if ($this->generator->valid()) { $this->nextCoroutine($next); } else { $this->result->resolve($value); } } catch (\Exception $exception) { $this->result->reject($exception); } catch (\Throwable $throwable) { $this->result->reject($throwable); } } /** * @internal */ public function _handleFailure($reason) { unset($this->currentPromise); try { $nextYield = $this->generator->throw(\Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Create::exceptionFor($reason)); // The throw was caught, so keep iterating on the coroutine $this->nextCoroutine($nextYield); } catch (\Exception $exception) { $this->result->reject($exception); } catch (\Throwable $throwable) { $this->result->reject($throwable); } } } PK!Cv%guzzlehttp/guzzle/src/UriTemplate.phpnu[ ['prefix' => '', 'joiner' => ',', 'query' => \false], '+' => ['prefix' => '', 'joiner' => ',', 'query' => \false], '#' => ['prefix' => '#', 'joiner' => ',', 'query' => \false], '.' => ['prefix' => '.', 'joiner' => '.', 'query' => \false], '/' => ['prefix' => '/', 'joiner' => '/', 'query' => \false], ';' => ['prefix' => ';', 'joiner' => ';', 'query' => \true], '?' => ['prefix' => '?', 'joiner' => '&', 'query' => \true], '&' => ['prefix' => '&', 'joiner' => '&', 'query' => \true]]; /** @var array Delimiters */ private static $delims = [':', '/', '?', '#', '[', ']', '@', '!', '$', '&', '\'', '(', ')', '*', '+', ',', ';', '=']; /** @var array Percent encoded delimiters */ private static $delimsPct = ['%3A', '%2F', '%3F', '%23', '%5B', '%5D', '%40', '%21', '%24', '%26', '%27', '%28', '%29', '%2A', '%2B', '%2C', '%3B', '%3D']; public function expand($template, array $variables) { if (\false === \strpos($template, '{')) { return $template; } $this->template = $template; $this->variables = $variables; return \preg_replace_callback('/\\{([^\\}]+)\\}/', [$this, 'expandMatch'], $this->template); } /** * Parse an expression into parts * * @param string $expression Expression to parse * * @return array Returns an associative array of parts */ private function parseExpression($expression) { $result = []; if (isset(self::$operatorHash[$expression[0]])) { $result['operator'] = $expression[0]; $expression = \substr($expression, 1); } else { $result['operator'] = ''; } foreach (\explode(',', $expression) as $value) { $value = \trim($value); $varspec = []; if ($colonPos = \strpos($value, ':')) { $varspec['value'] = \substr($value, 0, $colonPos); $varspec['modifier'] = ':'; $varspec['position'] = (int) \substr($value, $colonPos + 1); } elseif (\substr($value, -1) === '*') { $varspec['modifier'] = '*'; $varspec['value'] = \substr($value, 0, -1); } else { $varspec['value'] = (string) $value; $varspec['modifier'] = ''; } $result['values'][] = $varspec; } return $result; } /** * Process an expansion * * @param array $matches Matches met in the preg_replace_callback * * @return string Returns the replacement string */ private function expandMatch(array $matches) { static $rfc1738to3986 = ['+' => '%20', '%7e' => '~']; $replacements = []; $parsed = self::parseExpression($matches[1]); $prefix = self::$operatorHash[$parsed['operator']]['prefix']; $joiner = self::$operatorHash[$parsed['operator']]['joiner']; $useQuery = self::$operatorHash[$parsed['operator']]['query']; foreach ($parsed['values'] as $value) { if (!isset($this->variables[$value['value']])) { continue; } $variable = $this->variables[$value['value']]; $actuallyUseQuery = $useQuery; $expanded = ''; if (\is_array($variable)) { $isAssoc = $this->isAssoc($variable); $kvp = []; foreach ($variable as $key => $var) { if ($isAssoc) { $key = \rawurlencode($key); $isNestedArray = \is_array($var); } else { $isNestedArray = \false; } if (!$isNestedArray) { $var = \rawurlencode($var); if ($parsed['operator'] === '+' || $parsed['operator'] === '#') { $var = $this->decodeReserved($var); } } if ($value['modifier'] === '*') { if ($isAssoc) { if ($isNestedArray) { // Nested arrays must allow for deeply nested // structures. $var = \strtr(\http_build_query([$key => $var]), $rfc1738to3986); } else { $var = $key . '=' . $var; } } elseif ($key > 0 && $actuallyUseQuery) { $var = $value['value'] . '=' . $var; } } $kvp[$key] = $var; } if (empty($variable)) { $actuallyUseQuery = \false; } elseif ($value['modifier'] === '*') { $expanded = \implode($joiner, $kvp); if ($isAssoc) { // Don't prepend the value name when using the explode // modifier with an associative array. $actuallyUseQuery = \false; } } else { if ($isAssoc) { // When an associative array is encountered and the // explode modifier is not set, then the result must be // a comma separated list of keys followed by their // respective values. foreach ($kvp as $k => &$v) { $v = $k . ',' . $v; } } $expanded = \implode(',', $kvp); } } else { if ($value['modifier'] === ':') { $variable = \substr($variable, 0, $value['position']); } $expanded = \rawurlencode($variable); if ($parsed['operator'] === '+' || $parsed['operator'] === '#') { $expanded = $this->decodeReserved($expanded); } } if ($actuallyUseQuery) { if (!$expanded && $joiner !== '&') { $expanded = $value['value']; } else { $expanded = $value['value'] . '=' . $expanded; } } $replacements[] = $expanded; } $ret = \implode($joiner, $replacements); if ($ret && $prefix) { return $prefix . $ret; } return $ret; } /** * Determines if an array is associative. * * This makes the assumption that input arrays are sequences or hashes. * This assumption is a tradeoff for accuracy in favor of speed, but it * should work in almost every case where input is supplied for a URI * template. * * @param array $array Array to check * * @return bool */ private function isAssoc(array $array) { return $array && \array_keys($array)[0] !== 0; } /** * Removes percent encoding on reserved characters (used with + and # * modifiers). * * @param string $string String to fix * * @return string */ private function decodeReserved($string) { return \str_replace(self::$delimsPct, self::$delims, $string); } } PK!:1Ȁ /guzzlehttp/guzzle/src/PrepareBodyMiddleware.phpnu[nextHandler = $nextHandler; } /** * @param RequestInterface $request * @param array $options * * @return PromiseInterface */ public function __invoke(\Google\Site_Kit_Dependencies\Psr\Http\Message\RequestInterface $request, array $options) { $fn = $this->nextHandler; // Don't do anything if the request has no body. if ($request->getBody()->getSize() === 0) { return $fn($request, $options); } $modify = []; // Add a default content-type if possible. if (!$request->hasHeader('Content-Type')) { if ($uri = $request->getBody()->getMetadata('uri')) { if ($type = \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\mimetype_from_filename($uri)) { $modify['set_headers']['Content-Type'] = $type; } } } // Add a default content-length or transfer-encoding header. if (!$request->hasHeader('Content-Length') && !$request->hasHeader('Transfer-Encoding')) { $size = $request->getBody()->getSize(); if ($size !== null) { $modify['set_headers']['Content-Length'] = $size; } else { $modify['set_headers']['Transfer-Encoding'] = 'chunked'; } } // Add the expect header if needed. $this->addExpectHeader($request, $options, $modify); return $fn(\Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\modify_request($request, $modify), $options); } /** * Add expect header * * @return void */ private function addExpectHeader(\Google\Site_Kit_Dependencies\Psr\Http\Message\RequestInterface $request, array $options, array &$modify) { // Determine if the Expect header should be used if ($request->hasHeader('Expect')) { return; } $expect = isset($options['expect']) ? $options['expect'] : null; // Return if disabled or if you're not using HTTP/1.1 or HTTP/2.0 if ($expect === \false || $request->getProtocolVersion() < 1.1) { return; } // The expect header is unconditionally enabled if ($expect === \true) { $modify['set_headers']['Expect'] = '100-Continue'; return; } // By default, send the expect header when the payload is > 1mb if ($expect === null) { $expect = 1048576; } // Always add if the body cannot be rewound, the size cannot be // determined, or the size is greater than the cutoff threshold $body = $request->getBody(); $size = $body->getSize(); if ($size === null || $size >= (int) $expect || !$body->isSeekable()) { $modify['set_headers']['Expect'] = '100-Continue'; } } } PK!čLL)guzzlehttp/guzzle/src/RetryMiddleware.phpnu[decider = $decider; $this->nextHandler = $nextHandler; $this->delay = $delay ?: __CLASS__ . '::exponentialDelay'; } /** * Default exponential backoff delay function. * * @param int $retries * * @return int milliseconds. */ public static function exponentialDelay($retries) { return (int) \pow(2, $retries - 1) * 1000; } /** * @param RequestInterface $request * @param array $options * * @return PromiseInterface */ public function __invoke(\Google\Site_Kit_Dependencies\Psr\Http\Message\RequestInterface $request, array $options) { if (!isset($options['retries'])) { $options['retries'] = 0; } $fn = $this->nextHandler; return $fn($request, $options)->then($this->onFulfilled($request, $options), $this->onRejected($request, $options)); } /** * Execute fulfilled closure * * @return mixed */ private function onFulfilled(\Google\Site_Kit_Dependencies\Psr\Http\Message\RequestInterface $req, array $options) { return function ($value) use($req, $options) { if (!\call_user_func($this->decider, $options['retries'], $req, $value, null)) { return $value; } return $this->doRetry($req, $options, $value); }; } /** * Execute rejected closure * * @return callable */ private function onRejected(\Google\Site_Kit_Dependencies\Psr\Http\Message\RequestInterface $req, array $options) { return function ($reason) use($req, $options) { if (!\call_user_func($this->decider, $options['retries'], $req, null, $reason)) { return \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\rejection_for($reason); } return $this->doRetry($req, $options); }; } /** * @return self */ private function doRetry(\Google\Site_Kit_Dependencies\Psr\Http\Message\RequestInterface $request, array $options, \Google\Site_Kit_Dependencies\Psr\Http\Message\ResponseInterface $response = null) { $options['delay'] = \call_user_func($this->delay, ++$options['retries'], $response); return $this($request, $options); } } PK!Ռ 'guzzlehttp/guzzle/src/TransferStats.phpnu[request = $request; $this->response = $response; $this->transferTime = $transferTime; $this->handlerErrorData = $handlerErrorData; $this->handlerStats = $handlerStats; } /** * @return RequestInterface */ public function getRequest() { return $this->request; } /** * Returns the response that was received (if any). * * @return ResponseInterface|null */ public function getResponse() { return $this->response; } /** * Returns true if a response was received. * * @return bool */ public function hasResponse() { return $this->response !== null; } /** * Gets handler specific error data. * * This might be an exception, a integer representing an error code, or * anything else. Relying on this value assumes that you know what handler * you are using. * * @return mixed */ public function getHandlerErrorData() { return $this->handlerErrorData; } /** * Get the effective URI the request was sent to. * * @return UriInterface */ public function getEffectiveUri() { return $this->request->getUri(); } /** * Get the estimated time the request was being transferred by the handler. * * @return float|null Time in seconds. */ public function getTransferTime() { return $this->transferTime; } /** * Gets an array of all of the handler specific transfer data. * * @return array */ public function getHandlerStats() { return $this->handlerStats; } /** * Get a specific handler statistic from the handler by name. * * @param string $stat Handler specific transfer stat to retrieve. * * @return mixed|null */ public function getHandlerStat($stat) { return isset($this->handlerStats[$stat]) ? $this->handlerStats[$stat] : null; } } PK! 9*guzzlehttp/guzzle/src/MessageFormatter.phpnu[>>>>>>>\n{request}\n<<<<<<<<\n{response}\n--------\n{error}"; const SHORT = '[{ts}] "{method} {target} HTTP/{version}" {code}'; /** @var string Template used to format log messages */ private $template; /** * @param string $template Log message template */ public function __construct($template = self::CLF) { $this->template = $template ?: self::CLF; } /** * Returns a formatted message string. * * @param RequestInterface $request Request that was sent * @param ResponseInterface $response Response that was received * @param \Exception $error Exception that was received * * @return string */ public function format(\Google\Site_Kit_Dependencies\Psr\Http\Message\RequestInterface $request, \Google\Site_Kit_Dependencies\Psr\Http\Message\ResponseInterface $response = null, \Exception $error = null) { $cache = []; return \preg_replace_callback('/{\\s*([A-Za-z_\\-\\.0-9]+)\\s*}/', function (array $matches) use($request, $response, $error, &$cache) { if (isset($cache[$matches[1]])) { return $cache[$matches[1]]; } $result = ''; switch ($matches[1]) { case 'request': $result = \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\str($request); break; case 'response': $result = $response ? \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\str($response) : ''; break; case 'req_headers': $result = \trim($request->getMethod() . ' ' . $request->getRequestTarget()) . ' HTTP/' . $request->getProtocolVersion() . "\r\n" . $this->headers($request); break; case 'res_headers': $result = $response ? \sprintf('HTTP/%s %d %s', $response->getProtocolVersion(), $response->getStatusCode(), $response->getReasonPhrase()) . "\r\n" . $this->headers($response) : 'NULL'; break; case 'req_body': $result = $request->getBody(); break; case 'res_body': $result = $response ? $response->getBody() : 'NULL'; break; case 'ts': case 'date_iso_8601': $result = \gmdate('c'); break; case 'date_common_log': $result = \date('d/M/Y:H:i:s O'); break; case 'method': $result = $request->getMethod(); break; case 'version': $result = $request->getProtocolVersion(); break; case 'uri': case 'url': $result = $request->getUri(); break; case 'target': $result = $request->getRequestTarget(); break; case 'req_version': $result = $request->getProtocolVersion(); break; case 'res_version': $result = $response ? $response->getProtocolVersion() : 'NULL'; break; case 'host': $result = $request->getHeaderLine('Host'); break; case 'hostname': $result = \gethostname(); break; case 'code': $result = $response ? $response->getStatusCode() : 'NULL'; break; case 'phrase': $result = $response ? $response->getReasonPhrase() : 'NULL'; break; case 'error': $result = $error ? $error->getMessage() : 'NULL'; break; default: // handle prefixed dynamic headers if (\strpos($matches[1], 'req_header_') === 0) { $result = $request->getHeaderLine(\substr($matches[1], 11)); } elseif (\strpos($matches[1], 'res_header_') === 0) { $result = $response ? $response->getHeaderLine(\substr($matches[1], 11)) : 'NULL'; } } $cache[$matches[1]] = $result; return $result; }, $this->template); } /** * Get headers from message as string * * @return string */ private function headers(\Google\Site_Kit_Dependencies\Psr\Http\Message\MessageInterface $message) { $result = ''; foreach ($message->getHeaders() as $name => $values) { $result .= $name . ': ' . \implode(', ', $values) . "\r\n"; } return \trim($result); } } PK!uS :):)#guzzlehttp/guzzle/src/functions.phpnu[expand($template, $variables); } /** * Debug function used to describe the provided value type and class. * * @param mixed $input * * @return string Returns a string containing the type of the variable and * if a class is provided, the class name. */ function describe_type($input) { switch (\gettype($input)) { case 'object': return 'object(' . \get_class($input) . ')'; case 'array': return 'array(' . \count($input) . ')'; default: \ob_start(); \var_dump($input); // normalize float vs double return \str_replace('double(', 'float(', \rtrim(\ob_get_clean())); } } /** * Parses an array of header lines into an associative array of headers. * * @param iterable $lines Header lines array of strings in the following * format: "Name: Value" * @return array */ function headers_from_lines($lines) { $headers = []; foreach ($lines as $line) { $parts = \explode(':', $line, 2); $headers[\trim($parts[0])][] = isset($parts[1]) ? \trim($parts[1]) : null; } return $headers; } /** * Returns a debug stream based on the provided variable. * * @param mixed $value Optional value * * @return resource */ function debug_resource($value = null) { if (\is_resource($value)) { return $value; } elseif (\defined('STDOUT')) { return \STDOUT; } return \fopen('php://output', 'w'); } /** * Chooses and creates a default handler to use based on the environment. * * The returned handler is not wrapped by any default middlewares. * * @return callable Returns the best handler for the given system. * @throws \RuntimeException if no viable Handler is available. */ function choose_handler() { $handler = null; if (\function_exists('curl_multi_exec') && \function_exists('curl_exec')) { $handler = \Google\Site_Kit_Dependencies\GuzzleHttp\Handler\Proxy::wrapSync(new \Google\Site_Kit_Dependencies\GuzzleHttp\Handler\CurlMultiHandler(), new \Google\Site_Kit_Dependencies\GuzzleHttp\Handler\CurlHandler()); } elseif (\function_exists('curl_exec')) { $handler = new \Google\Site_Kit_Dependencies\GuzzleHttp\Handler\CurlHandler(); } elseif (\function_exists('curl_multi_exec')) { $handler = new \Google\Site_Kit_Dependencies\GuzzleHttp\Handler\CurlMultiHandler(); } if (\ini_get('allow_url_fopen')) { $handler = $handler ? \Google\Site_Kit_Dependencies\GuzzleHttp\Handler\Proxy::wrapStreaming($handler, new \Google\Site_Kit_Dependencies\GuzzleHttp\Handler\StreamHandler()) : new \Google\Site_Kit_Dependencies\GuzzleHttp\Handler\StreamHandler(); } elseif (!$handler) { throw new \RuntimeException('GuzzleHttp requires cURL, the ' . 'allow_url_fopen ini setting, or a custom HTTP handler.'); } return $handler; } /** * Get the default User-Agent string to use with Guzzle * * @return string */ function default_user_agent() { static $defaultAgent = ''; if (!$defaultAgent) { $defaultAgent = 'GuzzleHttp/' . \Google\Site_Kit_Dependencies\GuzzleHttp\Client::VERSION; if (\extension_loaded('curl') && \function_exists('curl_version')) { $defaultAgent .= ' curl/' . \curl_version()['version']; } $defaultAgent .= ' PHP/' . \PHP_VERSION; } return $defaultAgent; } /** * Returns the default cacert bundle for the current system. * * First, the openssl.cafile and curl.cainfo php.ini settings are checked. * If those settings are not configured, then the common locations for * bundles found on Red Hat, CentOS, Fedora, Ubuntu, Debian, FreeBSD, OS X * and Windows are checked. If any of these file locations are found on * disk, they will be utilized. * * Note: the result of this function is cached for subsequent calls. * * @return string * @throws \RuntimeException if no bundle can be found. */ function default_ca_bundle() { static $cached = null; static $cafiles = [ // Red Hat, CentOS, Fedora (provided by the ca-certificates package) '/etc/pki/tls/certs/ca-bundle.crt', // Ubuntu, Debian (provided by the ca-certificates package) '/etc/ssl/certs/ca-certificates.crt', // FreeBSD (provided by the ca_root_nss package) '/usr/local/share/certs/ca-root-nss.crt', // SLES 12 (provided by the ca-certificates package) '/var/lib/ca-certificates/ca-bundle.pem', // OS X provided by homebrew (using the default path) '/usr/local/etc/openssl/cert.pem', // Google app engine '/etc/ca-certificates.crt', // Windows? 'C:\\windows\\system32\\curl-ca-bundle.crt', 'C:\\windows\\curl-ca-bundle.crt', ]; if ($cached) { return $cached; } if ($ca = \ini_get('openssl.cafile')) { return $cached = $ca; } if ($ca = \ini_get('curl.cainfo')) { return $cached = $ca; } foreach ($cafiles as $filename) { if (\file_exists($filename)) { return $cached = $filename; } } throw new \RuntimeException(<<push(\Google\Site_Kit_Dependencies\GuzzleHttp\Middleware::httpErrors(), 'http_errors'); $stack->push(\Google\Site_Kit_Dependencies\GuzzleHttp\Middleware::redirect(), 'allow_redirects'); $stack->push(\Google\Site_Kit_Dependencies\GuzzleHttp\Middleware::cookies(), 'cookies'); $stack->push(\Google\Site_Kit_Dependencies\GuzzleHttp\Middleware::prepareBody(), 'prepare_body'); return $stack; } /** * @param callable $handler Underlying HTTP handler. */ public function __construct(callable $handler = null) { $this->handler = $handler; } /** * Invokes the handler stack as a composed handler * * @param RequestInterface $request * @param array $options * * @return ResponseInterface|PromiseInterface */ public function __invoke(\Google\Site_Kit_Dependencies\Psr\Http\Message\RequestInterface $request, array $options) { $handler = $this->resolve(); return $handler($request, $options); } /** * Dumps a string representation of the stack. * * @return string */ public function __toString() { $depth = 0; $stack = []; if ($this->handler) { $stack[] = "0) Handler: " . $this->debugCallable($this->handler); } $result = ''; foreach (\array_reverse($this->stack) as $tuple) { $depth++; $str = "{$depth}) Name: '{$tuple[1]}', "; $str .= "Function: " . $this->debugCallable($tuple[0]); $result = "> {$str}\n{$result}"; $stack[] = $str; } foreach (\array_keys($stack) as $k) { $result .= "< {$stack[$k]}\n"; } return $result; } /** * Set the HTTP handler that actually returns a promise. * * @param callable $handler Accepts a request and array of options and * returns a Promise. */ public function setHandler(callable $handler) { $this->handler = $handler; $this->cached = null; } /** * Returns true if the builder has a handler. * * @return bool */ public function hasHandler() { return (bool) $this->handler; } /** * Unshift a middleware to the bottom of the stack. * * @param callable $middleware Middleware function * @param string $name Name to register for this middleware. */ public function unshift(callable $middleware, $name = null) { \array_unshift($this->stack, [$middleware, $name]); $this->cached = null; } /** * Push a middleware to the top of the stack. * * @param callable $middleware Middleware function * @param string $name Name to register for this middleware. */ public function push(callable $middleware, $name = '') { $this->stack[] = [$middleware, $name]; $this->cached = null; } /** * Add a middleware before another middleware by name. * * @param string $findName Middleware to find * @param callable $middleware Middleware function * @param string $withName Name to register for this middleware. */ public function before($findName, callable $middleware, $withName = '') { $this->splice($findName, $withName, $middleware, \true); } /** * Add a middleware after another middleware by name. * * @param string $findName Middleware to find * @param callable $middleware Middleware function * @param string $withName Name to register for this middleware. */ public function after($findName, callable $middleware, $withName = '') { $this->splice($findName, $withName, $middleware, \false); } /** * Remove a middleware by instance or name from the stack. * * @param callable|string $remove Middleware to remove by instance or name. */ public function remove($remove) { $this->cached = null; $idx = \is_callable($remove) ? 0 : 1; $this->stack = \array_values(\array_filter($this->stack, function ($tuple) use($idx, $remove) { return $tuple[$idx] !== $remove; })); } /** * Compose the middleware and handler into a single callable function. * * @return callable */ public function resolve() { if (!$this->cached) { if (!($prev = $this->handler)) { throw new \LogicException('No handler has been specified'); } foreach (\array_reverse($this->stack) as $fn) { $prev = $fn[0]($prev); } $this->cached = $prev; } return $this->cached; } /** * @param string $name * @return int */ private function findByName($name) { foreach ($this->stack as $k => $v) { if ($v[1] === $name) { return $k; } } throw new \InvalidArgumentException("Middleware not found: {$name}"); } /** * Splices a function into the middleware list at a specific position. * * @param string $findName * @param string $withName * @param callable $middleware * @param bool $before */ private function splice($findName, $withName, callable $middleware, $before) { $this->cached = null; $idx = $this->findByName($findName); $tuple = [$middleware, $withName]; if ($before) { if ($idx === 0) { \array_unshift($this->stack, $tuple); } else { $replacement = [$tuple, $this->stack[$idx]]; \array_splice($this->stack, $idx, 1, $replacement); } } elseif ($idx === \count($this->stack) - 1) { $this->stack[] = $tuple; } else { $replacement = [$this->stack[$idx], $tuple]; \array_splice($this->stack, $idx, 1, $replacement); } } /** * Provides a debug string for a given callable. * * @param array|callable $fn Function to write as a string. * * @return string */ private function debugCallable($fn) { if (\is_string($fn)) { return "callable({$fn})"; } if (\is_array($fn)) { return \is_string($fn[0]) ? "callable({$fn[0]}::{$fn[1]})" : "callable(['" . \get_class($fn[0]) . "', '{$fn[1]}'])"; } return 'callable(' . \spl_object_hash($fn) . ')'; } } PK!TgHy y guzzlehttp/guzzle/src/Utils.phpnu[getHost()) { $asciiHost = self::idnToAsci($uri->getHost(), $options, $info); if ($asciiHost === \false) { $errorBitSet = isset($info['errors']) ? $info['errors'] : 0; $errorConstants = \array_filter(\array_keys(\get_defined_constants()), function ($name) { return \substr($name, 0, 11) === 'IDNA_ERROR_'; }); $errors = []; foreach ($errorConstants as $errorConstant) { if ($errorBitSet & \constant($errorConstant)) { $errors[] = $errorConstant; } } $errorMessage = 'IDN conversion failed'; if ($errors) { $errorMessage .= ' (errors: ' . \implode(', ', $errors) . ')'; } throw new \Google\Site_Kit_Dependencies\GuzzleHttp\Exception\InvalidArgumentException($errorMessage); } else { if ($uri->getHost() !== $asciiHost) { // Replace URI only if the ASCII version is different $uri = $uri->withHost($asciiHost); } } } return $uri; } /** * @param string $domain * @param int $options * @param array $info * * @return string|false */ private static function idnToAsci($domain, $options, &$info = []) { if (\preg_match('%^[ -~]+$%', $domain) === 1) { return $domain; } if (\extension_loaded('intl') && \defined('INTL_IDNA_VARIANT_UTS46')) { return \idn_to_ascii($domain, $options, \INTL_IDNA_VARIANT_UTS46, $info); } /* * The Idn class is marked as @internal. Verify that class and method exists. */ if (\method_exists(\Google\Site_Kit_Dependencies\Symfony\Polyfill\Intl\Idn\Idn::class, 'idn_to_ascii')) { return \Google\Site_Kit_Dependencies\Symfony\Polyfill\Intl\Idn\Idn::idn_to_ascii($domain, $options, \Google\Site_Kit_Dependencies\Symfony\Polyfill\Intl\Idn\Idn::INTL_IDNA_VARIANT_UTS46, $info); } throw new \RuntimeException('ext-intl or symfony/polyfill-intl-idn not loaded or too old'); } } PK!Eguzzlehttp/guzzle/src/Pool.phpnu[ $rfn) { if ($rfn instanceof \Google\Site_Kit_Dependencies\Psr\Http\Message\RequestInterface) { (yield $key => $client->sendAsync($rfn, $opts)); } elseif (\is_callable($rfn)) { (yield $key => $rfn($opts)); } else { throw new \InvalidArgumentException('Each value yielded by ' . 'the iterator must be a Psr7\\Http\\Message\\RequestInterface ' . 'or a callable that returns a promise that fulfills ' . 'with a Psr7\\Message\\Http\\ResponseInterface object.'); } } }; $this->each = new \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\EachPromise($requests(), $config); } /** * Get promise * * @return PromiseInterface */ public function promise() { return $this->each->promise(); } /** * Sends multiple requests concurrently and returns an array of responses * and exceptions that uses the same ordering as the provided requests. * * IMPORTANT: This method keeps every request and response in memory, and * as such, is NOT recommended when sending a large number or an * indeterminate number of requests concurrently. * * @param ClientInterface $client Client used to send the requests * @param array|\Iterator $requests Requests to send concurrently. * @param array $options Passes through the options available in * {@see GuzzleHttp\Pool::__construct} * * @return array Returns an array containing the response or an exception * in the same order that the requests were sent. * @throws \InvalidArgumentException if the event format is incorrect. */ public static function batch(\Google\Site_Kit_Dependencies\GuzzleHttp\ClientInterface $client, $requests, array $options = []) { $res = []; self::cmpCallback($options, 'fulfilled', $res); self::cmpCallback($options, 'rejected', $res); $pool = new static($client, $requests, $options); $pool->promise()->wait(); \ksort($res); return $res; } /** * Execute callback(s) * * @return void */ private static function cmpCallback(array &$options, $name, array &$results) { if (!isset($options[$name])) { $options[$name] = function ($v, $k) use(&$results) { $results[$k] = $v; }; } else { $currentFn = $options[$name]; $options[$name] = function ($v, $k) use(&$results, $currentFn) { $currentFn($v, $k); $results[$k] = $v; }; } } } PK!&&07 7 )guzzlehttp/guzzle/src/ClientInterface.phpnu[filename = $cookieFile; $this->storeSessionCookies = $storeSessionCookies; if (\file_exists($cookieFile)) { $this->load($cookieFile); } } /** * Saves the file when shutting down */ public function __destruct() { $this->save($this->filename); } /** * Saves the cookies to a file. * * @param string $filename File to save * @throws \RuntimeException if the file cannot be found or created */ public function save($filename) { $json = []; foreach ($this as $cookie) { /** @var SetCookie $cookie */ if (\Google\Site_Kit_Dependencies\GuzzleHttp\Cookie\CookieJar::shouldPersist($cookie, $this->storeSessionCookies)) { $json[] = $cookie->toArray(); } } $jsonStr = \Google\Site_Kit_Dependencies\GuzzleHttp\json_encode($json); if (\false === \file_put_contents($filename, $jsonStr, \LOCK_EX)) { throw new \RuntimeException("Unable to save file {$filename}"); } } /** * Load cookies from a JSON formatted file. * * Old cookies are kept unless overwritten by newly loaded ones. * * @param string $filename Cookie file to load. * @throws \RuntimeException if the file cannot be loaded. */ public function load($filename) { $json = \file_get_contents($filename); if (\false === $json) { throw new \RuntimeException("Unable to load file {$filename}"); } elseif ($json === '') { return; } $data = \Google\Site_Kit_Dependencies\GuzzleHttp\json_decode($json, \true); if (\is_array($data)) { foreach (\json_decode($json, \true) as $cookie) { $this->setCookie(new \Google\Site_Kit_Dependencies\GuzzleHttp\Cookie\SetCookie($cookie)); } } elseif (\strlen($data)) { throw new \RuntimeException("Invalid cookie file: {$filename}"); } } } PK!F=((*guzzlehttp/guzzle/src/Cookie/SetCookie.phpnu[ null, 'Value' => null, 'Domain' => null, 'Path' => '/', 'Max-Age' => null, 'Expires' => null, 'Secure' => \false, 'Discard' => \false, 'HttpOnly' => \false]; /** @var array Cookie data */ private $data; /** * Create a new SetCookie object from a string * * @param string $cookie Set-Cookie header string * * @return self */ public static function fromString($cookie) { // Create the default return array $data = self::$defaults; // Explode the cookie string using a series of semicolons $pieces = \array_filter(\array_map('trim', \explode(';', $cookie))); // The name of the cookie (first kvp) must exist and include an equal sign. if (empty($pieces[0]) || !\strpos($pieces[0], '=')) { return new self($data); } // Add the cookie pieces into the parsed data array foreach ($pieces as $part) { $cookieParts = \explode('=', $part, 2); $key = \trim($cookieParts[0]); $value = isset($cookieParts[1]) ? \trim($cookieParts[1], " \n\r\t\0\v") : \true; // Only check for non-cookies when cookies have been found if (empty($data['Name'])) { $data['Name'] = $key; $data['Value'] = $value; } else { foreach (\array_keys(self::$defaults) as $search) { if (!\strcasecmp($search, $key)) { $data[$search] = $value; continue 2; } } $data[$key] = $value; } } return new self($data); } /** * @param array $data Array of cookie data provided by a Cookie parser */ public function __construct(array $data = []) { $this->data = \array_replace(self::$defaults, $data); // Extract the Expires value and turn it into a UNIX timestamp if needed if (!$this->getExpires() && $this->getMaxAge()) { // Calculate the Expires date $this->setExpires(\time() + $this->getMaxAge()); } elseif ($this->getExpires() && !\is_numeric($this->getExpires())) { $this->setExpires($this->getExpires()); } } public function __toString() { $str = $this->data['Name'] . '=' . $this->data['Value'] . '; '; foreach ($this->data as $k => $v) { if ($k !== 'Name' && $k !== 'Value' && $v !== null && $v !== \false) { if ($k === 'Expires') { $str .= 'Expires=' . \gmdate('D, d M Y H:i:s \\G\\M\\T', $v) . '; '; } else { $str .= ($v === \true ? $k : "{$k}={$v}") . '; '; } } } return \rtrim($str, '; '); } public function toArray() { return $this->data; } /** * Get the cookie name * * @return string */ public function getName() { return $this->data['Name']; } /** * Set the cookie name * * @param string $name Cookie name */ public function setName($name) { $this->data['Name'] = $name; } /** * Get the cookie value * * @return string */ public function getValue() { return $this->data['Value']; } /** * Set the cookie value * * @param string $value Cookie value */ public function setValue($value) { $this->data['Value'] = $value; } /** * Get the domain * * @return string|null */ public function getDomain() { return $this->data['Domain']; } /** * Set the domain of the cookie * * @param string $domain */ public function setDomain($domain) { $this->data['Domain'] = $domain; } /** * Get the path * * @return string */ public function getPath() { return $this->data['Path']; } /** * Set the path of the cookie * * @param string $path Path of the cookie */ public function setPath($path) { $this->data['Path'] = $path; } /** * Maximum lifetime of the cookie in seconds * * @return int|null */ public function getMaxAge() { return $this->data['Max-Age']; } /** * Set the max-age of the cookie * * @param int $maxAge Max age of the cookie in seconds */ public function setMaxAge($maxAge) { $this->data['Max-Age'] = $maxAge; } /** * The UNIX timestamp when the cookie Expires * * @return mixed */ public function getExpires() { return $this->data['Expires']; } /** * Set the unix timestamp for which the cookie will expire * * @param int $timestamp Unix timestamp */ public function setExpires($timestamp) { $this->data['Expires'] = \is_numeric($timestamp) ? (int) $timestamp : \strtotime($timestamp); } /** * Get whether or not this is a secure cookie * * @return bool|null */ public function getSecure() { return $this->data['Secure']; } /** * Set whether or not the cookie is secure * * @param bool $secure Set to true or false if secure */ public function setSecure($secure) { $this->data['Secure'] = $secure; } /** * Get whether or not this is a session cookie * * @return bool|null */ public function getDiscard() { return $this->data['Discard']; } /** * Set whether or not this is a session cookie * * @param bool $discard Set to true or false if this is a session cookie */ public function setDiscard($discard) { $this->data['Discard'] = $discard; } /** * Get whether or not this is an HTTP only cookie * * @return bool */ public function getHttpOnly() { return $this->data['HttpOnly']; } /** * Set whether or not this is an HTTP only cookie * * @param bool $httpOnly Set to true or false if this is HTTP only */ public function setHttpOnly($httpOnly) { $this->data['HttpOnly'] = $httpOnly; } /** * Check if the cookie matches a path value. * * A request-path path-matches a given cookie-path if at least one of * the following conditions holds: * * - The cookie-path and the request-path are identical. * - The cookie-path is a prefix of the request-path, and the last * character of the cookie-path is %x2F ("/"). * - The cookie-path is a prefix of the request-path, and the first * character of the request-path that is not included in the cookie- * path is a %x2F ("/") character. * * @param string $requestPath Path to check against * * @return bool */ public function matchesPath($requestPath) { $cookiePath = $this->getPath(); // Match on exact matches or when path is the default empty "/" if ($cookiePath === '/' || $cookiePath == $requestPath) { return \true; } // Ensure that the cookie-path is a prefix of the request path. if (0 !== \strpos($requestPath, $cookiePath)) { return \false; } // Match if the last character of the cookie-path is "/" if (\substr($cookiePath, -1, 1) === '/') { return \true; } // Match if the first character not included in cookie path is "/" return \substr($requestPath, \strlen($cookiePath), 1) === '/'; } /** * Check if the cookie matches a domain value * * @param string $domain Domain to check against * * @return bool */ public function matchesDomain($domain) { $cookieDomain = $this->getDomain(); if (null === $cookieDomain) { return \true; } // Remove the leading '.' as per spec in RFC 6265. // http://tools.ietf.org/html/rfc6265#section-5.2.3 $cookieDomain = \ltrim(\strtolower($cookieDomain), '.'); $domain = \strtolower($domain); // Domain not set or exact match. if ('' === $cookieDomain || $domain === $cookieDomain) { return \true; } // Matching the subdomain according to RFC 6265. // http://tools.ietf.org/html/rfc6265#section-5.1.3 if (\filter_var($domain, \FILTER_VALIDATE_IP)) { return \false; } return (bool) \preg_match('/\\.' . \preg_quote($cookieDomain, '/') . '$/', $domain); } /** * Check if the cookie is expired * * @return bool */ public function isExpired() { return $this->getExpires() !== null && \time() > $this->getExpires(); } /** * Check if the cookie is valid according to RFC 6265 * * @return bool|string Returns true if valid or an error message if invalid */ public function validate() { // Names must not be empty, but can be 0 $name = $this->getName(); if (empty($name) && !\is_numeric($name)) { return 'The cookie name must not be empty'; } // Check if any of the invalid characters are present in the cookie name if (\preg_match('/[\\x00-\\x20\\x22\\x28-\\x29\\x2c\\x2f\\x3a-\\x40\\x5c\\x7b\\x7d\\x7f]/', $name)) { return 'Cookie name must not contain invalid characters: ASCII ' . 'Control characters (0-31;127), space, tab and the ' . 'following characters: ()<>@,;:\\"/?={}'; } // Value must not be empty, but can be 0 $value = $this->getValue(); if (empty($value) && !\is_numeric($value)) { return 'The cookie value must not be empty'; } // Domains must not be empty, but can be 0 // A "0" is not a valid internet domain, but may be used as server name // in a private network. $domain = $this->getDomain(); if (empty($domain) && !\is_numeric($domain)) { return 'The cookie domain must not be empty'; } return \true; } } PK!*&&*guzzlehttp/guzzle/src/Cookie/CookieJar.phpnu[strictMode = $strictMode; foreach ($cookieArray as $cookie) { if (!$cookie instanceof \Google\Site_Kit_Dependencies\GuzzleHttp\Cookie\SetCookie) { $cookie = new \Google\Site_Kit_Dependencies\GuzzleHttp\Cookie\SetCookie($cookie); } $this->setCookie($cookie); } } /** * Create a new Cookie jar from an associative array and domain. * * @param array $cookies Cookies to create the jar from * @param string $domain Domain to set the cookies to * * @return self */ public static function fromArray(array $cookies, $domain) { $cookieJar = new self(); foreach ($cookies as $name => $value) { $cookieJar->setCookie(new \Google\Site_Kit_Dependencies\GuzzleHttp\Cookie\SetCookie(['Domain' => $domain, 'Name' => $name, 'Value' => $value, 'Discard' => \true])); } return $cookieJar; } /** * @deprecated */ public static function getCookieValue($value) { return $value; } /** * Evaluate if this cookie should be persisted to storage * that survives between requests. * * @param SetCookie $cookie Being evaluated. * @param bool $allowSessionCookies If we should persist session cookies * @return bool */ public static function shouldPersist(\Google\Site_Kit_Dependencies\GuzzleHttp\Cookie\SetCookie $cookie, $allowSessionCookies = \false) { if ($cookie->getExpires() || $allowSessionCookies) { if (!$cookie->getDiscard()) { return \true; } } return \false; } /** * Finds and returns the cookie based on the name * * @param string $name cookie name to search for * @return SetCookie|null cookie that was found or null if not found */ public function getCookieByName($name) { // don't allow a non string name if ($name === null || !\is_scalar($name)) { return null; } foreach ($this->cookies as $cookie) { if ($cookie->getName() !== null && \strcasecmp($cookie->getName(), $name) === 0) { return $cookie; } } return null; } public function toArray() { return \array_map(function (\Google\Site_Kit_Dependencies\GuzzleHttp\Cookie\SetCookie $cookie) { return $cookie->toArray(); }, $this->getIterator()->getArrayCopy()); } public function clear($domain = null, $path = null, $name = null) { if (!$domain) { $this->cookies = []; return; } elseif (!$path) { $this->cookies = \array_filter($this->cookies, function (\Google\Site_Kit_Dependencies\GuzzleHttp\Cookie\SetCookie $cookie) use($domain) { return !$cookie->matchesDomain($domain); }); } elseif (!$name) { $this->cookies = \array_filter($this->cookies, function (\Google\Site_Kit_Dependencies\GuzzleHttp\Cookie\SetCookie $cookie) use($path, $domain) { return !($cookie->matchesPath($path) && $cookie->matchesDomain($domain)); }); } else { $this->cookies = \array_filter($this->cookies, function (\Google\Site_Kit_Dependencies\GuzzleHttp\Cookie\SetCookie $cookie) use($path, $domain, $name) { return !($cookie->getName() == $name && $cookie->matchesPath($path) && $cookie->matchesDomain($domain)); }); } } public function clearSessionCookies() { $this->cookies = \array_filter($this->cookies, function (\Google\Site_Kit_Dependencies\GuzzleHttp\Cookie\SetCookie $cookie) { return !$cookie->getDiscard() && $cookie->getExpires(); }); } public function setCookie(\Google\Site_Kit_Dependencies\GuzzleHttp\Cookie\SetCookie $cookie) { // If the name string is empty (but not 0), ignore the set-cookie // string entirely. $name = $cookie->getName(); if (!$name && $name !== '0') { return \false; } // Only allow cookies with set and valid domain, name, value $result = $cookie->validate(); if ($result !== \true) { if ($this->strictMode) { throw new \RuntimeException('Invalid cookie: ' . $result); } else { $this->removeCookieIfEmpty($cookie); return \false; } } // Resolve conflicts with previously set cookies foreach ($this->cookies as $i => $c) { // Two cookies are identical, when their path, and domain are // identical. if ($c->getPath() != $cookie->getPath() || $c->getDomain() != $cookie->getDomain() || $c->getName() != $cookie->getName()) { continue; } // The previously set cookie is a discard cookie and this one is // not so allow the new cookie to be set if (!$cookie->getDiscard() && $c->getDiscard()) { unset($this->cookies[$i]); continue; } // If the new cookie's expiration is further into the future, then // replace the old cookie if ($cookie->getExpires() > $c->getExpires()) { unset($this->cookies[$i]); continue; } // If the value has changed, we better change it if ($cookie->getValue() !== $c->getValue()) { unset($this->cookies[$i]); continue; } // The cookie exists, so no need to continue return \false; } $this->cookies[] = $cookie; return \true; } public function count() { return \count($this->cookies); } public function getIterator() { return new \ArrayIterator(\array_values($this->cookies)); } public function extractCookies(\Google\Site_Kit_Dependencies\Psr\Http\Message\RequestInterface $request, \Google\Site_Kit_Dependencies\Psr\Http\Message\ResponseInterface $response) { if ($cookieHeader = $response->getHeader('Set-Cookie')) { foreach ($cookieHeader as $cookie) { $sc = \Google\Site_Kit_Dependencies\GuzzleHttp\Cookie\SetCookie::fromString($cookie); if (!$sc->getDomain()) { $sc->setDomain($request->getUri()->getHost()); } if (0 !== \strpos($sc->getPath(), '/')) { $sc->setPath($this->getCookiePathFromRequest($request)); } if (!$sc->matchesDomain($request->getUri()->getHost())) { continue; } // Note: At this point `$sc->getDomain()` being a public suffix should // be rejected, but we don't want to pull in the full PSL dependency. $this->setCookie($sc); } } } /** * Computes cookie path following RFC 6265 section 5.1.4 * * @link https://tools.ietf.org/html/rfc6265#section-5.1.4 * * @param RequestInterface $request * @return string */ private function getCookiePathFromRequest(\Google\Site_Kit_Dependencies\Psr\Http\Message\RequestInterface $request) { $uriPath = $request->getUri()->getPath(); if ('' === $uriPath) { return '/'; } if (0 !== \strpos($uriPath, '/')) { return '/'; } if ('/' === $uriPath) { return '/'; } if (0 === ($lastSlashPos = \strrpos($uriPath, '/'))) { return '/'; } return \substr($uriPath, 0, $lastSlashPos); } public function withCookieHeader(\Google\Site_Kit_Dependencies\Psr\Http\Message\RequestInterface $request) { $values = []; $uri = $request->getUri(); $scheme = $uri->getScheme(); $host = $uri->getHost(); $path = $uri->getPath() ?: '/'; foreach ($this->cookies as $cookie) { if ($cookie->matchesPath($path) && $cookie->matchesDomain($host) && !$cookie->isExpired() && (!$cookie->getSecure() || $scheme === 'https')) { $values[] = $cookie->getName() . '=' . $cookie->getValue(); } } return $values ? $request->withHeader('Cookie', \implode('; ', $values)) : $request; } /** * If a cookie already exists and the server asks to set it again with a * null value, the cookie must be deleted. * * @param SetCookie $cookie */ private function removeCookieIfEmpty(\Google\Site_Kit_Dependencies\GuzzleHttp\Cookie\SetCookie $cookie) { $cookieValue = $cookie->getValue(); if ($cookieValue === null || $cookieValue === '') { $this->clear($cookie->getDomain(), $cookie->getPath(), $cookie->getName()); } } } PK!޿HH1guzzlehttp/guzzle/src/Cookie/SessionCookieJar.phpnu[sessionKey = $sessionKey; $this->storeSessionCookies = $storeSessionCookies; $this->load(); } /** * Saves cookies to session when shutting down */ public function __destruct() { $this->save(); } /** * Save cookies to the client session */ public function save() { $json = []; foreach ($this as $cookie) { /** @var SetCookie $cookie */ if (\Google\Site_Kit_Dependencies\GuzzleHttp\Cookie\CookieJar::shouldPersist($cookie, $this->storeSessionCookies)) { $json[] = $cookie->toArray(); } } $_SESSION[$this->sessionKey] = \json_encode($json); } /** * Load the contents of the client session into the data array */ protected function load() { if (!isset($_SESSION[$this->sessionKey])) { return; } $data = \json_decode($_SESSION[$this->sessionKey], \true); if (\is_array($data)) { foreach ($data as $cookie) { $this->setCookie(new \Google\Site_Kit_Dependencies\GuzzleHttp\Cookie\SetCookie($cookie)); } } elseif (\strlen($data)) { throw new \RuntimeException("Invalid cookie data"); } } } PK!! 3guzzlehttp/guzzle/src/Cookie/CookieJarInterface.phpnu[ 5, 'protocols' => ['http', 'https'], 'strict' => \false, 'referer' => \false, 'track_redirects' => \false]; /** @var callable */ private $nextHandler; /** * @param callable $nextHandler Next handler to invoke. */ public function __construct(callable $nextHandler) { $this->nextHandler = $nextHandler; } /** * @param RequestInterface $request * @param array $options * * @return PromiseInterface */ public function __invoke(\Google\Site_Kit_Dependencies\Psr\Http\Message\RequestInterface $request, array $options) { $fn = $this->nextHandler; if (empty($options['allow_redirects'])) { return $fn($request, $options); } if ($options['allow_redirects'] === \true) { $options['allow_redirects'] = self::$defaultSettings; } elseif (!\is_array($options['allow_redirects'])) { throw new \InvalidArgumentException('allow_redirects must be true, false, or array'); } else { // Merge the default settings with the provided settings $options['allow_redirects'] += self::$defaultSettings; } if (empty($options['allow_redirects']['max'])) { return $fn($request, $options); } return $fn($request, $options)->then(function (\Google\Site_Kit_Dependencies\Psr\Http\Message\ResponseInterface $response) use($request, $options) { return $this->checkRedirect($request, $options, $response); }); } /** * @param RequestInterface $request * @param array $options * @param ResponseInterface $response * * @return ResponseInterface|PromiseInterface */ public function checkRedirect(\Google\Site_Kit_Dependencies\Psr\Http\Message\RequestInterface $request, array $options, \Google\Site_Kit_Dependencies\Psr\Http\Message\ResponseInterface $response) { if (\substr($response->getStatusCode(), 0, 1) != '3' || !$response->hasHeader('Location')) { return $response; } $this->guardMax($request, $options); $nextRequest = $this->modifyRequest($request, $options, $response); // If authorization is handled by curl, unset it if URI is cross-origin. if (\Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\UriComparator::isCrossOrigin($request->getUri(), $nextRequest->getUri()) && \defined('\\CURLOPT_HTTPAUTH')) { unset($options['curl'][\CURLOPT_HTTPAUTH], $options['curl'][\CURLOPT_USERPWD]); } if (isset($options['allow_redirects']['on_redirect'])) { \call_user_func($options['allow_redirects']['on_redirect'], $request, $response, $nextRequest->getUri()); } /** @var PromiseInterface|ResponseInterface $promise */ $promise = $this($nextRequest, $options); // Add headers to be able to track history of redirects. if (!empty($options['allow_redirects']['track_redirects'])) { return $this->withTracking($promise, (string) $nextRequest->getUri(), $response->getStatusCode()); } return $promise; } /** * Enable tracking on promise. * * @return PromiseInterface */ private function withTracking(\Google\Site_Kit_Dependencies\GuzzleHttp\Promise\PromiseInterface $promise, $uri, $statusCode) { return $promise->then(function (\Google\Site_Kit_Dependencies\Psr\Http\Message\ResponseInterface $response) use($uri, $statusCode) { // Note that we are pushing to the front of the list as this // would be an earlier response than what is currently present // in the history header. $historyHeader = $response->getHeader(self::HISTORY_HEADER); $statusHeader = $response->getHeader(self::STATUS_HISTORY_HEADER); \array_unshift($historyHeader, $uri); \array_unshift($statusHeader, $statusCode); return $response->withHeader(self::HISTORY_HEADER, $historyHeader)->withHeader(self::STATUS_HISTORY_HEADER, $statusHeader); }); } /** * Check for too many redirects. * * @return void * * @throws TooManyRedirectsException Too many redirects. */ private function guardMax(\Google\Site_Kit_Dependencies\Psr\Http\Message\RequestInterface $request, array &$options) { $current = isset($options['__redirect_count']) ? $options['__redirect_count'] : 0; $options['__redirect_count'] = $current + 1; $max = $options['allow_redirects']['max']; if ($options['__redirect_count'] > $max) { throw new \Google\Site_Kit_Dependencies\GuzzleHttp\Exception\TooManyRedirectsException("Will not follow more than {$max} redirects", $request); } } /** * @param RequestInterface $request * @param array $options * @param ResponseInterface $response * * @return RequestInterface */ public function modifyRequest(\Google\Site_Kit_Dependencies\Psr\Http\Message\RequestInterface $request, array $options, \Google\Site_Kit_Dependencies\Psr\Http\Message\ResponseInterface $response) { // Request modifications to apply. $modify = []; $protocols = $options['allow_redirects']['protocols']; // Use a GET request if this is an entity enclosing request and we are // not forcing RFC compliance, but rather emulating what all browsers // would do. $statusCode = $response->getStatusCode(); if ($statusCode == 303 || $statusCode <= 302 && !$options['allow_redirects']['strict']) { $modify['method'] = 'GET'; $modify['body'] = ''; } $uri = self::redirectUri($request, $response, $protocols); if (isset($options['idn_conversion']) && $options['idn_conversion'] !== \false) { $idnOptions = $options['idn_conversion'] === \true ? \IDNA_DEFAULT : $options['idn_conversion']; $uri = \Google\Site_Kit_Dependencies\GuzzleHttp\Utils::idnUriConvert($uri, $idnOptions); } $modify['uri'] = $uri; \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\rewind_body($request); // Add the Referer header if it is told to do so and only // add the header if we are not redirecting from https to http. if ($options['allow_redirects']['referer'] && $modify['uri']->getScheme() === $request->getUri()->getScheme()) { $uri = $request->getUri()->withUserInfo(''); $modify['set_headers']['Referer'] = (string) $uri; } else { $modify['remove_headers'][] = 'Referer'; } // Remove Authorization and Cookie headers if URI is cross-origin. if (\Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\UriComparator::isCrossOrigin($request->getUri(), $modify['uri'])) { $modify['remove_headers'][] = 'Authorization'; $modify['remove_headers'][] = 'Cookie'; } return \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\modify_request($request, $modify); } /** * Set the appropriate URL on the request based on the location header. * * @param RequestInterface $request * @param ResponseInterface $response * @param array $protocols * * @return UriInterface */ private static function redirectUri(\Google\Site_Kit_Dependencies\Psr\Http\Message\RequestInterface $request, \Google\Site_Kit_Dependencies\Psr\Http\Message\ResponseInterface $response, array $protocols) { $location = \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\UriResolver::resolve($request->getUri(), new \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Uri($response->getHeaderLine('Location'))); // Ensure that the redirect URI is allowed based on the protocols. if (!\in_array($location->getScheme(), $protocols)) { throw new \Google\Site_Kit_Dependencies\GuzzleHttp\Exception\BadResponseException(\sprintf('Redirect URI, %s, does not use one of the allowed redirect protocols: %s', $location, \implode(', ', $protocols)), $request, $response); } return $location; } } PK!eWW6guzzlehttp/guzzle/src/Handler/CurlFactoryInterface.phpnu[maxHandles = $maxHandles; } public function create(\Google\Site_Kit_Dependencies\Psr\Http\Message\RequestInterface $request, array $options) { if (isset($options['curl']['body_as_string'])) { $options['_body_as_string'] = $options['curl']['body_as_string']; unset($options['curl']['body_as_string']); } $easy = new \Google\Site_Kit_Dependencies\GuzzleHttp\Handler\EasyHandle(); $easy->request = $request; $easy->options = $options; $conf = $this->getDefaultConf($easy); $this->applyMethod($easy, $conf); $this->applyHandlerOptions($easy, $conf); $this->applyHeaders($easy, $conf); unset($conf['_headers']); // Add handler options from the request configuration options if (isset($options['curl'])) { $conf = \array_replace($conf, $options['curl']); } $conf[\CURLOPT_HEADERFUNCTION] = $this->createHeaderFn($easy); $easy->handle = $this->handles ? \array_pop($this->handles) : \curl_init(); \curl_setopt_array($easy->handle, $conf); return $easy; } public function release(\Google\Site_Kit_Dependencies\GuzzleHttp\Handler\EasyHandle $easy) { $resource = $easy->handle; unset($easy->handle); if (\count($this->handles) >= $this->maxHandles) { \curl_close($resource); } else { // Remove all callback functions as they can hold onto references // and are not cleaned up by curl_reset. Using curl_setopt_array // does not work for some reason, so removing each one // individually. \curl_setopt($resource, \CURLOPT_HEADERFUNCTION, null); \curl_setopt($resource, \CURLOPT_READFUNCTION, null); \curl_setopt($resource, \CURLOPT_WRITEFUNCTION, null); \curl_setopt($resource, \CURLOPT_PROGRESSFUNCTION, null); \curl_reset($resource); $this->handles[] = $resource; } } /** * Completes a cURL transaction, either returning a response promise or a * rejected promise. * * @param callable $handler * @param EasyHandle $easy * @param CurlFactoryInterface $factory Dictates how the handle is released * * @return \GuzzleHttp\Promise\PromiseInterface */ public static function finish(callable $handler, \Google\Site_Kit_Dependencies\GuzzleHttp\Handler\EasyHandle $easy, \Google\Site_Kit_Dependencies\GuzzleHttp\Handler\CurlFactoryInterface $factory) { if (isset($easy->options['on_stats'])) { self::invokeStats($easy); } if (!$easy->response || $easy->errno) { return self::finishError($handler, $easy, $factory); } // Return the response if it is present and there is no error. $factory->release($easy); // Rewind the body of the response if possible. $body = $easy->response->getBody(); if ($body->isSeekable()) { $body->rewind(); } return new \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\FulfilledPromise($easy->response); } private static function invokeStats(\Google\Site_Kit_Dependencies\GuzzleHttp\Handler\EasyHandle $easy) { $curlStats = \curl_getinfo($easy->handle); $curlStats['appconnect_time'] = \curl_getinfo($easy->handle, \CURLINFO_APPCONNECT_TIME); $stats = new \Google\Site_Kit_Dependencies\GuzzleHttp\TransferStats($easy->request, $easy->response, $curlStats['total_time'], $easy->errno, $curlStats); \call_user_func($easy->options['on_stats'], $stats); } private static function finishError(callable $handler, \Google\Site_Kit_Dependencies\GuzzleHttp\Handler\EasyHandle $easy, \Google\Site_Kit_Dependencies\GuzzleHttp\Handler\CurlFactoryInterface $factory) { // Get error information and release the handle to the factory. $ctx = ['errno' => $easy->errno, 'error' => \curl_error($easy->handle), 'appconnect_time' => \curl_getinfo($easy->handle, \CURLINFO_APPCONNECT_TIME)] + \curl_getinfo($easy->handle); $ctx[self::CURL_VERSION_STR] = \curl_version()['version']; $factory->release($easy); // Retry when nothing is present or when curl failed to rewind. if (empty($easy->options['_err_message']) && (!$easy->errno || $easy->errno == 65)) { return self::retryFailedRewind($handler, $easy, $ctx); } return self::createRejection($easy, $ctx); } private static function createRejection(\Google\Site_Kit_Dependencies\GuzzleHttp\Handler\EasyHandle $easy, array $ctx) { static $connectionErrors = [\CURLE_OPERATION_TIMEOUTED => \true, \CURLE_COULDNT_RESOLVE_HOST => \true, \CURLE_COULDNT_CONNECT => \true, \CURLE_SSL_CONNECT_ERROR => \true, \CURLE_GOT_NOTHING => \true]; // If an exception was encountered during the onHeaders event, then // return a rejected promise that wraps that exception. if ($easy->onHeadersException) { return \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\rejection_for(new \Google\Site_Kit_Dependencies\GuzzleHttp\Exception\RequestException('An error was encountered during the on_headers event', $easy->request, $easy->response, $easy->onHeadersException, $ctx)); } if (\version_compare($ctx[self::CURL_VERSION_STR], self::LOW_CURL_VERSION_NUMBER)) { $message = \sprintf('cURL error %s: %s (%s)', $ctx['errno'], $ctx['error'], 'see https://curl.haxx.se/libcurl/c/libcurl-errors.html'); } else { $message = \sprintf('cURL error %s: %s (%s) for %s', $ctx['errno'], $ctx['error'], 'see https://curl.haxx.se/libcurl/c/libcurl-errors.html', $easy->request->getUri()); } // Create a connection exception if it was a specific error code. $error = isset($connectionErrors[$easy->errno]) ? new \Google\Site_Kit_Dependencies\GuzzleHttp\Exception\ConnectException($message, $easy->request, null, $ctx) : new \Google\Site_Kit_Dependencies\GuzzleHttp\Exception\RequestException($message, $easy->request, $easy->response, null, $ctx); return \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\rejection_for($error); } private function getDefaultConf(\Google\Site_Kit_Dependencies\GuzzleHttp\Handler\EasyHandle $easy) { $conf = ['_headers' => $easy->request->getHeaders(), \CURLOPT_CUSTOMREQUEST => $easy->request->getMethod(), \CURLOPT_URL => (string) $easy->request->getUri()->withFragment(''), \CURLOPT_RETURNTRANSFER => \false, \CURLOPT_HEADER => \false, \CURLOPT_CONNECTTIMEOUT => 150]; if (\defined('CURLOPT_PROTOCOLS')) { $conf[\CURLOPT_PROTOCOLS] = \CURLPROTO_HTTP | \CURLPROTO_HTTPS; } $version = $easy->request->getProtocolVersion(); if ($version == 1.1) { $conf[\CURLOPT_HTTP_VERSION] = \CURL_HTTP_VERSION_1_1; } elseif ($version == 2.0) { $conf[\CURLOPT_HTTP_VERSION] = \CURL_HTTP_VERSION_2_0; } else { $conf[\CURLOPT_HTTP_VERSION] = \CURL_HTTP_VERSION_1_0; } return $conf; } private function applyMethod(\Google\Site_Kit_Dependencies\GuzzleHttp\Handler\EasyHandle $easy, array &$conf) { $body = $easy->request->getBody(); $size = $body->getSize(); if ($size === null || $size > 0) { $this->applyBody($easy->request, $easy->options, $conf); return; } $method = $easy->request->getMethod(); if ($method === 'PUT' || $method === 'POST') { // See http://tools.ietf.org/html/rfc7230#section-3.3.2 if (!$easy->request->hasHeader('Content-Length')) { $conf[\CURLOPT_HTTPHEADER][] = 'Content-Length: 0'; } } elseif ($method === 'HEAD') { $conf[\CURLOPT_NOBODY] = \true; unset($conf[\CURLOPT_WRITEFUNCTION], $conf[\CURLOPT_READFUNCTION], $conf[\CURLOPT_FILE], $conf[\CURLOPT_INFILE]); } } private function applyBody(\Google\Site_Kit_Dependencies\Psr\Http\Message\RequestInterface $request, array $options, array &$conf) { $size = $request->hasHeader('Content-Length') ? (int) $request->getHeaderLine('Content-Length') : null; // Send the body as a string if the size is less than 1MB OR if the // [curl][body_as_string] request value is set. if ($size !== null && $size < 1000000 || !empty($options['_body_as_string'])) { $conf[\CURLOPT_POSTFIELDS] = (string) $request->getBody(); // Don't duplicate the Content-Length header $this->removeHeader('Content-Length', $conf); $this->removeHeader('Transfer-Encoding', $conf); } else { $conf[\CURLOPT_UPLOAD] = \true; if ($size !== null) { $conf[\CURLOPT_INFILESIZE] = $size; $this->removeHeader('Content-Length', $conf); } $body = $request->getBody(); if ($body->isSeekable()) { $body->rewind(); } $conf[\CURLOPT_READFUNCTION] = function ($ch, $fd, $length) use($body) { return $body->read($length); }; } // If the Expect header is not present, prevent curl from adding it if (!$request->hasHeader('Expect')) { $conf[\CURLOPT_HTTPHEADER][] = 'Expect:'; } // cURL sometimes adds a content-type by default. Prevent this. if (!$request->hasHeader('Content-Type')) { $conf[\CURLOPT_HTTPHEADER][] = 'Content-Type:'; } } private function applyHeaders(\Google\Site_Kit_Dependencies\GuzzleHttp\Handler\EasyHandle $easy, array &$conf) { foreach ($conf['_headers'] as $name => $values) { foreach ($values as $value) { $value = (string) $value; if ($value === '') { // cURL requires a special format for empty headers. // See https://github.com/guzzle/guzzle/issues/1882 for more details. $conf[\CURLOPT_HTTPHEADER][] = "{$name};"; } else { $conf[\CURLOPT_HTTPHEADER][] = "{$name}: {$value}"; } } } // Remove the Accept header if one was not set if (!$easy->request->hasHeader('Accept')) { $conf[\CURLOPT_HTTPHEADER][] = 'Accept:'; } } /** * Remove a header from the options array. * * @param string $name Case-insensitive header to remove * @param array $options Array of options to modify */ private function removeHeader($name, array &$options) { foreach (\array_keys($options['_headers']) as $key) { if (!\strcasecmp($key, $name)) { unset($options['_headers'][$key]); return; } } } private function applyHandlerOptions(\Google\Site_Kit_Dependencies\GuzzleHttp\Handler\EasyHandle $easy, array &$conf) { $options = $easy->options; if (isset($options['verify'])) { if ($options['verify'] === \false) { unset($conf[\CURLOPT_CAINFO]); $conf[\CURLOPT_SSL_VERIFYHOST] = 0; $conf[\CURLOPT_SSL_VERIFYPEER] = \false; } else { $conf[\CURLOPT_SSL_VERIFYHOST] = 2; $conf[\CURLOPT_SSL_VERIFYPEER] = \true; if (\is_string($options['verify'])) { // Throw an error if the file/folder/link path is not valid or doesn't exist. if (!\file_exists($options['verify'])) { throw new \InvalidArgumentException("SSL CA bundle not found: {$options['verify']}"); } // If it's a directory or a link to a directory use CURLOPT_CAPATH. // If not, it's probably a file, or a link to a file, so use CURLOPT_CAINFO. if (\is_dir($options['verify']) || \is_link($options['verify']) && \is_dir(\readlink($options['verify']))) { $conf[\CURLOPT_CAPATH] = $options['verify']; } else { $conf[\CURLOPT_CAINFO] = $options['verify']; } } } } if (!empty($options['decode_content'])) { $accept = $easy->request->getHeaderLine('Accept-Encoding'); if ($accept) { $conf[\CURLOPT_ENCODING] = $accept; } else { $conf[\CURLOPT_ENCODING] = ''; // Don't let curl send the header over the wire $conf[\CURLOPT_HTTPHEADER][] = 'Accept-Encoding:'; } } if (isset($options['sink'])) { $sink = $options['sink']; if (!\is_string($sink)) { $sink = \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\stream_for($sink); } elseif (!\is_dir(\dirname($sink))) { // Ensure that the directory exists before failing in curl. throw new \RuntimeException(\sprintf('Directory %s does not exist for sink value of %s', \dirname($sink), $sink)); } else { $sink = new \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\LazyOpenStream($sink, 'w+'); } $easy->sink = $sink; $conf[\CURLOPT_WRITEFUNCTION] = function ($ch, $write) use($sink) { return $sink->write($write); }; } else { // Use a default temp stream if no sink was set. $conf[\CURLOPT_FILE] = \fopen('php://temp', 'w+'); $easy->sink = \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\stream_for($conf[\CURLOPT_FILE]); } $timeoutRequiresNoSignal = \false; if (isset($options['timeout'])) { $timeoutRequiresNoSignal |= $options['timeout'] < 1; $conf[\CURLOPT_TIMEOUT_MS] = $options['timeout'] * 1000; } // CURL default value is CURL_IPRESOLVE_WHATEVER if (isset($options['force_ip_resolve'])) { if ('v4' === $options['force_ip_resolve']) { $conf[\CURLOPT_IPRESOLVE] = \CURL_IPRESOLVE_V4; } elseif ('v6' === $options['force_ip_resolve']) { $conf[\CURLOPT_IPRESOLVE] = \CURL_IPRESOLVE_V6; } } if (isset($options['connect_timeout'])) { $timeoutRequiresNoSignal |= $options['connect_timeout'] < 1; $conf[\CURLOPT_CONNECTTIMEOUT_MS] = $options['connect_timeout'] * 1000; } if ($timeoutRequiresNoSignal && \strtoupper(\substr(\PHP_OS, 0, 3)) !== 'WIN') { $conf[\CURLOPT_NOSIGNAL] = \true; } if (isset($options['proxy'])) { if (!\is_array($options['proxy'])) { $conf[\CURLOPT_PROXY] = $options['proxy']; } else { $scheme = $easy->request->getUri()->getScheme(); if (isset($options['proxy'][$scheme])) { $host = $easy->request->getUri()->getHost(); if (!isset($options['proxy']['no']) || !\Google\Site_Kit_Dependencies\GuzzleHttp\is_host_in_noproxy($host, $options['proxy']['no'])) { $conf[\CURLOPT_PROXY] = $options['proxy'][$scheme]; } } } } if (isset($options['cert'])) { $cert = $options['cert']; if (\is_array($cert)) { $conf[\CURLOPT_SSLCERTPASSWD] = $cert[1]; $cert = $cert[0]; } if (!\file_exists($cert)) { throw new \InvalidArgumentException("SSL certificate not found: {$cert}"); } $conf[\CURLOPT_SSLCERT] = $cert; } if (isset($options['ssl_key'])) { if (\is_array($options['ssl_key'])) { if (\count($options['ssl_key']) === 2) { list($sslKey, $conf[\CURLOPT_SSLKEYPASSWD]) = $options['ssl_key']; } else { list($sslKey) = $options['ssl_key']; } } $sslKey = isset($sslKey) ? $sslKey : $options['ssl_key']; if (!\file_exists($sslKey)) { throw new \InvalidArgumentException("SSL private key not found: {$sslKey}"); } $conf[\CURLOPT_SSLKEY] = $sslKey; } if (isset($options['progress'])) { $progress = $options['progress']; if (!\is_callable($progress)) { throw new \InvalidArgumentException('progress client option must be callable'); } $conf[\CURLOPT_NOPROGRESS] = \false; $conf[\CURLOPT_PROGRESSFUNCTION] = function () use($progress) { $args = \func_get_args(); // PHP 5.5 pushed the handle onto the start of the args if (\is_resource($args[0])) { \array_shift($args); } \call_user_func_array($progress, $args); }; } if (!empty($options['debug'])) { $conf[\CURLOPT_STDERR] = \Google\Site_Kit_Dependencies\GuzzleHttp\debug_resource($options['debug']); $conf[\CURLOPT_VERBOSE] = \true; } } /** * This function ensures that a response was set on a transaction. If one * was not set, then the request is retried if possible. This error * typically means you are sending a payload, curl encountered a * "Connection died, retrying a fresh connect" error, tried to rewind the * stream, and then encountered a "necessary data rewind wasn't possible" * error, causing the request to be sent through curl_multi_info_read() * without an error status. */ private static function retryFailedRewind(callable $handler, \Google\Site_Kit_Dependencies\GuzzleHttp\Handler\EasyHandle $easy, array $ctx) { try { // Only rewind if the body has been read from. $body = $easy->request->getBody(); if ($body->tell() > 0) { $body->rewind(); } } catch (\RuntimeException $e) { $ctx['error'] = 'The connection unexpectedly failed without ' . 'providing an error. The request would have been retried, ' . 'but attempting to rewind the request body failed. ' . 'Exception: ' . $e; return self::createRejection($easy, $ctx); } // Retry no more than 3 times before giving up. if (!isset($easy->options['_curl_retries'])) { $easy->options['_curl_retries'] = 1; } elseif ($easy->options['_curl_retries'] == 2) { $ctx['error'] = 'The cURL request was retried 3 times ' . 'and did not succeed. The most likely reason for the failure ' . 'is that cURL was unable to rewind the body of the request ' . 'and subsequent retries resulted in the same error. Turn on ' . 'the debug option to see what went wrong. See ' . 'https://bugs.php.net/bug.php?id=47204 for more information.'; return self::createRejection($easy, $ctx); } else { $easy->options['_curl_retries']++; } return $handler($easy->request, $easy->options); } private function createHeaderFn(\Google\Site_Kit_Dependencies\GuzzleHttp\Handler\EasyHandle $easy) { if (isset($easy->options['on_headers'])) { $onHeaders = $easy->options['on_headers']; if (!\is_callable($onHeaders)) { throw new \InvalidArgumentException('on_headers must be callable'); } } else { $onHeaders = null; } return function ($ch, $h) use($onHeaders, $easy, &$startingResponse) { $value = \trim($h); if ($value === '') { $startingResponse = \true; $easy->createResponse(); if ($onHeaders !== null) { try { $onHeaders($easy->response); } catch (\Exception $e) { // Associate the exception with the handle and trigger // a curl header write error by returning 0. $easy->onHeadersException = $e; return -1; } } } elseif ($startingResponse) { $startingResponse = \false; $easy->headers = [$value]; } else { $easy->headers[] = $value; } return \strlen($h); }; } } PK!ѩa a ,guzzlehttp/guzzle/src/Handler/EasyHandle.phpnu[headers)) { throw new \RuntimeException('No headers have been received'); } // HTTP-version SP status-code SP reason-phrase $startLine = \explode(' ', \array_shift($this->headers), 3); $headers = \Google\Site_Kit_Dependencies\GuzzleHttp\headers_from_lines($this->headers); $normalizedKeys = \Google\Site_Kit_Dependencies\GuzzleHttp\normalize_header_keys($headers); if (!empty($this->options['decode_content']) && isset($normalizedKeys['content-encoding'])) { $headers['x-encoded-content-encoding'] = $headers[$normalizedKeys['content-encoding']]; unset($headers[$normalizedKeys['content-encoding']]); if (isset($normalizedKeys['content-length'])) { $headers['x-encoded-content-length'] = $headers[$normalizedKeys['content-length']]; $bodyLength = (int) $this->sink->getSize(); if ($bodyLength) { $headers[$normalizedKeys['content-length']] = $bodyLength; } else { unset($headers[$normalizedKeys['content-length']]); } } } // Attach a response to the easy handle with the parsed headers. $this->response = new \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Response($startLine[1], $headers, $this->sink, \substr($startLine[0], 5), isset($startLine[2]) ? (string) $startLine[2] : null); } public function __get($name) { $msg = $name === 'handle' ? 'The EasyHandle has been released' : 'Invalid property: ' . $name; throw new \BadMethodCallException($msg); } } PK!ڮII/guzzlehttp/guzzle/src/Handler/StreamHandler.phpnu[withoutHeader('Expect'); // Append a content-length header if body size is zero to match // cURL's behavior. if (0 === $request->getBody()->getSize()) { $request = $request->withHeader('Content-Length', '0'); } return $this->createResponse($request, $options, $this->createStream($request, $options), $startTime); } catch (\InvalidArgumentException $e) { throw $e; } catch (\Exception $e) { // Determine if the error was a networking error. $message = $e->getMessage(); // This list can probably get more comprehensive. if (\strpos($message, 'getaddrinfo') || \strpos($message, 'Connection refused') || \strpos($message, "couldn't connect to host") || \strpos($message, "connection attempt failed")) { $e = new \Google\Site_Kit_Dependencies\GuzzleHttp\Exception\ConnectException($e->getMessage(), $request, $e); } $e = \Google\Site_Kit_Dependencies\GuzzleHttp\Exception\RequestException::wrapException($request, $e); $this->invokeStats($options, $request, $startTime, null, $e); return \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\rejection_for($e); } } private function invokeStats(array $options, \Google\Site_Kit_Dependencies\Psr\Http\Message\RequestInterface $request, $startTime, \Google\Site_Kit_Dependencies\Psr\Http\Message\ResponseInterface $response = null, $error = null) { if (isset($options['on_stats'])) { $stats = new \Google\Site_Kit_Dependencies\GuzzleHttp\TransferStats($request, $response, \Google\Site_Kit_Dependencies\GuzzleHttp\Utils::currentTime() - $startTime, $error, []); \call_user_func($options['on_stats'], $stats); } } private function createResponse(\Google\Site_Kit_Dependencies\Psr\Http\Message\RequestInterface $request, array $options, $stream, $startTime) { $hdrs = $this->lastHeaders; $this->lastHeaders = []; $parts = \explode(' ', \array_shift($hdrs), 3); $ver = \explode('/', $parts[0])[1]; $status = $parts[1]; $reason = isset($parts[2]) ? $parts[2] : null; $headers = \Google\Site_Kit_Dependencies\GuzzleHttp\headers_from_lines($hdrs); list($stream, $headers) = $this->checkDecode($options, $headers, $stream); $stream = \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\stream_for($stream); $sink = $stream; if (\strcasecmp('HEAD', $request->getMethod())) { $sink = $this->createSink($stream, $options); } $response = new \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Response($status, $headers, $sink, $ver, $reason); if (isset($options['on_headers'])) { try { $options['on_headers']($response); } catch (\Exception $e) { $msg = 'An error was encountered during the on_headers event'; $ex = new \Google\Site_Kit_Dependencies\GuzzleHttp\Exception\RequestException($msg, $request, $response, $e); return \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\rejection_for($ex); } } // Do not drain when the request is a HEAD request because they have // no body. if ($sink !== $stream) { $this->drain($stream, $sink, $response->getHeaderLine('Content-Length')); } $this->invokeStats($options, $request, $startTime, $response, null); return new \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\FulfilledPromise($response); } private function createSink(\Google\Site_Kit_Dependencies\Psr\Http\Message\StreamInterface $stream, array $options) { if (!empty($options['stream'])) { return $stream; } $sink = isset($options['sink']) ? $options['sink'] : \fopen('php://temp', 'r+'); return \is_string($sink) ? new \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\LazyOpenStream($sink, 'w+') : \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\stream_for($sink); } private function checkDecode(array $options, array $headers, $stream) { // Automatically decode responses when instructed. if (!empty($options['decode_content'])) { $normalizedKeys = \Google\Site_Kit_Dependencies\GuzzleHttp\normalize_header_keys($headers); if (isset($normalizedKeys['content-encoding'])) { $encoding = $headers[$normalizedKeys['content-encoding']]; if ($encoding[0] === 'gzip' || $encoding[0] === 'deflate') { $stream = new \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\InflateStream(\Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\stream_for($stream)); $headers['x-encoded-content-encoding'] = $headers[$normalizedKeys['content-encoding']]; // Remove content-encoding header unset($headers[$normalizedKeys['content-encoding']]); // Fix content-length header if (isset($normalizedKeys['content-length'])) { $headers['x-encoded-content-length'] = $headers[$normalizedKeys['content-length']]; $length = (int) $stream->getSize(); if ($length === 0) { unset($headers[$normalizedKeys['content-length']]); } else { $headers[$normalizedKeys['content-length']] = [$length]; } } } } } return [$stream, $headers]; } /** * Drains the source stream into the "sink" client option. * * @param StreamInterface $source * @param StreamInterface $sink * @param string $contentLength Header specifying the amount of * data to read. * * @return StreamInterface * @throws \RuntimeException when the sink option is invalid. */ private function drain(\Google\Site_Kit_Dependencies\Psr\Http\Message\StreamInterface $source, \Google\Site_Kit_Dependencies\Psr\Http\Message\StreamInterface $sink, $contentLength) { // If a content-length header is provided, then stop reading once // that number of bytes has been read. This can prevent infinitely // reading from a stream when dealing with servers that do not honor // Connection: Close headers. \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\copy_to_stream($source, $sink, \strlen($contentLength) > 0 && (int) $contentLength > 0 ? (int) $contentLength : -1); $sink->seek(0); $source->close(); return $sink; } /** * Create a resource and check to ensure it was created successfully * * @param callable $callback Callable that returns stream resource * * @return resource * @throws \RuntimeException on error */ private function createResource(callable $callback) { $errors = null; \set_error_handler(function ($_, $msg, $file, $line) use(&$errors) { $errors[] = ['message' => $msg, 'file' => $file, 'line' => $line]; return \true; }); $resource = $callback(); \restore_error_handler(); if (!$resource) { $message = 'Error creating resource: '; foreach ($errors as $err) { foreach ($err as $key => $value) { $message .= "[{$key}] {$value}" . \PHP_EOL; } } throw new \RuntimeException(\trim($message)); } return $resource; } private function createStream(\Google\Site_Kit_Dependencies\Psr\Http\Message\RequestInterface $request, array $options) { static $methods; if (!$methods) { $methods = \array_flip(\get_class_methods(__CLASS__)); } // HTTP/1.1 streams using the PHP stream wrapper require a // Connection: close header if ($request->getProtocolVersion() == '1.1' && !$request->hasHeader('Connection')) { $request = $request->withHeader('Connection', 'close'); } // Ensure SSL is verified by default if (!isset($options['verify'])) { $options['verify'] = \true; } $params = []; $context = $this->getDefaultContext($request); if (isset($options['on_headers']) && !\is_callable($options['on_headers'])) { throw new \InvalidArgumentException('on_headers must be callable'); } if (!empty($options)) { foreach ($options as $key => $value) { $method = "add_{$key}"; if (isset($methods[$method])) { $this->{$method}($request, $context, $value, $params); } } } if (isset($options['stream_context'])) { if (!\is_array($options['stream_context'])) { throw new \InvalidArgumentException('stream_context must be an array'); } $context = \array_replace_recursive($context, $options['stream_context']); } // Microsoft NTLM authentication only supported with curl handler if (isset($options['auth']) && \is_array($options['auth']) && isset($options['auth'][2]) && 'ntlm' == $options['auth'][2]) { throw new \InvalidArgumentException('Microsoft NTLM authentication only supported with curl handler'); } $uri = $this->resolveHost($request, $options); $context = $this->createResource(function () use($context, $params) { return \stream_context_create($context, $params); }); return $this->createResource(function () use($uri, &$http_response_header, $context, $options) { $resource = \fopen((string) $uri, 'r', null, $context); $this->lastHeaders = $http_response_header; if (isset($options['read_timeout'])) { $readTimeout = $options['read_timeout']; $sec = (int) $readTimeout; $usec = ($readTimeout - $sec) * 100000; \stream_set_timeout($resource, $sec, $usec); } return $resource; }); } private function resolveHost(\Google\Site_Kit_Dependencies\Psr\Http\Message\RequestInterface $request, array $options) { $uri = $request->getUri(); if (isset($options['force_ip_resolve']) && !\filter_var($uri->getHost(), \FILTER_VALIDATE_IP)) { if ('v4' === $options['force_ip_resolve']) { $records = \dns_get_record($uri->getHost(), \DNS_A); if (!isset($records[0]['ip'])) { throw new \Google\Site_Kit_Dependencies\GuzzleHttp\Exception\ConnectException(\sprintf("Could not resolve IPv4 address for host '%s'", $uri->getHost()), $request); } $uri = $uri->withHost($records[0]['ip']); } elseif ('v6' === $options['force_ip_resolve']) { $records = \dns_get_record($uri->getHost(), \DNS_AAAA); if (!isset($records[0]['ipv6'])) { throw new \Google\Site_Kit_Dependencies\GuzzleHttp\Exception\ConnectException(\sprintf("Could not resolve IPv6 address for host '%s'", $uri->getHost()), $request); } $uri = $uri->withHost('[' . $records[0]['ipv6'] . ']'); } } return $uri; } private function getDefaultContext(\Google\Site_Kit_Dependencies\Psr\Http\Message\RequestInterface $request) { $headers = ''; foreach ($request->getHeaders() as $name => $value) { foreach ($value as $val) { $headers .= "{$name}: {$val}\r\n"; } } $context = ['http' => ['method' => $request->getMethod(), 'header' => $headers, 'protocol_version' => $request->getProtocolVersion(), 'ignore_errors' => \true, 'follow_location' => 0]]; $body = (string) $request->getBody(); if (!empty($body)) { $context['http']['content'] = $body; // Prevent the HTTP handler from adding a Content-Type header. if (!$request->hasHeader('Content-Type')) { $context['http']['header'] .= "Content-Type:\r\n"; } } $context['http']['header'] = \rtrim($context['http']['header']); return $context; } private function add_proxy(\Google\Site_Kit_Dependencies\Psr\Http\Message\RequestInterface $request, &$options, $value, &$params) { if (!\is_array($value)) { $options['http']['proxy'] = $value; } else { $scheme = $request->getUri()->getScheme(); if (isset($value[$scheme])) { if (!isset($value['no']) || !\Google\Site_Kit_Dependencies\GuzzleHttp\is_host_in_noproxy($request->getUri()->getHost(), $value['no'])) { $options['http']['proxy'] = $value[$scheme]; } } } } private function add_timeout(\Google\Site_Kit_Dependencies\Psr\Http\Message\RequestInterface $request, &$options, $value, &$params) { if ($value > 0) { $options['http']['timeout'] = $value; } } private function add_verify(\Google\Site_Kit_Dependencies\Psr\Http\Message\RequestInterface $request, &$options, $value, &$params) { if ($value === \true) { // PHP 5.6 or greater will find the system cert by default. When // < 5.6, use the Guzzle bundled cacert. if (\PHP_VERSION_ID < 50600) { $options['ssl']['cafile'] = \Google\Site_Kit_Dependencies\GuzzleHttp\default_ca_bundle(); } } elseif (\is_string($value)) { $options['ssl']['cafile'] = $value; if (!\file_exists($value)) { throw new \RuntimeException("SSL CA bundle not found: {$value}"); } } elseif ($value === \false) { $options['ssl']['verify_peer'] = \false; $options['ssl']['verify_peer_name'] = \false; return; } else { throw new \InvalidArgumentException('Invalid verify request option'); } $options['ssl']['verify_peer'] = \true; $options['ssl']['verify_peer_name'] = \true; $options['ssl']['allow_self_signed'] = \false; } private function add_cert(\Google\Site_Kit_Dependencies\Psr\Http\Message\RequestInterface $request, &$options, $value, &$params) { if (\is_array($value)) { $options['ssl']['passphrase'] = $value[1]; $value = $value[0]; } if (!\file_exists($value)) { throw new \RuntimeException("SSL certificate not found: {$value}"); } $options['ssl']['local_cert'] = $value; } private function add_progress(\Google\Site_Kit_Dependencies\Psr\Http\Message\RequestInterface $request, &$options, $value, &$params) { $this->addNotification($params, function ($code, $a, $b, $c, $transferred, $total) use($value) { if ($code == \STREAM_NOTIFY_PROGRESS) { $value($total, $transferred, null, null); } }); } private function add_debug(\Google\Site_Kit_Dependencies\Psr\Http\Message\RequestInterface $request, &$options, $value, &$params) { if ($value === \false) { return; } static $map = [\STREAM_NOTIFY_CONNECT => 'CONNECT', \STREAM_NOTIFY_AUTH_REQUIRED => 'AUTH_REQUIRED', \STREAM_NOTIFY_AUTH_RESULT => 'AUTH_RESULT', \STREAM_NOTIFY_MIME_TYPE_IS => 'MIME_TYPE_IS', \STREAM_NOTIFY_FILE_SIZE_IS => 'FILE_SIZE_IS', \STREAM_NOTIFY_REDIRECTED => 'REDIRECTED', \STREAM_NOTIFY_PROGRESS => 'PROGRESS', \STREAM_NOTIFY_FAILURE => 'FAILURE', \STREAM_NOTIFY_COMPLETED => 'COMPLETED', \STREAM_NOTIFY_RESOLVE => 'RESOLVE']; static $args = ['severity', 'message', 'message_code', 'bytes_transferred', 'bytes_max']; $value = \Google\Site_Kit_Dependencies\GuzzleHttp\debug_resource($value); $ident = $request->getMethod() . ' ' . $request->getUri()->withFragment(''); $this->addNotification($params, function () use($ident, $value, $map, $args) { $passed = \func_get_args(); $code = \array_shift($passed); \fprintf($value, '<%s> [%s] ', $ident, $map[$code]); foreach (\array_filter($passed) as $i => $v) { \fwrite($value, $args[$i] . ': "' . $v . '" '); } \fwrite($value, "\n"); }); } private function addNotification(array &$params, callable $notify) { // Wrap the existing function if needed. if (!isset($params['notification'])) { $params['notification'] = $notify; } else { $params['notification'] = $this->callArray([$params['notification'], $notify]); } } private function callArray(array $functions) { return function () use($functions) { $args = \func_get_args(); foreach ($functions as $fn) { \call_user_func_array($fn, $args); } }; } } PK!s(^^-guzzlehttp/guzzle/src/Handler/MockHandler.phpnu[onFulfilled = $onFulfilled; $this->onRejected = $onRejected; if ($queue) { \call_user_func_array([$this, 'append'], $queue); } } public function __invoke(\Google\Site_Kit_Dependencies\Psr\Http\Message\RequestInterface $request, array $options) { if (!$this->queue) { throw new \OutOfBoundsException('Mock queue is empty'); } if (isset($options['delay']) && \is_numeric($options['delay'])) { \usleep($options['delay'] * 1000); } $this->lastRequest = $request; $this->lastOptions = $options; $response = \array_shift($this->queue); if (isset($options['on_headers'])) { if (!\is_callable($options['on_headers'])) { throw new \InvalidArgumentException('on_headers must be callable'); } try { $options['on_headers']($response); } catch (\Exception $e) { $msg = 'An error was encountered during the on_headers event'; $response = new \Google\Site_Kit_Dependencies\GuzzleHttp\Exception\RequestException($msg, $request, $response, $e); } } if (\is_callable($response)) { $response = \call_user_func($response, $request, $options); } $response = $response instanceof \Exception ? \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\rejection_for($response) : \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\promise_for($response); return $response->then(function ($value) use($request, $options) { $this->invokeStats($request, $options, $value); if ($this->onFulfilled) { \call_user_func($this->onFulfilled, $value); } if (isset($options['sink'])) { $contents = (string) $value->getBody(); $sink = $options['sink']; if (\is_resource($sink)) { \fwrite($sink, $contents); } elseif (\is_string($sink)) { \file_put_contents($sink, $contents); } elseif ($sink instanceof \Google\Site_Kit_Dependencies\Psr\Http\Message\StreamInterface) { $sink->write($contents); } } return $value; }, function ($reason) use($request, $options) { $this->invokeStats($request, $options, null, $reason); if ($this->onRejected) { \call_user_func($this->onRejected, $reason); } return \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\rejection_for($reason); }); } /** * Adds one or more variadic requests, exceptions, callables, or promises * to the queue. */ public function append() { foreach (\func_get_args() as $value) { if ($value instanceof \Google\Site_Kit_Dependencies\Psr\Http\Message\ResponseInterface || $value instanceof \Exception || $value instanceof \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\PromiseInterface || \is_callable($value)) { $this->queue[] = $value; } else { throw new \InvalidArgumentException('Expected a response or ' . 'exception. Found ' . \Google\Site_Kit_Dependencies\GuzzleHttp\describe_type($value)); } } } /** * Get the last received request. * * @return RequestInterface */ public function getLastRequest() { return $this->lastRequest; } /** * Get the last received request options. * * @return array */ public function getLastOptions() { return $this->lastOptions; } /** * Returns the number of remaining items in the queue. * * @return int */ public function count() { return \count($this->queue); } public function reset() { $this->queue = []; } private function invokeStats(\Google\Site_Kit_Dependencies\Psr\Http\Message\RequestInterface $request, array $options, \Google\Site_Kit_Dependencies\Psr\Http\Message\ResponseInterface $response = null, $reason = null) { if (isset($options['on_stats'])) { $transferTime = isset($options['transfer_time']) ? $options['transfer_time'] : 0; $stats = new \Google\Site_Kit_Dependencies\GuzzleHttp\TransferStats($request, $response, $transferTime, $reason); \call_user_func($options['on_stats'], $stats); } } } PK!{,S-guzzlehttp/guzzle/src/Handler/CurlHandler.phpnu[factory = isset($options['handle_factory']) ? $options['handle_factory'] : new \Google\Site_Kit_Dependencies\GuzzleHttp\Handler\CurlFactory(3); } public function __invoke(\Google\Site_Kit_Dependencies\Psr\Http\Message\RequestInterface $request, array $options) { if (isset($options['delay'])) { \usleep($options['delay'] * 1000); } $easy = $this->factory->create($request, $options); \curl_exec($easy->handle); $easy->errno = \curl_errno($easy->handle); return \Google\Site_Kit_Dependencies\GuzzleHttp\Handler\CurlFactory::finish($this, $easy, $this->factory); } } PK!992guzzlehttp/guzzle/src/Handler/CurlMultiHandler.phpnu[factory = isset($options['handle_factory']) ? $options['handle_factory'] : new \Google\Site_Kit_Dependencies\GuzzleHttp\Handler\CurlFactory(50); if (isset($options['select_timeout'])) { $this->selectTimeout = $options['select_timeout']; } elseif ($selectTimeout = \getenv('GUZZLE_CURL_SELECT_TIMEOUT')) { $this->selectTimeout = $selectTimeout; } else { $this->selectTimeout = 1; } $this->options = isset($options['options']) ? $options['options'] : []; } public function __get($name) { if ($name === '_mh') { $this->_mh = \curl_multi_init(); foreach ($this->options as $option => $value) { // A warning is raised in case of a wrong option. \curl_multi_setopt($this->_mh, $option, $value); } // Further calls to _mh will return the value directly, without entering the // __get() method at all. return $this->_mh; } throw new \BadMethodCallException(); } public function __destruct() { if (isset($this->_mh)) { \curl_multi_close($this->_mh); unset($this->_mh); } } public function __invoke(\Google\Site_Kit_Dependencies\Psr\Http\Message\RequestInterface $request, array $options) { $easy = $this->factory->create($request, $options); $id = (int) $easy->handle; $promise = new \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Promise([$this, 'execute'], function () use($id) { return $this->cancel($id); }); $this->addRequest(['easy' => $easy, 'deferred' => $promise]); return $promise; } /** * Ticks the curl event loop. */ public function tick() { // Add any delayed handles if needed. if ($this->delays) { $currentTime = \Google\Site_Kit_Dependencies\GuzzleHttp\Utils::currentTime(); foreach ($this->delays as $id => $delay) { if ($currentTime >= $delay) { unset($this->delays[$id]); \curl_multi_add_handle($this->_mh, $this->handles[$id]['easy']->handle); } } } // Step through the task queue which may add additional requests. \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\queue()->run(); if ($this->active && \curl_multi_select($this->_mh, $this->selectTimeout) === -1) { // Perform a usleep if a select returns -1. // See: https://bugs.php.net/bug.php?id=61141 \usleep(250); } while (\curl_multi_exec($this->_mh, $this->active) === \CURLM_CALL_MULTI_PERFORM) { } $this->processMessages(); } /** * Runs until all outstanding connections have completed. */ public function execute() { $queue = \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\queue(); while ($this->handles || !$queue->isEmpty()) { // If there are no transfers, then sleep for the next delay if (!$this->active && $this->delays) { \usleep($this->timeToNext()); } $this->tick(); } } private function addRequest(array $entry) { $easy = $entry['easy']; $id = (int) $easy->handle; $this->handles[$id] = $entry; if (empty($easy->options['delay'])) { \curl_multi_add_handle($this->_mh, $easy->handle); } else { $this->delays[$id] = \Google\Site_Kit_Dependencies\GuzzleHttp\Utils::currentTime() + $easy->options['delay'] / 1000; } } /** * Cancels a handle from sending and removes references to it. * * @param int $id Handle ID to cancel and remove. * * @return bool True on success, false on failure. */ private function cancel($id) { // Cannot cancel if it has been processed. if (!isset($this->handles[$id])) { return \false; } $handle = $this->handles[$id]['easy']->handle; unset($this->delays[$id], $this->handles[$id]); \curl_multi_remove_handle($this->_mh, $handle); \curl_close($handle); return \true; } private function processMessages() { while ($done = \curl_multi_info_read($this->_mh)) { $id = (int) $done['handle']; \curl_multi_remove_handle($this->_mh, $done['handle']); if (!isset($this->handles[$id])) { // Probably was cancelled. continue; } $entry = $this->handles[$id]; unset($this->handles[$id], $this->delays[$id]); $entry['easy']->errno = $done['result']; $entry['deferred']->resolve(\Google\Site_Kit_Dependencies\GuzzleHttp\Handler\CurlFactory::finish($this, $entry['easy'], $this->factory)); } } private function timeToNext() { $currentTime = \Google\Site_Kit_Dependencies\GuzzleHttp\Utils::currentTime(); $nextTime = \PHP_INT_MAX; foreach ($this->delays as $time) { if ($time < $nextTime) { $nextTime = $time; } } return \max(0, $nextTime - $currentTime) * 1000000; } } PK!C4ff'guzzlehttp/guzzle/src/Handler/Proxy.phpnu[stream = $stream; $msg = $msg ?: 'Could not seek the stream to position ' . $pos; parent::__construct($msg); } /** * @return StreamInterface */ public function getStream() { return $this->stream; } } PK!~"3guzzlehttp/guzzle/src/Exception/GuzzleException.phpnu[getStatusCode() : 0; parent::__construct($message, $code, $previous); $this->request = $request; $this->response = $response; $this->handlerContext = $handlerContext; } /** * Wrap non-RequestExceptions with a RequestException * * @param RequestInterface $request * @param \Exception $e * * @return RequestException */ public static function wrapException(\Google\Site_Kit_Dependencies\Psr\Http\Message\RequestInterface $request, \Exception $e) { return $e instanceof \Google\Site_Kit_Dependencies\GuzzleHttp\Exception\RequestException ? $e : new \Google\Site_Kit_Dependencies\GuzzleHttp\Exception\RequestException($e->getMessage(), $request, null, $e); } /** * Factory method to create a new exception with a normalized error message * * @param RequestInterface $request Request * @param ResponseInterface $response Response received * @param \Exception $previous Previous exception * @param array $ctx Optional handler context. * * @return self */ public static function create(\Google\Site_Kit_Dependencies\Psr\Http\Message\RequestInterface $request, \Google\Site_Kit_Dependencies\Psr\Http\Message\ResponseInterface $response = null, \Exception $previous = null, array $ctx = []) { if (!$response) { return new self('Error completing request', $request, null, $previous, $ctx); } $level = (int) \floor($response->getStatusCode() / 100); if ($level === 4) { $label = 'Client error'; $className = \Google\Site_Kit_Dependencies\GuzzleHttp\Exception\ClientException::class; } elseif ($level === 5) { $label = 'Server error'; $className = \Google\Site_Kit_Dependencies\GuzzleHttp\Exception\ServerException::class; } else { $label = 'Unsuccessful request'; $className = __CLASS__; } $uri = $request->getUri(); $uri = static::obfuscateUri($uri); // Client Error: `GET /` resulted in a `404 Not Found` response: // ... (truncated) $message = \sprintf('%s: `%s %s` resulted in a `%s %s` response', $label, $request->getMethod(), $uri, $response->getStatusCode(), $response->getReasonPhrase()); $summary = static::getResponseBodySummary($response); if ($summary !== null) { $message .= ":\n{$summary}\n"; } return new $className($message, $request, $response, $previous, $ctx); } /** * Get a short summary of the response * * Will return `null` if the response is not printable. * * @param ResponseInterface $response * * @return string|null */ public static function getResponseBodySummary(\Google\Site_Kit_Dependencies\Psr\Http\Message\ResponseInterface $response) { return \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\get_message_body_summary($response); } /** * Obfuscates URI if there is a username and a password present * * @param UriInterface $uri * * @return UriInterface */ private static function obfuscateUri(\Google\Site_Kit_Dependencies\Psr\Http\Message\UriInterface $uri) { $userInfo = $uri->getUserInfo(); if (\false !== ($pos = \strpos($userInfo, ':'))) { return $uri->withUserInfo(\substr($userInfo, 0, $pos), '***'); } return $uri; } /** * Get the request that caused the exception * * @return RequestInterface */ public function getRequest() { return $this->request; } /** * Get the associated response * * @return ResponseInterface|null */ public function getResponse() { return $this->response; } /** * Check if a response was received * * @return bool */ public function hasResponse() { return $this->response !== null; } /** * Get contextual information about the error from the underlying handler. * * The contents of this array will vary depending on which handler you are * using. It may also be just an empty array. Relying on this data will * couple you to a specific handler, but can give more debug information * when needed. * * @return array */ public function getHandlerContext() { return $this->handlerContext; } } PK!9+ε=guzzlehttp/guzzle/src/Exception/TooManyRedirectsException.phpnu[withCookieHeader($request); return $handler($request, $options)->then(function ($response) use($cookieJar, $request) { $cookieJar->extractCookies($request, $response); return $response; }); }; }; } /** * Middleware that throws exceptions for 4xx or 5xx responses when the * "http_error" request option is set to true. * * @return callable Returns a function that accepts the next handler. */ public static function httpErrors() { return function (callable $handler) { return function ($request, array $options) use($handler) { if (empty($options['http_errors'])) { return $handler($request, $options); } return $handler($request, $options)->then(function (\Google\Site_Kit_Dependencies\Psr\Http\Message\ResponseInterface $response) use($request) { $code = $response->getStatusCode(); if ($code < 400) { return $response; } throw \Google\Site_Kit_Dependencies\GuzzleHttp\Exception\RequestException::create($request, $response); }); }; }; } /** * Middleware that pushes history data to an ArrayAccess container. * * @param array|\ArrayAccess $container Container to hold the history (by reference). * * @return callable Returns a function that accepts the next handler. * @throws \InvalidArgumentException if container is not an array or ArrayAccess. */ public static function history(&$container) { if (!\is_array($container) && !$container instanceof \ArrayAccess) { throw new \InvalidArgumentException('history container must be an array or object implementing ArrayAccess'); } return function (callable $handler) use(&$container) { return function ($request, array $options) use($handler, &$container) { return $handler($request, $options)->then(function ($value) use($request, &$container, $options) { $container[] = ['request' => $request, 'response' => $value, 'error' => null, 'options' => $options]; return $value; }, function ($reason) use($request, &$container, $options) { $container[] = ['request' => $request, 'response' => null, 'error' => $reason, 'options' => $options]; return \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\rejection_for($reason); }); }; }; } /** * Middleware that invokes a callback before and after sending a request. * * The provided listener cannot modify or alter the response. It simply * "taps" into the chain to be notified before returning the promise. The * before listener accepts a request and options array, and the after * listener accepts a request, options array, and response promise. * * @param callable $before Function to invoke before forwarding the request. * @param callable $after Function invoked after forwarding. * * @return callable Returns a function that accepts the next handler. */ public static function tap(callable $before = null, callable $after = null) { return function (callable $handler) use($before, $after) { return function ($request, array $options) use($handler, $before, $after) { if ($before) { $before($request, $options); } $response = $handler($request, $options); if ($after) { $after($request, $options, $response); } return $response; }; }; } /** * Middleware that handles request redirects. * * @return callable Returns a function that accepts the next handler. */ public static function redirect() { return function (callable $handler) { return new \Google\Site_Kit_Dependencies\GuzzleHttp\RedirectMiddleware($handler); }; } /** * Middleware that retries requests based on the boolean result of * invoking the provided "decider" function. * * If no delay function is provided, a simple implementation of exponential * backoff will be utilized. * * @param callable $decider Function that accepts the number of retries, * a request, [response], and [exception] and * returns true if the request is to be retried. * @param callable $delay Function that accepts the number of retries and * returns the number of milliseconds to delay. * * @return callable Returns a function that accepts the next handler. */ public static function retry(callable $decider, callable $delay = null) { return function (callable $handler) use($decider, $delay) { return new \Google\Site_Kit_Dependencies\GuzzleHttp\RetryMiddleware($decider, $handler, $delay); }; } /** * Middleware that logs requests, responses, and errors using a message * formatter. * * @param LoggerInterface $logger Logs messages. * @param MessageFormatter $formatter Formatter used to create message strings. * @param string $logLevel Level at which to log requests. * * @return callable Returns a function that accepts the next handler. */ public static function log(\Google\Site_Kit_Dependencies\Psr\Log\LoggerInterface $logger, \Google\Site_Kit_Dependencies\GuzzleHttp\MessageFormatter $formatter, $logLevel = 'info') { return function (callable $handler) use($logger, $formatter, $logLevel) { return function ($request, array $options) use($handler, $logger, $formatter, $logLevel) { return $handler($request, $options)->then(function ($response) use($logger, $request, $formatter, $logLevel) { $message = $formatter->format($request, $response); $logger->log($logLevel, $message); return $response; }, function ($reason) use($logger, $request, $formatter) { $response = $reason instanceof \Google\Site_Kit_Dependencies\GuzzleHttp\Exception\RequestException ? $reason->getResponse() : null; $message = $formatter->format($request, $response, $reason); $logger->notice($message); return \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\rejection_for($reason); }); }; }; } /** * This middleware adds a default content-type if possible, a default * content-length or transfer-encoding header, and the expect header. * * @return callable */ public static function prepareBody() { return function (callable $handler) { return new \Google\Site_Kit_Dependencies\GuzzleHttp\PrepareBodyMiddleware($handler); }; } /** * Middleware that applies a map function to the request before passing to * the next handler. * * @param callable $fn Function that accepts a RequestInterface and returns * a RequestInterface. * @return callable */ public static function mapRequest(callable $fn) { return function (callable $handler) use($fn) { return function ($request, array $options) use($handler, $fn) { return $handler($fn($request), $options); }; }; } /** * Middleware that applies a map function to the resolved promise's * response. * * @param callable $fn Function that accepts a ResponseInterface and * returns a ResponseInterface. * @return callable */ public static function mapResponse(callable $fn) { return function (callable $handler) use($fn) { return function ($request, array $options) use($handler, $fn) { return $handler($request, $options)->then($fn); }; }; } } PK!+OO guzzlehttp/guzzle/src/Client.phpnu[ 'http://www.foo.com/1.0/', * 'timeout' => 0, * 'allow_redirects' => false, * 'proxy' => '192.168.16.1:10' * ]); * * Client configuration settings include the following options: * * - handler: (callable) Function that transfers HTTP requests over the * wire. The function is called with a Psr7\Http\Message\RequestInterface * and array of transfer options, and must return a * GuzzleHttp\Promise\PromiseInterface that is fulfilled with a * Psr7\Http\Message\ResponseInterface on success. * If no handler is provided, a default handler will be created * that enables all of the request options below by attaching all of the * default middleware to the handler. * - base_uri: (string|UriInterface) Base URI of the client that is merged * into relative URIs. Can be a string or instance of UriInterface. * - **: any request option * * @param array $config Client configuration settings. * * @see \GuzzleHttp\RequestOptions for a list of available request options. */ public function __construct(array $config = []) { if (!isset($config['handler'])) { $config['handler'] = \Google\Site_Kit_Dependencies\GuzzleHttp\HandlerStack::create(); } elseif (!\is_callable($config['handler'])) { throw new \InvalidArgumentException('handler must be a callable'); } // Convert the base_uri to a UriInterface if (isset($config['base_uri'])) { $config['base_uri'] = \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\uri_for($config['base_uri']); } $this->configureDefaults($config); } /** * @param string $method * @param array $args * * @return Promise\PromiseInterface */ public function __call($method, $args) { if (\count($args) < 1) { throw new \InvalidArgumentException('Magic request methods require a URI and optional options array'); } $uri = $args[0]; $opts = isset($args[1]) ? $args[1] : []; return \substr($method, -5) === 'Async' ? $this->requestAsync(\substr($method, 0, -5), $uri, $opts) : $this->request($method, $uri, $opts); } /** * Asynchronously send an HTTP request. * * @param array $options Request options to apply to the given * request and to the transfer. See \GuzzleHttp\RequestOptions. * * @return Promise\PromiseInterface */ public function sendAsync(\Google\Site_Kit_Dependencies\Psr\Http\Message\RequestInterface $request, array $options = []) { // Merge the base URI into the request URI if needed. $options = $this->prepareDefaults($options); return $this->transfer($request->withUri($this->buildUri($request->getUri(), $options), $request->hasHeader('Host')), $options); } /** * Send an HTTP request. * * @param array $options Request options to apply to the given * request and to the transfer. See \GuzzleHttp\RequestOptions. * * @return ResponseInterface * @throws GuzzleException */ public function send(\Google\Site_Kit_Dependencies\Psr\Http\Message\RequestInterface $request, array $options = []) { $options[\Google\Site_Kit_Dependencies\GuzzleHttp\RequestOptions::SYNCHRONOUS] = \true; return $this->sendAsync($request, $options)->wait(); } /** * Create and send an asynchronous HTTP request. * * Use an absolute path to override the base path of the client, or a * relative path to append to the base path of the client. The URL can * contain the query string as well. Use an array to provide a URL * template and additional variables to use in the URL template expansion. * * @param string $method HTTP method * @param string|UriInterface $uri URI object or string. * @param array $options Request options to apply. See \GuzzleHttp\RequestOptions. * * @return Promise\PromiseInterface */ public function requestAsync($method, $uri = '', array $options = []) { $options = $this->prepareDefaults($options); // Remove request modifying parameter because it can be done up-front. $headers = isset($options['headers']) ? $options['headers'] : []; $body = isset($options['body']) ? $options['body'] : null; $version = isset($options['version']) ? $options['version'] : '1.1'; // Merge the URI into the base URI. $uri = $this->buildUri($uri, $options); if (\is_array($body)) { $this->invalidBody(); } $request = new \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Request($method, $uri, $headers, $body, $version); // Remove the option so that they are not doubly-applied. unset($options['headers'], $options['body'], $options['version']); return $this->transfer($request, $options); } /** * Create and send an HTTP request. * * Use an absolute path to override the base path of the client, or a * relative path to append to the base path of the client. The URL can * contain the query string as well. * * @param string $method HTTP method. * @param string|UriInterface $uri URI object or string. * @param array $options Request options to apply. See \GuzzleHttp\RequestOptions. * * @return ResponseInterface * @throws GuzzleException */ public function request($method, $uri = '', array $options = []) { $options[\Google\Site_Kit_Dependencies\GuzzleHttp\RequestOptions::SYNCHRONOUS] = \true; return $this->requestAsync($method, $uri, $options)->wait(); } /** * Get a client configuration option. * * These options include default request options of the client, a "handler" * (if utilized by the concrete client), and a "base_uri" if utilized by * the concrete client. * * @param string|null $option The config option to retrieve. * * @return mixed */ public function getConfig($option = null) { return $option === null ? $this->config : (isset($this->config[$option]) ? $this->config[$option] : null); } /** * @param string|null $uri * * @return UriInterface */ private function buildUri($uri, array $config) { // for BC we accept null which would otherwise fail in uri_for $uri = \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\uri_for($uri === null ? '' : $uri); if (isset($config['base_uri'])) { $uri = \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\UriResolver::resolve(\Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\uri_for($config['base_uri']), $uri); } if (isset($config['idn_conversion']) && $config['idn_conversion'] !== \false) { $idnOptions = $config['idn_conversion'] === \true ? \IDNA_DEFAULT : $config['idn_conversion']; $uri = \Google\Site_Kit_Dependencies\GuzzleHttp\Utils::idnUriConvert($uri, $idnOptions); } return $uri->getScheme() === '' && $uri->getHost() !== '' ? $uri->withScheme('http') : $uri; } /** * Configures the default options for a client. * * @param array $config * @return void */ private function configureDefaults(array $config) { $defaults = ['allow_redirects' => \Google\Site_Kit_Dependencies\GuzzleHttp\RedirectMiddleware::$defaultSettings, 'http_errors' => \true, 'decode_content' => \true, 'verify' => \true, 'cookies' => \false, 'idn_conversion' => \true]; // Use the standard Linux HTTP_PROXY and HTTPS_PROXY if set. // We can only trust the HTTP_PROXY environment variable in a CLI // process due to the fact that PHP has no reliable mechanism to // get environment variables that start with "HTTP_". if (\php_sapi_name() === 'cli' && \getenv('HTTP_PROXY')) { $defaults['proxy']['http'] = \getenv('HTTP_PROXY'); } if ($proxy = \getenv('HTTPS_PROXY')) { $defaults['proxy']['https'] = $proxy; } if ($noProxy = \getenv('NO_PROXY')) { $cleanedNoProxy = \str_replace(' ', '', $noProxy); $defaults['proxy']['no'] = \explode(',', $cleanedNoProxy); } $this->config = $config + $defaults; if (!empty($config['cookies']) && $config['cookies'] === \true) { $this->config['cookies'] = new \Google\Site_Kit_Dependencies\GuzzleHttp\Cookie\CookieJar(); } // Add the default user-agent header. if (!isset($this->config['headers'])) { $this->config['headers'] = ['User-Agent' => default_user_agent()]; } else { // Add the User-Agent header if one was not already set. foreach (\array_keys($this->config['headers']) as $name) { if (\strtolower($name) === 'user-agent') { return; } } $this->config['headers']['User-Agent'] = default_user_agent(); } } /** * Merges default options into the array. * * @param array $options Options to modify by reference * * @return array */ private function prepareDefaults(array $options) { $defaults = $this->config; if (!empty($defaults['headers'])) { // Default headers are only added if they are not present. $defaults['_conditional'] = $defaults['headers']; unset($defaults['headers']); } // Special handling for headers is required as they are added as // conditional headers and as headers passed to a request ctor. if (\array_key_exists('headers', $options)) { // Allows default headers to be unset. if ($options['headers'] === null) { $defaults['_conditional'] = []; unset($options['headers']); } elseif (!\is_array($options['headers'])) { throw new \InvalidArgumentException('headers must be an array'); } } // Shallow merge defaults underneath options. $result = $options + $defaults; // Remove null values. foreach ($result as $k => $v) { if ($v === null) { unset($result[$k]); } } return $result; } /** * Transfers the given request and applies request options. * * The URI of the request is not modified and the request options are used * as-is without merging in default options. * * @param array $options See \GuzzleHttp\RequestOptions. * * @return Promise\PromiseInterface */ private function transfer(\Google\Site_Kit_Dependencies\Psr\Http\Message\RequestInterface $request, array $options) { // save_to -> sink if (isset($options['save_to'])) { $options['sink'] = $options['save_to']; unset($options['save_to']); } // exceptions -> http_errors if (isset($options['exceptions'])) { $options['http_errors'] = $options['exceptions']; unset($options['exceptions']); } $request = $this->applyOptions($request, $options); /** @var HandlerStack $handler */ $handler = $options['handler']; try { return \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\promise_for($handler($request, $options)); } catch (\Exception $e) { return \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\rejection_for($e); } } /** * Applies the array of request options to a request. * * @param RequestInterface $request * @param array $options * * @return RequestInterface */ private function applyOptions(\Google\Site_Kit_Dependencies\Psr\Http\Message\RequestInterface $request, array &$options) { $modify = ['set_headers' => []]; if (isset($options['headers'])) { $modify['set_headers'] = $options['headers']; unset($options['headers']); } if (isset($options['form_params'])) { if (isset($options['multipart'])) { throw new \InvalidArgumentException('You cannot use ' . 'form_params and multipart at the same time. Use the ' . 'form_params option if you want to send application/' . 'x-www-form-urlencoded requests, and the multipart ' . 'option to send multipart/form-data requests.'); } $options['body'] = \http_build_query($options['form_params'], '', '&'); unset($options['form_params']); // Ensure that we don't have the header in different case and set the new value. $options['_conditional'] = \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\_caseless_remove(['Content-Type'], $options['_conditional']); $options['_conditional']['Content-Type'] = 'application/x-www-form-urlencoded'; } if (isset($options['multipart'])) { $options['body'] = new \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\MultipartStream($options['multipart']); unset($options['multipart']); } if (isset($options['json'])) { $options['body'] = \Google\Site_Kit_Dependencies\GuzzleHttp\json_encode($options['json']); unset($options['json']); // Ensure that we don't have the header in different case and set the new value. $options['_conditional'] = \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\_caseless_remove(['Content-Type'], $options['_conditional']); $options['_conditional']['Content-Type'] = 'application/json'; } if (!empty($options['decode_content']) && $options['decode_content'] !== \true) { // Ensure that we don't have the header in different case and set the new value. $options['_conditional'] = \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\_caseless_remove(['Accept-Encoding'], $options['_conditional']); $modify['set_headers']['Accept-Encoding'] = $options['decode_content']; } if (isset($options['body'])) { if (\is_array($options['body'])) { $this->invalidBody(); } $modify['body'] = \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\stream_for($options['body']); unset($options['body']); } if (!empty($options['auth']) && \is_array($options['auth'])) { $value = $options['auth']; $type = isset($value[2]) ? \strtolower($value[2]) : 'basic'; switch ($type) { case 'basic': // Ensure that we don't have the header in different case and set the new value. $modify['set_headers'] = \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\_caseless_remove(['Authorization'], $modify['set_headers']); $modify['set_headers']['Authorization'] = 'Basic ' . \base64_encode("{$value[0]}:{$value[1]}"); break; case 'digest': // @todo: Do not rely on curl $options['curl'][\CURLOPT_HTTPAUTH] = \CURLAUTH_DIGEST; $options['curl'][\CURLOPT_USERPWD] = "{$value[0]}:{$value[1]}"; break; case 'ntlm': $options['curl'][\CURLOPT_HTTPAUTH] = \CURLAUTH_NTLM; $options['curl'][\CURLOPT_USERPWD] = "{$value[0]}:{$value[1]}"; break; } } if (isset($options['query'])) { $value = $options['query']; if (\is_array($value)) { $value = \http_build_query($value, null, '&', \PHP_QUERY_RFC3986); } if (!\is_string($value)) { throw new \InvalidArgumentException('query must be a string or array'); } $modify['query'] = $value; unset($options['query']); } // Ensure that sink is not an invalid value. if (isset($options['sink'])) { // TODO: Add more sink validation? if (\is_bool($options['sink'])) { throw new \InvalidArgumentException('sink must not be a boolean'); } } $request = \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\modify_request($request, $modify); if ($request->getBody() instanceof \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\MultipartStream) { // Use a multipart/form-data POST if a Content-Type is not set. // Ensure that we don't have the header in different case and set the new value. $options['_conditional'] = \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\_caseless_remove(['Content-Type'], $options['_conditional']); $options['_conditional']['Content-Type'] = 'multipart/form-data; boundary=' . $request->getBody()->getBoundary(); } // Merge in conditional headers if they are not present. if (isset($options['_conditional'])) { // Build up the changes so it's in a single clone of the message. $modify = []; foreach ($options['_conditional'] as $k => $v) { if (!$request->hasHeader($k)) { $modify['set_headers'][$k] = $v; } } $request = \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\modify_request($request, $modify); // Don't pass this internal value along to middleware/handlers. unset($options['_conditional']); } return $request; } /** * Throw Exception with pre-set message. * @return void * @throws \InvalidArgumentException Invalid body. */ private function invalidBody() { throw new \InvalidArgumentException('Passing in the "body" request ' . 'option as an array to send a POST request has been deprecated. ' . 'Please use the "form_params" request option to send a ' . 'application/x-www-form-urlencoded request, or the "multipart" ' . 'request option to send a multipart/form-data request.'); } } PK!9guzzlehttp/guzzle/Dockerfilenu[FROM composer:latest as setup RUN mkdir /guzzle WORKDIR /guzzle RUN set -xe \ && composer init --name=guzzlehttp/test --description="Simple project for testing Guzzle scripts" --author="Márk Sági-Kazár " --no-interaction \ && composer require guzzlehttp/guzzle FROM php:7.3 RUN mkdir /guzzle WORKDIR /guzzle COPY --from=setup /guzzle /guzzle PK!5xzz$guzzlehttp/psr7/src/UploadedFile.phpnu[setError($errorStatus); $this->setSize($size); $this->setClientFilename($clientFilename); $this->setClientMediaType($clientMediaType); if ($this->isOk()) { $this->setStreamOrFile($streamOrFile); } } /** * Depending on the value set file or stream variable * * @param mixed $streamOrFile * * @throws InvalidArgumentException */ private function setStreamOrFile($streamOrFile) { if (\is_string($streamOrFile)) { $this->file = $streamOrFile; } elseif (\is_resource($streamOrFile)) { $this->stream = new \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Stream($streamOrFile); } elseif ($streamOrFile instanceof \Google\Site_Kit_Dependencies\Psr\Http\Message\StreamInterface) { $this->stream = $streamOrFile; } else { throw new \InvalidArgumentException('Invalid stream or file provided for UploadedFile'); } } /** * @param int $error * * @throws InvalidArgumentException */ private function setError($error) { if (\false === \is_int($error)) { throw new \InvalidArgumentException('Upload file error status must be an integer'); } if (\false === \in_array($error, \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\UploadedFile::$errors)) { throw new \InvalidArgumentException('Invalid error status for UploadedFile'); } $this->error = $error; } /** * @param int $size * * @throws InvalidArgumentException */ private function setSize($size) { if (\false === \is_int($size)) { throw new \InvalidArgumentException('Upload file size must be an integer'); } $this->size = $size; } /** * @param mixed $param * * @return bool */ private function isStringOrNull($param) { return \in_array(\gettype($param), ['string', 'NULL']); } /** * @param mixed $param * * @return bool */ private function isStringNotEmpty($param) { return \is_string($param) && \false === empty($param); } /** * @param string|null $clientFilename * * @throws InvalidArgumentException */ private function setClientFilename($clientFilename) { if (\false === $this->isStringOrNull($clientFilename)) { throw new \InvalidArgumentException('Upload file client filename must be a string or null'); } $this->clientFilename = $clientFilename; } /** * @param string|null $clientMediaType * * @throws InvalidArgumentException */ private function setClientMediaType($clientMediaType) { if (\false === $this->isStringOrNull($clientMediaType)) { throw new \InvalidArgumentException('Upload file client media type must be a string or null'); } $this->clientMediaType = $clientMediaType; } /** * Return true if there is no upload error * * @return bool */ private function isOk() { return $this->error === \UPLOAD_ERR_OK; } /** * @return bool */ public function isMoved() { return $this->moved; } /** * @throws RuntimeException if is moved or not ok */ private function validateActive() { if (\false === $this->isOk()) { throw new \RuntimeException('Cannot retrieve stream due to upload error'); } if ($this->isMoved()) { throw new \RuntimeException('Cannot retrieve stream after it has already been moved'); } } /** * {@inheritdoc} * * @throws RuntimeException if the upload was not successful. */ public function getStream() { $this->validateActive(); if ($this->stream instanceof \Google\Site_Kit_Dependencies\Psr\Http\Message\StreamInterface) { return $this->stream; } return new \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\LazyOpenStream($this->file, 'r+'); } /** * {@inheritdoc} * * @see http://php.net/is_uploaded_file * @see http://php.net/move_uploaded_file * * @param string $targetPath Path to which to move the uploaded file. * * @throws RuntimeException if the upload was not successful. * @throws InvalidArgumentException if the $path specified is invalid. * @throws RuntimeException on any error during the move operation, or on * the second or subsequent call to the method. */ public function moveTo($targetPath) { $this->validateActive(); if (\false === $this->isStringNotEmpty($targetPath)) { throw new \InvalidArgumentException('Invalid path provided for move operation; must be a non-empty string'); } if ($this->file) { $this->moved = \php_sapi_name() == 'cli' ? \rename($this->file, $targetPath) : \move_uploaded_file($this->file, $targetPath); } else { \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Utils::copyToStream($this->getStream(), new \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\LazyOpenStream($targetPath, 'w')); $this->moved = \true; } if (\false === $this->moved) { throw new \RuntimeException(\sprintf('Uploaded file could not be moved to %s', $targetPath)); } } /** * {@inheritdoc} * * @return int|null The file size in bytes or null if unknown. */ public function getSize() { return $this->size; } /** * {@inheritdoc} * * @see http://php.net/manual/en/features.file-upload.errors.php * * @return int One of PHP's UPLOAD_ERR_XXX constants. */ public function getError() { return $this->error; } /** * {@inheritdoc} * * @return string|null The filename sent by the client or null if none * was provided. */ public function getClientFilename() { return $this->clientFilename; } /** * {@inheritdoc} */ public function getClientMediaType() { return $this->clientMediaType; } } PK!E$guzzlehttp/psr7/src/MessageTrait.phpnu[ array of values */ private $headers = []; /** @var array Map of lowercase header name => original name at registration */ private $headerNames = []; /** @var string */ private $protocol = '1.1'; /** @var StreamInterface|null */ private $stream; public function getProtocolVersion() { return $this->protocol; } public function withProtocolVersion($version) { if ($this->protocol === $version) { return $this; } $new = clone $this; $new->protocol = $version; return $new; } public function getHeaders() { return $this->headers; } public function hasHeader($header) { return isset($this->headerNames[\strtolower($header)]); } public function getHeader($header) { $header = \strtolower($header); if (!isset($this->headerNames[$header])) { return []; } $header = $this->headerNames[$header]; return $this->headers[$header]; } public function getHeaderLine($header) { return \implode(', ', $this->getHeader($header)); } public function withHeader($header, $value) { $this->assertHeader($header); $value = $this->normalizeHeaderValue($value); $normalized = \strtolower($header); $new = clone $this; if (isset($new->headerNames[$normalized])) { unset($new->headers[$new->headerNames[$normalized]]); } $new->headerNames[$normalized] = $header; $new->headers[$header] = $value; return $new; } public function withAddedHeader($header, $value) { $this->assertHeader($header); $value = $this->normalizeHeaderValue($value); $normalized = \strtolower($header); $new = clone $this; if (isset($new->headerNames[$normalized])) { $header = $this->headerNames[$normalized]; $new->headers[$header] = \array_merge($this->headers[$header], $value); } else { $new->headerNames[$normalized] = $header; $new->headers[$header] = $value; } return $new; } public function withoutHeader($header) { $normalized = \strtolower($header); if (!isset($this->headerNames[$normalized])) { return $this; } $header = $this->headerNames[$normalized]; $new = clone $this; unset($new->headers[$header], $new->headerNames[$normalized]); return $new; } public function getBody() { if (!$this->stream) { $this->stream = \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Utils::streamFor(''); } return $this->stream; } public function withBody(\Google\Site_Kit_Dependencies\Psr\Http\Message\StreamInterface $body) { if ($body === $this->stream) { return $this; } $new = clone $this; $new->stream = $body; return $new; } private function setHeaders(array $headers) { $this->headerNames = $this->headers = []; foreach ($headers as $header => $value) { if (\is_int($header)) { // Numeric array keys are converted to int by PHP but having a header name '123' is not forbidden by the spec // and also allowed in withHeader(). So we need to cast it to string again for the following assertion to pass. $header = (string) $header; } $this->assertHeader($header); $value = $this->normalizeHeaderValue($value); $normalized = \strtolower($header); if (isset($this->headerNames[$normalized])) { $header = $this->headerNames[$normalized]; $this->headers[$header] = \array_merge($this->headers[$header], $value); } else { $this->headerNames[$normalized] = $header; $this->headers[$header] = $value; } } } /** * @param mixed $value * * @return string[] */ private function normalizeHeaderValue($value) { if (!\is_array($value)) { return $this->trimAndValidateHeaderValues([$value]); } if (\count($value) === 0) { throw new \InvalidArgumentException('Header value can not be an empty array.'); } return $this->trimAndValidateHeaderValues($value); } /** * Trims whitespace from the header values. * * Spaces and tabs ought to be excluded by parsers when extracting the field value from a header field. * * header-field = field-name ":" OWS field-value OWS * OWS = *( SP / HTAB ) * * @param mixed[] $values Header values * * @return string[] Trimmed header values * * @see https://tools.ietf.org/html/rfc7230#section-3.2.4 */ private function trimAndValidateHeaderValues(array $values) { return \array_map(function ($value) { if (!\is_scalar($value) && null !== $value) { throw new \InvalidArgumentException(\sprintf('Header value must be scalar or null but %s provided.', \is_object($value) ? \get_class($value) : \gettype($value))); } $trimmed = \trim((string) $value, " \t"); $this->assertValue($trimmed); return $trimmed; }, \array_values($values)); } /** * @see https://tools.ietf.org/html/rfc7230#section-3.2 * * @param mixed $header * * @return void */ private function assertHeader($header) { if (!\is_string($header)) { throw new \InvalidArgumentException(\sprintf('Header name must be a string but %s provided.', \is_object($header) ? \get_class($header) : \gettype($header))); } if ($header === '') { throw new \InvalidArgumentException('Header name can not be empty.'); } if (!\preg_match('/^[a-zA-Z0-9\'`#$%&*+.^_|~!-]+$/D', $header)) { throw new \InvalidArgumentException(\sprintf('"%s" is not valid header name.', $header)); } } /** * @param string $value * * @return void * * @see https://tools.ietf.org/html/rfc7230#section-3.2 * * field-value = *( field-content / obs-fold ) * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] * field-vchar = VCHAR / obs-text * VCHAR = %x21-7E * obs-text = %x80-FF * obs-fold = CRLF 1*( SP / HTAB ) */ private function assertValue($value) { // The regular expression intentionally does not support the obs-fold production, because as // per RFC 7230#3.2.4: // // A sender MUST NOT generate a message that includes // line folding (i.e., that has any field-value that contains a match to // the obs-fold rule) unless the message is intended for packaging // within the message/http media type. // // Clients must not send a request with line folding and a server sending folded headers is // likely very rare. Line folding is a fairly obscure feature of HTTP/1.1 and thus not accepting // folding is not likely to break any legitimate use case. if (!\preg_match('/^[\\x20\\x09\\x21-\\x7E\\x80-\\xFF]*$/D', $value)) { throw new \InvalidArgumentException(\sprintf('"%s" is not valid header value.', $value)); } } } PK! Bguzzlehttp/psr7/src/Rfc7230.phpnu[@,;:\\\"/[\\]?={}\1- ]++):[ \t]*+((?:[ \t]*+[!-~-]++)*+)[ \t]*+\r?\n)m"; const HEADER_FOLD_REGEX = "(\r?\n[ \t]++)"; } PK!!pp guzzlehttp/psr7/src/Response.phpnu[ 'Continue', 101 => 'Switching Protocols', 102 => 'Processing', 200 => 'OK', 201 => 'Created', 202 => 'Accepted', 203 => 'Non-Authoritative Information', 204 => 'No Content', 205 => 'Reset Content', 206 => 'Partial Content', 207 => 'Multi-status', 208 => 'Already Reported', 300 => 'Multiple Choices', 301 => 'Moved Permanently', 302 => 'Found', 303 => 'See Other', 304 => 'Not Modified', 305 => 'Use Proxy', 306 => 'Switch Proxy', 307 => 'Temporary Redirect', 400 => 'Bad Request', 401 => 'Unauthorized', 402 => 'Payment Required', 403 => 'Forbidden', 404 => 'Not Found', 405 => 'Method Not Allowed', 406 => 'Not Acceptable', 407 => 'Proxy Authentication Required', 408 => 'Request Time-out', 409 => 'Conflict', 410 => 'Gone', 411 => 'Length Required', 412 => 'Precondition Failed', 413 => 'Request Entity Too Large', 414 => 'Request-URI Too Large', 415 => 'Unsupported Media Type', 416 => 'Requested range not satisfiable', 417 => 'Expectation Failed', 418 => 'I\'m a teapot', 422 => 'Unprocessable Entity', 423 => 'Locked', 424 => 'Failed Dependency', 425 => 'Unordered Collection', 426 => 'Upgrade Required', 428 => 'Precondition Required', 429 => 'Too Many Requests', 431 => 'Request Header Fields Too Large', 451 => 'Unavailable For Legal Reasons', 500 => 'Internal Server Error', 501 => 'Not Implemented', 502 => 'Bad Gateway', 503 => 'Service Unavailable', 504 => 'Gateway Time-out', 505 => 'HTTP Version not supported', 506 => 'Variant Also Negotiates', 507 => 'Insufficient Storage', 508 => 'Loop Detected', 511 => 'Network Authentication Required']; /** @var string */ private $reasonPhrase = ''; /** @var int */ private $statusCode = 200; /** * @param int $status Status code * @param array $headers Response headers * @param string|resource|StreamInterface|null $body Response body * @param string $version Protocol version * @param string|null $reason Reason phrase (when empty a default will be used based on the status code) */ public function __construct($status = 200, array $headers = [], $body = null, $version = '1.1', $reason = null) { $this->assertStatusCodeIsInteger($status); $status = (int) $status; $this->assertStatusCodeRange($status); $this->statusCode = $status; if ($body !== '' && $body !== null) { $this->stream = \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Utils::streamFor($body); } $this->setHeaders($headers); if ($reason == '' && isset(self::$phrases[$this->statusCode])) { $this->reasonPhrase = self::$phrases[$this->statusCode]; } else { $this->reasonPhrase = (string) $reason; } $this->protocol = $version; } public function getStatusCode() { return $this->statusCode; } public function getReasonPhrase() { return $this->reasonPhrase; } public function withStatus($code, $reasonPhrase = '') { $this->assertStatusCodeIsInteger($code); $code = (int) $code; $this->assertStatusCodeRange($code); $new = clone $this; $new->statusCode = $code; if ($reasonPhrase == '' && isset(self::$phrases[$new->statusCode])) { $reasonPhrase = self::$phrases[$new->statusCode]; } $new->reasonPhrase = (string) $reasonPhrase; return $new; } private function assertStatusCodeIsInteger($statusCode) { if (\filter_var($statusCode, \FILTER_VALIDATE_INT) === \false) { throw new \InvalidArgumentException('Status code must be an integer value.'); } } private function assertStatusCodeRange($statusCode) { if ($statusCode < 100 || $statusCode >= 600) { throw new \InvalidArgumentException('Status code must be an integer value between 1xx and 5xx.'); } } } PK!9-methods = $methods; // Create the functions on the class foreach ($methods as $name => $fn) { $this->{'_fn_' . $name} = $fn; } } /** * Lazily determine which methods are not implemented. * * @throws \BadMethodCallException */ public function __get($name) { throw new \BadMethodCallException(\str_replace('_fn_', '', $name) . '() is not implemented in the FnStream'); } /** * The close method is called on the underlying stream only if possible. */ public function __destruct() { if (isset($this->_fn_close)) { \call_user_func($this->_fn_close); } } /** * An unserialize would allow the __destruct to run when the unserialized value goes out of scope. * * @throws \LogicException */ public function __wakeup() { throw new \LogicException('FnStream should never be unserialized'); } /** * Adds custom functionality to an underlying stream by intercepting * specific method calls. * * @param StreamInterface $stream Stream to decorate * @param array $methods Hash of method name to a closure * * @return FnStream */ public static function decorate(\Google\Site_Kit_Dependencies\Psr\Http\Message\StreamInterface $stream, array $methods) { // If any of the required methods were not provided, then simply // proxy to the decorated stream. foreach (\array_diff(self::$slots, \array_keys($methods)) as $diff) { $methods[$diff] = [$stream, $diff]; } return new self($methods); } public function __toString() { return \call_user_func($this->_fn___toString); } public function close() { return \call_user_func($this->_fn_close); } public function detach() { return \call_user_func($this->_fn_detach); } public function getSize() { return \call_user_func($this->_fn_getSize); } public function tell() { return \call_user_func($this->_fn_tell); } public function eof() { return \call_user_func($this->_fn_eof); } public function isSeekable() { return \call_user_func($this->_fn_isSeekable); } public function rewind() { \call_user_func($this->_fn_rewind); } public function seek($offset, $whence = \SEEK_SET) { \call_user_func($this->_fn_seek, $offset, $whence); } public function isWritable() { return \call_user_func($this->_fn_isWritable); } public function write($string) { return \call_user_func($this->_fn_write, $string); } public function isReadable() { return \call_user_func($this->_fn_isReadable); } public function read($length) { return \call_user_func($this->_fn_read, $length); } public function getContents() { return \call_user_func($this->_fn_getContents); } public function getMetadata($key = null) { return \call_user_func($this->_fn_getMetadata, $key); } } PK!N d d $guzzlehttp/psr7/src/BufferStream.phpnu[hwm = $hwm; } public function __toString() { return $this->getContents(); } public function getContents() { $buffer = $this->buffer; $this->buffer = ''; return $buffer; } public function close() { $this->buffer = ''; } public function detach() { $this->close(); return null; } public function getSize() { return \strlen($this->buffer); } public function isReadable() { return \true; } public function isWritable() { return \true; } public function isSeekable() { return \false; } public function rewind() { $this->seek(0); } public function seek($offset, $whence = \SEEK_SET) { throw new \RuntimeException('Cannot seek a BufferStream'); } public function eof() { return \strlen($this->buffer) === 0; } public function tell() { throw new \RuntimeException('Cannot determine the position of a BufferStream'); } /** * Reads data from the buffer. */ public function read($length) { $currentLength = \strlen($this->buffer); if ($length >= $currentLength) { // No need to slice the buffer because we don't have enough data. $result = $this->buffer; $this->buffer = ''; } else { // Slice up the result to provide a subset of the buffer. $result = \substr($this->buffer, 0, $length); $this->buffer = \substr($this->buffer, $length); } return $result; } /** * Writes data to the buffer. */ public function write($string) { $this->buffer .= $string; // TODO: What should happen here? if (\strlen($this->buffer) >= $this->hwm) { return \false; } return \strlen($string); } public function getMetadata($key = null) { if ($key == 'hwm') { return $this->hwm; } return $key ? null : []; } } PK!*wЈguzzlehttp/psr7/src/Request.phpnu[assertMethod($method); if (!$uri instanceof \Google\Site_Kit_Dependencies\Psr\Http\Message\UriInterface) { $uri = new \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Uri($uri); } $this->method = \strtoupper($method); $this->uri = $uri; $this->setHeaders($headers); $this->protocol = $version; if (!isset($this->headerNames['host'])) { $this->updateHostFromUri(); } if ($body !== '' && $body !== null) { $this->stream = \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Utils::streamFor($body); } } public function getRequestTarget() { if ($this->requestTarget !== null) { return $this->requestTarget; } $target = $this->uri->getPath(); if ($target == '') { $target = '/'; } if ($this->uri->getQuery() != '') { $target .= '?' . $this->uri->getQuery(); } return $target; } public function withRequestTarget($requestTarget) { if (\preg_match('#\\s#', $requestTarget)) { throw new \InvalidArgumentException('Invalid request target provided; cannot contain whitespace'); } $new = clone $this; $new->requestTarget = $requestTarget; return $new; } public function getMethod() { return $this->method; } public function withMethod($method) { $this->assertMethod($method); $new = clone $this; $new->method = \strtoupper($method); return $new; } public function getUri() { return $this->uri; } public function withUri(\Google\Site_Kit_Dependencies\Psr\Http\Message\UriInterface $uri, $preserveHost = \false) { if ($uri === $this->uri) { return $this; } $new = clone $this; $new->uri = $uri; if (!$preserveHost || !isset($this->headerNames['host'])) { $new->updateHostFromUri(); } return $new; } private function updateHostFromUri() { $host = $this->uri->getHost(); if ($host == '') { return; } if (($port = $this->uri->getPort()) !== null) { $host .= ':' . $port; } if (isset($this->headerNames['host'])) { $header = $this->headerNames['host']; } else { $header = 'Host'; $this->headerNames['host'] = 'Host'; } // Ensure Host is the first header. // See: http://tools.ietf.org/html/rfc7230#section-5.4 $this->headers = [$header => [$host]] + $this->headers; } private function assertMethod($method) { if (!\is_string($method) || $method === '') { throw new \InvalidArgumentException('Method must be a non-empty string.'); } } } PK!|s33 guzzlehttp/psr7/src/MimeType.phpnu[ 'video/3gpp', '7z' => 'application/x-7z-compressed', 'aac' => 'audio/x-aac', 'ai' => 'application/postscript', 'aif' => 'audio/x-aiff', 'asc' => 'text/plain', 'asf' => 'video/x-ms-asf', 'atom' => 'application/atom+xml', 'avi' => 'video/x-msvideo', 'bmp' => 'image/bmp', 'bz2' => 'application/x-bzip2', 'cer' => 'application/pkix-cert', 'crl' => 'application/pkix-crl', 'crt' => 'application/x-x509-ca-cert', 'css' => 'text/css', 'csv' => 'text/csv', 'cu' => 'application/cu-seeme', 'deb' => 'application/x-debian-package', 'doc' => 'application/msword', 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'dvi' => 'application/x-dvi', 'eot' => 'application/vnd.ms-fontobject', 'eps' => 'application/postscript', 'epub' => 'application/epub+zip', 'etx' => 'text/x-setext', 'flac' => 'audio/flac', 'flv' => 'video/x-flv', 'gif' => 'image/gif', 'gz' => 'application/gzip', 'htm' => 'text/html', 'html' => 'text/html', 'ico' => 'image/x-icon', 'ics' => 'text/calendar', 'ini' => 'text/plain', 'iso' => 'application/x-iso9660-image', 'jar' => 'application/java-archive', 'jpe' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'jpg' => 'image/jpeg', 'js' => 'text/javascript', 'json' => 'application/json', 'latex' => 'application/x-latex', 'log' => 'text/plain', 'm4a' => 'audio/mp4', 'm4v' => 'video/mp4', 'mid' => 'audio/midi', 'midi' => 'audio/midi', 'mov' => 'video/quicktime', 'mkv' => 'video/x-matroska', 'mp3' => 'audio/mpeg', 'mp4' => 'video/mp4', 'mp4a' => 'audio/mp4', 'mp4v' => 'video/mp4', 'mpe' => 'video/mpeg', 'mpeg' => 'video/mpeg', 'mpg' => 'video/mpeg', 'mpg4' => 'video/mp4', 'oga' => 'audio/ogg', 'ogg' => 'audio/ogg', 'ogv' => 'video/ogg', 'ogx' => 'application/ogg', 'pbm' => 'image/x-portable-bitmap', 'pdf' => 'application/pdf', 'pgm' => 'image/x-portable-graymap', 'png' => 'image/png', 'pnm' => 'image/x-portable-anymap', 'ppm' => 'image/x-portable-pixmap', 'ppt' => 'application/vnd.ms-powerpoint', 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'ps' => 'application/postscript', 'qt' => 'video/quicktime', 'rar' => 'application/x-rar-compressed', 'ras' => 'image/x-cmu-raster', 'rss' => 'application/rss+xml', 'rtf' => 'application/rtf', 'sgm' => 'text/sgml', 'sgml' => 'text/sgml', 'svg' => 'image/svg+xml', 'swf' => 'application/x-shockwave-flash', 'tar' => 'application/x-tar', 'tif' => 'image/tiff', 'tiff' => 'image/tiff', 'torrent' => 'application/x-bittorrent', 'ttf' => 'application/x-font-ttf', 'txt' => 'text/plain', 'wav' => 'audio/x-wav', 'webm' => 'video/webm', 'webp' => 'image/webp', 'wma' => 'audio/x-ms-wma', 'wmv' => 'video/x-ms-wmv', 'woff' => 'application/x-font-woff', 'wsdl' => 'application/wsdl+xml', 'xbm' => 'image/x-xbitmap', 'xls' => 'application/vnd.ms-excel', 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'xml' => 'application/xml', 'xpm' => 'image/x-xpixmap', 'xwd' => 'image/x-xwindowdump', 'yaml' => 'text/yaml', 'yml' => 'text/yaml', 'zip' => 'application/zip']; $extension = \strtolower($extension); return isset($mimetypes[$extension]) ? $mimetypes[$extension] : null; } } PK!7伣%guzzlehttp/psr7/src/CachingStream.phpnu[remoteStream = $stream; $this->stream = $target ?: new \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Stream(\Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Utils::tryFopen('php://temp', 'r+')); } public function getSize() { $remoteSize = $this->remoteStream->getSize(); if (null === $remoteSize) { return null; } return \max($this->stream->getSize(), $remoteSize); } public function rewind() { $this->seek(0); } public function seek($offset, $whence = \SEEK_SET) { if ($whence == \SEEK_SET) { $byte = $offset; } elseif ($whence == \SEEK_CUR) { $byte = $offset + $this->tell(); } elseif ($whence == \SEEK_END) { $size = $this->remoteStream->getSize(); if ($size === null) { $size = $this->cacheEntireStream(); } $byte = $size + $offset; } else { throw new \InvalidArgumentException('Invalid whence'); } $diff = $byte - $this->stream->getSize(); if ($diff > 0) { // Read the remoteStream until we have read in at least the amount // of bytes requested, or we reach the end of the file. while ($diff > 0 && !$this->remoteStream->eof()) { $this->read($diff); $diff = $byte - $this->stream->getSize(); } } else { // We can just do a normal seek since we've already seen this byte. $this->stream->seek($byte); } } public function read($length) { // Perform a regular read on any previously read data from the buffer $data = $this->stream->read($length); $remaining = $length - \strlen($data); // More data was requested so read from the remote stream if ($remaining) { // If data was written to the buffer in a position that would have // been filled from the remote stream, then we must skip bytes on // the remote stream to emulate overwriting bytes from that // position. This mimics the behavior of other PHP stream wrappers. $remoteData = $this->remoteStream->read($remaining + $this->skipReadBytes); if ($this->skipReadBytes) { $len = \strlen($remoteData); $remoteData = \substr($remoteData, $this->skipReadBytes); $this->skipReadBytes = \max(0, $this->skipReadBytes - $len); } $data .= $remoteData; $this->stream->write($remoteData); } return $data; } public function write($string) { // When appending to the end of the currently read stream, you'll want // to skip bytes from being read from the remote stream to emulate // other stream wrappers. Basically replacing bytes of data of a fixed // length. $overflow = \strlen($string) + $this->tell() - $this->remoteStream->tell(); if ($overflow > 0) { $this->skipReadBytes += $overflow; } return $this->stream->write($string); } public function eof() { return $this->stream->eof() && $this->remoteStream->eof(); } /** * Close both the remote stream and buffer stream */ public function close() { $this->remoteStream->close() && $this->stream->close(); } private function cacheEntireStream() { $target = new \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\FnStream(['write' => 'strlen']); \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Utils::copyToStream($this, $target); return $this->tell(); } } PK!Au5D'D'%guzzlehttp/psr7/src/ServerRequest.phpnu[serverParams = $serverParams; parent::__construct($method, $uri, $headers, $body, $version); } /** * Return an UploadedFile instance array. * * @param array $files A array which respect $_FILES structure * * @return array * * @throws InvalidArgumentException for unrecognized values */ public static function normalizeFiles(array $files) { $normalized = []; foreach ($files as $key => $value) { if ($value instanceof \Google\Site_Kit_Dependencies\Psr\Http\Message\UploadedFileInterface) { $normalized[$key] = $value; } elseif (\is_array($value) && isset($value['tmp_name'])) { $normalized[$key] = self::createUploadedFileFromSpec($value); } elseif (\is_array($value)) { $normalized[$key] = self::normalizeFiles($value); continue; } else { throw new \InvalidArgumentException('Invalid value in files specification'); } } return $normalized; } /** * Create and return an UploadedFile instance from a $_FILES specification. * * If the specification represents an array of values, this method will * delegate to normalizeNestedFileSpec() and return that return value. * * @param array $value $_FILES struct * * @return array|UploadedFileInterface */ private static function createUploadedFileFromSpec(array $value) { if (\is_array($value['tmp_name'])) { return self::normalizeNestedFileSpec($value); } return new \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\UploadedFile($value['tmp_name'], (int) $value['size'], (int) $value['error'], $value['name'], $value['type']); } /** * Normalize an array of file specifications. * * Loops through all nested files and returns a normalized array of * UploadedFileInterface instances. * * @param array $files * * @return UploadedFileInterface[] */ private static function normalizeNestedFileSpec(array $files = []) { $normalizedFiles = []; foreach (\array_keys($files['tmp_name']) as $key) { $spec = ['tmp_name' => $files['tmp_name'][$key], 'size' => $files['size'][$key], 'error' => $files['error'][$key], 'name' => $files['name'][$key], 'type' => $files['type'][$key]]; $normalizedFiles[$key] = self::createUploadedFileFromSpec($spec); } return $normalizedFiles; } /** * Return a ServerRequest populated with superglobals: * $_GET * $_POST * $_COOKIE * $_FILES * $_SERVER * * @return ServerRequestInterface */ public static function fromGlobals() { $method = isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : 'GET'; $headers = \getallheaders(); $uri = self::getUriFromGlobals(); $body = new \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\CachingStream(new \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\LazyOpenStream('php://input', 'r+')); $protocol = isset($_SERVER['SERVER_PROTOCOL']) ? \str_replace('HTTP/', '', $_SERVER['SERVER_PROTOCOL']) : '1.1'; $serverRequest = new \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\ServerRequest($method, $uri, $headers, $body, $protocol, $_SERVER); return $serverRequest->withCookieParams($_COOKIE)->withQueryParams($_GET)->withParsedBody($_POST)->withUploadedFiles(self::normalizeFiles($_FILES)); } private static function extractHostAndPortFromAuthority($authority) { $uri = 'http://' . $authority; $parts = \parse_url($uri); if (\false === $parts) { return [null, null]; } $host = isset($parts['host']) ? $parts['host'] : null; $port = isset($parts['port']) ? $parts['port'] : null; return [$host, $port]; } /** * Get a Uri populated with values from $_SERVER. * * @return UriInterface */ public static function getUriFromGlobals() { $uri = new \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Uri(''); $uri = $uri->withScheme(!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' ? 'https' : 'http'); $hasPort = \false; if (isset($_SERVER['HTTP_HOST'])) { list($host, $port) = self::extractHostAndPortFromAuthority($_SERVER['HTTP_HOST']); if ($host !== null) { $uri = $uri->withHost($host); } if ($port !== null) { $hasPort = \true; $uri = $uri->withPort($port); } } elseif (isset($_SERVER['SERVER_NAME'])) { $uri = $uri->withHost($_SERVER['SERVER_NAME']); } elseif (isset($_SERVER['SERVER_ADDR'])) { $uri = $uri->withHost($_SERVER['SERVER_ADDR']); } if (!$hasPort && isset($_SERVER['SERVER_PORT'])) { $uri = $uri->withPort($_SERVER['SERVER_PORT']); } $hasQuery = \false; if (isset($_SERVER['REQUEST_URI'])) { $requestUriParts = \explode('?', $_SERVER['REQUEST_URI'], 2); $uri = $uri->withPath($requestUriParts[0]); if (isset($requestUriParts[1])) { $hasQuery = \true; $uri = $uri->withQuery($requestUriParts[1]); } } if (!$hasQuery && isset($_SERVER['QUERY_STRING'])) { $uri = $uri->withQuery($_SERVER['QUERY_STRING']); } return $uri; } /** * {@inheritdoc} */ public function getServerParams() { return $this->serverParams; } /** * {@inheritdoc} */ public function getUploadedFiles() { return $this->uploadedFiles; } /** * {@inheritdoc} */ public function withUploadedFiles(array $uploadedFiles) { $new = clone $this; $new->uploadedFiles = $uploadedFiles; return $new; } /** * {@inheritdoc} */ public function getCookieParams() { return $this->cookieParams; } /** * {@inheritdoc} */ public function withCookieParams(array $cookies) { $new = clone $this; $new->cookieParams = $cookies; return $new; } /** * {@inheritdoc} */ public function getQueryParams() { return $this->queryParams; } /** * {@inheritdoc} */ public function withQueryParams(array $query) { $new = clone $this; $new->queryParams = $query; return $new; } /** * {@inheritdoc} */ public function getParsedBody() { return $this->parsedBody; } /** * {@inheritdoc} */ public function withParsedBody($data) { $new = clone $this; $new->parsedBody = $data; return $new; } /** * {@inheritdoc} */ public function getAttributes() { return $this->attributes; } /** * {@inheritdoc} */ public function getAttribute($attribute, $default = null) { if (\false === \array_key_exists($attribute, $this->attributes)) { return $default; } return $this->attributes[$attribute]; } /** * {@inheritdoc} */ public function withAttribute($attribute, $value) { $new = clone $this; $new->attributes[$attribute] = $value; return $new; } /** * {@inheritdoc} */ public function withoutAttribute($attribute) { if (\false === \array_key_exists($attribute, $this->attributes)) { return $this; } $new = clone $this; unset($new->attributes[$attribute]); return $new; } } PK!)JK"guzzlehttp/psr7/src/PumpStream.phpnu[source = $source; $this->size = isset($options['size']) ? $options['size'] : null; $this->metadata = isset($options['metadata']) ? $options['metadata'] : []; $this->buffer = new \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\BufferStream(); } public function __toString() { try { return \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Utils::copyToString($this); } catch (\Exception $e) { return ''; } } public function close() { $this->detach(); } public function detach() { $this->tellPos = \false; $this->source = null; return null; } public function getSize() { return $this->size; } public function tell() { return $this->tellPos; } public function eof() { return !$this->source; } public function isSeekable() { return \false; } public function rewind() { $this->seek(0); } public function seek($offset, $whence = \SEEK_SET) { throw new \RuntimeException('Cannot seek a PumpStream'); } public function isWritable() { return \false; } public function write($string) { throw new \RuntimeException('Cannot write to a PumpStream'); } public function isReadable() { return \true; } public function read($length) { $data = $this->buffer->read($length); $readLen = \strlen($data); $this->tellPos += $readLen; $remaining = $length - $readLen; if ($remaining) { $this->pump($remaining); $data .= $this->buffer->read($remaining); $this->tellPos += \strlen($data) - $readLen; } return $data; } public function getContents() { $result = ''; while (!$this->eof()) { $result .= $this->read(1000000); } return $result; } public function getMetadata($key = null) { if (!$key) { return $this->metadata; } return isset($this->metadata[$key]) ? $this->metadata[$key] : null; } private function pump($length) { if ($this->source) { do { $data = \call_user_func($this->source, $length); if ($data === \false || $data === null) { $this->source = null; return; } $this->buffer->write($data); $length -= \strlen($data); } while ($length > 0); } } } PK!V guzzlehttp/psr7/src/Query.phpnu[ '1', 'foo[b]' => '2'])`. * * @param string $str Query string to parse * @param int|bool $urlEncoding How the query string is encoded * * @return array */ public static function parse($str, $urlEncoding = \true) { $result = []; if ($str === '') { return $result; } if ($urlEncoding === \true) { $decoder = function ($value) { return \rawurldecode(\str_replace('+', ' ', $value)); }; } elseif ($urlEncoding === \PHP_QUERY_RFC3986) { $decoder = 'rawurldecode'; } elseif ($urlEncoding === \PHP_QUERY_RFC1738) { $decoder = 'urldecode'; } else { $decoder = function ($str) { return $str; }; } foreach (\explode('&', $str) as $kvp) { $parts = \explode('=', $kvp, 2); $key = $decoder($parts[0]); $value = isset($parts[1]) ? $decoder($parts[1]) : null; if (!isset($result[$key])) { $result[$key] = $value; } else { if (!\is_array($result[$key])) { $result[$key] = [$result[$key]]; } $result[$key][] = $value; } } return $result; } /** * Build a query string from an array of key value pairs. * * This function can use the return value of `parse()` to build a query * string. This function does not modify the provided keys when an array is * encountered (like `http_build_query()` would). * * @param array $params Query string parameters. * @param int|false $encoding Set to false to not encode, PHP_QUERY_RFC3986 * to encode using RFC3986, or PHP_QUERY_RFC1738 * to encode using RFC1738. * * @return string */ public static function build(array $params, $encoding = \PHP_QUERY_RFC3986) { if (!$params) { return ''; } if ($encoding === \false) { $encoder = function ($str) { return $str; }; } elseif ($encoding === \PHP_QUERY_RFC3986) { $encoder = 'rawurlencode'; } elseif ($encoding === \PHP_QUERY_RFC1738) { $encoder = 'urlencode'; } else { throw new \InvalidArgumentException('Invalid type'); } $qs = ''; foreach ($params as $k => $v) { $k = $encoder($k); if (!\is_array($v)) { $qs .= $k; if ($v !== null) { $qs .= '=' . $encoder($v); } $qs .= '&'; } else { foreach ($v as $vv) { $qs .= $k; if ($vv !== null) { $qs .= '=' . $encoder($vv); } $qs .= '&'; } } } return $qs ? (string) \substr($qs, 0, -1) : ''; } } PK!&guzzlehttp/psr7/src/DroppingStream.phpnu[stream = $stream; $this->maxLength = $maxLength; } public function write($string) { $diff = $this->maxLength - $this->stream->getSize(); // Begin returning 0 when the underlying stream is too large. if ($diff <= 0) { return 0; } // Write the stream or a subset of the stream if needed. if (\strlen($string) < $diff) { return $this->stream->write($string); } return $this->stream->write(\substr($string, 0, $diff)); } } PK!z:z:!guzzlehttp/psr7/src/functions.phpnu[ '1', 'foo[b]' => '2'])`. * * @param string $str Query string to parse * @param int|bool $urlEncoding How the query string is encoded * * @return array * * @deprecated parse_query will be removed in guzzlehttp/psr7:2.0. Use Query::parse instead. */ function parse_query($str, $urlEncoding = \true) { return \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Query::parse($str, $urlEncoding); } /** * Build a query string from an array of key value pairs. * * This function can use the return value of `parse_query()` to build a query * string. This function does not modify the provided keys when an array is * encountered (like `http_build_query()` would). * * @param array $params Query string parameters. * @param int|false $encoding Set to false to not encode, PHP_QUERY_RFC3986 * to encode using RFC3986, or PHP_QUERY_RFC1738 * to encode using RFC1738. * * @return string * * @deprecated build_query will be removed in guzzlehttp/psr7:2.0. Use Query::build instead. */ function build_query(array $params, $encoding = \PHP_QUERY_RFC3986) { return \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Query::build($params, $encoding); } /** * Determines the mimetype of a file by looking at its extension. * * @param string $filename * * @return string|null * * @deprecated mimetype_from_filename will be removed in guzzlehttp/psr7:2.0. Use MimeType::fromFilename instead. */ function mimetype_from_filename($filename) { return \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\MimeType::fromFilename($filename); } /** * Maps a file extensions to a mimetype. * * @param $extension string The file extension. * * @return string|null * * @link http://svn.apache.org/repos/asf/httpd/httpd/branches/1.3.x/conf/mime.types * @deprecated mimetype_from_extension will be removed in guzzlehttp/psr7:2.0. Use MimeType::fromExtension instead. */ function mimetype_from_extension($extension) { return \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\MimeType::fromExtension($extension); } /** * Parses an HTTP message into an associative array. * * The array contains the "start-line" key containing the start line of * the message, "headers" key containing an associative array of header * array values, and a "body" key containing the body of the message. * * @param string $message HTTP request or response to parse. * * @return array * * @internal * * @deprecated _parse_message will be removed in guzzlehttp/psr7:2.0. Use Message::parseMessage instead. */ function _parse_message($message) { return \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Message::parseMessage($message); } /** * Constructs a URI for an HTTP request message. * * @param string $path Path from the start-line * @param array $headers Array of headers (each value an array). * * @return string * * @internal * * @deprecated _parse_request_uri will be removed in guzzlehttp/psr7:2.0. Use Message::parseRequestUri instead. */ function _parse_request_uri($path, array $headers) { return \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Message::parseRequestUri($path, $headers); } /** * Get a short summary of the message body. * * Will return `null` if the response is not printable. * * @param MessageInterface $message The message to get the body summary * @param int $truncateAt The maximum allowed size of the summary * * @return string|null * * @deprecated get_message_body_summary will be removed in guzzlehttp/psr7:2.0. Use Message::bodySummary instead. */ function get_message_body_summary(\Google\Site_Kit_Dependencies\Psr\Http\Message\MessageInterface $message, $truncateAt = 120) { return \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Message::bodySummary($message, $truncateAt); } /** * Remove the items given by the keys, case insensitively from the data. * * @param iterable $keys * * @return array * * @internal * * @deprecated _caseless_remove will be removed in guzzlehttp/psr7:2.0. Use Utils::caselessRemove instead. */ function _caseless_remove($keys, array $data) { return \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Utils::caselessRemove($keys, $data); } PK!ql'guzzlehttp/psr7/src/MultipartStream.phpnu[boundary = $boundary ?: \sha1(\uniqid('', \true)); $this->stream = $this->createStream($elements); } /** * Get the boundary * * @return string */ public function getBoundary() { return $this->boundary; } public function isWritable() { return \false; } /** * Get the headers needed before transferring the content of a POST file */ private function getHeaders(array $headers) { $str = ''; foreach ($headers as $key => $value) { $str .= "{$key}: {$value}\r\n"; } return "--{$this->boundary}\r\n" . \trim($str) . "\r\n\r\n"; } /** * Create the aggregate stream that will be used to upload the POST data */ protected function createStream(array $elements) { $stream = new \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\AppendStream(); foreach ($elements as $element) { $this->addElement($stream, $element); } // Add the trailing boundary with CRLF $stream->addStream(\Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Utils::streamFor("--{$this->boundary}--\r\n")); return $stream; } private function addElement(\Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\AppendStream $stream, array $element) { foreach (['contents', 'name'] as $key) { if (!\array_key_exists($key, $element)) { throw new \InvalidArgumentException("A '{$key}' key is required"); } } $element['contents'] = \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Utils::streamFor($element['contents']); if (empty($element['filename'])) { $uri = $element['contents']->getMetadata('uri'); if (\substr($uri, 0, 6) !== 'php://') { $element['filename'] = $uri; } } list($body, $headers) = $this->createElement($element['name'], $element['contents'], isset($element['filename']) ? $element['filename'] : null, isset($element['headers']) ? $element['headers'] : []); $stream->addStream(\Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Utils::streamFor($this->getHeaders($headers))); $stream->addStream($body); $stream->addStream(\Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Utils::streamFor("\r\n")); } /** * @return array */ private function createElement($name, \Google\Site_Kit_Dependencies\Psr\Http\Message\StreamInterface $stream, $filename, array $headers) { // Set a default content-disposition header if one was no provided $disposition = $this->getHeader($headers, 'content-disposition'); if (!$disposition) { $headers['Content-Disposition'] = $filename === '0' || $filename ? \sprintf('form-data; name="%s"; filename="%s"', $name, \basename($filename)) : "form-data; name=\"{$name}\""; } // Set a default content-length header if one was no provided $length = $this->getHeader($headers, 'content-length'); if (!$length) { if ($length = $stream->getSize()) { $headers['Content-Length'] = (string) $length; } } // Set a default Content-Type if one was not supplied $type = $this->getHeader($headers, 'content-type'); if (!$type && ($filename === '0' || $filename)) { if ($type = \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\MimeType::fromFilename($filename)) { $headers['Content-Type'] = $type; } } return [$stream, $headers]; } private function getHeader(array $headers, $key) { $lowercaseHeader = \strtolower($key); foreach ($headers as $k => $v) { if (\strtolower($k) === $lowercaseHeader) { return $v; } } return null; } } PK!C0M;M;guzzlehttp/psr7/src/Utils.phpnu[ $keys * * @return array */ public static function caselessRemove($keys, array $data) { $result = []; foreach ($keys as &$key) { $key = \strtolower($key); } foreach ($data as $k => $v) { if (!\in_array(\strtolower($k), $keys)) { $result[$k] = $v; } } return $result; } /** * Copy the contents of a stream into another stream until the given number * of bytes have been read. * * @param StreamInterface $source Stream to read from * @param StreamInterface $dest Stream to write to * @param int $maxLen Maximum number of bytes to read. Pass -1 * to read the entire stream. * * @throws \RuntimeException on error. */ public static function copyToStream(\Google\Site_Kit_Dependencies\Psr\Http\Message\StreamInterface $source, \Google\Site_Kit_Dependencies\Psr\Http\Message\StreamInterface $dest, $maxLen = -1) { $bufferSize = 8192; if ($maxLen === -1) { while (!$source->eof()) { if (!$dest->write($source->read($bufferSize))) { break; } } } else { $remaining = $maxLen; while ($remaining > 0 && !$source->eof()) { $buf = $source->read(\min($bufferSize, $remaining)); $len = \strlen($buf); if (!$len) { break; } $remaining -= $len; $dest->write($buf); } } } /** * Copy the contents of a stream into a string until the given number of * bytes have been read. * * @param StreamInterface $stream Stream to read * @param int $maxLen Maximum number of bytes to read. Pass -1 * to read the entire stream. * * @return string * * @throws \RuntimeException on error. */ public static function copyToString(\Google\Site_Kit_Dependencies\Psr\Http\Message\StreamInterface $stream, $maxLen = -1) { $buffer = ''; if ($maxLen === -1) { while (!$stream->eof()) { $buf = $stream->read(1048576); // Using a loose equality here to match on '' and false. if ($buf == null) { break; } $buffer .= $buf; } return $buffer; } $len = 0; while (!$stream->eof() && $len < $maxLen) { $buf = $stream->read($maxLen - $len); // Using a loose equality here to match on '' and false. if ($buf == null) { break; } $buffer .= $buf; $len = \strlen($buffer); } return $buffer; } /** * Calculate a hash of a stream. * * This method reads the entire stream to calculate a rolling hash, based * on PHP's `hash_init` functions. * * @param StreamInterface $stream Stream to calculate the hash for * @param string $algo Hash algorithm (e.g. md5, crc32, etc) * @param bool $rawOutput Whether or not to use raw output * * @return string Returns the hash of the stream * * @throws \RuntimeException on error. */ public static function hash(\Google\Site_Kit_Dependencies\Psr\Http\Message\StreamInterface $stream, $algo, $rawOutput = \false) { $pos = $stream->tell(); if ($pos > 0) { $stream->rewind(); } $ctx = \hash_init($algo); while (!$stream->eof()) { \hash_update($ctx, $stream->read(1048576)); } $out = \hash_final($ctx, (bool) $rawOutput); $stream->seek($pos); return $out; } /** * Clone and modify a request with the given changes. * * This method is useful for reducing the number of clones needed to mutate * a message. * * The changes can be one of: * - method: (string) Changes the HTTP method. * - set_headers: (array) Sets the given headers. * - remove_headers: (array) Remove the given headers. * - body: (mixed) Sets the given body. * - uri: (UriInterface) Set the URI. * - query: (string) Set the query string value of the URI. * - version: (string) Set the protocol version. * * @param RequestInterface $request Request to clone and modify. * @param array $changes Changes to apply. * * @return RequestInterface */ public static function modifyRequest(\Google\Site_Kit_Dependencies\Psr\Http\Message\RequestInterface $request, array $changes) { if (!$changes) { return $request; } $headers = $request->getHeaders(); if (!isset($changes['uri'])) { $uri = $request->getUri(); } else { // Remove the host header if one is on the URI if ($host = $changes['uri']->getHost()) { $changes['set_headers']['Host'] = $host; if ($port = $changes['uri']->getPort()) { $standardPorts = ['http' => 80, 'https' => 443]; $scheme = $changes['uri']->getScheme(); if (isset($standardPorts[$scheme]) && $port != $standardPorts[$scheme]) { $changes['set_headers']['Host'] .= ':' . $port; } } } $uri = $changes['uri']; } if (!empty($changes['remove_headers'])) { $headers = self::caselessRemove($changes['remove_headers'], $headers); } if (!empty($changes['set_headers'])) { $headers = self::caselessRemove(\array_keys($changes['set_headers']), $headers); $headers = $changes['set_headers'] + $headers; } if (isset($changes['query'])) { $uri = $uri->withQuery($changes['query']); } if ($request instanceof \Google\Site_Kit_Dependencies\Psr\Http\Message\ServerRequestInterface) { $new = (new \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\ServerRequest(isset($changes['method']) ? $changes['method'] : $request->getMethod(), $uri, $headers, isset($changes['body']) ? $changes['body'] : $request->getBody(), isset($changes['version']) ? $changes['version'] : $request->getProtocolVersion(), $request->getServerParams()))->withParsedBody($request->getParsedBody())->withQueryParams($request->getQueryParams())->withCookieParams($request->getCookieParams())->withUploadedFiles($request->getUploadedFiles()); foreach ($request->getAttributes() as $key => $value) { $new = $new->withAttribute($key, $value); } return $new; } return new \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Request(isset($changes['method']) ? $changes['method'] : $request->getMethod(), $uri, $headers, isset($changes['body']) ? $changes['body'] : $request->getBody(), isset($changes['version']) ? $changes['version'] : $request->getProtocolVersion()); } /** * Read a line from the stream up to the maximum allowed buffer length. * * @param StreamInterface $stream Stream to read from * @param int|null $maxLength Maximum buffer length * * @return string */ public static function readLine(\Google\Site_Kit_Dependencies\Psr\Http\Message\StreamInterface $stream, $maxLength = null) { $buffer = ''; $size = 0; while (!$stream->eof()) { // Using a loose equality here to match on '' and false. if (null == ($byte = $stream->read(1))) { return $buffer; } $buffer .= $byte; // Break when a new line is found or the max length - 1 is reached if ($byte === "\n" || ++$size === $maxLength - 1) { break; } } return $buffer; } /** * Create a new stream based on the input type. * * Options is an associative array that can contain the following keys: * - metadata: Array of custom metadata. * - size: Size of the stream. * * This method accepts the following `$resource` types: * - `Psr\Http\Message\StreamInterface`: Returns the value as-is. * - `string`: Creates a stream object that uses the given string as the contents. * - `resource`: Creates a stream object that wraps the given PHP stream resource. * - `Iterator`: If the provided value implements `Iterator`, then a read-only * stream object will be created that wraps the given iterable. Each time the * stream is read from, data from the iterator will fill a buffer and will be * continuously called until the buffer is equal to the requested read size. * Subsequent read calls will first read from the buffer and then call `next` * on the underlying iterator until it is exhausted. * - `object` with `__toString()`: If the object has the `__toString()` method, * the object will be cast to a string and then a stream will be returned that * uses the string value. * - `NULL`: When `null` is passed, an empty stream object is returned. * - `callable` When a callable is passed, a read-only stream object will be * created that invokes the given callable. The callable is invoked with the * number of suggested bytes to read. The callable can return any number of * bytes, but MUST return `false` when there is no more data to return. The * stream object that wraps the callable will invoke the callable until the * number of requested bytes are available. Any additional bytes will be * buffered and used in subsequent reads. * * @param resource|string|int|float|bool|StreamInterface|callable|\Iterator|null $resource Entity body data * @param array $options Additional options * * @return StreamInterface * * @throws \InvalidArgumentException if the $resource arg is not valid. */ public static function streamFor($resource = '', array $options = []) { if (\is_scalar($resource)) { $stream = self::tryFopen('php://temp', 'r+'); if ($resource !== '') { \fwrite($stream, $resource); \fseek($stream, 0); } return new \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Stream($stream, $options); } switch (\gettype($resource)) { case 'resource': /* * The 'php://input' is a special stream with quirks and inconsistencies. * We avoid using that stream by reading it into php://temp */ $metaData = \stream_get_meta_data($resource); if (isset($metaData['uri']) && $metaData['uri'] === 'php://input') { $stream = self::tryFopen('php://temp', 'w+'); \fwrite($stream, \stream_get_contents($resource)); \fseek($stream, 0); $resource = $stream; } return new \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Stream($resource, $options); case 'object': if ($resource instanceof \Google\Site_Kit_Dependencies\Psr\Http\Message\StreamInterface) { return $resource; } elseif ($resource instanceof \Iterator) { return new \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\PumpStream(function () use($resource) { if (!$resource->valid()) { return \false; } $result = $resource->current(); $resource->next(); return $result; }, $options); } elseif (\method_exists($resource, '__toString')) { return \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Utils::streamFor((string) $resource, $options); } break; case 'NULL': return new \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Stream(self::tryFopen('php://temp', 'r+'), $options); } if (\is_callable($resource)) { return new \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\PumpStream($resource, $options); } throw new \InvalidArgumentException('Invalid resource type: ' . \gettype($resource)); } /** * Safely opens a PHP stream resource using a filename. * * When fopen fails, PHP normally raises a warning. This function adds an * error handler that checks for errors and throws an exception instead. * * @param string $filename File to open * @param string $mode Mode used to open the file * * @return resource * * @throws \RuntimeException if the file cannot be opened */ public static function tryFopen($filename, $mode) { $ex = null; \set_error_handler(function () use($filename, $mode, &$ex) { $ex = new \RuntimeException(\sprintf('Unable to open "%s" using mode "%s": %s', $filename, $mode, \func_get_args()[1])); return \true; }); try { $handle = \fopen($filename, $mode); } catch (\Throwable $e) { $ex = new \RuntimeException(\sprintf('Unable to open "%s" using mode "%s": %s', $filename, $mode, $e->getMessage()), 0, $e); } \restore_error_handler(); if ($ex) { /** @var $ex \RuntimeException */ throw $ex; } return $handle; } /** * Returns a UriInterface for the given value. * * This function accepts a string or UriInterface and returns a * UriInterface for the given value. If the value is already a * UriInterface, it is returned as-is. * * @param string|UriInterface $uri * * @return UriInterface * * @throws \InvalidArgumentException */ public static function uriFor($uri) { if ($uri instanceof \Google\Site_Kit_Dependencies\Psr\Http\Message\UriInterface) { return $uri; } if (\is_string($uri)) { return new \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Uri($uri); } throw new \InvalidArgumentException('URI must be a string or UriInterface'); } } PK!  $guzzlehttp/psr7/src/AppendStream.phpnu[addStream($stream); } } public function __toString() { try { $this->rewind(); return $this->getContents(); } catch (\Exception $e) { return ''; } } /** * Add a stream to the AppendStream * * @param StreamInterface $stream Stream to append. Must be readable. * * @throws \InvalidArgumentException if the stream is not readable */ public function addStream(\Google\Site_Kit_Dependencies\Psr\Http\Message\StreamInterface $stream) { if (!$stream->isReadable()) { throw new \InvalidArgumentException('Each stream must be readable'); } // The stream is only seekable if all streams are seekable if (!$stream->isSeekable()) { $this->seekable = \false; } $this->streams[] = $stream; } public function getContents() { return \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Utils::copyToString($this); } /** * Closes each attached stream. * * {@inheritdoc} */ public function close() { $this->pos = $this->current = 0; $this->seekable = \true; foreach ($this->streams as $stream) { $stream->close(); } $this->streams = []; } /** * Detaches each attached stream. * * Returns null as it's not clear which underlying stream resource to return. * * {@inheritdoc} */ public function detach() { $this->pos = $this->current = 0; $this->seekable = \true; foreach ($this->streams as $stream) { $stream->detach(); } $this->streams = []; return null; } public function tell() { return $this->pos; } /** * Tries to calculate the size by adding the size of each stream. * * If any of the streams do not return a valid number, then the size of the * append stream cannot be determined and null is returned. * * {@inheritdoc} */ public function getSize() { $size = 0; foreach ($this->streams as $stream) { $s = $stream->getSize(); if ($s === null) { return null; } $size += $s; } return $size; } public function eof() { return !$this->streams || $this->current >= \count($this->streams) - 1 && $this->streams[$this->current]->eof(); } public function rewind() { $this->seek(0); } /** * Attempts to seek to the given position. Only supports SEEK_SET. * * {@inheritdoc} */ public function seek($offset, $whence = \SEEK_SET) { if (!$this->seekable) { throw new \RuntimeException('This AppendStream is not seekable'); } elseif ($whence !== \SEEK_SET) { throw new \RuntimeException('The AppendStream can only seek with SEEK_SET'); } $this->pos = $this->current = 0; // Rewind each stream foreach ($this->streams as $i => $stream) { try { $stream->rewind(); } catch (\Exception $e) { throw new \RuntimeException('Unable to seek stream ' . $i . ' of the AppendStream', 0, $e); } } // Seek to the actual position by reading from each stream while ($this->pos < $offset && !$this->eof()) { $result = $this->read(\min(8096, $offset - $this->pos)); if ($result === '') { break; } } } /** * Reads from all of the appended streams until the length is met or EOF. * * {@inheritdoc} */ public function read($length) { $buffer = ''; $total = \count($this->streams) - 1; $remaining = $length; $progressToNext = \false; while ($remaining > 0) { // Progress to the next stream if needed. if ($progressToNext || $this->streams[$this->current]->eof()) { $progressToNext = \false; if ($this->current === $total) { break; } $this->current++; } $result = $this->streams[$this->current]->read($remaining); // Using a loose comparison here to match on '', false, and null if ($result == null) { $progressToNext = \true; continue; } $buffer .= $result; $remaining = $length - \strlen($buffer); } $this->pos += \strlen($buffer); return $buffer; } public function isReadable() { return \true; } public function isWritable() { return \false; } public function isSeekable() { return $this->seekable; } public function write($string) { throw new \RuntimeException('Cannot write to an AppendStream'); } public function getMetadata($key = null) { return $key ? null : []; } } PK!###guzzlehttp/psr7/src/UriResolver.phpnu[getScheme() != '') { return $rel->withPath(self::removeDotSegments($rel->getPath())); } if ($rel->getAuthority() != '') { $targetAuthority = $rel->getAuthority(); $targetPath = self::removeDotSegments($rel->getPath()); $targetQuery = $rel->getQuery(); } else { $targetAuthority = $base->getAuthority(); if ($rel->getPath() === '') { $targetPath = $base->getPath(); $targetQuery = $rel->getQuery() != '' ? $rel->getQuery() : $base->getQuery(); } else { if ($rel->getPath()[0] === '/') { $targetPath = $rel->getPath(); } else { if ($targetAuthority != '' && $base->getPath() === '') { $targetPath = '/' . $rel->getPath(); } else { $lastSlashPos = \strrpos($base->getPath(), '/'); if ($lastSlashPos === \false) { $targetPath = $rel->getPath(); } else { $targetPath = \substr($base->getPath(), 0, $lastSlashPos + 1) . $rel->getPath(); } } } $targetPath = self::removeDotSegments($targetPath); $targetQuery = $rel->getQuery(); } } return new \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Uri(\Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Uri::composeComponents($base->getScheme(), $targetAuthority, $targetPath, $targetQuery, $rel->getFragment())); } /** * Returns the target URI as a relative reference from the base URI. * * This method is the counterpart to resolve(): * * (string) $target === (string) UriResolver::resolve($base, UriResolver::relativize($base, $target)) * * One use-case is to use the current request URI as base URI and then generate relative links in your documents * to reduce the document size or offer self-contained downloadable document archives. * * $base = new Uri('http://example.com/a/b/'); * echo UriResolver::relativize($base, new Uri('http://example.com/a/b/c')); // prints 'c'. * echo UriResolver::relativize($base, new Uri('http://example.com/a/x/y')); // prints '../x/y'. * echo UriResolver::relativize($base, new Uri('http://example.com/a/b/?q')); // prints '?q'. * echo UriResolver::relativize($base, new Uri('http://example.org/a/b/')); // prints '//example.org/a/b/'. * * This method also accepts a target that is already relative and will try to relativize it further. Only a * relative-path reference will be returned as-is. * * echo UriResolver::relativize($base, new Uri('/a/b/c')); // prints 'c' as well * * @param UriInterface $base Base URI * @param UriInterface $target Target URI * * @return UriInterface The relative URI reference */ public static function relativize(\Google\Site_Kit_Dependencies\Psr\Http\Message\UriInterface $base, \Google\Site_Kit_Dependencies\Psr\Http\Message\UriInterface $target) { if ($target->getScheme() !== '' && ($base->getScheme() !== $target->getScheme() || $target->getAuthority() === '' && $base->getAuthority() !== '')) { return $target; } if (\Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Uri::isRelativePathReference($target)) { // As the target is already highly relative we return it as-is. It would be possible to resolve // the target with `$target = self::resolve($base, $target);` and then try make it more relative // by removing a duplicate query. But let's not do that automatically. return $target; } if ($target->getAuthority() !== '' && $base->getAuthority() !== $target->getAuthority()) { return $target->withScheme(''); } // We must remove the path before removing the authority because if the path starts with two slashes, the URI // would turn invalid. And we also cannot set a relative path before removing the authority, as that is also // invalid. $emptyPathUri = $target->withScheme('')->withPath('')->withUserInfo('')->withPort(null)->withHost(''); if ($base->getPath() !== $target->getPath()) { return $emptyPathUri->withPath(self::getRelativePath($base, $target)); } if ($base->getQuery() === $target->getQuery()) { // Only the target fragment is left. And it must be returned even if base and target fragment are the same. return $emptyPathUri->withQuery(''); } // If the base URI has a query but the target has none, we cannot return an empty path reference as it would // inherit the base query component when resolving. if ($target->getQuery() === '') { $segments = \explode('/', $target->getPath()); $lastSegment = \end($segments); return $emptyPathUri->withPath($lastSegment === '' ? './' : $lastSegment); } return $emptyPathUri; } private static function getRelativePath(\Google\Site_Kit_Dependencies\Psr\Http\Message\UriInterface $base, \Google\Site_Kit_Dependencies\Psr\Http\Message\UriInterface $target) { $sourceSegments = \explode('/', $base->getPath()); $targetSegments = \explode('/', $target->getPath()); \array_pop($sourceSegments); $targetLastSegment = \array_pop($targetSegments); foreach ($sourceSegments as $i => $segment) { if (isset($targetSegments[$i]) && $segment === $targetSegments[$i]) { unset($sourceSegments[$i], $targetSegments[$i]); } else { break; } } $targetSegments[] = $targetLastSegment; $relativePath = \str_repeat('../', \count($sourceSegments)) . \implode('/', $targetSegments); // A reference to am empty last segment or an empty first sub-segment must be prefixed with "./". // This also applies to a segment with a colon character (e.g., "file:colon") that cannot be used // as the first segment of a relative-path reference, as it would be mistaken for a scheme name. if ('' === $relativePath || \false !== \strpos(\explode('/', $relativePath, 2)[0], ':')) { $relativePath = "./{$relativePath}"; } elseif ('/' === $relativePath[0]) { if ($base->getAuthority() != '' && $base->getPath() === '') { // In this case an extra slash is added by resolve() automatically. So we must not add one here. $relativePath = ".{$relativePath}"; } else { $relativePath = "./{$relativePath}"; } } return $relativePath; } private function __construct() { // cannot be instantiated } } PK!w_S S ,guzzlehttp/psr7/src/StreamDecoratorTrait.phpnu[stream = $stream; } /** * Magic method used to create a new stream if streams are not added in * the constructor of a decorator (e.g., LazyOpenStream). * * @param string $name Name of the property (allows "stream" only). * * @return StreamInterface */ public function __get($name) { if ($name == 'stream') { $this->stream = $this->createStream(); return $this->stream; } throw new \UnexpectedValueException("{$name} not found on class"); } public function __toString() { try { if ($this->isSeekable()) { $this->seek(0); } return $this->getContents(); } catch (\Exception $e) { // Really, PHP? https://bugs.php.net/bug.php?id=53648 \trigger_error('StreamDecorator::__toString exception: ' . (string) $e, \E_USER_ERROR); return ''; } } public function getContents() { return \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Utils::copyToString($this); } /** * Allow decorators to implement custom methods * * @param string $method Missing method name * @param array $args Method arguments * * @return mixed */ public function __call($method, array $args) { $result = \call_user_func_array([$this->stream, $method], $args); // Always return the wrapped object if the result is a return $this return $result === $this->stream ? $this : $result; } public function close() { $this->stream->close(); } public function getMetadata($key = null) { return $this->stream->getMetadata($key); } public function detach() { return $this->stream->detach(); } public function getSize() { return $this->stream->getSize(); } public function eof() { return $this->stream->eof(); } public function tell() { return $this->stream->tell(); } public function isReadable() { return $this->stream->isReadable(); } public function isWritable() { return $this->stream->isWritable(); } public function isSeekable() { return $this->stream->isSeekable(); } public function rewind() { $this->seek(0); } public function seek($offset, $whence = \SEEK_SET) { $this->stream->seek($offset, $whence); } public function read($length) { return $this->stream->read($length); } public function write($string) { return $this->stream->write($string); } /** * Implement in subclasses to dynamically create streams when requested. * * @return StreamInterface * * @throws \BadMethodCallException */ protected function createStream() { throw new \BadMethodCallException('Not implemented'); } } PK!']|N N %guzzlehttp/psr7/src/StreamWrapper.phpnu[isReadable()) { $mode = $stream->isWritable() ? 'r+' : 'r'; } elseif ($stream->isWritable()) { $mode = 'w'; } else { throw new \InvalidArgumentException('The stream must be readable, ' . 'writable, or both.'); } return \fopen('guzzle://stream', $mode, null, self::createStreamContext($stream)); } /** * Creates a stream context that can be used to open a stream as a php stream resource. * * @param StreamInterface $stream * * @return resource */ public static function createStreamContext(\Google\Site_Kit_Dependencies\Psr\Http\Message\StreamInterface $stream) { return \stream_context_create(['guzzle' => ['stream' => $stream]]); } /** * Registers the stream wrapper if needed */ public static function register() { if (!\in_array('guzzle', \stream_get_wrappers())) { \stream_wrapper_register('guzzle', __CLASS__); } } public function stream_open($path, $mode, $options, &$opened_path) { $options = \stream_context_get_options($this->context); if (!isset($options['guzzle']['stream'])) { return \false; } $this->mode = $mode; $this->stream = $options['guzzle']['stream']; return \true; } public function stream_read($count) { return $this->stream->read($count); } public function stream_write($data) { return (int) $this->stream->write($data); } public function stream_tell() { return $this->stream->tell(); } public function stream_eof() { return $this->stream->eof(); } public function stream_seek($offset, $whence) { $this->stream->seek($offset, $whence); return \true; } public function stream_cast($cast_as) { $stream = clone $this->stream; return $stream->detach(); } public function stream_stat() { static $modeMap = ['r' => 33060, 'rb' => 33060, 'r+' => 33206, 'w' => 33188, 'wb' => 33188]; return ['dev' => 0, 'ino' => 0, 'mode' => $modeMap[$this->mode], 'nlink' => 0, 'uid' => 0, 'gid' => 0, 'rdev' => 0, 'size' => $this->stream->getSize() ?: 0, 'atime' => 0, 'mtime' => 0, 'ctime' => 0, 'blksize' => 0, 'blocks' => 0]; } public function url_stat($path, $flags) { return ['dev' => 0, 'ino' => 0, 'mode' => 0, 'nlink' => 0, 'uid' => 0, 'gid' => 0, 'rdev' => 0, 'size' => 0, 'atime' => 0, 'mtime' => 0, 'ctime' => 0, 'blksize' => 0, 'blocks' => 0]; } } PK!u!!guzzlehttp/psr7/src/Message.phpnu[getMethod() . ' ' . $message->getRequestTarget()) . ' HTTP/' . $message->getProtocolVersion(); if (!$message->hasHeader('host')) { $msg .= "\r\nHost: " . $message->getUri()->getHost(); } } elseif ($message instanceof \Google\Site_Kit_Dependencies\Psr\Http\Message\ResponseInterface) { $msg = 'HTTP/' . $message->getProtocolVersion() . ' ' . $message->getStatusCode() . ' ' . $message->getReasonPhrase(); } else { throw new \InvalidArgumentException('Unknown message type'); } foreach ($message->getHeaders() as $name => $values) { if (\strtolower($name) === 'set-cookie') { foreach ($values as $value) { $msg .= "\r\n{$name}: " . $value; } } else { $msg .= "\r\n{$name}: " . \implode(', ', $values); } } return "{$msg}\r\n\r\n" . $message->getBody(); } /** * Get a short summary of the message body. * * Will return `null` if the response is not printable. * * @param MessageInterface $message The message to get the body summary * @param int $truncateAt The maximum allowed size of the summary * * @return string|null */ public static function bodySummary(\Google\Site_Kit_Dependencies\Psr\Http\Message\MessageInterface $message, $truncateAt = 120) { $body = $message->getBody(); if (!$body->isSeekable() || !$body->isReadable()) { return null; } $size = $body->getSize(); if ($size === 0) { return null; } $summary = $body->read($truncateAt); $body->rewind(); if ($size > $truncateAt) { $summary .= ' (truncated...)'; } // Matches any printable character, including unicode characters: // letters, marks, numbers, punctuation, spacing, and separators. if (\preg_match('/[^\\pL\\pM\\pN\\pP\\pS\\pZ\\n\\r\\t]/u', $summary)) { return null; } return $summary; } /** * Attempts to rewind a message body and throws an exception on failure. * * The body of the message will only be rewound if a call to `tell()` * returns a value other than `0`. * * @param MessageInterface $message Message to rewind * * @throws \RuntimeException */ public static function rewindBody(\Google\Site_Kit_Dependencies\Psr\Http\Message\MessageInterface $message) { $body = $message->getBody(); if ($body->tell()) { $body->rewind(); } } /** * Parses an HTTP message into an associative array. * * The array contains the "start-line" key containing the start line of * the message, "headers" key containing an associative array of header * array values, and a "body" key containing the body of the message. * * @param string $message HTTP request or response to parse. * * @return array */ public static function parseMessage($message) { if (!$message) { throw new \InvalidArgumentException('Invalid message'); } $message = \ltrim($message, "\r\n"); $messageParts = \preg_split("/\r?\n\r?\n/", $message, 2); if ($messageParts === \false || \count($messageParts) !== 2) { throw new \InvalidArgumentException('Invalid message: Missing header delimiter'); } list($rawHeaders, $body) = $messageParts; $rawHeaders .= "\r\n"; // Put back the delimiter we split previously $headerParts = \preg_split("/\r?\n/", $rawHeaders, 2); if ($headerParts === \false || \count($headerParts) !== 2) { throw new \InvalidArgumentException('Invalid message: Missing status line'); } list($startLine, $rawHeaders) = $headerParts; if (\preg_match("/(?:^HTTP\\/|^[A-Z]+ \\S+ HTTP\\/)(\\d+(?:\\.\\d+)?)/i", $startLine, $matches) && $matches[1] === '1.0') { // Header folding is deprecated for HTTP/1.1, but allowed in HTTP/1.0 $rawHeaders = \preg_replace(\Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Rfc7230::HEADER_FOLD_REGEX, ' ', $rawHeaders); } /** @var array[] $headerLines */ $count = \preg_match_all(\Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Rfc7230::HEADER_REGEX, $rawHeaders, $headerLines, \PREG_SET_ORDER); // If these aren't the same, then one line didn't match and there's an invalid header. if ($count !== \substr_count($rawHeaders, "\n")) { // Folding is deprecated, see https://tools.ietf.org/html/rfc7230#section-3.2.4 if (\preg_match(\Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Rfc7230::HEADER_FOLD_REGEX, $rawHeaders)) { throw new \InvalidArgumentException('Invalid header syntax: Obsolete line folding'); } throw new \InvalidArgumentException('Invalid header syntax'); } $headers = []; foreach ($headerLines as $headerLine) { $headers[$headerLine[1]][] = $headerLine[2]; } return ['start-line' => $startLine, 'headers' => $headers, 'body' => $body]; } /** * Constructs a URI for an HTTP request message. * * @param string $path Path from the start-line * @param array $headers Array of headers (each value an array). * * @return string */ public static function parseRequestUri($path, array $headers) { $hostKey = \array_filter(\array_keys($headers), function ($k) { return \strtolower($k) === 'host'; }); // If no host is found, then a full URI cannot be constructed. if (!$hostKey) { return $path; } $host = $headers[\reset($hostKey)][0]; $scheme = \substr($host, -4) === ':443' ? 'https' : 'http'; return $scheme . '://' . $host . '/' . \ltrim($path, '/'); } /** * Parses a request message string into a request object. * * @param string $message Request message string. * * @return Request */ public static function parseRequest($message) { $data = self::parseMessage($message); $matches = []; if (!\preg_match('/^[\\S]+\\s+([a-zA-Z]+:\\/\\/|\\/).*/', $data['start-line'], $matches)) { throw new \InvalidArgumentException('Invalid request string'); } $parts = \explode(' ', $data['start-line'], 3); $version = isset($parts[2]) ? \explode('/', $parts[2])[1] : '1.1'; $request = new \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Request($parts[0], $matches[1] === '/' ? self::parseRequestUri($parts[1], $data['headers']) : $parts[1], $data['headers'], $data['body'], $version); return $matches[1] === '/' ? $request : $request->withRequestTarget($parts[1]); } /** * Parses a response message string into a response object. * * @param string $message Response message string. * * @return Response */ public static function parseResponse($message) { $data = self::parseMessage($message); // According to https://tools.ietf.org/html/rfc7230#section-3.1.2 the space // between status-code and reason-phrase is required. But browsers accept // responses without space and reason as well. if (!\preg_match('/^HTTP\\/.* [0-9]{3}( .*|$)/', $data['start-line'])) { throw new \InvalidArgumentException('Invalid response string: ' . $data['start-line']); } $parts = \explode(' ', $data['start-line'], 3); return new \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Response((int) $parts[1], $data['headers'], $data['body'], \explode('/', $parts[0])[1], isset($parts[2]) ? $parts[2] : null); } } PK! dYYguzzlehttp/psr7/src/Uri.phpnu[ 80, 'https' => 443, 'ftp' => 21, 'gopher' => 70, 'nntp' => 119, 'news' => 119, 'telnet' => 23, 'tn3270' => 23, 'imap' => 143, 'pop' => 110, 'ldap' => 389]; private static $charUnreserved = 'a-zA-Z0-9_\\-\\.~'; private static $charSubDelims = '!\\$&\'\\(\\)\\*\\+,;='; private static $replaceQuery = ['=' => '%3D', '&' => '%26']; /** @var string Uri scheme. */ private $scheme = ''; /** @var string Uri user info. */ private $userInfo = ''; /** @var string Uri host. */ private $host = ''; /** @var int|null Uri port. */ private $port; /** @var string Uri path. */ private $path = ''; /** @var string Uri query string. */ private $query = ''; /** @var string Uri fragment. */ private $fragment = ''; /** * @param string $uri URI to parse */ public function __construct($uri = '') { // weak type check to also accept null until we can add scalar type hints if ($uri != '') { $parts = self::parse($uri); if ($parts === \false) { throw new \InvalidArgumentException("Unable to parse URI: {$uri}"); } $this->applyParts($parts); } } /** * UTF-8 aware \parse_url() replacement. * * The internal function produces broken output for non ASCII domain names * (IDN) when used with locales other than "C". * * On the other hand, cURL understands IDN correctly only when UTF-8 locale * is configured ("C.UTF-8", "en_US.UTF-8", etc.). * * @see https://bugs.php.net/bug.php?id=52923 * @see https://www.php.net/manual/en/function.parse-url.php#114817 * @see https://curl.haxx.se/libcurl/c/CURLOPT_URL.html#ENCODING * * @param string $url * * @return array|false */ private static function parse($url) { // If IPv6 $prefix = ''; if (\preg_match('%^(.*://\\[[0-9:a-f]+\\])(.*?)$%', $url, $matches)) { $prefix = $matches[1]; $url = $matches[2]; } $encodedUrl = \preg_replace_callback('%[^:/@?&=#]+%usD', static function ($matches) { return \urlencode($matches[0]); }, $url); $result = \parse_url($prefix . $encodedUrl); if ($result === \false) { return \false; } return \array_map('urldecode', $result); } public function __toString() { return self::composeComponents($this->scheme, $this->getAuthority(), $this->path, $this->query, $this->fragment); } /** * Composes a URI reference string from its various components. * * Usually this method does not need to be called manually but instead is used indirectly via * `Psr\Http\Message\UriInterface::__toString`. * * PSR-7 UriInterface treats an empty component the same as a missing component as * getQuery(), getFragment() etc. always return a string. This explains the slight * difference to RFC 3986 Section 5.3. * * Another adjustment is that the authority separator is added even when the authority is missing/empty * for the "file" scheme. This is because PHP stream functions like `file_get_contents` only work with * `file:///myfile` but not with `file:/myfile` although they are equivalent according to RFC 3986. But * `file:///` is the more common syntax for the file scheme anyway (Chrome for example redirects to * that format). * * @param string $scheme * @param string $authority * @param string $path * @param string $query * @param string $fragment * * @return string * * @link https://tools.ietf.org/html/rfc3986#section-5.3 */ public static function composeComponents($scheme, $authority, $path, $query, $fragment) { $uri = ''; // weak type checks to also accept null until we can add scalar type hints if ($scheme != '') { $uri .= $scheme . ':'; } if ($authority != '' || $scheme === 'file') { $uri .= '//' . $authority; } $uri .= $path; if ($query != '') { $uri .= '?' . $query; } if ($fragment != '') { $uri .= '#' . $fragment; } return $uri; } /** * Whether the URI has the default port of the current scheme. * * `Psr\Http\Message\UriInterface::getPort` may return null or the standard port. This method can be used * independently of the implementation. * * @param UriInterface $uri * * @return bool */ public static function isDefaultPort(\Google\Site_Kit_Dependencies\Psr\Http\Message\UriInterface $uri) { return $uri->getPort() === null || isset(self::$defaultPorts[$uri->getScheme()]) && $uri->getPort() === self::$defaultPorts[$uri->getScheme()]; } /** * Whether the URI is absolute, i.e. it has a scheme. * * An instance of UriInterface can either be an absolute URI or a relative reference. This method returns true * if it is the former. An absolute URI has a scheme. A relative reference is used to express a URI relative * to another URI, the base URI. Relative references can be divided into several forms: * - network-path references, e.g. '//example.com/path' * - absolute-path references, e.g. '/path' * - relative-path references, e.g. 'subpath' * * @param UriInterface $uri * * @return bool * * @see Uri::isNetworkPathReference * @see Uri::isAbsolutePathReference * @see Uri::isRelativePathReference * @link https://tools.ietf.org/html/rfc3986#section-4 */ public static function isAbsolute(\Google\Site_Kit_Dependencies\Psr\Http\Message\UriInterface $uri) { return $uri->getScheme() !== ''; } /** * Whether the URI is a network-path reference. * * A relative reference that begins with two slash characters is termed an network-path reference. * * @param UriInterface $uri * * @return bool * * @link https://tools.ietf.org/html/rfc3986#section-4.2 */ public static function isNetworkPathReference(\Google\Site_Kit_Dependencies\Psr\Http\Message\UriInterface $uri) { return $uri->getScheme() === '' && $uri->getAuthority() !== ''; } /** * Whether the URI is a absolute-path reference. * * A relative reference that begins with a single slash character is termed an absolute-path reference. * * @param UriInterface $uri * * @return bool * * @link https://tools.ietf.org/html/rfc3986#section-4.2 */ public static function isAbsolutePathReference(\Google\Site_Kit_Dependencies\Psr\Http\Message\UriInterface $uri) { return $uri->getScheme() === '' && $uri->getAuthority() === '' && isset($uri->getPath()[0]) && $uri->getPath()[0] === '/'; } /** * Whether the URI is a relative-path reference. * * A relative reference that does not begin with a slash character is termed a relative-path reference. * * @param UriInterface $uri * * @return bool * * @link https://tools.ietf.org/html/rfc3986#section-4.2 */ public static function isRelativePathReference(\Google\Site_Kit_Dependencies\Psr\Http\Message\UriInterface $uri) { return $uri->getScheme() === '' && $uri->getAuthority() === '' && (!isset($uri->getPath()[0]) || $uri->getPath()[0] !== '/'); } /** * Whether the URI is a same-document reference. * * A same-document reference refers to a URI that is, aside from its fragment * component, identical to the base URI. When no base URI is given, only an empty * URI reference (apart from its fragment) is considered a same-document reference. * * @param UriInterface $uri The URI to check * @param UriInterface|null $base An optional base URI to compare against * * @return bool * * @link https://tools.ietf.org/html/rfc3986#section-4.4 */ public static function isSameDocumentReference(\Google\Site_Kit_Dependencies\Psr\Http\Message\UriInterface $uri, \Google\Site_Kit_Dependencies\Psr\Http\Message\UriInterface $base = null) { if ($base !== null) { $uri = \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\UriResolver::resolve($base, $uri); return $uri->getScheme() === $base->getScheme() && $uri->getAuthority() === $base->getAuthority() && $uri->getPath() === $base->getPath() && $uri->getQuery() === $base->getQuery(); } return $uri->getScheme() === '' && $uri->getAuthority() === '' && $uri->getPath() === '' && $uri->getQuery() === ''; } /** * Removes dot segments from a path and returns the new path. * * @param string $path * * @return string * * @deprecated since version 1.4. Use UriResolver::removeDotSegments instead. * @see UriResolver::removeDotSegments */ public static function removeDotSegments($path) { return \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\UriResolver::removeDotSegments($path); } /** * Converts the relative URI into a new URI that is resolved against the base URI. * * @param UriInterface $base Base URI * @param string|UriInterface $rel Relative URI * * @return UriInterface * * @deprecated since version 1.4. Use UriResolver::resolve instead. * @see UriResolver::resolve */ public static function resolve(\Google\Site_Kit_Dependencies\Psr\Http\Message\UriInterface $base, $rel) { if (!$rel instanceof \Google\Site_Kit_Dependencies\Psr\Http\Message\UriInterface) { $rel = new self($rel); } return \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\UriResolver::resolve($base, $rel); } /** * Creates a new URI with a specific query string value removed. * * Any existing query string values that exactly match the provided key are * removed. * * @param UriInterface $uri URI to use as a base. * @param string $key Query string key to remove. * * @return UriInterface */ public static function withoutQueryValue(\Google\Site_Kit_Dependencies\Psr\Http\Message\UriInterface $uri, $key) { $result = self::getFilteredQueryString($uri, [$key]); return $uri->withQuery(\implode('&', $result)); } /** * Creates a new URI with a specific query string value. * * Any existing query string values that exactly match the provided key are * removed and replaced with the given key value pair. * * A value of null will set the query string key without a value, e.g. "key" * instead of "key=value". * * @param UriInterface $uri URI to use as a base. * @param string $key Key to set. * @param string|null $value Value to set * * @return UriInterface */ public static function withQueryValue(\Google\Site_Kit_Dependencies\Psr\Http\Message\UriInterface $uri, $key, $value) { $result = self::getFilteredQueryString($uri, [$key]); $result[] = self::generateQueryString($key, $value); return $uri->withQuery(\implode('&', $result)); } /** * Creates a new URI with multiple specific query string values. * * It has the same behavior as withQueryValue() but for an associative array of key => value. * * @param UriInterface $uri URI to use as a base. * @param array $keyValueArray Associative array of key and values * * @return UriInterface */ public static function withQueryValues(\Google\Site_Kit_Dependencies\Psr\Http\Message\UriInterface $uri, array $keyValueArray) { $result = self::getFilteredQueryString($uri, \array_keys($keyValueArray)); foreach ($keyValueArray as $key => $value) { $result[] = self::generateQueryString($key, $value); } return $uri->withQuery(\implode('&', $result)); } /** * Creates a URI from a hash of `parse_url` components. * * @param array $parts * * @return UriInterface * * @link http://php.net/manual/en/function.parse-url.php * * @throws \InvalidArgumentException If the components do not form a valid URI. */ public static function fromParts(array $parts) { $uri = new self(); $uri->applyParts($parts); $uri->validateState(); return $uri; } public function getScheme() { return $this->scheme; } public function getAuthority() { $authority = $this->host; if ($this->userInfo !== '') { $authority = $this->userInfo . '@' . $authority; } if ($this->port !== null) { $authority .= ':' . $this->port; } return $authority; } public function getUserInfo() { return $this->userInfo; } public function getHost() { return $this->host; } public function getPort() { return $this->port; } public function getPath() { return $this->path; } public function getQuery() { return $this->query; } public function getFragment() { return $this->fragment; } public function withScheme($scheme) { $scheme = $this->filterScheme($scheme); if ($this->scheme === $scheme) { return $this; } $new = clone $this; $new->scheme = $scheme; $new->removeDefaultPort(); $new->validateState(); return $new; } public function withUserInfo($user, $password = null) { $info = $this->filterUserInfoComponent($user); if ($password !== null) { $info .= ':' . $this->filterUserInfoComponent($password); } if ($this->userInfo === $info) { return $this; } $new = clone $this; $new->userInfo = $info; $new->validateState(); return $new; } public function withHost($host) { $host = $this->filterHost($host); if ($this->host === $host) { return $this; } $new = clone $this; $new->host = $host; $new->validateState(); return $new; } public function withPort($port) { $port = $this->filterPort($port); if ($this->port === $port) { return $this; } $new = clone $this; $new->port = $port; $new->removeDefaultPort(); $new->validateState(); return $new; } public function withPath($path) { $path = $this->filterPath($path); if ($this->path === $path) { return $this; } $new = clone $this; $new->path = $path; $new->validateState(); return $new; } public function withQuery($query) { $query = $this->filterQueryAndFragment($query); if ($this->query === $query) { return $this; } $new = clone $this; $new->query = $query; return $new; } public function withFragment($fragment) { $fragment = $this->filterQueryAndFragment($fragment); if ($this->fragment === $fragment) { return $this; } $new = clone $this; $new->fragment = $fragment; return $new; } /** * Apply parse_url parts to a URI. * * @param array $parts Array of parse_url parts to apply. */ private function applyParts(array $parts) { $this->scheme = isset($parts['scheme']) ? $this->filterScheme($parts['scheme']) : ''; $this->userInfo = isset($parts['user']) ? $this->filterUserInfoComponent($parts['user']) : ''; $this->host = isset($parts['host']) ? $this->filterHost($parts['host']) : ''; $this->port = isset($parts['port']) ? $this->filterPort($parts['port']) : null; $this->path = isset($parts['path']) ? $this->filterPath($parts['path']) : ''; $this->query = isset($parts['query']) ? $this->filterQueryAndFragment($parts['query']) : ''; $this->fragment = isset($parts['fragment']) ? $this->filterQueryAndFragment($parts['fragment']) : ''; if (isset($parts['pass'])) { $this->userInfo .= ':' . $this->filterUserInfoComponent($parts['pass']); } $this->removeDefaultPort(); } /** * @param string $scheme * * @return string * * @throws \InvalidArgumentException If the scheme is invalid. */ private function filterScheme($scheme) { if (!\is_string($scheme)) { throw new \InvalidArgumentException('Scheme must be a string'); } return \strtr($scheme, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'); } /** * @param string $component * * @return string * * @throws \InvalidArgumentException If the user info is invalid. */ private function filterUserInfoComponent($component) { if (!\is_string($component)) { throw new \InvalidArgumentException('User info must be a string'); } return \preg_replace_callback('/(?:[^%' . self::$charUnreserved . self::$charSubDelims . ']+|%(?![A-Fa-f0-9]{2}))/', [$this, 'rawurlencodeMatchZero'], $component); } /** * @param string $host * * @return string * * @throws \InvalidArgumentException If the host is invalid. */ private function filterHost($host) { if (!\is_string($host)) { throw new \InvalidArgumentException('Host must be a string'); } return \strtr($host, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'); } /** * @param int|null $port * * @return int|null * * @throws \InvalidArgumentException If the port is invalid. */ private function filterPort($port) { if ($port === null) { return null; } $port = (int) $port; if (0 > $port || 0xffff < $port) { throw new \InvalidArgumentException(\sprintf('Invalid port: %d. Must be between 0 and 65535', $port)); } return $port; } /** * @param UriInterface $uri * @param array $keys * * @return array */ private static function getFilteredQueryString(\Google\Site_Kit_Dependencies\Psr\Http\Message\UriInterface $uri, array $keys) { $current = $uri->getQuery(); if ($current === '') { return []; } $decodedKeys = \array_map('rawurldecode', $keys); return \array_filter(\explode('&', $current), function ($part) use($decodedKeys) { return !\in_array(\rawurldecode(\explode('=', $part)[0]), $decodedKeys, \true); }); } /** * @param string $key * @param string|null $value * * @return string */ private static function generateQueryString($key, $value) { // Query string separators ("=", "&") within the key or value need to be encoded // (while preventing double-encoding) before setting the query string. All other // chars that need percent-encoding will be encoded by withQuery(). $queryString = \strtr($key, self::$replaceQuery); if ($value !== null) { $queryString .= '=' . \strtr($value, self::$replaceQuery); } return $queryString; } private function removeDefaultPort() { if ($this->port !== null && self::isDefaultPort($this)) { $this->port = null; } } /** * Filters the path of a URI * * @param string $path * * @return string * * @throws \InvalidArgumentException If the path is invalid. */ private function filterPath($path) { if (!\is_string($path)) { throw new \InvalidArgumentException('Path must be a string'); } return \preg_replace_callback('/(?:[^' . self::$charUnreserved . self::$charSubDelims . '%:@\\/]++|%(?![A-Fa-f0-9]{2}))/', [$this, 'rawurlencodeMatchZero'], $path); } /** * Filters the query string or fragment of a URI. * * @param string $str * * @return string * * @throws \InvalidArgumentException If the query or fragment is invalid. */ private function filterQueryAndFragment($str) { if (!\is_string($str)) { throw new \InvalidArgumentException('Query and fragment must be a string'); } return \preg_replace_callback('/(?:[^' . self::$charUnreserved . self::$charSubDelims . '%:@\\/\\?]++|%(?![A-Fa-f0-9]{2}))/', [$this, 'rawurlencodeMatchZero'], $str); } private function rawurlencodeMatchZero(array $match) { return \rawurlencode($match[0]); } private function validateState() { if ($this->host === '' && ($this->scheme === 'http' || $this->scheme === 'https')) { $this->host = self::HTTP_DEFAULT_HOST; } if ($this->getAuthority() === '') { if (0 === \strpos($this->path, '//')) { throw new \InvalidArgumentException('The path of a URI without an authority must not start with two slashes "//"'); } if ($this->scheme === '' && \false !== \strpos(\explode('/', $this->path, 2)[0], ':')) { throw new \InvalidArgumentException('A relative URI must not have a path beginning with a segment containing a colon'); } } elseif (isset($this->path[0]) && $this->path[0] !== '/') { @\trigger_error('The path of a URI with an authority must start with a slash "/" or be empty. Automagically fixing the URI ' . 'by adding a leading slash to the path is deprecated since version 1.4 and will throw an exception instead.', \E_USER_DEPRECATED); $this->path = '/' . $this->path; //throw new \InvalidArgumentException('The path of a URI with an authority must start with a slash "/" or be empty'); } } } PK!%guzzlehttp/psr7/src/InflateStream.phpnu[read(10); $filenameHeaderLength = $this->getLengthOfPossibleFilenameHeader($stream, $header); // Skip the header, that is 10 + length of filename + 1 (nil) bytes $stream = new \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\LimitStream($stream, -1, 10 + $filenameHeaderLength); $resource = \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\StreamWrapper::getResource($stream); \stream_filter_append($resource, 'zlib.inflate', \STREAM_FILTER_READ); $this->stream = $stream->isSeekable() ? new \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Stream($resource) : new \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\NoSeekStream(new \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Stream($resource)); } /** * @param StreamInterface $stream * @param $header * * @return int */ private function getLengthOfPossibleFilenameHeader(\Google\Site_Kit_Dependencies\Psr\Http\Message\StreamInterface $stream, $header) { $filename_header_length = 0; if (\substr(\bin2hex($header), 6, 2) === '08') { // we have a filename, read until nil $filename_header_length = 1; while ($stream->read(1) !== \chr(0)) { $filename_header_length++; } } return $filename_header_length; } } PK!@")guzzlehttp/psr7/src/functions_include.phpnu[filename = $filename; $this->mode = $mode; } /** * Creates the underlying stream lazily when required. * * @return StreamInterface */ protected function createStream() { return \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Utils::streamFor(\Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Utils::tryFopen($this->filename, $this->mode)); } } PK!NlZZ%guzzlehttp/psr7/src/UriComparator.phpnu[getHost(), $modified->getHost()) !== 0) { return \true; } if ($original->getScheme() !== $modified->getScheme()) { return \true; } if (self::computePort($original) !== self::computePort($modified)) { return \true; } return \false; } /** * @return int */ private static function computePort(\Google\Site_Kit_Dependencies\Psr\Http\Message\UriInterface $uri) { $port = $uri->getPort(); if (null !== $port) { return $port; } return 'https' === $uri->getScheme() ? 443 : 80; } private function __construct() { // cannot be instantiated } } PK!'մ#guzzlehttp/psr7/src/LimitStream.phpnu[stream = $stream; $this->setLimit($limit); $this->setOffset($offset); } public function eof() { // Always return true if the underlying stream is EOF if ($this->stream->eof()) { return \true; } // No limit and the underlying stream is not at EOF if ($this->limit == -1) { return \false; } return $this->stream->tell() >= $this->offset + $this->limit; } /** * Returns the size of the limited subset of data * {@inheritdoc} */ public function getSize() { if (null === ($length = $this->stream->getSize())) { return null; } elseif ($this->limit == -1) { return $length - $this->offset; } else { return \min($this->limit, $length - $this->offset); } } /** * Allow for a bounded seek on the read limited stream * {@inheritdoc} */ public function seek($offset, $whence = \SEEK_SET) { if ($whence !== \SEEK_SET || $offset < 0) { throw new \RuntimeException(\sprintf('Cannot seek to offset %s with whence %s', $offset, $whence)); } $offset += $this->offset; if ($this->limit !== -1) { if ($offset > $this->offset + $this->limit) { $offset = $this->offset + $this->limit; } } $this->stream->seek($offset); } /** * Give a relative tell() * {@inheritdoc} */ public function tell() { return $this->stream->tell() - $this->offset; } /** * Set the offset to start limiting from * * @param int $offset Offset to seek to and begin byte limiting from * * @throws \RuntimeException if the stream cannot be seeked. */ public function setOffset($offset) { $current = $this->stream->tell(); if ($current !== $offset) { // If the stream cannot seek to the offset position, then read to it if ($this->stream->isSeekable()) { $this->stream->seek($offset); } elseif ($current > $offset) { throw new \RuntimeException("Could not seek to stream offset {$offset}"); } else { $this->stream->read($offset - $current); } } $this->offset = $offset; } /** * Set the limit of bytes that the decorator allows to be read from the * stream. * * @param int $limit Number of bytes to allow to be read from the stream. * Use -1 for no limit. */ public function setLimit($limit) { $this->limit = $limit; } public function read($length) { if ($this->limit == -1) { return $this->stream->read($length); } // Check if the current position is less than the total allowed // bytes + original offset $remaining = $this->offset + $this->limit - $this->stream->tell(); if ($remaining > 0) { // Only return the amount of requested data, ensuring that the byte // limit is not exceeded return $this->stream->read(\min($remaining, $length)); } return ''; } } PK!:hguzzlehttp/psr7/src/Stream.phpnu[size = $options['size']; } $this->customMetadata = isset($options['metadata']) ? $options['metadata'] : []; $this->stream = $stream; $meta = \stream_get_meta_data($this->stream); $this->seekable = $meta['seekable']; $this->readable = (bool) \preg_match(self::READABLE_MODES, $meta['mode']); $this->writable = (bool) \preg_match(self::WRITABLE_MODES, $meta['mode']); $this->uri = $this->getMetadata('uri'); } /** * Closes the stream when the destructed */ public function __destruct() { $this->close(); } public function __toString() { try { if ($this->isSeekable()) { $this->seek(0); } return $this->getContents(); } catch (\Exception $e) { return ''; } } public function getContents() { if (!isset($this->stream)) { throw new \RuntimeException('Stream is detached'); } $contents = \stream_get_contents($this->stream); if ($contents === \false) { throw new \RuntimeException('Unable to read stream contents'); } return $contents; } public function close() { if (isset($this->stream)) { if (\is_resource($this->stream)) { \fclose($this->stream); } $this->detach(); } } public function detach() { if (!isset($this->stream)) { return null; } $result = $this->stream; unset($this->stream); $this->size = $this->uri = null; $this->readable = $this->writable = $this->seekable = \false; return $result; } public function getSize() { if ($this->size !== null) { return $this->size; } if (!isset($this->stream)) { return null; } // Clear the stat cache if the stream has a URI if ($this->uri) { \clearstatcache(\true, $this->uri); } $stats = \fstat($this->stream); if (isset($stats['size'])) { $this->size = $stats['size']; return $this->size; } return null; } public function isReadable() { return $this->readable; } public function isWritable() { return $this->writable; } public function isSeekable() { return $this->seekable; } public function eof() { if (!isset($this->stream)) { throw new \RuntimeException('Stream is detached'); } return \feof($this->stream); } public function tell() { if (!isset($this->stream)) { throw new \RuntimeException('Stream is detached'); } $result = \ftell($this->stream); if ($result === \false) { throw new \RuntimeException('Unable to determine stream position'); } return $result; } public function rewind() { $this->seek(0); } public function seek($offset, $whence = \SEEK_SET) { $whence = (int) $whence; if (!isset($this->stream)) { throw new \RuntimeException('Stream is detached'); } if (!$this->seekable) { throw new \RuntimeException('Stream is not seekable'); } if (\fseek($this->stream, $offset, $whence) === -1) { throw new \RuntimeException('Unable to seek to stream position ' . $offset . ' with whence ' . \var_export($whence, \true)); } } public function read($length) { if (!isset($this->stream)) { throw new \RuntimeException('Stream is detached'); } if (!$this->readable) { throw new \RuntimeException('Cannot read from non-readable stream'); } if ($length < 0) { throw new \RuntimeException('Length parameter cannot be negative'); } if (0 === $length) { return ''; } $string = \fread($this->stream, $length); if (\false === $string) { throw new \RuntimeException('Unable to read from stream'); } return $string; } public function write($string) { if (!isset($this->stream)) { throw new \RuntimeException('Stream is detached'); } if (!$this->writable) { throw new \RuntimeException('Cannot write to a non-writable stream'); } // We can't know the size after writing anything $this->size = null; $result = \fwrite($this->stream, $string); if ($result === \false) { throw new \RuntimeException('Unable to write to stream'); } return $result; } public function getMetadata($key = null) { if (!isset($this->stream)) { return $key ? null : []; } elseif (!$key) { return $this->customMetadata + \stream_get_meta_data($this->stream); } elseif (isset($this->customMetadata[$key])) { return $this->customMetadata[$key]; } $meta = \stream_get_meta_data($this->stream); return isset($meta[$key]) ? $meta[$key] : null; } } PK!Bׅ!!%guzzlehttp/psr7/src/UriNormalizer.phpnu[getPath() === '' && ($uri->getScheme() === 'http' || $uri->getScheme() === 'https')) { $uri = $uri->withPath('/'); } if ($flags & self::REMOVE_DEFAULT_HOST && $uri->getScheme() === 'file' && $uri->getHost() === 'localhost') { $uri = $uri->withHost(''); } if ($flags & self::REMOVE_DEFAULT_PORT && $uri->getPort() !== null && \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Uri::isDefaultPort($uri)) { $uri = $uri->withPort(null); } if ($flags & self::REMOVE_DOT_SEGMENTS && !\Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Uri::isRelativePathReference($uri)) { $uri = $uri->withPath(\Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\UriResolver::removeDotSegments($uri->getPath())); } if ($flags & self::REMOVE_DUPLICATE_SLASHES) { $uri = $uri->withPath(\preg_replace('#//++#', '/', $uri->getPath())); } if ($flags & self::SORT_QUERY_PARAMETERS && $uri->getQuery() !== '') { $queryKeyValues = \explode('&', $uri->getQuery()); \sort($queryKeyValues); $uri = $uri->withQuery(\implode('&', $queryKeyValues)); } return $uri; } /** * Whether two URIs can be considered equivalent. * * Both URIs are normalized automatically before comparison with the given $normalizations bitmask. The method also * accepts relative URI references and returns true when they are equivalent. This of course assumes they will be * resolved against the same base URI. If this is not the case, determination of equivalence or difference of * relative references does not mean anything. * * @param UriInterface $uri1 An URI to compare * @param UriInterface $uri2 An URI to compare * @param int $normalizations A bitmask of normalizations to apply, see constants * * @return bool * * @link https://tools.ietf.org/html/rfc3986#section-6.1 */ public static function isEquivalent(\Google\Site_Kit_Dependencies\Psr\Http\Message\UriInterface $uri1, \Google\Site_Kit_Dependencies\Psr\Http\Message\UriInterface $uri2, $normalizations = self::PRESERVING_NORMALIZATIONS) { return (string) self::normalize($uri1, $normalizations) === (string) self::normalize($uri2, $normalizations); } private static function capitalizePercentEncoding(\Google\Site_Kit_Dependencies\Psr\Http\Message\UriInterface $uri) { $regex = '/(?:%[A-Fa-f0-9]{2})++/'; $callback = function (array $match) { return \strtoupper($match[0]); }; return $uri->withPath(\preg_replace_callback($regex, $callback, $uri->getPath()))->withQuery(\preg_replace_callback($regex, $callback, $uri->getQuery())); } private static function decodeUnreservedCharacters(\Google\Site_Kit_Dependencies\Psr\Http\Message\UriInterface $uri) { $regex = '/%(?:2D|2E|5F|7E|3[0-9]|[46][1-9A-F]|[57][0-9A])/i'; $callback = function (array $match) { return \rawurldecode($match[0]); }; return $uri->withPath(\preg_replace_callback($regex, $callback, $uri->getPath()))->withQuery(\preg_replace_callback($regex, $callback, $uri->getQuery())); } private function __construct() { // cannot be instantiated } } PK!ߡguzzlehttp/psr7/src/Header.phpnu[]+>|[^=]+/', $kvp, $matches)) { $m = $matches[0]; if (isset($m[1])) { $part[\trim($m[0], $trimmed)] = \trim($m[1], $trimmed); } else { $part[] = \trim($m[0], $trimmed); } } } if ($part) { $params[] = $part; } } return $params; } /** * Converts an array of header values that may contain comma separated * headers into an array of headers with no comma separated values. * * @param string|array $header Header to normalize. * * @return array Returns the normalized header field values. */ public static function normalize($header) { if (!\is_array($header)) { return \array_map('trim', \explode(',', $header)); } $result = []; foreach ($header as $value) { foreach ((array) $value as $v) { if (\strpos($v, ',') === \false) { $result[] = $v; continue; } foreach (\preg_split('/,(?=([^"]*"[^"]*")*[^"]*$)/', $v) as $vv) { $result[] = \trim($vv); } } } return $result; } } PK!K google/apiclient/src/Service.phpnu[client = $clientOrConfig; } elseif (\is_array($clientOrConfig)) { $this->client = new \Google\Site_Kit_Dependencies\Google\Client($clientOrConfig ?: []); } else { $errorMessage = 'Google\\Site_Kit_Dependencies\\constructor must be array or instance of Google\\Client'; if (\class_exists('TypeError')) { throw new \TypeError($errorMessage); } \trigger_error($errorMessage, \E_USER_ERROR); } } /** * Return the associated Google\Client class. * @return \Google\Client */ public function getClient() { return $this->client; } /** * Create a new HTTP Batch handler for this service * * @return Batch */ public function createBatch() { return new \Google\Site_Kit_Dependencies\Google\Http\Batch($this->client, \false, $this->rootUrl, $this->batchPath); } } PK!y ]((google/apiclient/src/Model.phpnu[mapTypes($array); } $this->gapiInit(); } /** * Getter that handles passthrough access to the data array, and lazy object creation. * @param string $key Property name. * @return mixed The value if any, or null. */ public function __get($key) { $keyType = $this->keyType($key); $keyDataType = $this->dataType($key); if ($keyType && !isset($this->processed[$key])) { if (isset($this->modelData[$key])) { $val = $this->modelData[$key]; } elseif ($keyDataType == 'array' || $keyDataType == 'map') { $val = array(); } else { $val = null; } if ($this->isAssociativeArray($val)) { if ($keyDataType && 'map' == $keyDataType) { foreach ($val as $arrayKey => $arrayItem) { $this->modelData[$key][$arrayKey] = new $keyType($arrayItem); } } else { $this->modelData[$key] = new $keyType($val); } } else { if (\is_array($val)) { $arrayObject = array(); foreach ($val as $arrayIndex => $arrayItem) { $arrayObject[$arrayIndex] = new $keyType($arrayItem); } $this->modelData[$key] = $arrayObject; } } $this->processed[$key] = \true; } return isset($this->modelData[$key]) ? $this->modelData[$key] : null; } /** * Initialize this object's properties from an array. * * @param array $array Used to seed this object's properties. * @return void */ protected function mapTypes($array) { // Hard initialise simple types, lazy load more complex ones. foreach ($array as $key => $val) { if ($keyType = $this->keyType($key)) { $dataType = $this->dataType($key); if ($dataType == 'array' || $dataType == 'map') { $this->{$key} = array(); foreach ($val as $itemKey => $itemVal) { if ($itemVal instanceof $keyType) { $this->{$key}[$itemKey] = $itemVal; } else { $this->{$key}[$itemKey] = new $keyType($itemVal); } } } elseif ($val instanceof $keyType) { $this->{$key} = $val; } else { $this->{$key} = new $keyType($val); } unset($array[$key]); } elseif (\property_exists($this, $key)) { $this->{$key} = $val; unset($array[$key]); } elseif (\property_exists($this, $camelKey = $this->camelCase($key))) { // This checks if property exists as camelCase, leaving it in array as snake_case // in case of backwards compatibility issues. $this->{$camelKey} = $val; } } $this->modelData = $array; } /** * Blank initialiser to be used in subclasses to do post-construction initialisation - this * avoids the need for subclasses to have to implement the variadics handling in their * constructors. */ protected function gapiInit() { return; } /** * Create a simplified object suitable for straightforward * conversion to JSON. This is relatively expensive * due to the usage of reflection, but shouldn't be called * a whole lot, and is the most straightforward way to filter. */ public function toSimpleObject() { $object = new \stdClass(); // Process all other data. foreach ($this->modelData as $key => $val) { $result = $this->getSimpleValue($val); if ($result !== null) { $object->{$key} = $this->nullPlaceholderCheck($result); } } // Process all public properties. $reflect = new \ReflectionObject($this); $props = $reflect->getProperties(\ReflectionProperty::IS_PUBLIC); foreach ($props as $member) { $name = $member->getName(); $result = $this->getSimpleValue($this->{$name}); if ($result !== null) { $name = $this->getMappedName($name); $object->{$name} = $this->nullPlaceholderCheck($result); } } return $object; } /** * Handle different types of values, primarily * other objects and map and array data types. */ private function getSimpleValue($value) { if ($value instanceof \Google\Site_Kit_Dependencies\Google\Model) { return $value->toSimpleObject(); } else { if (\is_array($value)) { $return = array(); foreach ($value as $key => $a_value) { $a_value = $this->getSimpleValue($a_value); if ($a_value !== null) { $key = $this->getMappedName($key); $return[$key] = $this->nullPlaceholderCheck($a_value); } } return $return; } } return $value; } /** * Check whether the value is the null placeholder and return true null. */ private function nullPlaceholderCheck($value) { if ($value === self::NULL_VALUE) { return null; } return $value; } /** * If there is an internal name mapping, use that. */ private function getMappedName($key) { if (isset($this->internal_gapi_mappings, $this->internal_gapi_mappings[$key])) { $key = $this->internal_gapi_mappings[$key]; } return $key; } /** * Returns true only if the array is associative. * @param array $array * @return bool True if the array is associative. */ protected function isAssociativeArray($array) { if (!\is_array($array)) { return \false; } $keys = \array_keys($array); foreach ($keys as $key) { if (\is_string($key)) { return \true; } } return \false; } /** * Verify if $obj is an array. * @throws \Google\Exception Thrown if $obj isn't an array. * @param array $obj Items that should be validated. * @param string $method Method expecting an array as an argument. */ public function assertIsArray($obj, $method) { if ($obj && !\is_array($obj)) { throw new \Google\Site_Kit_Dependencies\Google\Exception("Incorrect parameter type passed to {$method}(). Expected an array."); } } /** @return bool */ #[\ReturnTypeWillChange] public function offsetExists($offset) { return isset($this->{$offset}) || isset($this->modelData[$offset]); } /** @return mixed */ #[\ReturnTypeWillChange] public function offsetGet($offset) { return isset($this->{$offset}) ? $this->{$offset} : $this->__get($offset); } /** @return void */ #[\ReturnTypeWillChange] public function offsetSet($offset, $value) { if (\property_exists($this, $offset)) { $this->{$offset} = $value; } else { $this->modelData[$offset] = $value; $this->processed[$offset] = \true; } } /** @return void */ #[\ReturnTypeWillChange] public function offsetUnset($offset) { unset($this->modelData[$offset]); } protected function keyType($key) { $keyType = $key . "Type"; // ensure keyType is a valid class if (\property_exists($this, $keyType) && \class_exists($this->{$keyType})) { return $this->{$keyType}; } } protected function dataType($key) { $dataType = $key . "DataType"; if (\property_exists($this, $dataType)) { return $this->{$dataType}; } } public function __isset($key) { return isset($this->modelData[$key]); } public function __unset($key) { unset($this->modelData[$key]); } /** * Convert a string to camelCase * @param string $value * @return string */ private function camelCase($value) { $value = \ucwords(\str_replace(array('-', '_'), ' ', $value)); $value = \str_replace(' ', '', $value); $value[0] = \strtolower($value[0]); return $value; } } PK!*7google/apiclient/src/AuthHandler/Guzzle6AuthHandler.phpnu[cache = $cache; $this->cacheConfig = $cacheConfig; } public function attachCredentials(\Google\Site_Kit_Dependencies\GuzzleHttp\ClientInterface $http, \Google\Site_Kit_Dependencies\Google\Auth\CredentialsLoader $credentials, callable $tokenCallback = null) { // use the provided cache if ($this->cache) { $credentials = new \Google\Site_Kit_Dependencies\Google\Auth\FetchAuthTokenCache($credentials, $this->cacheConfig, $this->cache); } return $this->attachCredentialsCache($http, $credentials, $tokenCallback); } public function attachCredentialsCache(\Google\Site_Kit_Dependencies\GuzzleHttp\ClientInterface $http, \Google\Site_Kit_Dependencies\Google\Auth\FetchAuthTokenCache $credentials, callable $tokenCallback = null) { // if we end up needing to make an HTTP request to retrieve credentials, we // can use our existing one, but we need to throw exceptions so the error // bubbles up. $authHttp = $this->createAuthHttp($http); $authHttpHandler = \Google\Site_Kit_Dependencies\Google\Auth\HttpHandler\HttpHandlerFactory::build($authHttp); $middleware = new \Google\Site_Kit_Dependencies\Google\Auth\Middleware\AuthTokenMiddleware($credentials, $authHttpHandler, $tokenCallback); $config = $http->getConfig(); $config['handler']->remove('google_auth'); $config['handler']->push($middleware, 'google_auth'); $config['auth'] = 'google_auth'; $http = new \Google\Site_Kit_Dependencies\GuzzleHttp\Client($config); return $http; } public function attachToken(\Google\Site_Kit_Dependencies\GuzzleHttp\ClientInterface $http, array $token, array $scopes) { $tokenFunc = function ($scopes) use($token) { return $token['access_token']; }; $middleware = new \Google\Site_Kit_Dependencies\Google\Auth\Middleware\ScopedAccessTokenMiddleware($tokenFunc, $scopes, $this->cacheConfig, $this->cache); $config = $http->getConfig(); $config['handler']->remove('google_auth'); $config['handler']->push($middleware, 'google_auth'); $config['auth'] = 'scoped'; $http = new \Google\Site_Kit_Dependencies\GuzzleHttp\Client($config); return $http; } public function attachKey(\Google\Site_Kit_Dependencies\GuzzleHttp\ClientInterface $http, $key) { $middleware = new \Google\Site_Kit_Dependencies\Google\Auth\Middleware\SimpleMiddleware(['key' => $key]); $config = $http->getConfig(); $config['handler']->remove('google_auth'); $config['handler']->push($middleware, 'google_auth'); $config['auth'] = 'simple'; $http = new \Google\Site_Kit_Dependencies\GuzzleHttp\Client($config); return $http; } private function createAuthHttp(\Google\Site_Kit_Dependencies\GuzzleHttp\ClientInterface $http) { return new \Google\Site_Kit_Dependencies\GuzzleHttp\Client(['base_uri' => $http->getConfig('base_uri'), 'http_errors' => \true, 'verify' => $http->getConfig('verify'), 'proxy' => $http->getConfig('proxy')]); } } PK!R-  7google/apiclient/src/AuthHandler/Guzzle7AuthHandler.phpnu[cache = $cache; $this->cacheConfig = $cacheConfig; } public function attachCredentials(\Google\Site_Kit_Dependencies\GuzzleHttp\ClientInterface $http, \Google\Site_Kit_Dependencies\Google\Auth\CredentialsLoader $credentials, callable $tokenCallback = null) { // use the provided cache if ($this->cache) { $credentials = new \Google\Site_Kit_Dependencies\Google\Auth\FetchAuthTokenCache($credentials, $this->cacheConfig, $this->cache); } return $this->attachCredentialsCache($http, $credentials, $tokenCallback); } public function attachCredentialsCache(\Google\Site_Kit_Dependencies\GuzzleHttp\ClientInterface $http, \Google\Site_Kit_Dependencies\Google\Auth\FetchAuthTokenCache $credentials, callable $tokenCallback = null) { // if we end up needing to make an HTTP request to retrieve credentials, we // can use our existing one, but we need to throw exceptions so the error // bubbles up. $authHttp = $this->createAuthHttp($http); $authHttpHandler = \Google\Site_Kit_Dependencies\Google\Auth\HttpHandler\HttpHandlerFactory::build($authHttp); $subscriber = new \Google\Site_Kit_Dependencies\Google\Auth\Subscriber\AuthTokenSubscriber($credentials, $authHttpHandler, $tokenCallback); $http->setDefaultOption('auth', 'google_auth'); $http->getEmitter()->attach($subscriber); return $http; } public function attachToken(\Google\Site_Kit_Dependencies\GuzzleHttp\ClientInterface $http, array $token, array $scopes) { $tokenFunc = function ($scopes) use($token) { return $token['access_token']; }; $subscriber = new \Google\Site_Kit_Dependencies\Google\Auth\Subscriber\ScopedAccessTokenSubscriber($tokenFunc, $scopes, $this->cacheConfig, $this->cache); $http->setDefaultOption('auth', 'scoped'); $http->getEmitter()->attach($subscriber); return $http; } public function attachKey(\Google\Site_Kit_Dependencies\GuzzleHttp\ClientInterface $http, $key) { $subscriber = new \Google\Site_Kit_Dependencies\Google\Auth\Subscriber\SimpleSubscriber(['key' => $key]); $http->setDefaultOption('auth', 'simple'); $http->getEmitter()->attach($subscriber); return $http; } private function createAuthHttp(\Google\Site_Kit_Dependencies\GuzzleHttp\ClientInterface $http) { return new \Google\Site_Kit_Dependencies\GuzzleHttp\Client(['base_url' => $http->getBaseUrl(), 'defaults' => ['exceptions' => \true, 'verify' => $http->getDefaultOption('verify'), 'proxy' => $http->getDefaultOption('proxy')]]); } } PK!\9*google/apiclient/src/Service/Exception.phpnu[= 0) { parent::__construct($message, $code, $previous); } else { parent::__construct($message, $code); } $this->errors = $errors; } /** * An example of the possible errors returned. * * { * "domain": "global", * "reason": "authError", * "message": "Invalid Credentials", * "locationType": "header", * "location": "Authorization", * } * * @return [{string, string}] List of errors return in an HTTP response or []. */ public function getErrors() { return $this->errors; } } PK!Kd*d*)google/apiclient/src/Service/Resource.phpnu[ array('type' => 'string', 'location' => 'query'), 'fields' => array('type' => 'string', 'location' => 'query'), 'trace' => array('type' => 'string', 'location' => 'query'), 'userIp' => array('type' => 'string', 'location' => 'query'), 'quotaUser' => array('type' => 'string', 'location' => 'query'), 'data' => array('type' => 'string', 'location' => 'body'), 'mimeType' => array('type' => 'string', 'location' => 'header'), 'uploadType' => array('type' => 'string', 'location' => 'query'), 'mediaUpload' => array('type' => 'complex', 'location' => 'query'), 'prettyPrint' => array('type' => 'string', 'location' => 'query')); /** @var string $rootUrl */ private $rootUrl; /** @var \Google\Client $client */ private $client; /** @var string $serviceName */ private $serviceName; /** @var string $servicePath */ private $servicePath; /** @var string $resourceName */ private $resourceName; /** @var array $methods */ private $methods; public function __construct($service, $serviceName, $resourceName, $resource) { $this->rootUrl = $service->rootUrl; $this->client = $service->getClient(); $this->servicePath = $service->servicePath; $this->serviceName = $serviceName; $this->resourceName = $resourceName; $this->methods = \is_array($resource) && isset($resource['methods']) ? $resource['methods'] : array($resourceName => $resource); } /** * TODO: This function needs simplifying. * @param $name * @param $arguments * @param $expectedClass - optional, the expected class name * @return mixed|$expectedClass|ResponseInterface|RequestInterface * @throws \Google\Exception */ public function call($name, $arguments, $expectedClass = null) { if (!isset($this->methods[$name])) { $this->client->getLogger()->error('Service method unknown', array('service' => $this->serviceName, 'resource' => $this->resourceName, 'method' => $name)); throw new \Google\Site_Kit_Dependencies\Google\Exception("Unknown function: " . "{$this->serviceName}->{$this->resourceName}->{$name}()"); } $method = $this->methods[$name]; $parameters = $arguments[0]; // postBody is a special case since it's not defined in the discovery // document as parameter, but we abuse the param entry for storing it. $postBody = null; if (isset($parameters['postBody'])) { if ($parameters['postBody'] instanceof \Google\Site_Kit_Dependencies\Google\Model) { // In the cases the post body is an existing object, we want // to use the smart method to create a simple object for // for JSONification. $parameters['postBody'] = $parameters['postBody']->toSimpleObject(); } else { if (\is_object($parameters['postBody'])) { // If the post body is another kind of object, we will try and // wrangle it into a sensible format. $parameters['postBody'] = $this->convertToArrayAndStripNulls($parameters['postBody']); } } $postBody = (array) $parameters['postBody']; unset($parameters['postBody']); } // TODO: optParams here probably should have been // handled already - this may well be redundant code. if (isset($parameters['optParams'])) { $optParams = $parameters['optParams']; unset($parameters['optParams']); $parameters = \array_merge($parameters, $optParams); } if (!isset($method['parameters'])) { $method['parameters'] = array(); } $method['parameters'] = \array_merge($this->stackParameters, $method['parameters']); foreach ($parameters as $key => $val) { if ($key != 'postBody' && !isset($method['parameters'][$key])) { $this->client->getLogger()->error('Service parameter unknown', array('service' => $this->serviceName, 'resource' => $this->resourceName, 'method' => $name, 'parameter' => $key)); throw new \Google\Site_Kit_Dependencies\Google\Exception("({$name}) unknown parameter: '{$key}'"); } } foreach ($method['parameters'] as $paramName => $paramSpec) { if (isset($paramSpec['required']) && $paramSpec['required'] && !isset($parameters[$paramName])) { $this->client->getLogger()->error('Service parameter missing', array('service' => $this->serviceName, 'resource' => $this->resourceName, 'method' => $name, 'parameter' => $paramName)); throw new \Google\Site_Kit_Dependencies\Google\Exception("({$name}) missing required param: '{$paramName}'"); } if (isset($parameters[$paramName])) { $value = $parameters[$paramName]; $parameters[$paramName] = $paramSpec; $parameters[$paramName]['value'] = $value; unset($parameters[$paramName]['required']); } else { // Ensure we don't pass nulls. unset($parameters[$paramName]); } } $this->client->getLogger()->info('Service Call', array('service' => $this->serviceName, 'resource' => $this->resourceName, 'method' => $name, 'arguments' => $parameters)); // build the service uri $url = $this->createRequestUri($method['path'], $parameters); // NOTE: because we're creating the request by hand, // and because the service has a rootUrl property // the "base_uri" of the Http Client is not accounted for $request = new \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Request($method['httpMethod'], $url, ['content-type' => 'application/json'], $postBody ? \json_encode($postBody) : ''); // support uploads if (isset($parameters['data'])) { $mimeType = isset($parameters['mimeType']) ? $parameters['mimeType']['value'] : 'application/octet-stream'; $data = $parameters['data']['value']; $upload = new \Google\Site_Kit_Dependencies\Google\Http\MediaFileUpload($this->client, $request, $mimeType, $data); // pull down the modified request $request = $upload->getRequest(); } // if this is a media type, we will return the raw response // rather than using an expected class if (isset($parameters['alt']) && $parameters['alt']['value'] == 'media') { $expectedClass = null; } // if the client is marked for deferring, rather than // execute the request, return the response if ($this->client->shouldDefer()) { // @TODO find a better way to do this $request = $request->withHeader('X-Php-Expected-Class', $expectedClass); return $request; } return $this->client->execute($request, $expectedClass); } protected function convertToArrayAndStripNulls($o) { $o = (array) $o; foreach ($o as $k => $v) { if ($v === null) { unset($o[$k]); } elseif (\is_object($v) || \is_array($v)) { $o[$k] = $this->convertToArrayAndStripNulls($o[$k]); } } return $o; } /** * Parse/expand request parameters and create a fully qualified * request uri. * @static * @param string $restPath * @param array $params * @return string $requestUrl */ public function createRequestUri($restPath, $params) { // Override the default servicePath address if the $restPath use a / if ('/' == \substr($restPath, 0, 1)) { $requestUrl = \substr($restPath, 1); } else { $requestUrl = $this->servicePath . $restPath; } // code for leading slash if ($this->rootUrl) { if ('/' !== \substr($this->rootUrl, -1) && '/' !== \substr($requestUrl, 0, 1)) { $requestUrl = '/' . $requestUrl; } $requestUrl = $this->rootUrl . $requestUrl; } $uriTemplateVars = array(); $queryVars = array(); foreach ($params as $paramName => $paramSpec) { if ($paramSpec['type'] == 'boolean') { $paramSpec['value'] = $paramSpec['value'] ? 'true' : 'false'; } if ($paramSpec['location'] == 'path') { $uriTemplateVars[$paramName] = $paramSpec['value']; } else { if ($paramSpec['location'] == 'query') { if (\is_array($paramSpec['value'])) { foreach ($paramSpec['value'] as $value) { $queryVars[] = $paramName . '=' . \rawurlencode(\rawurldecode($value)); } } else { $queryVars[] = $paramName . '=' . \rawurlencode(\rawurldecode($paramSpec['value'])); } } } } if (\count($uriTemplateVars)) { $uriTemplateParser = new \Google\Site_Kit_Dependencies\Google\Utils\UriTemplate(); $requestUrl = $uriTemplateParser->parse($requestUrl, $uriTemplateVars); } if (\count($queryVars)) { $requestUrl .= '?' . \implode('&', $queryVars); } return $requestUrl; } } PK!6  'google/apiclient/src/Task/Exception.phpnu[getComposer(); $extra = $composer->getPackage()->getExtra(); $servicesToKeep = isset($extra['google/apiclient-services']) ? $extra['google/apiclient-services'] : []; if ($servicesToKeep) { $vendorDir = $composer->getConfig()->get('vendor-dir'); $serviceDir = \sprintf('%s/google/apiclient-services/src/Google/Service', $vendorDir); if (!\is_dir($serviceDir)) { // path for google/apiclient-services >= 0.200.0 $serviceDir = \sprintf('%s/google/apiclient-services/src', $vendorDir); } self::verifyServicesToKeep($serviceDir, $servicesToKeep); $finder = self::getServicesToRemove($serviceDir, $servicesToKeep); $filesystem = $filesystem ?: new \Google\Site_Kit_Dependencies\Symfony\Component\Filesystem\Filesystem(); if (0 !== ($count = \count($finder))) { $event->getIO()->write(\sprintf('Removing %s google services', $count)); foreach ($finder as $file) { $realpath = $file->getRealPath(); $filesystem->remove($realpath); $filesystem->remove($realpath . '.php'); } } } } /** * @throws InvalidArgumentException when the service doesn't exist */ private static function verifyServicesToKeep($serviceDir, array $servicesToKeep) { $finder = (new \Google\Site_Kit_Dependencies\Symfony\Component\Finder\Finder())->directories()->depth('== 0'); foreach ($servicesToKeep as $service) { if (!\preg_match('/^[a-zA-Z0-9]*$/', $service)) { throw new \InvalidArgumentException(\sprintf('Invalid Google service name "%s"', $service)); } try { $finder->in($serviceDir . '/' . $service); } catch (\InvalidArgumentException $e) { throw new \InvalidArgumentException(\sprintf('Google service "%s" does not exist or was removed previously', $service)); } } } private static function getServicesToRemove($serviceDir, array $servicesToKeep) { // find all files in the current directory return (new \Google\Site_Kit_Dependencies\Symfony\Component\Finder\Finder())->directories()->depth('== 0')->in($serviceDir)->exclude($servicesToKeep); } } PK!-  'google/apiclient/src/Task/Retryable.phpnu[ self::TASK_RETRY_ALWAYS, '503' => self::TASK_RETRY_ALWAYS, 'rateLimitExceeded' => self::TASK_RETRY_ALWAYS, 'userRateLimitExceeded' => self::TASK_RETRY_ALWAYS, 6 => self::TASK_RETRY_ALWAYS, // CURLE_COULDNT_RESOLVE_HOST 7 => self::TASK_RETRY_ALWAYS, // CURLE_COULDNT_CONNECT 28 => self::TASK_RETRY_ALWAYS, // CURLE_OPERATION_TIMEOUTED 35 => self::TASK_RETRY_ALWAYS, // CURLE_SSL_CONNECT_ERROR 52 => self::TASK_RETRY_ALWAYS, // CURLE_GOT_NOTHING 'lighthouseError' => self::TASK_RETRY_NEVER, ]; /** * Creates a new task runner with exponential backoff support. * * @param array $config The task runner config * @param string $name The name of the current task (used for logging) * @param callable $action The task to run and possibly retry * @param array $arguments The task arguments * @throws \Google\Task\Exception when misconfigured */ public function __construct($config, $name, $action, array $arguments = array()) { if (isset($config['initial_delay'])) { if ($config['initial_delay'] < 0) { throw new \Google\Site_Kit_Dependencies\Google\Task\Exception('Task configuration `initial_delay` must not be negative.'); } $this->delay = $config['initial_delay']; } if (isset($config['max_delay'])) { if ($config['max_delay'] <= 0) { throw new \Google\Site_Kit_Dependencies\Google\Task\Exception('Task configuration `max_delay` must be greater than 0.'); } $this->maxDelay = $config['max_delay']; } if (isset($config['factor'])) { if ($config['factor'] <= 0) { throw new \Google\Site_Kit_Dependencies\Google\Task\Exception('Task configuration `factor` must be greater than 0.'); } $this->factor = $config['factor']; } if (isset($config['jitter'])) { if ($config['jitter'] <= 0) { throw new \Google\Site_Kit_Dependencies\Google\Task\Exception('Task configuration `jitter` must be greater than 0.'); } $this->jitter = $config['jitter']; } if (isset($config['retries'])) { if ($config['retries'] < 0) { throw new \Google\Site_Kit_Dependencies\Google\Task\Exception('Task configuration `retries` must not be negative.'); } $this->maxAttempts += $config['retries']; } if (!\is_callable($action)) { throw new \Google\Site_Kit_Dependencies\Google\Task\Exception('Task argument `$action` must be a valid callable.'); } $this->action = $action; $this->arguments = $arguments; } /** * Checks if a retry can be attempted. * * @return boolean */ public function canAttempt() { return $this->attempts < $this->maxAttempts; } /** * Runs the task and (if applicable) automatically retries when errors occur. * * @return mixed * @throws \Google\Service\Exception on failure when no retries are available. */ public function run() { while ($this->attempt()) { try { return \call_user_func_array($this->action, $this->arguments); } catch (\Google\Site_Kit_Dependencies\Google\Service\Exception $exception) { $allowedRetries = $this->allowedRetries($exception->getCode(), $exception->getErrors()); if (!$this->canAttempt() || !$allowedRetries) { throw $exception; } if ($allowedRetries > 0) { $this->maxAttempts = \min($this->maxAttempts, $this->attempts + $allowedRetries); } } } } /** * Runs a task once, if possible. This is useful for bypassing the `run()` * loop. * * NOTE: If this is not the first attempt, this function will sleep in * accordance to the backoff configurations before running the task. * * @return boolean */ public function attempt() { if (!$this->canAttempt()) { return \false; } if ($this->attempts > 0) { $this->backOff(); } $this->attempts++; return \true; } /** * Sleeps in accordance to the backoff configurations. */ private function backOff() { $delay = $this->getDelay(); \usleep($delay * 1000000); } /** * Gets the delay (in seconds) for the current backoff period. * * @return float */ private function getDelay() { $jitter = $this->getJitter(); $factor = $this->attempts > 1 ? $this->factor + $jitter : 1 + \abs($jitter); return $this->delay = \min($this->maxDelay, $this->delay * $factor); } /** * Gets the current jitter (random number between -$this->jitter and * $this->jitter). * * @return float */ private function getJitter() { return $this->jitter * 2 * \mt_rand() / \mt_getrandmax() - $this->jitter; } /** * Gets the number of times the associated task can be retried. * * NOTE: -1 is returned if the task can be retried indefinitely * * @return integer */ public function allowedRetries($code, $errors = array()) { if (isset($this->retryMap[$code])) { return $this->retryMap[$code]; } if (!empty($errors) && isset($errors[0]['reason'], $this->retryMap[$errors[0]['reason']])) { return $this->retryMap[$errors[0]['reason']]; } return 0; } public function setRetryMap($retryMap) { $this->retryMap = $retryMap; } } PK!o"google/apiclient/src/Exception.phpnu[ 'Google\\Site_Kit_Dependencies\Google_Client', 'Google\\Site_Kit_Dependencies\\Google\\Service' => 'Google\\Site_Kit_Dependencies\Google_Service', 'Google\\Site_Kit_Dependencies\\Google\\AccessToken\\Revoke' => 'Google\\Site_Kit_Dependencies\Google_AccessToken_Revoke', 'Google\\Site_Kit_Dependencies\\Google\\AccessToken\\Verify' => 'Google\\Site_Kit_Dependencies\Google_AccessToken_Verify', 'Google\\Site_Kit_Dependencies\\Google\\Model' => 'Google\\Site_Kit_Dependencies\Google_Model', 'Google\\Site_Kit_Dependencies\\Google\\Utils\\UriTemplate' => 'Google\\Site_Kit_Dependencies\Google_Utils_UriTemplate', 'Google\\Site_Kit_Dependencies\\Google\\AuthHandler\\Guzzle6AuthHandler' => 'Google\\Site_Kit_Dependencies\Google_AuthHandler_Guzzle6AuthHandler', 'Google\\Site_Kit_Dependencies\\Google\\AuthHandler\\Guzzle7AuthHandler' => 'Google\\Site_Kit_Dependencies\Google_AuthHandler_Guzzle7AuthHandler', 'Google\\Site_Kit_Dependencies\\Google\\AuthHandler\\Guzzle5AuthHandler' => 'Google\\Site_Kit_Dependencies\Google_AuthHandler_Guzzle5AuthHandler', 'Google\\Site_Kit_Dependencies\\Google\\AuthHandler\\AuthHandlerFactory' => 'Google\\Site_Kit_Dependencies\Google_AuthHandler_AuthHandlerFactory', 'Google\\Site_Kit_Dependencies\\Google\\Http\\Batch' => 'Google\\Site_Kit_Dependencies\Google_Http_Batch', 'Google\\Site_Kit_Dependencies\\Google\\Http\\MediaFileUpload' => 'Google\\Site_Kit_Dependencies\Google_Http_MediaFileUpload', 'Google\\Site_Kit_Dependencies\\Google\\Http\\REST' => 'Google\\Site_Kit_Dependencies\Google_Http_REST', 'Google\\Site_Kit_Dependencies\\Google\\Task\\Retryable' => 'Google\\Site_Kit_Dependencies\Google_Task_Retryable', 'Google\\Site_Kit_Dependencies\\Google\\Task\\Exception' => 'Google\\Site_Kit_Dependencies\Google_Task_Exception', 'Google\\Site_Kit_Dependencies\\Google\\Task\\Runner' => 'Google\\Site_Kit_Dependencies\Google_Task_Runner', 'Google\\Site_Kit_Dependencies\\Google\\Collection' => 'Google\\Site_Kit_Dependencies\Google_Collection', 'Google\\Site_Kit_Dependencies\\Google\\Service\\Exception' => 'Google\\Site_Kit_Dependencies\Google_Service_Exception', 'Google\\Site_Kit_Dependencies\\Google\\Service\\Resource' => 'Google\\Site_Kit_Dependencies\Google_Service_Resource', 'Google\\Site_Kit_Dependencies\\Google\\Exception' => 'Google\\Site_Kit_Dependencies\Google_Exception']; foreach ($classMap as $class => $alias) { \class_alias($class, $alias); } /** * This class needs to be defined explicitly as scripts must be recognized by * the autoloader. */ class Google_Task_Composer extends \Google\Site_Kit_Dependencies\Google\Task\Composer { } if (\false) { class Google_AccessToken_Revoke extends \Google\Site_Kit_Dependencies\Google\AccessToken\Revoke { } class Google_AccessToken_Verify extends \Google\Site_Kit_Dependencies\Google\AccessToken\Verify { } class Google_AuthHandler_AuthHandlerFactory extends \Google\Site_Kit_Dependencies\Google\AuthHandler\AuthHandlerFactory { } class Google_AuthHandler_Guzzle5AuthHandler extends \Google\Site_Kit_Dependencies\Google\AuthHandler\Guzzle5AuthHandler { } class Google_AuthHandler_Guzzle6AuthHandler extends \Google\Site_Kit_Dependencies\Google\AuthHandler\Guzzle6AuthHandler { } class Google_AuthHandler_Guzzle7AuthHandler extends \Google\Site_Kit_Dependencies\Google\AuthHandler\Guzzle7AuthHandler { } class Google_Client extends \Google\Site_Kit_Dependencies\Google\Client { } class Google_Collection extends \Google\Site_Kit_Dependencies\Google\Collection { } class Google_Exception extends \Google\Site_Kit_Dependencies\Google\Exception { } class Google_Http_Batch extends \Google\Site_Kit_Dependencies\Google\Http\Batch { } class Google_Http_MediaFileUpload extends \Google\Site_Kit_Dependencies\Google\Http\MediaFileUpload { } class Google_Http_REST extends \Google\Site_Kit_Dependencies\Google\Http\REST { } class Google_Model extends \Google\Site_Kit_Dependencies\Google\Model { } class Google_Service extends \Google\Site_Kit_Dependencies\Google\Service { } class Google_Service_Exception extends \Google\Site_Kit_Dependencies\Google\Service\Exception { } class Google_Service_Resource extends \Google\Site_Kit_Dependencies\Google\Service\Resource { } class Google_Task_Exception extends \Google\Site_Kit_Dependencies\Google\Task\Exception { } interface Google_Task_Retryable extends \Google\Site_Kit_Dependencies\Google\Task\Retryable { } class Google_Task_Runner extends \Google\Site_Kit_Dependencies\Google\Task\Runner { } class Google_Utils_UriTemplate extends \Google\Site_Kit_Dependencies\Google\Utils\UriTemplate { } } PK!z))*google/apiclient/src/Utils/UriTemplate.phpnu[ "reserved", "/" => "segments", "." => "dotprefix", "#" => "fragment", ";" => "semicolon", "?" => "form", "&" => "continuation"); /** * @var reserved array * These are the characters which should not be URL encoded in reserved * strings. */ private $reserved = array("=", ",", "!", "@", "|", ":", "/", "?", "#", "[", "]", '$', "&", "'", "(", ")", "*", "+", ";"); private $reservedEncoded = array("%3D", "%2C", "%21", "%40", "%7C", "%3A", "%2F", "%3F", "%23", "%5B", "%5D", "%24", "%26", "%27", "%28", "%29", "%2A", "%2B", "%3B"); public function parse($string, array $parameters) { return $this->resolveNextSection($string, $parameters); } /** * This function finds the first matching {...} block and * executes the replacement. It then calls itself to find * subsequent blocks, if any. */ private function resolveNextSection($string, $parameters) { $start = \strpos($string, "{"); if ($start === \false) { return $string; } $end = \strpos($string, "}"); if ($end === \false) { return $string; } $string = $this->replace($string, $start, $end, $parameters); return $this->resolveNextSection($string, $parameters); } private function replace($string, $start, $end, $parameters) { // We know a data block will have {} round it, so we can strip that. $data = \substr($string, $start + 1, $end - $start - 1); // If the first character is one of the reserved operators, it effects // the processing of the stream. if (isset($this->operators[$data[0]])) { $op = $this->operators[$data[0]]; $data = \substr($data, 1); $prefix = ""; $prefix_on_missing = \false; switch ($op) { case "reserved": // Reserved means certain characters should not be URL encoded $data = $this->replaceVars($data, $parameters, ",", null, \true); break; case "fragment": // Comma separated with fragment prefix. Bare values only. $prefix = "#"; $prefix_on_missing = \true; $data = $this->replaceVars($data, $parameters, ",", null, \true); break; case "segments": // Slash separated data. Bare values only. $prefix = "/"; $data = $this->replaceVars($data, $parameters, "/"); break; case "dotprefix": // Dot separated data. Bare values only. $prefix = "."; $prefix_on_missing = \true; $data = $this->replaceVars($data, $parameters, "."); break; case "semicolon": // Semicolon prefixed and separated. Uses the key name $prefix = ";"; $data = $this->replaceVars($data, $parameters, ";", "=", \false, \true, \false); break; case "form": // Standard URL format. Uses the key name $prefix = "?"; $data = $this->replaceVars($data, $parameters, "&", "="); break; case "continuation": // Standard URL, but with leading ampersand. Uses key name. $prefix = "&"; $data = $this->replaceVars($data, $parameters, "&", "="); break; } // Add the initial prefix character if data is valid. if ($data || $data !== \false && $prefix_on_missing) { $data = $prefix . $data; } } else { // If no operator we replace with the defaults. $data = $this->replaceVars($data, $parameters); } // This is chops out the {...} and replaces with the new section. return \substr($string, 0, $start) . $data . \substr($string, $end + 1); } private function replaceVars($section, $parameters, $sep = ",", $combine = null, $reserved = \false, $tag_empty = \false, $combine_on_empty = \true) { if (\strpos($section, ",") === \false) { // If we only have a single value, we can immediately process. return $this->combine($section, $parameters, $sep, $combine, $reserved, $tag_empty, $combine_on_empty); } else { // If we have multiple values, we need to split and loop over them. // Each is treated individually, then glued together with the // separator character. $vars = \explode(",", $section); return $this->combineList( $vars, $sep, $parameters, $combine, $reserved, \false, // Never emit empty strings in multi-param replacements $combine_on_empty ); } } public function combine($key, $parameters, $sep, $combine, $reserved, $tag_empty, $combine_on_empty) { $length = \false; $explode = \false; $skip_final_combine = \false; $value = \false; // Check for length restriction. if (\strpos($key, ":") !== \false) { list($key, $length) = \explode(":", $key); } // Check for explode parameter. if ($key[\strlen($key) - 1] == "*") { $explode = \true; $key = \substr($key, 0, -1); $skip_final_combine = \true; } // Define the list separator. $list_sep = $explode ? $sep : ","; if (isset($parameters[$key])) { $data_type = $this->getDataType($parameters[$key]); switch ($data_type) { case self::TYPE_SCALAR: $value = $this->getValue($parameters[$key], $length); break; case self::TYPE_LIST: $values = array(); foreach ($parameters[$key] as $pkey => $pvalue) { $pvalue = $this->getValue($pvalue, $length); if ($combine && $explode) { $values[$pkey] = $key . $combine . $pvalue; } else { $values[$pkey] = $pvalue; } } $value = \implode($list_sep, $values); if ($value == '') { return ''; } break; case self::TYPE_MAP: $values = array(); foreach ($parameters[$key] as $pkey => $pvalue) { $pvalue = $this->getValue($pvalue, $length); if ($explode) { $pkey = $this->getValue($pkey, $length); $values[] = $pkey . "=" . $pvalue; // Explode triggers = combine. } else { $values[] = $pkey; $values[] = $pvalue; } } $value = \implode($list_sep, $values); if ($value == '') { return \false; } break; } } else { if ($tag_empty) { // If we are just indicating empty values with their key name, return that. return $key; } else { // Otherwise we can skip this variable due to not being defined. return \false; } } if ($reserved) { $value = \str_replace($this->reservedEncoded, $this->reserved, $value); } // If we do not need to include the key name, we just return the raw // value. if (!$combine || $skip_final_combine) { return $value; } // Else we combine the key name: foo=bar, if value is not the empty string. return $key . ($value != '' || $combine_on_empty ? $combine . $value : ''); } /** * Return the type of a passed in value */ private function getDataType($data) { if (\is_array($data)) { \reset($data); if (\key($data) !== 0) { return self::TYPE_MAP; } return self::TYPE_LIST; } return self::TYPE_SCALAR; } /** * Utility function that merges multiple combine calls * for multi-key templates. */ private function combineList($vars, $sep, $parameters, $combine, $reserved, $tag_empty, $combine_on_empty) { $ret = array(); foreach ($vars as $var) { $response = $this->combine($var, $parameters, $sep, $combine, $reserved, $tag_empty, $combine_on_empty); if ($response === \false) { continue; } $ret[] = $response; } return \implode($sep, $ret); } /** * Utility function to encode and trim values */ private function getValue($value, $length) { if ($length) { $value = \substr($value, 0, $length); } $value = \rawurlencode($value); return $value; } } PK!Dk((+google/apiclient/src/AccessToken/Verify.phpnu[http = $http; $this->cache = $cache; $this->jwt = $jwt ?: $this->getJwtService(); } /** * Verifies an id token and returns the authenticated apiLoginTicket. * Throws an exception if the id token is not valid. * The audience parameter can be used to control which id tokens are * accepted. By default, the id token must have been issued to this OAuth2 client. * * @param string $idToken the ID token in JWT format * @param string $audience Optional. The audience to verify against JWt "aud" * @return array the token payload, if successful */ public function verifyIdToken($idToken, $audience = null) { if (empty($idToken)) { throw new \LogicException('id_token cannot be null'); } // set phpseclib constants if applicable $this->setPhpsecConstants(); // Check signature $certs = $this->getFederatedSignOnCerts(); foreach ($certs as $cert) { try { $payload = $this->jwt->decode($idToken, $this->getPublicKey($cert), array('RS256')); if (\property_exists($payload, 'aud')) { if ($audience && $payload->aud != $audience) { return \false; } } // support HTTP and HTTPS issuers // @see https://developers.google.com/identity/sign-in/web/backend-auth $issuers = array(self::OAUTH2_ISSUER, self::OAUTH2_ISSUER_HTTPS); if (!isset($payload->iss) || !\in_array($payload->iss, $issuers)) { return \false; } return (array) $payload; } catch (\Google\Site_Kit_Dependencies\ExpiredException $e) { return \false; } catch (\Google\Site_Kit_Dependencies\Firebase\JWT\ExpiredException $e) { return \false; } catch (\Google\Site_Kit_Dependencies\Firebase\JWT\SignatureInvalidException $e) { // continue } catch (\DomainException $e) { // continue } } return \false; } private function getCache() { return $this->cache; } /** * Retrieve and cache a certificates file. * * @param $url string location * @throws \Google\Exception * @return array certificates */ private function retrieveCertsFromLocation($url) { // If we're retrieving a local file, just grab it. if (0 !== \strpos($url, 'http')) { if (!($file = \file_get_contents($url))) { throw new \Google\Site_Kit_Dependencies\Google\Exception("Failed to retrieve verification certificates: '" . $url . "'."); } return \json_decode($file, \true); } $response = $this->http->get($url); if ($response->getStatusCode() == 200) { return \json_decode((string) $response->getBody(), \true); } throw new \Google\Site_Kit_Dependencies\Google\Exception(\sprintf('Failed to retrieve verification certificates: "%s".', $response->getBody()->getContents()), $response->getStatusCode()); } // Gets federated sign-on certificates to use for verifying identity tokens. // Returns certs as array structure, where keys are key ids, and values // are PEM encoded certificates. private function getFederatedSignOnCerts() { $certs = null; if ($cache = $this->getCache()) { $cacheItem = $cache->getItem('federated_signon_certs_v3'); $certs = $cacheItem->get(); } if (!$certs) { $certs = $this->retrieveCertsFromLocation(self::FEDERATED_SIGNON_CERT_URL); if ($cache) { $cacheItem->expiresAt(new \DateTime('+1 hour')); $cacheItem->set($certs); $cache->save($cacheItem); } } if (!isset($certs['keys'])) { throw new \Google\Site_Kit_Dependencies\Google\AccessToken\InvalidArgumentException('federated sign-on certs expects "keys" to be set'); } return $certs['keys']; } private function getJwtService() { $jwtClass = 'JWT'; if (\class_exists('Google\\Site_Kit_Dependencies\\Firebase\\JWT\\JWT')) { $jwtClass = 'Google\\Site_Kit_Dependencies\\Firebase\\JWT\\JWT'; } if (\property_exists($jwtClass, 'leeway') && $jwtClass::$leeway < 1) { // Ensures JWT leeway is at least 1 // @see https://github.com/google/google-api-php-client/issues/827 $jwtClass::$leeway = 1; } return new $jwtClass(); } private function getPublicKey($cert) { $bigIntClass = $this->getBigIntClass(); $modulus = new $bigIntClass($this->jwt->urlsafeB64Decode($cert['n']), 256); $exponent = new $bigIntClass($this->jwt->urlsafeB64Decode($cert['e']), 256); $component = array('n' => $modulus, 'e' => $exponent); if (\class_exists('Google\\Site_Kit_Dependencies\\phpseclib3\\Crypt\\RSA\\PublicKey')) { /** @var PublicKey $loader */ $loader = \Google\Site_Kit_Dependencies\phpseclib3\Crypt\PublicKeyLoader::load($component); return $loader->toString('PKCS8'); } $rsaClass = $this->getRsaClass(); $rsa = new $rsaClass(); $rsa->loadKey($component); return $rsa->getPublicKey(); } private function getRsaClass() { if (\class_exists('Google\\Site_Kit_Dependencies\\phpseclib3\\Crypt\\RSA')) { return 'Google\\Site_Kit_Dependencies\\phpseclib3\\Crypt\\RSA'; } if (\class_exists('Google\\Site_Kit_Dependencies\\phpseclib\\Crypt\\RSA')) { return 'Google\\Site_Kit_Dependencies\\phpseclib\\Crypt\\RSA'; } return 'Crypt_RSA'; } private function getBigIntClass() { if (\class_exists('Google\\Site_Kit_Dependencies\\phpseclib3\\Math\\BigInteger')) { return 'Google\\Site_Kit_Dependencies\\phpseclib3\\Math\\BigInteger'; } if (\class_exists('Google\\Site_Kit_Dependencies\\phpseclib\\Math\\BigInteger')) { return 'Google\\Site_Kit_Dependencies\\phpseclib\\Math\\BigInteger'; } return 'Math_BigInteger'; } private function getOpenSslConstant() { if (\class_exists('Google\\Site_Kit_Dependencies\\phpseclib3\\Crypt\\AES')) { return 'phpseclib3\\Crypt\\AES::ENGINE_OPENSSL'; } if (\class_exists('Google\\Site_Kit_Dependencies\\phpseclib\\Crypt\\RSA')) { return 'phpseclib\\Crypt\\RSA::MODE_OPENSSL'; } if (\class_exists('Google\\Site_Kit_Dependencies\\Crypt_RSA')) { return 'CRYPT_RSA_MODE_OPENSSL'; } throw new \Exception('Cannot find RSA class'); } /** * phpseclib calls "phpinfo" by default, which requires special * whitelisting in the AppEngine VM environment. This function * sets constants to bypass the need for phpseclib to check phpinfo * * @see phpseclib/Math/BigInteger * @see https://github.com/GoogleCloudPlatform/getting-started-php/issues/85 */ private function setPhpsecConstants() { if (\filter_var(\getenv('GAE_VM'), \FILTER_VALIDATE_BOOLEAN)) { if (!\defined('Google\\Site_Kit_Dependencies\\MATH_BIGINTEGER_OPENSSL_ENABLED')) { \define('Google\\Site_Kit_Dependencies\\MATH_BIGINTEGER_OPENSSL_ENABLED', \true); } if (!\defined('Google\\Site_Kit_Dependencies\\CRYPT_RSA_MODE')) { \define('Google\\Site_Kit_Dependencies\\CRYPT_RSA_MODE', \constant($this->getOpenSslConstant())); } } } } PK!8F F +google/apiclient/src/AccessToken/Revoke.phpnu[http = $http; } /** * Revoke an OAuth2 access token or refresh token. This method will revoke the current access * token, if a token isn't provided. * * @param string|array $token The token (access token or a refresh token) that should be revoked. * @return boolean Returns True if the revocation was successful, otherwise False. */ public function revokeToken($token) { if (\is_array($token)) { if (isset($token['refresh_token'])) { $token = $token['refresh_token']; } else { $token = $token['access_token']; } } $body = \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Utils::streamFor(\http_build_query(array('token' => $token))); $request = new \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Request('POST', \Google\Site_Kit_Dependencies\Google\Client::OAUTH2_REVOKE_URI, ['Cache-Control' => 'no-store', 'Content-Type' => 'application/x-www-form-urlencoded'], $body); $httpHandler = \Google\Site_Kit_Dependencies\Google\Auth\HttpHandler\HttpHandlerFactory::build($this->http); $response = $httpHandler($request); return $response->getStatusCode() == 200; } } PK!ܽ¤ #google/apiclient/src/Collection.phpnu[{$this->collection_key}) && \is_array($this->{$this->collection_key})) { \reset($this->{$this->collection_key}); } } /** @return mixed */ #[\ReturnTypeWillChange] public function current() { $this->coerceType($this->key()); if (\is_array($this->{$this->collection_key})) { return \current($this->{$this->collection_key}); } } /** @return mixed */ #[\ReturnTypeWillChange] public function key() { if (isset($this->{$this->collection_key}) && \is_array($this->{$this->collection_key})) { return \key($this->{$this->collection_key}); } } /** @return void */ #[\ReturnTypeWillChange] public function next() { return \next($this->{$this->collection_key}); } /** @return bool */ #[\ReturnTypeWillChange] public function valid() { $key = $this->key(); return $key !== null && $key !== \false; } /** @return int */ #[\ReturnTypeWillChange] public function count() { if (!isset($this->{$this->collection_key})) { return 0; } return \count($this->{$this->collection_key}); } /** @return bool */ public function offsetExists($offset) { if (!\is_numeric($offset)) { return parent::offsetExists($offset); } return isset($this->{$this->collection_key}[$offset]); } /** @return mixed */ public function offsetGet($offset) { if (!\is_numeric($offset)) { return parent::offsetGet($offset); } $this->coerceType($offset); return $this->{$this->collection_key}[$offset]; } /** @return void */ public function offsetSet($offset, $value) { if (!\is_numeric($offset)) { parent::offsetSet($offset, $value); } $this->{$this->collection_key}[$offset] = $value; } /** @return void */ public function offsetUnset($offset) { if (!\is_numeric($offset)) { parent::offsetUnset($offset); } unset($this->{$this->collection_key}[$offset]); } private function coerceType($offset) { $keyType = $this->keyType($this->collection_key); if ($keyType && !\is_object($this->{$this->collection_key}[$offset])) { $this->{$this->collection_key}[$offset] = new $keyType($this->{$this->collection_key}[$offset]); } } } PK!Drgoogle/apiclient/src/Client.phpnu[config = \array_merge([ 'application_name' => '', // Don't change these unless you're working against a special development // or testing environment. 'base_path' => self::API_BASE_PATH, // https://developers.google.com/console 'client_id' => '', 'client_secret' => '', // Can be a path to JSON credentials or an array representing those // credentials (@see Google\Client::setAuthConfig), or an instance of // Google\Auth\CredentialsLoader. 'credentials' => null, // @see Google\Client::setScopes 'scopes' => null, // Sets X-Goog-User-Project, which specifies a user project to bill // for access charges associated with the request 'quota_project' => null, 'redirect_uri' => null, 'state' => null, // Simple API access key, also from the API console. Ensure you get // a Server key, and not a Browser key. 'developer_key' => '', // For use with Google Cloud Platform // fetch the ApplicationDefaultCredentials, if applicable // @see https://developers.google.com/identity/protocols/application-default-credentials 'use_application_default_credentials' => \false, 'signing_key' => null, 'signing_algorithm' => null, 'subject' => null, // Other OAuth2 parameters. 'hd' => '', 'prompt' => '', 'openid.realm' => '', 'include_granted_scopes' => null, 'login_hint' => '', 'request_visible_actions' => '', 'access_type' => 'online', 'approval_prompt' => 'auto', // Task Runner retry configuration // @see Google\Task\Runner 'retry' => array(), 'retry_map' => null, // Cache class implementing Psr\Cache\CacheItemPoolInterface. // Defaults to Google\Auth\Cache\MemoryCacheItemPool. 'cache' => null, // cache config for downstream auth caching 'cache_config' => [], // function to be called when an access token is fetched // follows the signature function ($cacheKey, $accessToken) 'token_callback' => null, // Service class used in Google\Client::verifyIdToken. // Explicitly pass this in to avoid setting JWT::$leeway 'jwt' => null, // Setting api_format_v2 will return more detailed error messages // from certain APIs. 'api_format_v2' => \false, ], $config); if (!\is_null($this->config['credentials'])) { if ($this->config['credentials'] instanceof \Google\Site_Kit_Dependencies\Google\Auth\CredentialsLoader) { $this->credentials = $this->config['credentials']; } else { $this->setAuthConfig($this->config['credentials']); } unset($this->config['credentials']); } if (!\is_null($this->config['scopes'])) { $this->setScopes($this->config['scopes']); unset($this->config['scopes']); } // Set a default token callback to update the in-memory access token if (\is_null($this->config['token_callback'])) { $this->config['token_callback'] = function ($cacheKey, $newAccessToken) { $this->setAccessToken([ 'access_token' => $newAccessToken, 'expires_in' => 3600, // Google default 'created' => \time(), ]); }; } if (!\is_null($this->config['cache'])) { $this->setCache($this->config['cache']); unset($this->config['cache']); } } /** * Get a string containing the version of the library. * * @return string */ public function getLibraryVersion() { return self::LIBVER; } /** * For backwards compatibility * alias for fetchAccessTokenWithAuthCode * * @param $code string code from accounts.google.com * @return array access token * @deprecated */ public function authenticate($code) { return $this->fetchAccessTokenWithAuthCode($code); } /** * Attempt to exchange a code for an valid authentication token. * Helper wrapped around the OAuth 2.0 implementation. * * @param $code string code from accounts.google.com * @return array access token */ public function fetchAccessTokenWithAuthCode($code) { if (\strlen($code) == 0) { throw new \InvalidArgumentException("Invalid code"); } $auth = $this->getOAuth2Service(); $auth->setCode($code); $auth->setRedirectUri($this->getRedirectUri()); $httpHandler = \Google\Site_Kit_Dependencies\Google\Auth\HttpHandler\HttpHandlerFactory::build($this->getHttpClient()); $creds = $auth->fetchAuthToken($httpHandler); if ($creds && isset($creds['access_token'])) { $creds['created'] = \time(); $this->setAccessToken($creds); } return $creds; } /** * For backwards compatibility * alias for fetchAccessTokenWithAssertion * * @return array access token * @deprecated */ public function refreshTokenWithAssertion() { return $this->fetchAccessTokenWithAssertion(); } /** * Fetches a fresh access token with a given assertion token. * @param ClientInterface $authHttp optional. * @return array access token */ public function fetchAccessTokenWithAssertion(\Google\Site_Kit_Dependencies\GuzzleHttp\ClientInterface $authHttp = null) { if (!$this->isUsingApplicationDefaultCredentials()) { throw new \DomainException('set the JSON service account credentials using' . ' Google\\Client::setAuthConfig or set the path to your JSON file' . ' with the "GOOGLE_APPLICATION_CREDENTIALS" environment variable' . ' and call Google\\Client::useApplicationDefaultCredentials to' . ' refresh a token with assertion.'); } $this->getLogger()->log('info', 'OAuth2 access token refresh with Signed JWT assertion grants.'); $credentials = $this->createApplicationDefaultCredentials(); $httpHandler = \Google\Site_Kit_Dependencies\Google\Auth\HttpHandler\HttpHandlerFactory::build($authHttp); $creds = $credentials->fetchAuthToken($httpHandler); if ($creds && isset($creds['access_token'])) { $creds['created'] = \time(); $this->setAccessToken($creds); } return $creds; } /** * For backwards compatibility * alias for fetchAccessTokenWithRefreshToken * * @param string $refreshToken * @return array access token */ public function refreshToken($refreshToken) { return $this->fetchAccessTokenWithRefreshToken($refreshToken); } /** * Fetches a fresh OAuth 2.0 access token with the given refresh token. * @param string $refreshToken * @return array access token */ public function fetchAccessTokenWithRefreshToken($refreshToken = null) { if (null === $refreshToken) { if (!isset($this->token['refresh_token'])) { throw new \LogicException('refresh token must be passed in or set as part of setAccessToken'); } $refreshToken = $this->token['refresh_token']; } $this->getLogger()->info('OAuth2 access token refresh'); $auth = $this->getOAuth2Service(); $auth->setRefreshToken($refreshToken); $httpHandler = \Google\Site_Kit_Dependencies\Google\Auth\HttpHandler\HttpHandlerFactory::build($this->getHttpClient()); $creds = $auth->fetchAuthToken($httpHandler); if ($creds && isset($creds['access_token'])) { $creds['created'] = \time(); if (!isset($creds['refresh_token'])) { $creds['refresh_token'] = $refreshToken; } $this->setAccessToken($creds); } return $creds; } /** * Create a URL to obtain user authorization. * The authorization endpoint allows the user to first * authenticate, and then grant/deny the access request. * @param string|array $scope The scope is expressed as an array or list of space-delimited strings. * @return string */ public function createAuthUrl($scope = null) { if (empty($scope)) { $scope = $this->prepareScopes(); } if (\is_array($scope)) { $scope = \implode(' ', $scope); } // only accept one of prompt or approval_prompt $approvalPrompt = $this->config['prompt'] ? null : $this->config['approval_prompt']; // include_granted_scopes should be string "true", string "false", or null $includeGrantedScopes = $this->config['include_granted_scopes'] === null ? null : \var_export($this->config['include_granted_scopes'], \true); $params = \array_filter(['access_type' => $this->config['access_type'], 'approval_prompt' => $approvalPrompt, 'hd' => $this->config['hd'], 'include_granted_scopes' => $includeGrantedScopes, 'login_hint' => $this->config['login_hint'], 'openid.realm' => $this->config['openid.realm'], 'prompt' => $this->config['prompt'], 'response_type' => 'code', 'scope' => $scope, 'state' => $this->config['state']]); // If the list of scopes contains plus.login, add request_visible_actions // to auth URL. $rva = $this->config['request_visible_actions']; if (\strlen($rva) > 0 && \false !== \strpos($scope, 'plus.login')) { $params['request_visible_actions'] = $rva; } $auth = $this->getOAuth2Service(); return (string) $auth->buildFullAuthorizationUri($params); } /** * Adds auth listeners to the HTTP client based on the credentials * set in the Google API Client object * * @param ClientInterface $http the http client object. * @return ClientInterface the http client object */ public function authorize(\Google\Site_Kit_Dependencies\GuzzleHttp\ClientInterface $http = null) { $http = $http ?: $this->getHttpClient(); $authHandler = $this->getAuthHandler(); // These conditionals represent the decision tree for authentication // 1. Check if a Google\Auth\CredentialsLoader instance has been supplied via the "credentials" option // 2. Check for Application Default Credentials // 3a. Check for an Access Token // 3b. If access token exists but is expired, try to refresh it // 4. Check for API Key if ($this->credentials) { return $authHandler->attachCredentials($http, $this->credentials, $this->config['token_callback']); } if ($this->isUsingApplicationDefaultCredentials()) { $credentials = $this->createApplicationDefaultCredentials(); return $authHandler->attachCredentialsCache($http, $credentials, $this->config['token_callback']); } if ($token = $this->getAccessToken()) { $scopes = $this->prepareScopes(); // add refresh subscriber to request a new token if (isset($token['refresh_token']) && $this->isAccessTokenExpired()) { $credentials = $this->createUserRefreshCredentials($scopes, $token['refresh_token']); return $authHandler->attachCredentials($http, $credentials, $this->config['token_callback']); } return $authHandler->attachToken($http, $token, (array) $scopes); } if ($key = $this->config['developer_key']) { return $authHandler->attachKey($http, $key); } return $http; } /** * Set the configuration to use application default credentials for * authentication * * @see https://developers.google.com/identity/protocols/application-default-credentials * @param boolean $useAppCreds */ public function useApplicationDefaultCredentials($useAppCreds = \true) { $this->config['use_application_default_credentials'] = $useAppCreds; } /** * To prevent useApplicationDefaultCredentials from inappropriately being * called in a conditional * * @see https://developers.google.com/identity/protocols/application-default-credentials */ public function isUsingApplicationDefaultCredentials() { return $this->config['use_application_default_credentials']; } /** * Set the access token used for requests. * * Note that at the time requests are sent, tokens are cached. A token will be * cached for each combination of service and authentication scopes. If a * cache pool is not provided, creating a new instance of the client will * allow modification of access tokens. If a persistent cache pool is * provided, in order to change the access token, you must clear the cached * token by calling `$client->getCache()->clear()`. (Use caution in this case, * as calling `clear()` will remove all cache items, including any items not * related to Google API PHP Client.) * * @param string|array $token * @throws InvalidArgumentException */ public function setAccessToken($token) { if (\is_string($token)) { if ($json = \json_decode($token, \true)) { $token = $json; } else { // assume $token is just the token string $token = array('access_token' => $token); } } if ($token == null) { throw new \InvalidArgumentException('invalid json token'); } if (!isset($token['access_token'])) { throw new \InvalidArgumentException("Invalid token format"); } $this->token = $token; } public function getAccessToken() { return $this->token; } /** * @return string|null */ public function getRefreshToken() { if (isset($this->token['refresh_token'])) { return $this->token['refresh_token']; } return null; } /** * Returns if the access_token is expired. * @return bool Returns True if the access_token is expired. */ public function isAccessTokenExpired() { if (!$this->token) { return \true; } $created = 0; if (isset($this->token['created'])) { $created = $this->token['created']; } elseif (isset($this->token['id_token'])) { // check the ID token for "iat" // signature verification is not required here, as we are just // using this for convenience to save a round trip request // to the Google API server $idToken = $this->token['id_token']; if (\substr_count($idToken, '.') == 2) { $parts = \explode('.', $idToken); $payload = \json_decode(\base64_decode($parts[1]), \true); if ($payload && isset($payload['iat'])) { $created = $payload['iat']; } } } // If the token is set to expire in the next 30 seconds. return $created + ($this->token['expires_in'] - 30) < \time(); } /** * @deprecated See UPGRADING.md for more information */ public function getAuth() { throw new \BadMethodCallException('This function no longer exists. See UPGRADING.md for more information'); } /** * @deprecated See UPGRADING.md for more information */ public function setAuth($auth) { throw new \BadMethodCallException('This function no longer exists. See UPGRADING.md for more information'); } /** * Set the OAuth 2.0 Client ID. * @param string $clientId */ public function setClientId($clientId) { $this->config['client_id'] = $clientId; } public function getClientId() { return $this->config['client_id']; } /** * Set the OAuth 2.0 Client Secret. * @param string $clientSecret */ public function setClientSecret($clientSecret) { $this->config['client_secret'] = $clientSecret; } public function getClientSecret() { return $this->config['client_secret']; } /** * Set the OAuth 2.0 Redirect URI. * @param string $redirectUri */ public function setRedirectUri($redirectUri) { $this->config['redirect_uri'] = $redirectUri; } public function getRedirectUri() { return $this->config['redirect_uri']; } /** * Set OAuth 2.0 "state" parameter to achieve per-request customization. * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-22#section-3.1.2.2 * @param string $state */ public function setState($state) { $this->config['state'] = $state; } /** * @param string $accessType Possible values for access_type include: * {@code "offline"} to request offline access from the user. * {@code "online"} to request online access from the user. */ public function setAccessType($accessType) { $this->config['access_type'] = $accessType; } /** * @param string $approvalPrompt Possible values for approval_prompt include: * {@code "force"} to force the approval UI to appear. * {@code "auto"} to request auto-approval when possible. (This is the default value) */ public function setApprovalPrompt($approvalPrompt) { $this->config['approval_prompt'] = $approvalPrompt; } /** * Set the login hint, email address or sub id. * @param string $loginHint */ public function setLoginHint($loginHint) { $this->config['login_hint'] = $loginHint; } /** * Set the application name, this is included in the User-Agent HTTP header. * @param string $applicationName */ public function setApplicationName($applicationName) { $this->config['application_name'] = $applicationName; } /** * If 'plus.login' is included in the list of requested scopes, you can use * this method to define types of app activities that your app will write. * You can find a list of available types here: * @link https://developers.google.com/+/api/moment-types * * @param array $requestVisibleActions Array of app activity types */ public function setRequestVisibleActions($requestVisibleActions) { if (\is_array($requestVisibleActions)) { $requestVisibleActions = \implode(" ", $requestVisibleActions); } $this->config['request_visible_actions'] = $requestVisibleActions; } /** * Set the developer key to use, these are obtained through the API Console. * @see http://code.google.com/apis/console-help/#generatingdevkeys * @param string $developerKey */ public function setDeveloperKey($developerKey) { $this->config['developer_key'] = $developerKey; } /** * Set the hd (hosted domain) parameter streamlines the login process for * Google Apps hosted accounts. By including the domain of the user, you * restrict sign-in to accounts at that domain. * @param $hd string - the domain to use. */ public function setHostedDomain($hd) { $this->config['hd'] = $hd; } /** * Set the prompt hint. Valid values are none, consent and select_account. * If no value is specified and the user has not previously authorized * access, then the user is shown a consent screen. * @param $prompt string * {@code "none"} Do not display any authentication or consent screens. Must not be specified with other values. * {@code "consent"} Prompt the user for consent. * {@code "select_account"} Prompt the user to select an account. */ public function setPrompt($prompt) { $this->config['prompt'] = $prompt; } /** * openid.realm is a parameter from the OpenID 2.0 protocol, not from OAuth * 2.0. It is used in OpenID 2.0 requests to signify the URL-space for which * an authentication request is valid. * @param $realm string - the URL-space to use. */ public function setOpenidRealm($realm) { $this->config['openid.realm'] = $realm; } /** * If this is provided with the value true, and the authorization request is * granted, the authorization will include any previous authorizations * granted to this user/application combination for other scopes. * @param $include boolean - the URL-space to use. */ public function setIncludeGrantedScopes($include) { $this->config['include_granted_scopes'] = $include; } /** * sets function to be called when an access token is fetched * @param callable $tokenCallback - function ($cacheKey, $accessToken) */ public function setTokenCallback(callable $tokenCallback) { $this->config['token_callback'] = $tokenCallback; } /** * Revoke an OAuth2 access token or refresh token. This method will revoke the current access * token, if a token isn't provided. * * @param string|array|null $token The token (access token or a refresh token) that should be revoked. * @return boolean Returns True if the revocation was successful, otherwise False. */ public function revokeToken($token = null) { $tokenRevoker = new \Google\Site_Kit_Dependencies\Google\AccessToken\Revoke($this->getHttpClient()); return $tokenRevoker->revokeToken($token ?: $this->getAccessToken()); } /** * Verify an id_token. This method will verify the current id_token, if one * isn't provided. * * @throws LogicException If no token was provided and no token was set using `setAccessToken`. * @throws UnexpectedValueException If the token is not a valid JWT. * @param string|null $idToken The token (id_token) that should be verified. * @return array|false Returns the token payload as an array if the verification was * successful, false otherwise. */ public function verifyIdToken($idToken = null) { $tokenVerifier = new \Google\Site_Kit_Dependencies\Google\AccessToken\Verify($this->getHttpClient(), $this->getCache(), $this->config['jwt']); if (null === $idToken) { $token = $this->getAccessToken(); if (!isset($token['id_token'])) { throw new \LogicException('id_token must be passed in or set as part of setAccessToken'); } $idToken = $token['id_token']; } return $tokenVerifier->verifyIdToken($idToken, $this->getClientId()); } /** * Set the scopes to be requested. Must be called before createAuthUrl(). * Will remove any previously configured scopes. * @param string|array $scope_or_scopes, ie: * array( * 'https://www.googleapis.com/auth/plus.login', * 'https://www.googleapis.com/auth/moderator' * ); */ public function setScopes($scope_or_scopes) { $this->requestedScopes = array(); $this->addScope($scope_or_scopes); } /** * This functions adds a scope to be requested as part of the OAuth2.0 flow. * Will append any scopes not previously requested to the scope parameter. * A single string will be treated as a scope to request. An array of strings * will each be appended. * @param $scope_or_scopes string|array e.g. "profile" */ public function addScope($scope_or_scopes) { if (\is_string($scope_or_scopes) && !\in_array($scope_or_scopes, $this->requestedScopes)) { $this->requestedScopes[] = $scope_or_scopes; } else { if (\is_array($scope_or_scopes)) { foreach ($scope_or_scopes as $scope) { $this->addScope($scope); } } } } /** * Returns the list of scopes requested by the client * @return array the list of scopes * */ public function getScopes() { return $this->requestedScopes; } /** * @return string|null * @visible For Testing */ public function prepareScopes() { if (empty($this->requestedScopes)) { return null; } return \implode(' ', $this->requestedScopes); } /** * Helper method to execute deferred HTTP requests. * * @param $request RequestInterface|\Google\Http\Batch * @param string $expectedClass * @throws \Google\Exception * @return mixed|$expectedClass|ResponseInterface */ public function execute(\Google\Site_Kit_Dependencies\Psr\Http\Message\RequestInterface $request, $expectedClass = null) { $request = $request->withHeader('User-Agent', \sprintf('%s %s%s', $this->config['application_name'], self::USER_AGENT_SUFFIX, $this->getLibraryVersion()))->withHeader('x-goog-api-client', \sprintf('gl-php/%s gdcl/%s', \phpversion(), $this->getLibraryVersion())); if ($this->config['api_format_v2']) { $request = $request->withHeader('X-GOOG-API-FORMAT-VERSION', 2); } // call the authorize method // this is where most of the grunt work is done $http = $this->authorize(); return \Google\Site_Kit_Dependencies\Google\Http\REST::execute($http, $request, $expectedClass, $this->config['retry'], $this->config['retry_map']); } /** * Declare whether batch calls should be used. This may increase throughput * by making multiple requests in one connection. * * @param boolean $useBatch True if the batch support should * be enabled. Defaults to False. */ public function setUseBatch($useBatch) { // This is actually an alias for setDefer. $this->setDefer($useBatch); } /** * Are we running in Google AppEngine? * return bool */ public function isAppEngine() { return isset($_SERVER['SERVER_SOFTWARE']) && \strpos($_SERVER['SERVER_SOFTWARE'], 'Google App Engine') !== \false; } public function setConfig($name, $value) { $this->config[$name] = $value; } public function getConfig($name, $default = null) { return isset($this->config[$name]) ? $this->config[$name] : $default; } /** * For backwards compatibility * alias for setAuthConfig * * @param string $file the configuration file * @throws \Google\Exception * @deprecated */ public function setAuthConfigFile($file) { $this->setAuthConfig($file); } /** * Set the auth config from new or deprecated JSON config. * This structure should match the file downloaded from * the "Download JSON" button on in the Google Developer * Console. * @param string|array $config the configuration json * @throws \Google\Exception */ public function setAuthConfig($config) { if (\is_string($config)) { if (!\file_exists($config)) { throw new \InvalidArgumentException(\sprintf('file "%s" does not exist', $config)); } $json = \file_get_contents($config); if (!($config = \json_decode($json, \true))) { throw new \LogicException('invalid json for auth config'); } } $key = isset($config['installed']) ? 'installed' : 'web'; if (isset($config['type']) && $config['type'] == 'service_account') { // application default credentials $this->useApplicationDefaultCredentials(); // set the information from the config $this->setClientId($config['client_id']); $this->config['client_email'] = $config['client_email']; $this->config['signing_key'] = $config['private_key']; $this->config['signing_algorithm'] = 'HS256'; } elseif (isset($config[$key])) { // old-style $this->setClientId($config[$key]['client_id']); $this->setClientSecret($config[$key]['client_secret']); if (isset($config[$key]['redirect_uris'])) { $this->setRedirectUri($config[$key]['redirect_uris'][0]); } } else { // new-style $this->setClientId($config['client_id']); $this->setClientSecret($config['client_secret']); if (isset($config['redirect_uris'])) { $this->setRedirectUri($config['redirect_uris'][0]); } } } /** * Use when the service account has been delegated domain wide access. * * @param string $subject an email address account to impersonate */ public function setSubject($subject) { $this->config['subject'] = $subject; } /** * Declare whether making API calls should make the call immediately, or * return a request which can be called with ->execute(); * * @param boolean $defer True if calls should not be executed right away. */ public function setDefer($defer) { $this->deferExecution = $defer; } /** * Whether or not to return raw requests * @return boolean */ public function shouldDefer() { return $this->deferExecution; } /** * @return OAuth2 implementation */ public function getOAuth2Service() { if (!isset($this->auth)) { $this->auth = $this->createOAuth2Service(); } return $this->auth; } /** * create a default google auth object */ protected function createOAuth2Service() { $auth = new \Google\Site_Kit_Dependencies\Google\Auth\OAuth2(['clientId' => $this->getClientId(), 'clientSecret' => $this->getClientSecret(), 'authorizationUri' => self::OAUTH2_AUTH_URL, 'tokenCredentialUri' => self::OAUTH2_TOKEN_URI, 'redirectUri' => $this->getRedirectUri(), 'issuer' => $this->config['client_id'], 'signingKey' => $this->config['signing_key'], 'signingAlgorithm' => $this->config['signing_algorithm']]); return $auth; } /** * Set the Cache object * @param CacheItemPoolInterface $cache */ public function setCache(\Google\Site_Kit_Dependencies\Psr\Cache\CacheItemPoolInterface $cache) { $this->cache = $cache; } /** * @return CacheItemPoolInterface */ public function getCache() { if (!$this->cache) { $this->cache = $this->createDefaultCache(); } return $this->cache; } /** * @param array $cacheConfig */ public function setCacheConfig(array $cacheConfig) { $this->config['cache_config'] = $cacheConfig; } /** * Set the Logger object * @param LoggerInterface $logger */ public function setLogger(\Google\Site_Kit_Dependencies\Psr\Log\LoggerInterface $logger) { $this->logger = $logger; } /** * @return LoggerInterface */ public function getLogger() { if (!isset($this->logger)) { $this->logger = $this->createDefaultLogger(); } return $this->logger; } protected function createDefaultLogger() { $logger = new \Google\Site_Kit_Dependencies\Monolog\Logger('google-api-php-client'); if ($this->isAppEngine()) { $handler = new \Google\Site_Kit_Dependencies\Monolog\Handler\SyslogHandler('app', \LOG_USER, \Google\Site_Kit_Dependencies\Monolog\Logger::NOTICE); } else { $handler = new \Google\Site_Kit_Dependencies\Monolog\Handler\StreamHandler('php://stderr', \Google\Site_Kit_Dependencies\Monolog\Logger::NOTICE); } $logger->pushHandler($handler); return $logger; } protected function createDefaultCache() { return new \Google\Site_Kit_Dependencies\Google\Auth\Cache\MemoryCacheItemPool(); } /** * Set the Http Client object * @param ClientInterface $http */ public function setHttpClient(\Google\Site_Kit_Dependencies\GuzzleHttp\ClientInterface $http) { $this->http = $http; } /** * @return ClientInterface */ public function getHttpClient() { if (null === $this->http) { $this->http = $this->createDefaultHttpClient(); } return $this->http; } /** * Set the API format version. * * `true` will use V2, which may return more useful error messages. * * @param bool $value */ public function setApiFormatV2($value) { $this->config['api_format_v2'] = (bool) $value; } protected function createDefaultHttpClient() { $guzzleVersion = null; if (\defined('\\Google\\Site_Kit_Dependencies\\GuzzleHttp\\ClientInterface::MAJOR_VERSION')) { $guzzleVersion = \Google\Site_Kit_Dependencies\GuzzleHttp\ClientInterface::MAJOR_VERSION; } elseif (\defined('\\Google\\Site_Kit_Dependencies\\GuzzleHttp\\ClientInterface::VERSION')) { $guzzleVersion = (int) \substr(\Google\Site_Kit_Dependencies\GuzzleHttp\ClientInterface::VERSION, 0, 1); } if (5 === $guzzleVersion) { $options = ['base_url' => $this->config['base_path'], 'defaults' => ['exceptions' => \false]]; if ($this->isAppEngine()) { // set StreamHandler on AppEngine by default $options['handler'] = new \Google\Site_Kit_Dependencies\GuzzleHttp\Ring\Client\StreamHandler(); $options['defaults']['verify'] = '/etc/ca-certificates.crt'; } } elseif (6 === $guzzleVersion || 7 === $guzzleVersion) { // guzzle 6 or 7 $options = ['base_uri' => $this->config['base_path'], 'http_errors' => \false]; } else { throw new \LogicException('Could not find supported version of Guzzle.'); } return new \Google\Site_Kit_Dependencies\GuzzleHttp\Client($options); } /** * @return FetchAuthTokenCache */ private function createApplicationDefaultCredentials() { $scopes = $this->prepareScopes(); $sub = $this->config['subject']; $signingKey = $this->config['signing_key']; // create credentials using values supplied in setAuthConfig if ($signingKey) { $serviceAccountCredentials = array('client_id' => $this->config['client_id'], 'client_email' => $this->config['client_email'], 'private_key' => $signingKey, 'type' => 'service_account', 'quota_project_id' => $this->config['quota_project']); $credentials = \Google\Site_Kit_Dependencies\Google\Auth\CredentialsLoader::makeCredentials($scopes, $serviceAccountCredentials); } else { // When $sub is provided, we cannot pass cache classes to ::getCredentials // because FetchAuthTokenCache::setSub does not exist. // The result is when $sub is provided, calls to ::onGce are not cached. $credentials = \Google\Site_Kit_Dependencies\Google\Auth\ApplicationDefaultCredentials::getCredentials($scopes, null, $sub ? null : $this->config['cache_config'], $sub ? null : $this->getCache(), $this->config['quota_project']); } // for service account domain-wide authority (impersonating a user) // @see https://developers.google.com/identity/protocols/OAuth2ServiceAccount if ($sub) { if (!$credentials instanceof \Google\Site_Kit_Dependencies\Google\Auth\Credentials\ServiceAccountCredentials) { throw new \DomainException('domain-wide authority requires service account credentials'); } $credentials->setSub($sub); } // If we are not using FetchAuthTokenCache yet, create it now if (!$credentials instanceof \Google\Site_Kit_Dependencies\Google\Auth\FetchAuthTokenCache) { $credentials = new \Google\Site_Kit_Dependencies\Google\Auth\FetchAuthTokenCache($credentials, $this->config['cache_config'], $this->getCache()); } return $credentials; } protected function getAuthHandler() { // Be very careful using the cache, as the underlying auth library's cache // implementation is naive, and the cache keys do not account for user // sessions. // // @see https://github.com/google/google-api-php-client/issues/821 return \Google\Site_Kit_Dependencies\Google\AuthHandler\AuthHandlerFactory::build($this->getCache(), $this->config['cache_config']); } private function createUserRefreshCredentials($scope, $refreshToken) { $creds = \array_filter(array('client_id' => $this->getClientId(), 'client_secret' => $this->getClientSecret(), 'refresh_token' => $refreshToken)); return new \Google\Site_Kit_Dependencies\Google\Auth\Credentials\UserRefreshCredentials($scope, $creds); } } PK!ͺ/ / #google/apiclient/src/Http/Batch.phpnu[client = $client; $this->boundary = $boundary ?: \mt_rand(); $this->rootUrl = \rtrim($rootUrl ?: $this->client->getConfig('base_path'), '/'); $this->batchPath = $batchPath ?: self::BATCH_PATH; } public function add(\Google\Site_Kit_Dependencies\Psr\Http\Message\RequestInterface $request, $key = \false) { if (\false == $key) { $key = \mt_rand(); } $this->requests[$key] = $request; } public function execute() { $body = ''; $classes = array(); $batchHttpTemplate = <<requests as $key => $request) { $firstLine = \sprintf('%s %s HTTP/%s', $request->getMethod(), $request->getRequestTarget(), $request->getProtocolVersion()); $content = (string) $request->getBody(); $headers = ''; foreach ($request->getHeaders() as $name => $values) { $headers .= \sprintf("%s:%s\r\n", $name, \implode(', ', $values)); } $body .= \sprintf($batchHttpTemplate, $this->boundary, $key, $firstLine, $headers, $content ? "\n" . $content : ''); $classes['response-' . $key] = $request->getHeaderLine('X-Php-Expected-Class'); } $body .= "--{$this->boundary}--"; $body = \trim($body); $url = $this->rootUrl . '/' . $this->batchPath; $headers = array('Content-Type' => \sprintf('multipart/mixed; boundary=%s', $this->boundary), 'Content-Length' => \strlen($body)); $request = new \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Request('POST', $url, $headers, $body); $response = $this->client->execute($request); return $this->parseResponse($response, $classes); } public function parseResponse(\Google\Site_Kit_Dependencies\Psr\Http\Message\ResponseInterface $response, $classes = array()) { $contentType = $response->getHeaderLine('content-type'); $contentType = \explode(';', $contentType); $boundary = \false; foreach ($contentType as $part) { $part = \explode('=', $part, 2); if (isset($part[0]) && 'boundary' == \trim($part[0])) { $boundary = $part[1]; } } $body = (string) $response->getBody(); if (!empty($body)) { $body = \str_replace("--{$boundary}--", "--{$boundary}", $body); $parts = \explode("--{$boundary}", $body); $responses = array(); $requests = \array_values($this->requests); foreach ($parts as $i => $part) { $part = \trim($part); if (!empty($part)) { list($rawHeaders, $part) = \explode("\r\n\r\n", $part, 2); $headers = $this->parseRawHeaders($rawHeaders); $status = \substr($part, 0, \strpos($part, "\n")); $status = \explode(" ", $status); $status = $status[1]; list($partHeaders, $partBody) = $this->parseHttpResponse($part, \false); $response = new \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Response($status, $partHeaders, \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Utils::streamFor($partBody)); // Need content id. $key = $headers['content-id']; try { $response = \Google\Site_Kit_Dependencies\Google\Http\REST::decodeHttpResponse($response, $requests[$i - 1]); } catch (\Google\Site_Kit_Dependencies\Google\Service\Exception $e) { // Store the exception as the response, so successful responses // can be processed. $response = $e; } $responses[$key] = $response; } } return $responses; } return null; } private function parseRawHeaders($rawHeaders) { $headers = array(); $responseHeaderLines = \explode("\r\n", $rawHeaders); foreach ($responseHeaderLines as $headerLine) { if ($headerLine && \strpos($headerLine, ':') !== \false) { list($header, $value) = \explode(': ', $headerLine, 2); $header = \strtolower($header); if (isset($headers[$header])) { $headers[$header] = \array_merge((array) $headers[$header], (array) $value); } else { $headers[$header] = $value; } } } return $headers; } /** * Used by the IO lib and also the batch processing. * * @param $respData * @param $headerSize * @return array */ private function parseHttpResponse($respData, $headerSize) { // check proxy header foreach (self::$CONNECTION_ESTABLISHED_HEADERS as $established_header) { if (\stripos($respData, $established_header) !== \false) { // existed, remove it $respData = \str_ireplace($established_header, '', $respData); // Subtract the proxy header size unless the cURL bug prior to 7.30.0 // is present which prevented the proxy header size from being taken into // account. // @TODO look into this // if (!$this->needsQuirk()) { // $headerSize -= strlen($established_header); // } break; } } if ($headerSize) { $responseBody = \substr($respData, $headerSize); $responseHeaders = \substr($respData, 0, $headerSize); } else { $responseSegments = \explode("\r\n\r\n", $respData, 2); $responseHeaders = $responseSegments[0]; $responseBody = isset($responseSegments[1]) ? $responseSegments[1] : null; } $responseHeaders = $this->parseRawHeaders($responseHeaders); return array($responseHeaders, $responseBody); } } PK!Q;;"google/apiclient/src/Http/REST.phpnu[getMethod(), (string) $request->getUri()), array(\get_class(), 'doExecute'), array($client, $request, $expectedClass)); if (null !== $retryMap) { $runner->setRetryMap($retryMap); } return $runner->run(); } /** * Executes a Psr\Http\Message\RequestInterface * * @param Client $client * @param RequestInterface $request * @param string $expectedClass * @return array decoded result * @throws \Google\Service\Exception on server side error (ie: not authenticated, * invalid or malformed post body, invalid url) */ public static function doExecute(\Google\Site_Kit_Dependencies\GuzzleHttp\ClientInterface $client, \Google\Site_Kit_Dependencies\Psr\Http\Message\RequestInterface $request, $expectedClass = null) { try { $httpHandler = \Google\Site_Kit_Dependencies\Google\Auth\HttpHandler\HttpHandlerFactory::build($client); $response = $httpHandler($request); } catch (\Google\Site_Kit_Dependencies\GuzzleHttp\Exception\RequestException $e) { // if Guzzle throws an exception, catch it and handle the response if (!$e->hasResponse()) { throw $e; } $response = $e->getResponse(); // specific checking for Guzzle 5: convert to PSR7 response if ($response instanceof \Google\Site_Kit_Dependencies\GuzzleHttp\Message\ResponseInterface) { $response = new \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Response($response->getStatusCode(), $response->getHeaders() ?: [], $response->getBody(), $response->getProtocolVersion(), $response->getReasonPhrase()); } } return self::decodeHttpResponse($response, $request, $expectedClass); } /** * Decode an HTTP Response. * @static * @throws \Google\Service\Exception * @param RequestInterface $response The http response to be decoded. * @param ResponseInterface $response * @param string $expectedClass * @return mixed|null */ public static function decodeHttpResponse(\Google\Site_Kit_Dependencies\Psr\Http\Message\ResponseInterface $response, \Google\Site_Kit_Dependencies\Psr\Http\Message\RequestInterface $request = null, $expectedClass = null) { $code = $response->getStatusCode(); // retry strategy if (\intVal($code) >= 400) { // if we errored out, it should be safe to grab the response body $body = (string) $response->getBody(); // Check if we received errors, and add those to the Exception for convenience throw new \Google\Site_Kit_Dependencies\Google\Service\Exception($body, $code, null, self::getResponseErrors($body)); } // Ensure we only pull the entire body into memory if the request is not // of media type $body = self::decodeBody($response, $request); if ($expectedClass = self::determineExpectedClass($expectedClass, $request)) { $json = \json_decode($body, \true); return new $expectedClass($json); } return $response; } private static function decodeBody(\Google\Site_Kit_Dependencies\Psr\Http\Message\ResponseInterface $response, \Google\Site_Kit_Dependencies\Psr\Http\Message\RequestInterface $request = null) { if (self::isAltMedia($request)) { // don't decode the body, it's probably a really long string return ''; } return (string) $response->getBody(); } private static function determineExpectedClass($expectedClass, \Google\Site_Kit_Dependencies\Psr\Http\Message\RequestInterface $request = null) { // "false" is used to explicitly prevent an expected class from being returned if (\false === $expectedClass) { return null; } // if we don't have a request, we just use what's passed in if (null === $request) { return $expectedClass; } // return what we have in the request header if one was not supplied return $expectedClass ?: $request->getHeaderLine('X-Php-Expected-Class'); } private static function getResponseErrors($body) { $json = \json_decode($body, \true); if (isset($json['error']['errors'])) { return $json['error']['errors']; } return null; } private static function isAltMedia(\Google\Site_Kit_Dependencies\Psr\Http\Message\RequestInterface $request = null) { if ($request && ($qs = $request->getUri()->getQuery())) { \parse_str($qs, $query); if (isset($query['alt']) && $query['alt'] == 'media') { return \true; } } return \false; } } PK! U}**-google/apiclient/src/Http/MediaFileUpload.phpnu[client = $client; $this->request = $request; $this->mimeType = $mimeType; $this->data = $data; $this->resumable = $resumable; $this->chunkSize = $chunkSize; $this->progress = 0; $this->process(); } /** * Set the size of the file that is being uploaded. * @param $size - int file size in bytes */ public function setFileSize($size) { $this->size = $size; } /** * Return the progress on the upload * @return int progress in bytes uploaded. */ public function getProgress() { return $this->progress; } /** * Send the next part of the file to upload. * @param string|bool $chunk Optional. The next set of bytes to send. If false will * use $data passed at construct time. */ public function nextChunk($chunk = \false) { $resumeUri = $this->getResumeUri(); if (\false == $chunk) { $chunk = \substr($this->data, $this->progress, $this->chunkSize); } $lastBytePos = $this->progress + \strlen($chunk) - 1; $headers = array('content-range' => "bytes {$this->progress}-{$lastBytePos}/{$this->size}", 'content-length' => \strlen($chunk), 'expect' => ''); $request = new \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Request('PUT', $resumeUri, $headers, \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Utils::streamFor($chunk)); return $this->makePutRequest($request); } /** * Return the HTTP result code from the last call made. * @return int code */ public function getHttpResultCode() { return $this->httpResultCode; } /** * Sends a PUT-Request to google drive and parses the response, * setting the appropiate variables from the response() * * @param RequestInterface $request the Request which will be send * * @return false|mixed false when the upload is unfinished or the decoded http response * */ private function makePutRequest(\Google\Site_Kit_Dependencies\Psr\Http\Message\RequestInterface $request) { $response = $this->client->execute($request); $this->httpResultCode = $response->getStatusCode(); if (308 == $this->httpResultCode) { // Track the amount uploaded. $range = $response->getHeaderLine('range'); if ($range) { $range_array = \explode('-', $range); $this->progress = $range_array[1] + 1; } // Allow for changing upload URLs. $location = $response->getHeaderLine('location'); if ($location) { $this->resumeUri = $location; } // No problems, but upload not complete. return \false; } return \Google\Site_Kit_Dependencies\Google\Http\REST::decodeHttpResponse($response, $this->request); } /** * Resume a previously unfinished upload * @param $resumeUri the resume-URI of the unfinished, resumable upload. */ public function resume($resumeUri) { $this->resumeUri = $resumeUri; $headers = array('content-range' => "bytes */{$this->size}", 'content-length' => 0); $httpRequest = new \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Request('PUT', $this->resumeUri, $headers); return $this->makePutRequest($httpRequest); } /** * @return RequestInterface * @visible for testing */ private function process() { $this->transformToUploadUrl(); $request = $this->request; $postBody = ''; $contentType = \false; $meta = (string) $request->getBody(); $meta = \is_string($meta) ? \json_decode($meta, \true) : $meta; $uploadType = $this->getUploadType($meta); $request = $request->withUri(\Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Uri::withQueryValue($request->getUri(), 'uploadType', $uploadType)); $mimeType = $this->mimeType ?: $request->getHeaderLine('content-type'); if (self::UPLOAD_RESUMABLE_TYPE == $uploadType) { $contentType = $mimeType; $postBody = \is_string($meta) ? $meta : \json_encode($meta); } else { if (self::UPLOAD_MEDIA_TYPE == $uploadType) { $contentType = $mimeType; $postBody = $this->data; } else { if (self::UPLOAD_MULTIPART_TYPE == $uploadType) { // This is a multipart/related upload. $boundary = $this->boundary ?: \mt_rand(); $boundary = \str_replace('"', '', $boundary); $contentType = 'multipart/related; boundary=' . $boundary; $related = "--{$boundary}\r\n"; $related .= "Content-Type: application/json; charset=UTF-8\r\n"; $related .= "\r\n" . \json_encode($meta) . "\r\n"; $related .= "--{$boundary}\r\n"; $related .= "Content-Type: {$mimeType}\r\n"; $related .= "Content-Transfer-Encoding: base64\r\n"; $related .= "\r\n" . \base64_encode($this->data) . "\r\n"; $related .= "--{$boundary}--"; $postBody = $related; } } } $request = $request->withBody(\Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Utils::streamFor($postBody)); if (isset($contentType) && $contentType) { $request = $request->withHeader('content-type', $contentType); } return $this->request = $request; } /** * Valid upload types: * - resumable (UPLOAD_RESUMABLE_TYPE) * - media (UPLOAD_MEDIA_TYPE) * - multipart (UPLOAD_MULTIPART_TYPE) * @param $meta * @return string * @visible for testing */ public function getUploadType($meta) { if ($this->resumable) { return self::UPLOAD_RESUMABLE_TYPE; } if (\false == $meta && $this->data) { return self::UPLOAD_MEDIA_TYPE; } return self::UPLOAD_MULTIPART_TYPE; } public function getResumeUri() { if (null === $this->resumeUri) { $this->resumeUri = $this->fetchResumeUri(); } return $this->resumeUri; } private function fetchResumeUri() { $body = $this->request->getBody(); if ($body) { $headers = array('content-type' => 'application/json; charset=UTF-8', 'content-length' => $body->getSize(), 'x-upload-content-type' => $this->mimeType, 'x-upload-content-length' => $this->size, 'expect' => ''); foreach ($headers as $key => $value) { $this->request = $this->request->withHeader($key, $value); } } $response = $this->client->execute($this->request, \false); $location = $response->getHeaderLine('location'); $code = $response->getStatusCode(); if (200 == $code && \true == $location) { return $location; } $message = $code; $body = \json_decode((string) $this->request->getBody(), \true); if (isset($body['error']['errors'])) { $message .= ': '; foreach ($body['error']['errors'] as $error) { $message .= "{$error['domain']}, {$error['message']};"; } $message = \rtrim($message, ';'); } $error = "Failed to start the resumable upload (HTTP {$message})"; $this->client->getLogger()->error($error); throw new \Google\Site_Kit_Dependencies\Google\Exception($error); } private function transformToUploadUrl() { $parts = \parse_url((string) $this->request->getUri()); if (!isset($parts['path'])) { $parts['path'] = ''; } $parts['path'] = '/upload' . $parts['path']; $uri = \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Uri::fromParts($parts); $this->request = $this->request->withUri($uri); } public function setChunkSize($chunkSize) { $this->chunkSize = $chunkSize; } public function getRequest() { return $this->request; } } PK!EN,N,google/auth/COPYINGnu[ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2015 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. PK!ƺ2google/auth/src/HttpHandler/Guzzle6HttpHandler.phpnu[client = $client; } /** * Accepts a PSR-7 request and an array of options and returns a PSR-7 response. * * @param RequestInterface $request * @param array $options * @return ResponseInterface */ public function __invoke(\Google\Site_Kit_Dependencies\Psr\Http\Message\RequestInterface $request, array $options = []) { return $this->client->send($request, $options); } /** * Accepts a PSR-7 request and an array of options and returns a PromiseInterface * * @param RequestInterface $request * @param array $options * * @return \GuzzleHttp\Promise\PromiseInterface */ public function async(\Google\Site_Kit_Dependencies\Psr\Http\Message\RequestInterface $request, array $options = []) { return $this->client->sendAsync($request, $options); } } PK!,[/google/auth/src/HttpHandler/HttpClientCache.phpnu[client = $client; } /** * Accepts a PSR-7 Request and an array of options and returns a PSR-7 response. * * @param RequestInterface $request * @param array $options * @return ResponseInterface */ public function __invoke(\Google\Site_Kit_Dependencies\Psr\Http\Message\RequestInterface $request, array $options = []) { $response = $this->client->send($this->createGuzzle5Request($request, $options)); return $this->createPsr7Response($response); } /** * Accepts a PSR-7 request and an array of options and returns a PromiseInterface * * @param RequestInterface $request * @param array $options * @return Promise */ public function async(\Google\Site_Kit_Dependencies\Psr\Http\Message\RequestInterface $request, array $options = []) { if (!\class_exists('Google\\Site_Kit_Dependencies\\GuzzleHttp\\Promise\\Promise')) { throw new \Exception('Install guzzlehttp/promises to use async with Guzzle 5'); } $futureResponse = $this->client->send($this->createGuzzle5Request($request, ['future' => \true] + $options)); $promise = new \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Promise(function () use($futureResponse) { try { $futureResponse->wait(); } catch (\Exception $e) { // The promise is already delivered when the exception is // thrown, so don't rethrow it. } }, [$futureResponse, 'cancel']); $futureResponse->then([$promise, 'resolve'], [$promise, 'reject']); return $promise->then(function (\Google\Site_Kit_Dependencies\GuzzleHttp\Message\ResponseInterface $response) { // Adapt the Guzzle 5 Response to a PSR-7 Response. return $this->createPsr7Response($response); }, function (\Exception $e) { return new \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\RejectedPromise($e); }); } private function createGuzzle5Request(\Google\Site_Kit_Dependencies\Psr\Http\Message\RequestInterface $request, array $options) { return $this->client->createRequest($request->getMethod(), $request->getUri(), \array_merge_recursive(['headers' => $request->getHeaders(), 'body' => $request->getBody()], $options)); } private function createPsr7Response(\Google\Site_Kit_Dependencies\GuzzleHttp\Message\ResponseInterface $response) { return new \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Response($response->getStatusCode(), $response->getHeaders() ?: [], $response->getBody(), $response->getProtocolVersion(), $response->getReasonPhrase()); } } PK!v  2google/auth/src/HttpHandler/Guzzle7HttpHandler.phpnu[setDefaultOption('auth', 'google_auth'); $subscriber = new \Google\Site_Kit_Dependencies\Google\Auth\Subscriber\AuthTokenSubscriber($fetcher, $httpHandler, $tokenCallback); $client->getEmitter()->attach($subscriber); return $client; } $middleware = new \Google\Site_Kit_Dependencies\Google\Auth\Middleware\AuthTokenMiddleware($fetcher, $httpHandler, $tokenCallback); $stack = \Google\Site_Kit_Dependencies\GuzzleHttp\HandlerStack::create(); $stack->push($middleware); return new \Google\Site_Kit_Dependencies\GuzzleHttp\Client(['handler' => $stack, 'auth' => 'google_auth'] + $httpClientOptions); } /** * Create a new instance of InsecureCredentials. * * @return InsecureCredentials */ public static function makeInsecureCredentials() { return new \Google\Site_Kit_Dependencies\Google\Auth\Credentials\InsecureCredentials(); } /** * export a callback function which updates runtime metadata. * * @return array updateMetadata function * @deprecated */ public function getUpdateMetadataFunc() { return array($this, 'updateMetadata'); } /** * Updates metadata with the authorization token. * * @param array $metadata metadata hashmap * @param string $authUri optional auth uri * @param callable $httpHandler callback which delivers psr7 request * @return array updated metadata hashmap */ public function updateMetadata($metadata, $authUri = null, callable $httpHandler = null) { if (isset($metadata[self::AUTH_METADATA_KEY])) { // Auth metadata has already been set return $metadata; } $result = $this->fetchAuthToken($httpHandler); if (!isset($result['access_token'])) { return $metadata; } $metadata_copy = $metadata; $metadata_copy[self::AUTH_METADATA_KEY] = array('Bearer ' . $result['access_token']); return $metadata_copy; } /** * Gets a callable which returns the default device certification. * * @throws UnexpectedValueException * @return callable|null */ public static function getDefaultClientCertSource() { if (!($clientCertSourceJson = self::loadDefaultClientCertSourceFile())) { return null; } $clientCertSourceCmd = $clientCertSourceJson['cert_provider_command']; return function () use($clientCertSourceCmd) { $cmd = \array_map('escapeshellarg', $clientCertSourceCmd); \exec(\implode(' ', $cmd), $output, $returnVar); if (0 === $returnVar) { return \implode(\PHP_EOL, $output); } throw new \RuntimeException('"cert_provider_command" failed with a nonzero exit code'); }; } /** * Determines whether or not the default device certificate should be loaded. * * @return bool */ public static function shouldLoadClientCertSource() { return \filter_var(\getenv(self::MTLS_CERT_ENV_VAR), \FILTER_VALIDATE_BOOLEAN); } private static function loadDefaultClientCertSourceFile() { $rootEnv = self::isOnWindows() ? 'APPDATA' : 'HOME'; $path = \sprintf('%s/%s', \getenv($rootEnv), self::MTLS_WELL_KNOWN_PATH); if (!\file_exists($path)) { return null; } $jsonKey = \file_get_contents($path); $clientCertSourceJson = \json_decode($jsonKey, \true); if (!$clientCertSourceJson) { throw new \UnexpectedValueException('Invalid client cert source JSON'); } if (!isset($clientCertSourceJson['cert_provider_command'])) { throw new \UnexpectedValueException('cert source requires "cert_provider_command"'); } if (!\is_array($clientCertSourceJson['cert_provider_command'])) { throw new \UnexpectedValueException('cert source expects "cert_provider_command" to be an array'); } return $clientCertSourceJson; } } PK!99-google/auth/src/ServiceAccountSignerTrait.phpnu[auth->getSigningKey(); $signedString = ''; if (\class_exists('Google\\Site_Kit_Dependencies\\phpseclib\\Crypt\\RSA') && !$forceOpenssl) { $rsa = new \Google\Site_Kit_Dependencies\phpseclib\Crypt\RSA(); $rsa->loadKey($privateKey); $rsa->setSignatureMode(\Google\Site_Kit_Dependencies\phpseclib\Crypt\RSA::SIGNATURE_PKCS1); $rsa->setHash('sha256'); $signedString = $rsa->sign($stringToSign); } elseif (\extension_loaded('openssl')) { \openssl_sign($stringToSign, $signedString, $privateKey, 'sha256WithRSAEncryption'); } else { // @codeCoverageIgnoreStart throw new \RuntimeException('OpenSSL is not installed.'); } // @codeCoverageIgnoreEnd return \base64_encode($signedString); } } PK!M_google/auth/src/OAuth2.phpnu[ self::DEFAULT_EXPIRY_SECONDS, 'extensionParams' => [], 'authorizationUri' => null, 'redirectUri' => null, 'tokenCredentialUri' => null, 'state' => null, 'username' => null, 'password' => null, 'clientId' => null, 'clientSecret' => null, 'issuer' => null, 'sub' => null, 'audience' => null, 'signingKey' => null, 'signingKeyId' => null, 'signingAlgorithm' => null, 'scope' => null, 'additionalClaims' => []], $config); $this->setAuthorizationUri($opts['authorizationUri']); $this->setRedirectUri($opts['redirectUri']); $this->setTokenCredentialUri($opts['tokenCredentialUri']); $this->setState($opts['state']); $this->setUsername($opts['username']); $this->setPassword($opts['password']); $this->setClientId($opts['clientId']); $this->setClientSecret($opts['clientSecret']); $this->setIssuer($opts['issuer']); $this->setSub($opts['sub']); $this->setExpiry($opts['expiry']); $this->setAudience($opts['audience']); $this->setSigningKey($opts['signingKey']); $this->setSigningKeyId($opts['signingKeyId']); $this->setSigningAlgorithm($opts['signingAlgorithm']); $this->setScope($opts['scope']); $this->setExtensionParams($opts['extensionParams']); $this->setAdditionalClaims($opts['additionalClaims']); $this->updateToken($opts); } /** * Verifies the idToken if present. * * - if none is present, return null * - if present, but invalid, raises DomainException. * - otherwise returns the payload in the idtoken as a PHP object. * * The behavior of this method varies depending on the version of * `firebase/php-jwt` you are using. In versions lower than 3.0.0, if * `$publicKey` is null, the key is decoded without being verified. In * newer versions, if a public key is not given, this method will throw an * `\InvalidArgumentException`. * * @param string $publicKey The public key to use to authenticate the token * @param array $allowed_algs List of supported verification algorithms * @throws \DomainException if the token is missing an audience. * @throws \DomainException if the audience does not match the one set in * the OAuth2 class instance. * @throws \UnexpectedValueException If the token is invalid * @throws SignatureInvalidException If the signature is invalid. * @throws BeforeValidException If the token is not yet valid. * @throws ExpiredException If the token has expired. * @return null|object */ public function verifyIdToken($publicKey = null, $allowed_algs = array()) { $idToken = $this->getIdToken(); if (\is_null($idToken)) { return null; } $resp = $this->jwtDecode($idToken, $publicKey, $allowed_algs); if (!\property_exists($resp, 'aud')) { throw new \DomainException('No audience found the id token'); } if ($resp->aud != $this->getAudience()) { throw new \DomainException('Wrong audience present in the id token'); } return $resp; } /** * Obtains the encoded jwt from the instance data. * * @param array $config array optional configuration parameters * @return string */ public function toJwt(array $config = []) { if (\is_null($this->getSigningKey())) { throw new \DomainException('No signing key available'); } if (\is_null($this->getSigningAlgorithm())) { throw new \DomainException('No signing algorithm specified'); } $now = \time(); $opts = \array_merge(['skew' => self::DEFAULT_SKEW_SECONDS], $config); $assertion = ['iss' => $this->getIssuer(), 'exp' => $now + $this->getExpiry(), 'iat' => $now - $opts['skew']]; foreach ($assertion as $k => $v) { if (\is_null($v)) { throw new \DomainException($k . ' should not be null'); } } if (!\is_null($this->getAudience())) { $assertion['aud'] = $this->getAudience(); } if (!\is_null($this->getScope())) { $assertion['scope'] = $this->getScope(); } if (empty($assertion['scope']) && empty($assertion['aud'])) { throw new \DomainException('one of scope or aud should not be null'); } if (!\is_null($this->getSub())) { $assertion['sub'] = $this->getSub(); } $assertion += $this->getAdditionalClaims(); return $this->jwtEncode($assertion, $this->getSigningKey(), $this->getSigningAlgorithm(), $this->getSigningKeyId()); } /** * Generates a request for token credentials. * * @return RequestInterface the authorization Url. */ public function generateCredentialsRequest() { $uri = $this->getTokenCredentialUri(); if (\is_null($uri)) { throw new \DomainException('No token credential URI was set.'); } $grantType = $this->getGrantType(); $params = array('grant_type' => $grantType); switch ($grantType) { case 'authorization_code': $params['code'] = $this->getCode(); $params['redirect_uri'] = $this->getRedirectUri(); $this->addClientCredentials($params); break; case 'password': $params['username'] = $this->getUsername(); $params['password'] = $this->getPassword(); $this->addClientCredentials($params); break; case 'refresh_token': $params['refresh_token'] = $this->getRefreshToken(); $this->addClientCredentials($params); break; case self::JWT_URN: $params['assertion'] = $this->toJwt(); break; default: if (!\is_null($this->getRedirectUri())) { # Grant type was supposed to be 'authorization_code', as there # is a redirect URI. throw new \DomainException('Missing authorization code'); } unset($params['grant_type']); if (!\is_null($grantType)) { $params['grant_type'] = $grantType; } $params = \array_merge($params, $this->getExtensionParams()); } $headers = ['Cache-Control' => 'no-store', 'Content-Type' => 'application/x-www-form-urlencoded']; return new \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Request('POST', $uri, $headers, \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Query::build($params)); } /** * Fetches the auth tokens based on the current state. * * @param callable $httpHandler callback which delivers psr7 request * @return array the response */ public function fetchAuthToken(callable $httpHandler = null) { if (\is_null($httpHandler)) { $httpHandler = \Google\Site_Kit_Dependencies\Google\Auth\HttpHandler\HttpHandlerFactory::build(\Google\Site_Kit_Dependencies\Google\Auth\HttpHandler\HttpClientCache::getHttpClient()); } $response = $httpHandler($this->generateCredentialsRequest()); $credentials = $this->parseTokenResponse($response); $this->updateToken($credentials); return $credentials; } /** * Obtains a key that can used to cache the results of #fetchAuthToken. * * The key is derived from the scopes. * * @return string a key that may be used to cache the auth token. */ public function getCacheKey() { if (\is_array($this->scope)) { return \implode(':', $this->scope); } if ($this->audience) { return $this->audience; } // If scope has not set, return null to indicate no caching. return null; } /** * Parses the fetched tokens. * * @param ResponseInterface $resp the response. * @return array the tokens parsed from the response body. * @throws \Exception */ public function parseTokenResponse(\Google\Site_Kit_Dependencies\Psr\Http\Message\ResponseInterface $resp) { $body = (string) $resp->getBody(); if ($resp->hasHeader('Content-Type') && $resp->getHeaderLine('Content-Type') == 'application/x-www-form-urlencoded') { $res = array(); \parse_str($body, $res); return $res; } // Assume it's JSON; if it's not throw an exception if (null === ($res = \json_decode($body, \true))) { throw new \Exception('Invalid JSON response'); } return $res; } /** * Updates an OAuth 2.0 client. * * Example: * ``` * $oauth->updateToken([ * 'refresh_token' => 'n4E9O119d', * 'access_token' => 'FJQbwq9', * 'expires_in' => 3600 * ]); * ``` * * @param array $config * The configuration parameters related to the token. * * - refresh_token * The refresh token associated with the access token * to be refreshed. * * - access_token * The current access token for this client. * * - id_token * The current ID token for this client. * * - expires_in * The time in seconds until access token expiration. * * - expires_at * The time as an integer number of seconds since the Epoch * * - issued_at * The timestamp that the token was issued at. */ public function updateToken(array $config) { $opts = \array_merge(['extensionParams' => [], 'access_token' => null, 'id_token' => null, 'expires_in' => null, 'expires_at' => null, 'issued_at' => null], $config); $this->setExpiresAt($opts['expires_at']); $this->setExpiresIn($opts['expires_in']); // By default, the token is issued at `Time.now` when `expiresIn` is set, // but this can be used to supply a more precise time. if (!\is_null($opts['issued_at'])) { $this->setIssuedAt($opts['issued_at']); } $this->setAccessToken($opts['access_token']); $this->setIdToken($opts['id_token']); // The refresh token should only be updated if a value is explicitly // passed in, as some access token responses do not include a refresh // token. if (\array_key_exists('refresh_token', $opts)) { $this->setRefreshToken($opts['refresh_token']); } } /** * Builds the authorization Uri that the user should be redirected to. * * @param array $config configuration options that customize the return url * @return UriInterface the authorization Url. * @throws InvalidArgumentException */ public function buildFullAuthorizationUri(array $config = []) { if (\is_null($this->getAuthorizationUri())) { throw new \InvalidArgumentException('requires an authorizationUri to have been set'); } $params = \array_merge(['response_type' => 'code', 'access_type' => 'offline', 'client_id' => $this->clientId, 'redirect_uri' => $this->redirectUri, 'state' => $this->state, 'scope' => $this->getScope()], $config); // Validate the auth_params if (\is_null($params['client_id'])) { throw new \InvalidArgumentException('missing the required client identifier'); } if (\is_null($params['redirect_uri'])) { throw new \InvalidArgumentException('missing the required redirect URI'); } if (!empty($params['prompt']) && !empty($params['approval_prompt'])) { throw new \InvalidArgumentException('prompt and approval_prompt are mutually exclusive'); } // Construct the uri object; return it if it is valid. $result = clone $this->authorizationUri; $existingParams = \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Query::parse($result->getQuery()); $result = $result->withQuery(\Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Query::build(\array_merge($existingParams, $params))); if ($result->getScheme() != 'https') { throw new \InvalidArgumentException('Authorization endpoint must be protected by TLS'); } return $result; } /** * Sets the authorization server's HTTP endpoint capable of authenticating * the end-user and obtaining authorization. * * @param string $uri */ public function setAuthorizationUri($uri) { $this->authorizationUri = $this->coerceUri($uri); } /** * Gets the authorization server's HTTP endpoint capable of authenticating * the end-user and obtaining authorization. * * @return UriInterface */ public function getAuthorizationUri() { return $this->authorizationUri; } /** * Gets the authorization server's HTTP endpoint capable of issuing tokens * and refreshing expired tokens. * * @return string */ public function getTokenCredentialUri() { return $this->tokenCredentialUri; } /** * Sets the authorization server's HTTP endpoint capable of issuing tokens * and refreshing expired tokens. * * @param string $uri */ public function setTokenCredentialUri($uri) { $this->tokenCredentialUri = $this->coerceUri($uri); } /** * Gets the redirection URI used in the initial request. * * @return string */ public function getRedirectUri() { return $this->redirectUri; } /** * Sets the redirection URI used in the initial request. * * @param string $uri */ public function setRedirectUri($uri) { if (\is_null($uri)) { $this->redirectUri = null; return; } // redirect URI must be absolute if (!$this->isAbsoluteUri($uri)) { // "postmessage" is a reserved URI string in Google-land // @see https://developers.google.com/identity/sign-in/web/server-side-flow if ('postmessage' !== (string) $uri) { throw new \InvalidArgumentException('Redirect URI must be absolute'); } } $this->redirectUri = (string) $uri; } /** * Gets the scope of the access requests as a space-delimited String. * * @return string */ public function getScope() { if (\is_null($this->scope)) { return $this->scope; } return \implode(' ', $this->scope); } /** * Sets the scope of the access request, expressed either as an Array or as * a space-delimited String. * * @param string|array $scope * @throws InvalidArgumentException */ public function setScope($scope) { if (\is_null($scope)) { $this->scope = null; } elseif (\is_string($scope)) { $this->scope = \explode(' ', $scope); } elseif (\is_array($scope)) { foreach ($scope as $s) { $pos = \strpos($s, ' '); if ($pos !== \false) { throw new \InvalidArgumentException('array scope values should not contain spaces'); } } $this->scope = $scope; } else { throw new \InvalidArgumentException('scopes should be a string or array of strings'); } } /** * Gets the current grant type. * * @return string */ public function getGrantType() { if (!\is_null($this->grantType)) { return $this->grantType; } // Returns the inferred grant type, based on the current object instance // state. if (!\is_null($this->code)) { return 'authorization_code'; } if (!\is_null($this->refreshToken)) { return 'refresh_token'; } if (!\is_null($this->username) && !\is_null($this->password)) { return 'password'; } if (!\is_null($this->issuer) && !\is_null($this->signingKey)) { return self::JWT_URN; } return null; } /** * Sets the current grant type. * * @param $grantType * @throws InvalidArgumentException */ public function setGrantType($grantType) { if (\in_array($grantType, self::$knownGrantTypes)) { $this->grantType = $grantType; } else { // validate URI if (!$this->isAbsoluteUri($grantType)) { throw new \InvalidArgumentException('invalid grant type'); } $this->grantType = (string) $grantType; } } /** * Gets an arbitrary string designed to allow the client to maintain state. * * @return string */ public function getState() { return $this->state; } /** * Sets an arbitrary string designed to allow the client to maintain state. * * @param string $state */ public function setState($state) { $this->state = $state; } /** * Gets the authorization code issued to this client. */ public function getCode() { return $this->code; } /** * Sets the authorization code issued to this client. * * @param string $code */ public function setCode($code) { $this->code = $code; } /** * Gets the resource owner's username. */ public function getUsername() { return $this->username; } /** * Sets the resource owner's username. * * @param string $username */ public function setUsername($username) { $this->username = $username; } /** * Gets the resource owner's password. */ public function getPassword() { return $this->password; } /** * Sets the resource owner's password. * * @param $password */ public function setPassword($password) { $this->password = $password; } /** * Sets a unique identifier issued to the client to identify itself to the * authorization server. */ public function getClientId() { return $this->clientId; } /** * Sets a unique identifier issued to the client to identify itself to the * authorization server. * * @param $clientId */ public function setClientId($clientId) { $this->clientId = $clientId; } /** * Gets a shared symmetric secret issued by the authorization server, which * is used to authenticate the client. */ public function getClientSecret() { return $this->clientSecret; } /** * Sets a shared symmetric secret issued by the authorization server, which * is used to authenticate the client. * * @param $clientSecret */ public function setClientSecret($clientSecret) { $this->clientSecret = $clientSecret; } /** * Gets the Issuer ID when using assertion profile. */ public function getIssuer() { return $this->issuer; } /** * Sets the Issuer ID when using assertion profile. * * @param string $issuer */ public function setIssuer($issuer) { $this->issuer = $issuer; } /** * Gets the target sub when issuing assertions. */ public function getSub() { return $this->sub; } /** * Sets the target sub when issuing assertions. * * @param string $sub */ public function setSub($sub) { $this->sub = $sub; } /** * Gets the target audience when issuing assertions. */ public function getAudience() { return $this->audience; } /** * Sets the target audience when issuing assertions. * * @param string $audience */ public function setAudience($audience) { $this->audience = $audience; } /** * Gets the signing key when using an assertion profile. */ public function getSigningKey() { return $this->signingKey; } /** * Sets the signing key when using an assertion profile. * * @param string $signingKey */ public function setSigningKey($signingKey) { $this->signingKey = $signingKey; } /** * Gets the signing key id when using an assertion profile. * * @return string */ public function getSigningKeyId() { return $this->signingKeyId; } /** * Sets the signing key id when using an assertion profile. * * @param string $signingKeyId */ public function setSigningKeyId($signingKeyId) { $this->signingKeyId = $signingKeyId; } /** * Gets the signing algorithm when using an assertion profile. * * @return string */ public function getSigningAlgorithm() { return $this->signingAlgorithm; } /** * Sets the signing algorithm when using an assertion profile. * * @param string $signingAlgorithm */ public function setSigningAlgorithm($signingAlgorithm) { if (\is_null($signingAlgorithm)) { $this->signingAlgorithm = null; } elseif (!\in_array($signingAlgorithm, self::$knownSigningAlgorithms)) { throw new \InvalidArgumentException('unknown signing algorithm'); } else { $this->signingAlgorithm = $signingAlgorithm; } } /** * Gets the set of parameters used by extension when using an extension * grant type. */ public function getExtensionParams() { return $this->extensionParams; } /** * Sets the set of parameters used by extension when using an extension * grant type. * * @param $extensionParams */ public function setExtensionParams($extensionParams) { $this->extensionParams = $extensionParams; } /** * Gets the number of seconds assertions are valid for. */ public function getExpiry() { return $this->expiry; } /** * Sets the number of seconds assertions are valid for. * * @param int $expiry */ public function setExpiry($expiry) { $this->expiry = $expiry; } /** * Gets the lifetime of the access token in seconds. */ public function getExpiresIn() { return $this->expiresIn; } /** * Sets the lifetime of the access token in seconds. * * @param int $expiresIn */ public function setExpiresIn($expiresIn) { if (\is_null($expiresIn)) { $this->expiresIn = null; $this->issuedAt = null; } else { $this->issuedAt = \time(); $this->expiresIn = (int) $expiresIn; } } /** * Gets the time the current access token expires at. * * @return int */ public function getExpiresAt() { if (!\is_null($this->expiresAt)) { return $this->expiresAt; } if (!\is_null($this->issuedAt) && !\is_null($this->expiresIn)) { return $this->issuedAt + $this->expiresIn; } return null; } /** * Returns true if the acccess token has expired. * * @return bool */ public function isExpired() { $expiration = $this->getExpiresAt(); $now = \time(); return !\is_null($expiration) && $now >= $expiration; } /** * Sets the time the current access token expires at. * * @param int $expiresAt */ public function setExpiresAt($expiresAt) { $this->expiresAt = $expiresAt; } /** * Gets the time the current access token was issued at. */ public function getIssuedAt() { return $this->issuedAt; } /** * Sets the time the current access token was issued at. * * @param int $issuedAt */ public function setIssuedAt($issuedAt) { $this->issuedAt = $issuedAt; } /** * Gets the current access token. */ public function getAccessToken() { return $this->accessToken; } /** * Sets the current access token. * * @param string $accessToken */ public function setAccessToken($accessToken) { $this->accessToken = $accessToken; } /** * Gets the current ID token. */ public function getIdToken() { return $this->idToken; } /** * Sets the current ID token. * * @param $idToken */ public function setIdToken($idToken) { $this->idToken = $idToken; } /** * Gets the refresh token associated with the current access token. */ public function getRefreshToken() { return $this->refreshToken; } /** * Sets the refresh token associated with the current access token. * * @param $refreshToken */ public function setRefreshToken($refreshToken) { $this->refreshToken = $refreshToken; } /** * Sets additional claims to be included in the JWT token * * @param array $additionalClaims */ public function setAdditionalClaims(array $additionalClaims) { $this->additionalClaims = $additionalClaims; } /** * Gets the additional claims to be included in the JWT token. * * @return array */ public function getAdditionalClaims() { return $this->additionalClaims; } /** * The expiration of the last received token. * * @return array|null */ public function getLastReceivedToken() { if ($token = $this->getAccessToken()) { // the bare necessity of an auth token $authToken = ['access_token' => $token, 'expires_at' => $this->getExpiresAt()]; } elseif ($idToken = $this->getIdToken()) { $authToken = ['id_token' => $idToken, 'expires_at' => $this->getExpiresAt()]; } else { return null; } if ($expiresIn = $this->getExpiresIn()) { $authToken['expires_in'] = $expiresIn; } if ($issuedAt = $this->getIssuedAt()) { $authToken['issued_at'] = $issuedAt; } if ($refreshToken = $this->getRefreshToken()) { $authToken['refresh_token'] = $refreshToken; } return $authToken; } /** * Get the client ID. * * Alias of {@see Google\Auth\OAuth2::getClientId()}. * * @param callable $httpHandler * @return string * @access private */ public function getClientName(callable $httpHandler = null) { return $this->getClientId(); } /** * @todo handle uri as array * * @param string $uri * @return null|UriInterface */ private function coerceUri($uri) { if (\is_null($uri)) { return; } return \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Utils::uriFor($uri); } /** * @param string $idToken * @param string|array|null $publicKey * @param array $allowedAlgs * @return object */ private function jwtDecode($idToken, $publicKey, $allowedAlgs) { if (\class_exists('Google\\Site_Kit_Dependencies\\Firebase\\JWT\\JWT')) { return \Google\Site_Kit_Dependencies\Firebase\JWT\JWT::decode($idToken, $publicKey, $allowedAlgs); } return \Google\Site_Kit_Dependencies\JWT::decode($idToken, $publicKey, $allowedAlgs); } private function jwtEncode($assertion, $signingKey, $signingAlgorithm, $signingKeyId = null) { if (\class_exists('Google\\Site_Kit_Dependencies\\Firebase\\JWT\\JWT')) { return \Google\Site_Kit_Dependencies\Firebase\JWT\JWT::encode($assertion, $signingKey, $signingAlgorithm, $signingKeyId); } return \Google\Site_Kit_Dependencies\JWT::encode($assertion, $signingKey, $signingAlgorithm, $signingKeyId); } /** * Determines if the URI is absolute based on its scheme and host or path * (RFC 3986). * * @param string $uri * @return bool */ private function isAbsoluteUri($uri) { $uri = $this->coerceUri($uri); return $uri->getScheme() && ($uri->getHost() || $uri->getPath()); } /** * @param array $params * @return array */ private function addClientCredentials(&$params) { $clientId = $this->getClientId(); $clientSecret = $this->getClientSecret(); if ($clientId && $clientSecret) { $params['client_id'] = $clientId; $params['client_secret'] = $clientSecret; } return $params; } } PK!M881google/auth/src/ApplicationDefaultCredentials.phpnu[push($middleware); * * $client = new Client([ * 'handler' => $stack, * 'base_uri' => 'https://www.googleapis.com/taskqueue/v1beta2/projects/', * 'auth' => 'google_auth' // authorize all requests * ]); * * $res = $client->get('myproject/taskqueues/myqueue'); * ``` */ class ApplicationDefaultCredentials { /** * Obtains an AuthTokenSubscriber that uses the default FetchAuthTokenInterface * implementation to use in this environment. * * If supplied, $scope is used to in creating the credentials instance if * this does not fallback to the compute engine defaults. * * @param string|array scope the scope of the access request, expressed * either as an Array or as a space-delimited String. * @param callable $httpHandler callback which delivers psr7 request * @param array $cacheConfig configuration for the cache when it's present * @param CacheItemPoolInterface $cache A cache implementation, may be * provided if you have one already available for use. * @return AuthTokenSubscriber * @throws DomainException if no implementation can be obtained. */ public static function getSubscriber($scope = null, callable $httpHandler = null, array $cacheConfig = null, \Google\Site_Kit_Dependencies\Psr\Cache\CacheItemPoolInterface $cache = null) { $creds = self::getCredentials($scope, $httpHandler, $cacheConfig, $cache); return new \Google\Site_Kit_Dependencies\Google\Auth\Subscriber\AuthTokenSubscriber($creds, $httpHandler); } /** * Obtains an AuthTokenMiddleware that uses the default FetchAuthTokenInterface * implementation to use in this environment. * * If supplied, $scope is used to in creating the credentials instance if * this does not fallback to the compute engine defaults. * * @param string|array scope the scope of the access request, expressed * either as an Array or as a space-delimited String. * @param callable $httpHandler callback which delivers psr7 request * @param array $cacheConfig configuration for the cache when it's present * @param CacheItemPoolInterface $cache A cache implementation, may be * provided if you have one already available for use. * @param string $quotaProject specifies a project to bill for access * charges associated with the request. * @return AuthTokenMiddleware * @throws DomainException if no implementation can be obtained. */ public static function getMiddleware($scope = null, callable $httpHandler = null, array $cacheConfig = null, \Google\Site_Kit_Dependencies\Psr\Cache\CacheItemPoolInterface $cache = null, $quotaProject = null) { $creds = self::getCredentials($scope, $httpHandler, $cacheConfig, $cache, $quotaProject); return new \Google\Site_Kit_Dependencies\Google\Auth\Middleware\AuthTokenMiddleware($creds, $httpHandler); } /** * Obtains the default FetchAuthTokenInterface implementation to use * in this environment. * * @param string|array $scope the scope of the access request, expressed * either as an Array or as a space-delimited String. * @param callable $httpHandler callback which delivers psr7 request * @param array $cacheConfig configuration for the cache when it's present * @param CacheItemPoolInterface $cache A cache implementation, may be * provided if you have one already available for use. * @param string $quotaProject specifies a project to bill for access * charges associated with the request. * @param string|array $defaultScope The default scope to use if no * user-defined scopes exist, expressed either as an Array or as a * space-delimited string. * * @return CredentialsLoader * @throws DomainException if no implementation can be obtained. */ public static function getCredentials($scope = null, callable $httpHandler = null, array $cacheConfig = null, \Google\Site_Kit_Dependencies\Psr\Cache\CacheItemPoolInterface $cache = null, $quotaProject = null, $defaultScope = null) { $creds = null; $jsonKey = \Google\Site_Kit_Dependencies\Google\Auth\CredentialsLoader::fromEnv() ?: \Google\Site_Kit_Dependencies\Google\Auth\CredentialsLoader::fromWellKnownFile(); $anyScope = $scope ?: $defaultScope; if (!$httpHandler) { if (!($client = \Google\Site_Kit_Dependencies\Google\Auth\HttpHandler\HttpClientCache::getHttpClient())) { $client = new \Google\Site_Kit_Dependencies\GuzzleHttp\Client(); \Google\Site_Kit_Dependencies\Google\Auth\HttpHandler\HttpClientCache::setHttpClient($client); } $httpHandler = \Google\Site_Kit_Dependencies\Google\Auth\HttpHandler\HttpHandlerFactory::build($client); } if (!\is_null($jsonKey)) { if ($quotaProject) { $jsonKey['quota_project_id'] = $quotaProject; } $creds = \Google\Site_Kit_Dependencies\Google\Auth\CredentialsLoader::makeCredentials($scope, $jsonKey, $defaultScope); } elseif (\Google\Site_Kit_Dependencies\Google\Auth\Credentials\AppIdentityCredentials::onAppEngine() && !\Google\Site_Kit_Dependencies\Google\Auth\Credentials\GCECredentials::onAppEngineFlexible()) { $creds = new \Google\Site_Kit_Dependencies\Google\Auth\Credentials\AppIdentityCredentials($anyScope); } elseif (self::onGce($httpHandler, $cacheConfig, $cache)) { $creds = new \Google\Site_Kit_Dependencies\Google\Auth\Credentials\GCECredentials(null, $anyScope, null, $quotaProject); } if (\is_null($creds)) { throw new \DomainException(self::notFound()); } if (!\is_null($cache)) { $creds = new \Google\Site_Kit_Dependencies\Google\Auth\FetchAuthTokenCache($creds, $cacheConfig, $cache); } return $creds; } /** * Obtains an AuthTokenMiddleware which will fetch an ID token to use in the * Authorization header. The middleware is configured with the default * FetchAuthTokenInterface implementation to use in this environment. * * If supplied, $targetAudience is used to set the "aud" on the resulting * ID token. * * @param string $targetAudience The audience for the ID token. * @param callable $httpHandler callback which delivers psr7 request * @param array $cacheConfig configuration for the cache when it's present * @param CacheItemPoolInterface $cache A cache implementation, may be * provided if you have one already available for use. * @return AuthTokenMiddleware * @throws DomainException if no implementation can be obtained. */ public static function getIdTokenMiddleware($targetAudience, callable $httpHandler = null, array $cacheConfig = null, \Google\Site_Kit_Dependencies\Psr\Cache\CacheItemPoolInterface $cache = null) { $creds = self::getIdTokenCredentials($targetAudience, $httpHandler, $cacheConfig, $cache); return new \Google\Site_Kit_Dependencies\Google\Auth\Middleware\AuthTokenMiddleware($creds, $httpHandler); } /** * Obtains an ProxyAuthTokenMiddleware which will fetch an ID token to use in the * Authorization header. The middleware is configured with the default * FetchAuthTokenInterface implementation to use in this environment. * * If supplied, $targetAudience is used to set the "aud" on the resulting * ID token. * * @param string $targetAudience The audience for the ID token. * @param callable $httpHandler callback which delivers psr7 request * @param array $cacheConfig configuration for the cache when it's present * @param CacheItemPoolInterface $cache A cache implementation, may be * provided if you have one already available for use. * @return ProxyAuthTokenMiddleware * @throws DomainException if no implementation can be obtained. */ public static function getProxyIdTokenMiddleware($targetAudience, callable $httpHandler = null, array $cacheConfig = null, \Google\Site_Kit_Dependencies\Psr\Cache\CacheItemPoolInterface $cache = null) { $creds = self::getIdTokenCredentials($targetAudience, $httpHandler, $cacheConfig, $cache); return new \Google\Site_Kit_Dependencies\Google\Auth\Middleware\ProxyAuthTokenMiddleware($creds, $httpHandler); } /** * Obtains the default FetchAuthTokenInterface implementation to use * in this environment, configured with a $targetAudience for fetching an ID * token. * * @param string $targetAudience The audience for the ID token. * @param callable $httpHandler callback which delivers psr7 request * @param array $cacheConfig configuration for the cache when it's present * @param CacheItemPoolInterface $cache A cache implementation, may be * provided if you have one already available for use. * @return CredentialsLoader * @throws DomainException if no implementation can be obtained. * @throws InvalidArgumentException if JSON "type" key is invalid */ public static function getIdTokenCredentials($targetAudience, callable $httpHandler = null, array $cacheConfig = null, \Google\Site_Kit_Dependencies\Psr\Cache\CacheItemPoolInterface $cache = null) { $creds = null; $jsonKey = \Google\Site_Kit_Dependencies\Google\Auth\CredentialsLoader::fromEnv() ?: \Google\Site_Kit_Dependencies\Google\Auth\CredentialsLoader::fromWellKnownFile(); if (!$httpHandler) { if (!($client = \Google\Site_Kit_Dependencies\Google\Auth\HttpHandler\HttpClientCache::getHttpClient())) { $client = new \Google\Site_Kit_Dependencies\GuzzleHttp\Client(); \Google\Site_Kit_Dependencies\Google\Auth\HttpHandler\HttpClientCache::setHttpClient($client); } $httpHandler = \Google\Site_Kit_Dependencies\Google\Auth\HttpHandler\HttpHandlerFactory::build($client); } if (!\is_null($jsonKey)) { if (!\array_key_exists('type', $jsonKey)) { throw new \InvalidArgumentException('json key is missing the type field'); } if ($jsonKey['type'] == 'authorized_user') { throw new \InvalidArgumentException('ID tokens are not supported for end user credentials'); } if ($jsonKey['type'] != 'service_account') { throw new \InvalidArgumentException('invalid value in the type field'); } $creds = new \Google\Site_Kit_Dependencies\Google\Auth\Credentials\ServiceAccountCredentials(null, $jsonKey, null, $targetAudience); } elseif (self::onGce($httpHandler, $cacheConfig, $cache)) { $creds = new \Google\Site_Kit_Dependencies\Google\Auth\Credentials\GCECredentials(null, null, $targetAudience); } if (\is_null($creds)) { throw new \DomainException(self::notFound()); } if (!\is_null($cache)) { $creds = new \Google\Site_Kit_Dependencies\Google\Auth\FetchAuthTokenCache($creds, $cacheConfig, $cache); } return $creds; } private static function notFound() { $msg = 'Could not load the default credentials. Browse to '; $msg .= 'https://developers.google.com'; $msg .= '/accounts/docs/application-default-credentials'; $msg .= ' for more information'; return $msg; } private static function onGce(callable $httpHandler = null, array $cacheConfig = null, \Google\Site_Kit_Dependencies\Psr\Cache\CacheItemPoolInterface $cache = null) { $gceCacheConfig = []; foreach (['lifetime', 'prefix'] as $key) { if (isset($cacheConfig['gce_' . $key])) { $gceCacheConfig[$key] = $cacheConfig['gce_' . $key]; } } return (new \Google\Site_Kit_Dependencies\Google\Auth\GCECache($gceCacheConfig, $cache))->onGce($httpHandler); } } PK!VCG.google/auth/src/ProjectIdProviderInterface.phpnu[' */ class ScopedAccessTokenMiddleware { use CacheTrait; const DEFAULT_CACHE_LIFETIME = 1500; /** * @var CacheItemPoolInterface */ private $cache; /** * @var array configuration */ private $cacheConfig; /** * @var callable */ private $tokenFunc; /** * @var array|string */ private $scopes; /** * Creates a new ScopedAccessTokenMiddleware. * * @param callable $tokenFunc a token generator function * @param array|string $scopes the token authentication scopes * @param array $cacheConfig configuration for the cache when it's present * @param CacheItemPoolInterface $cache an implementation of CacheItemPoolInterface */ public function __construct(callable $tokenFunc, $scopes, array $cacheConfig = null, \Google\Site_Kit_Dependencies\Psr\Cache\CacheItemPoolInterface $cache = null) { $this->tokenFunc = $tokenFunc; if (!(\is_string($scopes) || \is_array($scopes))) { throw new \InvalidArgumentException('wants scope should be string or array'); } $this->scopes = $scopes; if (!\is_null($cache)) { $this->cache = $cache; $this->cacheConfig = \array_merge(['lifetime' => self::DEFAULT_CACHE_LIFETIME, 'prefix' => ''], $cacheConfig); } } /** * Updates the request with an Authorization header when auth is 'scoped'. * * E.g this could be used to authenticate using the AppEngine * AppIdentityService. * * use google\appengine\api\app_identity\AppIdentityService; * use Google\Auth\Middleware\ScopedAccessTokenMiddleware; * use GuzzleHttp\Client; * use GuzzleHttp\HandlerStack; * * $scope = 'https://www.googleapis.com/auth/taskqueue' * $middleware = new ScopedAccessTokenMiddleware( * 'AppIdentityService::getAccessToken', * $scope, * [ 'prefix' => 'Google\Auth\ScopedAccessToken::' ], * $cache = new Memcache() * ); * $stack = HandlerStack::create(); * $stack->push($middleware); * * $client = new Client([ * 'handler' => $stack, * 'base_url' => 'https://www.googleapis.com/taskqueue/v1beta2/projects/', * 'auth' => 'scoped' // authorize all requests * ]); * * $res = $client->get('myproject/taskqueues/myqueue'); * * @param callable $handler * @return \Closure */ public function __invoke(callable $handler) { return function (\Google\Site_Kit_Dependencies\Psr\Http\Message\RequestInterface $request, array $options) use($handler) { // Requests using "auth"="scoped" will be authorized. if (!isset($options['auth']) || $options['auth'] !== 'scoped') { return $handler($request, $options); } $request = $request->withHeader('authorization', 'Bearer ' . $this->fetchToken()); return $handler($request, $options); }; } /** * @return string */ private function getCacheKey() { $key = null; if (\is_string($this->scopes)) { $key .= $this->scopes; } elseif (\is_array($this->scopes)) { $key .= \implode(':', $this->scopes); } return $key; } /** * Determine if token is available in the cache, if not call tokenFunc to * fetch it. * * @return string */ private function fetchToken() { $cacheKey = $this->getCacheKey(); $cached = $this->getCachedValue($cacheKey); if (!empty($cached)) { return $cached; } $token = \call_user_func($this->tokenFunc, $this->scopes); $this->setCachedValue($cacheKey, $token); return $token; } } PK!ɺ /google/auth/src/Middleware/SimpleMiddleware.phpnu[config = \array_merge(['key' => null], $config); } /** * Updates the request query with the developer key if auth is set to simple. * * use Google\Auth\Middleware\SimpleMiddleware; * use GuzzleHttp\Client; * use GuzzleHttp\HandlerStack; * * $my_key = 'is not the same as yours'; * $middleware = new SimpleMiddleware(['key' => $my_key]); * $stack = HandlerStack::create(); * $stack->push($middleware); * * $client = new Client([ * 'handler' => $stack, * 'base_uri' => 'https://www.googleapis.com/discovery/v1/', * 'auth' => 'simple' * ]); * * $res = $client->get('drive/v2/rest'); * * @param callable $handler * @return \Closure */ public function __invoke(callable $handler) { return function (\Google\Site_Kit_Dependencies\Psr\Http\Message\RequestInterface $request, array $options) use($handler) { // Requests using "auth"="scoped" will be authorized. if (!isset($options['auth']) || $options['auth'] !== 'simple') { return $handler($request, $options); } $query = \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Query::parse($request->getUri()->getQuery()); $params = \array_merge($query, $this->config); $uri = $request->getUri()->withQuery(\Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Query::build($params)); $request = $request->withUri($uri); return $handler($request, $options); }; } } PK! I7google/auth/src/Middleware/ProxyAuthTokenMiddleware.phpnu[' */ class ProxyAuthTokenMiddleware { /** * @var callback */ private $httpHandler; /** * @var FetchAuthTokenInterface */ private $fetcher; /** * @var callable */ private $tokenCallback; /** * Creates a new ProxyAuthTokenMiddleware. * * @param FetchAuthTokenInterface $fetcher is used to fetch the auth token * @param callable $httpHandler (optional) callback which delivers psr7 request * @param callable $tokenCallback (optional) function to be called when a new token is fetched. */ public function __construct(\Google\Site_Kit_Dependencies\Google\Auth\FetchAuthTokenInterface $fetcher, callable $httpHandler = null, callable $tokenCallback = null) { $this->fetcher = $fetcher; $this->httpHandler = $httpHandler; $this->tokenCallback = $tokenCallback; } /** * Updates the request with an Authorization header when auth is 'google_auth'. * * use Google\Auth\Middleware\ProxyAuthTokenMiddleware; * use Google\Auth\OAuth2; * use GuzzleHttp\Client; * use GuzzleHttp\HandlerStack; * * $config = [...]; * $oauth2 = new OAuth2($config) * $middleware = new ProxyAuthTokenMiddleware($oauth2); * $stack = HandlerStack::create(); * $stack->push($middleware); * * $client = new Client([ * 'handler' => $stack, * 'base_uri' => 'https://www.googleapis.com/taskqueue/v1beta2/projects/', * 'proxy_auth' => 'google_auth' // authorize all requests * ]); * * $res = $client->get('myproject/taskqueues/myqueue'); * * @param callable $handler * @return \Closure */ public function __invoke(callable $handler) { return function (\Google\Site_Kit_Dependencies\Psr\Http\Message\RequestInterface $request, array $options) use($handler) { // Requests using "proxy_auth"="google_auth" will be authorized. if (!isset($options['proxy_auth']) || $options['proxy_auth'] !== 'google_auth') { return $handler($request, $options); } $request = $request->withHeader('proxy-authorization', 'Bearer ' . $this->fetchToken()); if ($quotaProject = $this->getQuotaProject()) { $request = $request->withHeader(\Google\Site_Kit_Dependencies\Google\Auth\GetQuotaProjectInterface::X_GOOG_USER_PROJECT_HEADER, $quotaProject); } return $handler($request, $options); }; } /** * Call fetcher to fetch the token. * * @return string */ private function fetchToken() { $auth_tokens = $this->fetcher->fetchAuthToken($this->httpHandler); if (\array_key_exists('access_token', $auth_tokens)) { // notify the callback if applicable if ($this->tokenCallback) { \call_user_func($this->tokenCallback, $this->fetcher->getCacheKey(), $auth_tokens['access_token']); } return $auth_tokens['access_token']; } if (\array_key_exists('id_token', $auth_tokens)) { return $auth_tokens['id_token']; } } private function getQuotaProject() { if ($this->fetcher instanceof \Google\Site_Kit_Dependencies\Google\Auth\GetQuotaProjectInterface) { return $this->fetcher->getQuotaProject(); } } } PK!nbb2google/auth/src/Middleware/AuthTokenMiddleware.phpnu[' */ class AuthTokenMiddleware { /** * @var callback */ private $httpHandler; /** * @var FetchAuthTokenInterface */ private $fetcher; /** * @var callable */ private $tokenCallback; /** * Creates a new AuthTokenMiddleware. * * @param FetchAuthTokenInterface $fetcher is used to fetch the auth token * @param callable $httpHandler (optional) callback which delivers psr7 request * @param callable $tokenCallback (optional) function to be called when a new token is fetched. */ public function __construct(\Google\Site_Kit_Dependencies\Google\Auth\FetchAuthTokenInterface $fetcher, callable $httpHandler = null, callable $tokenCallback = null) { $this->fetcher = $fetcher; $this->httpHandler = $httpHandler; $this->tokenCallback = $tokenCallback; } /** * Updates the request with an Authorization header when auth is 'google_auth'. * * use Google\Auth\Middleware\AuthTokenMiddleware; * use Google\Auth\OAuth2; * use GuzzleHttp\Client; * use GuzzleHttp\HandlerStack; * * $config = [...]; * $oauth2 = new OAuth2($config) * $middleware = new AuthTokenMiddleware($oauth2); * $stack = HandlerStack::create(); * $stack->push($middleware); * * $client = new Client([ * 'handler' => $stack, * 'base_uri' => 'https://www.googleapis.com/taskqueue/v1beta2/projects/', * 'auth' => 'google_auth' // authorize all requests * ]); * * $res = $client->get('myproject/taskqueues/myqueue'); * * @param callable $handler * @return \Closure */ public function __invoke(callable $handler) { return function (\Google\Site_Kit_Dependencies\Psr\Http\Message\RequestInterface $request, array $options) use($handler) { // Requests using "auth"="google_auth" will be authorized. if (!isset($options['auth']) || $options['auth'] !== 'google_auth') { return $handler($request, $options); } $request = $request->withHeader('authorization', 'Bearer ' . $this->fetchToken()); if ($quotaProject = $this->getQuotaProject()) { $request = $request->withHeader(\Google\Site_Kit_Dependencies\Google\Auth\GetQuotaProjectInterface::X_GOOG_USER_PROJECT_HEADER, $quotaProject); } return $handler($request, $options); }; } /** * Call fetcher to fetch the token. * * @return string */ private function fetchToken() { $auth_tokens = $this->fetcher->fetchAuthToken($this->httpHandler); if (\array_key_exists('access_token', $auth_tokens)) { // notify the callback if applicable if ($this->tokenCallback) { \call_user_func($this->tokenCallback, $this->fetcher->getCacheKey(), $auth_tokens['access_token']); } return $auth_tokens['access_token']; } if (\array_key_exists('id_token', $auth_tokens)) { return $auth_tokens['id_token']; } } private function getQuotaProject() { if ($this->fetcher instanceof \Google\Site_Kit_Dependencies\Google\Auth\GetQuotaProjectInterface) { return $this->fetcher->getQuotaProject(); } } } PK!google/auth/src/CacheTrait.phpnu[cache)) { return; } $key = $this->getFullCacheKey($k); if (\is_null($key)) { return; } $cacheItem = $this->cache->getItem($key); if ($cacheItem->isHit()) { return $cacheItem->get(); } } /** * Saves the value in the cache when that is available. */ private function setCachedValue($k, $v) { if (\is_null($this->cache)) { return; } $key = $this->getFullCacheKey($k); if (\is_null($key)) { return; } $cacheItem = $this->cache->getItem($key); $cacheItem->set($v); $cacheItem->expiresAfter($this->cacheConfig['lifetime']); return $this->cache->save($cacheItem); } private function getFullCacheKey($key) { if (\is_null($key)) { return; } $key = $this->cacheConfig['prefix'] . $key; // ensure we do not have illegal characters $key = \preg_replace('|[^a-zA-Z0-9_\\.!]|', '', $key); // Hash keys if they exceed $maxKeyLength (defaults to 64) if ($this->maxKeyLength && \strlen($key) > $this->maxKeyLength) { $key = \substr(\hash('sha256', $key), 0, $this->maxKeyLength); } return $key; } } PK!3!+google/auth/src/FetchAuthTokenInterface.phpnu[fetcher = $fetcher; $this->cache = $cache; $this->cacheConfig = \array_merge(['lifetime' => 1500, 'prefix' => ''], (array) $cacheConfig); } /** * Implements FetchAuthTokenInterface#fetchAuthToken. * * Checks the cache for a valid auth token and fetches the auth tokens * from the supplied fetcher. * * @param callable $httpHandler callback which delivers psr7 request * @return array the response * @throws \Exception */ public function fetchAuthToken(callable $httpHandler = null) { if ($cached = $this->fetchAuthTokenFromCache()) { return $cached; } $auth_token = $this->fetcher->fetchAuthToken($httpHandler); $this->saveAuthTokenInCache($auth_token); return $auth_token; } /** * @return string */ public function getCacheKey() { return $this->getFullCacheKey($this->fetcher->getCacheKey()); } /** * @return array|null */ public function getLastReceivedToken() { return $this->fetcher->getLastReceivedToken(); } /** * Get the client name from the fetcher. * * @param callable $httpHandler An HTTP handler to deliver PSR7 requests. * @return string */ public function getClientName(callable $httpHandler = null) { if (!$this->fetcher instanceof \Google\Site_Kit_Dependencies\Google\Auth\SignBlobInterface) { throw new \RuntimeException('Credentials fetcher does not implement ' . 'Google\\Auth\\SignBlobInterface'); } return $this->fetcher->getClientName($httpHandler); } /** * Sign a blob using the fetcher. * * @param string $stringToSign The string to sign. * @param bool $forceOpenSsl Require use of OpenSSL for local signing. Does * not apply to signing done using external services. **Defaults to** * `false`. * @return string The resulting signature. * @throws \RuntimeException If the fetcher does not implement * `Google\Auth\SignBlobInterface`. */ public function signBlob($stringToSign, $forceOpenSsl = \false) { if (!$this->fetcher instanceof \Google\Site_Kit_Dependencies\Google\Auth\SignBlobInterface) { throw new \RuntimeException('Credentials fetcher does not implement ' . 'Google\\Auth\\SignBlobInterface'); } // Pass the access token from cache to GCECredentials for signing a blob. // This saves a call to the metadata server when a cached token exists. if ($this->fetcher instanceof \Google\Site_Kit_Dependencies\Google\Auth\Credentials\GCECredentials) { $cached = $this->fetchAuthTokenFromCache(); $accessToken = isset($cached['access_token']) ? $cached['access_token'] : null; return $this->fetcher->signBlob($stringToSign, $forceOpenSsl, $accessToken); } return $this->fetcher->signBlob($stringToSign, $forceOpenSsl); } /** * Get the quota project used for this API request from the credentials * fetcher. * * @return string|null */ public function getQuotaProject() { if ($this->fetcher instanceof \Google\Site_Kit_Dependencies\Google\Auth\GetQuotaProjectInterface) { return $this->fetcher->getQuotaProject(); } } /* * Get the Project ID from the fetcher. * * @param callable $httpHandler Callback which delivers psr7 request * @return string|null * @throws \RuntimeException If the fetcher does not implement * `Google\Auth\ProvidesProjectIdInterface`. */ public function getProjectId(callable $httpHandler = null) { if (!$this->fetcher instanceof \Google\Site_Kit_Dependencies\Google\Auth\ProjectIdProviderInterface) { throw new \RuntimeException('Credentials fetcher does not implement ' . 'Google\\Auth\\ProvidesProjectIdInterface'); } return $this->fetcher->getProjectId($httpHandler); } /** * Updates metadata with the authorization token. * * @param array $metadata metadata hashmap * @param string $authUri optional auth uri * @param callable $httpHandler callback which delivers psr7 request * @return array updated metadata hashmap * @throws \RuntimeException If the fetcher does not implement * `Google\Auth\UpdateMetadataInterface`. */ public function updateMetadata($metadata, $authUri = null, callable $httpHandler = null) { if (!$this->fetcher instanceof \Google\Site_Kit_Dependencies\Google\Auth\UpdateMetadataInterface) { throw new \RuntimeException('Credentials fetcher does not implement ' . 'Google\\Auth\\UpdateMetadataInterface'); } $cached = $this->fetchAuthTokenFromCache($authUri); if ($cached) { // Set the access token in the `Authorization` metadata header so // the downstream call to updateMetadata know they don't need to // fetch another token. if (isset($cached['access_token'])) { $metadata[self::AUTH_METADATA_KEY] = ['Bearer ' . $cached['access_token']]; } } $newMetadata = $this->fetcher->updateMetadata($metadata, $authUri, $httpHandler); if (!$cached && ($token = $this->fetcher->getLastReceivedToken())) { $this->saveAuthTokenInCache($token, $authUri); } return $newMetadata; } private function fetchAuthTokenFromCache($authUri = null) { // Use the cached value if its available. // // TODO: correct caching; update the call to setCachedValue to set the expiry // to the value returned with the auth token. // // TODO: correct caching; enable the cache to be cleared. // if $authUri is set, use it as the cache key $cacheKey = $authUri ? $this->getFullCacheKey($authUri) : $this->fetcher->getCacheKey(); $cached = $this->getCachedValue($cacheKey); if (\is_array($cached)) { if (empty($cached['expires_at'])) { // If there is no expiration data, assume token is not expired. // (for JwtAccess and ID tokens) return $cached; } if (\time() < $cached['expires_at']) { // access token is not expired return $cached; } } return null; } private function saveAuthTokenInCache($authToken, $authUri = null) { if (isset($authToken['access_token']) || isset($authToken['id_token'])) { // if $authUri is set, use it as the cache key $cacheKey = $authUri ? $this->getFullCacheKey($authUri) : $this->fetcher->getCacheKey(); $this->setCachedValue($cacheKey, $authToken); } } } PK!} } .google/auth/src/Credentials/IAMCredentials.phpnu[selector = $selector; $this->token = $token; } /** * export a callback function which updates runtime metadata. * * @return array updateMetadata function */ public function getUpdateMetadataFunc() { return array($this, 'updateMetadata'); } /** * Updates metadata with the appropriate header metadata. * * @param array $metadata metadata hashmap * @param string $unusedAuthUri optional auth uri * @param callable $httpHandler callback which delivers psr7 request * Note: this param is unused here, only included here for * consistency with other credentials class * * @return array updated metadata hashmap */ public function updateMetadata($metadata, $unusedAuthUri = null, callable $httpHandler = null) { $metadata_copy = $metadata; $metadata_copy[self::SELECTOR_KEY] = $this->selector; $metadata_copy[self::TOKEN_KEY] = $this->token; return $metadata_copy; } } PK!o\G)G)9google/auth/src/Credentials/ServiceAccountCredentials.phpnu[push($middleware); * * $client = new Client([ * 'handler' => $stack, * 'base_uri' => 'https://www.googleapis.com/taskqueue/v1beta2/projects/', * 'auth' => 'google_auth' // authorize all requests * ]); * * $res = $client->get('myproject/taskqueues/myqueue'); */ class ServiceAccountCredentials extends \Google\Site_Kit_Dependencies\Google\Auth\CredentialsLoader implements \Google\Site_Kit_Dependencies\Google\Auth\GetQuotaProjectInterface, \Google\Site_Kit_Dependencies\Google\Auth\SignBlobInterface, \Google\Site_Kit_Dependencies\Google\Auth\ProjectIdProviderInterface { use ServiceAccountSignerTrait; /** * The OAuth2 instance used to conduct authorization. * * @var OAuth2 */ protected $auth; /** * The quota project associated with the JSON credentials * * @var string */ protected $quotaProject; /* * @var string|null */ protected $projectId; /* * @var array|null */ private $lastReceivedJwtAccessToken; /* * @var bool */ private $useJwtAccessWithScope = \false; /* * @var ServiceAccountJwtAccessCredentials|null */ private $jwtAccessCredentials; /** * Create a new ServiceAccountCredentials. * * @param string|array $scope the scope of the access request, expressed * either as an Array or as a space-delimited String. * @param string|array $jsonKey JSON credential file path or JSON credentials * as an associative array * @param string $sub an email address account to impersonate, in situations when * the service account has been delegated domain wide access. * @param string $targetAudience The audience for the ID token. */ public function __construct($scope, $jsonKey, $sub = null, $targetAudience = null) { if (\is_string($jsonKey)) { if (!\file_exists($jsonKey)) { throw new \InvalidArgumentException('file does not exist'); } $jsonKeyStream = \file_get_contents($jsonKey); if (!($jsonKey = \json_decode($jsonKeyStream, \true))) { throw new \LogicException('invalid json for auth config'); } } if (!\array_key_exists('client_email', $jsonKey)) { throw new \InvalidArgumentException('json key is missing the client_email field'); } if (!\array_key_exists('private_key', $jsonKey)) { throw new \InvalidArgumentException('json key is missing the private_key field'); } if (\array_key_exists('quota_project_id', $jsonKey)) { $this->quotaProject = (string) $jsonKey['quota_project_id']; } if ($scope && $targetAudience) { throw new \InvalidArgumentException('Scope and targetAudience cannot both be supplied'); } $additionalClaims = []; if ($targetAudience) { $additionalClaims = ['target_audience' => $targetAudience]; } $this->auth = new \Google\Site_Kit_Dependencies\Google\Auth\OAuth2(['audience' => self::TOKEN_CREDENTIAL_URI, 'issuer' => $jsonKey['client_email'], 'scope' => $scope, 'signingAlgorithm' => 'RS256', 'signingKey' => $jsonKey['private_key'], 'sub' => $sub, 'tokenCredentialUri' => self::TOKEN_CREDENTIAL_URI, 'additionalClaims' => $additionalClaims]); $this->projectId = isset($jsonKey['project_id']) ? $jsonKey['project_id'] : null; } /** * When called, the ServiceAccountCredentials will use an instance of * ServiceAccountJwtAccessCredentials to fetch (self-sign) an access token * even when only scopes are supplied. Otherwise, * ServiceAccountJwtAccessCredentials is only called when no scopes and an * authUrl (audience) is suppled. */ public function useJwtAccessWithScope() { $this->useJwtAccessWithScope = \true; } /** * @param callable $httpHandler * * @return array A set of auth related metadata, containing the following * keys: * - access_token (string) * - expires_in (int) * - token_type (string) */ public function fetchAuthToken(callable $httpHandler = null) { if ($this->useSelfSignedJwt()) { $jwtCreds = $this->createJwtAccessCredentials(); $accessToken = $jwtCreds->fetchAuthToken($httpHandler); if ($lastReceivedToken = $jwtCreds->getLastReceivedToken()) { // Keep self-signed JWTs in memory as the last received token $this->lastReceivedJwtAccessToken = $lastReceivedToken; } return $accessToken; } return $this->auth->fetchAuthToken($httpHandler); } /** * @return string */ public function getCacheKey() { $key = $this->auth->getIssuer() . ':' . $this->auth->getCacheKey(); if ($sub = $this->auth->getSub()) { $key .= ':' . $sub; } return $key; } /** * @return array */ public function getLastReceivedToken() { // If self-signed JWTs are being used, fetch the last received token // from memory. Else, fetch it from OAuth2 return $this->useSelfSignedJwt() ? $this->lastReceivedJwtAccessToken : $this->auth->getLastReceivedToken(); } /** * Get the project ID from the service account keyfile. * * Returns null if the project ID does not exist in the keyfile. * * @param callable $httpHandler Not used by this credentials type. * @return string|null */ public function getProjectId(callable $httpHandler = null) { return $this->projectId; } /** * Updates metadata with the authorization token. * * @param array $metadata metadata hashmap * @param string $authUri optional auth uri * @param callable $httpHandler callback which delivers psr7 request * @return array updated metadata hashmap */ public function updateMetadata($metadata, $authUri = null, callable $httpHandler = null) { // scope exists. use oauth implementation if (!$this->useSelfSignedJwt()) { return parent::updateMetadata($metadata, $authUri, $httpHandler); } $jwtCreds = $this->createJwtAccessCredentials(); if ($this->auth->getScope()) { // Prefer user-provided "scope" to "audience" $updatedMetadata = $jwtCreds->updateMetadata($metadata, null, $httpHandler); } else { $updatedMetadata = $jwtCreds->updateMetadata($metadata, $authUri, $httpHandler); } if ($lastReceivedToken = $jwtCreds->getLastReceivedToken()) { // Keep self-signed JWTs in memory as the last received token $this->lastReceivedJwtAccessToken = $lastReceivedToken; } return $updatedMetadata; } private function createJwtAccessCredentials() { if (!$this->jwtAccessCredentials) { // Create credentials for self-signing a JWT (JwtAccess) $credJson = array('private_key' => $this->auth->getSigningKey(), 'client_email' => $this->auth->getIssuer()); $this->jwtAccessCredentials = new \Google\Site_Kit_Dependencies\Google\Auth\Credentials\ServiceAccountJwtAccessCredentials($credJson, $this->auth->getScope()); } return $this->jwtAccessCredentials; } /** * @param string $sub an email address account to impersonate, in situations when * the service account has been delegated domain wide access. */ public function setSub($sub) { $this->auth->setSub($sub); } /** * Get the client name from the keyfile. * * In this case, it returns the keyfile's client_email key. * * @param callable $httpHandler Not used by this credentials type. * @return string */ public function getClientName(callable $httpHandler = null) { return $this->auth->getIssuer(); } /** * Get the quota project used for this API request * * @return string|null */ public function getQuotaProject() { return $this->quotaProject; } private function useSelfSignedJwt() { // If claims are set, this call is for "id_tokens" if ($this->auth->getAdditionalClaims()) { return \false; } // When true, ServiceAccountCredentials will always use JwtAccess for access tokens if ($this->useJwtAccessWithScope) { return \true; } return \is_null($this->auth->getScope()); } } PK!!\W6google/auth/src/Credentials/UserRefreshCredentials.phpnu[auth = new \Google\Site_Kit_Dependencies\Google\Auth\OAuth2(['clientId' => $jsonKey['client_id'], 'clientSecret' => $jsonKey['client_secret'], 'refresh_token' => $jsonKey['refresh_token'], 'scope' => $scope, 'tokenCredentialUri' => self::TOKEN_CREDENTIAL_URI]); if (\array_key_exists('quota_project_id', $jsonKey)) { $this->quotaProject = (string) $jsonKey['quota_project_id']; } } /** * @param callable $httpHandler * * @return array A set of auth related metadata, containing the following * keys: * - access_token (string) * - expires_in (int) * - scope (string) * - token_type (string) * - id_token (string) */ public function fetchAuthToken(callable $httpHandler = null) { return $this->auth->fetchAuthToken($httpHandler); } /** * @return string */ public function getCacheKey() { return $this->auth->getClientId() . ':' . $this->auth->getCacheKey(); } /** * @return array */ public function getLastReceivedToken() { return $this->auth->getLastReceivedToken(); } /** * Get the quota project used for this API request * * @return string|null */ public function getQuotaProject() { return $this->quotaProject; } } PK!UBgoogle/auth/src/Credentials/ServiceAccountJwtAccessCredentials.phpnu[quotaProject = (string) $jsonKey['quota_project_id']; } $this->auth = new \Google\Site_Kit_Dependencies\Google\Auth\OAuth2(['issuer' => $jsonKey['client_email'], 'sub' => $jsonKey['client_email'], 'signingAlgorithm' => 'RS256', 'signingKey' => $jsonKey['private_key'], 'scope' => $scope]); $this->projectId = isset($jsonKey['project_id']) ? $jsonKey['project_id'] : null; } /** * Updates metadata with the authorization token. * * @param array $metadata metadata hashmap * @param string $authUri optional auth uri * @param callable $httpHandler callback which delivers psr7 request * @return array updated metadata hashmap */ public function updateMetadata($metadata, $authUri = null, callable $httpHandler = null) { $scope = $this->auth->getScope(); if (empty($authUri) && empty($scope)) { return $metadata; } $this->auth->setAudience($authUri); return parent::updateMetadata($metadata, $authUri, $httpHandler); } /** * Implements FetchAuthTokenInterface#fetchAuthToken. * * @param callable $httpHandler * * @return array|void A set of auth related metadata, containing the * following keys: * - access_token (string) */ public function fetchAuthToken(callable $httpHandler = null) { $audience = $this->auth->getAudience(); $scope = $this->auth->getScope(); if (empty($audience) && empty($scope)) { return null; } if (!empty($audience) && !empty($scope)) { throw new \UnexpectedValueException('Cannot sign both audience and scope in JwtAccess'); } $access_token = $this->auth->toJwt(); // Set the self-signed access token in OAuth2 for getLastReceivedToken $this->auth->setAccessToken($access_token); return array('access_token' => $access_token); } /** * @return string */ public function getCacheKey() { return $this->auth->getCacheKey(); } /** * @return array */ public function getLastReceivedToken() { return $this->auth->getLastReceivedToken(); } /** * Get the project ID from the service account keyfile. * * Returns null if the project ID does not exist in the keyfile. * * @param callable $httpHandler Not used by this credentials type. * @return string|null */ public function getProjectId(callable $httpHandler = null) { return $this->projectId; } /** * Get the client name from the keyfile. * * In this case, it returns the keyfile's client_email key. * * @param callable $httpHandler Not used by this credentials type. * @return string */ public function getClientName(callable $httpHandler = null) { return $this->auth->getIssuer(); } /** * Get the quota project used for this API request * * @return string|null */ public function getQuotaProject() { return $this->quotaProject; } } PK!7炊3google/auth/src/Credentials/InsecureCredentials.phpnu[ '']; /** * Fetches the auth token. In this case it returns an empty string. * * @param callable $httpHandler * @return array A set of auth related metadata, containing the following * keys: * - access_token (string) */ public function fetchAuthToken(callable $httpHandler = null) { return $this->token; } /** * Returns the cache key. In this case it returns a null value, disabling * caching. * * @return string|null */ public function getCacheKey() { return null; } /** * Fetches the last received token. In this case, it returns the same empty string * auth token. * * @return array */ public function getLastReceivedToken() { return $this->token; } } PK!vXCXC.google/auth/src/Credentials/GCECredentials.phpnu[push($middleware); * * $client = new Client([ * 'handler' => $stack, * 'base_uri' => 'https://www.googleapis.com/taskqueue/v1beta2/projects/', * 'auth' => 'google_auth' * ]); * * $res = $client->get('myproject/taskqueues/myqueue'); */ class GCECredentials extends \Google\Site_Kit_Dependencies\Google\Auth\CredentialsLoader implements \Google\Site_Kit_Dependencies\Google\Auth\SignBlobInterface, \Google\Site_Kit_Dependencies\Google\Auth\ProjectIdProviderInterface, \Google\Site_Kit_Dependencies\Google\Auth\GetQuotaProjectInterface { // phpcs:disable const cacheKey = 'GOOGLE_AUTH_PHP_GCE'; // phpcs:enable /** * The metadata IP address on appengine instances. * * The IP is used instead of the domain 'metadata' to avoid slow responses * when not on Compute Engine. */ const METADATA_IP = '169.254.169.254'; /** * The metadata path of the default token. */ const TOKEN_URI_PATH = 'v1/instance/service-accounts/default/token'; /** * The metadata path of the default id token. */ const ID_TOKEN_URI_PATH = 'v1/instance/service-accounts/default/identity'; /** * The metadata path of the client ID. */ const CLIENT_ID_URI_PATH = 'v1/instance/service-accounts/default/email'; /** * The metadata path of the project ID. */ const PROJECT_ID_URI_PATH = 'v1/project/project-id'; /** * The header whose presence indicates GCE presence. */ const FLAVOR_HEADER = 'Metadata-Flavor'; /** * Note: the explicit `timeout` and `tries` below is a workaround. The underlying * issue is that resolving an unknown host on some networks will take * 20-30 seconds; making this timeout short fixes the issue, but * could lead to false negatives in the event that we are on GCE, but * the metadata resolution was particularly slow. The latter case is * "unlikely" since the expected 4-nines time is about 0.5 seconds. * This allows us to limit the total ping maximum timeout to 1.5 seconds * for developer desktop scenarios. */ const MAX_COMPUTE_PING_TRIES = 3; const COMPUTE_PING_CONNECTION_TIMEOUT_S = 0.5; /** * Flag used to ensure that the onGCE test is only done once;. * * @var bool */ private $hasCheckedOnGce = \false; /** *