Utils.php 47 KB

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