Utility.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742
  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 false;
  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. * A more robust wrapper around for file_exists() which easily
  203. * fails to return true for existent remote files.
  204. * Per default it allows http/https images to be looked up via urlExists()
  205. * for a better result.
  206. *
  207. * @param string $file File
  208. * @param string $pattern
  209. * @return bool Success
  210. */
  211. public static function fileExists($file, $pattern = '~^https?://~i') {
  212. if (!preg_match($pattern, $file)) {
  213. return file_exists($file);
  214. }
  215. return static::urlExists($file);
  216. }
  217. /**
  218. * file_exists() does not always work with URLs.
  219. * So if you check on strpos(http) === 0 you can use this
  220. * to check for URLs instead.
  221. *
  222. * @param string $url Absolute URL
  223. * @return bool Success
  224. */
  225. public static function urlExists($url) {
  226. // @codingStandardsIgnoreStart
  227. $headers = @get_headers($url);
  228. // @codingStandardsIgnoreEnd
  229. if ($headers && preg_match('|\b200\b|', $headers[0])) {
  230. return true;
  231. }
  232. return false;
  233. }
  234. /**
  235. * Parse headers from a specific URL content.
  236. *
  237. * @param string $url
  238. * @return mixed array of headers or FALSE on failure
  239. */
  240. public static function getHeaderFromUrl($url) {
  241. // @codingStandardsIgnoreStart
  242. $url = @parse_url($url);
  243. // @codingStandardsIgnoreEnd
  244. if (empty($url)) {
  245. return false;
  246. }
  247. $url = array_map('trim', $url);
  248. $url['port'] = (!isset($url['port'])) ? '' : (':' . (int)$url['port']);
  249. $path = (isset($url['path'])) ? $url['path'] : '';
  250. if (empty($path)) {
  251. $path = '/';
  252. }
  253. $path .= (isset($url['query'])) ? "?$url[query]" : '';
  254. $defaults = [
  255. 'http' => [
  256. 'header' => "Accept: text/html\r\n" .
  257. "Connection: Close\r\n" .
  258. "User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64)\r\n",
  259. ]
  260. ];
  261. stream_context_get_default($defaults);
  262. if (isset($url['host']) && $url['host'] !== gethostbyname($url['host'])) {
  263. $url = "$url[scheme]://$url[host]$url[port]$path";
  264. $headers = get_headers($url);
  265. if (is_array($headers)) {
  266. return $headers;
  267. }
  268. }
  269. return false;
  270. }
  271. /**
  272. * Add protocol prefix if necessary (and possible)
  273. *
  274. * @param string $url
  275. * @param string|null $prefix
  276. * @return string
  277. */
  278. public static function autoPrefixUrl($url, $prefix = null) {
  279. if ($prefix === null) {
  280. $prefix = 'http://';
  281. }
  282. $pos = strpos($url, '.');
  283. if ($pos !== false) {
  284. if (strpos(substr($url, 0, $pos), '//') === false) {
  285. $url = $prefix . $url;
  286. }
  287. }
  288. return $url;
  289. }
  290. /**
  291. * Returns true only if all values are true.
  292. *
  293. * @param array $array
  294. * @return bool Result
  295. */
  296. public static function logicalAnd($array) {
  297. if (empty($array)) {
  298. return false;
  299. }
  300. foreach ($array as $result) {
  301. if (!$result) {
  302. return false;
  303. }
  304. }
  305. return true;
  306. }
  307. /**
  308. * Returns true if at least one value is true.
  309. *
  310. * @param array $array
  311. * @return bool Result
  312. */
  313. public static function logicalOr($array) {
  314. foreach ($array as $result) {
  315. if ($result) {
  316. return true;
  317. }
  318. }
  319. return false;
  320. }
  321. /**
  322. * On non-transaction db connections it will return a deep array of bools instead of bool.
  323. * So we need to call this method inside the modified saveAll() method to return the expected single bool there, too.
  324. *
  325. * @param array $array
  326. * @return bool
  327. * @deprecated Not sure this is useful for CakePHP 3.0
  328. */
  329. public static function isValidSaveAll($array) {
  330. if (!$array) {
  331. return false;
  332. }
  333. $ret = true;
  334. foreach ($array as $key => $val) {
  335. if (is_array($val)) {
  336. $ret = $ret & static::logicalAnd($val);
  337. } else {
  338. $ret = $ret & $val;
  339. }
  340. }
  341. return (bool)$ret;
  342. }
  343. /**
  344. * Convenience function for automatic casting in form methods etc.
  345. *
  346. * @param mixed $value
  347. * @param string $type
  348. * @return mixed Safe value for DB query, or NULL if type was not a valid one
  349. */
  350. public static function typeCast($value, $type) {
  351. switch ($type) {
  352. case 'int':
  353. $value = (int)$value;
  354. break;
  355. case 'float':
  356. $value = (float)$value;
  357. break;
  358. case 'double':
  359. $value = (double)$value;
  360. break;
  361. case 'array':
  362. $value = (array)$value;
  363. break;
  364. case 'bool':
  365. $value = (bool)$value;
  366. break;
  367. case 'string':
  368. $value = (string)$value;
  369. break;
  370. default:
  371. return null;
  372. }
  373. return $value;
  374. }
  375. /**
  376. * Trim recursively
  377. *
  378. * @param mixed $value
  379. * @return array|string
  380. */
  381. public static function trimDeep($value) {
  382. $value = is_array($value) ? array_map('self::trimDeep', $value) : trim($value);
  383. return $value;
  384. }
  385. /**
  386. * Applies h() recursively
  387. *
  388. * @param mixed $value
  389. * @return array|string
  390. */
  391. public static function specialcharsDeep($value) {
  392. $value = is_array($value) ? array_map('self::specialcharsDeep', $value) : htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
  393. return $value;
  394. }
  395. /**
  396. * Main deep method
  397. *
  398. * @param callable $function
  399. * @param mixed $value
  400. * @return array|string
  401. */
  402. public static function deep($function, $value) {
  403. $value = is_array($value) ? array_map('self::' . $function, $value) : $function($value);
  404. return $value;
  405. }
  406. /**
  407. * Counts the dimensions of an array. If $all is set to false (which is the default) it will
  408. * only consider the dimension of the first element in the array.
  409. *
  410. * @param array $array Array to count dimensions on
  411. * @param bool $all Set to true to count the dimension considering all elements in array
  412. * @param int $count Start the dimension count at this number
  413. * @return int The number of dimensions in $array
  414. */
  415. public static function countDim($array, $all = false, $count = 0) {
  416. if ($all) {
  417. $depth = [$count];
  418. if (is_array($array) && reset($array) !== false) {
  419. foreach ($array as $value) {
  420. $depth[] = static::countDim($value, true, $count + 1);
  421. }
  422. }
  423. $return = max($depth);
  424. } else {
  425. if (is_array(reset($array))) {
  426. $return = static::countDim(reset($array)) + 1;
  427. } else {
  428. $return = 1;
  429. }
  430. }
  431. return $return;
  432. }
  433. /**
  434. * Expands the values of an array of strings into a deep array.
  435. * Opposite of flattenList().
  436. *
  437. * It needs at least a single separator to be present in all values
  438. * as the key would otherwise be undefined. If data can contain such key-less
  439. * rows, use $undefinedKey to avoid an exception being thrown. But it will
  440. * effectivly collide with other values in that same key then.
  441. *
  442. * So `Some.Deep.Value` becomes `array('Some' => array('Deep' => array('Value')))`.
  443. *
  444. * @param array $data
  445. * @param string $separator
  446. * @param string|null $undefinedKey
  447. * @return array
  448. */
  449. public static function expandList(array $data, $separator = '.', $undefinedKey = null) {
  450. $result = [];
  451. foreach ($data as $value) {
  452. $keys = explode($separator, $value);
  453. $value = array_pop($keys);
  454. $keys = array_reverse($keys);
  455. if (!isset($keys[0])) {
  456. if ($undefinedKey === null) {
  457. throw new RuntimeException('Key-less values are not supported without $undefinedKey.');
  458. }
  459. $keys[0] = $undefinedKey;
  460. }
  461. $child = [$keys[0] => [$value]];
  462. array_shift($keys);
  463. foreach ($keys as $k) {
  464. $child = [
  465. $k => $child
  466. ];
  467. }
  468. $result = Hash::merge($result, $child);
  469. }
  470. return $result;
  471. }
  472. /**
  473. * Flattens a deep array into an array of strings.
  474. * Opposite of expandList().
  475. *
  476. * So `array('Some' => array('Deep' => array('Value')))` becomes `Some.Deep.Value`.
  477. *
  478. * Note that primarily only string should be used.
  479. * However, boolean values are casted to int and thus
  480. * both boolean and integer values also supported.
  481. *
  482. * @param array $data
  483. * @param string $separator
  484. * @return array
  485. */
  486. public static function flattenList(array $data, $separator = '.') {
  487. $result = [];
  488. $stack = [];
  489. $path = null;
  490. reset($data);
  491. while (!empty($data)) {
  492. $key = key($data);
  493. $element = $data[$key];
  494. unset($data[$key]);
  495. if (is_array($element) && !empty($element)) {
  496. if (!empty($data)) {
  497. $stack[] = [$data, $path];
  498. }
  499. $data = $element;
  500. reset($data);
  501. $path .= $key . $separator;
  502. } else {
  503. if (is_bool($element)) {
  504. $element = (int)$element;
  505. }
  506. $result[] = $path . $element;
  507. }
  508. if (empty($data) && !empty($stack)) {
  509. list($data, $path) = array_pop($stack);
  510. reset($data);
  511. }
  512. }
  513. return $result;
  514. }
  515. /**
  516. * Force-flattens an array.
  517. *
  518. * Careful with this method. It can lose information.
  519. * The keys will not be changed, thus possibly overwrite each other.
  520. *
  521. * //TODO: check if it can be replace by Hash::flatten() or Utility::flatten().
  522. *
  523. * @param array $array Array to flatten
  524. * @param bool $preserveKeys
  525. * @return array
  526. */
  527. public static function arrayFlatten($array, $preserveKeys = false) {
  528. if ($preserveKeys) {
  529. return static::_arrayFlatten($array);
  530. }
  531. if (!$array) {
  532. return [];
  533. }
  534. $result = [];
  535. foreach ($array as $key => $value) {
  536. if (is_array($value)) {
  537. $result = array_merge($result, static::arrayFlatten($value));
  538. } else {
  539. $result[$key] = $value;
  540. }
  541. }
  542. return $result;
  543. }
  544. /**
  545. * Force-flattens an array and preserves the keys.
  546. *
  547. * Careful with this method. It can lose information.
  548. * The keys will not be changed, thus possibly overwrite each other.
  549. *
  550. * //TODO: check if it can be replace by Hash::flatten() or Utility::flatten().
  551. *
  552. * @param array $a
  553. * @param array $f
  554. * @return array
  555. */
  556. protected static function _arrayFlatten($a, $f = []) {
  557. if (!$a) {
  558. return [];
  559. }
  560. foreach ($a as $k => $v) {
  561. if (is_array($v)) {
  562. $f = static::_arrayFlatten($v, $f);
  563. } else {
  564. $f[$k] = $v;
  565. }
  566. }
  567. return $f;
  568. }
  569. /**
  570. * Similar to array_shift but on the keys of the array
  571. * like array_shift() only for keys and not values
  572. *
  573. * @param array $array keyValuePairs
  574. * @return string key
  575. */
  576. public static function arrayShiftKeys(&$array) {
  577. foreach ($array as $key => $value) {
  578. unset($array[$key]);
  579. return $key;
  580. }
  581. }
  582. /**
  583. * @var int
  584. */
  585. protected static $_counterStartTime;
  586. /**
  587. * Returns microtime as float value
  588. * (to be subtracted right away)
  589. *
  590. * @param int $precision
  591. * @return float
  592. */
  593. public static function microtime($precision = 8) {
  594. return round(microtime(true), $precision);
  595. }
  596. /**
  597. * @return void
  598. */
  599. public static function startClock() {
  600. static::$_counterStartTime = static::microtime();
  601. }
  602. /**
  603. * @param int $precision
  604. * @param bool $restartClock
  605. * @return float
  606. */
  607. public static function returnElapsedTime($precision = 8, $restartClock = false) {
  608. $startTime = static::$_counterStartTime;
  609. if ($restartClock) {
  610. static::startClock();
  611. }
  612. return static::calcElapsedTime($startTime, static::microtime(), $precision);
  613. }
  614. /**
  615. * Returns microtime as float value
  616. * (to be subtracted right away)
  617. *
  618. * @param int $start
  619. * @param int $end
  620. * @param int $precision
  621. * @return float
  622. */
  623. public static function calcElapsedTime($start, $end, $precision = 8) {
  624. $elapsed = $end - $start;
  625. return round($elapsed, $precision);
  626. }
  627. /**
  628. * Returns pretty JSON
  629. *
  630. * @link https://github.com/ndejong/pretty_json/blob/master/pretty_json.php
  631. * @param string $json The original JSON string
  632. * @param string $indString The string to indent with
  633. * @return string
  634. * @deprecated Now there is a JSON_PRETTY_PRINT option available on json_encode()
  635. */
  636. public static function prettyJson($json, $indString = "\t") {
  637. // Replace any escaped \" marks so we don't get tripped up on quotemarks_counter
  638. $tokens = preg_split('|([\{\}\]\[,])|', str_replace('\"', '~~PRETTY_JSON_QUOTEMARK~~', $json), -1, PREG_SPLIT_DELIM_CAPTURE);
  639. $indent = 0;
  640. $result = '';
  641. $quotemarksCounter = 0;
  642. $nextTokenUsePrefix = true;
  643. foreach ($tokens as $token) {
  644. $quotemarksCounter = $quotemarksCounter + (count(explode('"', $token)) - 1);
  645. if ($token === '') {
  646. continue;
  647. }
  648. if ($nextTokenUsePrefix) {
  649. $prefix = str_repeat($indString, $indent);
  650. } else {
  651. $prefix = null;
  652. }
  653. // Determine if the quote marks are open or closed
  654. if ($quotemarksCounter & 1) {
  655. // odd - thus quotemarks open
  656. $nextTokenUsePrefix = false;
  657. $newLine = null;
  658. } else {
  659. // even - thus quotemarks closed
  660. $nextTokenUsePrefix = true;
  661. $newLine = "\n";
  662. }
  663. if ($token === '{' || $token === '[') {
  664. $indent++;
  665. $result .= $token . $newLine;
  666. } elseif ($token === '}' || $token === ']') {
  667. $indent--;
  668. if ($indent >= 0) {
  669. $prefix = str_repeat($indString, $indent);
  670. }
  671. if ($nextTokenUsePrefix) {
  672. $result .= $newLine . $prefix . $token;
  673. } else {
  674. $result .= $newLine . $token;
  675. }
  676. } elseif ($token === ',') {
  677. $result .= $token . $newLine;
  678. } else {
  679. $result .= $prefix . $token;
  680. }
  681. }
  682. return str_replace('~~PRETTY_JSON_QUOTEMARK~~', '\"', $result);
  683. }
  684. }