Page.php 84 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917
  1. <?php
  2. /**
  3. * @package Grav\Common\Page
  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\Page;
  9. use Exception;
  10. use Grav\Common\Cache;
  11. use Grav\Common\Config\Config;
  12. use Grav\Common\Data\Blueprint;
  13. use Grav\Common\File\CompiledYamlFile;
  14. use Grav\Common\Filesystem\Folder;
  15. use Grav\Common\Grav;
  16. use Grav\Common\Language\Language;
  17. use Grav\Common\Markdown\Parsedown;
  18. use Grav\Common\Markdown\ParsedownExtra;
  19. use Grav\Common\Page\Interfaces\PageCollectionInterface;
  20. use Grav\Common\Page\Interfaces\PageInterface;
  21. use Grav\Common\Media\Traits\MediaTrait;
  22. use Grav\Common\Page\Markdown\Excerpts;
  23. use Grav\Common\Page\Traits\PageFormTrait;
  24. use Grav\Common\Twig\Twig;
  25. use Grav\Common\Uri;
  26. use Grav\Common\Utils;
  27. use Grav\Common\Yaml;
  28. use Grav\Framework\Flex\Flex;
  29. use InvalidArgumentException;
  30. use RocketTheme\Toolbox\Event\Event;
  31. use RocketTheme\Toolbox\File\MarkdownFile;
  32. use RuntimeException;
  33. use SplFileInfo;
  34. use function dirname;
  35. use function in_array;
  36. use function is_array;
  37. use function is_object;
  38. use function is_string;
  39. use function strlen;
  40. define('PAGE_ORDER_PREFIX_REGEX', '/^[0-9]+\./u');
  41. /**
  42. * Class Page
  43. * @package Grav\Common\Page
  44. */
  45. class Page implements PageInterface
  46. {
  47. use PageFormTrait;
  48. use MediaTrait;
  49. /** @var string|null Filename. Leave as null if page is folder. */
  50. protected $name;
  51. /** @var bool */
  52. protected $initialized = false;
  53. /** @var string */
  54. protected $folder;
  55. /** @var string */
  56. protected $path;
  57. /** @var string */
  58. protected $extension;
  59. /** @var string */
  60. protected $url_extension;
  61. /** @var string */
  62. protected $id;
  63. /** @var string */
  64. protected $parent;
  65. /** @var string */
  66. protected $template;
  67. /** @var int */
  68. protected $expires;
  69. /** @var string */
  70. protected $cache_control;
  71. /** @var bool */
  72. protected $visible;
  73. /** @var bool */
  74. protected $published;
  75. /** @var int */
  76. protected $publish_date;
  77. /** @var int|null */
  78. protected $unpublish_date;
  79. /** @var string */
  80. protected $slug;
  81. /** @var string|null */
  82. protected $route;
  83. /** @var string|null */
  84. protected $raw_route;
  85. /** @var string */
  86. protected $url;
  87. /** @var array */
  88. protected $routes;
  89. /** @var bool */
  90. protected $routable;
  91. /** @var int */
  92. protected $modified;
  93. /** @var string */
  94. protected $redirect;
  95. /** @var string */
  96. protected $external_url;
  97. /** @var object|null */
  98. protected $header;
  99. /** @var string */
  100. protected $frontmatter;
  101. /** @var string */
  102. protected $language;
  103. /** @var string|null */
  104. protected $content;
  105. /** @var array */
  106. protected $content_meta;
  107. /** @var string|null */
  108. protected $summary;
  109. /** @var string */
  110. protected $raw_content;
  111. /** @var array|null */
  112. protected $metadata;
  113. /** @var string */
  114. protected $title;
  115. /** @var int */
  116. protected $max_count;
  117. /** @var string */
  118. protected $menu;
  119. /** @var int */
  120. protected $date;
  121. /** @var string */
  122. protected $dateformat;
  123. /** @var array */
  124. protected $taxonomy;
  125. /** @var string */
  126. protected $order_by;
  127. /** @var string */
  128. protected $order_dir;
  129. /** @var array|string|null */
  130. protected $order_manual;
  131. /** @var bool */
  132. protected $modular_twig;
  133. /** @var array */
  134. protected $process;
  135. /** @var int|null */
  136. protected $summary_size;
  137. /** @var bool */
  138. protected $markdown_extra;
  139. /** @var bool */
  140. protected $etag;
  141. /** @var bool */
  142. protected $last_modified;
  143. /** @var string */
  144. protected $home_route;
  145. /** @var bool */
  146. protected $hide_home_route;
  147. /** @var bool */
  148. protected $ssl;
  149. /** @var string */
  150. protected $template_format;
  151. /** @var bool */
  152. protected $debugger;
  153. /** @var PageInterface|null Unmodified (original) version of the page. Used for copying and moving the page. */
  154. private $_original;
  155. /** @var string Action */
  156. private $_action;
  157. /**
  158. * Page Object Constructor
  159. */
  160. public function __construct()
  161. {
  162. /** @var Config $config */
  163. $config = Grav::instance()['config'];
  164. $this->taxonomy = [];
  165. $this->process = $config->get('system.pages.process');
  166. $this->published = true;
  167. }
  168. /**
  169. * Initializes the page instance variables based on a file
  170. *
  171. * @param SplFileInfo $file The file information for the .md file that the page represents
  172. * @param string|null $extension
  173. * @return $this
  174. */
  175. public function init(SplFileInfo $file, $extension = null)
  176. {
  177. $config = Grav::instance()['config'];
  178. $this->initialized = true;
  179. // some extension logic
  180. if (empty($extension)) {
  181. $this->extension('.' . $file->getExtension());
  182. } else {
  183. $this->extension($extension);
  184. }
  185. // extract page language from page extension
  186. $language = trim(Utils::basename($this->extension(), 'md'), '.') ?: null;
  187. $this->language($language);
  188. $this->hide_home_route = $config->get('system.home.hide_in_urls', false);
  189. $this->home_route = $this->adjustRouteCase($config->get('system.home.alias'));
  190. $this->filePath($file->getPathname());
  191. $this->modified($file->getMTime());
  192. $this->id($this->modified() . md5($this->filePath()));
  193. $this->routable(true);
  194. $this->header();
  195. $this->date();
  196. $this->metadata();
  197. $this->url();
  198. $this->visible();
  199. $this->modularTwig(strpos($this->slug(), '_') === 0);
  200. $this->setPublishState();
  201. $this->published();
  202. $this->urlExtension();
  203. return $this;
  204. }
  205. #[\ReturnTypeWillChange]
  206. public function __clone()
  207. {
  208. $this->initialized = false;
  209. $this->header = $this->header ? clone $this->header : null;
  210. }
  211. /**
  212. * @return void
  213. */
  214. public function initialize(): void
  215. {
  216. if (!$this->initialized) {
  217. $this->initialized = true;
  218. $this->route = null;
  219. $this->raw_route = null;
  220. $this->_forms = null;
  221. }
  222. }
  223. /**
  224. * @return void
  225. */
  226. protected function processFrontmatter()
  227. {
  228. // Quick check for twig output tags in frontmatter if enabled
  229. $process_fields = (array)$this->header();
  230. if (Utils::contains(json_encode(array_values($process_fields)), '{{')) {
  231. $ignored_fields = [];
  232. foreach ((array)Grav::instance()['config']->get('system.pages.frontmatter.ignore_fields') as $field) {
  233. if (isset($process_fields[$field])) {
  234. $ignored_fields[$field] = $process_fields[$field];
  235. unset($process_fields[$field]);
  236. }
  237. }
  238. $text_header = Grav::instance()['twig']->processString(json_encode($process_fields, JSON_UNESCAPED_UNICODE), ['page' => $this]);
  239. $this->header((object)(json_decode($text_header, true) + $ignored_fields));
  240. }
  241. }
  242. /**
  243. * Return an array with the routes of other translated languages
  244. *
  245. * @param bool $onlyPublished only return published translations
  246. * @return array the page translated languages
  247. */
  248. public function translatedLanguages($onlyPublished = false)
  249. {
  250. $grav = Grav::instance();
  251. /** @var Language $language */
  252. $language = $grav['language'];
  253. $languages = $language->getLanguages();
  254. $defaultCode = $language->getDefault();
  255. $name = substr($this->name, 0, -strlen($this->extension()));
  256. $translatedLanguages = [];
  257. foreach ($languages as $languageCode) {
  258. $languageExtension = ".{$languageCode}.md";
  259. $path = $this->path . DS . $this->folder . DS . $name . $languageExtension;
  260. $exists = file_exists($path);
  261. // Default language may be saved without language file location.
  262. if (!$exists && $languageCode === $defaultCode) {
  263. $languageExtension = '.md';
  264. $path = $this->path . DS . $this->folder . DS . $name . $languageExtension;
  265. $exists = file_exists($path);
  266. }
  267. if ($exists) {
  268. $aPage = new Page();
  269. $aPage->init(new SplFileInfo($path), $languageExtension);
  270. $aPage->route($this->route());
  271. $aPage->rawRoute($this->rawRoute());
  272. $route = $aPage->header()->routes['default'] ?? $aPage->rawRoute();
  273. if (!$route) {
  274. $route = $aPage->route();
  275. }
  276. if ($onlyPublished && !$aPage->published()) {
  277. continue;
  278. }
  279. $translatedLanguages[$languageCode] = $route;
  280. }
  281. }
  282. return $translatedLanguages;
  283. }
  284. /**
  285. * Return an array listing untranslated languages available
  286. *
  287. * @param bool $includeUnpublished also list unpublished translations
  288. * @return array the page untranslated languages
  289. */
  290. public function untranslatedLanguages($includeUnpublished = false)
  291. {
  292. $grav = Grav::instance();
  293. /** @var Language $language */
  294. $language = $grav['language'];
  295. $languages = $language->getLanguages();
  296. $translated = array_keys($this->translatedLanguages(!$includeUnpublished));
  297. return array_values(array_diff($languages, $translated));
  298. }
  299. /**
  300. * Gets and Sets the raw data
  301. *
  302. * @param string|null $var Raw content string
  303. * @return string Raw content string
  304. */
  305. public function raw($var = null)
  306. {
  307. $file = $this->file();
  308. if ($var) {
  309. // First update file object.
  310. if ($file) {
  311. $file->raw($var);
  312. }
  313. // Reset header and content.
  314. $this->modified = time();
  315. $this->id($this->modified() . md5($this->filePath()));
  316. $this->header = null;
  317. $this->content = null;
  318. $this->summary = null;
  319. }
  320. return $file ? $file->raw() : '';
  321. }
  322. /**
  323. * Gets and Sets the page frontmatter
  324. *
  325. * @param string|null $var
  326. *
  327. * @return string
  328. */
  329. public function frontmatter($var = null)
  330. {
  331. if ($var) {
  332. $this->frontmatter = (string)$var;
  333. // Update also file object.
  334. $file = $this->file();
  335. if ($file) {
  336. $file->frontmatter((string)$var);
  337. }
  338. // Force content re-processing.
  339. $this->id(time() . md5($this->filePath()));
  340. }
  341. if (!$this->frontmatter) {
  342. $this->header();
  343. }
  344. return $this->frontmatter;
  345. }
  346. /**
  347. * Gets and Sets the header based on the YAML configuration at the top of the .md file
  348. *
  349. * @param object|array|null $var a YAML object representing the configuration for the file
  350. * @return \stdClass the current YAML configuration
  351. */
  352. public function header($var = null)
  353. {
  354. if ($var) {
  355. $this->header = (object)$var;
  356. // Update also file object.
  357. $file = $this->file();
  358. if ($file) {
  359. $file->header((array)$var);
  360. }
  361. // Force content re-processing.
  362. $this->id(time() . md5($this->filePath()));
  363. }
  364. if (!$this->header) {
  365. $file = $this->file();
  366. if ($file) {
  367. try {
  368. $this->raw_content = $file->markdown();
  369. $this->frontmatter = $file->frontmatter();
  370. $this->header = (object)$file->header();
  371. if (!Utils::isAdminPlugin()) {
  372. // If there's a `frontmatter.yaml` file merge that in with the page header
  373. // note page's own frontmatter has precedence and will overwrite any defaults
  374. $frontmatterFile = CompiledYamlFile::instance($this->path . '/' . $this->folder . '/frontmatter.yaml');
  375. if ($frontmatterFile->exists()) {
  376. $frontmatter_data = (array)$frontmatterFile->content();
  377. $this->header = (object)array_replace_recursive(
  378. $frontmatter_data,
  379. (array)$this->header
  380. );
  381. $frontmatterFile->free();
  382. }
  383. // Process frontmatter with Twig if enabled
  384. if (Grav::instance()['config']->get('system.pages.frontmatter.process_twig') === true) {
  385. $this->processFrontmatter();
  386. }
  387. }
  388. } catch (Exception $e) {
  389. $file->raw(Grav::instance()['language']->translate([
  390. 'GRAV.FRONTMATTER_ERROR_PAGE',
  391. $this->slug(),
  392. $file->filename(),
  393. $e->getMessage(),
  394. $file->raw()
  395. ]));
  396. $this->raw_content = $file->markdown();
  397. $this->frontmatter = $file->frontmatter();
  398. $this->header = (object)$file->header();
  399. }
  400. $var = true;
  401. }
  402. }
  403. if ($var) {
  404. if (isset($this->header->slug)) {
  405. $this->slug($this->header->slug);
  406. }
  407. if (isset($this->header->routes)) {
  408. $this->routes = (array)$this->header->routes;
  409. }
  410. if (isset($this->header->title)) {
  411. $this->title = trim($this->header->title);
  412. }
  413. if (isset($this->header->language)) {
  414. $this->language = trim($this->header->language);
  415. }
  416. if (isset($this->header->template)) {
  417. $this->template = trim($this->header->template);
  418. }
  419. if (isset($this->header->menu)) {
  420. $this->menu = trim($this->header->menu);
  421. }
  422. if (isset($this->header->routable)) {
  423. $this->routable = (bool)$this->header->routable;
  424. }
  425. if (isset($this->header->visible)) {
  426. $this->visible = (bool)$this->header->visible;
  427. }
  428. if (isset($this->header->redirect)) {
  429. $this->redirect = trim($this->header->redirect);
  430. }
  431. if (isset($this->header->external_url)) {
  432. $this->external_url = trim($this->header->external_url);
  433. }
  434. if (isset($this->header->order_dir)) {
  435. $this->order_dir = trim($this->header->order_dir);
  436. }
  437. if (isset($this->header->order_by)) {
  438. $this->order_by = trim($this->header->order_by);
  439. }
  440. if (isset($this->header->order_manual)) {
  441. $this->order_manual = (array)$this->header->order_manual;
  442. }
  443. if (isset($this->header->dateformat)) {
  444. $this->dateformat($this->header->dateformat);
  445. }
  446. if (isset($this->header->date)) {
  447. $this->date($this->header->date);
  448. }
  449. if (isset($this->header->markdown_extra)) {
  450. $this->markdown_extra = (bool)$this->header->markdown_extra;
  451. }
  452. if (isset($this->header->taxonomy)) {
  453. $this->taxonomy($this->header->taxonomy);
  454. }
  455. if (isset($this->header->max_count)) {
  456. $this->max_count = (int)$this->header->max_count;
  457. }
  458. if (isset($this->header->process)) {
  459. foreach ((array)$this->header->process as $process => $status) {
  460. $this->process[$process] = (bool)$status;
  461. }
  462. }
  463. if (isset($this->header->published)) {
  464. $this->published = (bool)$this->header->published;
  465. }
  466. if (isset($this->header->publish_date)) {
  467. $this->publishDate($this->header->publish_date);
  468. }
  469. if (isset($this->header->unpublish_date)) {
  470. $this->unpublishDate($this->header->unpublish_date);
  471. }
  472. if (isset($this->header->expires)) {
  473. $this->expires = (int)$this->header->expires;
  474. }
  475. if (isset($this->header->cache_control)) {
  476. $this->cache_control = $this->header->cache_control;
  477. }
  478. if (isset($this->header->etag)) {
  479. $this->etag = (bool)$this->header->etag;
  480. }
  481. if (isset($this->header->last_modified)) {
  482. $this->last_modified = (bool)$this->header->last_modified;
  483. }
  484. if (isset($this->header->ssl)) {
  485. $this->ssl = (bool)$this->header->ssl;
  486. }
  487. if (isset($this->header->template_format)) {
  488. $this->template_format = $this->header->template_format;
  489. }
  490. if (isset($this->header->debugger)) {
  491. $this->debugger = (bool)$this->header->debugger;
  492. }
  493. if (isset($this->header->append_url_extension)) {
  494. $this->url_extension = $this->header->append_url_extension;
  495. }
  496. }
  497. return $this->header;
  498. }
  499. /**
  500. * Get page language
  501. *
  502. * @param string|null $var
  503. * @return mixed
  504. */
  505. public function language($var = null)
  506. {
  507. if ($var !== null) {
  508. $this->language = $var;
  509. }
  510. return $this->language;
  511. }
  512. /**
  513. * Modify a header value directly
  514. *
  515. * @param string $key
  516. * @param mixed $value
  517. */
  518. public function modifyHeader($key, $value)
  519. {
  520. $this->header->{$key} = $value;
  521. }
  522. /**
  523. * @return int
  524. */
  525. public function httpResponseCode()
  526. {
  527. return (int)($this->header()->http_response_code ?? 200);
  528. }
  529. /**
  530. * @return array
  531. */
  532. public function httpHeaders()
  533. {
  534. $headers = [];
  535. $grav = Grav::instance();
  536. $format = $this->templateFormat();
  537. $cache_control = $this->cacheControl();
  538. $expires = $this->expires();
  539. // Set Content-Type header
  540. $headers['Content-Type'] = Utils::getMimeByExtension($format, 'text/html');
  541. // Calculate Expires Headers if set to > 0
  542. if ($expires > 0) {
  543. $expires_date = gmdate('D, d M Y H:i:s', time() + $expires) . ' GMT';
  544. if (!$cache_control) {
  545. $headers['Cache-Control'] = 'max-age=' . $expires;
  546. }
  547. $headers['Expires'] = $expires_date;
  548. }
  549. // Set Cache-Control header
  550. if ($cache_control) {
  551. $headers['Cache-Control'] = strtolower($cache_control);
  552. }
  553. // Set Last-Modified header
  554. if ($this->lastModified()) {
  555. $last_modified_date = gmdate('D, d M Y H:i:s', $this->modified()) . ' GMT';
  556. $headers['Last-Modified'] = $last_modified_date;
  557. }
  558. // Ask Grav to calculate ETag from the final content.
  559. if ($this->eTag()) {
  560. $headers['ETag'] = '1';
  561. }
  562. // Set Vary: Accept-Encoding header
  563. if ($grav['config']->get('system.pages.vary_accept_encoding', false)) {
  564. $headers['Vary'] = 'Accept-Encoding';
  565. }
  566. // Added new Headers event
  567. $headers_obj = (object) $headers;
  568. Grav::instance()->fireEvent('onPageHeaders', new Event(['headers' => $headers_obj]));
  569. return (array)$headers_obj;
  570. }
  571. /**
  572. * Get the summary.
  573. *
  574. * @param int|null $size Max summary size.
  575. * @param bool $textOnly Only count text size.
  576. * @return string
  577. */
  578. public function summary($size = null, $textOnly = false)
  579. {
  580. $config = (array)Grav::instance()['config']->get('site.summary');
  581. if (isset($this->header->summary)) {
  582. $config = array_merge($config, $this->header->summary);
  583. }
  584. // Return summary based on settings in site config file
  585. if (!$config['enabled']) {
  586. return $this->content();
  587. }
  588. // Set up variables to process summary from page or from custom summary
  589. if ($this->summary === null) {
  590. $content = $textOnly ? strip_tags($this->content()) : $this->content();
  591. $summary_size = $this->summary_size;
  592. } else {
  593. $content = $textOnly ? strip_tags($this->summary) : $this->summary;
  594. $summary_size = mb_strwidth($content, 'utf-8');
  595. }
  596. // Return calculated summary based on summary divider's position
  597. $format = $config['format'];
  598. // Return entire page content on wrong/ unknown format
  599. if (!in_array($format, ['short', 'long'])) {
  600. return $content;
  601. }
  602. if (($format === 'short') && isset($summary_size)) {
  603. // Slice the string
  604. if (mb_strwidth($content, 'utf8') > $summary_size) {
  605. return mb_substr($content, 0, $summary_size);
  606. }
  607. return $content;
  608. }
  609. // Get summary size from site config's file
  610. if ($size === null) {
  611. $size = $config['size'];
  612. }
  613. // If the size is zero, return the entire page content
  614. if ($size === 0) {
  615. return $content;
  616. // Return calculated summary based on defaults
  617. }
  618. if (!is_numeric($size) || ($size < 0)) {
  619. $size = 300;
  620. }
  621. // Only return string but not html, wrap whatever html tag you want when using
  622. if ($textOnly) {
  623. if (mb_strwidth($content, 'utf-8') <= $size) {
  624. return $content;
  625. }
  626. return mb_strimwidth($content, 0, $size, '…', 'UTF-8');
  627. }
  628. $summary = Utils::truncateHtml($content, $size);
  629. return html_entity_decode($summary, ENT_COMPAT | ENT_HTML401, 'UTF-8');
  630. }
  631. /**
  632. * Sets the summary of the page
  633. *
  634. * @param string $summary Summary
  635. */
  636. public function setSummary($summary)
  637. {
  638. $this->summary = $summary;
  639. }
  640. /**
  641. * Gets and Sets the content based on content portion of the .md file
  642. *
  643. * @param string|null $var Content
  644. * @return string Content
  645. */
  646. public function content($var = null)
  647. {
  648. if ($var !== null) {
  649. $this->raw_content = $var;
  650. // Update file object.
  651. $file = $this->file();
  652. if ($file) {
  653. $file->markdown($var);
  654. }
  655. // Force re-processing.
  656. $this->id(time() . md5($this->filePath()));
  657. $this->content = null;
  658. }
  659. // If no content, process it
  660. if ($this->content === null) {
  661. // Get media
  662. $this->media();
  663. /** @var Config $config */
  664. $config = Grav::instance()['config'];
  665. // Load cached content
  666. /** @var Cache $cache */
  667. $cache = Grav::instance()['cache'];
  668. $cache_id = md5('page' . $this->getCacheKey());
  669. $content_obj = $cache->fetch($cache_id);
  670. if (is_array($content_obj)) {
  671. $this->content = $content_obj['content'];
  672. $this->content_meta = $content_obj['content_meta'];
  673. } else {
  674. $this->content = $content_obj;
  675. }
  676. $process_markdown = $this->shouldProcess('markdown');
  677. $process_twig = $this->shouldProcess('twig') || $this->modularTwig();
  678. $cache_enable = $this->header->cache_enable ?? $config->get(
  679. 'system.cache.enabled',
  680. true
  681. );
  682. $twig_first = $this->header->twig_first ?? $config->get(
  683. 'system.pages.twig_first',
  684. false
  685. );
  686. // never cache twig means it's always run after content
  687. $never_cache_twig = $this->header->never_cache_twig ?? $config->get(
  688. 'system.pages.never_cache_twig',
  689. true
  690. );
  691. // if no cached-content run everything
  692. if ($never_cache_twig) {
  693. if ($this->content === false || $cache_enable === false) {
  694. $this->content = $this->raw_content;
  695. Grav::instance()->fireEvent('onPageContentRaw', new Event(['page' => $this]));
  696. if ($process_markdown) {
  697. $this->processMarkdown();
  698. }
  699. // Content Processed but not cached yet
  700. Grav::instance()->fireEvent('onPageContentProcessed', new Event(['page' => $this]));
  701. if ($cache_enable) {
  702. $this->cachePageContent();
  703. }
  704. }
  705. if ($process_twig) {
  706. $this->processTwig();
  707. }
  708. } else {
  709. if ($this->content === false || $cache_enable === false) {
  710. $this->content = $this->raw_content;
  711. Grav::instance()->fireEvent('onPageContentRaw', new Event(['page' => $this]));
  712. if ($twig_first) {
  713. if ($process_twig) {
  714. $this->processTwig();
  715. }
  716. if ($process_markdown) {
  717. $this->processMarkdown();
  718. }
  719. // Content Processed but not cached yet
  720. Grav::instance()->fireEvent('onPageContentProcessed', new Event(['page' => $this]));
  721. } else {
  722. if ($process_markdown) {
  723. $this->processMarkdown($process_twig);
  724. }
  725. // Content Processed but not cached yet
  726. Grav::instance()->fireEvent('onPageContentProcessed', new Event(['page' => $this]));
  727. if ($process_twig) {
  728. $this->processTwig();
  729. }
  730. }
  731. if ($cache_enable) {
  732. $this->cachePageContent();
  733. }
  734. }
  735. }
  736. // Handle summary divider
  737. $delimiter = $config->get('site.summary.delimiter', '===');
  738. $divider_pos = mb_strpos($this->content, "<p>{$delimiter}</p>");
  739. if ($divider_pos !== false) {
  740. $this->summary_size = $divider_pos;
  741. $this->content = str_replace("<p>{$delimiter}</p>", '', $this->content);
  742. }
  743. // Fire event when Page::content() is called
  744. Grav::instance()->fireEvent('onPageContent', new Event(['page' => $this]));
  745. }
  746. return $this->content;
  747. }
  748. /**
  749. * Get the contentMeta array and initialize content first if it's not already
  750. *
  751. * @return mixed
  752. */
  753. public function contentMeta()
  754. {
  755. if ($this->content === null) {
  756. $this->content();
  757. }
  758. return $this->getContentMeta();
  759. }
  760. /**
  761. * Add an entry to the page's contentMeta array
  762. *
  763. * @param string $name
  764. * @param mixed $value
  765. */
  766. public function addContentMeta($name, $value)
  767. {
  768. $this->content_meta[$name] = $value;
  769. }
  770. /**
  771. * Return the whole contentMeta array as it currently stands
  772. *
  773. * @param string|null $name
  774. *
  775. * @return mixed|null
  776. */
  777. public function getContentMeta($name = null)
  778. {
  779. if ($name) {
  780. return $this->content_meta[$name] ?? null;
  781. }
  782. return $this->content_meta;
  783. }
  784. /**
  785. * Sets the whole content meta array in one shot
  786. *
  787. * @param array $content_meta
  788. *
  789. * @return array
  790. */
  791. public function setContentMeta($content_meta)
  792. {
  793. return $this->content_meta = $content_meta;
  794. }
  795. /**
  796. * Process the Markdown content. Uses Parsedown or Parsedown Extra depending on configuration
  797. *
  798. * @param bool $keepTwig If true, content between twig tags will not be processed.
  799. * @return void
  800. */
  801. protected function processMarkdown(bool $keepTwig = false)
  802. {
  803. /** @var Config $config */
  804. $config = Grav::instance()['config'];
  805. $markdownDefaults = (array)$config->get('system.pages.markdown');
  806. if (isset($this->header()->markdown)) {
  807. $markdownDefaults = array_merge($markdownDefaults, $this->header()->markdown);
  808. }
  809. // pages.markdown_extra is deprecated, but still check it...
  810. if (!isset($markdownDefaults['extra']) && (isset($this->markdown_extra) || $config->get('system.pages.markdown_extra') !== null)) {
  811. user_error('Configuration option \'system.pages.markdown_extra\' is deprecated since Grav 1.5, use \'system.pages.markdown.extra\' instead', E_USER_DEPRECATED);
  812. $markdownDefaults['extra'] = $this->markdown_extra ?: $config->get('system.pages.markdown_extra');
  813. }
  814. $extra = $markdownDefaults['extra'] ?? false;
  815. $defaults = [
  816. 'markdown' => $markdownDefaults,
  817. 'images' => $config->get('system.images', [])
  818. ];
  819. $excerpts = new Excerpts($this, $defaults);
  820. // Initialize the preferred variant of Parsedown
  821. if ($extra) {
  822. $parsedown = new ParsedownExtra($excerpts);
  823. } else {
  824. $parsedown = new Parsedown($excerpts);
  825. }
  826. $content = $this->content;
  827. if ($keepTwig) {
  828. $token = [
  829. '/' . Utils::generateRandomString(3),
  830. Utils::generateRandomString(3) . '/'
  831. ];
  832. // Base64 encode any twig.
  833. $content = preg_replace_callback(
  834. ['/({#.*?#})/mu', '/({{.*?}})/mu', '/({%.*?%})/mu'],
  835. static function ($matches) use ($token) { return $token[0] . base64_encode($matches[1]) . $token[1]; },
  836. $content
  837. );
  838. }
  839. $content = $parsedown->text($content);
  840. if ($keepTwig) {
  841. // Base64 decode the encoded twig.
  842. $content = preg_replace_callback(
  843. ['`' . $token[0] . '([A-Za-z0-9+/]+={0,2})' . $token[1] . '`mu'],
  844. static function ($matches) { return base64_decode($matches[1]); },
  845. $content
  846. );
  847. }
  848. $this->content = $content;
  849. }
  850. /**
  851. * Process the Twig page content.
  852. *
  853. * @return void
  854. */
  855. private function processTwig()
  856. {
  857. /** @var Twig $twig */
  858. $twig = Grav::instance()['twig'];
  859. $this->content = $twig->processPage($this, $this->content);
  860. }
  861. /**
  862. * Fires the onPageContentProcessed event, and caches the page content using a unique ID for the page
  863. *
  864. * @return void
  865. */
  866. public function cachePageContent()
  867. {
  868. /** @var Cache $cache */
  869. $cache = Grav::instance()['cache'];
  870. $cache_id = md5('page' . $this->getCacheKey());
  871. $cache->save($cache_id, ['content' => $this->content, 'content_meta' => $this->content_meta]);
  872. }
  873. /**
  874. * Needed by the onPageContentProcessed event to get the raw page content
  875. *
  876. * @return string the current page content
  877. */
  878. public function getRawContent()
  879. {
  880. return $this->content;
  881. }
  882. /**
  883. * Needed by the onPageContentProcessed event to set the raw page content
  884. *
  885. * @param string|null $content
  886. * @return void
  887. */
  888. public function setRawContent($content)
  889. {
  890. $this->content = $content ?? '';
  891. }
  892. /**
  893. * Get value from a page variable (used mostly for creating edit forms).
  894. *
  895. * @param string $name Variable name.
  896. * @param mixed $default
  897. * @return mixed
  898. */
  899. public function value($name, $default = null)
  900. {
  901. if ($name === 'content') {
  902. return $this->raw_content;
  903. }
  904. if ($name === 'route') {
  905. $parent = $this->parent();
  906. return $parent ? $parent->rawRoute() : '';
  907. }
  908. if ($name === 'order') {
  909. $order = $this->order();
  910. return $order ? (int)$this->order() : '';
  911. }
  912. if ($name === 'ordering') {
  913. return (bool)$this->order();
  914. }
  915. if ($name === 'folder') {
  916. return preg_replace(PAGE_ORDER_PREFIX_REGEX, '', $this->folder);
  917. }
  918. if ($name === 'slug') {
  919. return $this->slug();
  920. }
  921. if ($name === 'name') {
  922. $name = $this->name();
  923. $language = $this->language() ? '.' . $this->language() : '';
  924. $pattern = '%(' . preg_quote($language, '%') . ')?\.md$%';
  925. $name = preg_replace($pattern, '', $name);
  926. if ($this->isModule()) {
  927. return 'modular/' . $name;
  928. }
  929. return $name;
  930. }
  931. if ($name === 'media') {
  932. return $this->media()->all();
  933. }
  934. if ($name === 'media.file') {
  935. return $this->media()->files();
  936. }
  937. if ($name === 'media.video') {
  938. return $this->media()->videos();
  939. }
  940. if ($name === 'media.image') {
  941. return $this->media()->images();
  942. }
  943. if ($name === 'media.audio') {
  944. return $this->media()->audios();
  945. }
  946. $path = explode('.', $name);
  947. $scope = array_shift($path);
  948. if ($name === 'frontmatter') {
  949. return $this->frontmatter;
  950. }
  951. if ($scope === 'header') {
  952. $current = $this->header();
  953. foreach ($path as $field) {
  954. if (is_object($current) && isset($current->{$field})) {
  955. $current = $current->{$field};
  956. } elseif (is_array($current) && isset($current[$field])) {
  957. $current = $current[$field];
  958. } else {
  959. return $default;
  960. }
  961. }
  962. return $current;
  963. }
  964. return $default;
  965. }
  966. /**
  967. * Gets and Sets the Page raw content
  968. *
  969. * @param string|null $var
  970. * @return string
  971. */
  972. public function rawMarkdown($var = null)
  973. {
  974. if ($var !== null) {
  975. $this->raw_content = $var;
  976. }
  977. return $this->raw_content;
  978. }
  979. /**
  980. * @return bool
  981. * @internal
  982. */
  983. public function translated(): bool
  984. {
  985. return $this->initialized;
  986. }
  987. /**
  988. * Get file object to the page.
  989. *
  990. * @return MarkdownFile|null
  991. */
  992. public function file()
  993. {
  994. if ($this->name) {
  995. return MarkdownFile::instance($this->filePath());
  996. }
  997. return null;
  998. }
  999. /**
  1000. * Save page if there's a file assigned to it.
  1001. *
  1002. * @param bool|array $reorder Internal use.
  1003. */
  1004. public function save($reorder = true)
  1005. {
  1006. // Perform move, copy [or reordering] if needed.
  1007. $this->doRelocation();
  1008. $file = $this->file();
  1009. if ($file) {
  1010. $file->filename($this->filePath());
  1011. $file->header((array)$this->header());
  1012. $file->markdown($this->raw_content);
  1013. $file->save();
  1014. }
  1015. // Perform reorder if required
  1016. if ($reorder && is_array($reorder)) {
  1017. $this->doReorder($reorder);
  1018. }
  1019. // We need to signal Flex Pages about the change.
  1020. /** @var Flex|null $flex */
  1021. $flex = Grav::instance()['flex'] ?? null;
  1022. $directory = $flex ? $flex->getDirectory('pages') : null;
  1023. if (null !== $directory) {
  1024. $directory->clearCache();
  1025. }
  1026. $this->_original = null;
  1027. }
  1028. /**
  1029. * Prepare move page to new location. Moves also everything that's under the current page.
  1030. *
  1031. * You need to call $this->save() in order to perform the move.
  1032. *
  1033. * @param PageInterface $parent New parent page.
  1034. * @return $this
  1035. */
  1036. public function move(PageInterface $parent)
  1037. {
  1038. if (!$this->_original) {
  1039. $clone = clone $this;
  1040. $this->_original = $clone;
  1041. }
  1042. $this->_action = 'move';
  1043. if ($this->route() === $parent->route()) {
  1044. throw new RuntimeException('Failed: Cannot set page parent to self');
  1045. }
  1046. if (Utils::startsWith($parent->rawRoute(), $this->rawRoute())) {
  1047. throw new RuntimeException('Failed: Cannot set page parent to a child of current page');
  1048. }
  1049. $this->parent($parent);
  1050. $this->id(time() . md5($this->filePath()));
  1051. if ($parent->path()) {
  1052. $this->path($parent->path() . '/' . $this->folder());
  1053. }
  1054. if ($parent->route()) {
  1055. $this->route($parent->route() . '/' . $this->slug());
  1056. } else {
  1057. $this->route(Grav::instance()['pages']->root()->route() . '/' . $this->slug());
  1058. }
  1059. $this->raw_route = null;
  1060. return $this;
  1061. }
  1062. /**
  1063. * Prepare a copy from the page. Copies also everything that's under the current page.
  1064. *
  1065. * Returns a new Page object for the copy.
  1066. * You need to call $this->save() in order to perform the move.
  1067. *
  1068. * @param PageInterface $parent New parent page.
  1069. * @return $this
  1070. */
  1071. public function copy(PageInterface $parent)
  1072. {
  1073. $this->move($parent);
  1074. $this->_action = 'copy';
  1075. return $this;
  1076. }
  1077. /**
  1078. * Get blueprints for the page.
  1079. *
  1080. * @return Blueprint
  1081. */
  1082. public function blueprints()
  1083. {
  1084. $grav = Grav::instance();
  1085. /** @var Pages $pages */
  1086. $pages = $grav['pages'];
  1087. $blueprint = $pages->blueprints($this->blueprintName());
  1088. $fields = $blueprint->fields();
  1089. $edit_mode = isset($grav['admin']) ? $grav['config']->get('plugins.admin.edit_mode') : null;
  1090. // override if you only want 'normal' mode
  1091. if (empty($fields) && ($edit_mode === 'auto' || $edit_mode === 'normal')) {
  1092. $blueprint = $pages->blueprints('default');
  1093. }
  1094. // override if you only want 'expert' mode
  1095. if (!empty($fields) && $edit_mode === 'expert') {
  1096. $blueprint = $pages->blueprints('');
  1097. }
  1098. return $blueprint;
  1099. }
  1100. /**
  1101. * Returns the blueprint from the page.
  1102. *
  1103. * @param string $name Not used.
  1104. * @return Blueprint Returns a Blueprint.
  1105. */
  1106. public function getBlueprint(string $name = '')
  1107. {
  1108. return $this->blueprints();
  1109. }
  1110. /**
  1111. * Get the blueprint name for this page. Use the blueprint form field if set
  1112. *
  1113. * @return string
  1114. */
  1115. public function blueprintName()
  1116. {
  1117. $blueprint_name = filter_input(INPUT_POST, 'blueprint', FILTER_SANITIZE_STRING) ?: $this->template();
  1118. return $blueprint_name;
  1119. }
  1120. /**
  1121. * Validate page header.
  1122. *
  1123. * @return void
  1124. * @throws Exception
  1125. */
  1126. public function validate()
  1127. {
  1128. $blueprints = $this->blueprints();
  1129. $blueprints->validate($this->toArray());
  1130. }
  1131. /**
  1132. * Filter page header from illegal contents.
  1133. *
  1134. * @return void
  1135. */
  1136. public function filter()
  1137. {
  1138. $blueprints = $this->blueprints();
  1139. $values = $blueprints->filter($this->toArray());
  1140. if ($values && isset($values['header'])) {
  1141. $this->header($values['header']);
  1142. }
  1143. }
  1144. /**
  1145. * Get unknown header variables.
  1146. *
  1147. * @return array
  1148. */
  1149. public function extra()
  1150. {
  1151. $blueprints = $this->blueprints();
  1152. return $blueprints->extra($this->toArray()['header'], 'header.');
  1153. }
  1154. /**
  1155. * Convert page to an array.
  1156. *
  1157. * @return array
  1158. */
  1159. public function toArray()
  1160. {
  1161. return [
  1162. 'header' => (array)$this->header(),
  1163. 'content' => (string)$this->value('content')
  1164. ];
  1165. }
  1166. /**
  1167. * Convert page to YAML encoded string.
  1168. *
  1169. * @return string
  1170. */
  1171. public function toYaml()
  1172. {
  1173. return Yaml::dump($this->toArray(), 20);
  1174. }
  1175. /**
  1176. * Convert page to JSON encoded string.
  1177. *
  1178. * @return string
  1179. */
  1180. public function toJson()
  1181. {
  1182. return json_encode($this->toArray());
  1183. }
  1184. /**
  1185. * @return string
  1186. */
  1187. public function getCacheKey(): string
  1188. {
  1189. return $this->id();
  1190. }
  1191. /**
  1192. * Gets and sets the associated media as found in the page folder.
  1193. *
  1194. * @param Media|null $var Representation of associated media.
  1195. * @return Media Representation of associated media.
  1196. */
  1197. public function media($var = null)
  1198. {
  1199. if ($var) {
  1200. $this->setMedia($var);
  1201. }
  1202. /** @var Media $media */
  1203. $media = $this->getMedia();
  1204. return $media;
  1205. }
  1206. /**
  1207. * Get filesystem path to the associated media.
  1208. *
  1209. * @return string|null
  1210. */
  1211. public function getMediaFolder()
  1212. {
  1213. return $this->path();
  1214. }
  1215. /**
  1216. * Get display order for the associated media.
  1217. *
  1218. * @return array Empty array means default ordering.
  1219. */
  1220. public function getMediaOrder()
  1221. {
  1222. $header = $this->header();
  1223. return isset($header->media_order) ? array_map('trim', explode(',', (string)$header->media_order)) : [];
  1224. }
  1225. /**
  1226. * Gets and sets the name field. If no name field is set, it will return 'default.md'.
  1227. *
  1228. * @param string|null $var The name of this page.
  1229. * @return string The name of this page.
  1230. */
  1231. public function name($var = null)
  1232. {
  1233. if ($var !== null) {
  1234. $this->name = $var;
  1235. }
  1236. return $this->name ?: 'default.md';
  1237. }
  1238. /**
  1239. * Returns child page type.
  1240. *
  1241. * @return string
  1242. */
  1243. public function childType()
  1244. {
  1245. return isset($this->header->child_type) ? (string)$this->header->child_type : '';
  1246. }
  1247. /**
  1248. * Gets and sets the template field. This is used to find the correct Twig template file to render.
  1249. * If no field is set, it will return the name without the .md extension
  1250. *
  1251. * @param string|null $var the template name
  1252. * @return string the template name
  1253. */
  1254. public function template($var = null)
  1255. {
  1256. if ($var !== null) {
  1257. $this->template = $var;
  1258. }
  1259. if (empty($this->template)) {
  1260. $this->template = ($this->isModule() ? 'modular/' : '') . str_replace($this->extension(), '', $this->name());
  1261. }
  1262. return $this->template;
  1263. }
  1264. /**
  1265. * Allows a page to override the output render format, usually the extension provided in the URL.
  1266. * (e.g. `html`, `json`, `xml`, etc).
  1267. *
  1268. * @param string|null $var
  1269. * @return string
  1270. */
  1271. public function templateFormat($var = null)
  1272. {
  1273. if (null !== $var) {
  1274. $this->template_format = is_string($var) ? $var : null;
  1275. }
  1276. if (!isset($this->template_format)) {
  1277. $this->template_format = ltrim($this->header->append_url_extension ?? Utils::getPageFormat(), '.');
  1278. }
  1279. return $this->template_format;
  1280. }
  1281. /**
  1282. * Gets and sets the extension field.
  1283. *
  1284. * @param string|null $var
  1285. * @return string
  1286. */
  1287. public function extension($var = null)
  1288. {
  1289. if ($var !== null) {
  1290. $this->extension = $var;
  1291. }
  1292. if (empty($this->extension)) {
  1293. $this->extension = '.' . Utils::pathinfo($this->name(), PATHINFO_EXTENSION);
  1294. }
  1295. return $this->extension;
  1296. }
  1297. /**
  1298. * Returns the page extension, got from the page `url_extension` config and falls back to the
  1299. * system config `system.pages.append_url_extension`.
  1300. *
  1301. * @return string The extension of this page. For example `.html`
  1302. */
  1303. public function urlExtension()
  1304. {
  1305. if ($this->home()) {
  1306. return '';
  1307. }
  1308. // if not set in the page get the value from system config
  1309. if (null === $this->url_extension) {
  1310. $this->url_extension = Grav::instance()['config']->get('system.pages.append_url_extension', '');
  1311. }
  1312. return $this->url_extension;
  1313. }
  1314. /**
  1315. * Gets and sets the expires field. If not set will return the default
  1316. *
  1317. * @param int|null $var The new expires value.
  1318. * @return int The expires value
  1319. */
  1320. public function expires($var = null)
  1321. {
  1322. if ($var !== null) {
  1323. $this->expires = $var;
  1324. }
  1325. return $this->expires ?? Grav::instance()['config']->get('system.pages.expires');
  1326. }
  1327. /**
  1328. * Gets and sets the cache-control property. If not set it will return the default value (null)
  1329. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control for more details on valid options
  1330. *
  1331. * @param string|null $var
  1332. * @return string|null
  1333. */
  1334. public function cacheControl($var = null)
  1335. {
  1336. if ($var !== null) {
  1337. $this->cache_control = $var;
  1338. }
  1339. return $this->cache_control ?? Grav::instance()['config']->get('system.pages.cache_control');
  1340. }
  1341. /**
  1342. * Gets and sets the title for this Page. If no title is set, it will use the slug() to get a name
  1343. *
  1344. * @param string|null $var the title of the Page
  1345. * @return string the title of the Page
  1346. */
  1347. public function title($var = null)
  1348. {
  1349. if ($var !== null) {
  1350. $this->title = $var;
  1351. }
  1352. if (empty($this->title)) {
  1353. $this->title = ucfirst($this->slug());
  1354. }
  1355. return $this->title;
  1356. }
  1357. /**
  1358. * Gets and sets the menu name for this Page. This is the text that can be used specifically for navigation.
  1359. * If no menu field is set, it will use the title()
  1360. *
  1361. * @param string|null $var the menu field for the page
  1362. * @return string the menu field for the page
  1363. */
  1364. public function menu($var = null)
  1365. {
  1366. if ($var !== null) {
  1367. $this->menu = $var;
  1368. }
  1369. if (empty($this->menu)) {
  1370. $this->menu = $this->title();
  1371. }
  1372. return $this->menu;
  1373. }
  1374. /**
  1375. * Gets and Sets whether or not this Page is visible for navigation
  1376. *
  1377. * @param bool|null $var true if the page is visible
  1378. * @return bool true if the page is visible
  1379. */
  1380. public function visible($var = null)
  1381. {
  1382. if ($var !== null) {
  1383. $this->visible = (bool)$var;
  1384. }
  1385. if ($this->visible === null) {
  1386. // Set item visibility in menu if folder is different from slug
  1387. // eg folder = 01.Home and slug = Home
  1388. if (preg_match(PAGE_ORDER_PREFIX_REGEX, $this->folder)) {
  1389. $this->visible = true;
  1390. } else {
  1391. $this->visible = false;
  1392. }
  1393. }
  1394. return $this->visible;
  1395. }
  1396. /**
  1397. * Gets and Sets whether or not this Page is considered published
  1398. *
  1399. * @param bool|null $var true if the page is published
  1400. * @return bool true if the page is published
  1401. */
  1402. public function published($var = null)
  1403. {
  1404. if ($var !== null) {
  1405. $this->published = (bool)$var;
  1406. }
  1407. // If not published, should not be visible in menus either
  1408. if ($this->published === false) {
  1409. $this->visible = false;
  1410. }
  1411. return $this->published;
  1412. }
  1413. /**
  1414. * Gets and Sets the Page publish date
  1415. *
  1416. * @param string|null $var string representation of a date
  1417. * @return int unix timestamp representation of the date
  1418. */
  1419. public function publishDate($var = null)
  1420. {
  1421. if ($var !== null) {
  1422. $this->publish_date = Utils::date2timestamp($var, $this->dateformat);
  1423. }
  1424. return $this->publish_date;
  1425. }
  1426. /**
  1427. * Gets and Sets the Page unpublish date
  1428. *
  1429. * @param string|null $var string representation of a date
  1430. * @return int|null unix timestamp representation of the date
  1431. */
  1432. public function unpublishDate($var = null)
  1433. {
  1434. if ($var !== null) {
  1435. $this->unpublish_date = Utils::date2timestamp($var, $this->dateformat);
  1436. }
  1437. return $this->unpublish_date;
  1438. }
  1439. /**
  1440. * Gets and Sets whether or not this Page is routable, ie you can reach it
  1441. * via a URL.
  1442. * The page must be *routable* and *published*
  1443. *
  1444. * @param bool|null $var true if the page is routable
  1445. * @return bool true if the page is routable
  1446. */
  1447. public function routable($var = null)
  1448. {
  1449. if ($var !== null) {
  1450. $this->routable = (bool)$var;
  1451. }
  1452. return $this->routable && $this->published();
  1453. }
  1454. /**
  1455. * @param bool|null $var
  1456. * @return bool
  1457. */
  1458. public function ssl($var = null)
  1459. {
  1460. if ($var !== null) {
  1461. $this->ssl = (bool)$var;
  1462. }
  1463. return $this->ssl;
  1464. }
  1465. /**
  1466. * Gets and Sets the process setup for this Page. This is multi-dimensional array that consists of
  1467. * a simple array of arrays with the form array("markdown"=>true) for example
  1468. *
  1469. * @param array|null $var an Array of name value pairs where the name is the process and value is true or false
  1470. * @return array an Array of name value pairs where the name is the process and value is true or false
  1471. */
  1472. public function process($var = null)
  1473. {
  1474. if ($var !== null) {
  1475. $this->process = (array)$var;
  1476. }
  1477. return $this->process;
  1478. }
  1479. /**
  1480. * Returns the state of the debugger override setting for this page
  1481. *
  1482. * @return bool
  1483. */
  1484. public function debugger()
  1485. {
  1486. return !(isset($this->debugger) && $this->debugger === false);
  1487. }
  1488. /**
  1489. * Function to merge page metadata tags and build an array of Metadata objects
  1490. * that can then be rendered in the page.
  1491. *
  1492. * @param array|null $var an Array of metadata values to set
  1493. * @return array an Array of metadata values for the page
  1494. */
  1495. public function metadata($var = null)
  1496. {
  1497. if ($var !== null) {
  1498. $this->metadata = (array)$var;
  1499. }
  1500. // if not metadata yet, process it.
  1501. if (null === $this->metadata) {
  1502. $header_tag_http_equivs = ['content-type', 'default-style', 'refresh', 'x-ua-compatible', 'content-security-policy'];
  1503. $this->metadata = [];
  1504. // Set the Generator tag
  1505. $metadata = [
  1506. 'generator' => 'GravCMS'
  1507. ];
  1508. $config = Grav::instance()['config'];
  1509. $escape = !$config->get('system.strict_mode.twig_compat', false) || $config->get('system.twig.autoescape', true);
  1510. // Get initial metadata for the page
  1511. $metadata = array_merge($metadata, $config->get('site.metadata', []));
  1512. if (isset($this->header->metadata) && is_array($this->header->metadata)) {
  1513. // Merge any site.metadata settings in with page metadata
  1514. $metadata = array_merge($metadata, $this->header->metadata);
  1515. }
  1516. // Build an array of meta objects..
  1517. foreach ((array)$metadata as $key => $value) {
  1518. // Lowercase the key
  1519. $key = strtolower($key);
  1520. // If this is a property type metadata: "og", "twitter", "facebook" etc
  1521. // Backward compatibility for nested arrays in metas
  1522. if (is_array($value)) {
  1523. foreach ($value as $property => $prop_value) {
  1524. $prop_key = $key . ':' . $property;
  1525. $this->metadata[$prop_key] = [
  1526. 'name' => $prop_key,
  1527. 'property' => $prop_key,
  1528. 'content' => $escape ? htmlspecialchars($prop_value, ENT_QUOTES | ENT_HTML5, 'UTF-8') : $prop_value
  1529. ];
  1530. }
  1531. } else {
  1532. // If it this is a standard meta data type
  1533. if ($value) {
  1534. if (in_array($key, $header_tag_http_equivs, true)) {
  1535. $this->metadata[$key] = [
  1536. 'http_equiv' => $key,
  1537. 'content' => $escape ? htmlspecialchars($value, ENT_COMPAT, 'UTF-8') : $value
  1538. ];
  1539. } elseif ($key === 'charset') {
  1540. $this->metadata[$key] = ['charset' => $escape ? htmlspecialchars($value, ENT_QUOTES | ENT_HTML5, 'UTF-8') : $value];
  1541. } else {
  1542. // if it's a social metadata with separator, render as property
  1543. $separator = strpos($key, ':');
  1544. $hasSeparator = $separator && $separator < strlen($key) - 1;
  1545. $entry = [
  1546. 'content' => $escape ? htmlspecialchars($value, ENT_QUOTES | ENT_HTML5, 'UTF-8') : $value
  1547. ];
  1548. if ($hasSeparator && !Utils::startsWith($key, ['twitter', 'flattr'])) {
  1549. $entry['property'] = $key;
  1550. } else {
  1551. $entry['name'] = $key;
  1552. }
  1553. $this->metadata[$key] = $entry;
  1554. }
  1555. }
  1556. }
  1557. }
  1558. }
  1559. return $this->metadata;
  1560. }
  1561. /**
  1562. * Reset the metadata and pull from header again
  1563. */
  1564. public function resetMetadata()
  1565. {
  1566. $this->metadata = null;
  1567. }
  1568. /**
  1569. * Gets and Sets the slug for the Page. The slug is used in the URL routing. If not set it uses
  1570. * the parent folder from the path
  1571. *
  1572. * @param string|null $var the slug, e.g. 'my-blog'
  1573. * @return string the slug
  1574. */
  1575. public function slug($var = null)
  1576. {
  1577. if ($var !== null && $var !== '') {
  1578. $this->slug = $var;
  1579. }
  1580. if (empty($this->slug)) {
  1581. $this->slug = $this->adjustRouteCase(preg_replace(PAGE_ORDER_PREFIX_REGEX, '', $this->folder)) ?: null;
  1582. }
  1583. return $this->slug;
  1584. }
  1585. /**
  1586. * Get/set order number of this page.
  1587. *
  1588. * @param int|null $var
  1589. * @return string|bool
  1590. */
  1591. public function order($var = null)
  1592. {
  1593. if ($var !== null) {
  1594. $order = $var ? sprintf('%02d.', (int)$var) : '';
  1595. $this->folder($order . preg_replace(PAGE_ORDER_PREFIX_REGEX, '', $this->folder));
  1596. return $order;
  1597. }
  1598. preg_match(PAGE_ORDER_PREFIX_REGEX, $this->folder, $order);
  1599. return $order[0] ?? false;
  1600. }
  1601. /**
  1602. * Gets the URL for a page - alias of url().
  1603. *
  1604. * @param bool $include_host
  1605. * @return string the permalink
  1606. */
  1607. public function link($include_host = false)
  1608. {
  1609. return $this->url($include_host);
  1610. }
  1611. /**
  1612. * Gets the URL with host information, aka Permalink.
  1613. * @return string The permalink.
  1614. */
  1615. public function permalink()
  1616. {
  1617. return $this->url(true, false, true, true);
  1618. }
  1619. /**
  1620. * Returns the canonical URL for a page
  1621. *
  1622. * @param bool $include_lang
  1623. * @return string
  1624. */
  1625. public function canonical($include_lang = true)
  1626. {
  1627. return $this->url(true, true, $include_lang);
  1628. }
  1629. /**
  1630. * Gets the url for the Page.
  1631. *
  1632. * @param bool $include_host Defaults false, but true would include http://yourhost.com
  1633. * @param bool $canonical True to return the canonical URL
  1634. * @param bool $include_base Include base url on multisite as well as language code
  1635. * @param bool $raw_route
  1636. * @return string The url.
  1637. */
  1638. public function url($include_host = false, $canonical = false, $include_base = true, $raw_route = false)
  1639. {
  1640. // Override any URL when external_url is set
  1641. if (isset($this->external_url)) {
  1642. return $this->external_url;
  1643. }
  1644. $grav = Grav::instance();
  1645. /** @var Pages $pages */
  1646. $pages = $grav['pages'];
  1647. /** @var Config $config */
  1648. $config = $grav['config'];
  1649. // get base route (multi-site base and language)
  1650. $route = $include_base ? $pages->baseRoute() : '';
  1651. // add full route if configured to do so
  1652. if (!$include_host && $config->get('system.absolute_urls', false)) {
  1653. $include_host = true;
  1654. }
  1655. if ($canonical) {
  1656. $route .= $this->routeCanonical();
  1657. } elseif ($raw_route) {
  1658. $route .= $this->rawRoute();
  1659. } else {
  1660. $route .= $this->route();
  1661. }
  1662. /** @var Uri $uri */
  1663. $uri = $grav['uri'];
  1664. $url = $uri->rootUrl($include_host) . '/' . trim($route, '/') . $this->urlExtension();
  1665. return Uri::filterPath($url);
  1666. }
  1667. /**
  1668. * Gets the route for the page based on the route headers if available, else from
  1669. * the parents route and the current Page's slug.
  1670. *
  1671. * @param string|null $var Set new default route.
  1672. * @return string|null The route for the Page.
  1673. */
  1674. public function route($var = null)
  1675. {
  1676. if ($var !== null) {
  1677. $this->route = $var;
  1678. }
  1679. if (empty($this->route)) {
  1680. $baseRoute = null;
  1681. // calculate route based on parent slugs
  1682. $parent = $this->parent();
  1683. if (isset($parent)) {
  1684. if ($this->hide_home_route && $parent->route() === $this->home_route) {
  1685. $baseRoute = '';
  1686. } else {
  1687. $baseRoute = (string)$parent->route();
  1688. }
  1689. }
  1690. $this->route = isset($baseRoute) ? $baseRoute . '/' . $this->slug() : null;
  1691. if (!empty($this->routes) && isset($this->routes['default'])) {
  1692. $this->routes['aliases'][] = $this->route;
  1693. $this->route = $this->routes['default'];
  1694. return $this->route;
  1695. }
  1696. }
  1697. return $this->route;
  1698. }
  1699. /**
  1700. * Helper method to clear the route out so it regenerates next time you use it
  1701. */
  1702. public function unsetRouteSlug()
  1703. {
  1704. unset($this->route, $this->slug);
  1705. }
  1706. /**
  1707. * Gets and Sets the page raw route
  1708. *
  1709. * @param string|null $var
  1710. * @return null|string
  1711. */
  1712. public function rawRoute($var = null)
  1713. {
  1714. if ($var !== null) {
  1715. $this->raw_route = $var;
  1716. }
  1717. if (empty($this->raw_route)) {
  1718. $parent = $this->parent();
  1719. $baseRoute = $parent ? (string)$parent->rawRoute() : null;
  1720. $slug = $this->adjustRouteCase(preg_replace(PAGE_ORDER_PREFIX_REGEX, '', $this->folder));
  1721. $this->raw_route = isset($baseRoute) ? $baseRoute . '/' . $slug : null;
  1722. }
  1723. return $this->raw_route;
  1724. }
  1725. /**
  1726. * Gets the route aliases for the page based on page headers.
  1727. *
  1728. * @param array|null $var list of route aliases
  1729. * @return array The route aliases for the Page.
  1730. */
  1731. public function routeAliases($var = null)
  1732. {
  1733. if ($var !== null) {
  1734. $this->routes['aliases'] = (array)$var;
  1735. }
  1736. if (!empty($this->routes) && isset($this->routes['aliases'])) {
  1737. return $this->routes['aliases'];
  1738. }
  1739. return [];
  1740. }
  1741. /**
  1742. * Gets the canonical route for this page if its set. If provided it will use
  1743. * that value, else if it's `true` it will use the default route.
  1744. *
  1745. * @param string|null $var
  1746. * @return bool|string
  1747. */
  1748. public function routeCanonical($var = null)
  1749. {
  1750. if ($var !== null) {
  1751. $this->routes['canonical'] = $var;
  1752. }
  1753. if (!empty($this->routes) && isset($this->routes['canonical'])) {
  1754. return $this->routes['canonical'];
  1755. }
  1756. return $this->route();
  1757. }
  1758. /**
  1759. * Gets and sets the identifier for this Page object.
  1760. *
  1761. * @param string|null $var the identifier
  1762. * @return string the identifier
  1763. */
  1764. public function id($var = null)
  1765. {
  1766. if (null === $this->id) {
  1767. // We need to set unique id to avoid potential cache conflicts between pages.
  1768. $var = time() . md5($this->filePath());
  1769. }
  1770. if ($var !== null) {
  1771. // store unique per language
  1772. $active_lang = Grav::instance()['language']->getLanguage() ?: '';
  1773. $id = $active_lang . $var;
  1774. $this->id = $id;
  1775. }
  1776. return $this->id;
  1777. }
  1778. /**
  1779. * Gets and sets the modified timestamp.
  1780. *
  1781. * @param int|null $var modified unix timestamp
  1782. * @return int modified unix timestamp
  1783. */
  1784. public function modified($var = null)
  1785. {
  1786. if ($var !== null) {
  1787. $this->modified = $var;
  1788. }
  1789. return $this->modified;
  1790. }
  1791. /**
  1792. * Gets the redirect set in the header.
  1793. *
  1794. * @param string|null $var redirect url
  1795. * @return string|null
  1796. */
  1797. public function redirect($var = null)
  1798. {
  1799. if ($var !== null) {
  1800. $this->redirect = $var;
  1801. }
  1802. return $this->redirect ?: null;
  1803. }
  1804. /**
  1805. * Gets and sets the option to show the etag header for the page.
  1806. *
  1807. * @param bool|null $var show etag header
  1808. * @return bool show etag header
  1809. */
  1810. public function eTag($var = null): bool
  1811. {
  1812. if ($var !== null) {
  1813. $this->etag = $var;
  1814. }
  1815. if (!isset($this->etag)) {
  1816. $this->etag = (bool)Grav::instance()['config']->get('system.pages.etag');
  1817. }
  1818. return $this->etag ?? false;
  1819. }
  1820. /**
  1821. * Gets and sets the option to show the last_modified header for the page.
  1822. *
  1823. * @param bool|null $var show last_modified header
  1824. * @return bool show last_modified header
  1825. */
  1826. public function lastModified($var = null)
  1827. {
  1828. if ($var !== null) {
  1829. $this->last_modified = $var;
  1830. }
  1831. if (!isset($this->last_modified)) {
  1832. $this->last_modified = (bool)Grav::instance()['config']->get('system.pages.last_modified');
  1833. }
  1834. return $this->last_modified;
  1835. }
  1836. /**
  1837. * Gets and sets the path to the .md file for this Page object.
  1838. *
  1839. * @param string|null $var the file path
  1840. * @return string|null the file path
  1841. */
  1842. public function filePath($var = null)
  1843. {
  1844. if ($var !== null) {
  1845. // Filename of the page.
  1846. $this->name = Utils::basename($var);
  1847. // Folder of the page.
  1848. $this->folder = Utils::basename(dirname($var));
  1849. // Path to the page.
  1850. $this->path = dirname($var, 2);
  1851. }
  1852. return rtrim($this->path . '/' . $this->folder . '/' . ($this->name() ?: ''), '/');
  1853. }
  1854. /**
  1855. * Gets the relative path to the .md file
  1856. *
  1857. * @return string The relative file path
  1858. */
  1859. public function filePathClean()
  1860. {
  1861. return str_replace(GRAV_ROOT . DS, '', $this->filePath());
  1862. }
  1863. /**
  1864. * Returns the clean path to the page file
  1865. *
  1866. * @return string
  1867. */
  1868. public function relativePagePath()
  1869. {
  1870. return str_replace('/' . $this->name(), '', $this->filePathClean());
  1871. }
  1872. /**
  1873. * Gets and sets the path to the folder where the .md for this Page object resides.
  1874. * This is equivalent to the filePath but without the filename.
  1875. *
  1876. * @param string|null $var the path
  1877. * @return string|null the path
  1878. */
  1879. public function path($var = null)
  1880. {
  1881. if ($var !== null) {
  1882. // Folder of the page.
  1883. $this->folder = Utils::basename($var);
  1884. // Path to the page.
  1885. $this->path = dirname($var);
  1886. }
  1887. return $this->path ? $this->path . '/' . $this->folder : null;
  1888. }
  1889. /**
  1890. * Get/set the folder.
  1891. *
  1892. * @param string|null $var Optional path
  1893. * @return string|null
  1894. */
  1895. public function folder($var = null)
  1896. {
  1897. if ($var !== null) {
  1898. $this->folder = $var;
  1899. }
  1900. return $this->folder;
  1901. }
  1902. /**
  1903. * Gets and sets the date for this Page object. This is typically passed in via the page headers
  1904. *
  1905. * @param string|null $var string representation of a date
  1906. * @return int unix timestamp representation of the date
  1907. */
  1908. public function date($var = null)
  1909. {
  1910. if ($var !== null) {
  1911. $this->date = Utils::date2timestamp($var, $this->dateformat);
  1912. }
  1913. if (!$this->date) {
  1914. $this->date = $this->modified;
  1915. }
  1916. return $this->date;
  1917. }
  1918. /**
  1919. * Gets and sets the date format for this Page object. This is typically passed in via the page headers
  1920. * using typical PHP date string structure - http://php.net/manual/en/function.date.php
  1921. *
  1922. * @param string|null $var string representation of a date format
  1923. * @return string string representation of a date format
  1924. */
  1925. public function dateformat($var = null)
  1926. {
  1927. if ($var !== null) {
  1928. $this->dateformat = $var;
  1929. }
  1930. return $this->dateformat;
  1931. }
  1932. /**
  1933. * Gets and sets the order by which any sub-pages should be sorted.
  1934. *
  1935. * @param string|null $var the order, either "asc" or "desc"
  1936. * @return string the order, either "asc" or "desc"
  1937. * @deprecated 1.6
  1938. */
  1939. public function orderDir($var = null)
  1940. {
  1941. //user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6', E_USER_DEPRECATED);
  1942. if ($var !== null) {
  1943. $this->order_dir = $var;
  1944. }
  1945. if (empty($this->order_dir)) {
  1946. $this->order_dir = 'asc';
  1947. }
  1948. return $this->order_dir;
  1949. }
  1950. /**
  1951. * Gets and sets the order by which the sub-pages should be sorted.
  1952. *
  1953. * default - is the order based on the file system, ie 01.Home before 02.Advark
  1954. * title - is the order based on the title set in the pages
  1955. * date - is the order based on the date set in the pages
  1956. * folder - is the order based on the name of the folder with any numerics omitted
  1957. *
  1958. * @param string|null $var supported options include "default", "title", "date", and "folder"
  1959. * @return string supported options include "default", "title", "date", and "folder"
  1960. * @deprecated 1.6
  1961. */
  1962. public function orderBy($var = null)
  1963. {
  1964. //user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6', E_USER_DEPRECATED);
  1965. if ($var !== null) {
  1966. $this->order_by = $var;
  1967. }
  1968. return $this->order_by;
  1969. }
  1970. /**
  1971. * Gets the manual order set in the header.
  1972. *
  1973. * @param string|null $var supported options include "default", "title", "date", and "folder"
  1974. * @return array
  1975. * @deprecated 1.6
  1976. */
  1977. public function orderManual($var = null)
  1978. {
  1979. //user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6', E_USER_DEPRECATED);
  1980. if ($var !== null) {
  1981. $this->order_manual = $var;
  1982. }
  1983. return (array)$this->order_manual;
  1984. }
  1985. /**
  1986. * Gets and sets the maxCount field which describes how many sub-pages should be displayed if the
  1987. * sub_pages header property is set for this page object.
  1988. *
  1989. * @param int|null $var the maximum number of sub-pages
  1990. * @return int the maximum number of sub-pages
  1991. * @deprecated 1.6
  1992. */
  1993. public function maxCount($var = null)
  1994. {
  1995. //user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6', E_USER_DEPRECATED);
  1996. if ($var !== null) {
  1997. $this->max_count = (int)$var;
  1998. }
  1999. if (empty($this->max_count)) {
  2000. /** @var Config $config */
  2001. $config = Grav::instance()['config'];
  2002. $this->max_count = (int)$config->get('system.pages.list.count');
  2003. }
  2004. return $this->max_count;
  2005. }
  2006. /**
  2007. * Gets and sets the taxonomy array which defines which taxonomies this page identifies itself with.
  2008. *
  2009. * @param array|null $var an array of taxonomies
  2010. * @return array an array of taxonomies
  2011. */
  2012. public function taxonomy($var = null)
  2013. {
  2014. if ($var !== null) {
  2015. // make sure first level are arrays
  2016. array_walk($var, static function (&$value) {
  2017. $value = (array) $value;
  2018. });
  2019. // make sure all values are strings
  2020. array_walk_recursive($var, static function (&$value) {
  2021. $value = (string) $value;
  2022. });
  2023. $this->taxonomy = $var;
  2024. }
  2025. return $this->taxonomy;
  2026. }
  2027. /**
  2028. * Gets and sets the modular var that helps identify this page is a modular child
  2029. *
  2030. * @param bool|null $var true if modular_twig
  2031. * @return bool true if modular_twig
  2032. * @deprecated 1.7 Use ->isModule() or ->modularTwig() method instead.
  2033. */
  2034. public function modular($var = null)
  2035. {
  2036. user_error(__METHOD__ . '() is deprecated since Grav 1.7, use ->isModule() or ->modularTwig() method instead', E_USER_DEPRECATED);
  2037. return $this->modularTwig($var);
  2038. }
  2039. /**
  2040. * Gets and sets the modular_twig var that helps identify this page as a modular child page that will need
  2041. * twig processing handled differently from a regular page.
  2042. *
  2043. * @param bool|null $var true if modular_twig
  2044. * @return bool true if modular_twig
  2045. */
  2046. public function modularTwig($var = null)
  2047. {
  2048. if ($var !== null) {
  2049. $this->modular_twig = (bool)$var;
  2050. if ($var) {
  2051. $this->visible(false);
  2052. // some routable logic
  2053. if (empty($this->header->routable)) {
  2054. $this->routable = false;
  2055. }
  2056. }
  2057. }
  2058. return $this->modular_twig ?? false;
  2059. }
  2060. /**
  2061. * Gets the configured state of the processing method.
  2062. *
  2063. * @param string $process the process, eg "twig" or "markdown"
  2064. * @return bool whether or not the processing method is enabled for this Page
  2065. */
  2066. public function shouldProcess($process)
  2067. {
  2068. return (bool)($this->process[$process] ?? false);
  2069. }
  2070. /**
  2071. * Gets and Sets the parent object for this page
  2072. *
  2073. * @param PageInterface|null $var the parent page object
  2074. * @return PageInterface|null the parent page object if it exists.
  2075. */
  2076. public function parent(PageInterface $var = null)
  2077. {
  2078. if ($var) {
  2079. $this->parent = $var->path();
  2080. return $var;
  2081. }
  2082. /** @var Pages $pages */
  2083. $pages = Grav::instance()['pages'];
  2084. return $pages->get($this->parent);
  2085. }
  2086. /**
  2087. * Gets the top parent object for this page. Can return page itself.
  2088. *
  2089. * @return PageInterface The top parent page object.
  2090. */
  2091. public function topParent()
  2092. {
  2093. $topParent = $this;
  2094. while (true) {
  2095. $theParent = $topParent->parent();
  2096. if ($theParent !== null && $theParent->parent() !== null) {
  2097. $topParent = $theParent;
  2098. } else {
  2099. break;
  2100. }
  2101. }
  2102. return $topParent;
  2103. }
  2104. /**
  2105. * Returns children of this page.
  2106. *
  2107. * @return PageCollectionInterface|Collection
  2108. */
  2109. public function children()
  2110. {
  2111. /** @var Pages $pages */
  2112. $pages = Grav::instance()['pages'];
  2113. return $pages->children($this->path());
  2114. }
  2115. /**
  2116. * Check to see if this item is the first in an array of sub-pages.
  2117. *
  2118. * @return bool True if item is first.
  2119. */
  2120. public function isFirst()
  2121. {
  2122. $parent = $this->parent();
  2123. $collection = $parent ? $parent->collection('content', false) : null;
  2124. if ($collection instanceof Collection) {
  2125. return $collection->isFirst($this->path());
  2126. }
  2127. return true;
  2128. }
  2129. /**
  2130. * Check to see if this item is the last in an array of sub-pages.
  2131. *
  2132. * @return bool True if item is last
  2133. */
  2134. public function isLast()
  2135. {
  2136. $parent = $this->parent();
  2137. $collection = $parent ? $parent->collection('content', false) : null;
  2138. if ($collection instanceof Collection) {
  2139. return $collection->isLast($this->path());
  2140. }
  2141. return true;
  2142. }
  2143. /**
  2144. * Gets the previous sibling based on current position.
  2145. *
  2146. * @return PageInterface the previous Page item
  2147. */
  2148. public function prevSibling()
  2149. {
  2150. return $this->adjacentSibling(-1);
  2151. }
  2152. /**
  2153. * Gets the next sibling based on current position.
  2154. *
  2155. * @return PageInterface the next Page item
  2156. */
  2157. public function nextSibling()
  2158. {
  2159. return $this->adjacentSibling(1);
  2160. }
  2161. /**
  2162. * Returns the adjacent sibling based on a direction.
  2163. *
  2164. * @param int $direction either -1 or +1
  2165. * @return PageInterface|false the sibling page
  2166. */
  2167. public function adjacentSibling($direction = 1)
  2168. {
  2169. $parent = $this->parent();
  2170. $collection = $parent ? $parent->collection('content', false) : null;
  2171. if ($collection instanceof Collection) {
  2172. return $collection->adjacentSibling($this->path(), $direction);
  2173. }
  2174. return false;
  2175. }
  2176. /**
  2177. * Returns the item in the current position.
  2178. *
  2179. * @return int|null The index of the current page.
  2180. */
  2181. public function currentPosition()
  2182. {
  2183. $parent = $this->parent();
  2184. $collection = $parent ? $parent->collection('content', false) : null;
  2185. if ($collection instanceof Collection) {
  2186. return $collection->currentPosition($this->path());
  2187. }
  2188. return 1;
  2189. }
  2190. /**
  2191. * Returns whether or not this page is the currently active page requested via the URL.
  2192. *
  2193. * @return bool True if it is active
  2194. */
  2195. public function active()
  2196. {
  2197. $uri_path = rtrim(urldecode(Grav::instance()['uri']->path()), '/') ?: '/';
  2198. $routes = Grav::instance()['pages']->routes();
  2199. return isset($routes[$uri_path]) && $routes[$uri_path] === $this->path();
  2200. }
  2201. /**
  2202. * Returns whether or not this URI's URL contains the URL of the active page.
  2203. * Or in other words, is this page's URL in the current URL
  2204. *
  2205. * @return bool True if active child exists
  2206. */
  2207. public function activeChild()
  2208. {
  2209. $grav = Grav::instance();
  2210. /** @var Uri $uri */
  2211. $uri = $grav['uri'];
  2212. /** @var Pages $pages */
  2213. $pages = $grav['pages'];
  2214. $uri_path = rtrim(urldecode($uri->path()), '/');
  2215. $routes = $pages->routes();
  2216. if (isset($routes[$uri_path])) {
  2217. $page = $pages->find($uri->route());
  2218. /** @var PageInterface|null $child_page */
  2219. $child_page = $page ? $page->parent() : null;
  2220. while ($child_page && !$child_page->root()) {
  2221. if ($this->path() === $child_page->path()) {
  2222. return true;
  2223. }
  2224. $child_page = $child_page->parent();
  2225. }
  2226. }
  2227. return false;
  2228. }
  2229. /**
  2230. * Returns whether or not this page is the currently configured home page.
  2231. *
  2232. * @return bool True if it is the homepage
  2233. */
  2234. public function home()
  2235. {
  2236. $home = Grav::instance()['config']->get('system.home.alias');
  2237. return $this->route() === $home || $this->rawRoute() === $home;
  2238. }
  2239. /**
  2240. * Returns whether or not this page is the root node of the pages tree.
  2241. *
  2242. * @return bool True if it is the root
  2243. */
  2244. public function root()
  2245. {
  2246. return !$this->parent && !$this->name && !$this->visible;
  2247. }
  2248. /**
  2249. * Helper method to return an ancestor page.
  2250. *
  2251. * @param bool|null $lookup Name of the parent folder
  2252. * @return PageInterface page you were looking for if it exists
  2253. */
  2254. public function ancestor($lookup = null)
  2255. {
  2256. /** @var Pages $pages */
  2257. $pages = Grav::instance()['pages'];
  2258. return $pages->ancestor($this->route, $lookup);
  2259. }
  2260. /**
  2261. * Helper method to return an ancestor page to inherit from. The current
  2262. * page object is returned.
  2263. *
  2264. * @param string $field Name of the parent folder
  2265. * @return PageInterface
  2266. */
  2267. public function inherited($field)
  2268. {
  2269. [$inherited, $currentParams] = $this->getInheritedParams($field);
  2270. $this->modifyHeader($field, $currentParams);
  2271. return $inherited;
  2272. }
  2273. /**
  2274. * Helper method to return an ancestor field only to inherit from. The
  2275. * first occurrence of an ancestor field will be returned if at all.
  2276. *
  2277. * @param string $field Name of the parent folder
  2278. *
  2279. * @return array
  2280. */
  2281. public function inheritedField($field)
  2282. {
  2283. [$inherited, $currentParams] = $this->getInheritedParams($field);
  2284. return $currentParams;
  2285. }
  2286. /**
  2287. * Method that contains shared logic for inherited() and inheritedField()
  2288. *
  2289. * @param string $field Name of the parent folder
  2290. * @return array
  2291. */
  2292. protected function getInheritedParams($field)
  2293. {
  2294. $pages = Grav::instance()['pages'];
  2295. /** @var Pages $pages */
  2296. $inherited = $pages->inherited($this->route, $field);
  2297. $inheritedParams = $inherited ? (array)$inherited->value('header.' . $field) : [];
  2298. $currentParams = (array)$this->value('header.' . $field);
  2299. if ($inheritedParams && is_array($inheritedParams)) {
  2300. $currentParams = array_replace_recursive($inheritedParams, $currentParams);
  2301. }
  2302. return [$inherited, $currentParams];
  2303. }
  2304. /**
  2305. * Helper method to return a page.
  2306. *
  2307. * @param string $url the url of the page
  2308. * @param bool $all
  2309. *
  2310. * @return PageInterface page you were looking for if it exists
  2311. */
  2312. public function find($url, $all = false)
  2313. {
  2314. /** @var Pages $pages */
  2315. $pages = Grav::instance()['pages'];
  2316. return $pages->find($url, $all);
  2317. }
  2318. /**
  2319. * Get a collection of pages in the current context.
  2320. *
  2321. * @param string|array $params
  2322. * @param bool $pagination
  2323. *
  2324. * @return PageCollectionInterface|Collection
  2325. * @throws InvalidArgumentException
  2326. */
  2327. public function collection($params = 'content', $pagination = true)
  2328. {
  2329. if (is_string($params)) {
  2330. // Look into a page header field.
  2331. $params = (array)$this->value('header.' . $params);
  2332. } elseif (!is_array($params)) {
  2333. throw new InvalidArgumentException('Argument should be either header variable name or array of parameters');
  2334. }
  2335. $params['filter'] = ($params['filter'] ?? []) + ['translated' => true];
  2336. $context = [
  2337. 'pagination' => $pagination,
  2338. 'self' => $this
  2339. ];
  2340. /** @var Pages $pages */
  2341. $pages = Grav::instance()['pages'];
  2342. return $pages->getCollection($params, $context);
  2343. }
  2344. /**
  2345. * @param string|array $value
  2346. * @param bool $only_published
  2347. * @return PageCollectionInterface|Collection
  2348. */
  2349. public function evaluate($value, $only_published = true)
  2350. {
  2351. $params = [
  2352. 'items' => $value,
  2353. 'published' => $only_published
  2354. ];
  2355. $context = [
  2356. 'event' => false,
  2357. 'pagination' => false,
  2358. 'url_taxonomy_filters' => false,
  2359. 'self' => $this
  2360. ];
  2361. /** @var Pages $pages */
  2362. $pages = Grav::instance()['pages'];
  2363. return $pages->getCollection($params, $context);
  2364. }
  2365. /**
  2366. * Returns whether or not this Page object has a .md file associated with it or if its just a directory.
  2367. *
  2368. * @return bool True if its a page with a .md file associated
  2369. */
  2370. public function isPage()
  2371. {
  2372. if ($this->name) {
  2373. return true;
  2374. }
  2375. return false;
  2376. }
  2377. /**
  2378. * Returns whether or not this Page object is a directory or a page.
  2379. *
  2380. * @return bool True if its a directory
  2381. */
  2382. public function isDir()
  2383. {
  2384. return !$this->isPage();
  2385. }
  2386. /**
  2387. * @return bool
  2388. */
  2389. public function isModule(): bool
  2390. {
  2391. return $this->modularTwig();
  2392. }
  2393. /**
  2394. * Returns whether the page exists in the filesystem.
  2395. *
  2396. * @return bool
  2397. */
  2398. public function exists()
  2399. {
  2400. $file = $this->file();
  2401. return $file && $file->exists();
  2402. }
  2403. /**
  2404. * Returns whether or not the current folder exists
  2405. *
  2406. * @return bool
  2407. */
  2408. public function folderExists()
  2409. {
  2410. return file_exists($this->path());
  2411. }
  2412. /**
  2413. * Cleans the path.
  2414. *
  2415. * @param string $path the path
  2416. * @return string the path
  2417. */
  2418. protected function cleanPath($path)
  2419. {
  2420. $lastchunk = strrchr($path, DS);
  2421. if (strpos($lastchunk, ':') !== false) {
  2422. $path = str_replace($lastchunk, '', $path);
  2423. }
  2424. return $path;
  2425. }
  2426. /**
  2427. * Reorders all siblings according to a defined order
  2428. *
  2429. * @param array|null $new_order
  2430. */
  2431. protected function doReorder($new_order)
  2432. {
  2433. if (!$this->_original) {
  2434. return;
  2435. }
  2436. $pages = Grav::instance()['pages'];
  2437. $pages->init();
  2438. $this->_original->path($this->path());
  2439. $parent = $this->parent();
  2440. $siblings = $parent ? $parent->children() : null;
  2441. if ($siblings) {
  2442. $siblings->order('slug', 'asc', $new_order);
  2443. $counter = 0;
  2444. // Reorder all moved pages.
  2445. foreach ($siblings as $slug => $page) {
  2446. $order = (int)trim($page->order(), '.');
  2447. $counter++;
  2448. if ($order) {
  2449. if ($page->path() === $this->path() && $this->folderExists()) {
  2450. // Handle current page; we do want to change ordering number, but nothing else.
  2451. $this->order($counter);
  2452. $this->save(false);
  2453. } else {
  2454. // Handle all the other pages.
  2455. $page = $pages->get($page->path());
  2456. if ($page && $page->folderExists() && !$page->_action) {
  2457. $page = $page->move($this->parent());
  2458. $page->order($counter);
  2459. $page->save(false);
  2460. }
  2461. }
  2462. }
  2463. }
  2464. }
  2465. }
  2466. /**
  2467. * Moves or copies the page in filesystem.
  2468. *
  2469. * @internal
  2470. * @return void
  2471. * @throws Exception
  2472. */
  2473. protected function doRelocation()
  2474. {
  2475. if (!$this->_original) {
  2476. return;
  2477. }
  2478. if (is_dir($this->_original->path())) {
  2479. if ($this->_action === 'move') {
  2480. Folder::move($this->_original->path(), $this->path());
  2481. } elseif ($this->_action === 'copy') {
  2482. Folder::copy($this->_original->path(), $this->path());
  2483. }
  2484. }
  2485. if ($this->name() !== $this->_original->name()) {
  2486. $path = $this->path();
  2487. if (is_file($path . '/' . $this->_original->name())) {
  2488. rename($path . '/' . $this->_original->name(), $path . '/' . $this->name());
  2489. }
  2490. }
  2491. }
  2492. /**
  2493. * @return void
  2494. */
  2495. protected function setPublishState()
  2496. {
  2497. // Handle publishing dates if no explicit published option set
  2498. if (Grav::instance()['config']->get('system.pages.publish_dates') && !isset($this->header->published)) {
  2499. // unpublish if required, if not clear cache right before page should be unpublished
  2500. if ($this->unpublishDate()) {
  2501. if ($this->unpublishDate() < time()) {
  2502. $this->published(false);
  2503. } else {
  2504. $this->published();
  2505. Grav::instance()['cache']->setLifeTime($this->unpublishDate());
  2506. }
  2507. }
  2508. // publish if required, if not clear cache right before page is published
  2509. if ($this->publishDate() && $this->publishDate() > time()) {
  2510. $this->published(false);
  2511. Grav::instance()['cache']->setLifeTime($this->publishDate());
  2512. }
  2513. }
  2514. }
  2515. /**
  2516. * @param string $route
  2517. * @return string
  2518. */
  2519. protected function adjustRouteCase($route)
  2520. {
  2521. $case_insensitive = Grav::instance()['config']->get('system.force_lowercase_urls');
  2522. return $case_insensitive ? mb_strtolower($route) : $route;
  2523. }
  2524. /**
  2525. * Gets the Page Unmodified (original) version of the page.
  2526. *
  2527. * @return PageInterface The original version of the page.
  2528. */
  2529. public function getOriginal()
  2530. {
  2531. return $this->_original;
  2532. }
  2533. /**
  2534. * Gets the action.
  2535. *
  2536. * @return string|null The Action string.
  2537. */
  2538. public function getAction()
  2539. {
  2540. return $this->_action;
  2541. }
  2542. }