Page.php 83 KB

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