Utility.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769
  1. <?php
  2. namespace Tools\Utility;
  3. use Cake\Routing\Router;
  4. use Cake\Utility\Hash;
  5. use RuntimeException;
  6. /**
  7. * Main class for all app-wide utility methods
  8. *
  9. * @author Mark Scherer
  10. * @license MIT
  11. */
  12. class Utility {
  13. /**
  14. * More sane !empty() method to not false positive `'0'` (0 as string) as empty.
  15. *
  16. * @param mixed $value
  17. * @return bool
  18. */
  19. public static function notEmpty($value) {
  20. return !empty($value) || $value === '0';
  21. }
  22. /**
  23. * Clean implementation of inArray to avoid false positives.
  24. *
  25. * in_array itself has some PHP flaws regarding cross-type comparison:
  26. * - in_array('50x', array(40, 50, 60)) would be true!
  27. * - in_array(50, array('40x', '50x', '60x')) would be true!
  28. *
  29. * @param mixed $needle
  30. * @param array $haystack
  31. * @return bool Success
  32. */
  33. public static function inArray($needle, $haystack) {
  34. $strict = !is_numeric($needle);
  35. return in_array((string)$needle, $haystack, $strict);
  36. }
  37. /**
  38. * Tokenizes a string using $separator.
  39. *
  40. * Options
  41. * - clean: true/false (defaults to true and removes empty tokens and whitespace)
  42. *
  43. * @param string $data The data to tokenize
  44. * @param string $separator The token to split the data on.
  45. * @param array $options
  46. * @return array
  47. */
  48. public static function tokenize($data, $separator = ',', $options = []) {
  49. $defaults = [
  50. 'clean' => true
  51. ];
  52. $options += $defaults;
  53. if (empty($data)) {
  54. return [];
  55. }
  56. $tokens = explode($separator, $data);
  57. if (empty($tokens) || !$options['clean']) {
  58. return $tokens;
  59. }
  60. $tokens = array_map('trim', $tokens);
  61. foreach ($tokens as $key => $token) {
  62. if ($token === '') {
  63. unset($tokens[$key]);
  64. }
  65. }
  66. return $tokens;
  67. }
  68. /**
  69. * Multibyte analogue of preg_match_all() function. Only that this returns the result.
  70. * By default this works properly with UTF8 strings.
  71. *
  72. * Do not forget to use preg_quote() first on strings that could potentially contain
  73. * unescaped characters.
  74. *
  75. * Note that you still need to add the u modifier (for UTF8) to your pattern yourself.
  76. *
  77. * Example: /some(.*)pattern/u
  78. *
  79. * @param string $pattern The pattern to use.
  80. * @param string $subject The string to match.
  81. * @param int $flags
  82. * @param int|null $offset
  83. * @return array Result
  84. */
  85. public static function pregMatchAll($pattern, $subject, $flags = PREG_SET_ORDER, $offset = null) {
  86. $pattern = substr($pattern, 0, 1) . '(*UTF8)' . substr($pattern, 1);
  87. preg_match_all($pattern, $subject, $matches, $flags, $offset);
  88. return $matches;
  89. }
  90. /**
  91. * Multibyte analogue of preg_match() function. Only that this returns the result.
  92. * By default this works properly with UTF8 strings.
  93. *
  94. * Do not forget to use preg_quote() first on strings that could potentially contain
  95. * unescaped characters.
  96. *
  97. * Note that you still need to add the u modifier (for UTF8) to your pattern yourself.
  98. *
  99. * Example: /some(.*)pattern/u
  100. *
  101. * @param string $pattern The pattern to use.
  102. * @param string $subject The string to match.
  103. * @param int|null $flags
  104. * @param int|null $offset
  105. * @return array Result
  106. */
  107. public static function pregMatch($pattern, $subject, $flags = null, $offset = null) {
  108. $pattern = substr($pattern, 0, 1) . '(*UTF8)' . substr($pattern, 1);
  109. preg_match($pattern, $subject, $matches, $flags, $offset);
  110. return $matches;
  111. }
  112. /**
  113. * Multibyte analogue of str_split() function.
  114. * By default this works properly with UTF8 strings.
  115. *
  116. * @param string $str
  117. * @param int $length
  118. * @return array Result
  119. */
  120. public static function strSplit($str, $length = 1) {
  121. if ($length < 1) {
  122. return [];
  123. }
  124. $result = [];
  125. $c = mb_strlen($str);
  126. for ($i = 0; $i < $c; $i += $length) {
  127. $result[] = mb_substr($str, $i, $length);
  128. }
  129. return $result;
  130. }
  131. /**
  132. * Get the current IP address.
  133. *
  134. * @param bool $safe
  135. * @return string IP address
  136. */
  137. public static function getClientIp($safe = true) {
  138. if (!$safe && env('HTTP_X_FORWARDED_FOR')) {
  139. $ipaddr = preg_replace('/(?:,.*)/', '', env('HTTP_X_FORWARDED_FOR'));
  140. } elseif (!$safe && env('HTTP_CLIENT_IP')) {
  141. $ipaddr = env('HTTP_CLIENT_IP');
  142. } else {
  143. $ipaddr = env('REMOTE_ADDR');
  144. }
  145. return trim($ipaddr);
  146. }
  147. /**
  148. * Get the current referrer if available.
  149. *
  150. * @param bool $full (defaults to false and leaves the url untouched)
  151. * @return string referer (local or foreign)
  152. */
  153. public static function getReferer($full = false) {
  154. $ref = env('HTTP_REFERER');
  155. $forwarded = env('HTTP_X_FORWARDED_HOST');
  156. if ($forwarded) {
  157. $ref = $forwarded;
  158. }
  159. if (empty($ref)) {
  160. return $ref;
  161. }
  162. if ($full) {
  163. $ref = Router::url($ref, $full);
  164. }
  165. return $ref;
  166. }
  167. /**
  168. * Remove unnessary stuff + add http:// for external urls
  169. * TODO: protocol to lower!
  170. *
  171. * @param string $url
  172. * @param bool $headerRedirect
  173. * @return string Cleaned Url
  174. */
  175. public static function cleanUrl($url, $headerRedirect = false) {
  176. if ($url === '' || $url === 'http://' || $url === 'http://www' || $url === 'http://www.') {
  177. $url = '';
  178. } else {
  179. $url = static::autoPrefixUrl($url, 'http://');
  180. }
  181. if ($headerRedirect && !empty($url)) {
  182. $headers = static::getHeaderFromUrl($url);
  183. if ($headers !== false) {
  184. $headerString = implode("\n", $headers);
  185. if ((bool)preg_match('#^HTTP/.*\s+[(301)]+\s#i', $headerString)) {
  186. foreach ($headers as $header) {
  187. if (mb_strpos($header, 'Location:') === 0) {
  188. $url = trim(hDec(mb_substr($header, 9))); // rawurldecode/urldecode ?
  189. }
  190. }
  191. }
  192. }
  193. }
  194. $length = mb_strlen($url);
  195. while (!empty($url) && mb_strrpos($url, '/') === $length - 1) {
  196. $url = mb_substr($url, 0, $length - 1);
  197. $length--;
  198. }
  199. return $url;
  200. }
  201. /**
  202. * Removes http:// or other protocols from the link.
  203. *
  204. * @param string $url
  205. * @param array $protocols Defaults to http and https. Pass empty array for all.
  206. * @return string strippedUrl
  207. */
  208. public static function stripProtocol($url, $protocols = ['http', 'https']) {
  209. $pieces = parse_url($url);
  210. // Already stripped?
  211. if (empty($pieces['scheme'])) {
  212. return $url;
  213. }
  214. if ($protocols && !in_array($pieces['scheme'], $protocols)) {
  215. return $url;
  216. }
  217. return mb_substr($url, mb_strlen($pieces['scheme']) + 3);
  218. }
  219. /**
  220. * A more robust wrapper around for file_exists() which easily
  221. * fails to return true for existent remote files.
  222. * Per default it allows http/https images to be looked up via urlExists()
  223. * for a better result.
  224. *
  225. * @param string $file File
  226. * @param string $pattern
  227. * @return bool Success
  228. */
  229. public static function fileExists($file, $pattern = '~^https?://~i') {
  230. if (!preg_match($pattern, $file)) {
  231. return file_exists($file);
  232. }
  233. return static::urlExists($file);
  234. }
  235. /**
  236. * file_exists() does not always work with URLs.
  237. * So if you check on strpos(http) === 0 you can use this
  238. * to check for URLs instead.
  239. *
  240. * @param string $url Absolute URL
  241. * @return bool Success
  242. */
  243. public static function urlExists($url) {
  244. // @codingStandardsIgnoreStart
  245. $headers = @get_headers($url);
  246. // @codingStandardsIgnoreEnd
  247. if ($headers && preg_match('|\b200\b|', $headers[0])) {
  248. return true;
  249. }
  250. return false;
  251. }
  252. /**
  253. * Parse headers from a specific URL content.
  254. *
  255. * @param string $url
  256. * @return mixed array of headers or FALSE on failure
  257. */
  258. public static function getHeaderFromUrl($url) {
  259. // @codingStandardsIgnoreStart
  260. $url = @parse_url($url);
  261. // @codingStandardsIgnoreEnd
  262. if (empty($url)) {
  263. return false;
  264. }
  265. $url = array_map('trim', $url);
  266. $url['port'] = (!isset($url['port'])) ? '' : (':' . (int)$url['port']);
  267. $path = (isset($url['path'])) ? $url['path'] : '';
  268. if (empty($path)) {
  269. $path = '/';
  270. }
  271. $path .= (isset($url['query'])) ? "?$url[query]" : '';
  272. $defaults = [
  273. 'http' => [
  274. 'header' => "Accept: text/html\r\n" .
  275. "Connection: Close\r\n" .
  276. "User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64)\r\n",
  277. ]
  278. ];
  279. stream_context_get_default($defaults);
  280. if (isset($url['host']) && $url['host'] !== gethostbyname($url['host'])) {
  281. $url = "$url[scheme]://$url[host]$url[port]$path";
  282. $headers = get_headers($url);
  283. if (is_array($headers)) {
  284. return $headers;
  285. }
  286. }
  287. return false;
  288. }
  289. /**
  290. * Add protocol prefix if necessary (and possible)
  291. *
  292. * @param string $url
  293. * @param string|null $prefix
  294. * @return string
  295. */
  296. public static function autoPrefixUrl($url, $prefix = null) {
  297. if ($prefix === null) {
  298. $prefix = 'http://';
  299. }
  300. $pos = strpos($url, '.');
  301. if ($pos !== false) {
  302. if (strpos(substr($url, 0, $pos), '//') === false) {
  303. $url = $prefix . $url;
  304. }
  305. }
  306. return $url;
  307. }
  308. /**
  309. * Returns true only if all values are true.
  310. *
  311. * @param array $array
  312. * @return bool Result
  313. */
  314. public static function logicalAnd($array) {
  315. if (empty($array)) {
  316. return false;
  317. }
  318. foreach ($array as $result) {
  319. if (!$result) {
  320. return false;
  321. }
  322. }
  323. return true;
  324. }
  325. /**
  326. * Returns true if at least one value is true.
  327. *
  328. * @param array $array
  329. * @return bool Result
  330. */
  331. public static function logicalOr($array) {
  332. foreach ($array as $result) {
  333. if ($result) {
  334. return true;
  335. }
  336. }
  337. return false;
  338. }
  339. /**
  340. * On non-transaction db connections it will return a deep array of bools instead of bool.
  341. * So we need to call this method inside the modified saveAll() method to return the expected single bool there, too.
  342. *
  343. * @param array $array
  344. * @return bool
  345. * @deprecated Not sure this is useful for CakePHP 3.0
  346. */
  347. public static function isValidSaveAll($array) {
  348. if (!$array) {
  349. return false;
  350. }
  351. $ret = true;
  352. foreach ($array as $key => $val) {
  353. if (is_array($val)) {
  354. $ret = $ret & static::logicalAnd($val);
  355. } else {
  356. $ret = $ret & $val;
  357. }
  358. }
  359. return (bool)$ret;
  360. }
  361. /**
  362. * Convenience function for automatic casting in form methods etc.
  363. *
  364. * @param mixed $value
  365. * @param string $type
  366. * @return mixed Safe value for DB query, or NULL if type was not a valid one
  367. */
  368. public static function typeCast($value, $type) {
  369. switch ($type) {
  370. case 'int':
  371. $value = (int)$value;
  372. break;
  373. case 'float':
  374. $value = (float)$value;
  375. break;
  376. case 'double':
  377. $value = (double)$value;
  378. break;
  379. case 'array':
  380. $value = (array)$value;
  381. break;
  382. case 'bool':
  383. $value = (bool)$value;
  384. break;
  385. case 'string':
  386. $value = (string)$value;
  387. break;
  388. default:
  389. return null;
  390. }
  391. return $value;
  392. }
  393. /**
  394. * Trim recursively
  395. *
  396. * @param string|array|null $value
  397. * @param bool $transformNullToString
  398. * @return array|string
  399. */
  400. public static function trimDeep($value, $transformNullToString = false) {
  401. if (is_array($value)) {
  402. foreach ($value as $k => $v) {
  403. $value[$k] = static::trimDeep($v, $transformNullToString);
  404. }
  405. return $value;
  406. }
  407. return ($value === null && !$transformNullToString) ? $value : trim($value);
  408. }
  409. /**
  410. * Applies h() recursively
  411. *
  412. * @param string|array $value
  413. * @return array|string
  414. */
  415. public static function specialcharsDeep($value) {
  416. $value = is_array($value) ? array_map('self::specialcharsDeep', $value) : htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
  417. return $value;
  418. }
  419. /**
  420. * Main deep method
  421. *
  422. * @param string|callable $function Callable or function name.
  423. * @param mixed $value
  424. * @return array|string
  425. */
  426. public static function deep($function, $value) {
  427. $value = is_array($value) ? array_map('self::' . $function, $value) : $function($value);
  428. return $value;
  429. }
  430. /**
  431. * Counts the dimensions of an array. If $all is set to false (which is the default) it will
  432. * only consider the dimension of the first element in the array.
  433. *
  434. * @param array $array Array to count dimensions on
  435. * @param bool $all Set to true to count the dimension considering all elements in array
  436. * @param int $count Start the dimension count at this number
  437. * @return int The number of dimensions in $array
  438. */
  439. public static function countDim($array, $all = false, $count = 0) {
  440. if ($all) {
  441. $depth = [$count];
  442. if (is_array($array) && reset($array) !== false) {
  443. foreach ($array as $value) {
  444. $depth[] = static::countDim($value, true, $count + 1);
  445. }
  446. }
  447. $return = max($depth);
  448. } else {
  449. if (is_array(reset($array))) {
  450. $return = static::countDim(reset($array)) + 1;
  451. } else {
  452. $return = 1;
  453. }
  454. }
  455. return $return;
  456. }
  457. /**
  458. * Expands the values of an array of strings into a deep array.
  459. * Opposite of flattenList().
  460. *
  461. * It needs at least a single separator to be present in all values
  462. * as the key would otherwise be undefined. If data can contain such key-less
  463. * rows, use $undefinedKey to avoid an exception being thrown. But it will
  464. * effectivly collide with other values in that same key then.
  465. *
  466. * So `Some.Deep.Value` becomes `array('Some' => array('Deep' => array('Value')))`.
  467. *
  468. * @param array $data
  469. * @param string $separator
  470. * @param string|null $undefinedKey
  471. * @return array
  472. */
  473. public static function expandList(array $data, $separator = '.', $undefinedKey = null) {
  474. $result = [];
  475. foreach ($data as $value) {
  476. $keys = explode($separator, $value);
  477. $value = array_pop($keys);
  478. $keys = array_reverse($keys);
  479. if (!isset($keys[0])) {
  480. if ($undefinedKey === null) {
  481. throw new RuntimeException('Key-less values are not supported without $undefinedKey.');
  482. }
  483. $keys[0] = $undefinedKey;
  484. }
  485. $child = [$keys[0] => [$value]];
  486. array_shift($keys);
  487. foreach ($keys as $k) {
  488. $child = [
  489. $k => $child
  490. ];
  491. }
  492. $result = Hash::merge($result, $child);
  493. }
  494. return $result;
  495. }
  496. /**
  497. * Flattens a deep array into an array of strings.
  498. * Opposite of expandList().
  499. *
  500. * So `array('Some' => array('Deep' => array('Value')))` becomes `Some.Deep.Value`.
  501. *
  502. * Note that primarily only string should be used.
  503. * However, boolean values are casted to int and thus
  504. * both boolean and integer values also supported.
  505. *
  506. * @param array $data
  507. * @param string $separator
  508. * @return array
  509. */
  510. public static function flattenList(array $data, $separator = '.') {
  511. $result = [];
  512. $stack = [];
  513. $path = null;
  514. reset($data);
  515. while (!empty($data)) {
  516. $key = key($data);
  517. $element = $data[$key];
  518. unset($data[$key]);
  519. if (is_array($element) && !empty($element)) {
  520. if (!empty($data)) {
  521. $stack[] = [$data, $path];
  522. }
  523. $data = $element;
  524. reset($data);
  525. $path .= $key . $separator;
  526. } else {
  527. if (is_bool($element)) {
  528. $element = (int)$element;
  529. }
  530. $result[] = $path . $element;
  531. }
  532. if (empty($data) && !empty($stack)) {
  533. list($data, $path) = array_pop($stack);
  534. reset($data);
  535. }
  536. }
  537. return $result;
  538. }
  539. /**
  540. * Force-flattens an array.
  541. *
  542. * Careful with this method. It can lose information.
  543. * The keys will not be changed, thus possibly overwrite each other.
  544. *
  545. * //TODO: check if it can be replace by Hash::flatten() or Utility::flatten().
  546. *
  547. * @param array $array Array to flatten
  548. * @param bool $preserveKeys
  549. * @return array
  550. */
  551. public static function arrayFlatten($array, $preserveKeys = false) {
  552. if ($preserveKeys) {
  553. return static::_arrayFlatten($array);
  554. }
  555. if (!$array) {
  556. return [];
  557. }
  558. $result = [];
  559. foreach ($array as $key => $value) {
  560. if (is_array($value)) {
  561. $result = array_merge($result, static::arrayFlatten($value));
  562. } else {
  563. $result[$key] = $value;
  564. }
  565. }
  566. return $result;
  567. }
  568. /**
  569. * Force-flattens an array and preserves the keys.
  570. *
  571. * Careful with this method. It can lose information.
  572. * The keys will not be changed, thus possibly overwrite each other.
  573. *
  574. * //TODO: check if it can be replace by Hash::flatten() or Utility::flatten().
  575. *
  576. * @param array $a
  577. * @param array $f
  578. * @return array
  579. */
  580. protected static function _arrayFlatten($a, $f = []) {
  581. if (!$a) {
  582. return [];
  583. }
  584. foreach ($a as $k => $v) {
  585. if (is_array($v)) {
  586. $f = static::_arrayFlatten($v, $f);
  587. } else {
  588. $f[$k] = $v;
  589. }
  590. }
  591. return $f;
  592. }
  593. /**
  594. * Similar to array_shift but on the keys of the array
  595. * like array_shift() only for keys and not values
  596. *
  597. * @param array $array keyValuePairs
  598. * @return string key
  599. */
  600. public static function arrayShiftKeys(&$array) {
  601. foreach ($array as $key => $value) {
  602. unset($array[$key]);
  603. return $key;
  604. }
  605. }
  606. /**
  607. * @var float
  608. */
  609. protected static $_counterStartTime = 0.0;
  610. /**
  611. * Returns microtime as float value
  612. * (to be subtracted right away)
  613. *
  614. * @param int $precision
  615. * @return float
  616. */
  617. public static function microtime($precision = 8) {
  618. return round(microtime(true), $precision);
  619. }
  620. /**
  621. * @return void
  622. */
  623. public static function startClock() {
  624. static::$_counterStartTime = static::microtime();
  625. }
  626. /**
  627. * @param int $precision
  628. * @param bool $restartClock
  629. * @return float
  630. */
  631. public static function returnElapsedTime($precision = 8, $restartClock = false) {
  632. $startTime = static::$_counterStartTime;
  633. if ($restartClock) {
  634. static::startClock();
  635. }
  636. return static::calcElapsedTime($startTime, static::microtime(), $precision);
  637. }
  638. /**
  639. * Returns microtime as float value
  640. * (to be subtracted right away)
  641. *
  642. * @param int $start
  643. * @param int $end
  644. * @param int $precision
  645. * @return float
  646. */
  647. public static function calcElapsedTime($start, $end, $precision = 8) {
  648. $elapsed = $end - $start;
  649. return round($elapsed, $precision);
  650. }
  651. /**
  652. * Returns pretty JSON
  653. *
  654. * @link https://github.com/ndejong/pretty_json/blob/master/pretty_json.php
  655. * @param string $json The original JSON string
  656. * @param string $indString The string to indent with
  657. * @return string
  658. * @deprecated Now there is a JSON_PRETTY_PRINT option available on json_encode()
  659. */
  660. public static function prettyJson($json, $indString = "\t") {
  661. // Replace any escaped \" marks so we don't get tripped up on quotemarks_counter
  662. $tokens = preg_split('|([\{\}\]\[,])|', str_replace('\"', '~~PRETTY_JSON_QUOTEMARK~~', $json), -1, PREG_SPLIT_DELIM_CAPTURE);
  663. $indent = 0;
  664. $result = '';
  665. $quotemarksCounter = 0;
  666. $nextTokenUsePrefix = true;
  667. foreach ($tokens as $token) {
  668. $quotemarksCounter = $quotemarksCounter + (count(explode('"', $token)) - 1);
  669. if ($token === '') {
  670. continue;
  671. }
  672. if ($nextTokenUsePrefix) {
  673. $prefix = str_repeat($indString, $indent);
  674. } else {
  675. $prefix = null;
  676. }
  677. // Determine if the quote marks are open or closed
  678. if ($quotemarksCounter & 1) {
  679. // odd - thus quotemarks open
  680. $nextTokenUsePrefix = false;
  681. $newLine = null;
  682. } else {
  683. // even - thus quotemarks closed
  684. $nextTokenUsePrefix = true;
  685. $newLine = "\n";
  686. }
  687. if ($token === '{' || $token === '[') {
  688. $indent++;
  689. $result .= $token . $newLine;
  690. } elseif ($token === '}' || $token === ']') {
  691. $indent--;
  692. if ($indent >= 0) {
  693. $prefix = str_repeat($indString, $indent);
  694. }
  695. if ($nextTokenUsePrefix) {
  696. $result .= $newLine . $prefix . $token;
  697. } else {
  698. $result .= $newLine . $token;
  699. }
  700. } elseif ($token === ',') {
  701. $result .= $token . $newLine;
  702. } else {
  703. $result .= $prefix . $token;
  704. }
  705. }
  706. return str_replace('~~PRETTY_JSON_QUOTEMARK~~', '\"', $result);
  707. }
  708. }