Page.php 84 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922
  1. <?php
  2. /**
  3. * @package Grav\Common\Page
  4. *
  5. * @copyright Copyright (c) 2015 - 2023 Trilby Media, LLC. All rights reserved.
  6. * @license MIT License; see LICENSE file for details.
  7. */
  8. namespace Grav\Common\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. if (!isset($_POST['blueprint'])) {
  1118. return $this->template();
  1119. }
  1120. $post_value = $_POST['blueprint'];
  1121. $sanitized_value = htmlspecialchars(strip_tags($post_value), ENT_QUOTES, 'UTF-8');
  1122. return $sanitized_value ?: $this->template();
  1123. }
  1124. /**
  1125. * Validate page header.
  1126. *
  1127. * @return void
  1128. * @throws Exception
  1129. */
  1130. public function validate()
  1131. {
  1132. $blueprints = $this->blueprints();
  1133. $blueprints->validate($this->toArray());
  1134. }
  1135. /**
  1136. * Filter page header from illegal contents.
  1137. *
  1138. * @return void
  1139. */
  1140. public function filter()
  1141. {
  1142. $blueprints = $this->blueprints();
  1143. $values = $blueprints->filter($this->toArray());
  1144. if ($values && isset($values['header'])) {
  1145. $this->header($values['header']);
  1146. }
  1147. }
  1148. /**
  1149. * Get unknown header variables.
  1150. *
  1151. * @return array
  1152. */
  1153. public function extra()
  1154. {
  1155. $blueprints = $this->blueprints();
  1156. return $blueprints->extra($this->toArray()['header'], 'header.');
  1157. }
  1158. /**
  1159. * Convert page to an array.
  1160. *
  1161. * @return array
  1162. */
  1163. public function toArray()
  1164. {
  1165. return [
  1166. 'header' => (array)$this->header(),
  1167. 'content' => (string)$this->value('content')
  1168. ];
  1169. }
  1170. /**
  1171. * Convert page to YAML encoded string.
  1172. *
  1173. * @return string
  1174. */
  1175. public function toYaml()
  1176. {
  1177. return Yaml::dump($this->toArray(), 20);
  1178. }
  1179. /**
  1180. * Convert page to JSON encoded string.
  1181. *
  1182. * @return string
  1183. */
  1184. public function toJson()
  1185. {
  1186. return json_encode($this->toArray());
  1187. }
  1188. /**
  1189. * @return string
  1190. */
  1191. public function getCacheKey(): string
  1192. {
  1193. return $this->id();
  1194. }
  1195. /**
  1196. * Gets and sets the associated media as found in the page folder.
  1197. *
  1198. * @param Media|null $var Representation of associated media.
  1199. * @return Media Representation of associated media.
  1200. */
  1201. public function media($var = null)
  1202. {
  1203. if ($var) {
  1204. $this->setMedia($var);
  1205. }
  1206. /** @var Media $media */
  1207. $media = $this->getMedia();
  1208. return $media;
  1209. }
  1210. /**
  1211. * Get filesystem path to the associated media.
  1212. *
  1213. * @return string|null
  1214. */
  1215. public function getMediaFolder()
  1216. {
  1217. return $this->path();
  1218. }
  1219. /**
  1220. * Get display order for the associated media.
  1221. *
  1222. * @return array Empty array means default ordering.
  1223. */
  1224. public function getMediaOrder()
  1225. {
  1226. $header = $this->header();
  1227. return isset($header->media_order) ? array_map('trim', explode(',', (string)$header->media_order)) : [];
  1228. }
  1229. /**
  1230. * Gets and sets the name field. If no name field is set, it will return 'default.md'.
  1231. *
  1232. * @param string|null $var The name of this page.
  1233. * @return string The name of this page.
  1234. */
  1235. public function name($var = null)
  1236. {
  1237. if ($var !== null) {
  1238. $this->name = $var;
  1239. }
  1240. return $this->name ?: 'default.md';
  1241. }
  1242. /**
  1243. * Returns child page type.
  1244. *
  1245. * @return string
  1246. */
  1247. public function childType()
  1248. {
  1249. return isset($this->header->child_type) ? (string)$this->header->child_type : '';
  1250. }
  1251. /**
  1252. * Gets and sets the template field. This is used to find the correct Twig template file to render.
  1253. * If no field is set, it will return the name without the .md extension
  1254. *
  1255. * @param string|null $var the template name
  1256. * @return string the template name
  1257. */
  1258. public function template($var = null)
  1259. {
  1260. if ($var !== null) {
  1261. $this->template = $var;
  1262. }
  1263. if (empty($this->template)) {
  1264. $this->template = ($this->isModule() ? 'modular/' : '') . str_replace($this->extension(), '', $this->name());
  1265. }
  1266. return $this->template;
  1267. }
  1268. /**
  1269. * Allows a page to override the output render format, usually the extension provided in the URL.
  1270. * (e.g. `html`, `json`, `xml`, etc).
  1271. *
  1272. * @param string|null $var
  1273. * @return string
  1274. */
  1275. public function templateFormat($var = null)
  1276. {
  1277. if (null !== $var) {
  1278. $this->template_format = is_string($var) ? $var : null;
  1279. }
  1280. if (!isset($this->template_format)) {
  1281. $this->template_format = ltrim($this->header->append_url_extension ?? Utils::getPageFormat(), '.');
  1282. }
  1283. return $this->template_format;
  1284. }
  1285. /**
  1286. * Gets and sets the extension field.
  1287. *
  1288. * @param string|null $var
  1289. * @return string
  1290. */
  1291. public function extension($var = null)
  1292. {
  1293. if ($var !== null) {
  1294. $this->extension = $var;
  1295. }
  1296. if (empty($this->extension)) {
  1297. $this->extension = '.' . Utils::pathinfo($this->name(), PATHINFO_EXTENSION);
  1298. }
  1299. return $this->extension;
  1300. }
  1301. /**
  1302. * Returns the page extension, got from the page `url_extension` config and falls back to the
  1303. * system config `system.pages.append_url_extension`.
  1304. *
  1305. * @return string The extension of this page. For example `.html`
  1306. */
  1307. public function urlExtension()
  1308. {
  1309. if ($this->home()) {
  1310. return '';
  1311. }
  1312. // if not set in the page get the value from system config
  1313. if (null === $this->url_extension) {
  1314. $this->url_extension = Grav::instance()['config']->get('system.pages.append_url_extension', '');
  1315. }
  1316. return $this->url_extension;
  1317. }
  1318. /**
  1319. * Gets and sets the expires field. If not set will return the default
  1320. *
  1321. * @param int|null $var The new expires value.
  1322. * @return int The expires value
  1323. */
  1324. public function expires($var = null)
  1325. {
  1326. if ($var !== null) {
  1327. $this->expires = $var;
  1328. }
  1329. return $this->expires ?? Grav::instance()['config']->get('system.pages.expires');
  1330. }
  1331. /**
  1332. * Gets and sets the cache-control property. If not set it will return the default value (null)
  1333. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control for more details on valid options
  1334. *
  1335. * @param string|null $var
  1336. * @return string|null
  1337. */
  1338. public function cacheControl($var = null)
  1339. {
  1340. if ($var !== null) {
  1341. $this->cache_control = $var;
  1342. }
  1343. return $this->cache_control ?? Grav::instance()['config']->get('system.pages.cache_control');
  1344. }
  1345. /**
  1346. * Gets and sets the title for this Page. If no title is set, it will use the slug() to get a name
  1347. *
  1348. * @param string|null $var the title of the Page
  1349. * @return string the title of the Page
  1350. */
  1351. public function title($var = null)
  1352. {
  1353. if ($var !== null) {
  1354. $this->title = $var;
  1355. }
  1356. if (empty($this->title)) {
  1357. $this->title = ucfirst($this->slug());
  1358. }
  1359. return $this->title;
  1360. }
  1361. /**
  1362. * Gets and sets the menu name for this Page. This is the text that can be used specifically for navigation.
  1363. * If no menu field is set, it will use the title()
  1364. *
  1365. * @param string|null $var the menu field for the page
  1366. * @return string the menu field for the page
  1367. */
  1368. public function menu($var = null)
  1369. {
  1370. if ($var !== null) {
  1371. $this->menu = $var;
  1372. }
  1373. if (empty($this->menu)) {
  1374. $this->menu = $this->title();
  1375. }
  1376. return $this->menu;
  1377. }
  1378. /**
  1379. * Gets and Sets whether or not this Page is visible for navigation
  1380. *
  1381. * @param bool|null $var true if the page is visible
  1382. * @return bool true if the page is visible
  1383. */
  1384. public function visible($var = null)
  1385. {
  1386. if ($var !== null) {
  1387. $this->visible = (bool)$var;
  1388. }
  1389. if ($this->visible === null) {
  1390. // Set item visibility in menu if folder is different from slug
  1391. // eg folder = 01.Home and slug = Home
  1392. if (preg_match(PAGE_ORDER_PREFIX_REGEX, $this->folder)) {
  1393. $this->visible = true;
  1394. } else {
  1395. $this->visible = false;
  1396. }
  1397. }
  1398. return $this->visible;
  1399. }
  1400. /**
  1401. * Gets and Sets whether or not this Page is considered published
  1402. *
  1403. * @param bool|null $var true if the page is published
  1404. * @return bool true if the page is published
  1405. */
  1406. public function published($var = null)
  1407. {
  1408. if ($var !== null) {
  1409. $this->published = (bool)$var;
  1410. }
  1411. // If not published, should not be visible in menus either
  1412. if ($this->published === false) {
  1413. $this->visible = false;
  1414. }
  1415. return $this->published;
  1416. }
  1417. /**
  1418. * Gets and Sets the Page publish date
  1419. *
  1420. * @param string|null $var string representation of a date
  1421. * @return int unix timestamp representation of the date
  1422. */
  1423. public function publishDate($var = null)
  1424. {
  1425. if ($var !== null) {
  1426. $this->publish_date = Utils::date2timestamp($var, $this->dateformat);
  1427. }
  1428. return $this->publish_date;
  1429. }
  1430. /**
  1431. * Gets and Sets the Page unpublish date
  1432. *
  1433. * @param string|null $var string representation of a date
  1434. * @return int|null unix timestamp representation of the date
  1435. */
  1436. public function unpublishDate($var = null)
  1437. {
  1438. if ($var !== null) {
  1439. $this->unpublish_date = Utils::date2timestamp($var, $this->dateformat);
  1440. }
  1441. return $this->unpublish_date;
  1442. }
  1443. /**
  1444. * Gets and Sets whether or not this Page is routable, ie you can reach it
  1445. * via a URL.
  1446. * The page must be *routable* and *published*
  1447. *
  1448. * @param bool|null $var true if the page is routable
  1449. * @return bool true if the page is routable
  1450. */
  1451. public function routable($var = null)
  1452. {
  1453. if ($var !== null) {
  1454. $this->routable = (bool)$var;
  1455. }
  1456. return $this->routable && $this->published();
  1457. }
  1458. /**
  1459. * @param bool|null $var
  1460. * @return bool
  1461. */
  1462. public function ssl($var = null)
  1463. {
  1464. if ($var !== null) {
  1465. $this->ssl = (bool)$var;
  1466. }
  1467. return $this->ssl;
  1468. }
  1469. /**
  1470. * Gets and Sets the process setup for this Page. This is multi-dimensional array that consists of
  1471. * a simple array of arrays with the form array("markdown"=>true) for example
  1472. *
  1473. * @param array|null $var an Array of name value pairs where the name is the process and value is true or false
  1474. * @return array an Array of name value pairs where the name is the process and value is true or false
  1475. */
  1476. public function process($var = null)
  1477. {
  1478. if ($var !== null) {
  1479. $this->process = (array)$var;
  1480. }
  1481. return $this->process;
  1482. }
  1483. /**
  1484. * Returns the state of the debugger override setting for this page
  1485. *
  1486. * @return bool
  1487. */
  1488. public function debugger()
  1489. {
  1490. return !(isset($this->debugger) && $this->debugger === false);
  1491. }
  1492. /**
  1493. * Function to merge page metadata tags and build an array of Metadata objects
  1494. * that can then be rendered in the page.
  1495. *
  1496. * @param array|null $var an Array of metadata values to set
  1497. * @return array an Array of metadata values for the page
  1498. */
  1499. public function metadata($var = null)
  1500. {
  1501. if ($var !== null) {
  1502. $this->metadata = (array)$var;
  1503. }
  1504. // if not metadata yet, process it.
  1505. if (null === $this->metadata) {
  1506. $header_tag_http_equivs = ['content-type', 'default-style', 'refresh', 'x-ua-compatible', 'content-security-policy'];
  1507. $this->metadata = [];
  1508. // Set the Generator tag
  1509. $metadata = [
  1510. 'generator' => 'GravCMS'
  1511. ];
  1512. $config = Grav::instance()['config'];
  1513. $escape = !$config->get('system.strict_mode.twig_compat', false) || $config->get('system.twig.autoescape', true);
  1514. // Get initial metadata for the page
  1515. $metadata = array_merge($metadata, $config->get('site.metadata', []));
  1516. if (isset($this->header->metadata) && is_array($this->header->metadata)) {
  1517. // Merge any site.metadata settings in with page metadata
  1518. $metadata = array_merge($metadata, $this->header->metadata);
  1519. }
  1520. // Build an array of meta objects..
  1521. foreach ((array)$metadata as $key => $value) {
  1522. // Lowercase the key
  1523. $key = strtolower($key);
  1524. // If this is a property type metadata: "og", "twitter", "facebook" etc
  1525. // Backward compatibility for nested arrays in metas
  1526. if (is_array($value)) {
  1527. foreach ($value as $property => $prop_value) {
  1528. $prop_key = $key . ':' . $property;
  1529. $this->metadata[$prop_key] = [
  1530. 'name' => $prop_key,
  1531. 'property' => $prop_key,
  1532. 'content' => $escape ? htmlspecialchars($prop_value, ENT_QUOTES | ENT_HTML5, 'UTF-8') : $prop_value
  1533. ];
  1534. }
  1535. } else {
  1536. // If it this is a standard meta data type
  1537. if ($value) {
  1538. if (in_array($key, $header_tag_http_equivs, true)) {
  1539. $this->metadata[$key] = [
  1540. 'http_equiv' => $key,
  1541. 'content' => $escape ? htmlspecialchars($value, ENT_COMPAT, 'UTF-8') : $value
  1542. ];
  1543. } elseif ($key === 'charset') {
  1544. $this->metadata[$key] = ['charset' => $escape ? htmlspecialchars($value, ENT_QUOTES | ENT_HTML5, 'UTF-8') : $value];
  1545. } else {
  1546. // if it's a social metadata with separator, render as property
  1547. $separator = strpos($key, ':');
  1548. $hasSeparator = $separator && $separator < strlen($key) - 1;
  1549. $entry = [
  1550. 'content' => $escape ? htmlspecialchars($value, ENT_QUOTES | ENT_HTML5, 'UTF-8') : $value
  1551. ];
  1552. if ($hasSeparator && !Utils::startsWith($key, ['twitter', 'flattr'])) {
  1553. $entry['property'] = $key;
  1554. } else {
  1555. $entry['name'] = $key;
  1556. }
  1557. $this->metadata[$key] = $entry;
  1558. }
  1559. }
  1560. }
  1561. }
  1562. }
  1563. return $this->metadata;
  1564. }
  1565. /**
  1566. * Reset the metadata and pull from header again
  1567. */
  1568. public function resetMetadata()
  1569. {
  1570. $this->metadata = null;
  1571. }
  1572. /**
  1573. * Gets and Sets the slug for the Page. The slug is used in the URL routing. If not set it uses
  1574. * the parent folder from the path
  1575. *
  1576. * @param string|null $var the slug, e.g. 'my-blog'
  1577. * @return string the slug
  1578. */
  1579. public function slug($var = null)
  1580. {
  1581. if ($var !== null && $var !== '') {
  1582. $this->slug = $var;
  1583. }
  1584. if (empty($this->slug)) {
  1585. $this->slug = $this->adjustRouteCase(preg_replace(PAGE_ORDER_PREFIX_REGEX, '', (string) $this->folder)) ?: null;
  1586. }
  1587. return $this->slug;
  1588. }
  1589. /**
  1590. * Get/set order number of this page.
  1591. *
  1592. * @param int|null $var
  1593. * @return string|bool
  1594. */
  1595. public function order($var = null)
  1596. {
  1597. if ($var !== null) {
  1598. $order = $var ? sprintf('%02d.', (int)$var) : '';
  1599. $this->folder($order . preg_replace(PAGE_ORDER_PREFIX_REGEX, '', $this->folder));
  1600. return $order;
  1601. }
  1602. preg_match(PAGE_ORDER_PREFIX_REGEX, $this->folder, $order);
  1603. return $order[0] ?? false;
  1604. }
  1605. /**
  1606. * Gets the URL for a page - alias of url().
  1607. *
  1608. * @param bool $include_host
  1609. * @return string the permalink
  1610. */
  1611. public function link($include_host = false)
  1612. {
  1613. return $this->url($include_host);
  1614. }
  1615. /**
  1616. * Gets the URL with host information, aka Permalink.
  1617. * @return string The permalink.
  1618. */
  1619. public function permalink()
  1620. {
  1621. return $this->url(true, false, true, true);
  1622. }
  1623. /**
  1624. * Returns the canonical URL for a page
  1625. *
  1626. * @param bool $include_lang
  1627. * @return string
  1628. */
  1629. public function canonical($include_lang = true)
  1630. {
  1631. return $this->url(true, true, $include_lang);
  1632. }
  1633. /**
  1634. * Gets the url for the Page.
  1635. *
  1636. * @param bool $include_host Defaults false, but true would include http://yourhost.com
  1637. * @param bool $canonical True to return the canonical URL
  1638. * @param bool $include_base Include base url on multisite as well as language code
  1639. * @param bool $raw_route
  1640. * @return string The url.
  1641. */
  1642. public function url($include_host = false, $canonical = false, $include_base = true, $raw_route = false)
  1643. {
  1644. // Override any URL when external_url is set
  1645. if (isset($this->external_url)) {
  1646. return $this->external_url;
  1647. }
  1648. $grav = Grav::instance();
  1649. /** @var Pages $pages */
  1650. $pages = $grav['pages'];
  1651. /** @var Config $config */
  1652. $config = $grav['config'];
  1653. // get base route (multi-site base and language)
  1654. $route = $include_base ? $pages->baseRoute() : '';
  1655. // add full route if configured to do so
  1656. if (!$include_host && $config->get('system.absolute_urls', false)) {
  1657. $include_host = true;
  1658. }
  1659. if ($canonical) {
  1660. $route .= $this->routeCanonical();
  1661. } elseif ($raw_route) {
  1662. $route .= $this->rawRoute();
  1663. } else {
  1664. $route .= $this->route();
  1665. }
  1666. /** @var Uri $uri */
  1667. $uri = $grav['uri'];
  1668. $url = $uri->rootUrl($include_host) . '/' . trim($route, '/') . $this->urlExtension();
  1669. return Uri::filterPath($url);
  1670. }
  1671. /**
  1672. * Gets the route for the page based on the route headers if available, else from
  1673. * the parents route and the current Page's slug.
  1674. *
  1675. * @param string|null $var Set new default route.
  1676. * @return string|null The route for the Page.
  1677. */
  1678. public function route($var = null)
  1679. {
  1680. if ($var !== null) {
  1681. $this->route = $var;
  1682. }
  1683. if (empty($this->route)) {
  1684. $baseRoute = null;
  1685. // calculate route based on parent slugs
  1686. $parent = $this->parent();
  1687. if (isset($parent)) {
  1688. if ($this->hide_home_route && $parent->route() === $this->home_route) {
  1689. $baseRoute = '';
  1690. } else {
  1691. $baseRoute = (string)$parent->route();
  1692. }
  1693. }
  1694. $this->route = isset($baseRoute) ? $baseRoute . '/' . $this->slug() : null;
  1695. if (!empty($this->routes) && isset($this->routes['default'])) {
  1696. $this->routes['aliases'][] = $this->route;
  1697. $this->route = $this->routes['default'];
  1698. return $this->route;
  1699. }
  1700. }
  1701. return $this->route;
  1702. }
  1703. /**
  1704. * Helper method to clear the route out so it regenerates next time you use it
  1705. */
  1706. public function unsetRouteSlug()
  1707. {
  1708. unset($this->route, $this->slug);
  1709. }
  1710. /**
  1711. * Gets and Sets the page raw route
  1712. *
  1713. * @param string|null $var
  1714. * @return null|string
  1715. */
  1716. public function rawRoute($var = null)
  1717. {
  1718. if ($var !== null) {
  1719. $this->raw_route = $var;
  1720. }
  1721. if (empty($this->raw_route)) {
  1722. $parent = $this->parent();
  1723. $baseRoute = $parent ? (string)$parent->rawRoute() : null;
  1724. $slug = $this->adjustRouteCase(preg_replace(PAGE_ORDER_PREFIX_REGEX, '', $this->folder));
  1725. $this->raw_route = isset($baseRoute) ? $baseRoute . '/' . $slug : null;
  1726. }
  1727. return $this->raw_route;
  1728. }
  1729. /**
  1730. * Gets the route aliases for the page based on page headers.
  1731. *
  1732. * @param array|null $var list of route aliases
  1733. * @return array The route aliases for the Page.
  1734. */
  1735. public function routeAliases($var = null)
  1736. {
  1737. if ($var !== null) {
  1738. $this->routes['aliases'] = (array)$var;
  1739. }
  1740. if (!empty($this->routes) && isset($this->routes['aliases'])) {
  1741. return $this->routes['aliases'];
  1742. }
  1743. return [];
  1744. }
  1745. /**
  1746. * Gets the canonical route for this page if its set. If provided it will use
  1747. * that value, else if it's `true` it will use the default route.
  1748. *
  1749. * @param string|null $var
  1750. * @return bool|string
  1751. */
  1752. public function routeCanonical($var = null)
  1753. {
  1754. if ($var !== null) {
  1755. $this->routes['canonical'] = $var;
  1756. }
  1757. if (!empty($this->routes) && isset($this->routes['canonical'])) {
  1758. return $this->routes['canonical'];
  1759. }
  1760. return $this->route();
  1761. }
  1762. /**
  1763. * Gets and sets the identifier for this Page object.
  1764. *
  1765. * @param string|null $var the identifier
  1766. * @return string the identifier
  1767. */
  1768. public function id($var = null)
  1769. {
  1770. if (null === $this->id) {
  1771. // We need to set unique id to avoid potential cache conflicts between pages.
  1772. $var = time() . md5($this->filePath());
  1773. }
  1774. if ($var !== null) {
  1775. // store unique per language
  1776. $active_lang = Grav::instance()['language']->getLanguage() ?: '';
  1777. $id = $active_lang . $var;
  1778. $this->id = $id;
  1779. }
  1780. return $this->id;
  1781. }
  1782. /**
  1783. * Gets and sets the modified timestamp.
  1784. *
  1785. * @param int|null $var modified unix timestamp
  1786. * @return int modified unix timestamp
  1787. */
  1788. public function modified($var = null)
  1789. {
  1790. if ($var !== null) {
  1791. $this->modified = $var;
  1792. }
  1793. return $this->modified;
  1794. }
  1795. /**
  1796. * Gets the redirect set in the header.
  1797. *
  1798. * @param string|null $var redirect url
  1799. * @return string|null
  1800. */
  1801. public function redirect($var = null)
  1802. {
  1803. if ($var !== null) {
  1804. $this->redirect = $var;
  1805. }
  1806. return $this->redirect ?: null;
  1807. }
  1808. /**
  1809. * Gets and sets the option to show the etag header for the page.
  1810. *
  1811. * @param bool|null $var show etag header
  1812. * @return bool show etag header
  1813. */
  1814. public function eTag($var = null): bool
  1815. {
  1816. if ($var !== null) {
  1817. $this->etag = $var;
  1818. }
  1819. if (!isset($this->etag)) {
  1820. $this->etag = (bool)Grav::instance()['config']->get('system.pages.etag');
  1821. }
  1822. return $this->etag ?? false;
  1823. }
  1824. /**
  1825. * Gets and sets the option to show the last_modified header for the page.
  1826. *
  1827. * @param bool|null $var show last_modified header
  1828. * @return bool show last_modified header
  1829. */
  1830. public function lastModified($var = null)
  1831. {
  1832. if ($var !== null) {
  1833. $this->last_modified = $var;
  1834. }
  1835. if (!isset($this->last_modified)) {
  1836. $this->last_modified = (bool)Grav::instance()['config']->get('system.pages.last_modified');
  1837. }
  1838. return $this->last_modified;
  1839. }
  1840. /**
  1841. * Gets and sets the path to the .md file for this Page object.
  1842. *
  1843. * @param string|null $var the file path
  1844. * @return string|null the file path
  1845. */
  1846. public function filePath($var = null)
  1847. {
  1848. if ($var !== null) {
  1849. // Filename of the page.
  1850. $this->name = Utils::basename($var);
  1851. // Folder of the page.
  1852. $this->folder = Utils::basename(dirname($var));
  1853. // Path to the page.
  1854. $this->path = dirname($var, 2);
  1855. }
  1856. return rtrim($this->path . '/' . $this->folder . '/' . ($this->name() ?: ''), '/');
  1857. }
  1858. /**
  1859. * Gets the relative path to the .md file
  1860. *
  1861. * @return string The relative file path
  1862. */
  1863. public function filePathClean()
  1864. {
  1865. return str_replace(GRAV_ROOT . DS, '', $this->filePath());
  1866. }
  1867. /**
  1868. * Returns the clean path to the page file
  1869. *
  1870. * @return string
  1871. */
  1872. public function relativePagePath()
  1873. {
  1874. return str_replace('/' . $this->name(), '', $this->filePathClean());
  1875. }
  1876. /**
  1877. * Gets and sets the path to the folder where the .md for this Page object resides.
  1878. * This is equivalent to the filePath but without the filename.
  1879. *
  1880. * @param string|null $var the path
  1881. * @return string|null the path
  1882. */
  1883. public function path($var = null)
  1884. {
  1885. if ($var !== null) {
  1886. // Folder of the page.
  1887. $this->folder = Utils::basename($var);
  1888. // Path to the page.
  1889. $this->path = dirname($var);
  1890. }
  1891. return $this->path ? $this->path . '/' . $this->folder : null;
  1892. }
  1893. /**
  1894. * Get/set the folder.
  1895. *
  1896. * @param string|null $var Optional path
  1897. * @return string|null
  1898. */
  1899. public function folder($var = null)
  1900. {
  1901. if ($var !== null) {
  1902. $this->folder = $var;
  1903. }
  1904. return $this->folder;
  1905. }
  1906. /**
  1907. * Gets and sets the date for this Page object. This is typically passed in via the page headers
  1908. *
  1909. * @param string|null $var string representation of a date
  1910. * @return int unix timestamp representation of the date
  1911. */
  1912. public function date($var = null)
  1913. {
  1914. if ($var !== null) {
  1915. $this->date = Utils::date2timestamp($var, $this->dateformat);
  1916. }
  1917. if (!$this->date) {
  1918. $this->date = $this->modified;
  1919. }
  1920. return $this->date;
  1921. }
  1922. /**
  1923. * Gets and sets the date format for this Page object. This is typically passed in via the page headers
  1924. * using typical PHP date string structure - http://php.net/manual/en/function.date.php
  1925. *
  1926. * @param string|null $var string representation of a date format
  1927. * @return string string representation of a date format
  1928. */
  1929. public function dateformat($var = null)
  1930. {
  1931. if ($var !== null) {
  1932. $this->dateformat = $var;
  1933. }
  1934. return $this->dateformat;
  1935. }
  1936. /**
  1937. * Gets and sets the order by which any sub-pages should be sorted.
  1938. *
  1939. * @param string|null $var the order, either "asc" or "desc"
  1940. * @return string the order, either "asc" or "desc"
  1941. * @deprecated 1.6
  1942. */
  1943. public function orderDir($var = null)
  1944. {
  1945. //user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6', E_USER_DEPRECATED);
  1946. if ($var !== null) {
  1947. $this->order_dir = $var;
  1948. }
  1949. if (empty($this->order_dir)) {
  1950. $this->order_dir = 'asc';
  1951. }
  1952. return $this->order_dir;
  1953. }
  1954. /**
  1955. * Gets and sets the order by which the sub-pages should be sorted.
  1956. *
  1957. * default - is the order based on the file system, ie 01.Home before 02.Advark
  1958. * title - is the order based on the title set in the pages
  1959. * date - is the order based on the date set in the pages
  1960. * folder - is the order based on the name of the folder with any numerics omitted
  1961. *
  1962. * @param string|null $var supported options include "default", "title", "date", and "folder"
  1963. * @return string supported options include "default", "title", "date", and "folder"
  1964. * @deprecated 1.6
  1965. */
  1966. public function orderBy($var = null)
  1967. {
  1968. //user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6', E_USER_DEPRECATED);
  1969. if ($var !== null) {
  1970. $this->order_by = $var;
  1971. }
  1972. return $this->order_by;
  1973. }
  1974. /**
  1975. * Gets the manual order set in the header.
  1976. *
  1977. * @param string|null $var supported options include "default", "title", "date", and "folder"
  1978. * @return array
  1979. * @deprecated 1.6
  1980. */
  1981. public function orderManual($var = null)
  1982. {
  1983. //user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6', E_USER_DEPRECATED);
  1984. if ($var !== null) {
  1985. $this->order_manual = $var;
  1986. }
  1987. return (array)$this->order_manual;
  1988. }
  1989. /**
  1990. * Gets and sets the maxCount field which describes how many sub-pages should be displayed if the
  1991. * sub_pages header property is set for this page object.
  1992. *
  1993. * @param int|null $var the maximum number of sub-pages
  1994. * @return int the maximum number of sub-pages
  1995. * @deprecated 1.6
  1996. */
  1997. public function maxCount($var = null)
  1998. {
  1999. //user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6', E_USER_DEPRECATED);
  2000. if ($var !== null) {
  2001. $this->max_count = (int)$var;
  2002. }
  2003. if (empty($this->max_count)) {
  2004. /** @var Config $config */
  2005. $config = Grav::instance()['config'];
  2006. $this->max_count = (int)$config->get('system.pages.list.count');
  2007. }
  2008. return $this->max_count;
  2009. }
  2010. /**
  2011. * Gets and sets the taxonomy array which defines which taxonomies this page identifies itself with.
  2012. *
  2013. * @param array|null $var an array of taxonomies
  2014. * @return array an array of taxonomies
  2015. */
  2016. public function taxonomy($var = null)
  2017. {
  2018. if ($var !== null) {
  2019. // make sure first level are arrays
  2020. array_walk($var, static function (&$value) {
  2021. $value = (array) $value;
  2022. });
  2023. // make sure all values are strings
  2024. array_walk_recursive($var, static function (&$value) {
  2025. $value = (string) $value;
  2026. });
  2027. $this->taxonomy = $var;
  2028. }
  2029. return $this->taxonomy;
  2030. }
  2031. /**
  2032. * Gets and sets the modular var that helps identify this page is a modular child
  2033. *
  2034. * @param bool|null $var true if modular_twig
  2035. * @return bool true if modular_twig
  2036. * @deprecated 1.7 Use ->isModule() or ->modularTwig() method instead.
  2037. */
  2038. public function modular($var = null)
  2039. {
  2040. user_error(__METHOD__ . '() is deprecated since Grav 1.7, use ->isModule() or ->modularTwig() method instead', E_USER_DEPRECATED);
  2041. return $this->modularTwig($var);
  2042. }
  2043. /**
  2044. * Gets and sets the modular_twig var that helps identify this page as a modular child page that will need
  2045. * twig processing handled differently from a regular page.
  2046. *
  2047. * @param bool|null $var true if modular_twig
  2048. * @return bool true if modular_twig
  2049. */
  2050. public function modularTwig($var = null)
  2051. {
  2052. if ($var !== null) {
  2053. $this->modular_twig = (bool)$var;
  2054. if ($var) {
  2055. $this->visible(false);
  2056. // some routable logic
  2057. if (empty($this->header->routable)) {
  2058. $this->routable = false;
  2059. }
  2060. }
  2061. }
  2062. return $this->modular_twig ?? false;
  2063. }
  2064. /**
  2065. * Gets the configured state of the processing method.
  2066. *
  2067. * @param string $process the process, eg "twig" or "markdown"
  2068. * @return bool whether or not the processing method is enabled for this Page
  2069. */
  2070. public function shouldProcess($process)
  2071. {
  2072. return (bool)($this->process[$process] ?? false);
  2073. }
  2074. /**
  2075. * Gets and Sets the parent object for this page
  2076. *
  2077. * @param PageInterface|null $var the parent page object
  2078. * @return PageInterface|null the parent page object if it exists.
  2079. */
  2080. public function parent(PageInterface $var = null)
  2081. {
  2082. if ($var) {
  2083. $this->parent = $var->path();
  2084. return $var;
  2085. }
  2086. /** @var Pages $pages */
  2087. $pages = Grav::instance()['pages'];
  2088. return $pages->get($this->parent);
  2089. }
  2090. /**
  2091. * Gets the top parent object for this page. Can return page itself.
  2092. *
  2093. * @return PageInterface The top parent page object.
  2094. */
  2095. public function topParent()
  2096. {
  2097. $topParent = $this;
  2098. while (true) {
  2099. $theParent = $topParent->parent();
  2100. if ($theParent !== null && $theParent->parent() !== null) {
  2101. $topParent = $theParent;
  2102. } else {
  2103. break;
  2104. }
  2105. }
  2106. return $topParent;
  2107. }
  2108. /**
  2109. * Returns children of this page.
  2110. *
  2111. * @return PageCollectionInterface|Collection
  2112. */
  2113. public function children()
  2114. {
  2115. /** @var Pages $pages */
  2116. $pages = Grav::instance()['pages'];
  2117. return $pages->children($this->path());
  2118. }
  2119. /**
  2120. * Check to see if this item is the first in an array of sub-pages.
  2121. *
  2122. * @return bool True if item is first.
  2123. */
  2124. public function isFirst()
  2125. {
  2126. $parent = $this->parent();
  2127. $collection = $parent ? $parent->collection('content', false) : null;
  2128. if ($collection instanceof Collection) {
  2129. return $collection->isFirst($this->path());
  2130. }
  2131. return true;
  2132. }
  2133. /**
  2134. * Check to see if this item is the last in an array of sub-pages.
  2135. *
  2136. * @return bool True if item is last
  2137. */
  2138. public function isLast()
  2139. {
  2140. $parent = $this->parent();
  2141. $collection = $parent ? $parent->collection('content', false) : null;
  2142. if ($collection instanceof Collection) {
  2143. return $collection->isLast($this->path());
  2144. }
  2145. return true;
  2146. }
  2147. /**
  2148. * Gets the previous sibling based on current position.
  2149. *
  2150. * @return PageInterface the previous Page item
  2151. */
  2152. public function prevSibling()
  2153. {
  2154. return $this->adjacentSibling(-1);
  2155. }
  2156. /**
  2157. * Gets the next sibling based on current position.
  2158. *
  2159. * @return PageInterface the next Page item
  2160. */
  2161. public function nextSibling()
  2162. {
  2163. return $this->adjacentSibling(1);
  2164. }
  2165. /**
  2166. * Returns the adjacent sibling based on a direction.
  2167. *
  2168. * @param int $direction either -1 or +1
  2169. * @return PageInterface|false the sibling page
  2170. */
  2171. public function adjacentSibling($direction = 1)
  2172. {
  2173. $parent = $this->parent();
  2174. $collection = $parent ? $parent->collection('content', false) : null;
  2175. if ($collection instanceof Collection) {
  2176. return $collection->adjacentSibling($this->path(), $direction);
  2177. }
  2178. return false;
  2179. }
  2180. /**
  2181. * Returns the item in the current position.
  2182. *
  2183. * @return int|null The index of the current page.
  2184. */
  2185. public function currentPosition()
  2186. {
  2187. $parent = $this->parent();
  2188. $collection = $parent ? $parent->collection('content', false) : null;
  2189. if ($collection instanceof Collection) {
  2190. return $collection->currentPosition($this->path());
  2191. }
  2192. return 1;
  2193. }
  2194. /**
  2195. * Returns whether or not this page is the currently active page requested via the URL.
  2196. *
  2197. * @return bool True if it is active
  2198. */
  2199. public function active()
  2200. {
  2201. $uri_path = rtrim(urldecode(Grav::instance()['uri']->path()), '/') ?: '/';
  2202. $routes = Grav::instance()['pages']->routes();
  2203. return isset($routes[$uri_path]) && $routes[$uri_path] === $this->path();
  2204. }
  2205. /**
  2206. * Returns whether or not this URI's URL contains the URL of the active page.
  2207. * Or in other words, is this page's URL in the current URL
  2208. *
  2209. * @return bool True if active child exists
  2210. */
  2211. public function activeChild()
  2212. {
  2213. $grav = Grav::instance();
  2214. /** @var Uri $uri */
  2215. $uri = $grav['uri'];
  2216. /** @var Pages $pages */
  2217. $pages = $grav['pages'];
  2218. $uri_path = rtrim(urldecode($uri->path()), '/');
  2219. $routes = $pages->routes();
  2220. if (isset($routes[$uri_path])) {
  2221. $page = $pages->find($uri->route());
  2222. /** @var PageInterface|null $child_page */
  2223. $child_page = $page ? $page->parent() : null;
  2224. while ($child_page && !$child_page->root()) {
  2225. if ($this->path() === $child_page->path()) {
  2226. return true;
  2227. }
  2228. $child_page = $child_page->parent();
  2229. }
  2230. }
  2231. return false;
  2232. }
  2233. /**
  2234. * Returns whether or not this page is the currently configured home page.
  2235. *
  2236. * @return bool True if it is the homepage
  2237. */
  2238. public function home()
  2239. {
  2240. $home = Grav::instance()['config']->get('system.home.alias');
  2241. return $this->route() === $home || $this->rawRoute() === $home;
  2242. }
  2243. /**
  2244. * Returns whether or not this page is the root node of the pages tree.
  2245. *
  2246. * @return bool True if it is the root
  2247. */
  2248. public function root()
  2249. {
  2250. return !$this->parent && !$this->name && !$this->visible;
  2251. }
  2252. /**
  2253. * Helper method to return an ancestor page.
  2254. *
  2255. * @param bool|null $lookup Name of the parent folder
  2256. * @return PageInterface page you were looking for if it exists
  2257. */
  2258. public function ancestor($lookup = null)
  2259. {
  2260. /** @var Pages $pages */
  2261. $pages = Grav::instance()['pages'];
  2262. return $pages->ancestor($this->route, $lookup);
  2263. }
  2264. /**
  2265. * Helper method to return an ancestor page to inherit from. The current
  2266. * page object is returned.
  2267. *
  2268. * @param string $field Name of the parent folder
  2269. * @return PageInterface
  2270. */
  2271. public function inherited($field)
  2272. {
  2273. [$inherited, $currentParams] = $this->getInheritedParams($field);
  2274. $this->modifyHeader($field, $currentParams);
  2275. return $inherited;
  2276. }
  2277. /**
  2278. * Helper method to return an ancestor field only to inherit from. The
  2279. * first occurrence of an ancestor field will be returned if at all.
  2280. *
  2281. * @param string $field Name of the parent folder
  2282. *
  2283. * @return array
  2284. */
  2285. public function inheritedField($field)
  2286. {
  2287. [$inherited, $currentParams] = $this->getInheritedParams($field);
  2288. return $currentParams;
  2289. }
  2290. /**
  2291. * Method that contains shared logic for inherited() and inheritedField()
  2292. *
  2293. * @param string $field Name of the parent folder
  2294. * @return array
  2295. */
  2296. protected function getInheritedParams($field)
  2297. {
  2298. $pages = Grav::instance()['pages'];
  2299. /** @var Pages $pages */
  2300. $inherited = $pages->inherited($this->route, $field);
  2301. $inheritedParams = $inherited ? (array)$inherited->value('header.' . $field) : [];
  2302. $currentParams = (array)$this->value('header.' . $field);
  2303. if ($inheritedParams && is_array($inheritedParams)) {
  2304. $currentParams = array_replace_recursive($inheritedParams, $currentParams);
  2305. }
  2306. return [$inherited, $currentParams];
  2307. }
  2308. /**
  2309. * Helper method to return a page.
  2310. *
  2311. * @param string $url the url of the page
  2312. * @param bool $all
  2313. *
  2314. * @return PageInterface page you were looking for if it exists
  2315. */
  2316. public function find($url, $all = false)
  2317. {
  2318. /** @var Pages $pages */
  2319. $pages = Grav::instance()['pages'];
  2320. return $pages->find($url, $all);
  2321. }
  2322. /**
  2323. * Get a collection of pages in the current context.
  2324. *
  2325. * @param string|array $params
  2326. * @param bool $pagination
  2327. *
  2328. * @return PageCollectionInterface|Collection
  2329. * @throws InvalidArgumentException
  2330. */
  2331. public function collection($params = 'content', $pagination = true)
  2332. {
  2333. if (is_string($params)) {
  2334. // Look into a page header field.
  2335. $params = (array)$this->value('header.' . $params);
  2336. } elseif (!is_array($params)) {
  2337. throw new InvalidArgumentException('Argument should be either header variable name or array of parameters');
  2338. }
  2339. $params['filter'] = ($params['filter'] ?? []) + ['translated' => true];
  2340. $context = [
  2341. 'pagination' => $pagination,
  2342. 'self' => $this
  2343. ];
  2344. /** @var Pages $pages */
  2345. $pages = Grav::instance()['pages'];
  2346. return $pages->getCollection($params, $context);
  2347. }
  2348. /**
  2349. * @param string|array $value
  2350. * @param bool $only_published
  2351. * @return PageCollectionInterface|Collection
  2352. */
  2353. public function evaluate($value, $only_published = true)
  2354. {
  2355. $params = [
  2356. 'items' => $value,
  2357. 'published' => $only_published
  2358. ];
  2359. $context = [
  2360. 'event' => false,
  2361. 'pagination' => false,
  2362. 'url_taxonomy_filters' => false,
  2363. 'self' => $this
  2364. ];
  2365. /** @var Pages $pages */
  2366. $pages = Grav::instance()['pages'];
  2367. return $pages->getCollection($params, $context);
  2368. }
  2369. /**
  2370. * Returns whether or not this Page object has a .md file associated with it or if its just a directory.
  2371. *
  2372. * @return bool True if its a page with a .md file associated
  2373. */
  2374. public function isPage()
  2375. {
  2376. if ($this->name) {
  2377. return true;
  2378. }
  2379. return false;
  2380. }
  2381. /**
  2382. * Returns whether or not this Page object is a directory or a page.
  2383. *
  2384. * @return bool True if its a directory
  2385. */
  2386. public function isDir()
  2387. {
  2388. return !$this->isPage();
  2389. }
  2390. /**
  2391. * @return bool
  2392. */
  2393. public function isModule(): bool
  2394. {
  2395. return $this->modularTwig();
  2396. }
  2397. /**
  2398. * Returns whether the page exists in the filesystem.
  2399. *
  2400. * @return bool
  2401. */
  2402. public function exists()
  2403. {
  2404. $file = $this->file();
  2405. return $file && $file->exists();
  2406. }
  2407. /**
  2408. * Returns whether or not the current folder exists
  2409. *
  2410. * @return bool
  2411. */
  2412. public function folderExists()
  2413. {
  2414. return file_exists($this->path());
  2415. }
  2416. /**
  2417. * Cleans the path.
  2418. *
  2419. * @param string $path the path
  2420. * @return string the path
  2421. */
  2422. protected function cleanPath($path)
  2423. {
  2424. $lastchunk = strrchr($path, DS);
  2425. if (strpos($lastchunk, ':') !== false) {
  2426. $path = str_replace($lastchunk, '', $path);
  2427. }
  2428. return $path;
  2429. }
  2430. /**
  2431. * Reorders all siblings according to a defined order
  2432. *
  2433. * @param array|null $new_order
  2434. */
  2435. protected function doReorder($new_order)
  2436. {
  2437. if (!$this->_original) {
  2438. return;
  2439. }
  2440. $pages = Grav::instance()['pages'];
  2441. $pages->init();
  2442. $this->_original->path($this->path());
  2443. $parent = $this->parent();
  2444. $siblings = $parent ? $parent->children() : null;
  2445. if ($siblings) {
  2446. $siblings->order('slug', 'asc', $new_order);
  2447. $counter = 0;
  2448. // Reorder all moved pages.
  2449. foreach ($siblings as $slug => $page) {
  2450. $order = (int)trim($page->order(), '.');
  2451. $counter++;
  2452. if ($order) {
  2453. if ($page->path() === $this->path() && $this->folderExists()) {
  2454. // Handle current page; we do want to change ordering number, but nothing else.
  2455. $this->order($counter);
  2456. $this->save(false);
  2457. } else {
  2458. // Handle all the other pages.
  2459. $page = $pages->get($page->path());
  2460. if ($page && $page->folderExists() && !$page->_action) {
  2461. $page = $page->move($this->parent());
  2462. $page->order($counter);
  2463. $page->save(false);
  2464. }
  2465. }
  2466. }
  2467. }
  2468. }
  2469. }
  2470. /**
  2471. * Moves or copies the page in filesystem.
  2472. *
  2473. * @internal
  2474. * @return void
  2475. * @throws Exception
  2476. */
  2477. protected function doRelocation()
  2478. {
  2479. if (!$this->_original) {
  2480. return;
  2481. }
  2482. if (is_dir($this->_original->path())) {
  2483. if ($this->_action === 'move') {
  2484. Folder::move($this->_original->path(), $this->path());
  2485. } elseif ($this->_action === 'copy') {
  2486. Folder::copy($this->_original->path(), $this->path());
  2487. }
  2488. }
  2489. if ($this->name() !== $this->_original->name()) {
  2490. $path = $this->path();
  2491. if (is_file($path . '/' . $this->_original->name())) {
  2492. rename($path . '/' . $this->_original->name(), $path . '/' . $this->name());
  2493. }
  2494. }
  2495. }
  2496. /**
  2497. * @return void
  2498. */
  2499. protected function setPublishState()
  2500. {
  2501. // Handle publishing dates if no explicit published option set
  2502. if (Grav::instance()['config']->get('system.pages.publish_dates') && !isset($this->header->published)) {
  2503. // unpublish if required, if not clear cache right before page should be unpublished
  2504. if ($this->unpublishDate()) {
  2505. if ($this->unpublishDate() < time()) {
  2506. $this->published(false);
  2507. } else {
  2508. $this->published();
  2509. Grav::instance()['cache']->setLifeTime($this->unpublishDate());
  2510. }
  2511. }
  2512. // publish if required, if not clear cache right before page is published
  2513. if ($this->publishDate() && $this->publishDate() > time()) {
  2514. $this->published(false);
  2515. Grav::instance()['cache']->setLifeTime($this->publishDate());
  2516. }
  2517. }
  2518. }
  2519. /**
  2520. * @param string $route
  2521. * @return string
  2522. */
  2523. protected function adjustRouteCase($route)
  2524. {
  2525. $case_insensitive = Grav::instance()['config']->get('system.force_lowercase_urls');
  2526. return $case_insensitive ? mb_strtolower($route) : $route;
  2527. }
  2528. /**
  2529. * Gets the Page Unmodified (original) version of the page.
  2530. *
  2531. * @return PageInterface The original version of the page.
  2532. */
  2533. public function getOriginal()
  2534. {
  2535. return $this->_original;
  2536. }
  2537. /**
  2538. * Gets the action.
  2539. *
  2540. * @return string|null The Action string.
  2541. */
  2542. public function getAction()
  2543. {
  2544. return $this->_action;
  2545. }
  2546. }