Utils.php 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637
  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. $extension = pathinfo($filename, PATHINFO_EXTENSION);
  745. return !(
  746. // Empty filenames are not allowed.
  747. !$filename
  748. // Filename should not contain horizontal/vertical tabs, newlines, nils or back/forward slashes.
  749. || strtr($filename, "\t\v\n\r\0\\/", '_______') !== $filename
  750. // Filename should not start or end with dot or space.
  751. || trim($filename, '. ') !== $filename
  752. // File extension should not be part of configured dangerous extensions
  753. || in_array($extension, $dangerous_extensions)
  754. );
  755. }
  756. /**
  757. * Normalize path by processing relative `.` and `..` syntax and merging path
  758. *
  759. * @param string $path
  760. *
  761. * @return string
  762. */
  763. public static function normalizePath($path)
  764. {
  765. // Resolve any streams
  766. /** @var UniformResourceLocator $locator */
  767. $locator = Grav::instance()['locator'];
  768. if ($locator->isStream($path)) {
  769. $path = $locator->findResource($path);
  770. }
  771. // Set root properly for any URLs
  772. $root = '';
  773. preg_match(self::ROOTURL_REGEX, $path, $matches);
  774. if ($matches) {
  775. $root = $matches[1];
  776. $path = $matches[2];
  777. }
  778. // Strip off leading / to ensure explode is accurate
  779. if (Utils::startsWith($path,'/')) {
  780. $root .= '/';
  781. $path = ltrim($path, '/');
  782. }
  783. // If there are any relative paths (..) handle those
  784. if (Utils::contains($path, '..')) {
  785. $segments = explode('/', trim($path, '/'));
  786. $ret = [];
  787. foreach ($segments as $segment) {
  788. if (($segment === '.') || $segment === '') {
  789. continue;
  790. }
  791. if ($segment === '..') {
  792. array_pop($ret);
  793. } else {
  794. $ret[] = $segment;
  795. }
  796. }
  797. $path = implode('/', $ret);
  798. }
  799. // Stick everything back together
  800. $normalized = $root . $path;
  801. return $normalized;
  802. }
  803. /**
  804. * Check whether a function is disabled in the PHP settings
  805. *
  806. * @param string $function the name of the function to check
  807. *
  808. * @return bool
  809. */
  810. public static function isFunctionDisabled($function)
  811. {
  812. return \in_array($function, explode(',', ini_get('disable_functions')), true);
  813. }
  814. /**
  815. * Get the formatted timezones list
  816. *
  817. * @return array
  818. */
  819. public static function timezones()
  820. {
  821. $timezones = \DateTimeZone::listIdentifiers(\DateTimeZone::ALL);
  822. $offsets = [];
  823. $testDate = new \DateTime();
  824. foreach ($timezones as $zone) {
  825. $tz = new \DateTimeZone($zone);
  826. $offsets[$zone] = $tz->getOffset($testDate);
  827. }
  828. asort($offsets);
  829. $timezone_list = [];
  830. foreach ($offsets as $timezone => $offset) {
  831. $offset_prefix = $offset < 0 ? '-' : '+';
  832. $offset_formatted = gmdate('H:i', abs($offset));
  833. $pretty_offset = "UTC${offset_prefix}${offset_formatted}";
  834. $timezone_list[$timezone] = "(${pretty_offset}) ".str_replace('_', ' ', $timezone);
  835. }
  836. return $timezone_list;
  837. }
  838. /**
  839. * Recursively filter an array, filtering values by processing them through the $fn function argument
  840. *
  841. * @param array $source the Array to filter
  842. * @param callable $fn the function to pass through each array item
  843. *
  844. * @return array
  845. */
  846. public static function arrayFilterRecursive(Array $source, $fn)
  847. {
  848. $result = [];
  849. foreach ($source as $key => $value) {
  850. if (is_array($value)) {
  851. $result[$key] = static::arrayFilterRecursive($value, $fn);
  852. continue;
  853. }
  854. if ($fn($key, $value)) {
  855. $result[$key] = $value; // KEEP
  856. continue;
  857. }
  858. }
  859. return $result;
  860. }
  861. /**
  862. * Flatten an array
  863. *
  864. * @param array $array
  865. * @return array
  866. */
  867. public static function arrayFlatten($array)
  868. {
  869. $flatten = array();
  870. foreach ($array as $key => $inner) {
  871. if (is_array($inner)) {
  872. foreach ($inner as $inner_key => $value) {
  873. $flatten[$inner_key] = $value;
  874. }
  875. } else {
  876. $flatten[$key] = $inner;
  877. }
  878. }
  879. return $flatten;
  880. }
  881. /**
  882. * Flatten a multi-dimensional associative array into dot notation
  883. *
  884. * @param array $array
  885. * @param string $prepend
  886. * @return array
  887. */
  888. public static function arrayFlattenDotNotation($array, $prepend = '')
  889. {
  890. $results = array();
  891. foreach ($array as $key => $value) {
  892. if (is_array($value)) {
  893. $results = array_merge($results, static::arrayFlattenDotNotation($value, $prepend.$key.'.'));
  894. } else {
  895. $results[$prepend.$key] = $value;
  896. }
  897. }
  898. return $results;
  899. }
  900. /**
  901. * Opposite of flatten, convert flat dot notation array to multi dimensional array
  902. *
  903. * @param array $array
  904. * @param string $separator
  905. * @return array
  906. */
  907. public static function arrayUnflattenDotNotation($array, $separator = '.')
  908. {
  909. $newArray = [];
  910. foreach ($array as $key => $value) {
  911. $dots = explode($separator, $key);
  912. if (\count($dots) > 1) {
  913. $last = &$newArray[$dots[0]];
  914. foreach ($dots as $k => $dot) {
  915. if ($k === 0) {
  916. continue;
  917. }
  918. $last = &$last[$dot];
  919. }
  920. $last = $value;
  921. } else {
  922. $newArray[$key] = $value;
  923. }
  924. }
  925. return $newArray;
  926. }
  927. /**
  928. * Checks if the passed path contains the language code prefix
  929. *
  930. * @param string $string The path
  931. *
  932. * @return bool|string Either false or the language
  933. *
  934. */
  935. public static function pathPrefixedByLangCode($string)
  936. {
  937. $languages_enabled = Grav::instance()['config']->get('system.languages.supported', []);
  938. $parts = explode('/', trim($string, '/'));
  939. if (count($parts) > 0 && in_array($parts[0], $languages_enabled)) {
  940. return $parts[0];
  941. }
  942. return false;
  943. }
  944. /**
  945. * Get the timestamp of a date
  946. *
  947. * @param string $date a String expressed in the system.pages.dateformat.default format, with fallback to a
  948. * strtotime argument
  949. * @param string $format a date format to use if possible
  950. * @return int the timestamp
  951. */
  952. public static function date2timestamp($date, $format = null)
  953. {
  954. $config = Grav::instance()['config'];
  955. $dateformat = $format ?: $config->get('system.pages.dateformat.default');
  956. // try to use DateTime and default format
  957. if ($dateformat) {
  958. $datetime = \DateTime::createFromFormat($dateformat, $date);
  959. } else {
  960. $datetime = new \DateTime($date);
  961. }
  962. // fallback to strtotime() if DateTime approach failed
  963. if ($datetime !== false) {
  964. return $datetime->getTimestamp();
  965. }
  966. return strtotime($date);
  967. }
  968. /**
  969. * @param array $array
  970. * @param string $path
  971. * @param null $default
  972. * @return mixed
  973. *
  974. * @deprecated 1.5 Use ->getDotNotation() method instead.
  975. */
  976. public static function resolve(array $array, $path, $default = null)
  977. {
  978. user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.5, use ->getDotNotation() method instead', E_USER_DEPRECATED);
  979. return static::getDotNotation($array, $path, $default);
  980. }
  981. /**
  982. * Checks if a value is positive
  983. *
  984. * @param string $value
  985. *
  986. * @return boolean
  987. */
  988. public static function isPositive($value)
  989. {
  990. return in_array($value, [true, 1, '1', 'yes', 'on', 'true'], true);
  991. }
  992. /**
  993. * Generates a nonce string to be hashed. Called by self::getNonce()
  994. * We removed the IP portion in this version because it causes too many inconsistencies
  995. * with reverse proxy setups.
  996. *
  997. * @param string $action
  998. * @param bool $previousTick if true, generates the token for the previous tick (the previous 12 hours)
  999. *
  1000. * @return string the nonce string
  1001. */
  1002. private static function generateNonceString($action, $previousTick = false)
  1003. {
  1004. $grav = Grav::instance();
  1005. $username = isset($grav['user']) ? $grav['user']->username : '';
  1006. $token = session_id();
  1007. $i = self::nonceTick();
  1008. if ($previousTick) {
  1009. $i--;
  1010. }
  1011. return ($i . '|' . $action . '|' . $username . '|' . $token . '|' . $grav['config']->get('security.salt'));
  1012. }
  1013. /**
  1014. * Get the time-dependent variable for nonce creation.
  1015. *
  1016. * Now a tick lasts a day. Once the day is passed, the nonce is not valid any more. Find a better way
  1017. * to ensure nonces issued near the end of the day do not expire in that small amount of time
  1018. *
  1019. * @return int the time part of the nonce. Changes once every 24 hours
  1020. */
  1021. private static function nonceTick()
  1022. {
  1023. $secondsInHalfADay = 60 * 60 * 12;
  1024. return (int)ceil(time() / $secondsInHalfADay);
  1025. }
  1026. /**
  1027. * Creates a hashed nonce tied to the passed action. Tied to the current user and time. The nonce for a given
  1028. * action is the same for 12 hours.
  1029. *
  1030. * @param string $action the action the nonce is tied to (e.g. save-user-admin or move-page-homepage)
  1031. * @param bool $previousTick if true, generates the token for the previous tick (the previous 12 hours)
  1032. *
  1033. * @return string the nonce
  1034. */
  1035. public static function getNonce($action, $previousTick = false)
  1036. {
  1037. // Don't regenerate this again if not needed
  1038. if (isset(static::$nonces[$action][$previousTick])) {
  1039. return static::$nonces[$action][$previousTick];
  1040. }
  1041. $nonce = md5(self::generateNonceString($action, $previousTick));
  1042. static::$nonces[$action][$previousTick] = $nonce;
  1043. return static::$nonces[$action][$previousTick];
  1044. }
  1045. /**
  1046. * Verify the passed nonce for the give action
  1047. *
  1048. * @param string|string[] $nonce the nonce to verify
  1049. * @param string $action the action to verify the nonce to
  1050. *
  1051. * @return boolean verified or not
  1052. */
  1053. public static function verifyNonce($nonce, $action)
  1054. {
  1055. //Safety check for multiple nonces
  1056. if (is_array($nonce)) {
  1057. $nonce = array_shift($nonce);
  1058. }
  1059. //Nonce generated 0-12 hours ago
  1060. if ($nonce === self::getNonce($action)) {
  1061. return true;
  1062. }
  1063. //Nonce generated 12-24 hours ago
  1064. $previousTick = true;
  1065. return $nonce === self::getNonce($action, $previousTick);
  1066. }
  1067. /**
  1068. * Simple helper method to get whether or not the admin plugin is active
  1069. *
  1070. * @return bool
  1071. */
  1072. public static function isAdminPlugin()
  1073. {
  1074. if (isset(Grav::instance()['admin'])) {
  1075. return true;
  1076. }
  1077. return false;
  1078. }
  1079. /**
  1080. * Get a portion of an array (passed by reference) with dot-notation key
  1081. *
  1082. * @param array $array
  1083. * @param string|int $key
  1084. * @param null $default
  1085. * @return mixed
  1086. */
  1087. public static function getDotNotation($array, $key, $default = null)
  1088. {
  1089. if (null === $key) {
  1090. return $array;
  1091. }
  1092. if (isset($array[$key])) {
  1093. return $array[$key];
  1094. }
  1095. foreach (explode('.', $key) as $segment) {
  1096. if (!is_array($array) || !array_key_exists($segment, $array)) {
  1097. return $default;
  1098. }
  1099. $array = $array[$segment];
  1100. }
  1101. return $array;
  1102. }
  1103. /**
  1104. * Set portion of array (passed by reference) for a dot-notation key
  1105. * and set the value
  1106. *
  1107. * @param array $array
  1108. * @param string|int $key
  1109. * @param mixed $value
  1110. * @param bool $merge
  1111. *
  1112. * @return mixed
  1113. */
  1114. public static function setDotNotation(&$array, $key, $value, $merge = false)
  1115. {
  1116. if (null === $key) {
  1117. return $array = $value;
  1118. }
  1119. $keys = explode('.', $key);
  1120. while (count($keys) > 1) {
  1121. $key = array_shift($keys);
  1122. if ( ! isset($array[$key]) || ! is_array($array[$key]))
  1123. {
  1124. $array[$key] = array();
  1125. }
  1126. $array =& $array[$key];
  1127. }
  1128. $key = array_shift($keys);
  1129. if (!$merge || !isset($array[$key])) {
  1130. $array[$key] = $value;
  1131. } else {
  1132. $array[$key] = array_merge($array[$key], $value);
  1133. }
  1134. return $array;
  1135. }
  1136. /**
  1137. * Utility method to determine if the current OS is Windows
  1138. *
  1139. * @return bool
  1140. */
  1141. public static function isWindows()
  1142. {
  1143. return strncasecmp(PHP_OS, 'WIN', 3) === 0;
  1144. }
  1145. /**
  1146. * Utility to determine if the server running PHP is Apache
  1147. *
  1148. * @return bool
  1149. */
  1150. public static function isApache() {
  1151. return isset($_SERVER['SERVER_SOFTWARE']) && strpos($_SERVER['SERVER_SOFTWARE'], 'Apache') !== false;
  1152. }
  1153. /**
  1154. * Sort a multidimensional array by another array of ordered keys
  1155. *
  1156. * @param array $array
  1157. * @param array $orderArray
  1158. * @return array
  1159. */
  1160. public static function sortArrayByArray(array $array, array $orderArray)
  1161. {
  1162. $ordered = array();
  1163. foreach ($orderArray as $key) {
  1164. if (array_key_exists($key, $array)) {
  1165. $ordered[$key] = $array[$key];
  1166. unset($array[$key]);
  1167. }
  1168. }
  1169. return $ordered + $array;
  1170. }
  1171. /**
  1172. * Sort an array by a key value in the array
  1173. *
  1174. * @param mixed $array
  1175. * @param string|int $array_key
  1176. * @param int $direction
  1177. * @param int $sort_flags
  1178. * @return array
  1179. */
  1180. public static function sortArrayByKey($array, $array_key, $direction = SORT_DESC, $sort_flags = SORT_REGULAR)
  1181. {
  1182. $output = [];
  1183. if (!is_array($array) || !$array) {
  1184. return $output;
  1185. }
  1186. foreach ($array as $key => $row) {
  1187. $output[$key] = $row[$array_key];
  1188. }
  1189. array_multisort($output, $direction, $sort_flags, $array);
  1190. return $array;
  1191. }
  1192. /**
  1193. * Get path based on a token
  1194. *
  1195. * @param string $path
  1196. * @param PageInterface|null $page
  1197. * @return string
  1198. * @throws \RuntimeException
  1199. */
  1200. public static function getPagePathFromToken($path, PageInterface $page = null)
  1201. {
  1202. $path_parts = pathinfo($path);
  1203. $grav = Grav::instance();
  1204. $basename = '';
  1205. if (isset($path_parts['extension'])) {
  1206. $basename = '/' . $path_parts['basename'];
  1207. $path = rtrim($path_parts['dirname'], ':');
  1208. }
  1209. $regex = '/(@self|self@)|((?:@page|page@):(?:.*))|((?:@theme|theme@):(?:.*))/';
  1210. preg_match($regex, $path, $matches);
  1211. if ($matches) {
  1212. if ($matches[1]) {
  1213. if (null === $page) {
  1214. throw new \RuntimeException('Page not available for this self@ reference');
  1215. }
  1216. } elseif ($matches[2]) {
  1217. // page@
  1218. $parts = explode(':', $path);
  1219. $route = $parts[1];
  1220. $page = $grav['page']->find($route);
  1221. } elseif ($matches[3]) {
  1222. // theme@
  1223. $parts = explode(':', $path);
  1224. $route = $parts[1];
  1225. $theme = str_replace(ROOT_DIR, '', $grav['locator']->findResource("theme://"));
  1226. return $theme . $route . $basename;
  1227. }
  1228. } else {
  1229. return $path . $basename;
  1230. }
  1231. if (!$page) {
  1232. throw new \RuntimeException('Page route not found: ' . $path);
  1233. }
  1234. $path = str_replace($matches[0], rtrim($page->relativePagePath(), '/'), $path);
  1235. return $path . $basename;
  1236. }
  1237. public static function getUploadLimit()
  1238. {
  1239. static $max_size = -1;
  1240. if ($max_size < 0) {
  1241. $post_max_size = static::parseSize(ini_get('post_max_size'));
  1242. if ($post_max_size > 0) {
  1243. $max_size = $post_max_size;
  1244. } else {
  1245. $max_size = 0;
  1246. }
  1247. $upload_max = static::parseSize(ini_get('upload_max_filesize'));
  1248. if ($upload_max > 0 && $upload_max < $max_size) {
  1249. $max_size = $upload_max;
  1250. }
  1251. }
  1252. return $max_size;
  1253. }
  1254. /**
  1255. * Convert bytes to the unit specified by the $to parameter.
  1256. *
  1257. * @param int $bytes The filesize in Bytes.
  1258. * @param string $to The unit type to convert to. Accepts K, M, or G for Kilobytes, Megabytes, or Gigabytes, respectively.
  1259. * @param int $decimal_places The number of decimal places to return.
  1260. *
  1261. * @return int Returns only the number of units, not the type letter. Returns 0 if the $to unit type is out of scope.
  1262. *
  1263. */
  1264. public static function convertSize($bytes, $to, $decimal_places = 1)
  1265. {
  1266. $formulas = array(
  1267. 'K' => number_format($bytes / 1024, $decimal_places),
  1268. 'M' => number_format($bytes / 1048576, $decimal_places),
  1269. 'G' => number_format($bytes / 1073741824, $decimal_places)
  1270. );
  1271. return $formulas[$to] ?? 0;
  1272. }
  1273. /**
  1274. * Return a pretty size based on bytes
  1275. *
  1276. * @param int $bytes
  1277. * @param int $precision
  1278. * @return string
  1279. */
  1280. public static function prettySize($bytes, $precision = 2)
  1281. {
  1282. $units = array('B', 'KB', 'MB', 'GB', 'TB');
  1283. $bytes = max($bytes, 0);
  1284. $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
  1285. $pow = min($pow, count($units) - 1);
  1286. // Uncomment one of the following alternatives
  1287. $bytes /= 1024 ** $pow;
  1288. // $bytes /= (1 << (10 * $pow));
  1289. return round($bytes, $precision) . ' ' . $units[$pow];
  1290. }
  1291. /**
  1292. * Parse a readable file size and return a value in bytes
  1293. *
  1294. * @param string|int $size
  1295. * @return int
  1296. */
  1297. public static function parseSize($size)
  1298. {
  1299. $unit = preg_replace('/[^bkmgtpezy]/i', '', $size);
  1300. $size = preg_replace('/[^0-9\.]/', '', $size);
  1301. if ($unit) {
  1302. $size = $size * pow(1024, stripos('bkmgtpezy', $unit[0]));
  1303. }
  1304. return (int) abs(round($size));
  1305. }
  1306. /**
  1307. * Multibyte-safe Parse URL function
  1308. *
  1309. * @param string $url
  1310. * @return array
  1311. * @throws \InvalidArgumentException
  1312. */
  1313. public static function multibyteParseUrl($url)
  1314. {
  1315. $enc_url = preg_replace_callback(
  1316. '%[^:/@?&=#]+%usD',
  1317. function ($matches) {
  1318. return urlencode($matches[0]);
  1319. },
  1320. $url
  1321. );
  1322. $parts = parse_url($enc_url);
  1323. if($parts === false) {
  1324. throw new \InvalidArgumentException('Malformed URL: ' . $url);
  1325. }
  1326. foreach($parts as $name => $value) {
  1327. $parts[$name] = urldecode($value);
  1328. }
  1329. return $parts;
  1330. }
  1331. /**
  1332. * Process a string as markdown
  1333. *
  1334. * @param string $string
  1335. *
  1336. * @param bool $block Block or Line processing
  1337. * @param null $page
  1338. * @return string
  1339. * @throws \Exception
  1340. */
  1341. public static function processMarkdown($string, $block = true, $page = null)
  1342. {
  1343. $grav = Grav::instance();
  1344. $page = $page ?? $grav['page'] ?? null;
  1345. $defaults = [
  1346. 'markdown' => $grav['config']->get('system.pages.markdown', []),
  1347. 'images' => $grav['config']->get('system.images', [])
  1348. ];
  1349. $extra = $defaults['markdown']['extra'] ?? false;
  1350. $excerpts = new Excerpts($page, $defaults);
  1351. // Initialize the preferred variant of Parsedown
  1352. if ($extra) {
  1353. $parsedown = new ParsedownExtra($excerpts);
  1354. } else {
  1355. $parsedown = new Parsedown($excerpts);
  1356. }
  1357. if ($block) {
  1358. $string = $parsedown->text($string);
  1359. } else {
  1360. $string = $parsedown->line($string);
  1361. }
  1362. return $string;
  1363. }
  1364. /**
  1365. * Find the subnet of an ip with CIDR prefix size
  1366. *
  1367. * @param string $ip
  1368. * @param int $prefix
  1369. *
  1370. * @return string
  1371. */
  1372. public static function getSubnet($ip, $prefix = 64)
  1373. {
  1374. if (!filter_var($ip, FILTER_VALIDATE_IP)) {
  1375. return $ip;
  1376. }
  1377. // Packed representation of IP
  1378. $ip = inet_pton($ip);
  1379. // Maximum netmask length = same as packed address
  1380. $len = 8*strlen($ip);
  1381. if ($prefix > $len) $prefix = $len;
  1382. $mask = str_repeat('f', $prefix>>2);
  1383. switch($prefix & 3)
  1384. {
  1385. case 3: $mask .= 'e'; break;
  1386. case 2: $mask .= 'c'; break;
  1387. case 1: $mask .= '8'; break;
  1388. }
  1389. $mask = str_pad($mask, $len>>2, '0');
  1390. // Packed representation of netmask
  1391. $mask = pack('H*', $mask);
  1392. // Bitwise - Take all bits that are both 1 to generate subnet
  1393. $subnet = inet_ntop($ip & $mask);
  1394. return $subnet;
  1395. }
  1396. /**
  1397. * Wrapper to ensure html, htm in the front of the supported page types
  1398. *
  1399. * @param array|null $defaults
  1400. * @return array|mixed
  1401. */
  1402. public static function getSupportPageTypes(array $defaults = null)
  1403. {
  1404. $types = Grav::instance()['config']->get('system.pages.types', $defaults);
  1405. // remove html/htm
  1406. $types = static::arrayRemoveValue($types, ['html', 'htm']);
  1407. // put them back at the front
  1408. $types = array_merge(['html', 'htm'], $types);
  1409. return $types;
  1410. }
  1411. }