Utils.php 64 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213
  1. <?php
  2. /**
  3. * @package Grav\Common
  4. *
  5. * @copyright Copyright (c) 2015 - 2023 Trilby Media, LLC. All rights reserved.
  6. * @license MIT License; see LICENSE file for details.
  7. */
  8. namespace Grav\Common;
  9. use DateTime;
  10. use DateTimeZone;
  11. use Exception;
  12. use Grav\Common\Flex\Types\Pages\PageObject;
  13. use Grav\Common\Helpers\Truncator;
  14. use Grav\Common\Page\Interfaces\PageInterface;
  15. use Grav\Common\Markdown\Parsedown;
  16. use Grav\Common\Markdown\ParsedownExtra;
  17. use Grav\Common\Page\Markdown\Excerpts;
  18. use Grav\Common\Page\Pages;
  19. use Grav\Framework\Flex\Flex;
  20. use Grav\Framework\Flex\Interfaces\FlexObjectInterface;
  21. use Grav\Framework\Media\Interfaces\MediaInterface;
  22. use InvalidArgumentException;
  23. use Negotiation\Accept;
  24. use Negotiation\Negotiator;
  25. use RocketTheme\Toolbox\Event\Event;
  26. use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
  27. use RuntimeException;
  28. use function array_key_exists;
  29. use function array_slice;
  30. use function count;
  31. use function extension_loaded;
  32. use function function_exists;
  33. use function in_array;
  34. use function is_array;
  35. use function is_callable;
  36. use function is_string;
  37. use function strlen;
  38. /**
  39. * Class Utils
  40. * @package Grav\Common
  41. */
  42. abstract class Utils
  43. {
  44. /** @var array */
  45. protected static $nonces = [];
  46. protected const ROOTURL_REGEX = '{^((?:http[s]?:\/\/[^\/]+)|(?:\/\/[^\/]+))(.*)}';
  47. // ^((?:http[s]?:)?[\/]?(?:\/))
  48. /**
  49. * Simple helper method to make getting a Grav URL easier
  50. *
  51. * @param string|object $input
  52. * @param bool $domain
  53. * @param bool $fail_gracefully
  54. * @return string|false
  55. */
  56. public static function url($input, $domain = false, $fail_gracefully = false)
  57. {
  58. if ((!is_string($input) && !is_callable([$input, '__toString'])) || !trim($input)) {
  59. if ($fail_gracefully) {
  60. $input = '/';
  61. } else {
  62. return false;
  63. }
  64. }
  65. $input = (string)$input;
  66. if (Uri::isExternal($input)) {
  67. return $input;
  68. }
  69. $grav = Grav::instance();
  70. /** @var Uri $uri */
  71. $uri = $grav['uri'];
  72. $resource = false;
  73. if (static::contains((string)$input, '://')) {
  74. // Url contains a scheme (https:// , user:// etc).
  75. /** @var UniformResourceLocator $locator */
  76. $locator = $grav['locator'];
  77. $parts = Uri::parseUrl($input);
  78. if (is_array($parts)) {
  79. // Make sure we always have scheme, host, port and path.
  80. $scheme = $parts['scheme'] ?? '';
  81. $host = $parts['host'] ?? '';
  82. $port = $parts['port'] ?? '';
  83. $path = $parts['path'] ?? '';
  84. if ($scheme && !$port) {
  85. // If URL has a scheme, we need to check if it's one of Grav streams.
  86. if (!$locator->schemeExists($scheme)) {
  87. // If scheme does not exists as a stream, assume it's external.
  88. return str_replace(' ', '%20', $input);
  89. }
  90. // Attempt to find the resource (because of parse_url() we need to put host back to path).
  91. $resource = $locator->findResource("{$scheme}://{$host}{$path}", false);
  92. if ($resource === false) {
  93. if (!$fail_gracefully) {
  94. return false;
  95. }
  96. // Return location where the file would be if it was saved.
  97. $resource = $locator->findResource("{$scheme}://{$host}{$path}", false, true);
  98. }
  99. } elseif ($host || $port) {
  100. // If URL doesn't have scheme but has host or port, it is external.
  101. return str_replace(' ', '%20', $input);
  102. }
  103. if (!empty($resource)) {
  104. // Add query string back.
  105. if (isset($parts['query'])) {
  106. $resource .= '?' . $parts['query'];
  107. }
  108. // Add fragment back.
  109. if (isset($parts['fragment'])) {
  110. $resource .= '#' . $parts['fragment'];
  111. }
  112. }
  113. } else {
  114. // Not a valid URL (can still be a stream).
  115. $resource = $locator->findResource($input, false);
  116. }
  117. } else {
  118. // Just a path.
  119. /** @var Pages $pages */
  120. $pages = $grav['pages'];
  121. // Is this a page?
  122. $page = $pages->find($input, true);
  123. if ($page && $page->routable()) {
  124. return $page->url($domain);
  125. }
  126. $root = preg_quote($uri->rootUrl(), '#');
  127. $pattern = '#(' . $root . '$|' . $root . '/)#';
  128. if (!empty($root) && preg_match($pattern, $input, $matches)) {
  129. $input = static::replaceFirstOccurrence($matches[0], '', $input);
  130. }
  131. $input = ltrim($input, '/');
  132. $resource = $input;
  133. }
  134. if (!$fail_gracefully && $resource === false) {
  135. return false;
  136. }
  137. $domain = $domain ?: $grav['config']->get('system.absolute_urls', false);
  138. return rtrim($uri->rootUrl($domain), '/') . '/' . ($resource ?: '');
  139. }
  140. /**
  141. * Helper method to find the full path to a file, be it a stream, a relative path, or
  142. * already a full path
  143. *
  144. * @param string $path
  145. * @return string
  146. */
  147. public static function fullPath($path)
  148. {
  149. $locator = Grav::instance()['locator'];
  150. if ($locator->isStream($path)) {
  151. $path = $locator->findResource($path, true);
  152. } elseif (!static::startsWith($path, GRAV_ROOT)) {
  153. $base_url = Grav::instance()['base_url'];
  154. $path = GRAV_ROOT . '/' . ltrim(static::replaceFirstOccurrence($base_url, '', $path), '/');
  155. }
  156. return $path;
  157. }
  158. /**
  159. * Check if the $haystack string starts with the substring $needle
  160. *
  161. * @param string $haystack
  162. * @param string|string[] $needle
  163. * @param bool $case_sensitive
  164. * @return bool
  165. */
  166. public static function startsWith($haystack, $needle, $case_sensitive = true)
  167. {
  168. $status = false;
  169. $compare_func = $case_sensitive ? 'mb_strpos' : 'mb_stripos';
  170. foreach ((array)$needle as $each_needle) {
  171. $status = $each_needle === '' || $compare_func((string) $haystack, $each_needle) === 0;
  172. if ($status) {
  173. break;
  174. }
  175. }
  176. return $status;
  177. }
  178. /**
  179. * Check if the $haystack string ends with the substring $needle
  180. *
  181. * @param string $haystack
  182. * @param string|string[] $needle
  183. * @param bool $case_sensitive
  184. * @return bool
  185. */
  186. public static function endsWith($haystack, $needle, $case_sensitive = true)
  187. {
  188. $status = false;
  189. $compare_func = $case_sensitive ? 'mb_strrpos' : 'mb_strripos';
  190. foreach ((array)$needle as $each_needle) {
  191. $expectedPosition = mb_strlen((string) $haystack) - mb_strlen($each_needle);
  192. $status = $each_needle === '' || $compare_func((string) $haystack, $each_needle, 0) === $expectedPosition;
  193. if ($status) {
  194. break;
  195. }
  196. }
  197. return $status;
  198. }
  199. /**
  200. * Check if the $haystack string contains the substring $needle
  201. *
  202. * @param string $haystack
  203. * @param string|string[] $needle
  204. * @param bool $case_sensitive
  205. * @return bool
  206. */
  207. public static function contains($haystack, $needle, $case_sensitive = true)
  208. {
  209. $status = false;
  210. $compare_func = $case_sensitive ? 'mb_strpos' : 'mb_stripos';
  211. foreach ((array)$needle as $each_needle) {
  212. $status = $each_needle === '' || $compare_func((string) $haystack, $each_needle) !== false;
  213. if ($status) {
  214. break;
  215. }
  216. }
  217. return $status;
  218. }
  219. /**
  220. * Function that can match wildcards
  221. *
  222. * match_wildcard('foo*', $test), // TRUE
  223. * match_wildcard('bar*', $test), // FALSE
  224. * match_wildcard('*bar*', $test), // TRUE
  225. * match_wildcard('**blob**', $test), // TRUE
  226. * match_wildcard('*a?d*', $test), // TRUE
  227. * match_wildcard('*etc**', $test) // TRUE
  228. *
  229. * @param string $wildcard_pattern
  230. * @param string $haystack
  231. * @return false|int
  232. */
  233. public static function matchWildcard($wildcard_pattern, $haystack)
  234. {
  235. $regex = str_replace(
  236. array("\*", "\?"), // wildcard chars
  237. array('.*', '.'), // regexp chars
  238. preg_quote($wildcard_pattern, '/')
  239. );
  240. return preg_match('/^' . $regex . '$/is', $haystack);
  241. }
  242. /**
  243. * Render simple template filling up the variables in it. If value is not defined, leave it as it was.
  244. *
  245. * @param string $template Template string
  246. * @param array $variables Variables with values
  247. * @param array $brackets Optional array of opening and closing brackets or symbols
  248. * @return string Final string filled with values
  249. */
  250. public static function simpleTemplate(string $template, array $variables, array $brackets = ['{', '}']): string
  251. {
  252. $opening = $brackets[0] ?? '{';
  253. $closing = $brackets[1] ?? '}';
  254. $expression = '/' . preg_quote($opening, '/') . '(.*?)' . preg_quote($closing, '/') . '/';
  255. $callback = static function ($match) use ($variables) {
  256. return $variables[$match[1]] ?? $match[0];
  257. };
  258. return preg_replace_callback($expression, $callback, $template);
  259. }
  260. /**
  261. * Returns the substring of a string up to a specified needle. if not found, return the whole haystack
  262. *
  263. * @param string $haystack
  264. * @param string $needle
  265. * @param bool $case_sensitive
  266. *
  267. * @return string
  268. */
  269. public static function substrToString($haystack, $needle, $case_sensitive = true)
  270. {
  271. $compare_func = $case_sensitive ? 'mb_strpos' : 'mb_stripos';
  272. if (static::contains($haystack, $needle, $case_sensitive)) {
  273. return mb_substr($haystack, 0, $compare_func($haystack, $needle, $case_sensitive));
  274. }
  275. return $haystack;
  276. }
  277. /**
  278. * Utility method to replace only the first occurrence in a string
  279. *
  280. * @param string $search
  281. * @param string $replace
  282. * @param string $subject
  283. *
  284. * @return string
  285. */
  286. public static function replaceFirstOccurrence($search, $replace, $subject)
  287. {
  288. if (!$search) {
  289. return $subject;
  290. }
  291. $pos = mb_strpos($subject, $search);
  292. if ($pos !== false) {
  293. $subject = static::mb_substr_replace($subject, $replace, $pos, mb_strlen($search));
  294. }
  295. return $subject;
  296. }
  297. /**
  298. * Utility method to replace only the last occurrence in a string
  299. *
  300. * @param string $search
  301. * @param string $replace
  302. * @param string $subject
  303. * @return string
  304. */
  305. public static function replaceLastOccurrence($search, $replace, $subject)
  306. {
  307. $pos = strrpos($subject, $search);
  308. if ($pos !== false) {
  309. $subject = static::mb_substr_replace($subject, $replace, $pos, mb_strlen($search));
  310. }
  311. return $subject;
  312. }
  313. /**
  314. * Multibyte compatible substr_replace
  315. *
  316. * @param string $original
  317. * @param string $replacement
  318. * @param int $position
  319. * @param int $length
  320. * @return string
  321. */
  322. public static function mb_substr_replace($original, $replacement, $position, $length)
  323. {
  324. $startString = mb_substr($original, 0, $position, 'UTF-8');
  325. $endString = mb_substr($original, $position + $length, mb_strlen($original), 'UTF-8');
  326. return $startString . $replacement . $endString;
  327. }
  328. /**
  329. * Merge two objects into one.
  330. *
  331. * @param object $obj1
  332. * @param object $obj2
  333. *
  334. * @return object
  335. */
  336. public static function mergeObjects($obj1, $obj2)
  337. {
  338. return (object)array_merge((array)$obj1, (array)$obj2);
  339. }
  340. /**
  341. * @param array $array
  342. * @return bool
  343. */
  344. public static function isAssoc(array $array)
  345. {
  346. return (array_values($array) !== $array);
  347. }
  348. /**
  349. * Lowercase an entire array. Useful when combined with `in_array()`
  350. *
  351. * @param array $a
  352. * @return array|false
  353. */
  354. public static function arrayLower(array $a)
  355. {
  356. return array_map('mb_strtolower', $a);
  357. }
  358. /**
  359. * Simple function to remove item/s in an array by value
  360. *
  361. * @param array $search
  362. * @param string|array $value
  363. * @return array
  364. */
  365. public static function arrayRemoveValue(array $search, $value)
  366. {
  367. foreach ((array)$value as $val) {
  368. $key = array_search($val, $search);
  369. if ($key !== false) {
  370. unset($search[$key]);
  371. }
  372. }
  373. return $search;
  374. }
  375. /**
  376. * Recursive Merge with uniqueness
  377. *
  378. * @param array $array1
  379. * @param array $array2
  380. * @return array
  381. */
  382. public static function arrayMergeRecursiveUnique($array1, $array2)
  383. {
  384. if (empty($array1)) {
  385. // Optimize the base case
  386. return $array2;
  387. }
  388. foreach ($array2 as $key => $value) {
  389. if (is_array($value) && isset($array1[$key]) && is_array($array1[$key])) {
  390. $value = static::arrayMergeRecursiveUnique($array1[$key], $value);
  391. }
  392. $array1[$key] = $value;
  393. }
  394. return $array1;
  395. }
  396. /**
  397. * Returns an array with the differences between $array1 and $array2
  398. *
  399. * @param array $array1
  400. * @param array $array2
  401. * @return array
  402. */
  403. public static function arrayDiffMultidimensional($array1, $array2)
  404. {
  405. $result = array();
  406. foreach ($array1 as $key => $value) {
  407. if (!is_array($array2) || !array_key_exists($key, $array2)) {
  408. $result[$key] = $value;
  409. continue;
  410. }
  411. if (is_array($value)) {
  412. $recursiveArrayDiff = static::ArrayDiffMultidimensional($value, $array2[$key]);
  413. if (count($recursiveArrayDiff)) {
  414. $result[$key] = $recursiveArrayDiff;
  415. }
  416. continue;
  417. }
  418. if ($value != $array2[$key]) {
  419. $result[$key] = $value;
  420. }
  421. }
  422. return $result;
  423. }
  424. /**
  425. * Array combine but supports different array lengths
  426. *
  427. * @param array $arr1
  428. * @param array $arr2
  429. * @return array|false
  430. */
  431. public static function arrayCombine($arr1, $arr2)
  432. {
  433. $count = min(count($arr1), count($arr2));
  434. return array_combine(array_slice($arr1, 0, $count), array_slice($arr2, 0, $count));
  435. }
  436. /**
  437. * Array is associative or not
  438. *
  439. * @param array $arr
  440. * @return bool
  441. */
  442. public static function arrayIsAssociative($arr)
  443. {
  444. if ([] === $arr) {
  445. return false;
  446. }
  447. return array_keys($arr) !== range(0, count($arr) - 1);
  448. }
  449. /**
  450. * Return the Grav date formats allowed
  451. *
  452. * @return array
  453. */
  454. public static function dateFormats()
  455. {
  456. $now = new DateTime();
  457. $date_formats = [
  458. 'd-m-Y H:i' => 'd-m-Y H:i (e.g. ' . $now->format('d-m-Y H:i') . ')',
  459. 'Y-m-d H:i' => 'Y-m-d H:i (e.g. ' . $now->format('Y-m-d H:i') . ')',
  460. 'm/d/Y h:i a' => 'm/d/Y h:i a (e.g. ' . $now->format('m/d/Y h:i a') . ')',
  461. 'H:i d-m-Y' => 'H:i d-m-Y (e.g. ' . $now->format('H:i d-m-Y') . ')',
  462. 'h:i a m/d/Y' => 'h:i a m/d/Y (e.g. ' . $now->format('h:i a m/d/Y') . ')',
  463. ];
  464. $default_format = Grav::instance()['config']->get('system.pages.dateformat.default');
  465. if ($default_format) {
  466. $date_formats = array_merge([$default_format => $default_format . ' (e.g. ' . $now->format($default_format) . ')'], $date_formats);
  467. }
  468. return $date_formats;
  469. }
  470. /**
  471. * Get current date/time
  472. *
  473. * @param string|null $default_format
  474. * @return string
  475. * @throws Exception
  476. */
  477. public static function dateNow($default_format = null)
  478. {
  479. $now = new DateTime();
  480. if (null === $default_format) {
  481. $default_format = Grav::instance()['config']->get('system.pages.dateformat.default');
  482. }
  483. return $now->format($default_format);
  484. }
  485. /**
  486. * Truncate text by number of characters but can cut off words.
  487. *
  488. * @param string $string
  489. * @param int $limit Max number of characters.
  490. * @param bool $up_to_break truncate up to breakpoint after char count
  491. * @param string $break Break point.
  492. * @param string $pad Appended padding to the end of the string.
  493. * @return string
  494. */
  495. public static function truncate($string, $limit = 150, $up_to_break = false, $break = ' ', $pad = '&hellip;')
  496. {
  497. // return with no change if string is shorter than $limit
  498. if (mb_strlen($string) <= $limit) {
  499. return $string;
  500. }
  501. // is $break present between $limit and the end of the string?
  502. if ($up_to_break && false !== ($breakpoint = mb_strpos($string, $break, $limit))) {
  503. if ($breakpoint < mb_strlen($string) - 1) {
  504. $string = mb_substr($string, 0, $breakpoint) . $pad;
  505. }
  506. } else {
  507. $string = mb_substr($string, 0, $limit) . $pad;
  508. }
  509. return $string;
  510. }
  511. /**
  512. * Truncate text by number of characters in a "word-safe" manor.
  513. *
  514. * @param string $string
  515. * @param int $limit
  516. * @return string
  517. */
  518. public static function safeTruncate($string, $limit = 150)
  519. {
  520. return static::truncate($string, $limit, true);
  521. }
  522. /**
  523. * Truncate HTML by number of characters. not "word-safe"!
  524. *
  525. * @param string $text
  526. * @param int $length in characters
  527. * @param string $ellipsis
  528. * @return string
  529. */
  530. public static function truncateHtml($text, $length = 100, $ellipsis = '...')
  531. {
  532. return Truncator::truncateLetters($text, $length, $ellipsis);
  533. }
  534. /**
  535. * Truncate HTML by number of characters in a "word-safe" manor.
  536. *
  537. * @param string $text
  538. * @param int $length in words
  539. * @param string $ellipsis
  540. * @return string
  541. */
  542. public static function safeTruncateHtml($text, $length = 25, $ellipsis = '...')
  543. {
  544. return Truncator::truncateWords($text, $length, $ellipsis);
  545. }
  546. /**
  547. * Generate a random string of a given length
  548. *
  549. * @param int $length
  550. * @return string
  551. */
  552. public static function generateRandomString($length = 5)
  553. {
  554. return substr(str_shuffle('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'), 0, $length);
  555. }
  556. /**
  557. * Generates a random string with configurable length, prefix and suffix.
  558. * Unlike the built-in `uniqid()`, this string is non-conflicting and safe
  559. *
  560. * @param int $length
  561. * @param array $options
  562. * @return string
  563. * @throws Exception
  564. */
  565. public static function uniqueId(int $length = 13, array $options = []): string
  566. {
  567. $options = array_merge(['prefix' => '', 'suffix' => ''], $options);
  568. $bytes = random_bytes(ceil($length / 2));
  569. return $options['prefix'] . substr(bin2hex($bytes), 0, $length) . $options['suffix'];
  570. }
  571. /**
  572. * Provides the ability to download a file to the browser
  573. *
  574. * @param string $file the full path to the file to be downloaded
  575. * @param bool $force_download as opposed to letting browser choose if to download or render
  576. * @param int $sec Throttling, try 0.1 for some speed throttling of downloads
  577. * @param int $bytes Size of chunks to send in bytes. Default is 1024
  578. * @param array $options Extra options: [mime, download_name, expires]
  579. * @throws Exception
  580. */
  581. public static function download($file, $force_download = true, $sec = 0, $bytes = 1024, array $options = [])
  582. {
  583. $grav = Grav::instance();
  584. if (file_exists($file)) {
  585. // fire download event
  586. $grav->fireEvent('onBeforeDownload', new Event(['file' => $file, 'options' => &$options]));
  587. $file_parts = static::pathinfo($file);
  588. $mimetype = $options['mime'] ?? static::getMimeByExtension($file_parts['extension']);
  589. $size = filesize($file); // File size
  590. $grav->cleanOutputBuffers();
  591. // required for IE, otherwise Content-Disposition may be ignored
  592. if (ini_get('zlib.output_compression')) {
  593. ini_set('zlib.output_compression', 'Off');
  594. }
  595. header('Content-Type: ' . $mimetype);
  596. header('Accept-Ranges: bytes');
  597. if ($force_download) {
  598. // output the regular HTTP headers
  599. header('Content-Disposition: attachment; filename="' . ($options['download_name'] ?? $file_parts['basename']) . '"');
  600. }
  601. // multipart-download and download resuming support
  602. if (isset($_SERVER['HTTP_RANGE'])) {
  603. [$a, $range] = explode('=', $_SERVER['HTTP_RANGE'], 2);
  604. [$range] = explode(',', $range, 2);
  605. [$range, $range_end] = explode('-', $range);
  606. $range = (int)$range;
  607. if (!$range_end) {
  608. $range_end = $size - 1;
  609. } else {
  610. $range_end = (int)$range_end;
  611. }
  612. $new_length = $range_end - $range + 1;
  613. header('HTTP/1.1 206 Partial Content');
  614. header("Content-Length: {$new_length}");
  615. header("Content-Range: bytes {$range}-{$range_end}/{$size}");
  616. } else {
  617. $range = 0;
  618. $new_length = $size;
  619. header('Content-Length: ' . $size);
  620. if ($grav['config']->get('system.cache.enabled')) {
  621. $expires = $options['expires'] ?? $grav['config']->get('system.pages.expires');
  622. if ($expires > 0) {
  623. $expires_date = gmdate('D, d M Y H:i:s T', time() + $expires);
  624. header('Cache-Control: max-age=' . $expires);
  625. header('Expires: ' . $expires_date);
  626. header('Pragma: cache');
  627. }
  628. header('Last-Modified: ' . gmdate('D, d M Y H:i:s T', filemtime($file)));
  629. // Return 304 Not Modified if the file is already cached in the browser
  630. if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) &&
  631. strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) >= filemtime($file)) {
  632. header('HTTP/1.1 304 Not Modified');
  633. exit();
  634. }
  635. }
  636. }
  637. /* output the file itself */
  638. $chunksize = $bytes * 8; //you may want to change this
  639. $bytes_send = 0;
  640. $fp = @fopen($file, 'rb');
  641. if ($fp) {
  642. if ($range) {
  643. fseek($fp, $range);
  644. }
  645. while (!feof($fp) && (!connection_aborted()) && ($bytes_send < $new_length)) {
  646. $buffer = fread($fp, $chunksize);
  647. echo($buffer); //echo($buffer); // is also possible
  648. flush();
  649. usleep($sec * 1000000);
  650. $bytes_send += strlen($buffer);
  651. }
  652. fclose($fp);
  653. } else {
  654. throw new RuntimeException('Error - can not open file.');
  655. }
  656. exit;
  657. }
  658. }
  659. /**
  660. * Returns the output render format, usually the extension provided in the URL. (e.g. `html`, `json`, `xml`, etc).
  661. *
  662. * @return string
  663. */
  664. public static function getPageFormat(): string
  665. {
  666. /** @var Uri $uri */
  667. $uri = Grav::instance()['uri'];
  668. // Set from uri extension
  669. $uri_extension = $uri->extension();
  670. if (is_string($uri_extension) && $uri->isValidExtension($uri_extension)) {
  671. return ($uri_extension);
  672. }
  673. // Use content negotiation via the `accept:` header
  674. $http_accept = $_SERVER['HTTP_ACCEPT'] ?? null;
  675. if (is_string($http_accept)) {
  676. $negotiator = new Negotiator();
  677. $supported_types = static::getSupportPageTypes(['html', 'json']);
  678. $priorities = static::getMimeTypes($supported_types);
  679. $media_type = $negotiator->getBest($http_accept, $priorities);
  680. $mimetype = $media_type instanceof Accept ? $media_type->getValue() : '';
  681. return static::getExtensionByMime($mimetype);
  682. }
  683. return 'html';
  684. }
  685. /**
  686. * Return the mimetype based on filename extension
  687. *
  688. * @param string $extension Extension of file (eg "txt")
  689. * @param string $default
  690. * @return string
  691. */
  692. public static function getMimeByExtension($extension, $default = 'application/octet-stream')
  693. {
  694. $extension = strtolower($extension);
  695. // look for some standard types
  696. switch ($extension) {
  697. case null:
  698. return $default;
  699. case 'json':
  700. return 'application/json';
  701. case 'html':
  702. return 'text/html';
  703. case 'atom':
  704. return 'application/atom+xml';
  705. case 'rss':
  706. return 'application/rss+xml';
  707. case 'xml':
  708. return 'application/xml';
  709. }
  710. $media_types = Grav::instance()['config']->get('media.types');
  711. return $media_types[$extension]['mime'] ?? $default;
  712. }
  713. /**
  714. * Get all the mimetypes for an array of extensions
  715. *
  716. * @param array $extensions
  717. * @return array
  718. */
  719. public static function getMimeTypes(array $extensions)
  720. {
  721. $mimetypes = [];
  722. foreach ($extensions as $extension) {
  723. $mimetype = static::getMimeByExtension($extension, false);
  724. if ($mimetype && !in_array($mimetype, $mimetypes)) {
  725. $mimetypes[] = $mimetype;
  726. }
  727. }
  728. return $mimetypes;
  729. }
  730. /**
  731. * Return all extensions for given mimetype. The first extension is the default one.
  732. *
  733. * @param string $mime Mime type (eg 'image/jpeg')
  734. * @return string[] List of extensions eg. ['jpg', 'jpe', 'jpeg']
  735. */
  736. public static function getExtensionsByMime($mime)
  737. {
  738. $mime = strtolower($mime);
  739. $media_types = (array)Grav::instance()['config']->get('media.types');
  740. $list = [];
  741. foreach ($media_types as $extension => $type) {
  742. if ($extension === '' || $extension === 'defaults') {
  743. continue;
  744. }
  745. if (isset($type['mime']) && $type['mime'] === $mime) {
  746. $list[] = $extension;
  747. }
  748. }
  749. return $list;
  750. }
  751. /**
  752. * Return the mimetype based on filename extension
  753. *
  754. * @param string $mime mime type (eg "text/html")
  755. * @param string $default default value
  756. * @return string
  757. */
  758. public static function getExtensionByMime($mime, $default = 'html')
  759. {
  760. $mime = strtolower($mime);
  761. // look for some standard mime types
  762. switch ($mime) {
  763. case '*/*':
  764. case 'text/*':
  765. case 'text/html':
  766. return 'html';
  767. case 'application/json':
  768. return 'json';
  769. case 'application/atom+xml':
  770. return 'atom';
  771. case 'application/rss+xml':
  772. return 'rss';
  773. case 'application/xml':
  774. return 'xml';
  775. }
  776. $media_types = (array)Grav::instance()['config']->get('media.types');
  777. foreach ($media_types as $extension => $type) {
  778. if ($extension === 'defaults') {
  779. continue;
  780. }
  781. if (isset($type['mime']) && $type['mime'] === $mime) {
  782. return $extension;
  783. }
  784. }
  785. return $default;
  786. }
  787. /**
  788. * Get all the extensions for an array of mimetypes
  789. *
  790. * @param array $mimetypes
  791. * @return array
  792. */
  793. public static function getExtensions(array $mimetypes)
  794. {
  795. $extensions = [];
  796. foreach ($mimetypes as $mimetype) {
  797. $extension = static::getExtensionByMime($mimetype, false);
  798. if ($extension && !in_array($extension, $extensions, true)) {
  799. $extensions[] = $extension;
  800. }
  801. }
  802. return $extensions;
  803. }
  804. /**
  805. * Return the mimetype based on filename
  806. *
  807. * @param string $filename Filename or path to file
  808. * @param string $default default value
  809. * @return string
  810. */
  811. public static function getMimeByFilename($filename, $default = 'application/octet-stream')
  812. {
  813. return static::getMimeByExtension(static::pathinfo($filename, PATHINFO_EXTENSION), $default);
  814. }
  815. /**
  816. * Return the mimetype based on existing local file
  817. *
  818. * @param string $filename Path to the file
  819. * @param string $default
  820. * @return string|bool
  821. */
  822. public static function getMimeByLocalFile($filename, $default = 'application/octet-stream')
  823. {
  824. $type = false;
  825. // For local files we can detect type by the file content.
  826. if (!stream_is_local($filename) || !file_exists($filename)) {
  827. return false;
  828. }
  829. // Prefer using finfo if it exists.
  830. if (extension_loaded('fileinfo')) {
  831. $finfo = finfo_open(FILEINFO_SYMLINK | FILEINFO_MIME_TYPE);
  832. $type = finfo_file($finfo, $filename);
  833. finfo_close($finfo);
  834. } else {
  835. // Fall back to use getimagesize() if it is available (not recommended, but better than nothing)
  836. $info = @getimagesize($filename);
  837. if ($info) {
  838. $type = $info['mime'];
  839. }
  840. }
  841. return $type ?: static::getMimeByFilename($filename, $default);
  842. }
  843. /**
  844. * Returns true if filename is considered safe.
  845. *
  846. * @param string $filename
  847. * @return bool
  848. */
  849. public static function checkFilename($filename)
  850. {
  851. $dangerous_extensions = Grav::instance()['config']->get('security.uploads_dangerous_extensions', []);
  852. $extension = static::pathinfo($filename, PATHINFO_EXTENSION);
  853. return !(
  854. // Empty filenames are not allowed.
  855. !$filename
  856. // Filename should not contain horizontal/vertical tabs, newlines, nils or back/forward slashes.
  857. || strtr($filename, "\t\v\n\r\0\\/", '_______') !== $filename
  858. // Filename should not start or end with dot or space.
  859. || trim($filename, '. ') !== $filename
  860. // File extension should not be part of configured dangerous extensions
  861. || in_array($extension, $dangerous_extensions)
  862. );
  863. }
  864. /**
  865. * Unicode-safe version of PHP’s pathinfo() function.
  866. *
  867. * @link https://www.php.net/manual/en/function.pathinfo.php
  868. *
  869. * @param string $path
  870. * @param int|null $flags
  871. * @return array|string
  872. */
  873. public static function pathinfo($path, int $flags = null)
  874. {
  875. $path = str_replace(['%2F', '%5C'], ['/', '\\'], rawurlencode($path));
  876. if (null === $flags) {
  877. $info = pathinfo($path);
  878. } else {
  879. $info = pathinfo($path, $flags);
  880. }
  881. if (is_array($info)) {
  882. return array_map('rawurldecode', $info);
  883. }
  884. return rawurldecode($info);
  885. }
  886. /**
  887. * Unicode-safe version of the PHP basename() function.
  888. *
  889. * @link https://www.php.net/manual/en/function.basename.php
  890. *
  891. * @param string $path
  892. * @param string $suffix
  893. * @return string
  894. */
  895. public static function basename($path, string $suffix = ''): string
  896. {
  897. return rawurldecode(basename(str_replace(['%2F', '%5C'], '/', rawurlencode($path)), $suffix));
  898. }
  899. /**
  900. * Normalize path by processing relative `.` and `..` syntax and merging path
  901. *
  902. * @param string $path
  903. * @return string
  904. */
  905. public static function normalizePath($path)
  906. {
  907. // Resolve any streams
  908. /** @var UniformResourceLocator $locator */
  909. $locator = Grav::instance()['locator'];
  910. if ($locator->isStream($path)) {
  911. $path = $locator->findResource($path);
  912. }
  913. // Set root properly for any URLs
  914. $root = '';
  915. preg_match(self::ROOTURL_REGEX, $path, $matches);
  916. if ($matches) {
  917. $root = $matches[1];
  918. $path = $matches[2];
  919. }
  920. // Strip off leading / to ensure explode is accurate
  921. if (static::startsWith($path, '/')) {
  922. $root .= '/';
  923. $path = ltrim($path, '/');
  924. }
  925. // If there are any relative paths (..) handle those
  926. if (static::contains($path, '..')) {
  927. $segments = explode('/', trim($path, '/'));
  928. $ret = [];
  929. foreach ($segments as $segment) {
  930. if (($segment === '.') || $segment === '') {
  931. continue;
  932. }
  933. if ($segment === '..') {
  934. array_pop($ret);
  935. } else {
  936. $ret[] = $segment;
  937. }
  938. }
  939. $path = implode('/', $ret);
  940. }
  941. // Stick everything back together
  942. $normalized = $root . $path;
  943. return $normalized;
  944. }
  945. /**
  946. * Check whether a function exists.
  947. *
  948. * Disabled functions count as non-existing functions, just like in PHP 8+.
  949. *
  950. * @param string $function the name of the function to check
  951. * @return bool
  952. */
  953. public static function functionExists($function): bool
  954. {
  955. if (!function_exists($function)) {
  956. return false;
  957. }
  958. // In PHP 7 we need to also exclude disabled methods.
  959. return !static::isFunctionDisabled($function);
  960. }
  961. /**
  962. * Check whether a function is disabled in the PHP settings
  963. *
  964. * @param string $function the name of the function to check
  965. * @return bool
  966. */
  967. public static function isFunctionDisabled($function): bool
  968. {
  969. static $list;
  970. if (null === $list) {
  971. $str = trim(ini_get('disable_functions') . ',' . ini_get('suhosin.executor.func.blacklist'), ',');
  972. $list = $str ? array_flip(preg_split('/\s*,\s*/', $str)) : [];
  973. }
  974. return array_key_exists($function, $list);
  975. }
  976. /**
  977. * Get the formatted timezones list
  978. *
  979. * @return array
  980. */
  981. public static function timezones()
  982. {
  983. $timezones = DateTimeZone::listIdentifiers(DateTimeZone::ALL);
  984. $offsets = [];
  985. $testDate = new DateTime();
  986. foreach ($timezones as $zone) {
  987. $tz = new DateTimeZone($zone);
  988. $offsets[$zone] = $tz->getOffset($testDate);
  989. }
  990. asort($offsets);
  991. $timezone_list = [];
  992. foreach ($offsets as $timezone => $offset) {
  993. $offset_prefix = $offset < 0 ? '-' : '+';
  994. $offset_formatted = gmdate('H:i', abs($offset));
  995. $pretty_offset = "UTC{$offset_prefix}{$offset_formatted}";
  996. $timezone_list[$timezone] = "({$pretty_offset}) " . str_replace('_', ' ', $timezone);
  997. }
  998. return $timezone_list;
  999. }
  1000. /**
  1001. * Recursively filter an array, filtering values by processing them through the $fn function argument
  1002. *
  1003. * @param array $source the Array to filter
  1004. * @param callable $fn the function to pass through each array item
  1005. * @return array
  1006. */
  1007. public static function arrayFilterRecursive(array $source, $fn)
  1008. {
  1009. $result = [];
  1010. foreach ($source as $key => $value) {
  1011. if (is_array($value)) {
  1012. $result[$key] = static::arrayFilterRecursive($value, $fn);
  1013. continue;
  1014. }
  1015. if ($fn($key, $value)) {
  1016. $result[$key] = $value; // KEEP
  1017. continue;
  1018. }
  1019. }
  1020. return $result;
  1021. }
  1022. /**
  1023. * Flatten a multi-dimensional associative array into query params.
  1024. *
  1025. * @param array $array
  1026. * @param string $prepend
  1027. * @return array
  1028. */
  1029. public static function arrayToQueryParams($array, $prepend = '')
  1030. {
  1031. $results = [];
  1032. foreach ($array as $key => $value) {
  1033. $name = $prepend ? $prepend . '[' . $key . ']' : $key;
  1034. if (is_array($value)) {
  1035. $results = array_merge($results, static::arrayToQueryParams($value, $name));
  1036. } else {
  1037. $results[$name] = $value;
  1038. }
  1039. }
  1040. return $results;
  1041. }
  1042. /**
  1043. * Flatten an array
  1044. *
  1045. * @param array $array
  1046. * @return array
  1047. */
  1048. public static function arrayFlatten($array)
  1049. {
  1050. $flatten = [];
  1051. foreach ($array as $key => $inner) {
  1052. if (is_array($inner)) {
  1053. foreach ($inner as $inner_key => $value) {
  1054. $flatten[$inner_key] = $value;
  1055. }
  1056. } else {
  1057. $flatten[$key] = $inner;
  1058. }
  1059. }
  1060. return $flatten;
  1061. }
  1062. /**
  1063. * Flatten a multi-dimensional associative array into dot notation
  1064. *
  1065. * @param array $array
  1066. * @param string $prepend
  1067. * @return array
  1068. */
  1069. public static function arrayFlattenDotNotation($array, $prepend = '')
  1070. {
  1071. $results = array();
  1072. foreach ($array as $key => $value) {
  1073. if (is_array($value)) {
  1074. $results = array_merge($results, static::arrayFlattenDotNotation($value, $prepend . $key . '.'));
  1075. } else {
  1076. $results[$prepend . $key] = $value;
  1077. }
  1078. }
  1079. return $results;
  1080. }
  1081. /**
  1082. * Opposite of flatten, convert flat dot notation array to multi dimensional array.
  1083. *
  1084. * If any of the parent has a scalar value, all children get ignored:
  1085. *
  1086. * admin.pages=true
  1087. * admin.pages.read=true
  1088. *
  1089. * becomes
  1090. *
  1091. * admin:
  1092. * pages: true
  1093. *
  1094. * @param array $array
  1095. * @param string $separator
  1096. * @return array
  1097. */
  1098. public static function arrayUnflattenDotNotation($array, $separator = '.')
  1099. {
  1100. $newArray = [];
  1101. foreach ($array as $key => $value) {
  1102. $dots = explode($separator, $key);
  1103. if (count($dots) > 1) {
  1104. $last = &$newArray[$dots[0]];
  1105. foreach ($dots as $k => $dot) {
  1106. if ($k === 0) {
  1107. continue;
  1108. }
  1109. // Cannot use a scalar value as an array
  1110. if (null !== $last && !is_array($last)) {
  1111. continue 2;
  1112. }
  1113. $last = &$last[$dot];
  1114. }
  1115. // Cannot use a scalar value as an array
  1116. if (null !== $last && !is_array($last)) {
  1117. continue;
  1118. }
  1119. $last = $value;
  1120. } else {
  1121. $newArray[$key] = $value;
  1122. }
  1123. }
  1124. return $newArray;
  1125. }
  1126. /**
  1127. * Checks if the passed path contains the language code prefix
  1128. *
  1129. * @param string $string The path
  1130. *
  1131. * @return bool|string Either false or the language
  1132. *
  1133. */
  1134. public static function pathPrefixedByLangCode($string)
  1135. {
  1136. $languages_enabled = Grav::instance()['config']->get('system.languages.supported', []);
  1137. $parts = explode('/', trim($string, '/'));
  1138. if (count($parts) > 0 && in_array($parts[0], $languages_enabled)) {
  1139. return $parts[0];
  1140. }
  1141. return false;
  1142. }
  1143. /**
  1144. * Get the timestamp of a date
  1145. *
  1146. * @param string $date a String expressed in the system.pages.dateformat.default format, with fallback to a
  1147. * strtotime argument
  1148. * @param string|null $format a date format to use if possible
  1149. * @return int the timestamp
  1150. */
  1151. public static function date2timestamp($date, $format = null)
  1152. {
  1153. $config = Grav::instance()['config'];
  1154. $dateformat = $format ?: $config->get('system.pages.dateformat.default');
  1155. // try to use DateTime and default format
  1156. if ($dateformat) {
  1157. $datetime = DateTime::createFromFormat($dateformat, $date);
  1158. } else {
  1159. $datetime = new DateTime($date);
  1160. }
  1161. // fallback to strtotime() if DateTime approach failed
  1162. if ($datetime !== false) {
  1163. return $datetime->getTimestamp();
  1164. }
  1165. return strtotime($date);
  1166. }
  1167. /**
  1168. * @param array $array
  1169. * @param string $path
  1170. * @param null $default
  1171. * @return mixed
  1172. *
  1173. * @deprecated 1.5 Use ->getDotNotation() method instead.
  1174. */
  1175. public static function resolve(array $array, $path, $default = null)
  1176. {
  1177. user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.5, use ->getDotNotation() method instead', E_USER_DEPRECATED);
  1178. return static::getDotNotation($array, $path, $default);
  1179. }
  1180. /**
  1181. * Checks if a value is positive (true)
  1182. *
  1183. * @param string $value
  1184. * @return bool
  1185. */
  1186. public static function isPositive($value)
  1187. {
  1188. return in_array($value, [true, 1, '1', 'yes', 'on', 'true'], true);
  1189. }
  1190. /**
  1191. * Checks if a value is negative (false)
  1192. *
  1193. * @param string $value
  1194. * @return bool
  1195. */
  1196. public static function isNegative($value)
  1197. {
  1198. return in_array($value, [false, 0, '0', 'no', 'off', 'false'], true);
  1199. }
  1200. /**
  1201. * Generates a nonce string to be hashed. Called by self::getNonce()
  1202. * We removed the IP portion in this version because it causes too many inconsistencies
  1203. * with reverse proxy setups.
  1204. *
  1205. * @param string $action
  1206. * @param bool $previousTick if true, generates the token for the previous tick (the previous 12 hours)
  1207. * @return string the nonce string
  1208. */
  1209. private static function generateNonceString($action, $previousTick = false)
  1210. {
  1211. $grav = Grav::instance();
  1212. $username = isset($grav['user']) ? $grav['user']->username : '';
  1213. $token = session_id();
  1214. $i = self::nonceTick();
  1215. if ($previousTick) {
  1216. $i--;
  1217. }
  1218. return ($i . '|' . $action . '|' . $username . '|' . $token . '|' . $grav['config']->get('security.salt'));
  1219. }
  1220. /**
  1221. * Get the time-dependent variable for nonce creation.
  1222. *
  1223. * Now a tick lasts a day. Once the day is passed, the nonce is not valid any more. Find a better way
  1224. * to ensure nonces issued near the end of the day do not expire in that small amount of time
  1225. *
  1226. * @return int the time part of the nonce. Changes once every 24 hours
  1227. */
  1228. private static function nonceTick()
  1229. {
  1230. $secondsInHalfADay = 60 * 60 * 12;
  1231. return (int)ceil(time() / $secondsInHalfADay);
  1232. }
  1233. /**
  1234. * Creates a hashed nonce tied to the passed action. Tied to the current user and time. The nonce for a given
  1235. * action is the same for 12 hours.
  1236. *
  1237. * @param string $action the action the nonce is tied to (e.g. save-user-admin or move-page-homepage)
  1238. * @param bool $previousTick if true, generates the token for the previous tick (the previous 12 hours)
  1239. * @return string the nonce
  1240. */
  1241. public static function getNonce($action, $previousTick = false)
  1242. {
  1243. // Don't regenerate this again if not needed
  1244. if (isset(static::$nonces[$action][$previousTick])) {
  1245. return static::$nonces[$action][$previousTick];
  1246. }
  1247. $nonce = md5(self::generateNonceString($action, $previousTick));
  1248. static::$nonces[$action][$previousTick] = $nonce;
  1249. return static::$nonces[$action][$previousTick];
  1250. }
  1251. /**
  1252. * Verify the passed nonce for the give action
  1253. *
  1254. * @param string|string[] $nonce the nonce to verify
  1255. * @param string $action the action to verify the nonce to
  1256. * @return boolean verified or not
  1257. */
  1258. public static function verifyNonce($nonce, $action)
  1259. {
  1260. //Safety check for multiple nonces
  1261. if (is_array($nonce)) {
  1262. $nonce = array_shift($nonce);
  1263. }
  1264. //Nonce generated 0-12 hours ago
  1265. if ($nonce === self::getNonce($action)) {
  1266. return true;
  1267. }
  1268. //Nonce generated 12-24 hours ago
  1269. return $nonce === self::getNonce($action, true);
  1270. }
  1271. /**
  1272. * Simple helper method to get whether or not the admin plugin is active
  1273. *
  1274. * @return bool
  1275. */
  1276. public static function isAdminPlugin()
  1277. {
  1278. return isset(Grav::instance()['admin']);
  1279. }
  1280. /**
  1281. * Get a portion of an array (passed by reference) with dot-notation key
  1282. *
  1283. * @param array $array
  1284. * @param string|int|null $key
  1285. * @param null $default
  1286. * @return mixed
  1287. */
  1288. public static function getDotNotation($array, $key, $default = null)
  1289. {
  1290. if (null === $key) {
  1291. return $array;
  1292. }
  1293. if (isset($array[$key])) {
  1294. return $array[$key];
  1295. }
  1296. foreach (explode('.', $key) as $segment) {
  1297. if (!is_array($array) || !array_key_exists($segment, $array)) {
  1298. return $default;
  1299. }
  1300. $array = $array[$segment];
  1301. }
  1302. return $array;
  1303. }
  1304. /**
  1305. * Set portion of array (passed by reference) for a dot-notation key
  1306. * and set the value
  1307. *
  1308. * @param array $array
  1309. * @param string|int|null $key
  1310. * @param mixed $value
  1311. * @param bool $merge
  1312. *
  1313. * @return mixed
  1314. */
  1315. public static function setDotNotation(&$array, $key, $value, $merge = false)
  1316. {
  1317. if (null === $key) {
  1318. return $array = $value;
  1319. }
  1320. $keys = explode('.', $key);
  1321. while (count($keys) > 1) {
  1322. $key = array_shift($keys);
  1323. if (!isset($array[$key]) || !is_array($array[$key])) {
  1324. $array[$key] = array();
  1325. }
  1326. $array =& $array[$key];
  1327. }
  1328. $key = array_shift($keys);
  1329. if (!$merge || !isset($array[$key])) {
  1330. $array[$key] = $value;
  1331. } else {
  1332. $array[$key] = array_merge($array[$key], $value);
  1333. }
  1334. return $array;
  1335. }
  1336. /**
  1337. * Utility method to determine if the current OS is Windows
  1338. *
  1339. * @return bool
  1340. */
  1341. public static function isWindows()
  1342. {
  1343. return strncasecmp(PHP_OS, 'WIN', 3) === 0;
  1344. }
  1345. /**
  1346. * Utility to determine if the server running PHP is Apache
  1347. *
  1348. * @return bool
  1349. */
  1350. public static function isApache()
  1351. {
  1352. return isset($_SERVER['SERVER_SOFTWARE']) && strpos($_SERVER['SERVER_SOFTWARE'], 'Apache') !== false;
  1353. }
  1354. /**
  1355. * Sort a multidimensional array by another array of ordered keys
  1356. *
  1357. * @param array $array
  1358. * @param array $orderArray
  1359. * @return array
  1360. */
  1361. public static function sortArrayByArray(array $array, array $orderArray)
  1362. {
  1363. $ordered = [];
  1364. foreach ($orderArray as $key) {
  1365. if (array_key_exists($key, $array)) {
  1366. $ordered[$key] = $array[$key];
  1367. unset($array[$key]);
  1368. }
  1369. }
  1370. return $ordered + $array;
  1371. }
  1372. /**
  1373. * Sort an array by a key value in the array
  1374. *
  1375. * @param mixed $array
  1376. * @param string|int $array_key
  1377. * @param int $direction
  1378. * @param int $sort_flags
  1379. * @return array
  1380. */
  1381. public static function sortArrayByKey($array, $array_key, $direction = SORT_DESC, $sort_flags = SORT_REGULAR)
  1382. {
  1383. $output = [];
  1384. if (!is_array($array) || !$array) {
  1385. return $output;
  1386. }
  1387. foreach ($array as $key => $row) {
  1388. $output[$key] = $row[$array_key];
  1389. }
  1390. array_multisort($output, $direction, $sort_flags, $array);
  1391. return $array;
  1392. }
  1393. /**
  1394. * Get relative page path based on a token.
  1395. *
  1396. * @param string $path
  1397. * @param PageInterface|null $page
  1398. * @return string
  1399. * @throws RuntimeException
  1400. */
  1401. public static function getPagePathFromToken($path, PageInterface $page = null)
  1402. {
  1403. return static::getPathFromToken($path, $page);
  1404. }
  1405. /**
  1406. * Get relative path based on a token.
  1407. *
  1408. * Path supports following syntaxes:
  1409. *
  1410. * 'self@', 'self@/path'
  1411. * 'page@:/route', 'page@:/route/filename.ext'
  1412. * 'theme@:', 'theme@:/path'
  1413. *
  1414. * @param string $path
  1415. * @param FlexObjectInterface|PageInterface|null $object
  1416. * @return string
  1417. * @throws RuntimeException
  1418. */
  1419. public static function getPathFromToken($path, $object = null)
  1420. {
  1421. $matches = static::resolveTokenPath($path);
  1422. if (null === $matches) {
  1423. return $path;
  1424. }
  1425. $grav = Grav::instance();
  1426. switch ($matches[0]) {
  1427. case 'self':
  1428. if (!$object instanceof MediaInterface) {
  1429. throw new RuntimeException(sprintf('Page not available for self@ reference: %s', $path));
  1430. }
  1431. if ($matches[2] === '') {
  1432. if ($object->exists()) {
  1433. $route = '/' . $matches[1];
  1434. if ($object instanceof PageInterface) {
  1435. return trim($object->relativePagePath() . $route, '/');
  1436. }
  1437. $folder = $object->getMediaFolder();
  1438. if ($folder) {
  1439. return trim($folder . $route, '/');
  1440. }
  1441. } else {
  1442. return '';
  1443. }
  1444. }
  1445. break;
  1446. case 'page':
  1447. if ($matches[1] === '') {
  1448. $route = '/' . $matches[2];
  1449. // Exclude filename from the page lookup.
  1450. if (static::pathinfo($route, PATHINFO_EXTENSION)) {
  1451. $basename = '/' . static::basename($route);
  1452. $route = \dirname($route);
  1453. } else {
  1454. $basename = '';
  1455. }
  1456. $key = trim($route === '/' ? $grav['config']->get('system.home.alias') : $route, '/');
  1457. if ($object instanceof PageObject) {
  1458. $object = $object->getFlexDirectory()->getObject($key);
  1459. } elseif (static::isAdminPlugin()) {
  1460. /** @var Flex|null $flex */
  1461. $flex = $grav['flex'] ?? null;
  1462. $object = $flex ? $flex->getObject($key, 'pages') : null;
  1463. } else {
  1464. /** @var Pages $pages */
  1465. $pages = $grav['pages'];
  1466. $object = $pages->find($route);
  1467. }
  1468. if ($object instanceof PageInterface) {
  1469. return trim($object->relativePagePath() . $basename, '/');
  1470. }
  1471. }
  1472. break;
  1473. case 'theme':
  1474. if ($matches[1] === '') {
  1475. $route = '/' . $matches[2];
  1476. $theme = $grav['locator']->findResource('theme://', false);
  1477. if (false !== $theme) {
  1478. return trim($theme . $route, '/');
  1479. }
  1480. }
  1481. break;
  1482. }
  1483. throw new RuntimeException(sprintf('Token path not found: %s', $path));
  1484. }
  1485. /**
  1486. * Returns [token, route, path] from '@token/route:/path'. Route and path are optional. If pattern does not match, return null.
  1487. *
  1488. * @param string $path
  1489. * @return string[]|null
  1490. */
  1491. protected static function resolveTokenPath(string $path): ?array
  1492. {
  1493. if (strpos($path, '@') !== false) {
  1494. $regex = '/^(@\w+|\w+@|@\w+@)([^:]*)(.*)$/u';
  1495. if (preg_match($regex, $path, $matches)) {
  1496. return [
  1497. trim($matches[1], '@'),
  1498. trim($matches[2], '/'),
  1499. trim($matches[3], ':/')
  1500. ];
  1501. }
  1502. }
  1503. return null;
  1504. }
  1505. /**
  1506. * @return int
  1507. */
  1508. public static function getUploadLimit()
  1509. {
  1510. static $max_size = -1;
  1511. if ($max_size < 0) {
  1512. $post_max_size = static::parseSize(ini_get('post_max_size'));
  1513. if ($post_max_size > 0) {
  1514. $max_size = $post_max_size;
  1515. } else {
  1516. $max_size = 0;
  1517. }
  1518. $upload_max = static::parseSize(ini_get('upload_max_filesize'));
  1519. if ($upload_max > 0 && $upload_max < $max_size) {
  1520. $max_size = $upload_max;
  1521. }
  1522. }
  1523. return $max_size;
  1524. }
  1525. /**
  1526. * Convert bytes to the unit specified by the $to parameter.
  1527. *
  1528. * @param int $bytes The filesize in Bytes.
  1529. * @param string $to The unit type to convert to. Accepts K, M, or G for Kilobytes, Megabytes, or Gigabytes, respectively.
  1530. * @param int $decimal_places The number of decimal places to return.
  1531. * @return int Returns only the number of units, not the type letter. Returns 0 if the $to unit type is out of scope.
  1532. *
  1533. */
  1534. public static function convertSize($bytes, $to, $decimal_places = 1)
  1535. {
  1536. $formulas = array(
  1537. 'K' => number_format($bytes / 1024, $decimal_places),
  1538. 'M' => number_format($bytes / 1048576, $decimal_places),
  1539. 'G' => number_format($bytes / 1073741824, $decimal_places)
  1540. );
  1541. return $formulas[$to] ?? 0;
  1542. }
  1543. /**
  1544. * Return a pretty size based on bytes
  1545. *
  1546. * @param int $bytes
  1547. * @param int $precision
  1548. * @return string
  1549. */
  1550. public static function prettySize($bytes, $precision = 2)
  1551. {
  1552. $units = array('B', 'KB', 'MB', 'GB', 'TB');
  1553. $bytes = max($bytes, 0);
  1554. $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
  1555. $pow = min($pow, count($units) - 1);
  1556. // Uncomment one of the following alternatives
  1557. $bytes /= 1024 ** $pow;
  1558. // $bytes /= (1 << (10 * $pow));
  1559. return round($bytes, $precision) . ' ' . $units[$pow];
  1560. }
  1561. /**
  1562. * Parse a readable file size and return a value in bytes
  1563. *
  1564. * @param string|int|float $size
  1565. * @return int
  1566. */
  1567. public static function parseSize($size)
  1568. {
  1569. $unit = preg_replace('/[^bkmgtpezy]/i', '', $size);
  1570. $size = (float)preg_replace('/[^0-9\.]/', '', $size);
  1571. if ($unit) {
  1572. $size *= 1024 ** stripos('bkmgtpezy', $unit[0]);
  1573. }
  1574. return (int)abs(round($size));
  1575. }
  1576. /**
  1577. * Multibyte-safe Parse URL function
  1578. *
  1579. * @param string $url
  1580. * @return array
  1581. * @throws InvalidArgumentException
  1582. */
  1583. public static function multibyteParseUrl($url)
  1584. {
  1585. $enc_url = preg_replace_callback(
  1586. '%[^:/@?&=#]+%usD',
  1587. static function ($matches) {
  1588. return urlencode($matches[0]);
  1589. },
  1590. $url
  1591. );
  1592. $parts = parse_url($enc_url);
  1593. if ($parts === false) {
  1594. throw new InvalidArgumentException('Malformed URL: ' . $url);
  1595. }
  1596. foreach ($parts as $name => $value) {
  1597. $parts[$name] = urldecode($value);
  1598. }
  1599. return $parts;
  1600. }
  1601. /**
  1602. * Process a string as markdown
  1603. *
  1604. * @param string $string
  1605. * @param bool $block Block or Line processing
  1606. * @param PageInterface|null $page
  1607. * @return string
  1608. * @throws Exception
  1609. */
  1610. public static function processMarkdown($string, $block = true, $page = null)
  1611. {
  1612. $grav = Grav::instance();
  1613. $page = $page ?? $grav['page'] ?? null;
  1614. $defaults = [
  1615. 'markdown' => $grav['config']->get('system.pages.markdown', []),
  1616. 'images' => $grav['config']->get('system.images', [])
  1617. ];
  1618. $extra = $defaults['markdown']['extra'] ?? false;
  1619. $excerpts = new Excerpts($page, $defaults);
  1620. // Initialize the preferred variant of Parsedown
  1621. if ($extra) {
  1622. $parsedown = new ParsedownExtra($excerpts);
  1623. } else {
  1624. $parsedown = new Parsedown($excerpts);
  1625. }
  1626. if ($block) {
  1627. $string = $parsedown->text((string) $string);
  1628. } else {
  1629. $string = $parsedown->line((string) $string);
  1630. }
  1631. return $string;
  1632. }
  1633. /**
  1634. * Find the subnet of an ip with CIDR prefix size
  1635. *
  1636. * @param string $ip
  1637. * @param int $prefix
  1638. * @return string
  1639. */
  1640. public static function getSubnet($ip, $prefix = 64)
  1641. {
  1642. if (!filter_var($ip, FILTER_VALIDATE_IP)) {
  1643. return $ip;
  1644. }
  1645. // Packed representation of IP
  1646. $ip = (string)inet_pton($ip);
  1647. // Maximum netmask length = same as packed address
  1648. $len = 8 * strlen($ip);
  1649. if ($prefix > $len) {
  1650. $prefix = $len;
  1651. }
  1652. $mask = str_repeat('f', $prefix >> 2);
  1653. switch ($prefix & 3) {
  1654. case 3:
  1655. $mask .= 'e';
  1656. break;
  1657. case 2:
  1658. $mask .= 'c';
  1659. break;
  1660. case 1:
  1661. $mask .= '8';
  1662. break;
  1663. }
  1664. $mask = str_pad($mask, $len >> 2, '0');
  1665. // Packed representation of netmask
  1666. $mask = pack('H*', $mask);
  1667. // Bitwise - Take all bits that are both 1 to generate subnet
  1668. $subnet = inet_ntop($ip & $mask);
  1669. return $subnet;
  1670. }
  1671. /**
  1672. * Wrapper to ensure html, htm in the front of the supported page types
  1673. *
  1674. * @param array|null $defaults
  1675. * @return array
  1676. */
  1677. public static function getSupportPageTypes(array $defaults = null)
  1678. {
  1679. $types = Grav::instance()['config']->get('system.pages.types', $defaults);
  1680. if (!is_array($types)) {
  1681. return [];
  1682. }
  1683. // remove html/htm
  1684. $types = static::arrayRemoveValue($types, ['html', 'htm']);
  1685. // put them back at the front
  1686. $types = array_merge(['html', 'htm'], $types);
  1687. return $types;
  1688. }
  1689. /**
  1690. * @param string|array|Closure $name
  1691. * @return bool
  1692. */
  1693. public static function isDangerousFunction($name): bool
  1694. {
  1695. static $commandExecutionFunctions = [
  1696. 'exec',
  1697. 'passthru',
  1698. 'system',
  1699. 'shell_exec',
  1700. 'popen',
  1701. 'proc_open',
  1702. 'pcntl_exec',
  1703. ];
  1704. static $codeExecutionFunctions = [
  1705. 'assert',
  1706. 'preg_replace',
  1707. 'create_function',
  1708. 'include',
  1709. 'include_once',
  1710. 'require',
  1711. 'require_once'
  1712. ];
  1713. static $callbackFunctions = [
  1714. 'ob_start' => 0,
  1715. 'array_diff_uassoc' => -1,
  1716. 'array_diff_ukey' => -1,
  1717. 'array_filter' => 1,
  1718. 'array_intersect_uassoc' => -1,
  1719. 'array_intersect_ukey' => -1,
  1720. 'array_map' => 0,
  1721. 'array_reduce' => 1,
  1722. 'array_udiff_assoc' => -1,
  1723. 'array_udiff_uassoc' => [-1, -2],
  1724. 'array_udiff' => -1,
  1725. 'array_uintersect_assoc' => -1,
  1726. 'array_uintersect_uassoc' => [-1, -2],
  1727. 'array_uintersect' => -1,
  1728. 'array_walk_recursive' => 1,
  1729. 'array_walk' => 1,
  1730. 'assert_options' => 1,
  1731. 'uasort' => 1,
  1732. 'uksort' => 1,
  1733. 'usort' => 1,
  1734. 'preg_replace_callback' => 1,
  1735. 'spl_autoload_register' => 0,
  1736. 'iterator_apply' => 1,
  1737. 'call_user_func' => 0,
  1738. 'call_user_func_array' => 0,
  1739. 'register_shutdown_function' => 0,
  1740. 'register_tick_function' => 0,
  1741. 'set_error_handler' => 0,
  1742. 'set_exception_handler' => 0,
  1743. 'session_set_save_handler' => [0, 1, 2, 3, 4, 5],
  1744. 'sqlite_create_aggregate' => [2, 3],
  1745. 'sqlite_create_function' => 2,
  1746. ];
  1747. static $informationDiscosureFunctions = [
  1748. 'phpinfo',
  1749. 'posix_mkfifo',
  1750. 'posix_getlogin',
  1751. 'posix_ttyname',
  1752. 'getenv',
  1753. 'get_current_user',
  1754. 'proc_get_status',
  1755. 'get_cfg_var',
  1756. 'disk_free_space',
  1757. 'disk_total_space',
  1758. 'diskfreespace',
  1759. 'getcwd',
  1760. 'getlastmo',
  1761. 'getmygid',
  1762. 'getmyinode',
  1763. 'getmypid',
  1764. 'getmyuid'
  1765. ];
  1766. static $otherFunctions = [
  1767. 'extract',
  1768. 'parse_str',
  1769. 'putenv',
  1770. 'ini_set',
  1771. 'mail',
  1772. 'header',
  1773. 'proc_nice',
  1774. 'proc_terminate',
  1775. 'proc_close',
  1776. 'pfsockopen',
  1777. 'fsockopen',
  1778. 'apache_child_terminate',
  1779. 'posix_kill',
  1780. 'posix_mkfifo',
  1781. 'posix_setpgid',
  1782. 'posix_setsid',
  1783. 'posix_setuid',
  1784. 'unserialize',
  1785. 'ini_alter',
  1786. 'simplexml_load_file',
  1787. 'simplexml_load_string',
  1788. 'forward_static_call',
  1789. 'forward_static_call_array',
  1790. ];
  1791. if (is_string($name)) {
  1792. $name = strtolower($name);
  1793. }
  1794. if ($name instanceof \Closure) {
  1795. return false;
  1796. }
  1797. if (is_array($name) || strpos($name, ":") !== false) {
  1798. return true;
  1799. }
  1800. if (strpos($name, "\\") !== false) {
  1801. return true;
  1802. }
  1803. if (in_array($name, $commandExecutionFunctions)) {
  1804. return true;
  1805. }
  1806. if (in_array($name, $codeExecutionFunctions)) {
  1807. return true;
  1808. }
  1809. if (isset($callbackFunctions[$name])) {
  1810. return true;
  1811. }
  1812. if (in_array($name, $informationDiscosureFunctions)) {
  1813. return true;
  1814. }
  1815. if (in_array($name, $otherFunctions)) {
  1816. return true;
  1817. }
  1818. return static::isFilesystemFunction($name);
  1819. }
  1820. /**
  1821. * @param string $name
  1822. * @return bool
  1823. */
  1824. public static function isFilesystemFunction(string $name): bool
  1825. {
  1826. static $fileWriteFunctions = [
  1827. 'fopen',
  1828. 'tmpfile',
  1829. 'bzopen',
  1830. 'gzopen',
  1831. // write to filesystem (partially in combination with reading)
  1832. 'chgrp',
  1833. 'chmod',
  1834. 'chown',
  1835. 'copy',
  1836. 'file_put_contents',
  1837. 'lchgrp',
  1838. 'lchown',
  1839. 'link',
  1840. 'mkdir',
  1841. 'move_uploaded_file',
  1842. 'rename',
  1843. 'rmdir',
  1844. 'symlink',
  1845. 'tempnam',
  1846. 'touch',
  1847. 'unlink',
  1848. 'imagepng',
  1849. 'imagewbmp',
  1850. 'image2wbmp',
  1851. 'imagejpeg',
  1852. 'imagexbm',
  1853. 'imagegif',
  1854. 'imagegd',
  1855. 'imagegd2',
  1856. 'iptcembed',
  1857. 'ftp_get',
  1858. 'ftp_nb_get',
  1859. ];
  1860. static $fileContentFunctions = [
  1861. 'file_get_contents',
  1862. 'file',
  1863. 'filegroup',
  1864. 'fileinode',
  1865. 'fileowner',
  1866. 'fileperms',
  1867. 'glob',
  1868. 'is_executable',
  1869. 'is_uploaded_file',
  1870. 'parse_ini_file',
  1871. 'readfile',
  1872. 'readlink',
  1873. 'realpath',
  1874. 'gzfile',
  1875. 'readgzfile',
  1876. 'stat',
  1877. 'imagecreatefromgif',
  1878. 'imagecreatefromjpeg',
  1879. 'imagecreatefrompng',
  1880. 'imagecreatefromwbmp',
  1881. 'imagecreatefromxbm',
  1882. 'imagecreatefromxpm',
  1883. 'ftp_put',
  1884. 'ftp_nb_put',
  1885. 'hash_update_file',
  1886. 'highlight_file',
  1887. 'show_source',
  1888. 'php_strip_whitespace',
  1889. ];
  1890. static $filesystemFunctions = [
  1891. // read from filesystem
  1892. 'file_exists',
  1893. 'fileatime',
  1894. 'filectime',
  1895. 'filemtime',
  1896. 'filesize',
  1897. 'filetype',
  1898. 'is_dir',
  1899. 'is_file',
  1900. 'is_link',
  1901. 'is_readable',
  1902. 'is_writable',
  1903. 'is_writeable',
  1904. 'linkinfo',
  1905. 'lstat',
  1906. //'pathinfo',
  1907. 'getimagesize',
  1908. 'exif_read_data',
  1909. 'read_exif_data',
  1910. 'exif_thumbnail',
  1911. 'exif_imagetype',
  1912. 'hash_file',
  1913. 'hash_hmac_file',
  1914. 'md5_file',
  1915. 'sha1_file',
  1916. 'get_meta_tags',
  1917. ];
  1918. if (in_array($name, $fileWriteFunctions)) {
  1919. return true;
  1920. }
  1921. if (in_array($name, $fileContentFunctions)) {
  1922. return true;
  1923. }
  1924. if (in_array($name, $filesystemFunctions)) {
  1925. return true;
  1926. }
  1927. return false;
  1928. }
  1929. }