Utils.php 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149
  1. <?php
  2. /**
  3. * @package Grav.Common
  4. *
  5. * @copyright Copyright (C) 2015 - 2018 Trilby Media, LLC. All rights reserved.
  6. * @license MIT License; see LICENSE file for details.
  7. */
  8. namespace Grav\Common;
  9. use DateTime;
  10. use Grav\Common\Helpers\Truncator;
  11. use Grav\Common\Page\Page;
  12. use RocketTheme\Toolbox\Event\Event;
  13. use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
  14. abstract class Utils
  15. {
  16. protected static $nonces = [];
  17. /**
  18. * Simple helper method to make getting a Grav URL easier
  19. *
  20. * @param $input
  21. * @param bool $domain
  22. * @return bool|null|string
  23. */
  24. public static function url($input, $domain = false)
  25. {
  26. if (!trim((string)$input)) {
  27. return false;
  28. }
  29. if (Grav::instance()['config']->get('system.absolute_urls', false)) {
  30. $domain = true;
  31. }
  32. if (Grav::instance()['uri']->isExternal($input)) {
  33. return $input;
  34. }
  35. $input = ltrim((string)$input, '/');
  36. if (Utils::contains((string)$input, '://')) {
  37. /** @var UniformResourceLocator $locator */
  38. $locator = Grav::instance()['locator'];
  39. $parts = Uri::parseUrl($input);
  40. if ($parts) {
  41. $resource = $locator->findResource("{$parts['scheme']}://{$parts['host']}{$parts['path']}", false);
  42. if (isset($parts['query'])) {
  43. $resource = $resource . '?' . $parts['query'];
  44. }
  45. } else {
  46. // Not a valid URL (can still be a stream).
  47. $resource = $locator->findResource($input, false);
  48. }
  49. } else {
  50. $resource = $input;
  51. }
  52. /** @var Uri $uri */
  53. $uri = Grav::instance()['uri'];
  54. return $resource ? rtrim($uri->rootUrl($domain), '/') . '/' . $resource : null;
  55. }
  56. /**
  57. * Check if the $haystack string starts with the substring $needle
  58. *
  59. * @param string $haystack
  60. * @param string|string[] $needle
  61. *
  62. * @return bool
  63. */
  64. public static function startsWith($haystack, $needle)
  65. {
  66. $status = false;
  67. foreach ((array)$needle as $each_needle) {
  68. $status = $each_needle === '' || strpos($haystack, $each_needle) === 0;
  69. if ($status) {
  70. break;
  71. }
  72. }
  73. return $status;
  74. }
  75. /**
  76. * Check if the $haystack string ends with the substring $needle
  77. *
  78. * @param string $haystack
  79. * @param string|string[] $needle
  80. *
  81. * @return bool
  82. */
  83. public static function endsWith($haystack, $needle)
  84. {
  85. $status = false;
  86. foreach ((array)$needle as $each_needle) {
  87. $status = $each_needle === '' || substr($haystack, -strlen($each_needle)) === $each_needle;
  88. if ($status) {
  89. break;
  90. }
  91. }
  92. return $status;
  93. }
  94. /**
  95. * Check if the $haystack string contains the substring $needle
  96. *
  97. * @param string $haystack
  98. * @param string|string[] $needle
  99. *
  100. * @return bool
  101. */
  102. public static function contains($haystack, $needle)
  103. {
  104. $status = false;
  105. foreach ((array)$needle as $each_needle) {
  106. $status = $each_needle === '' || strpos($haystack, $each_needle) !== false;
  107. if ($status) {
  108. break;
  109. }
  110. }
  111. return $status;
  112. }
  113. /**
  114. * Returns the substring of a string up to a specified needle. if not found, return the whole haystack
  115. *
  116. * @param $haystack
  117. * @param $needle
  118. *
  119. * @return string
  120. */
  121. public static function substrToString($haystack, $needle)
  122. {
  123. if (static::contains($haystack, $needle)) {
  124. return substr($haystack, 0, strpos($haystack, $needle));
  125. }
  126. return $haystack;
  127. }
  128. /**
  129. * Utility method to replace only the first occurrence in a string
  130. *
  131. * @param $search
  132. * @param $replace
  133. * @param $subject
  134. * @return mixed
  135. */
  136. public static function replaceFirstOccurrence($search, $replace, $subject)
  137. {
  138. if (!$search) {
  139. return $subject;
  140. }
  141. $pos = strpos($subject, $search);
  142. if ($pos !== false) {
  143. $subject = substr_replace($subject, $replace, $pos, strlen($search));
  144. }
  145. return $subject;
  146. }
  147. /**
  148. * Utility method to replace only the last occurrence in a string
  149. *
  150. * @param $search
  151. * @param $replace
  152. * @param $subject
  153. * @return mixed
  154. */
  155. public static function replaceLastOccurrence($search, $replace, $subject)
  156. {
  157. $pos = strrpos($subject, $search);
  158. if($pos !== false)
  159. {
  160. $subject = substr_replace($subject, $replace, $pos, strlen($search));
  161. }
  162. return $subject;
  163. }
  164. /**
  165. * Merge two objects into one.
  166. *
  167. * @param object $obj1
  168. * @param object $obj2
  169. *
  170. * @return object
  171. */
  172. public static function mergeObjects($obj1, $obj2)
  173. {
  174. return (object)array_merge((array)$obj1, (array)$obj2);
  175. }
  176. /**
  177. * Recursive Merge with uniqueness
  178. *
  179. * @param $array1
  180. * @param $array2
  181. * @return mixed
  182. */
  183. public static function arrayMergeRecursiveUnique($array1, $array2)
  184. {
  185. if (empty($array1)) {
  186. // Optimize the base case
  187. return $array2;
  188. }
  189. foreach ($array2 as $key => $value) {
  190. if (is_array($value) && isset($array1[$key]) && is_array($array1[$key])) {
  191. $value = static::arrayMergeRecursiveUnique($array1[$key], $value);
  192. }
  193. $array1[$key] = $value;
  194. }
  195. return $array1;
  196. }
  197. /**
  198. * Return the Grav date formats allowed
  199. *
  200. * @return array
  201. */
  202. public static function dateFormats()
  203. {
  204. $now = new DateTime();
  205. $date_formats = [
  206. 'd-m-Y H:i' => 'd-m-Y H:i (e.g. '.$now->format('d-m-Y H:i').')',
  207. 'Y-m-d H:i' => 'Y-m-d H:i (e.g. '.$now->format('Y-m-d H:i').')',
  208. 'm/d/Y h:i a' => 'm/d/Y h:i a (e.g. '.$now->format('m/d/Y h:i a').')',
  209. 'H:i d-m-Y' => 'H:i d-m-Y (e.g. '.$now->format('H:i d-m-Y').')',
  210. 'h:i a m/d/Y' => 'h:i a m/d/Y (e.g. '.$now->format('h:i a m/d/Y').')',
  211. ];
  212. $default_format = Grav::instance()['config']->get('system.pages.dateformat.default');
  213. if ($default_format) {
  214. $date_formats = array_merge([$default_format => $default_format.' (e.g. '.$now->format($default_format).')'], $date_formats);
  215. }
  216. return $date_formats;
  217. }
  218. /**
  219. * Truncate text by number of characters but can cut off words.
  220. *
  221. * @param string $string
  222. * @param int $limit Max number of characters.
  223. * @param bool $up_to_break truncate up to breakpoint after char count
  224. * @param string $break Break point.
  225. * @param string $pad Appended padding to the end of the string.
  226. *
  227. * @return string
  228. */
  229. public static function truncate($string, $limit = 150, $up_to_break = false, $break = " ", $pad = "&hellip;")
  230. {
  231. // return with no change if string is shorter than $limit
  232. if (mb_strlen($string) <= $limit) {
  233. return $string;
  234. }
  235. // is $break present between $limit and the end of the string?
  236. if ($up_to_break && false !== ($breakpoint = mb_strpos($string, $break, $limit))) {
  237. if ($breakpoint < mb_strlen($string) - 1) {
  238. $string = mb_substr($string, 0, $breakpoint) . $pad;
  239. }
  240. } else {
  241. $string = mb_substr($string, 0, $limit) . $pad;
  242. }
  243. return $string;
  244. }
  245. /**
  246. * Truncate text by number of characters in a "word-safe" manor.
  247. *
  248. * @param string $string
  249. * @param int $limit
  250. *
  251. * @return string
  252. */
  253. public static function safeTruncate($string, $limit = 150)
  254. {
  255. return static::truncate($string, $limit, true);
  256. }
  257. /**
  258. * Truncate HTML by number of characters. not "word-safe"!
  259. *
  260. * @param string $text
  261. * @param int $length in characters
  262. * @param string $ellipsis
  263. *
  264. * @return string
  265. */
  266. public static function truncateHtml($text, $length = 100, $ellipsis = '...')
  267. {
  268. return Truncator::truncateLetters($text, $length, $ellipsis);
  269. }
  270. /**
  271. * Truncate HTML by number of characters in a "word-safe" manor.
  272. *
  273. * @param string $text
  274. * @param int $length in words
  275. * @param string $ellipsis
  276. *
  277. * @return string
  278. */
  279. public static function safeTruncateHtml($text, $length = 25, $ellipsis = '...')
  280. {
  281. return Truncator::truncateWords($text, $length, $ellipsis);
  282. }
  283. /**
  284. * Generate a random string of a given length
  285. *
  286. * @param int $length
  287. *
  288. * @return string
  289. */
  290. public static function generateRandomString($length = 5)
  291. {
  292. return substr(str_shuffle('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'), 0, $length);
  293. }
  294. /**
  295. * Provides the ability to download a file to the browser
  296. *
  297. * @param string $file the full path to the file to be downloaded
  298. * @param bool $force_download as opposed to letting browser choose if to download or render
  299. * @param int $sec Throttling, try 0.1 for some speed throttling of downloads
  300. * @param int $bytes Size of chunks to send in bytes. Default is 1024
  301. * @throws \Exception
  302. */
  303. public static function download($file, $force_download = true, $sec = 0, $bytes = 1024)
  304. {
  305. if (file_exists($file)) {
  306. // fire download event
  307. Grav::instance()->fireEvent('onBeforeDownload', new Event(['file' => $file]));
  308. $file_parts = pathinfo($file);
  309. $mimetype = static::getMimeByExtension($file_parts['extension']);
  310. $size = filesize($file); // File size
  311. // clean all buffers
  312. while (ob_get_level()) {
  313. ob_end_clean();
  314. }
  315. // required for IE, otherwise Content-Disposition may be ignored
  316. if (ini_get('zlib.output_compression')) {
  317. ini_set('zlib.output_compression', 'Off');
  318. }
  319. header('Content-Type: ' . $mimetype);
  320. header('Accept-Ranges: bytes');
  321. if ($force_download) {
  322. // output the regular HTTP headers
  323. header('Content-Disposition: attachment; filename="' . $file_parts['basename'] . '"');
  324. }
  325. // multipart-download and download resuming support
  326. if (isset($_SERVER['HTTP_RANGE'])) {
  327. list($a, $range) = explode('=', $_SERVER['HTTP_RANGE'], 2);
  328. list($range) = explode(',', $range, 2);
  329. list($range, $range_end) = explode('-', $range);
  330. $range = (int)$range;
  331. if (!$range_end) {
  332. $range_end = $size - 1;
  333. } else {
  334. $range_end = (int)$range_end;
  335. }
  336. $new_length = $range_end - $range + 1;
  337. header('HTTP/1.1 206 Partial Content');
  338. header("Content-Length: {$new_length}");
  339. header("Content-Range: bytes {$range}-{$range_end}/{$size}");
  340. } else {
  341. $range = 0;
  342. $new_length = $size;
  343. header('Content-Length: ' . $size);
  344. if (Grav::instance()['config']->get('system.cache.enabled')) {
  345. $expires = Grav::instance()['config']->get('system.pages.expires');
  346. if ($expires > 0) {
  347. $expires_date = gmdate('D, d M Y H:i:s T', time() + $expires);
  348. header('Cache-Control: max-age=' . $expires);
  349. header('Expires: ' . $expires_date);
  350. header('Pragma: cache');
  351. }
  352. header('Last-Modified: ' . gmdate('D, d M Y H:i:s T', filemtime($file)));
  353. // Return 304 Not Modified if the file is already cached in the browser
  354. if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) &&
  355. strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) >= filemtime($file))
  356. {
  357. header('HTTP/1.1 304 Not Modified');
  358. exit();
  359. }
  360. }
  361. }
  362. /* output the file itself */
  363. $chunksize = $bytes * 8; //you may want to change this
  364. $bytes_send = 0;
  365. $fp = @fopen($file, 'rb');
  366. if ($fp) {
  367. if ($range) {
  368. fseek($fp, $range);
  369. }
  370. while (!feof($fp) && (!connection_aborted()) && ($bytes_send < $new_length) ) {
  371. $buffer = fread($fp, $chunksize);
  372. echo($buffer); //echo($buffer); // is also possible
  373. flush();
  374. usleep($sec * 1000000);
  375. $bytes_send += strlen($buffer);
  376. }
  377. fclose($fp);
  378. } else {
  379. throw new \RuntimeException('Error - can not open file.');
  380. }
  381. exit;
  382. }
  383. }
  384. /**
  385. * Return the mimetype based on filename extension
  386. *
  387. * @param string $extension Extension of file (eg "txt")
  388. * @param string $default
  389. *
  390. * @return string
  391. */
  392. public static function getMimeByExtension($extension, $default = 'application/octet-stream')
  393. {
  394. $extension = strtolower($extension);
  395. // look for some standard types
  396. switch ($extension) {
  397. case null:
  398. return $default;
  399. case 'json':
  400. return 'application/json';
  401. case 'html':
  402. return 'text/html';
  403. case 'atom':
  404. return 'application/atom+xml';
  405. case 'rss':
  406. return 'application/rss+xml';
  407. case 'xml':
  408. return 'application/xml';
  409. }
  410. $media_types = Grav::instance()['config']->get('media.types');
  411. if (isset($media_types[$extension])) {
  412. if (isset($media_types[$extension]['mime'])) {
  413. return $media_types[$extension]['mime'];
  414. }
  415. }
  416. return $default;
  417. }
  418. /**
  419. * Return the mimetype based on filename
  420. *
  421. * @param string $filename Filename or path to file
  422. * @param string $default default value
  423. *
  424. * @return string
  425. */
  426. public static function getMimeByFilename($filename, $default = 'application/octet-stream')
  427. {
  428. return static::getMimeByExtension(pathinfo($filename, PATHINFO_EXTENSION), $default);
  429. }
  430. /**
  431. * Return the mimetype based on existing local file
  432. *
  433. * @param string $filename Path to the file
  434. *
  435. * @return string|bool
  436. */
  437. public static function getMimeByLocalFile($filename, $default = 'application/octet-stream')
  438. {
  439. $type = false;
  440. // For local files we can detect type by the file content.
  441. if (!stream_is_local($filename) || !file_exists($filename)) {
  442. return false;
  443. }
  444. // Prefer using finfo if it exists.
  445. if (\extension_loaded('fileinfo')) {
  446. $finfo = finfo_open(FILEINFO_SYMLINK | FILEINFO_MIME_TYPE);
  447. $type = finfo_file($finfo, $filename);
  448. finfo_close($finfo);
  449. } else {
  450. // Fall back to use getimagesize() if it is available (not recommended, but better than nothing)
  451. $info = @getimagesize($filename);
  452. if ($info) {
  453. $type = $info['mime'];
  454. }
  455. }
  456. return $type ?: static::getMimeByFilename($filename, $default);
  457. }
  458. /**
  459. * Return the mimetype based on filename extension
  460. *
  461. * @param string $mime mime type (eg "text/html")
  462. * @param string $default default value
  463. *
  464. * @return string
  465. */
  466. public static function getExtensionByMime($mime, $default = 'html')
  467. {
  468. $mime = strtolower($mime);
  469. // look for some standard mime types
  470. switch ($mime) {
  471. case '*/*':
  472. case 'text/*':
  473. case 'text/html':
  474. return 'html';
  475. case 'application/json':
  476. return 'json';
  477. case 'application/atom+xml':
  478. return 'atom';
  479. case 'application/rss+xml':
  480. return 'rss';
  481. case 'application/xml':
  482. return 'xml';
  483. }
  484. $media_types = (array)Grav::instance()['config']->get('media.types');
  485. foreach ($media_types as $extension => $type) {
  486. if ($extension === 'defaults') {
  487. continue;
  488. }
  489. if (isset($type['mime']) && $type['mime'] === $mime) {
  490. return $extension;
  491. }
  492. }
  493. return $default;
  494. }
  495. /**
  496. * Returns true if filename is considered safe.
  497. *
  498. * @param string $filename
  499. * @return bool
  500. */
  501. public static function checkFilename($filename)
  502. {
  503. $dangerous_extensions = Grav::instance()['config']->get('security.uploads_dangerous_extensions', []);
  504. array_walk($dangerous_extensions, function(&$val) {
  505. $val = '.' . $val;
  506. });
  507. $extension = '.' . pathinfo($filename, PATHINFO_EXTENSION);
  508. return !(
  509. // Empty filenames are not allowed.
  510. !$filename
  511. // Filename should not contain horizontal/vertical tabs, newlines, nils or back/forward slashes.
  512. || strtr($filename, "\t\v\n\r\0\\/", '_______') !== $filename
  513. // Filename should not start or end with dot or space.
  514. || trim($filename, '. ') !== $filename
  515. // Filename should not contain .php in it.
  516. || static::contains($extension, $dangerous_extensions)
  517. );
  518. }
  519. /**
  520. * Normalize path by processing relative `.` and `..` syntax and merging path
  521. *
  522. * @param string $path
  523. *
  524. * @return string
  525. */
  526. public static function normalizePath($path)
  527. {
  528. $root = ($path[0] === '/') ? '/' : '';
  529. $segments = explode('/', trim($path, '/'));
  530. $ret = [];
  531. foreach ($segments as $segment) {
  532. if (($segment === '.') || $segment === '') {
  533. continue;
  534. }
  535. if ($segment === '..') {
  536. array_pop($ret);
  537. } else {
  538. $ret[] = $segment;
  539. }
  540. }
  541. return $root . implode('/', $ret);
  542. }
  543. /**
  544. * Check whether a function is disabled in the PHP settings
  545. *
  546. * @param string $function the name of the function to check
  547. *
  548. * @return bool
  549. */
  550. public static function isFunctionDisabled($function)
  551. {
  552. return in_array($function, explode(',', ini_get('disable_functions')), true);
  553. }
  554. /**
  555. * Get the formatted timezones list
  556. *
  557. * @return array
  558. */
  559. public static function timezones()
  560. {
  561. $timezones = \DateTimeZone::listIdentifiers(\DateTimeZone::ALL);
  562. $offsets = [];
  563. $testDate = new \DateTime;
  564. foreach ($timezones as $zone) {
  565. $tz = new \DateTimeZone($zone);
  566. $offsets[$zone] = $tz->getOffset($testDate);
  567. }
  568. asort($offsets);
  569. $timezone_list = [];
  570. foreach ($offsets as $timezone => $offset) {
  571. $offset_prefix = $offset < 0 ? '-' : '+';
  572. $offset_formatted = gmdate('H:i', abs($offset));
  573. $pretty_offset = "UTC${offset_prefix}${offset_formatted}";
  574. $timezone_list[$timezone] = "(${pretty_offset}) ".str_replace('_', ' ', $timezone);
  575. }
  576. return $timezone_list;
  577. }
  578. /**
  579. * Recursively filter an array, filtering values by processing them through the $fn function argument
  580. *
  581. * @param array $source the Array to filter
  582. * @param callable $fn the function to pass through each array item
  583. *
  584. * @return array
  585. */
  586. public static function arrayFilterRecursive(Array $source, $fn)
  587. {
  588. $result = [];
  589. foreach ($source as $key => $value) {
  590. if (is_array($value)) {
  591. $result[$key] = static::arrayFilterRecursive($value, $fn);
  592. continue;
  593. }
  594. if ($fn($key, $value)) {
  595. $result[$key] = $value; // KEEP
  596. continue;
  597. }
  598. }
  599. return $result;
  600. }
  601. /**
  602. * Flatten an array
  603. *
  604. * @param array $array
  605. * @return array
  606. */
  607. public static function arrayFlatten($array)
  608. {
  609. $flatten = array();
  610. foreach ($array as $key => $inner){
  611. if (is_array($inner)) {
  612. foreach ($inner as $inner_key => $value) {
  613. $flatten[$inner_key] = $value;
  614. }
  615. } else {
  616. $flatten[$key] = $inner;
  617. }
  618. }
  619. return $flatten;
  620. }
  621. /**
  622. * Checks if the passed path contains the language code prefix
  623. *
  624. * @param string $string The path
  625. *
  626. * @return bool
  627. */
  628. public static function pathPrefixedByLangCode($string)
  629. {
  630. if (strlen($string) <= 3) {
  631. return false;
  632. }
  633. $languages_enabled = Grav::instance()['config']->get('system.languages.supported', []);
  634. if ($string[0] === '/' && $string[3] === '/' && in_array(substr($string, 1, 2), $languages_enabled)) {
  635. return true;
  636. }
  637. return false;
  638. }
  639. /**
  640. * Get the timestamp of a date
  641. *
  642. * @param string $date a String expressed in the system.pages.dateformat.default format, with fallback to a
  643. * strtotime argument
  644. * @param string $format a date format to use if possible
  645. * @return int the timestamp
  646. */
  647. public static function date2timestamp($date, $format = null)
  648. {
  649. $config = Grav::instance()['config'];
  650. $dateformat = $format ?: $config->get('system.pages.dateformat.default');
  651. // try to use DateTime and default format
  652. if ($dateformat) {
  653. $datetime = DateTime::createFromFormat($dateformat, $date);
  654. } else {
  655. $datetime = new DateTime($date);
  656. }
  657. // fallback to strtotime() if DateTime approach failed
  658. if ($datetime !== false) {
  659. return $datetime->getTimestamp();
  660. }
  661. return strtotime($date);
  662. }
  663. /**
  664. * @param array $array
  665. * @param string $path
  666. * @param null $default
  667. * @return mixed
  668. *
  669. * @deprecated Use getDotNotation() method instead
  670. */
  671. public static function resolve(array $array, $path, $default = null)
  672. {
  673. user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.5, use getDotNotation() method instead', E_USER_DEPRECATED);
  674. return static::getDotNotation($array, $path, $default);
  675. }
  676. /**
  677. * Checks if a value is positive
  678. *
  679. * @param string $value
  680. *
  681. * @return boolean
  682. */
  683. public static function isPositive($value)
  684. {
  685. return in_array($value, [true, 1, '1', 'yes', 'on', 'true'], true);
  686. }
  687. /**
  688. * Generates a nonce string to be hashed. Called by self::getNonce()
  689. * We removed the IP portion in this version because it causes too many inconsistencies
  690. * with reverse proxy setups.
  691. *
  692. * @param string $action
  693. * @param bool $previousTick if true, generates the token for the previous tick (the previous 12 hours)
  694. *
  695. * @return string the nonce string
  696. */
  697. private static function generateNonceString($action, $previousTick = false)
  698. {
  699. $username = '';
  700. if (isset(Grav::instance()['user'])) {
  701. $user = Grav::instance()['user'];
  702. $username = $user->username;
  703. }
  704. $token = session_id();
  705. $i = self::nonceTick();
  706. if ($previousTick) {
  707. $i--;
  708. }
  709. return ($i . '|' . $action . '|' . $username . '|' . $token . '|' . Grav::instance()['config']->get('security.salt'));
  710. }
  711. /**
  712. * Get the time-dependent variable for nonce creation.
  713. *
  714. * Now a tick lasts a day. Once the day is passed, the nonce is not valid any more. Find a better way
  715. * to ensure nonces issued near the end of the day do not expire in that small amount of time
  716. *
  717. * @return int the time part of the nonce. Changes once every 24 hours
  718. */
  719. private static function nonceTick()
  720. {
  721. $secondsInHalfADay = 60 * 60 * 12;
  722. return (int)ceil(time() / $secondsInHalfADay);
  723. }
  724. /**
  725. * Creates a hashed nonce tied to the passed action. Tied to the current user and time. The nonce for a given
  726. * action is the same for 12 hours.
  727. *
  728. * @param string $action the action the nonce is tied to (e.g. save-user-admin or move-page-homepage)
  729. * @param bool $previousTick if true, generates the token for the previous tick (the previous 12 hours)
  730. *
  731. * @return string the nonce
  732. */
  733. public static function getNonce($action, $previousTick = false)
  734. {
  735. // Don't regenerate this again if not needed
  736. if (isset(static::$nonces[$action][$previousTick])) {
  737. return static::$nonces[$action][$previousTick];
  738. }
  739. $nonce = md5(self::generateNonceString($action, $previousTick));
  740. static::$nonces[$action][$previousTick] = $nonce;
  741. return static::$nonces[$action][$previousTick];
  742. }
  743. /**
  744. * Verify the passed nonce for the give action
  745. *
  746. * @param string|string[] $nonce the nonce to verify
  747. * @param string $action the action to verify the nonce to
  748. *
  749. * @return boolean verified or not
  750. */
  751. public static function verifyNonce($nonce, $action)
  752. {
  753. //Safety check for multiple nonces
  754. if (is_array($nonce)) {
  755. $nonce = array_shift($nonce);
  756. }
  757. //Nonce generated 0-12 hours ago
  758. if ($nonce === self::getNonce($action)) {
  759. return true;
  760. }
  761. //Nonce generated 12-24 hours ago
  762. $previousTick = true;
  763. if ($nonce === self::getNonce($action, $previousTick)) {
  764. return true;
  765. }
  766. //Invalid nonce
  767. return false;
  768. }
  769. /**
  770. * Simple helper method to get whether or not the admin plugin is active
  771. *
  772. * @return bool
  773. */
  774. public static function isAdminPlugin()
  775. {
  776. if (isset(Grav::instance()['admin'])) {
  777. return true;
  778. }
  779. return false;
  780. }
  781. /**
  782. * Get a portion of an array (passed by reference) with dot-notation key
  783. *
  784. * @param $array
  785. * @param $key
  786. * @param null $default
  787. * @return mixed
  788. */
  789. public static function getDotNotation($array, $key, $default = null)
  790. {
  791. if (null === $key) {
  792. return $array;
  793. }
  794. if (isset($array[$key])) {
  795. return $array[$key];
  796. }
  797. foreach (explode('.', $key) as $segment) {
  798. if (!is_array($array) || !array_key_exists($segment, $array)) {
  799. return $default;
  800. }
  801. $array = $array[$segment];
  802. }
  803. return $array;
  804. }
  805. /**
  806. * Set portion of array (passed by reference) for a dot-notation key
  807. * and set the value
  808. *
  809. * @param $array
  810. * @param $key
  811. * @param $value
  812. * @param bool $merge
  813. *
  814. * @return mixed
  815. */
  816. public static function setDotNotation(&$array, $key, $value, $merge = false)
  817. {
  818. if (null === $key) {
  819. return $array = $value;
  820. }
  821. $keys = explode('.', $key);
  822. while (count($keys) > 1) {
  823. $key = array_shift($keys);
  824. if ( ! isset($array[$key]) || ! is_array($array[$key]))
  825. {
  826. $array[$key] = array();
  827. }
  828. $array =& $array[$key];
  829. }
  830. $key = array_shift($keys);
  831. if (!$merge || !isset($array[$key])) {
  832. $array[$key] = $value;
  833. } else {
  834. $array[$key] = array_merge($array[$key], $value);
  835. }
  836. return $array;
  837. }
  838. /**
  839. * Utility method to determine if the current OS is Windows
  840. *
  841. * @return bool
  842. */
  843. public static function isWindows()
  844. {
  845. return strncasecmp(PHP_OS, 'WIN', 3) === 0;
  846. }
  847. /**
  848. * Utility to determine if the server running PHP is Apache
  849. *
  850. * @return bool
  851. */
  852. public static function isApache() {
  853. return isset($_SERVER['SERVER_SOFTWARE']) && strpos($_SERVER['SERVER_SOFTWARE'], 'Apache') !== false;
  854. }
  855. /**
  856. * Sort a multidimensional array by another array of ordered keys
  857. *
  858. * @param array $array
  859. * @param array $orderArray
  860. * @return array
  861. */
  862. public static function sortArrayByArray(array $array, array $orderArray)
  863. {
  864. $ordered = array();
  865. foreach ($orderArray as $key) {
  866. if (array_key_exists($key, $array)) {
  867. $ordered[$key] = $array[$key];
  868. unset($array[$key]);
  869. }
  870. }
  871. return $ordered + $array;
  872. }
  873. /**
  874. * Sort an array by a key value in the array
  875. *
  876. * @param $array
  877. * @param $array_key
  878. * @param int $direction
  879. * @param int $sort_flags
  880. * @return array
  881. */
  882. public static function sortArrayByKey($array, $array_key, $direction = SORT_DESC, $sort_flags = SORT_REGULAR )
  883. {
  884. $output = [];
  885. if (!is_array($array) || !$array) {
  886. return $output;
  887. }
  888. foreach ($array as $key => $row) {
  889. $output[$key] = $row[$array_key];
  890. }
  891. array_multisort($output, $direction, $sort_flags, $array);
  892. return $array;
  893. }
  894. /**
  895. * Get's path based on a token
  896. *
  897. * @param $path
  898. * @param Page|null $page
  899. * @return string
  900. * @throws \RuntimeException
  901. */
  902. public static function getPagePathFromToken($path, $page = null)
  903. {
  904. $path_parts = pathinfo($path);
  905. $grav = Grav::instance();
  906. $basename = '';
  907. if (isset($path_parts['extension'])) {
  908. $basename = '/' . $path_parts['basename'];
  909. $path = rtrim($path_parts['dirname'], ':');
  910. }
  911. $regex = '/(@self|self@)|((?:@page|page@):(?:.*))|((?:@theme|theme@):(?:.*))/';
  912. preg_match($regex, $path, $matches);
  913. if ($matches) {
  914. if ($matches[1]) {
  915. if (null === $page) {
  916. throw new \RuntimeException('Page not available for this self@ reference');
  917. }
  918. } elseif ($matches[2]) {
  919. // page@
  920. $parts = explode(':', $path);
  921. $route = $parts[1];
  922. $page = $grav['page']->find($route);
  923. } elseif ($matches[3]) {
  924. // theme@
  925. $parts = explode(':', $path);
  926. $route = $parts[1];
  927. $theme = str_replace(ROOT_DIR, '', $grav['locator']->findResource("theme://"));
  928. return $theme . $route . $basename;
  929. }
  930. } else {
  931. return $path . $basename;
  932. }
  933. if (!$page) {
  934. throw new \RuntimeException('Page route not found: ' . $path);
  935. }
  936. $path = str_replace($matches[0], rtrim($page->relativePagePath(), '/'), $path);
  937. return $path . $basename;
  938. }
  939. public static function getUploadLimit()
  940. {
  941. static $max_size = -1;
  942. if ($max_size < 0) {
  943. $post_max_size = static::parseSize(ini_get('post_max_size'));
  944. if ($post_max_size > 0) {
  945. $max_size = $post_max_size;
  946. }
  947. $upload_max = static::parseSize(ini_get('upload_max_filesize'));
  948. if ($upload_max > 0 && $upload_max < $max_size) {
  949. $max_size = $upload_max;
  950. }
  951. }
  952. return $max_size;
  953. }
  954. /**
  955. * Parse a readable file size and return a value in bytes
  956. *
  957. * @param $size
  958. * @return int
  959. */
  960. public static function parseSize($size)
  961. {
  962. $unit = preg_replace('/[^bkmgtpezy]/i', '', $size);
  963. $size = preg_replace('/[^0-9\.]/', '', $size);
  964. if ($unit) {
  965. return (int)($size * pow(1024, stripos('bkmgtpezy', $unit[0])));
  966. }
  967. return (int)$size;
  968. }
  969. /**
  970. * Multibyte-safe Parse URL function
  971. *
  972. * @param $url
  973. * @return mixed
  974. * @throws \InvalidArgumentException
  975. */
  976. public static function multibyteParseUrl($url)
  977. {
  978. $enc_url = preg_replace_callback(
  979. '%[^:/@?&=#]+%usD',
  980. function ($matches) {
  981. return urlencode($matches[0]);
  982. },
  983. $url
  984. );
  985. $parts = parse_url($enc_url);
  986. if($parts === false) {
  987. throw new \InvalidArgumentException('Malformed URL: ' . $url);
  988. }
  989. foreach($parts as $name => $value) {
  990. $parts[$name] = urldecode($value);
  991. }
  992. return $parts;
  993. }
  994. }