Utils.php 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641
  1. <?php
  2. /**
  3. * @package Grav\Common
  4. *
  5. * @copyright Copyright (C) 2015 - 2019 Trilby Media, LLC. All rights reserved.
  6. * @license MIT License; see LICENSE file for details.
  7. */
  8. namespace Grav\Common;
  9. use Grav\Common\Helpers\Truncator;
  10. use Grav\Common\Page\Interfaces\PageInterface;
  11. use Grav\Common\Markdown\Parsedown;
  12. use Grav\Common\Markdown\ParsedownExtra;
  13. use Grav\Common\Page\Markdown\Excerpts;
  14. use RocketTheme\Toolbox\Event\Event;
  15. use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
  16. abstract class Utils
  17. {
  18. protected static $nonces = [];
  19. protected const ROOTURL_REGEX = '{^((?:http[s]?:\/\/[^\/]+)|(?:\/\/[^\/]+))(.*)}';
  20. // ^((?:http[s]?:)?[\/]?(?:\/))
  21. /**
  22. * Simple helper method to make getting a Grav URL easier
  23. *
  24. * @param string|object $input
  25. * @param bool $domain
  26. * @param bool $fail_gracefully
  27. * @return bool|null|string
  28. */
  29. public static function url($input, $domain = false, $fail_gracefully = false)
  30. {
  31. if ((!is_string($input) && !method_exists($input, '__toString')) || !trim($input)) {
  32. if ($fail_gracefully) {
  33. $input = '/';
  34. } else {
  35. return false;
  36. }
  37. }
  38. $input = (string)$input;
  39. if (Uri::isExternal($input)) {
  40. return $input;
  41. }
  42. $grav = Grav::instance();
  43. /** @var Uri $uri */
  44. $uri = $grav['uri'];
  45. if (static::contains((string)$input, '://')) {
  46. /** @var UniformResourceLocator $locator */
  47. $locator = $grav['locator'];
  48. $parts = Uri::parseUrl($input);
  49. if (is_array($parts)) {
  50. // Make sure we always have scheme, host, port and path.
  51. $scheme = $parts['scheme'] ?? '';
  52. $host = $parts['host'] ?? '';
  53. $port = $parts['port'] ?? '';
  54. $path = $parts['path'] ?? '';
  55. if ($scheme && !$port) {
  56. // If URL has a scheme, we need to check if it's one of Grav streams.
  57. if (!$locator->schemeExists($scheme)) {
  58. // If scheme does not exists as a stream, assume it's external.
  59. return str_replace(' ', '%20', $input);
  60. }
  61. // Attempt to find the resource (because of parse_url() we need to put host back to path).
  62. $resource = $locator->findResource("{$scheme}://{$host}{$path}", false);
  63. if ($resource === false) {
  64. if (!$fail_gracefully) {
  65. return false;
  66. }
  67. // Return location where the file would be if it was saved.
  68. $resource = $locator->findResource("{$scheme}://{$host}{$path}", false, true);
  69. }
  70. } elseif ($host || $port) {
  71. // If URL doesn't have scheme but has host or port, it is external.
  72. return str_replace(' ', '%20', $input);
  73. }
  74. if (!empty($resource)) {
  75. // Add query string back.
  76. if (isset($parts['query'])) {
  77. $resource .= '?' . $parts['query'];
  78. }
  79. // Add fragment back.
  80. if (isset($parts['fragment'])) {
  81. $resource .= '#' . $parts['fragment'];
  82. }
  83. }
  84. } else {
  85. // Not a valid URL (can still be a stream).
  86. $resource = $locator->findResource($input, false);
  87. }
  88. } else {
  89. $root = $uri->rootUrl();
  90. if (static::startsWith($input, $root)) {
  91. $input = static::replaceFirstOccurrence($root, '', $input);
  92. }
  93. $input = ltrim($input, '/');
  94. $resource = $input;
  95. }
  96. if (!$fail_gracefully && $resource === false) {
  97. return false;
  98. }
  99. $domain = $domain ?: $grav['config']->get('system.absolute_urls', false);
  100. return rtrim($uri->rootUrl($domain), '/') . '/' . ($resource ?? '');
  101. }
  102. /**
  103. * Helper method to find the full path to a file, be it a stream, a relative path, or
  104. * already a full path
  105. *
  106. * @param $path
  107. * @return string
  108. */
  109. public static function fullPath($path)
  110. {
  111. $locator = Grav::instance()['locator'];
  112. if ($locator->isStream($path)) {
  113. $path = $locator->findResource($path, true);
  114. } elseif (!Utils::startsWith($path, GRAV_ROOT)) {
  115. $base_url = Grav::instance()['base_url'];
  116. $path = GRAV_ROOT . '/' . ltrim(Utils::replaceFirstOccurrence($base_url, '', $path), '/');
  117. }
  118. return $path;
  119. }
  120. /**
  121. * Check if the $haystack string starts with the substring $needle
  122. *
  123. * @param string $haystack
  124. * @param string|string[] $needle
  125. * @param bool $case_sensitive
  126. *
  127. * @return bool
  128. */
  129. public static function startsWith($haystack, $needle, $case_sensitive = true)
  130. {
  131. $status = false;
  132. $compare_func = $case_sensitive ? 'mb_strpos' : 'mb_stripos';
  133. foreach ((array)$needle as $each_needle) {
  134. $status = $each_needle === '' || $compare_func($haystack, $each_needle) === 0;
  135. if ($status) {
  136. break;
  137. }
  138. }
  139. return $status;
  140. }
  141. /**
  142. * Check if the $haystack string ends with the substring $needle
  143. *
  144. * @param string $haystack
  145. * @param string|string[] $needle
  146. * @param bool $case_sensitive
  147. *
  148. * @return bool
  149. */
  150. public static function endsWith($haystack, $needle, $case_sensitive = true)
  151. {
  152. $status = false;
  153. $compare_func = $case_sensitive ? 'mb_strrpos' : 'mb_strripos';
  154. foreach ((array)$needle as $each_needle) {
  155. $expectedPosition = mb_strlen($haystack) - mb_strlen($each_needle);
  156. $status = $each_needle === '' || $compare_func($haystack, $each_needle, 0) === $expectedPosition;
  157. if ($status) {
  158. break;
  159. }
  160. }
  161. return $status;
  162. }
  163. /**
  164. * Check if the $haystack string contains the substring $needle
  165. *
  166. * @param string $haystack
  167. * @param string|string[] $needle
  168. * @param bool $case_sensitive
  169. *
  170. * @return bool
  171. */
  172. public static function contains($haystack, $needle, $case_sensitive = true)
  173. {
  174. $status = false;
  175. $compare_func = $case_sensitive ? 'mb_strpos' : 'mb_stripos';
  176. foreach ((array)$needle as $each_needle) {
  177. $status = $each_needle === '' || $compare_func($haystack, $each_needle) !== false;
  178. if ($status) {
  179. break;
  180. }
  181. }
  182. return $status;
  183. }
  184. /**
  185. * Function that can match wildcards
  186. *
  187. * match_wildcard('foo*', $test), // TRUE
  188. * match_wildcard('bar*', $test), // FALSE
  189. * match_wildcard('*bar*', $test), // TRUE
  190. * match_wildcard('**blob**', $test), // TRUE
  191. * match_wildcard('*a?d*', $test), // TRUE
  192. * match_wildcard('*etc**', $test) // TRUE
  193. *
  194. * @param string $wildcard_pattern
  195. * @param string $haystack
  196. * @return false|int
  197. */
  198. public static function matchWildcard($wildcard_pattern, $haystack) {
  199. $regex = str_replace(
  200. array("\*", "\?"), // wildcard chars
  201. array('.*','.'), // regexp chars
  202. preg_quote($wildcard_pattern, '/')
  203. );
  204. return preg_match('/^'.$regex.'$/is', $haystack);
  205. }
  206. /**
  207. * Returns the substring of a string up to a specified needle. if not found, return the whole haystack
  208. *
  209. * @param string $haystack
  210. * @param string $needle
  211. * @param bool $case_sensitive
  212. *
  213. * @return string
  214. */
  215. public static function substrToString($haystack, $needle, $case_sensitive = true)
  216. {
  217. $compare_func = $case_sensitive ? 'mb_strpos' : 'mb_stripos';
  218. if (static::contains($haystack, $needle, $case_sensitive)) {
  219. return mb_substr($haystack, 0, $compare_func($haystack, $needle, $case_sensitive));
  220. }
  221. return $haystack;
  222. }
  223. /**
  224. * Utility method to replace only the first occurrence in a string
  225. *
  226. * @param string $search
  227. * @param string $replace
  228. * @param string $subject
  229. *
  230. * @return string
  231. */
  232. public static function replaceFirstOccurrence($search, $replace, $subject)
  233. {
  234. if (!$search) {
  235. return $subject;
  236. }
  237. $pos = mb_strpos($subject, $search);
  238. if ($pos !== false) {
  239. $subject = static::mb_substr_replace($subject, $replace, $pos, mb_strlen($search));
  240. }
  241. return $subject;
  242. }
  243. /**
  244. * Utility method to replace only the last occurrence in a string
  245. *
  246. * @param string $search
  247. * @param string $replace
  248. * @param string $subject
  249. * @return string
  250. */
  251. public static function replaceLastOccurrence($search, $replace, $subject)
  252. {
  253. $pos = strrpos($subject, $search);
  254. if($pos !== false)
  255. {
  256. $subject = static::mb_substr_replace($subject, $replace, $pos, mb_strlen($search));
  257. }
  258. return $subject;
  259. }
  260. /**
  261. * Multibyte compatible substr_replace
  262. *
  263. * @param string $original
  264. * @param string $replacement
  265. * @param int $position
  266. * @param int $length
  267. * @return string
  268. */
  269. public static function mb_substr_replace($original, $replacement, $position, $length)
  270. {
  271. $startString = mb_substr($original, 0, $position, "UTF-8");
  272. $endString = mb_substr($original, $position + $length, mb_strlen($original), "UTF-8");
  273. return $startString . $replacement . $endString;
  274. }
  275. /**
  276. * Merge two objects into one.
  277. *
  278. * @param object $obj1
  279. * @param object $obj2
  280. *
  281. * @return object
  282. */
  283. public static function mergeObjects($obj1, $obj2)
  284. {
  285. return (object)array_merge((array)$obj1, (array)$obj2);
  286. }
  287. /**
  288. * Lowercase an entire array. Useful when combined with `in_array()`
  289. *
  290. * @param array $a
  291. * @return array|false
  292. */
  293. public static function arrayLower(Array $a)
  294. {
  295. return array_map('mb_strtolower', $a);
  296. }
  297. /**
  298. * Simple function to remove item/s in an array by value
  299. *
  300. * @param $search array
  301. * @param $value string|array
  302. * @return array
  303. */
  304. public static function arrayRemoveValue(Array $search, $value)
  305. {
  306. foreach ((array) $value as $val) {
  307. $key = array_search($val, $search);
  308. if ($key !== false) {
  309. unset($search[$key]);
  310. }
  311. }
  312. return $search;
  313. }
  314. /**
  315. * Recursive Merge with uniqueness
  316. *
  317. * @param array $array1
  318. * @param array $array2
  319. * @return array
  320. */
  321. public static function arrayMergeRecursiveUnique($array1, $array2)
  322. {
  323. if (empty($array1)) {
  324. // Optimize the base case
  325. return $array2;
  326. }
  327. foreach ($array2 as $key => $value) {
  328. if (is_array($value) && isset($array1[$key]) && is_array($array1[$key])) {
  329. $value = static::arrayMergeRecursiveUnique($array1[$key], $value);
  330. }
  331. $array1[$key] = $value;
  332. }
  333. return $array1;
  334. }
  335. /**
  336. * Returns an array with the differences between $array1 and $array2
  337. *
  338. * @param array $array1
  339. * @param array $array2
  340. * @return array
  341. */
  342. public static function arrayDiffMultidimensional($array1, $array2)
  343. {
  344. $result = array();
  345. foreach ($array1 as $key => $value) {
  346. if (!is_array($array2) || !array_key_exists($key, $array2)) {
  347. $result[$key] = $value;
  348. continue;
  349. }
  350. if (is_array($value)) {
  351. $recursiveArrayDiff = static::ArrayDiffMultidimensional($value, $array2[$key]);
  352. if (count($recursiveArrayDiff)) {
  353. $result[$key] = $recursiveArrayDiff;
  354. }
  355. continue;
  356. }
  357. if ($value != $array2[$key]) {
  358. $result[$key] = $value;
  359. }
  360. }
  361. return $result;
  362. }
  363. /**
  364. * Array combine but supports different array lengths
  365. *
  366. * @param array $arr1
  367. * @param array $arr2
  368. * @return array|false
  369. */
  370. public static function arrayCombine($arr1, $arr2)
  371. {
  372. $count = min(count($arr1), count($arr2));
  373. return array_combine(array_slice($arr1, 0, $count), array_slice($arr2, 0, $count));
  374. }
  375. /**
  376. * Array is associative or not
  377. *
  378. * @param array $arr
  379. * @return bool
  380. */
  381. public static function arrayIsAssociative($arr)
  382. {
  383. if ([] === $arr) {
  384. return false;
  385. }
  386. return array_keys($arr) !== range(0, count($arr) - 1);
  387. }
  388. /**
  389. * Return the Grav date formats allowed
  390. *
  391. * @return array
  392. */
  393. public static function dateFormats()
  394. {
  395. $now = new \DateTime();
  396. $date_formats = [
  397. 'd-m-Y H:i' => 'd-m-Y H:i (e.g. '.$now->format('d-m-Y H:i').')',
  398. 'Y-m-d H:i' => 'Y-m-d H:i (e.g. '.$now->format('Y-m-d H:i').')',
  399. 'm/d/Y h:i a' => 'm/d/Y h:i a (e.g. '.$now->format('m/d/Y h:i a').')',
  400. 'H:i d-m-Y' => 'H:i d-m-Y (e.g. '.$now->format('H:i d-m-Y').')',
  401. 'h:i a m/d/Y' => 'h:i a m/d/Y (e.g. '.$now->format('h:i a m/d/Y').')',
  402. ];
  403. $default_format = Grav::instance()['config']->get('system.pages.dateformat.default');
  404. if ($default_format) {
  405. $date_formats = array_merge([$default_format => $default_format.' (e.g. '.$now->format($default_format).')'], $date_formats);
  406. }
  407. return $date_formats;
  408. }
  409. /**
  410. * Get current date/time
  411. *
  412. * @param string|null $default_format
  413. * @return string
  414. * @throws \Exception
  415. */
  416. public static function dateNow($default_format = null)
  417. {
  418. $now = new \DateTime();
  419. if (is_null($default_format)) {
  420. $default_format = Grav::instance()['config']->get('system.pages.dateformat.default');
  421. }
  422. return $now->format($default_format);
  423. }
  424. /**
  425. * Truncate text by number of characters but can cut off words.
  426. *
  427. * @param string $string
  428. * @param int $limit Max number of characters.
  429. * @param bool $up_to_break truncate up to breakpoint after char count
  430. * @param string $break Break point.
  431. * @param string $pad Appended padding to the end of the string.
  432. *
  433. * @return string
  434. */
  435. public static function truncate($string, $limit = 150, $up_to_break = false, $break = ' ', $pad = '&hellip;')
  436. {
  437. // return with no change if string is shorter than $limit
  438. if (mb_strlen($string) <= $limit) {
  439. return $string;
  440. }
  441. // is $break present between $limit and the end of the string?
  442. if ($up_to_break && false !== ($breakpoint = mb_strpos($string, $break, $limit))) {
  443. if ($breakpoint < mb_strlen($string) - 1) {
  444. $string = mb_substr($string, 0, $breakpoint) . $pad;
  445. }
  446. } else {
  447. $string = mb_substr($string, 0, $limit) . $pad;
  448. }
  449. return $string;
  450. }
  451. /**
  452. * Truncate text by number of characters in a "word-safe" manor.
  453. *
  454. * @param string $string
  455. * @param int $limit
  456. *
  457. * @return string
  458. */
  459. public static function safeTruncate($string, $limit = 150)
  460. {
  461. return static::truncate($string, $limit, true);
  462. }
  463. /**
  464. * Truncate HTML by number of characters. not "word-safe"!
  465. *
  466. * @param string $text
  467. * @param int $length in characters
  468. * @param string $ellipsis
  469. *
  470. * @return string
  471. */
  472. public static function truncateHtml($text, $length = 100, $ellipsis = '...')
  473. {
  474. return Truncator::truncateLetters($text, $length, $ellipsis);
  475. }
  476. /**
  477. * Truncate HTML by number of characters in a "word-safe" manor.
  478. *
  479. * @param string $text
  480. * @param int $length in words
  481. * @param string $ellipsis
  482. *
  483. * @return string
  484. */
  485. public static function safeTruncateHtml($text, $length = 25, $ellipsis = '...')
  486. {
  487. return Truncator::truncateWords($text, $length, $ellipsis);
  488. }
  489. /**
  490. * Generate a random string of a given length
  491. *
  492. * @param int $length
  493. *
  494. * @return string
  495. */
  496. public static function generateRandomString($length = 5)
  497. {
  498. return substr(str_shuffle('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'), 0, $length);
  499. }
  500. /**
  501. * Provides the ability to download a file to the browser
  502. *
  503. * @param string $file the full path to the file to be downloaded
  504. * @param bool $force_download as opposed to letting browser choose if to download or render
  505. * @param int $sec Throttling, try 0.1 for some speed throttling of downloads
  506. * @param int $bytes Size of chunks to send in bytes. Default is 1024
  507. * @throws \Exception
  508. */
  509. public static function download($file, $force_download = true, $sec = 0, $bytes = 1024)
  510. {
  511. if (file_exists($file)) {
  512. // fire download event
  513. Grav::instance()->fireEvent('onBeforeDownload', new Event(['file' => $file]));
  514. $file_parts = pathinfo($file);
  515. $mimetype = static::getMimeByExtension($file_parts['extension']);
  516. $size = filesize($file); // File size
  517. // clean all buffers
  518. while (ob_get_level()) {
  519. ob_end_clean();
  520. }
  521. // required for IE, otherwise Content-Disposition may be ignored
  522. if (ini_get('zlib.output_compression')) {
  523. ini_set('zlib.output_compression', 'Off');
  524. }
  525. header('Content-Type: ' . $mimetype);
  526. header('Accept-Ranges: bytes');
  527. if ($force_download) {
  528. // output the regular HTTP headers
  529. header('Content-Disposition: attachment; filename="' . $file_parts['basename'] . '"');
  530. }
  531. // multipart-download and download resuming support
  532. if (isset($_SERVER['HTTP_RANGE'])) {
  533. list($a, $range) = explode('=', $_SERVER['HTTP_RANGE'], 2);
  534. list($range) = explode(',', $range, 2);
  535. list($range, $range_end) = explode('-', $range);
  536. $range = (int)$range;
  537. if (!$range_end) {
  538. $range_end = $size - 1;
  539. } else {
  540. $range_end = (int)$range_end;
  541. }
  542. $new_length = $range_end - $range + 1;
  543. header('HTTP/1.1 206 Partial Content');
  544. header("Content-Length: {$new_length}");
  545. header("Content-Range: bytes {$range}-{$range_end}/{$size}");
  546. } else {
  547. $range = 0;
  548. $new_length = $size;
  549. header('Content-Length: ' . $size);
  550. if (Grav::instance()['config']->get('system.cache.enabled')) {
  551. $expires = Grav::instance()['config']->get('system.pages.expires');
  552. if ($expires > 0) {
  553. $expires_date = gmdate('D, d M Y H:i:s T', time() + $expires);
  554. header('Cache-Control: max-age=' . $expires);
  555. header('Expires: ' . $expires_date);
  556. header('Pragma: cache');
  557. }
  558. header('Last-Modified: ' . gmdate('D, d M Y H:i:s T', filemtime($file)));
  559. // Return 304 Not Modified if the file is already cached in the browser
  560. if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) &&
  561. strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) >= filemtime($file))
  562. {
  563. header('HTTP/1.1 304 Not Modified');
  564. exit();
  565. }
  566. }
  567. }
  568. /* output the file itself */
  569. $chunksize = $bytes * 8; //you may want to change this
  570. $bytes_send = 0;
  571. $fp = @fopen($file, 'rb');
  572. if ($fp) {
  573. if ($range) {
  574. fseek($fp, $range);
  575. }
  576. while (!feof($fp) && (!connection_aborted()) && ($bytes_send < $new_length) ) {
  577. $buffer = fread($fp, $chunksize);
  578. echo($buffer); //echo($buffer); // is also possible
  579. flush();
  580. usleep($sec * 1000000);
  581. $bytes_send += strlen($buffer);
  582. }
  583. fclose($fp);
  584. } else {
  585. throw new \RuntimeException('Error - can not open file.');
  586. }
  587. exit;
  588. }
  589. }
  590. /**
  591. * Return the mimetype based on filename extension
  592. *
  593. * @param string $extension Extension of file (eg "txt")
  594. * @param string $default
  595. *
  596. * @return string
  597. */
  598. public static function getMimeByExtension($extension, $default = 'application/octet-stream')
  599. {
  600. $extension = strtolower($extension);
  601. // look for some standard types
  602. switch ($extension) {
  603. case null:
  604. return $default;
  605. case 'json':
  606. return 'application/json';
  607. case 'html':
  608. return 'text/html';
  609. case 'atom':
  610. return 'application/atom+xml';
  611. case 'rss':
  612. return 'application/rss+xml';
  613. case 'xml':
  614. return 'application/xml';
  615. }
  616. $media_types = Grav::instance()['config']->get('media.types');
  617. if (isset($media_types[$extension])) {
  618. if (isset($media_types[$extension]['mime'])) {
  619. return $media_types[$extension]['mime'];
  620. }
  621. }
  622. return $default;
  623. }
  624. /**
  625. * Get all the mimetypes for an array of extensions
  626. *
  627. * @param array $extensions
  628. * @return array
  629. */
  630. public static function getMimeTypes(array $extensions)
  631. {
  632. $mimetypes = [];
  633. foreach ($extensions as $extension) {
  634. $mimetype = static::getMimeByExtension($extension, false);
  635. if ($mimetype && !in_array($mimetype, $mimetypes)) {
  636. $mimetypes[] = $mimetype;
  637. }
  638. }
  639. return $mimetypes;
  640. }
  641. /**
  642. * Return the mimetype based on filename extension
  643. *
  644. * @param string $mime mime type (eg "text/html")
  645. * @param string $default default value
  646. *
  647. * @return string
  648. */
  649. public static function getExtensionByMime($mime, $default = 'html')
  650. {
  651. $mime = strtolower($mime);
  652. // look for some standard mime types
  653. switch ($mime) {
  654. case '*/*':
  655. case 'text/*':
  656. case 'text/html':
  657. return 'html';
  658. case 'application/json':
  659. return 'json';
  660. case 'application/atom+xml':
  661. return 'atom';
  662. case 'application/rss+xml':
  663. return 'rss';
  664. case 'application/xml':
  665. return 'xml';
  666. }
  667. $media_types = (array)Grav::instance()['config']->get('media.types');
  668. foreach ($media_types as $extension => $type) {
  669. if ($extension === 'defaults') {
  670. continue;
  671. }
  672. if (isset($type['mime']) && $type['mime'] === $mime) {
  673. return $extension;
  674. }
  675. }
  676. return $default;
  677. }
  678. /**
  679. * Get all the extensions for an array of mimetypes
  680. *
  681. * @param array $mimetypes
  682. * @return array
  683. */
  684. public static function getExtensions(array $mimetypes)
  685. {
  686. $extensions = [];
  687. foreach ($mimetypes as $mimetype) {
  688. $extension = static::getExtensionByMime($mimetype, false);
  689. if ($extension && !\in_array($extension, $extensions, true)) {
  690. $extensions[] = $extension;
  691. }
  692. }
  693. return $extensions;
  694. }
  695. /**
  696. * Return the mimetype based on filename
  697. *
  698. * @param string $filename Filename or path to file
  699. * @param string $default default value
  700. *
  701. * @return string
  702. */
  703. public static function getMimeByFilename($filename, $default = 'application/octet-stream')
  704. {
  705. return static::getMimeByExtension(pathinfo($filename, PATHINFO_EXTENSION), $default);
  706. }
  707. /**
  708. * Return the mimetype based on existing local file
  709. *
  710. * @param string $filename Path to the file
  711. *
  712. * @return string|bool
  713. */
  714. public static function getMimeByLocalFile($filename, $default = 'application/octet-stream')
  715. {
  716. $type = false;
  717. // For local files we can detect type by the file content.
  718. if (!stream_is_local($filename) || !file_exists($filename)) {
  719. return false;
  720. }
  721. // Prefer using finfo if it exists.
  722. if (\extension_loaded('fileinfo')) {
  723. $finfo = finfo_open(FILEINFO_SYMLINK | FILEINFO_MIME_TYPE);
  724. $type = finfo_file($finfo, $filename);
  725. finfo_close($finfo);
  726. } else {
  727. // Fall back to use getimagesize() if it is available (not recommended, but better than nothing)
  728. $info = @getimagesize($filename);
  729. if ($info) {
  730. $type = $info['mime'];
  731. }
  732. }
  733. return $type ?: static::getMimeByFilename($filename, $default);
  734. }
  735. /**
  736. * Returns true if filename is considered safe.
  737. *
  738. * @param string $filename
  739. * @return bool
  740. */
  741. public static function checkFilename($filename)
  742. {
  743. $dangerous_extensions = Grav::instance()['config']->get('security.uploads_dangerous_extensions', []);
  744. array_walk($dangerous_extensions, function(&$val) {
  745. $val = '.' . $val;
  746. });
  747. $extension = '.' . pathinfo($filename, PATHINFO_EXTENSION);
  748. return !(
  749. // Empty filenames are not allowed.
  750. !$filename
  751. // Filename should not contain horizontal/vertical tabs, newlines, nils or back/forward slashes.
  752. || strtr($filename, "\t\v\n\r\0\\/", '_______') !== $filename
  753. // Filename should not start or end with dot or space.
  754. || trim($filename, '. ') !== $filename
  755. // Filename should not contain .php in it.
  756. || static::contains($extension, $dangerous_extensions)
  757. );
  758. }
  759. /**
  760. * Normalize path by processing relative `.` and `..` syntax and merging path
  761. *
  762. * @param string $path
  763. *
  764. * @return string
  765. */
  766. public static function normalizePath($path)
  767. {
  768. // Resolve any streams
  769. /** @var UniformResourceLocator $locator */
  770. $locator = Grav::instance()['locator'];
  771. if ($locator->isStream($path)) {
  772. $path = $locator->findResource($path);
  773. }
  774. // Set root properly for any URLs
  775. $root = '';
  776. preg_match(self::ROOTURL_REGEX, $path, $matches);
  777. if ($matches) {
  778. $root = $matches[1];
  779. $path = $matches[2];
  780. }
  781. // Strip off leading / to ensure explode is accurate
  782. if (Utils::startsWith($path,'/')) {
  783. $root .= '/';
  784. $path = ltrim($path, '/');
  785. }
  786. // If there are any relative paths (..) handle those
  787. if (Utils::contains($path, '..')) {
  788. $segments = explode('/', trim($path, '/'));
  789. $ret = [];
  790. foreach ($segments as $segment) {
  791. if (($segment === '.') || $segment === '') {
  792. continue;
  793. }
  794. if ($segment === '..') {
  795. array_pop($ret);
  796. } else {
  797. $ret[] = $segment;
  798. }
  799. }
  800. $path = implode('/', $ret);
  801. }
  802. // Stick everything back together
  803. $normalized = $root . $path;
  804. return $normalized;
  805. }
  806. /**
  807. * Check whether a function is disabled in the PHP settings
  808. *
  809. * @param string $function the name of the function to check
  810. *
  811. * @return bool
  812. */
  813. public static function isFunctionDisabled($function)
  814. {
  815. return \in_array($function, explode(',', ini_get('disable_functions')), true);
  816. }
  817. /**
  818. * Get the formatted timezones list
  819. *
  820. * @return array
  821. */
  822. public static function timezones()
  823. {
  824. $timezones = \DateTimeZone::listIdentifiers(\DateTimeZone::ALL);
  825. $offsets = [];
  826. $testDate = new \DateTime();
  827. foreach ($timezones as $zone) {
  828. $tz = new \DateTimeZone($zone);
  829. $offsets[$zone] = $tz->getOffset($testDate);
  830. }
  831. asort($offsets);
  832. $timezone_list = [];
  833. foreach ($offsets as $timezone => $offset) {
  834. $offset_prefix = $offset < 0 ? '-' : '+';
  835. $offset_formatted = gmdate('H:i', abs($offset));
  836. $pretty_offset = "UTC${offset_prefix}${offset_formatted}";
  837. $timezone_list[$timezone] = "(${pretty_offset}) ".str_replace('_', ' ', $timezone);
  838. }
  839. return $timezone_list;
  840. }
  841. /**
  842. * Recursively filter an array, filtering values by processing them through the $fn function argument
  843. *
  844. * @param array $source the Array to filter
  845. * @param callable $fn the function to pass through each array item
  846. *
  847. * @return array
  848. */
  849. public static function arrayFilterRecursive(Array $source, $fn)
  850. {
  851. $result = [];
  852. foreach ($source as $key => $value) {
  853. if (is_array($value)) {
  854. $result[$key] = static::arrayFilterRecursive($value, $fn);
  855. continue;
  856. }
  857. if ($fn($key, $value)) {
  858. $result[$key] = $value; // KEEP
  859. continue;
  860. }
  861. }
  862. return $result;
  863. }
  864. /**
  865. * Flatten an array
  866. *
  867. * @param array $array
  868. * @return array
  869. */
  870. public static function arrayFlatten($array)
  871. {
  872. $flatten = array();
  873. foreach ($array as $key => $inner) {
  874. if (is_array($inner)) {
  875. foreach ($inner as $inner_key => $value) {
  876. $flatten[$inner_key] = $value;
  877. }
  878. } else {
  879. $flatten[$key] = $inner;
  880. }
  881. }
  882. return $flatten;
  883. }
  884. /**
  885. * Flatten a multi-dimensional associative array into dot notation
  886. *
  887. * @param array $array
  888. * @param string $prepend
  889. * @return array
  890. */
  891. public static function arrayFlattenDotNotation($array, $prepend = '')
  892. {
  893. $results = array();
  894. foreach ($array as $key => $value) {
  895. if (is_array($value)) {
  896. $results = array_merge($results, static::arrayFlattenDotNotation($value, $prepend.$key.'.'));
  897. } else {
  898. $results[$prepend.$key] = $value;
  899. }
  900. }
  901. return $results;
  902. }
  903. /**
  904. * Opposite of flatten, convert flat dot notation array to multi dimensional array
  905. *
  906. * @param array $array
  907. * @param string $separator
  908. * @return array
  909. */
  910. public static function arrayUnflattenDotNotation($array, $separator = '.')
  911. {
  912. $newArray = [];
  913. foreach ($array as $key => $value) {
  914. $dots = explode($separator, $key);
  915. if (\count($dots) > 1) {
  916. $last = &$newArray[$dots[0]];
  917. foreach ($dots as $k => $dot) {
  918. if ($k === 0) {
  919. continue;
  920. }
  921. $last = &$last[$dot];
  922. }
  923. $last = $value;
  924. } else {
  925. $newArray[$key] = $value;
  926. }
  927. }
  928. return $newArray;
  929. }
  930. /**
  931. * Checks if the passed path contains the language code prefix
  932. *
  933. * @param string $string The path
  934. *
  935. * @return bool|string Either false or the language
  936. *
  937. */
  938. public static function pathPrefixedByLangCode($string)
  939. {
  940. $languages_enabled = Grav::instance()['config']->get('system.languages.supported', []);
  941. $parts = explode('/', trim($string, '/'));
  942. if (count($parts) > 0 && in_array($parts[0], $languages_enabled)) {
  943. return $parts[0];
  944. }
  945. return false;
  946. }
  947. /**
  948. * Get the timestamp of a date
  949. *
  950. * @param string $date a String expressed in the system.pages.dateformat.default format, with fallback to a
  951. * strtotime argument
  952. * @param string $format a date format to use if possible
  953. * @return int the timestamp
  954. */
  955. public static function date2timestamp($date, $format = null)
  956. {
  957. $config = Grav::instance()['config'];
  958. $dateformat = $format ?: $config->get('system.pages.dateformat.default');
  959. // try to use DateTime and default format
  960. if ($dateformat) {
  961. $datetime = \DateTime::createFromFormat($dateformat, $date);
  962. } else {
  963. $datetime = new \DateTime($date);
  964. }
  965. // fallback to strtotime() if DateTime approach failed
  966. if ($datetime !== false) {
  967. return $datetime->getTimestamp();
  968. }
  969. return strtotime($date);
  970. }
  971. /**
  972. * @param array $array
  973. * @param string $path
  974. * @param null $default
  975. * @return mixed
  976. *
  977. * @deprecated 1.5 Use ->getDotNotation() method instead.
  978. */
  979. public static function resolve(array $array, $path, $default = null)
  980. {
  981. user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.5, use ->getDotNotation() method instead', E_USER_DEPRECATED);
  982. return static::getDotNotation($array, $path, $default);
  983. }
  984. /**
  985. * Checks if a value is positive
  986. *
  987. * @param string $value
  988. *
  989. * @return boolean
  990. */
  991. public static function isPositive($value)
  992. {
  993. return in_array($value, [true, 1, '1', 'yes', 'on', 'true'], true);
  994. }
  995. /**
  996. * Generates a nonce string to be hashed. Called by self::getNonce()
  997. * We removed the IP portion in this version because it causes too many inconsistencies
  998. * with reverse proxy setups.
  999. *
  1000. * @param string $action
  1001. * @param bool $previousTick if true, generates the token for the previous tick (the previous 12 hours)
  1002. *
  1003. * @return string the nonce string
  1004. */
  1005. private static function generateNonceString($action, $previousTick = false)
  1006. {
  1007. $grav = Grav::instance();
  1008. $username = isset($grav['user']) ? $grav['user']->username : '';
  1009. $token = session_id();
  1010. $i = self::nonceTick();
  1011. if ($previousTick) {
  1012. $i--;
  1013. }
  1014. return ($i . '|' . $action . '|' . $username . '|' . $token . '|' . $grav['config']->get('security.salt'));
  1015. }
  1016. /**
  1017. * Get the time-dependent variable for nonce creation.
  1018. *
  1019. * Now a tick lasts a day. Once the day is passed, the nonce is not valid any more. Find a better way
  1020. * to ensure nonces issued near the end of the day do not expire in that small amount of time
  1021. *
  1022. * @return int the time part of the nonce. Changes once every 24 hours
  1023. */
  1024. private static function nonceTick()
  1025. {
  1026. $secondsInHalfADay = 60 * 60 * 12;
  1027. return (int)ceil(time() / $secondsInHalfADay);
  1028. }
  1029. /**
  1030. * Creates a hashed nonce tied to the passed action. Tied to the current user and time. The nonce for a given
  1031. * action is the same for 12 hours.
  1032. *
  1033. * @param string $action the action the nonce is tied to (e.g. save-user-admin or move-page-homepage)
  1034. * @param bool $previousTick if true, generates the token for the previous tick (the previous 12 hours)
  1035. *
  1036. * @return string the nonce
  1037. */
  1038. public static function getNonce($action, $previousTick = false)
  1039. {
  1040. // Don't regenerate this again if not needed
  1041. if (isset(static::$nonces[$action][$previousTick])) {
  1042. return static::$nonces[$action][$previousTick];
  1043. }
  1044. $nonce = md5(self::generateNonceString($action, $previousTick));
  1045. static::$nonces[$action][$previousTick] = $nonce;
  1046. return static::$nonces[$action][$previousTick];
  1047. }
  1048. /**
  1049. * Verify the passed nonce for the give action
  1050. *
  1051. * @param string|string[] $nonce the nonce to verify
  1052. * @param string $action the action to verify the nonce to
  1053. *
  1054. * @return boolean verified or not
  1055. */
  1056. public static function verifyNonce($nonce, $action)
  1057. {
  1058. //Safety check for multiple nonces
  1059. if (is_array($nonce)) {
  1060. $nonce = array_shift($nonce);
  1061. }
  1062. //Nonce generated 0-12 hours ago
  1063. if ($nonce === self::getNonce($action)) {
  1064. return true;
  1065. }
  1066. //Nonce generated 12-24 hours ago
  1067. $previousTick = true;
  1068. return $nonce === self::getNonce($action, $previousTick);
  1069. }
  1070. /**
  1071. * Simple helper method to get whether or not the admin plugin is active
  1072. *
  1073. * @return bool
  1074. */
  1075. public static function isAdminPlugin()
  1076. {
  1077. if (isset(Grav::instance()['admin'])) {
  1078. return true;
  1079. }
  1080. return false;
  1081. }
  1082. /**
  1083. * Get a portion of an array (passed by reference) with dot-notation key
  1084. *
  1085. * @param array $array
  1086. * @param string|int $key
  1087. * @param null $default
  1088. * @return mixed
  1089. */
  1090. public static function getDotNotation($array, $key, $default = null)
  1091. {
  1092. if (null === $key) {
  1093. return $array;
  1094. }
  1095. if (isset($array[$key])) {
  1096. return $array[$key];
  1097. }
  1098. foreach (explode('.', $key) as $segment) {
  1099. if (!is_array($array) || !array_key_exists($segment, $array)) {
  1100. return $default;
  1101. }
  1102. $array = $array[$segment];
  1103. }
  1104. return $array;
  1105. }
  1106. /**
  1107. * Set portion of array (passed by reference) for a dot-notation key
  1108. * and set the value
  1109. *
  1110. * @param array $array
  1111. * @param string|int $key
  1112. * @param mixed $value
  1113. * @param bool $merge
  1114. *
  1115. * @return mixed
  1116. */
  1117. public static function setDotNotation(&$array, $key, $value, $merge = false)
  1118. {
  1119. if (null === $key) {
  1120. return $array = $value;
  1121. }
  1122. $keys = explode('.', $key);
  1123. while (count($keys) > 1) {
  1124. $key = array_shift($keys);
  1125. if ( ! isset($array[$key]) || ! is_array($array[$key]))
  1126. {
  1127. $array[$key] = array();
  1128. }
  1129. $array =& $array[$key];
  1130. }
  1131. $key = array_shift($keys);
  1132. if (!$merge || !isset($array[$key])) {
  1133. $array[$key] = $value;
  1134. } else {
  1135. $array[$key] = array_merge($array[$key], $value);
  1136. }
  1137. return $array;
  1138. }
  1139. /**
  1140. * Utility method to determine if the current OS is Windows
  1141. *
  1142. * @return bool
  1143. */
  1144. public static function isWindows()
  1145. {
  1146. return strncasecmp(PHP_OS, 'WIN', 3) === 0;
  1147. }
  1148. /**
  1149. * Utility to determine if the server running PHP is Apache
  1150. *
  1151. * @return bool
  1152. */
  1153. public static function isApache() {
  1154. return isset($_SERVER['SERVER_SOFTWARE']) && strpos($_SERVER['SERVER_SOFTWARE'], 'Apache') !== false;
  1155. }
  1156. /**
  1157. * Sort a multidimensional array by another array of ordered keys
  1158. *
  1159. * @param array $array
  1160. * @param array $orderArray
  1161. * @return array
  1162. */
  1163. public static function sortArrayByArray(array $array, array $orderArray)
  1164. {
  1165. $ordered = array();
  1166. foreach ($orderArray as $key) {
  1167. if (array_key_exists($key, $array)) {
  1168. $ordered[$key] = $array[$key];
  1169. unset($array[$key]);
  1170. }
  1171. }
  1172. return $ordered + $array;
  1173. }
  1174. /**
  1175. * Sort an array by a key value in the array
  1176. *
  1177. * @param mixed $array
  1178. * @param string|int $array_key
  1179. * @param int $direction
  1180. * @param int $sort_flags
  1181. * @return array
  1182. */
  1183. public static function sortArrayByKey($array, $array_key, $direction = SORT_DESC, $sort_flags = SORT_REGULAR)
  1184. {
  1185. $output = [];
  1186. if (!is_array($array) || !$array) {
  1187. return $output;
  1188. }
  1189. foreach ($array as $key => $row) {
  1190. $output[$key] = $row[$array_key];
  1191. }
  1192. array_multisort($output, $direction, $sort_flags, $array);
  1193. return $array;
  1194. }
  1195. /**
  1196. * Get path based on a token
  1197. *
  1198. * @param string $path
  1199. * @param PageInterface|null $page
  1200. * @return string
  1201. * @throws \RuntimeException
  1202. */
  1203. public static function getPagePathFromToken($path, PageInterface $page = null)
  1204. {
  1205. $path_parts = pathinfo($path);
  1206. $grav = Grav::instance();
  1207. $basename = '';
  1208. if (isset($path_parts['extension'])) {
  1209. $basename = '/' . $path_parts['basename'];
  1210. $path = rtrim($path_parts['dirname'], ':');
  1211. }
  1212. $regex = '/(@self|self@)|((?:@page|page@):(?:.*))|((?:@theme|theme@):(?:.*))/';
  1213. preg_match($regex, $path, $matches);
  1214. if ($matches) {
  1215. if ($matches[1]) {
  1216. if (null === $page) {
  1217. throw new \RuntimeException('Page not available for this self@ reference');
  1218. }
  1219. } elseif ($matches[2]) {
  1220. // page@
  1221. $parts = explode(':', $path);
  1222. $route = $parts[1];
  1223. $page = $grav['page']->find($route);
  1224. } elseif ($matches[3]) {
  1225. // theme@
  1226. $parts = explode(':', $path);
  1227. $route = $parts[1];
  1228. $theme = str_replace(ROOT_DIR, '', $grav['locator']->findResource("theme://"));
  1229. return $theme . $route . $basename;
  1230. }
  1231. } else {
  1232. return $path . $basename;
  1233. }
  1234. if (!$page) {
  1235. throw new \RuntimeException('Page route not found: ' . $path);
  1236. }
  1237. $path = str_replace($matches[0], rtrim($page->relativePagePath(), '/'), $path);
  1238. return $path . $basename;
  1239. }
  1240. public static function getUploadLimit()
  1241. {
  1242. static $max_size = -1;
  1243. if ($max_size < 0) {
  1244. $post_max_size = static::parseSize(ini_get('post_max_size'));
  1245. if ($post_max_size > 0) {
  1246. $max_size = $post_max_size;
  1247. } else {
  1248. $max_size = 0;
  1249. }
  1250. $upload_max = static::parseSize(ini_get('upload_max_filesize'));
  1251. if ($upload_max > 0 && $upload_max < $max_size) {
  1252. $max_size = $upload_max;
  1253. }
  1254. }
  1255. return $max_size;
  1256. }
  1257. /**
  1258. * Convert bytes to the unit specified by the $to parameter.
  1259. *
  1260. * @param int $bytes The filesize in Bytes.
  1261. * @param string $to The unit type to convert to. Accepts K, M, or G for Kilobytes, Megabytes, or Gigabytes, respectively.
  1262. * @param int $decimal_places The number of decimal places to return.
  1263. *
  1264. * @return int Returns only the number of units, not the type letter. Returns 0 if the $to unit type is out of scope.
  1265. *
  1266. */
  1267. public static function convertSize($bytes, $to, $decimal_places = 1)
  1268. {
  1269. $formulas = array(
  1270. 'K' => number_format($bytes / 1024, $decimal_places),
  1271. 'M' => number_format($bytes / 1048576, $decimal_places),
  1272. 'G' => number_format($bytes / 1073741824, $decimal_places)
  1273. );
  1274. return $formulas[$to] ?? 0;
  1275. }
  1276. /**
  1277. * Return a pretty size based on bytes
  1278. *
  1279. * @param int $bytes
  1280. * @param int $precision
  1281. * @return string
  1282. */
  1283. public static function prettySize($bytes, $precision = 2)
  1284. {
  1285. $units = array('B', 'KB', 'MB', 'GB', 'TB');
  1286. $bytes = max($bytes, 0);
  1287. $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
  1288. $pow = min($pow, count($units) - 1);
  1289. // Uncomment one of the following alternatives
  1290. $bytes /= 1024 ** $pow;
  1291. // $bytes /= (1 << (10 * $pow));
  1292. return round($bytes, $precision) . ' ' . $units[$pow];
  1293. }
  1294. /**
  1295. * Parse a readable file size and return a value in bytes
  1296. *
  1297. * @param string|int $size
  1298. * @return int
  1299. */
  1300. public static function parseSize($size)
  1301. {
  1302. $unit = preg_replace('/[^bkmgtpezy]/i', '', $size);
  1303. $size = preg_replace('/[^0-9\.]/', '', $size);
  1304. if ($unit) {
  1305. $size = $size * pow(1024, stripos('bkmgtpezy', $unit[0]));
  1306. }
  1307. return (int) abs(round($size));
  1308. }
  1309. /**
  1310. * Multibyte-safe Parse URL function
  1311. *
  1312. * @param string $url
  1313. * @return array
  1314. * @throws \InvalidArgumentException
  1315. */
  1316. public static function multibyteParseUrl($url)
  1317. {
  1318. $enc_url = preg_replace_callback(
  1319. '%[^:/@?&=#]+%usD',
  1320. function ($matches) {
  1321. return urlencode($matches[0]);
  1322. },
  1323. $url
  1324. );
  1325. $parts = parse_url($enc_url);
  1326. if($parts === false) {
  1327. throw new \InvalidArgumentException('Malformed URL: ' . $url);
  1328. }
  1329. foreach($parts as $name => $value) {
  1330. $parts[$name] = urldecode($value);
  1331. }
  1332. return $parts;
  1333. }
  1334. /**
  1335. * Process a string as markdown
  1336. *
  1337. * @param string $string
  1338. *
  1339. * @param bool $block Block or Line processing
  1340. * @param null $page
  1341. * @return string
  1342. * @throws \Exception
  1343. */
  1344. public static function processMarkdown($string, $block = true, $page = null)
  1345. {
  1346. $grav = Grav::instance();
  1347. $page = $page ?? $grav['page'] ?? null;
  1348. $defaults = [
  1349. 'markdown' => $grav['config']->get('system.pages.markdown', []),
  1350. 'images' => $grav['config']->get('system.images', [])
  1351. ];
  1352. $extra = $defaults['markdown']['extra'] ?? false;
  1353. $excerpts = new Excerpts($page, $defaults);
  1354. // Initialize the preferred variant of Parsedown
  1355. if ($extra) {
  1356. $parsedown = new ParsedownExtra($excerpts);
  1357. } else {
  1358. $parsedown = new Parsedown($excerpts);
  1359. }
  1360. if ($block) {
  1361. $string = $parsedown->text($string);
  1362. } else {
  1363. $string = $parsedown->line($string);
  1364. }
  1365. return $string;
  1366. }
  1367. /**
  1368. * Find the subnet of an ip with CIDR prefix size
  1369. *
  1370. * @param string $ip
  1371. * @param int $prefix
  1372. *
  1373. * @return string
  1374. */
  1375. public static function getSubnet($ip, $prefix = 64)
  1376. {
  1377. if (!filter_var($ip, FILTER_VALIDATE_IP)) {
  1378. return $ip;
  1379. }
  1380. // Packed representation of IP
  1381. $ip = inet_pton($ip);
  1382. // Maximum netmask length = same as packed address
  1383. $len = 8*strlen($ip);
  1384. if ($prefix > $len) $prefix = $len;
  1385. $mask = str_repeat('f', $prefix>>2);
  1386. switch($prefix & 3)
  1387. {
  1388. case 3: $mask .= 'e'; break;
  1389. case 2: $mask .= 'c'; break;
  1390. case 1: $mask .= '8'; break;
  1391. }
  1392. $mask = str_pad($mask, $len>>2, '0');
  1393. // Packed representation of netmask
  1394. $mask = pack('H*', $mask);
  1395. // Bitwise - Take all bits that are both 1 to generate subnet
  1396. $subnet = inet_ntop($ip & $mask);
  1397. return $subnet;
  1398. }
  1399. /**
  1400. * Wrapper to ensure html, htm in the front of the supported page types
  1401. *
  1402. * @param array|null $defaults
  1403. * @return array|mixed
  1404. */
  1405. public static function getSupportPageTypes(array $defaults = null)
  1406. {
  1407. $types = Grav::instance()['config']->get('system.pages.types', $defaults);
  1408. // remove html/htm
  1409. $types = static::arrayRemoveValue($types, ['html', 'htm']);
  1410. // put them back at the front
  1411. $types = array_merge(['html', 'htm'], $types);
  1412. return $types;
  1413. }
  1414. }