PluginProbe
Media Cloud Sync / 1.2.12
Media Cloud Sync v1.2.12
1.4.0 1.3.12 1.3.11 1.3.10 trunk 1.0.0 1.0.1 1.0.2 1.0.3 1.1.0 1.1.1 1.2.0 1.2.10 1.2.11 1.2.12 1.2.13 1.2.2 1.2.3 1.2.4 1.2.5 1.2.6 1.2.7 1.2.8 1.2.9 1.3.0 All 34 releases
media-cloud-sync / includes / sdk / s3 / Aws / functions.php

functions.php in Media Cloud Sync 1.2.12, at includes/sdk/s3/Aws/functions.php

475 lines 13.6 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 namespace Dudlewebs\WPMCS\s3\Aws;
4
5 use Dudlewebs\WPMCS\s3\GuzzleHttp\Client;
6 use Dudlewebs\WPMCS\s3\Psr\Http\Message\RequestInterface;
7 use Dudlewebs\WPMCS\s3\GuzzleHttp\ClientInterface;
8 use Dudlewebs\WPMCS\s3\GuzzleHttp\Promise\FulfilledPromise;
9 //-----------------------------------------------------------------------------
10 // Functional functions
11 //-----------------------------------------------------------------------------
12 /**
13 * Returns a function that always returns the same value;
14 *
15 * @param mixed $value Value to return.
16 *
17 * @return callable
18 */
19 function constantly($value)
20 {
21 return function () use($value) {
22 return $value;
23 };
24 }
25 /**
26 * Filters values that do not satisfy the predicate function $pred.
27 *
28 * @param mixed $iterable Iterable sequence of data.
29 * @param callable $pred Function that accepts a value and returns true/false
30 *
31 * @return \Generator
32 */
33 function filter($iterable, callable $pred)
34 {
35 foreach ($iterable as $value) {
36 if ($pred($value)) {
37 (yield $value);
38 }
39 }
40 }
41 /**
42 * Applies a map function $f to each value in a collection.
43 *
44 * @param mixed $iterable Iterable sequence of data.
45 * @param callable $f Map function to apply.
46 *
47 * @return \Generator
48 */
49 function map($iterable, callable $f)
50 {
51 foreach ($iterable as $value) {
52 (yield $f($value));
53 }
54 }
55 /**
56 * Creates a generator that iterates over a sequence, then iterates over each
57 * value in the sequence and yields the application of the map function to each
58 * value.
59 *
60 * @param mixed $iterable Iterable sequence of data.
61 * @param callable $f Map function to apply.
62 *
63 * @return \Generator
64 */
65 function flatmap($iterable, callable $f)
66 {
67 foreach (map($iterable, $f) as $outer) {
68 foreach ($outer as $inner) {
69 (yield $inner);
70 }
71 }
72 }
73 /**
74 * Partitions the input sequence into partitions of the specified size.
75 *
76 * @param mixed $iterable Iterable sequence of data.
77 * @param int $size Size to make each partition (except possibly the last chunk)
78 *
79 * @return \Generator
80 */
81 function partition($iterable, $size)
82 {
83 $buffer = [];
84 foreach ($iterable as $value) {
85 $buffer[] = $value;
86 if (\count($buffer) === $size) {
87 (yield $buffer);
88 $buffer = [];
89 }
90 }
91 if ($buffer) {
92 (yield $buffer);
93 }
94 }
95 /**
96 * Returns a function that invokes the provided variadic functions one
97 * after the other until one of the functions returns a non-null value.
98 * The return function will call each passed function with any arguments it
99 * is provided.
100 *
101 * $a = function ($x, $y) { return null; };
102 * $b = function ($x, $y) { return $x + $y; };
103 * $fn = \Aws\or_chain($a, $b);
104 * echo $fn(1, 2); // 3
105 *
106 * @return callable
107 */
108 function or_chain()
109 {
110 $fns = \func_get_args();
111 return function () use($fns) {
112 $args = \func_get_args();
113 foreach ($fns as $fn) {
114 $result = $args ? \call_user_func_array($fn, $args) : $fn();
115 if ($result) {
116 return $result;
117 }
118 }
119 return null;
120 };
121 }
122 //-----------------------------------------------------------------------------
123 // JSON compiler and loading functions
124 //-----------------------------------------------------------------------------
125 /**
126 * Loads a compiled JSON file from a PHP file.
127 *
128 * If the JSON file has not been cached to disk as a PHP file, it will be loaded
129 * from the JSON source file and returned.
130 *
131 * @param string $path Path to the JSON file on disk
132 *
133 * @return mixed Returns the JSON decoded data. Note that JSON objects are
134 * decoded as associative arrays.
135 */
136 function load_compiled_json($path)
137 {
138 static $compiledList = [];
139 $compiledFilepath = "{$path}.php";
140 if (!isset($compiledList[$compiledFilepath])) {
141 if (\is_readable($compiledFilepath)) {
142 $compiledList[$compiledFilepath] = (include $compiledFilepath);
143 }
144 }
145 if (isset($compiledList[$compiledFilepath])) {
146 return $compiledList[$compiledFilepath];
147 }
148 if (!\file_exists($path)) {
149 throw new \InvalidArgumentException(\sprintf("File not found: %s", $path));
150 }
151 return \json_decode(\file_get_contents($path), \true);
152 }
153 /**
154 * No-op
155 */
156 function clear_compiled_json()
157 {
158 // pass
159 }
160 //-----------------------------------------------------------------------------
161 // Directory iterator functions.
162 //-----------------------------------------------------------------------------
163 /**
164 * Iterates over the files in a directory and works with custom wrappers.
165 *
166 * @param string $path Path to open (e.g., "s3://foo/bar").
167 * @param resource $context Stream wrapper context.
168 *
169 * @return \Generator Yields relative filename strings.
170 */
171 function dir_iterator($path, $context = null)
172 {
173 $dh = $context ? \opendir($path, $context) : \opendir($path);
174 if (!$dh) {
175 throw new \InvalidArgumentException('File not found: ' . $path);
176 }
177 while (($file = \readdir($dh)) !== \false) {
178 (yield $file);
179 }
180 \closedir($dh);
181 }
182 /**
183 * Returns a recursive directory iterator that yields absolute filenames.
184 *
185 * This iterator is not broken like PHP's built-in DirectoryIterator (which
186 * will read the first file from a stream wrapper, then rewind, then read
187 * it again).
188 *
189 * @param string $path Path to traverse (e.g., s3://bucket/key, /tmp)
190 * @param resource $context Stream context options.
191 *
192 * @return \Generator Yields absolute filenames.
193 */
194 function recursive_dir_iterator($path, $context = null)
195 {
196 $invalid = ['.' => \true, '..' => \true];
197 $pathLen = \strlen($path) + 1;
198 $iterator = dir_iterator($path, $context);
199 $queue = [];
200 do {
201 while ($iterator->valid()) {
202 $file = $iterator->current();
203 $iterator->next();
204 if (isset($invalid[\basename($file)])) {
205 continue;
206 }
207 $fullPath = "{$path}/{$file}";
208 (yield $fullPath);
209 if (\is_dir($fullPath)) {
210 $queue[] = $iterator;
211 $iterator = map(dir_iterator($fullPath, $context), function ($file) use($fullPath, $pathLen) {
212 return \substr("{$fullPath}/{$file}", $pathLen);
213 });
214 continue;
215 }
216 }
217 $iterator = \array_pop($queue);
218 } while ($iterator);
219 }
220 //-----------------------------------------------------------------------------
221 // Misc. functions.
222 //-----------------------------------------------------------------------------
223 /**
224 * Debug function used to describe the provided value type and class.
225 *
226 * @param mixed $input
227 *
228 * @return string Returns a string containing the type of the variable and
229 * if a class is provided, the class name.
230 */
231 function describe_type($input)
232 {
233 switch (\gettype($input)) {
234 case 'object':
235 return 'object(' . \get_class($input) . ')';
236 case 'array':
237 return 'array(' . \count($input) . ')';
238 default:
239 \ob_start();
240 \var_dump($input);
241 // normalize float vs double
242 return \str_replace('double(', 'float(', \rtrim(\ob_get_clean()));
243 }
244 }
245 /**
246 * Creates a default HTTP handler based on the available clients.
247 *
248 * @return callable
249 */
250 function default_http_handler()
251 {
252 $version = guzzle_major_version();
253 // If Guzzle 6 or 7 installed
254 if ($version === 6 || $version === 7) {
255 return new \Dudlewebs\WPMCS\s3\Aws\Handler\GuzzleV6\GuzzleHandler();
256 }
257 // If Guzzle 5 installed
258 if ($version === 5) {
259 return new \Dudlewebs\WPMCS\s3\Aws\Handler\GuzzleV5\GuzzleHandler();
260 }
261 throw new \RuntimeException('Unknown Guzzle version: ' . $version);
262 }
263 /**
264 * Gets the default user agent string depending on the Guzzle version
265 *
266 * @return string
267 */
268 function default_user_agent()
269 {
270 $version = guzzle_major_version();
271 // If Guzzle 6 or 7 installed
272 if ($version === 6 || $version === 7) {
273 return \Dudlewebs\WPMCS\s3\GuzzleHttp\default_user_agent();
274 }
275 // If Guzzle 5 installed
276 if ($version === 5) {
277 return \Dudlewebs\WPMCS\s3\GuzzleHttp\Client::getDefaultUserAgent();
278 }
279 throw new \RuntimeException('Unknown Guzzle version: ' . $version);
280 }
281 /**
282 * Get the major version of guzzle that is installed.
283 *
284 * @internal This function is internal and should not be used outside aws/aws-sdk-php.
285 * @return int
286 * @throws \RuntimeException
287 */
288 function guzzle_major_version()
289 {
290 static $cache = null;
291 if (null !== $cache) {
292 return $cache;
293 }
294 if (\defined('Dudlewebs\\WPMCS\\s3\\GuzzleHttp\\ClientInterface::VERSION')) {
295 $version = (string) ClientInterface::VERSION;
296 if ($version[0] === '6') {
297 return $cache = 6;
298 }
299 if ($version[0] === '5') {
300 return $cache = 5;
301 }
302 } elseif (\defined('Dudlewebs\\WPMCS\\s3\\GuzzleHttp\\ClientInterface::MAJOR_VERSION')) {
303 return $cache = ClientInterface::MAJOR_VERSION;
304 }
305 throw new \RuntimeException('Unable to determine what Guzzle version is installed.');
306 }
307 /**
308 * Serialize a request for a command but do not send it.
309 *
310 * Returns a promise that is fulfilled with the serialized request.
311 *
312 * @param CommandInterface $command Command to serialize.
313 *
314 * @return RequestInterface
315 * @throws \RuntimeException
316 */
317 function serialize(CommandInterface $command)
318 {
319 $request = null;
320 $handlerList = $command->getHandlerList();
321 // Return a mock result.
322 $handlerList->setHandler(function (CommandInterface $_, RequestInterface $r) use(&$request) {
323 $request = $r;
324 return new FulfilledPromise(new Result([]));
325 });
326 \call_user_func($handlerList->resolve(), $command)->wait();
327 if (!$request instanceof RequestInterface) {
328 throw new \RuntimeException('Calling handler did not serialize request');
329 }
330 return $request;
331 }
332 /**
333 * Retrieves data for a service from the SDK's service manifest file.
334 *
335 * Manifest data is stored statically, so it does not need to be loaded more
336 * than once per process. The JSON data is also cached in opcache.
337 *
338 * @param string $service Case-insensitive namespace or endpoint prefix of the
339 * service for which you are retrieving manifest data.
340 *
341 * @return array
342 * @throws \InvalidArgumentException if the service is not supported.
343 */
344 function manifest($service = null)
345 {
346 // Load the manifest and create aliases for lowercased namespaces
347 static $manifest = [];
348 static $aliases = [];
349 if (empty($manifest)) {
350 $manifest = load_compiled_json(__DIR__ . '/data/manifest.json');
351 foreach ($manifest as $endpoint => $info) {
352 $alias = \strtolower($info['namespace']);
353 if ($alias !== $endpoint) {
354 $aliases[$alias] = $endpoint;
355 }
356 }
357 }
358 // If no service specified, then return the whole manifest.
359 if ($service === null) {
360 return $manifest;
361 }
362 // Look up the service's info in the manifest data.
363 $service = \strtolower($service);
364 if (isset($manifest[$service])) {
365 return $manifest[$service] + ['endpoint' => $service];
366 }
367 if (isset($aliases[$service])) {
368 return manifest($aliases[$service]);
369 }
370 throw new \InvalidArgumentException("The service \"{$service}\" is not provided by the AWS SDK for PHP.");
371 }
372 /**
373 * Checks if supplied parameter is a valid hostname
374 *
375 * @param string $hostname
376 * @return bool
377 */
378 function is_valid_hostname($hostname)
379 {
380 return \preg_match("/^([a-z\\d](-*[a-z\\d])*)(\\.([a-z\\d](-*[a-z\\d])*))*\\.?\$/i", $hostname) && \preg_match("/^.{1,253}\$/", $hostname) && \preg_match("/^[^\\.]{1,63}(\\.[^\\.]{0,63})*\$/", $hostname);
381 }
382 /**
383 * Checks if supplied parameter is a valid host label
384 *
385 * @param $label
386 * @return bool
387 */
388 function is_valid_hostlabel($label)
389 {
390 return \preg_match("/^(?!-)[a-zA-Z0-9-]{1,63}(?<!-)\$/", $label);
391 }
392 /**
393 * Ignores '#' full line comments, which parse_ini_file no longer does
394 * in PHP 7+.
395 *
396 * @param $filename
397 * @param bool $process_sections
398 * @param int $scanner_mode
399 * @return array|bool
400 */
401 function parse_ini_file($filename, $process_sections = \false, $scanner_mode = \INI_SCANNER_NORMAL)
402 {
403 return \parse_ini_string(\preg_replace('/^#.*\\n/m', "", \file_get_contents($filename)), $process_sections, $scanner_mode);
404 }
405 /**
406 * Outputs boolean value of input for a select range of possible values,
407 * null otherwise
408 *
409 * @param $input
410 * @return bool|null
411 */
412 function boolean_value($input)
413 {
414 if (\is_bool($input)) {
415 return $input;
416 }
417 if ($input === 0) {
418 return \false;
419 }
420 if ($input === 1) {
421 return \true;
422 }
423 if (\is_string($input)) {
424 switch (\strtolower($input)) {
425 case "true":
426 case "on":
427 case "1":
428 return \true;
429 break;
430 case "false":
431 case "off":
432 case "0":
433 return \false;
434 break;
435 }
436 }
437 return null;
438 }
439 /**
440 * Checks if an input is a valid epoch time
441 *
442 * @param $input
443 * @return bool
444 */
445 function is_valid_epoch($input)
446 {
447 if (\is_string($input) || \is_numeric($input)) {
448 if (\is_string($input) && !\preg_match("/^-?[0-9]+\\.?[0-9]*\$/", $input)) {
449 return \false;
450 }
451 return \true;
452 }
453 return \false;
454 }
455 /**
456 * Checks if an input is a fips pseudo region
457 *
458 * @param $region
459 * @return bool
460 */
461 function is_fips_pseudo_region($region)
462 {
463 return \strpos($region, 'fips-') !== \false || \strpos($region, '-fips') !== \false;
464 }
465 /**
466 * Returns a region without a fips label
467 *
468 * @param $region
469 * @return string
470 */
471 function strip_fips_pseudo_regions($region)
472 {
473 return \str_replace(['fips-', '-fips'], ['', ''], $region);
474 }
475