Page.php 93 KB

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