GravExtension.php 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700
  1. <?php
  2. /**
  3. * @package Grav\Common\Twig
  4. *
  5. * @copyright Copyright (c) 2015 - 2022 Trilby Media, LLC. All rights reserved.
  6. * @license MIT License; see LICENSE file for details.
  7. */
  8. namespace Grav\Common\Twig\Extension;
  9. use CallbackFilterIterator;
  10. use Cron\CronExpression;
  11. use Grav\Common\Config\Config;
  12. use Grav\Common\Data\Data;
  13. use Grav\Common\Debugger;
  14. use Grav\Common\Grav;
  15. use Grav\Common\Inflector;
  16. use Grav\Common\Language\Language;
  17. use Grav\Common\Page\Collection;
  18. use Grav\Common\Page\Interfaces\PageInterface;
  19. use Grav\Common\Page\Media;
  20. use Grav\Common\Scheduler\Cron;
  21. use Grav\Common\Security;
  22. use Grav\Common\Twig\TokenParser\TwigTokenParserCache;
  23. use Grav\Common\Twig\TokenParser\TwigTokenParserLink;
  24. use Grav\Common\Twig\TokenParser\TwigTokenParserRender;
  25. use Grav\Common\Twig\TokenParser\TwigTokenParserScript;
  26. use Grav\Common\Twig\TokenParser\TwigTokenParserStyle;
  27. use Grav\Common\Twig\TokenParser\TwigTokenParserSwitch;
  28. use Grav\Common\Twig\TokenParser\TwigTokenParserThrow;
  29. use Grav\Common\Twig\TokenParser\TwigTokenParserTryCatch;
  30. use Grav\Common\Twig\TokenParser\TwigTokenParserMarkdown;
  31. use Grav\Common\User\Interfaces\UserInterface;
  32. use Grav\Common\Utils;
  33. use Grav\Common\Yaml;
  34. use Grav\Common\Helpers\Base32;
  35. use Grav\Framework\Flex\Interfaces\FlexObjectInterface;
  36. use Grav\Framework\Psr7\Response;
  37. use Iterator;
  38. use JsonSerializable;
  39. use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
  40. use Traversable;
  41. use Twig\Environment;
  42. use Twig\Error\RuntimeError;
  43. use Twig\Extension\AbstractExtension;
  44. use Twig\Extension\GlobalsInterface;
  45. use Twig\Loader\FilesystemLoader;
  46. use Twig\TwigFilter;
  47. use Twig\TwigFunction;
  48. use function array_slice;
  49. use function count;
  50. use function func_get_args;
  51. use function func_num_args;
  52. use function get_class;
  53. use function gettype;
  54. use function in_array;
  55. use function is_array;
  56. use function is_bool;
  57. use function is_float;
  58. use function is_int;
  59. use function is_numeric;
  60. use function is_object;
  61. use function is_scalar;
  62. use function is_string;
  63. use function strlen;
  64. /**
  65. * Class GravExtension
  66. * @package Grav\Common\Twig\Extension
  67. */
  68. class GravExtension extends AbstractExtension implements GlobalsInterface
  69. {
  70. /** @var Grav */
  71. protected $grav;
  72. /** @var Debugger|null */
  73. protected $debugger;
  74. /** @var Config */
  75. protected $config;
  76. /**
  77. * GravExtension constructor.
  78. */
  79. public function __construct()
  80. {
  81. $this->grav = Grav::instance();
  82. $this->debugger = $this->grav['debugger'] ?? null;
  83. $this->config = $this->grav['config'];
  84. }
  85. /**
  86. * Register some standard globals
  87. *
  88. * @return array
  89. */
  90. public function getGlobals(): array
  91. {
  92. return [
  93. 'grav' => $this->grav,
  94. ];
  95. }
  96. /**
  97. * Return a list of all filters.
  98. *
  99. * @return array
  100. */
  101. public function getFilters(): array
  102. {
  103. return [
  104. new TwigFilter('*ize', [$this, 'inflectorFilter']),
  105. new TwigFilter('absolute_url', [$this, 'absoluteUrlFilter']),
  106. new TwigFilter('contains', [$this, 'containsFilter']),
  107. new TwigFilter('chunk_split', [$this, 'chunkSplitFilter']),
  108. new TwigFilter('nicenumber', [$this, 'niceNumberFunc']),
  109. new TwigFilter('nicefilesize', [$this, 'niceFilesizeFunc']),
  110. new TwigFilter('nicetime', [$this, 'nicetimeFunc']),
  111. new TwigFilter('defined', [$this, 'definedDefaultFilter']),
  112. new TwigFilter('ends_with', [$this, 'endsWithFilter']),
  113. new TwigFilter('fieldName', [$this, 'fieldNameFilter']),
  114. new TwigFilter('parent_field', [$this, 'fieldParentFilter']),
  115. new TwigFilter('ksort', [$this, 'ksortFilter']),
  116. new TwigFilter('ltrim', [$this, 'ltrimFilter']),
  117. new TwigFilter('markdown', [$this, 'markdownFunction'], ['needs_context' => true, 'is_safe' => ['html']]),
  118. new TwigFilter('md5', [$this, 'md5Filter']),
  119. new TwigFilter('base32_encode', [$this, 'base32EncodeFilter']),
  120. new TwigFilter('base32_decode', [$this, 'base32DecodeFilter']),
  121. new TwigFilter('base64_encode', [$this, 'base64EncodeFilter']),
  122. new TwigFilter('base64_decode', [$this, 'base64DecodeFilter']),
  123. new TwigFilter('randomize', [$this, 'randomizeFilter']),
  124. new TwigFilter('modulus', [$this, 'modulusFilter']),
  125. new TwigFilter('rtrim', [$this, 'rtrimFilter']),
  126. new TwigFilter('pad', [$this, 'padFilter']),
  127. new TwigFilter('regex_replace', [$this, 'regexReplace']),
  128. new TwigFilter('safe_email', [$this, 'safeEmailFilter'], ['is_safe' => ['html']]),
  129. new TwigFilter('safe_truncate', [Utils::class, 'safeTruncate']),
  130. new TwigFilter('safe_truncate_html', [Utils::class, 'safeTruncateHTML']),
  131. new TwigFilter('sort_by_key', [$this, 'sortByKeyFilter']),
  132. new TwigFilter('starts_with', [$this, 'startsWithFilter']),
  133. new TwigFilter('truncate', [Utils::class, 'truncate']),
  134. new TwigFilter('truncate_html', [Utils::class, 'truncateHTML']),
  135. new TwigFilter('json_decode', [$this, 'jsonDecodeFilter']),
  136. new TwigFilter('array_unique', 'array_unique'),
  137. new TwigFilter('basename', 'basename'),
  138. new TwigFilter('dirname', 'dirname'),
  139. new TwigFilter('print_r', [$this, 'print_r']),
  140. new TwigFilter('yaml_encode', [$this, 'yamlEncodeFilter']),
  141. new TwigFilter('yaml_decode', [$this, 'yamlDecodeFilter']),
  142. new TwigFilter('nicecron', [$this, 'niceCronFilter']),
  143. new TwigFilter('replace_last', [$this, 'replaceLastFilter']),
  144. // Translations
  145. new TwigFilter('t', [$this, 'translate'], ['needs_environment' => true]),
  146. new TwigFilter('tl', [$this, 'translateLanguage']),
  147. new TwigFilter('ta', [$this, 'translateArray']),
  148. // Casting values
  149. new TwigFilter('string', [$this, 'stringFilter']),
  150. new TwigFilter('int', [$this, 'intFilter'], ['is_safe' => ['all']]),
  151. new TwigFilter('bool', [$this, 'boolFilter']),
  152. new TwigFilter('float', [$this, 'floatFilter'], ['is_safe' => ['all']]),
  153. new TwigFilter('array', [$this, 'arrayFilter']),
  154. new TwigFilter('yaml', [$this, 'yamlFilter']),
  155. // Object Types
  156. new TwigFilter('get_type', [$this, 'getTypeFunc']),
  157. new TwigFilter('of_type', [$this, 'ofTypeFunc']),
  158. // PHP methods
  159. new TwigFilter('count', 'count'),
  160. new TwigFilter('array_diff', 'array_diff'),
  161. // Security fix
  162. new TwigFilter('filter', [$this, 'filterFilter'], ['needs_environment' => true]),
  163. ];
  164. }
  165. /**
  166. * Return a list of all functions.
  167. *
  168. * @return array
  169. */
  170. public function getFunctions(): array
  171. {
  172. return [
  173. new TwigFunction('array', [$this, 'arrayFilter']),
  174. new TwigFunction('array_key_value', [$this, 'arrayKeyValueFunc']),
  175. new TwigFunction('array_key_exists', 'array_key_exists'),
  176. new TwigFunction('array_unique', 'array_unique'),
  177. new TwigFunction('array_intersect', [$this, 'arrayIntersectFunc']),
  178. new TwigFunction('array_diff', 'array_diff'),
  179. new TwigFunction('authorize', [$this, 'authorize']),
  180. new TwigFunction('debug', [$this, 'dump'], ['needs_context' => true, 'needs_environment' => true]),
  181. new TwigFunction('dump', [$this, 'dump'], ['needs_context' => true, 'needs_environment' => true]),
  182. new TwigFunction('vardump', [$this, 'vardumpFunc']),
  183. new TwigFunction('print_r', [$this, 'print_r']),
  184. new TwigFunction('http_response_code', 'http_response_code'),
  185. new TwigFunction('evaluate', [$this, 'evaluateStringFunc'], ['needs_context' => true]),
  186. new TwigFunction('evaluate_twig', [$this, 'evaluateTwigFunc'], ['needs_context' => true]),
  187. new TwigFunction('gist', [$this, 'gistFunc']),
  188. new TwigFunction('nonce_field', [$this, 'nonceFieldFunc']),
  189. new TwigFunction('pathinfo', 'pathinfo'),
  190. new TwigFunction('parseurl', 'parse_url'),
  191. new TwigFunction('random_string', [$this, 'randomStringFunc']),
  192. new TwigFunction('repeat', [$this, 'repeatFunc']),
  193. new TwigFunction('regex_replace', [$this, 'regexReplace']),
  194. new TwigFunction('regex_filter', [$this, 'regexFilter']),
  195. new TwigFunction('regex_match', [$this, 'regexMatch']),
  196. new TwigFunction('regex_split', [$this, 'regexSplit']),
  197. new TwigFunction('string', [$this, 'stringFilter']),
  198. new TwigFunction('url', [$this, 'urlFunc']),
  199. new TwigFunction('json_decode', [$this, 'jsonDecodeFilter']),
  200. new TwigFunction('get_cookie', [$this, 'getCookie']),
  201. new TwigFunction('redirect_me', [$this, 'redirectFunc']),
  202. new TwigFunction('range', [$this, 'rangeFunc']),
  203. new TwigFunction('isajaxrequest', [$this, 'isAjaxFunc']),
  204. new TwigFunction('exif', [$this, 'exifFunc']),
  205. new TwigFunction('media_directory', [$this, 'mediaDirFunc']),
  206. new TwigFunction('body_class', [$this, 'bodyClassFunc'], ['needs_context' => true]),
  207. new TwigFunction('theme_var', [$this, 'themeVarFunc'], ['needs_context' => true]),
  208. new TwigFunction('header_var', [$this, 'pageHeaderVarFunc'], ['needs_context' => true]),
  209. new TwigFunction('read_file', [$this, 'readFileFunc']),
  210. new TwigFunction('nicenumber', [$this, 'niceNumberFunc']),
  211. new TwigFunction('nicefilesize', [$this, 'niceFilesizeFunc']),
  212. new TwigFunction('nicetime', [$this, 'nicetimeFunc']),
  213. new TwigFunction('cron', [$this, 'cronFunc']),
  214. new TwigFunction('svg_image', [$this, 'svgImageFunction']),
  215. new TwigFunction('xss', [$this, 'xssFunc']),
  216. new TwigFunction('unique_id', [$this, 'uniqueId']),
  217. // Translations
  218. new TwigFunction('t', [$this, 'translate'], ['needs_environment' => true]),
  219. new TwigFunction('tl', [$this, 'translateLanguage']),
  220. new TwigFunction('ta', [$this, 'translateArray']),
  221. // Object Types
  222. new TwigFunction('get_type', [$this, 'getTypeFunc']),
  223. new TwigFunction('of_type', [$this, 'ofTypeFunc']),
  224. // PHP methods
  225. new TwigFunction('is_numeric', 'is_numeric'),
  226. new TwigFunction('is_iterable', 'is_iterable'),
  227. new TwigFunction('is_countable', 'is_countable'),
  228. new TwigFunction('is_null', 'is_null'),
  229. new TwigFunction('is_string', 'is_string'),
  230. new TwigFunction('is_array', 'is_array'),
  231. new TwigFunction('is_object', 'is_object'),
  232. new TwigFunction('count', 'count'),
  233. new TwigFunction('array_diff', 'array_diff'),
  234. ];
  235. }
  236. /**
  237. * @return array
  238. */
  239. public function getTokenParsers(): array
  240. {
  241. return [
  242. new TwigTokenParserRender(),
  243. new TwigTokenParserThrow(),
  244. new TwigTokenParserTryCatch(),
  245. new TwigTokenParserScript(),
  246. new TwigTokenParserStyle(),
  247. new TwigTokenParserLink(),
  248. new TwigTokenParserMarkdown(),
  249. new TwigTokenParserSwitch(),
  250. new TwigTokenParserCache(),
  251. ];
  252. }
  253. /**
  254. * @param mixed $var
  255. * @return string
  256. */
  257. public function print_r($var)
  258. {
  259. return print_r($var, true);
  260. }
  261. /**
  262. * Filters field name by changing dot notation into array notation.
  263. *
  264. * @param string $str
  265. * @return string
  266. */
  267. public function fieldNameFilter($str)
  268. {
  269. $path = explode('.', rtrim($str, '.'));
  270. return array_shift($path) . ($path ? '[' . implode('][', $path) . ']' : '');
  271. }
  272. /**
  273. * Filters field name by changing dot notation into array notation.
  274. *
  275. * @param string $str
  276. * @return string
  277. */
  278. public function fieldParentFilter($str)
  279. {
  280. $path = explode('.', rtrim($str, '.'));
  281. array_pop($path);
  282. return implode('.', $path);
  283. }
  284. /**
  285. * Protects email address.
  286. *
  287. * @param string $str
  288. * @return string
  289. */
  290. public function safeEmailFilter($str)
  291. {
  292. static $list = [
  293. '"' => '&#34;',
  294. "'" => '&#39;',
  295. '&' => '&amp;',
  296. '<' => '&lt;',
  297. '>' => '&gt;',
  298. '@' => '&#64;'
  299. ];
  300. $characters = mb_str_split($str, 1, 'UTF-8');
  301. $encoded = '';
  302. foreach ($characters as $chr) {
  303. $encoded .= $list[$chr] ?? (random_int(0, 1) ? '&#' . mb_ord($chr) . ';' : $chr);
  304. }
  305. return $encoded;
  306. }
  307. /**
  308. * Returns array in a random order.
  309. *
  310. * @param array|Traversable $original
  311. * @param int $offset Can be used to return only slice of the array.
  312. * @return array
  313. */
  314. public function randomizeFilter($original, $offset = 0)
  315. {
  316. if ($original instanceof Traversable) {
  317. $original = iterator_to_array($original, false);
  318. }
  319. if (!is_array($original)) {
  320. return $original;
  321. }
  322. $sorted = [];
  323. $random = array_slice($original, $offset);
  324. shuffle($random);
  325. $sizeOf = count($original);
  326. for ($x = 0; $x < $sizeOf; $x++) {
  327. if ($x < $offset) {
  328. $sorted[] = $original[$x];
  329. } else {
  330. $sorted[] = array_shift($random);
  331. }
  332. }
  333. return $sorted;
  334. }
  335. /**
  336. * Returns the modulus of an integer
  337. *
  338. * @param string|int $number
  339. * @param int $divider
  340. * @param array|null $items array of items to select from to return
  341. * @return int
  342. */
  343. public function modulusFilter($number, $divider, $items = null)
  344. {
  345. if (is_string($number)) {
  346. $number = strlen($number);
  347. }
  348. $remainder = $number % $divider;
  349. if (is_array($items)) {
  350. return $items[$remainder] ?? $items[0];
  351. }
  352. return $remainder;
  353. }
  354. /**
  355. * Inflector supports following notations:
  356. *
  357. * `{{ 'person'|pluralize }} => people`
  358. * `{{ 'shoes'|singularize }} => shoe`
  359. * `{{ 'welcome page'|titleize }} => "Welcome Page"`
  360. * `{{ 'send_email'|camelize }} => SendEmail`
  361. * `{{ 'CamelCased'|underscorize }} => camel_cased`
  362. * `{{ 'Something Text'|hyphenize }} => something-text`
  363. * `{{ 'something_text_to_read'|humanize }} => "Something text to read"`
  364. * `{{ '181'|monthize }} => 5`
  365. * `{{ '10'|ordinalize }} => 10th`
  366. *
  367. * @param string $action
  368. * @param string $data
  369. * @param int|null $count
  370. * @return string
  371. */
  372. public function inflectorFilter($action, $data, $count = null)
  373. {
  374. $action .= 'ize';
  375. /** @var Inflector $inflector */
  376. $inflector = $this->grav['inflector'];
  377. if (in_array(
  378. $action,
  379. ['titleize', 'camelize', 'underscorize', 'hyphenize', 'humanize', 'ordinalize', 'monthize'],
  380. true
  381. )) {
  382. return $inflector->{$action}($data);
  383. }
  384. if (in_array($action, ['pluralize', 'singularize'], true)) {
  385. return $count ? $inflector->{$action}($data, $count) : $inflector->{$action}($data);
  386. }
  387. return $data;
  388. }
  389. /**
  390. * Return MD5 hash from the input.
  391. *
  392. * @param string $str
  393. * @return string
  394. */
  395. public function md5Filter($str)
  396. {
  397. return md5($str);
  398. }
  399. /**
  400. * Return Base32 encoded string
  401. *
  402. * @param string $str
  403. * @return string
  404. */
  405. public function base32EncodeFilter($str)
  406. {
  407. return Base32::encode($str);
  408. }
  409. /**
  410. * Return Base32 decoded string
  411. *
  412. * @param string $str
  413. * @return string
  414. */
  415. public function base32DecodeFilter($str)
  416. {
  417. return Base32::decode($str);
  418. }
  419. /**
  420. * Return Base64 encoded string
  421. *
  422. * @param string $str
  423. * @return string
  424. */
  425. public function base64EncodeFilter($str)
  426. {
  427. return base64_encode($str);
  428. }
  429. /**
  430. * Return Base64 decoded string
  431. *
  432. * @param string $str
  433. * @return string|false
  434. */
  435. public function base64DecodeFilter($str)
  436. {
  437. return base64_decode($str);
  438. }
  439. /**
  440. * Sorts a collection by key
  441. *
  442. * @param array $input
  443. * @param string $filter
  444. * @param int $direction
  445. * @param int $sort_flags
  446. * @return array
  447. */
  448. public function sortByKeyFilter($input, $filter, $direction = SORT_ASC, $sort_flags = SORT_REGULAR)
  449. {
  450. return Utils::sortArrayByKey($input, $filter, $direction, $sort_flags);
  451. }
  452. /**
  453. * Return ksorted collection.
  454. *
  455. * @param array|null $array
  456. * @return array
  457. */
  458. public function ksortFilter($array)
  459. {
  460. if (null === $array) {
  461. $array = [];
  462. }
  463. ksort($array);
  464. return $array;
  465. }
  466. /**
  467. * Wrapper for chunk_split() function
  468. *
  469. * @param string $value
  470. * @param int $chars
  471. * @param string $split
  472. * @return string
  473. */
  474. public function chunkSplitFilter($value, $chars, $split = '-')
  475. {
  476. return chunk_split($value, $chars, $split);
  477. }
  478. /**
  479. * determine if a string contains another
  480. *
  481. * @param string $haystack
  482. * @param string $needle
  483. * @return string|bool
  484. * @todo returning $haystack here doesn't make much sense
  485. */
  486. public function containsFilter($haystack, $needle)
  487. {
  488. if (empty($needle)) {
  489. return $haystack;
  490. }
  491. return (strpos($haystack, (string) $needle) !== false);
  492. }
  493. /**
  494. * Gets a human readable output for cron syntax
  495. *
  496. * @param string $at
  497. * @return string
  498. */
  499. public function niceCronFilter($at)
  500. {
  501. $cron = new Cron($at);
  502. return $cron->getText('en');
  503. }
  504. /**
  505. * @param string|mixed $str
  506. * @param string $search
  507. * @param string $replace
  508. * @return string|mixed
  509. */
  510. public function replaceLastFilter($str, $search, $replace)
  511. {
  512. if (is_string($str) && ($pos = mb_strrpos($str, $search)) !== false) {
  513. $str = mb_substr($str, 0, $pos) . $replace . mb_substr($str, $pos + mb_strlen($search));
  514. }
  515. return $str;
  516. }
  517. /**
  518. * Get Cron object for a crontab 'at' format
  519. *
  520. * @param string $at
  521. * @return CronExpression
  522. */
  523. public function cronFunc($at)
  524. {
  525. return CronExpression::factory($at);
  526. }
  527. /**
  528. * displays a facebook style 'time ago' formatted date/time
  529. *
  530. * @param string $date
  531. * @param bool $long_strings
  532. * @param bool $show_tense
  533. * @return string
  534. */
  535. public function nicetimeFunc($date, $long_strings = true, $show_tense = true)
  536. {
  537. if (empty($date)) {
  538. return $this->grav['language']->translate('GRAV.NICETIME.NO_DATE_PROVIDED');
  539. }
  540. if ($long_strings) {
  541. $periods = [
  542. 'NICETIME.SECOND',
  543. 'NICETIME.MINUTE',
  544. 'NICETIME.HOUR',
  545. 'NICETIME.DAY',
  546. 'NICETIME.WEEK',
  547. 'NICETIME.MONTH',
  548. 'NICETIME.YEAR',
  549. 'NICETIME.DECADE'
  550. ];
  551. } else {
  552. $periods = [
  553. 'NICETIME.SEC',
  554. 'NICETIME.MIN',
  555. 'NICETIME.HR',
  556. 'NICETIME.DAY',
  557. 'NICETIME.WK',
  558. 'NICETIME.MO',
  559. 'NICETIME.YR',
  560. 'NICETIME.DEC'
  561. ];
  562. }
  563. $lengths = ['60', '60', '24', '7', '4.35', '12', '10'];
  564. $now = time();
  565. // check if unix timestamp
  566. if ((string)(int)$date === (string)$date) {
  567. $unix_date = $date;
  568. } else {
  569. $unix_date = strtotime($date);
  570. }
  571. // check validity of date
  572. if (empty($unix_date)) {
  573. return $this->grav['language']->translate('GRAV.NICETIME.BAD_DATE');
  574. }
  575. // is it future date or past date
  576. if ($now > $unix_date) {
  577. $difference = $now - $unix_date;
  578. $tense = $this->grav['language']->translate('GRAV.NICETIME.AGO');
  579. } elseif ($now == $unix_date) {
  580. $difference = $now - $unix_date;
  581. $tense = $this->grav['language']->translate('GRAV.NICETIME.JUST_NOW');
  582. } else {
  583. $difference = $unix_date - $now;
  584. $tense = $this->grav['language']->translate('GRAV.NICETIME.FROM_NOW');
  585. }
  586. for ($j = 0; $difference >= $lengths[$j] && $j < count($lengths) - 1; $j++) {
  587. $difference /= $lengths[$j];
  588. }
  589. $difference = round($difference);
  590. if ($difference != 1) {
  591. $periods[$j] .= '_PLURAL';
  592. }
  593. if ($this->grav['language']->getTranslation(
  594. $this->grav['language']->getLanguage(),
  595. $periods[$j] . '_MORE_THAN_TWO'
  596. )
  597. ) {
  598. if ($difference > 2) {
  599. $periods[$j] .= '_MORE_THAN_TWO';
  600. }
  601. }
  602. $periods[$j] = $this->grav['language']->translate('GRAV.'.$periods[$j]);
  603. if ($now == $unix_date) {
  604. return $tense;
  605. }
  606. $time = "{$difference} {$periods[$j]}";
  607. $time .= $show_tense ? " {$tense}" : '';
  608. return $time;
  609. }
  610. /**
  611. * Allow quick check of a string for XSS Vulnerabilities
  612. *
  613. * @param string|array $data
  614. * @return bool|string|array
  615. */
  616. public function xssFunc($data)
  617. {
  618. if (!is_array($data)) {
  619. return Security::detectXss($data);
  620. }
  621. $results = Security::detectXssFromArray($data);
  622. $results_parts = array_map(static function ($value, $key) {
  623. return $key.': \''.$value . '\'';
  624. }, array_values($results), array_keys($results));
  625. return implode(', ', $results_parts);
  626. }
  627. /**
  628. * Generates a random string with configurable length, prefix and suffix.
  629. * Unlike the built-in `uniqid()`, this string is non-conflicting and safe
  630. *
  631. * @param int $length
  632. * @param array $options
  633. * @return string
  634. * @throws \Exception
  635. */
  636. public function uniqueId(int $length = 9, array $options = ['prefix' => '', 'suffix' => '']): string
  637. {
  638. return Utils::uniqueId($length, $options);
  639. }
  640. /**
  641. * @param string $string
  642. * @return string
  643. */
  644. public function absoluteUrlFilter($string)
  645. {
  646. $url = $this->grav['uri']->base();
  647. $string = preg_replace('/((?:href|src) *= *[\'"](?!(http|ftp)))/i', "$1$url", $string);
  648. return $string;
  649. }
  650. /**
  651. * @param array $context
  652. * @param string $string
  653. * @param bool $block Block or Line processing
  654. * @return string
  655. */
  656. public function markdownFunction($context, $string, $block = true)
  657. {
  658. $page = $context['page'] ?? null;
  659. return Utils::processMarkdown($string, $block, $page);
  660. }
  661. /**
  662. * @param string $haystack
  663. * @param string $needle
  664. * @return bool
  665. */
  666. public function startsWithFilter($haystack, $needle)
  667. {
  668. return Utils::startsWith($haystack, $needle);
  669. }
  670. /**
  671. * @param string $haystack
  672. * @param string $needle
  673. * @return bool
  674. */
  675. public function endsWithFilter($haystack, $needle)
  676. {
  677. return Utils::endsWith($haystack, $needle);
  678. }
  679. /**
  680. * @param mixed $value
  681. * @param null $default
  682. * @return mixed|null
  683. */
  684. public function definedDefaultFilter($value, $default = null)
  685. {
  686. return $value ?? $default;
  687. }
  688. /**
  689. * @param string $value
  690. * @param string|null $chars
  691. * @return string
  692. */
  693. public function rtrimFilter($value, $chars = null)
  694. {
  695. return null !== $chars ? rtrim($value, $chars) : rtrim($value);
  696. }
  697. /**
  698. * @param string $value
  699. * @param string|null $chars
  700. * @return string
  701. */
  702. public function ltrimFilter($value, $chars = null)
  703. {
  704. return null !== $chars ? ltrim($value, $chars) : ltrim($value);
  705. }
  706. /**
  707. * Returns a string from a value. If the value is array, return it json encoded
  708. *
  709. * @param mixed $value
  710. * @return string
  711. */
  712. public function stringFilter($value)
  713. {
  714. // Format the array as a string
  715. if (is_array($value)) {
  716. return json_encode($value);
  717. }
  718. // Boolean becomes '1' or '0'
  719. if (is_bool($value)) {
  720. $value = (int)$value;
  721. }
  722. // Cast the other values to string.
  723. return (string)$value;
  724. }
  725. /**
  726. * Casts input to int.
  727. *
  728. * @param mixed $input
  729. * @return int
  730. */
  731. public function intFilter($input)
  732. {
  733. return (int) $input;
  734. }
  735. /**
  736. * Casts input to bool.
  737. *
  738. * @param mixed $input
  739. * @return bool
  740. */
  741. public function boolFilter($input)
  742. {
  743. return (bool) $input;
  744. }
  745. /**
  746. * Casts input to float.
  747. *
  748. * @param mixed $input
  749. * @return float
  750. */
  751. public function floatFilter($input)
  752. {
  753. return (float) $input;
  754. }
  755. /**
  756. * Casts input to array.
  757. *
  758. * @param mixed $input
  759. * @return array
  760. */
  761. public function arrayFilter($input)
  762. {
  763. if (is_array($input)) {
  764. return $input;
  765. }
  766. if (is_object($input)) {
  767. if (method_exists($input, 'toArray')) {
  768. return $input->toArray();
  769. }
  770. if ($input instanceof Iterator) {
  771. return iterator_to_array($input);
  772. }
  773. }
  774. return (array)$input;
  775. }
  776. /**
  777. * @param array|object $value
  778. * @param int|null $inline
  779. * @param int|null $indent
  780. * @return string
  781. */
  782. public function yamlFilter($value, $inline = null, $indent = null): string
  783. {
  784. return Yaml::dump($value, $inline, $indent);
  785. }
  786. /**
  787. * @param Environment $twig
  788. * @return string
  789. */
  790. public function translate(Environment $twig, ...$args)
  791. {
  792. // If admin and tu filter provided, use it
  793. if (isset($this->grav['admin'])) {
  794. $numargs = count($args);
  795. $lang = null;
  796. if (($numargs === 3 && is_array($args[1])) || ($numargs === 2 && !is_array($args[1]))) {
  797. $lang = array_pop($args);
  798. /** @var Language $language */
  799. $language = $this->grav['language'];
  800. if (is_string($lang) && !$language->getLanguageCode($lang)) {
  801. $args[] = $lang;
  802. $lang = null;
  803. }
  804. } elseif ($numargs === 2 && is_array($args[1])) {
  805. $subs = array_pop($args);
  806. $args = array_merge($args, $subs);
  807. }
  808. return $this->grav['admin']->translate($args, $lang);
  809. }
  810. // else use the default grav translate functionality
  811. return $this->grav['language']->translate($args);
  812. }
  813. /**
  814. * Translate Strings
  815. *
  816. * @param string|array $args
  817. * @param array|null $languages
  818. * @param bool $array_support
  819. * @param bool $html_out
  820. * @return string
  821. */
  822. public function translateLanguage($args, array $languages = null, $array_support = false, $html_out = false)
  823. {
  824. /** @var Language $language */
  825. $language = $this->grav['language'];
  826. return $language->translate($args, $languages, $array_support, $html_out);
  827. }
  828. /**
  829. * @param string $key
  830. * @param string $index
  831. * @param array|null $lang
  832. * @return string
  833. */
  834. public function translateArray($key, $index, $lang = null)
  835. {
  836. /** @var Language $language */
  837. $language = $this->grav['language'];
  838. return $language->translateArray($key, $index, $lang);
  839. }
  840. /**
  841. * Repeat given string x times.
  842. *
  843. * @param string $input
  844. * @param int $multiplier
  845. *
  846. * @return string
  847. */
  848. public function repeatFunc($input, $multiplier)
  849. {
  850. return str_repeat($input, $multiplier);
  851. }
  852. /**
  853. * Return URL to the resource.
  854. *
  855. * @example {{ url('theme://images/logo.png')|default('http://www.placehold.it/150x100/f4f4f4') }}
  856. *
  857. * @param string $input Resource to be located.
  858. * @param bool $domain True to include domain name.
  859. * @param bool $failGracefully If true, return URL even if the file does not exist.
  860. * @return string|false Returns url to the resource or null if resource was not found.
  861. */
  862. public function urlFunc($input, $domain = false, $failGracefully = false)
  863. {
  864. return Utils::url($input, $domain, $failGracefully);
  865. }
  866. /**
  867. * This function will evaluate Twig $twig through the $environment, and return its results.
  868. *
  869. * @param array $context
  870. * @param string $twig
  871. * @return mixed
  872. */
  873. public function evaluateTwigFunc($context, $twig)
  874. {
  875. $loader = new FilesystemLoader('.');
  876. $env = new Environment($loader);
  877. $env->addExtension($this);
  878. $template = $env->createTemplate($twig);
  879. return $template->render($context);
  880. }
  881. /**
  882. * This function will evaluate a $string through the $environment, and return its results.
  883. *
  884. * @param array $context
  885. * @param string $string
  886. * @return mixed
  887. */
  888. public function evaluateStringFunc($context, $string)
  889. {
  890. return $this->evaluateTwigFunc($context, "{{ $string }}");
  891. }
  892. /**
  893. * Based on Twig\Extension\Debug / twig_var_dump
  894. * (c) 2011 Fabien Potencier
  895. *
  896. * @param Environment $env
  897. * @param array $context
  898. */
  899. public function dump(Environment $env, $context)
  900. {
  901. if (!$env->isDebug() || !$this->debugger) {
  902. return;
  903. }
  904. $count = func_num_args();
  905. if (2 === $count) {
  906. $data = [];
  907. foreach ($context as $key => $value) {
  908. if (is_object($value)) {
  909. if (method_exists($value, 'toArray')) {
  910. $data[$key] = $value->toArray();
  911. } else {
  912. $data[$key] = 'Object (' . get_class($value) . ')';
  913. }
  914. } else {
  915. $data[$key] = $value;
  916. }
  917. }
  918. $this->debugger->addMessage($data, 'debug');
  919. } else {
  920. for ($i = 2; $i < $count; $i++) {
  921. $var = func_get_arg($i);
  922. $this->debugger->addMessage($var, 'debug');
  923. }
  924. }
  925. }
  926. /**
  927. * Output a Gist
  928. *
  929. * @param string $id
  930. * @param string|false $file
  931. * @return string
  932. */
  933. public function gistFunc($id, $file = false)
  934. {
  935. $url = 'https://gist.github.com/' . $id . '.js';
  936. if ($file) {
  937. $url .= '?file=' . $file;
  938. }
  939. return '<script src="' . $url . '"></script>';
  940. }
  941. /**
  942. * Generate a random string
  943. *
  944. * @param int $count
  945. * @return string
  946. */
  947. public function randomStringFunc($count = 5)
  948. {
  949. return Utils::generateRandomString($count);
  950. }
  951. /**
  952. * Pad a string to a certain length with another string
  953. *
  954. * @param string $input
  955. * @param int $pad_length
  956. * @param string $pad_string
  957. * @param int $pad_type
  958. * @return string
  959. */
  960. public static function padFilter($input, $pad_length, $pad_string = ' ', $pad_type = STR_PAD_RIGHT)
  961. {
  962. return str_pad($input, (int)$pad_length, $pad_string, $pad_type);
  963. }
  964. /**
  965. * Workaround for twig associative array initialization
  966. * Returns a key => val array
  967. *
  968. * @param string $key key of item
  969. * @param string $val value of item
  970. * @param array|null $current_array optional array to add to
  971. * @return array
  972. */
  973. public function arrayKeyValueFunc($key, $val, $current_array = null)
  974. {
  975. if (empty($current_array)) {
  976. return array($key => $val);
  977. }
  978. $current_array[$key] = $val;
  979. return $current_array;
  980. }
  981. /**
  982. * Wrapper for array_intersect() method
  983. *
  984. * @param array|Collection $array1
  985. * @param array|Collection $array2
  986. * @return array|Collection
  987. */
  988. public function arrayIntersectFunc($array1, $array2)
  989. {
  990. if ($array1 instanceof Collection && $array2 instanceof Collection) {
  991. return $array1->intersect($array2)->toArray();
  992. }
  993. return array_intersect($array1, $array2);
  994. }
  995. /**
  996. * Translate a string
  997. *
  998. * @return string
  999. */
  1000. public function translateFunc()
  1001. {
  1002. return $this->grav['language']->translate(func_get_args());
  1003. }
  1004. /**
  1005. * Authorize an action. Returns true if the user is logged in and
  1006. * has the right to execute $action.
  1007. *
  1008. * @param string|array $action An action or a list of actions. Each
  1009. * entry can be a string like 'group.action'
  1010. * or without dot notation an associative
  1011. * array.
  1012. * @return bool Returns TRUE if the user is authorized to
  1013. * perform the action, FALSE otherwise.
  1014. */
  1015. public function authorize($action)
  1016. {
  1017. // Admin can use Flex users even if the site does not; make sure we use the right version of the user.
  1018. $admin = $this->grav['admin'] ?? null;
  1019. if ($admin) {
  1020. $user = $admin->user;
  1021. } else {
  1022. /** @var UserInterface|null $user */
  1023. $user = $this->grav['user'] ?? null;
  1024. }
  1025. if (!$user) {
  1026. return false;
  1027. }
  1028. if (is_array($action)) {
  1029. if (Utils::isAssoc($action)) {
  1030. // Handle nested access structure.
  1031. $actions = Utils::arrayFlattenDotNotation($action);
  1032. } else {
  1033. // Handle simple access list.
  1034. $actions = array_combine($action, array_fill(0, count($action), true));
  1035. }
  1036. } else {
  1037. // Handle single action.
  1038. $actions = [(string)$action => true];
  1039. }
  1040. $count = count($actions);
  1041. foreach ($actions as $act => $authenticated) {
  1042. // Ignore 'admin.super' if it's not the only value to be checked.
  1043. if ($act === 'admin.super' && $count > 1 && $user instanceof FlexObjectInterface) {
  1044. continue;
  1045. }
  1046. $auth = $user->authorize($act) ?? false;
  1047. if (is_bool($auth) && $auth === Utils::isPositive($authenticated)) {
  1048. return true;
  1049. }
  1050. }
  1051. return false;
  1052. }
  1053. /**
  1054. * Used to add a nonce to a form. Call {{ nonce_field('action') }} specifying a string representing the action.
  1055. *
  1056. * For maximum protection, ensure that the string representing the action is as specific as possible
  1057. *
  1058. * @param string $action the action
  1059. * @param string $nonceParamName a custom nonce param name
  1060. * @return string the nonce input field
  1061. */
  1062. public function nonceFieldFunc($action, $nonceParamName = 'nonce')
  1063. {
  1064. $string = '<input type="hidden" name="' . $nonceParamName . '" value="' . Utils::getNonce($action) . '" />';
  1065. return $string;
  1066. }
  1067. /**
  1068. * Decodes string from JSON.
  1069. *
  1070. * @param string $str
  1071. * @param bool $assoc
  1072. * @param int $depth
  1073. * @param int $options
  1074. * @return array
  1075. */
  1076. public function jsonDecodeFilter($str, $assoc = false, $depth = 512, $options = 0)
  1077. {
  1078. return json_decode(html_entity_decode($str, ENT_COMPAT | ENT_HTML401, 'UTF-8'), $assoc, $depth, $options);
  1079. }
  1080. /**
  1081. * Used to retrieve a cookie value
  1082. *
  1083. * @param string $key The cookie name to retrieve
  1084. * @return string
  1085. */
  1086. public function getCookie($key)
  1087. {
  1088. return filter_input(INPUT_COOKIE, $key, FILTER_SANITIZE_STRING);
  1089. }
  1090. /**
  1091. * Twig wrapper for PHP's preg_replace method
  1092. *
  1093. * @param string|string[] $subject the content to perform the replacement on
  1094. * @param string|string[] $pattern the regex pattern to use for matches
  1095. * @param string|string[] $replace the replacement value either as a string or an array of replacements
  1096. * @param int $limit the maximum possible replacements for each pattern in each subject
  1097. * @return string|string[]|null the resulting content
  1098. */
  1099. public function regexReplace($subject, $pattern, $replace, $limit = -1)
  1100. {
  1101. return preg_replace($pattern, $replace, $subject, $limit);
  1102. }
  1103. /**
  1104. * Twig wrapper for PHP's preg_grep method
  1105. *
  1106. * @param array $array
  1107. * @param string $regex
  1108. * @param int $flags
  1109. * @return array
  1110. */
  1111. public function regexFilter($array, $regex, $flags = 0)
  1112. {
  1113. return preg_grep($regex, $array, $flags);
  1114. }
  1115. /**
  1116. * Twig wrapper for PHP's preg_match method
  1117. *
  1118. * @param string $subject the content to perform the match on
  1119. * @param string $pattern the regex pattern to use for match
  1120. * @param int $flags
  1121. * @param int $offset
  1122. * @return array|false returns the matches if there is at least one match in the subject for a given pattern or null if not.
  1123. */
  1124. public function regexMatch($subject, $pattern, $flags = 0, $offset = 0)
  1125. {
  1126. if (preg_match($pattern, $subject, $matches, $flags, $offset) === false) {
  1127. return false;
  1128. }
  1129. return $matches;
  1130. }
  1131. /**
  1132. * Twig wrapper for PHP's preg_split method
  1133. *
  1134. * @param string $subject the content to perform the split on
  1135. * @param string $pattern the regex pattern to use for split
  1136. * @param int $limit the maximum possible splits for the given pattern
  1137. * @param int $flags
  1138. * @return array|false the resulting array after performing the split operation
  1139. */
  1140. public function regexSplit($subject, $pattern, $limit = -1, $flags = 0)
  1141. {
  1142. return preg_split($pattern, $subject, $limit, $flags);
  1143. }
  1144. /**
  1145. * redirect browser from twig
  1146. *
  1147. * @param string $url the url to redirect to
  1148. * @param int $statusCode statusCode, default 303
  1149. * @return void
  1150. */
  1151. public function redirectFunc($url, $statusCode = 303)
  1152. {
  1153. $response = new Response($statusCode, ['location' => $url]);
  1154. $this->grav->close($response);
  1155. }
  1156. /**
  1157. * Generates an array containing a range of elements, optionally stepped
  1158. *
  1159. * @param int $start Minimum number, default 0
  1160. * @param int $end Maximum number, default `getrandmax()`
  1161. * @param int $step Increment between elements in the sequence, default 1
  1162. * @return array
  1163. */
  1164. public function rangeFunc($start = 0, $end = 100, $step = 1)
  1165. {
  1166. return range($start, $end, $step);
  1167. }
  1168. /**
  1169. * Check if HTTP_X_REQUESTED_WITH has been set to xmlhttprequest,
  1170. * in which case we may unsafely assume ajax. Non critical use only.
  1171. *
  1172. * @return bool True if HTTP_X_REQUESTED_WITH exists and has been set to xmlhttprequest
  1173. */
  1174. public function isAjaxFunc()
  1175. {
  1176. return (
  1177. !empty($_SERVER['HTTP_X_REQUESTED_WITH'])
  1178. && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest');
  1179. }
  1180. /**
  1181. * Get the Exif data for a file
  1182. *
  1183. * @param string $image
  1184. * @param bool $raw
  1185. * @return mixed
  1186. */
  1187. public function exifFunc($image, $raw = false)
  1188. {
  1189. if (isset($this->grav['exif'])) {
  1190. /** @var UniformResourceLocator $locator */
  1191. $locator = $this->grav['locator'];
  1192. if ($locator->isStream($image)) {
  1193. $image = $locator->findResource($image);
  1194. }
  1195. $exif_reader = $this->grav['exif']->getReader();
  1196. if ($image && file_exists($image) && $this->config->get('system.media.auto_metadata_exif') && $exif_reader) {
  1197. $exif_data = $exif_reader->read($image);
  1198. if ($exif_data) {
  1199. if ($raw) {
  1200. return $exif_data->getRawData();
  1201. }
  1202. return $exif_data->getData();
  1203. }
  1204. }
  1205. }
  1206. return null;
  1207. }
  1208. /**
  1209. * Simple function to read a file based on a filepath and output it
  1210. *
  1211. * @param string $filepath
  1212. * @return bool|string
  1213. */
  1214. public function readFileFunc($filepath)
  1215. {
  1216. /** @var UniformResourceLocator $locator */
  1217. $locator = $this->grav['locator'];
  1218. if ($locator->isStream($filepath)) {
  1219. $filepath = $locator->findResource($filepath);
  1220. }
  1221. if ($filepath && file_exists($filepath)) {
  1222. return file_get_contents($filepath);
  1223. }
  1224. return false;
  1225. }
  1226. /**
  1227. * Process a folder as Media and return a media object
  1228. *
  1229. * @param string $media_dir
  1230. * @return Media|null
  1231. */
  1232. public function mediaDirFunc($media_dir)
  1233. {
  1234. /** @var UniformResourceLocator $locator */
  1235. $locator = $this->grav['locator'];
  1236. if ($locator->isStream($media_dir)) {
  1237. $media_dir = $locator->findResource($media_dir);
  1238. }
  1239. if ($media_dir && file_exists($media_dir)) {
  1240. return new Media($media_dir);
  1241. }
  1242. return null;
  1243. }
  1244. /**
  1245. * Dump a variable to the browser
  1246. *
  1247. * @param mixed $var
  1248. * @return void
  1249. */
  1250. public function vardumpFunc($var)
  1251. {
  1252. dump($var);
  1253. }
  1254. /**
  1255. * Returns a nicer more readable filesize based on bytes
  1256. *
  1257. * @param int $bytes
  1258. * @return string
  1259. */
  1260. public function niceFilesizeFunc($bytes)
  1261. {
  1262. return Utils::prettySize($bytes);
  1263. }
  1264. /**
  1265. * Returns a nicer more readable number
  1266. *
  1267. * @param int|float|string $n
  1268. * @return string|bool
  1269. */
  1270. public function niceNumberFunc($n)
  1271. {
  1272. if (!is_float($n) && !is_int($n)) {
  1273. if (!is_string($n) || $n === '') {
  1274. return false;
  1275. }
  1276. // Strip any thousand formatting and find the first number.
  1277. $list = array_filter(preg_split("/\D+/", str_replace(',', '', $n)));
  1278. $n = reset($list);
  1279. if (!is_numeric($n)) {
  1280. return false;
  1281. }
  1282. $n = (float)$n;
  1283. }
  1284. // now filter it;
  1285. if ($n > 1000000000000) {
  1286. return round($n/1000000000000, 2).' t';
  1287. }
  1288. if ($n > 1000000000) {
  1289. return round($n/1000000000, 2).' b';
  1290. }
  1291. if ($n > 1000000) {
  1292. return round($n/1000000, 2).' m';
  1293. }
  1294. if ($n > 1000) {
  1295. return round($n/1000, 2).' k';
  1296. }
  1297. return number_format($n);
  1298. }
  1299. /**
  1300. * Get a theme variable
  1301. * Will try to get the variable for the current page, if not found, it tries it's parent page on up to root.
  1302. * If still not found, will use the theme's configuration value,
  1303. * If still not found, will use the $default value passed in
  1304. *
  1305. * @param array $context Twig Context
  1306. * @param string $var variable to be found (using dot notation)
  1307. * @param null $default the default value to be used as last resort
  1308. * @param PageInterface|null $page an optional page to use for the current page
  1309. * @param bool $exists toggle to simply return the page where the variable is set, else null
  1310. * @return mixed
  1311. */
  1312. public function themeVarFunc($context, $var, $default = null, $page = null, $exists = false)
  1313. {
  1314. $page = $page ?? $context['page'] ?? Grav::instance()['page'] ?? null;
  1315. // Try to find var in the page headers
  1316. if ($page instanceof PageInterface && $page->exists()) {
  1317. // Loop over pages and look for header vars
  1318. while ($page && !$page->root()) {
  1319. $header = new Data((array)$page->header());
  1320. $value = $header->get($var);
  1321. if (isset($value)) {
  1322. if ($exists) {
  1323. return $page;
  1324. }
  1325. return $value;
  1326. }
  1327. $page = $page->parent();
  1328. }
  1329. }
  1330. if ($exists) {
  1331. return false;
  1332. }
  1333. return Grav::instance()['config']->get('theme.' . $var, $default);
  1334. }
  1335. /**
  1336. * Look for a page header variable in an array of pages working its way through until a value is found
  1337. *
  1338. * @param array $context
  1339. * @param string $var the variable to look for in the page header
  1340. * @param string|string[]|null $pages array of pages to check (current page upwards if not null)
  1341. * @return mixed
  1342. * @deprecated 1.7 Use themeVarFunc() instead
  1343. */
  1344. public function pageHeaderVarFunc($context, $var, $pages = null)
  1345. {
  1346. if (is_array($pages)) {
  1347. $page = array_shift($pages);
  1348. } else {
  1349. $page = null;
  1350. }
  1351. return $this->themeVarFunc($context, $var, null, $page);
  1352. }
  1353. /**
  1354. * takes an array of classes, and if they are not set on body_classes
  1355. * look to see if they are set in theme config
  1356. *
  1357. * @param array $context
  1358. * @param string|string[] $classes
  1359. * @return string
  1360. */
  1361. public function bodyClassFunc($context, $classes)
  1362. {
  1363. $header = $context['page']->header();
  1364. $body_classes = $header->body_classes ?? '';
  1365. foreach ((array)$classes as $class) {
  1366. if (!empty($body_classes) && Utils::contains($body_classes, $class)) {
  1367. continue;
  1368. }
  1369. $val = $this->config->get('theme.' . $class, false) ? $class : false;
  1370. $body_classes .= $val ? ' ' . $val : '';
  1371. }
  1372. return $body_classes;
  1373. }
  1374. /**
  1375. * Returns the content of an SVG image and adds extra classes as needed
  1376. *
  1377. * @param string $path
  1378. * @param string|null $classes
  1379. * @return string|string[]|null
  1380. */
  1381. public static function svgImageFunction($path, $classes = null, $strip_style = false)
  1382. {
  1383. $path = Utils::fullPath($path);
  1384. $classes = $classes ?: '';
  1385. if (file_exists($path) && !is_dir($path)) {
  1386. $svg = file_get_contents($path);
  1387. $classes = " inline-block $classes";
  1388. $matched = false;
  1389. //Remove xml tag if it exists
  1390. $svg = preg_replace('/^<\?xml.*\?>/','', $svg);
  1391. //Strip style if needed
  1392. if ($strip_style) {
  1393. $svg = preg_replace('/<style.*<\/style>/s', '', $svg);
  1394. }
  1395. //Look for existing class
  1396. $svg = preg_replace_callback('/^<svg[^>]*(class=\"([^"]*)\")[^>]*>/', function($matches) use ($classes, &$matched) {
  1397. if (isset($matches[2])) {
  1398. $new_classes = $matches[2] . $classes;
  1399. $matched = true;
  1400. return str_replace($matches[1], "class=\"$new_classes\"", $matches[0]);
  1401. }
  1402. return $matches[0];
  1403. }, $svg
  1404. );
  1405. // no matches found just add the class
  1406. if (!$matched) {
  1407. $classes = trim($classes);
  1408. $svg = str_replace('<svg ', "<svg class=\"$classes\" ", $svg);
  1409. }
  1410. return trim($svg);
  1411. }
  1412. return null;
  1413. }
  1414. /**
  1415. * Dump/Encode data into YAML format
  1416. *
  1417. * @param array|object $data
  1418. * @param int $inline integer number of levels of inline syntax
  1419. * @return string
  1420. */
  1421. public function yamlEncodeFilter($data, $inline = 10)
  1422. {
  1423. if (!is_array($data)) {
  1424. if ($data instanceof JsonSerializable) {
  1425. $data = $data->jsonSerialize();
  1426. } elseif (method_exists($data, 'toArray')) {
  1427. $data = $data->toArray();
  1428. } else {
  1429. $data = json_decode(json_encode($data), true);
  1430. }
  1431. }
  1432. return Yaml::dump($data, $inline);
  1433. }
  1434. /**
  1435. * Decode/Parse data from YAML format
  1436. *
  1437. * @param string $data
  1438. * @return array
  1439. */
  1440. public function yamlDecodeFilter($data)
  1441. {
  1442. return Yaml::parse($data);
  1443. }
  1444. /**
  1445. * Function/Filter to return the type of variable
  1446. *
  1447. * @param mixed $var
  1448. * @return string
  1449. */
  1450. public function getTypeFunc($var)
  1451. {
  1452. return gettype($var);
  1453. }
  1454. /**
  1455. * Function/Filter to test type of variable
  1456. *
  1457. * @param mixed $var
  1458. * @param string|null $typeTest
  1459. * @param string|null $className
  1460. * @return bool
  1461. */
  1462. public function ofTypeFunc($var, $typeTest = null, $className = null)
  1463. {
  1464. switch ($typeTest) {
  1465. default:
  1466. return false;
  1467. case 'array':
  1468. return is_array($var);
  1469. case 'bool':
  1470. return is_bool($var);
  1471. case 'class':
  1472. return is_object($var) === true && get_class($var) === $className;
  1473. case 'float':
  1474. return is_float($var);
  1475. case 'int':
  1476. return is_int($var);
  1477. case 'numeric':
  1478. return is_numeric($var);
  1479. case 'object':
  1480. return is_object($var);
  1481. case 'scalar':
  1482. return is_scalar($var);
  1483. case 'string':
  1484. return is_string($var);
  1485. }
  1486. }
  1487. /**
  1488. * @param Environment $env
  1489. * @param array $array
  1490. * @param callable|string $arrow
  1491. * @return array|CallbackFilterIterator
  1492. * @throws RuntimeError
  1493. */
  1494. function filterFilter(Environment $env, $array, $arrow)
  1495. {
  1496. if (is_string($arrow) && Utils::isDangerousFunction($arrow)) {
  1497. throw new RuntimeError('Twig |filter("' . $arrow . '") is not allowed.');
  1498. }
  1499. return twig_array_filter($env, $array, $arrow);
  1500. }
  1501. }