Utility.php 17 KB

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