Page.php 93 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183
  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. // Ask Grav to calculate ETag from the final content.
  478. if ($this->eTag()) {
  479. $headers['ETag'] = '1';
  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, ENT_COMPAT | ENT_HTML401, 'UTF-8');
  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->getCacheKey());
  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->getCacheKey());
  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. public function getCacheKey(): string
  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) && is_array($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 (null === $this->id) {
  1738. // We need to set unique id to avoid potential cache conflicts between pages.
  1739. $var = time() . md5($this->filePath());
  1740. }
  1741. if ($var !== null) {
  1742. // store unique per language
  1743. $active_lang = Grav::instance()['language']->getLanguage() ?: '';
  1744. $id = $active_lang . $var;
  1745. $this->id = $id;
  1746. }
  1747. return $this->id;
  1748. }
  1749. /**
  1750. * Gets and sets the modified timestamp.
  1751. *
  1752. * @param int $var modified unix timestamp
  1753. *
  1754. * @return int modified unix timestamp
  1755. */
  1756. public function modified($var = null)
  1757. {
  1758. if ($var !== null) {
  1759. $this->modified = $var;
  1760. }
  1761. return $this->modified;
  1762. }
  1763. /**
  1764. * Gets the redirect set in the header.
  1765. *
  1766. * @param string $var redirect url
  1767. *
  1768. * @return string
  1769. */
  1770. public function redirect($var = null)
  1771. {
  1772. if ($var !== null) {
  1773. $this->redirect = $var;
  1774. }
  1775. return $this->redirect;
  1776. }
  1777. /**
  1778. * Gets and sets the option to show the etag header for the page.
  1779. *
  1780. * @param bool $var show etag header
  1781. *
  1782. * @return bool show etag header
  1783. */
  1784. public function eTag($var = null)
  1785. {
  1786. if ($var !== null) {
  1787. $this->etag = $var;
  1788. }
  1789. if (!isset($this->etag)) {
  1790. $this->etag = (bool)Grav::instance()['config']->get('system.pages.etag');
  1791. }
  1792. return $this->etag;
  1793. }
  1794. /**
  1795. * Gets and sets the option to show the last_modified header for the page.
  1796. *
  1797. * @param bool $var show last_modified header
  1798. *
  1799. * @return bool show last_modified header
  1800. */
  1801. public function lastModified($var = null)
  1802. {
  1803. if ($var !== null) {
  1804. $this->last_modified = $var;
  1805. }
  1806. if (!isset($this->last_modified)) {
  1807. $this->last_modified = (bool)Grav::instance()['config']->get('system.pages.last_modified');
  1808. }
  1809. return $this->last_modified;
  1810. }
  1811. /**
  1812. * Gets and sets the path to the .md file for this Page object.
  1813. *
  1814. * @param string $var the file path
  1815. *
  1816. * @return string|null the file path
  1817. */
  1818. public function filePath($var = null)
  1819. {
  1820. if ($var !== null) {
  1821. // Filename of the page.
  1822. $this->name = basename($var);
  1823. // Folder of the page.
  1824. $this->folder = basename(dirname($var));
  1825. // Path to the page.
  1826. $this->path = dirname($var, 2);
  1827. }
  1828. return $this->path . '/' . $this->folder . '/' . ($this->name ?: '');
  1829. }
  1830. /**
  1831. * Gets the relative path to the .md file
  1832. *
  1833. * @return string The relative file path
  1834. */
  1835. public function filePathClean()
  1836. {
  1837. return str_replace(ROOT_DIR, '', $this->filePath());
  1838. }
  1839. /**
  1840. * Returns the clean path to the page file
  1841. */
  1842. public function relativePagePath()
  1843. {
  1844. return str_replace('/' . $this->name(), '', $this->filePathClean());
  1845. }
  1846. /**
  1847. * Gets and sets the path to the folder where the .md for this Page object resides.
  1848. * This is equivalent to the filePath but without the filename.
  1849. *
  1850. * @param string $var the path
  1851. *
  1852. * @return string|null the path
  1853. */
  1854. public function path($var = null)
  1855. {
  1856. if ($var !== null) {
  1857. // Folder of the page.
  1858. $this->folder = basename($var);
  1859. // Path to the page.
  1860. $this->path = dirname($var);
  1861. }
  1862. return $this->path ? $this->path . '/' . $this->folder : null;
  1863. }
  1864. /**
  1865. * Get/set the folder.
  1866. *
  1867. * @param string $var Optional path
  1868. *
  1869. * @return string|null
  1870. */
  1871. public function folder($var = null)
  1872. {
  1873. if ($var !== null) {
  1874. $this->folder = $var;
  1875. }
  1876. return $this->folder;
  1877. }
  1878. /**
  1879. * Gets and sets the date for this Page object. This is typically passed in via the page headers
  1880. *
  1881. * @param string $var string representation of a date
  1882. *
  1883. * @return int unix timestamp representation of the date
  1884. */
  1885. public function date($var = null)
  1886. {
  1887. if ($var !== null) {
  1888. $this->date = Utils::date2timestamp($var, $this->dateformat);
  1889. }
  1890. if (!$this->date) {
  1891. $this->date = $this->modified;
  1892. }
  1893. return $this->date;
  1894. }
  1895. /**
  1896. * Gets and sets the date format for this Page object. This is typically passed in via the page headers
  1897. * using typical PHP date string structure - http://php.net/manual/en/function.date.php
  1898. *
  1899. * @param string $var string representation of a date format
  1900. *
  1901. * @return string string representation of a date format
  1902. */
  1903. public function dateformat($var = null)
  1904. {
  1905. if ($var !== null) {
  1906. $this->dateformat = $var;
  1907. }
  1908. return $this->dateformat;
  1909. }
  1910. /**
  1911. * Gets and sets the order by which any sub-pages should be sorted.
  1912. *
  1913. * @param string $var the order, either "asc" or "desc"
  1914. *
  1915. * @return string the order, either "asc" or "desc"
  1916. * @deprecated 1.6
  1917. */
  1918. public function orderDir($var = null)
  1919. {
  1920. //user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6', E_USER_DEPRECATED);
  1921. if ($var !== null) {
  1922. $this->order_dir = $var;
  1923. }
  1924. if (empty($this->order_dir)) {
  1925. $this->order_dir = 'asc';
  1926. }
  1927. return $this->order_dir;
  1928. }
  1929. /**
  1930. * Gets and sets the order by which the sub-pages should be sorted.
  1931. *
  1932. * default - is the order based on the file system, ie 01.Home before 02.Advark
  1933. * title - is the order based on the title set in the pages
  1934. * date - is the order based on the date set in the pages
  1935. * folder - is the order based on the name of the folder with any numerics omitted
  1936. *
  1937. * @param string $var supported options include "default", "title", "date", and "folder"
  1938. *
  1939. * @return string supported options include "default", "title", "date", and "folder"
  1940. * @deprecated 1.6
  1941. */
  1942. public function orderBy($var = null)
  1943. {
  1944. //user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6', E_USER_DEPRECATED);
  1945. if ($var !== null) {
  1946. $this->order_by = $var;
  1947. }
  1948. return $this->order_by;
  1949. }
  1950. /**
  1951. * Gets the manual order set in the header.
  1952. *
  1953. * @param string $var supported options include "default", "title", "date", and "folder"
  1954. *
  1955. * @return array
  1956. * @deprecated 1.6
  1957. */
  1958. public function orderManual($var = null)
  1959. {
  1960. //user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6', E_USER_DEPRECATED);
  1961. if ($var !== null) {
  1962. $this->order_manual = $var;
  1963. }
  1964. return (array)$this->order_manual;
  1965. }
  1966. /**
  1967. * Gets and sets the maxCount field which describes how many sub-pages should be displayed if the
  1968. * sub_pages header property is set for this page object.
  1969. *
  1970. * @param int $var the maximum number of sub-pages
  1971. *
  1972. * @return int the maximum number of sub-pages
  1973. * @deprecated 1.6
  1974. */
  1975. public function maxCount($var = null)
  1976. {
  1977. //user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6', E_USER_DEPRECATED);
  1978. if ($var !== null) {
  1979. $this->max_count = (int)$var;
  1980. }
  1981. if (empty($this->max_count)) {
  1982. /** @var Config $config */
  1983. $config = Grav::instance()['config'];
  1984. $this->max_count = (int)$config->get('system.pages.list.count');
  1985. }
  1986. return $this->max_count;
  1987. }
  1988. /**
  1989. * Gets and sets the taxonomy array which defines which taxonomies this page identifies itself with.
  1990. *
  1991. * @param array $var an array of taxonomies
  1992. *
  1993. * @return array an array of taxonomies
  1994. */
  1995. public function taxonomy($var = null)
  1996. {
  1997. if ($var !== null) {
  1998. // make sure first level are arrays
  1999. array_walk($var, function(&$value) {
  2000. $value = (array) $value;
  2001. });
  2002. // make sure all values are strings
  2003. array_walk_recursive($var, function(&$value) {
  2004. $value = (string) $value;
  2005. });
  2006. $this->taxonomy = $var;
  2007. }
  2008. return $this->taxonomy;
  2009. }
  2010. /**
  2011. * Gets and sets the modular var that helps identify this page is a modular child
  2012. *
  2013. * @param bool $var true if modular_twig
  2014. *
  2015. * @return bool true if modular_twig
  2016. */
  2017. public function modular($var = null)
  2018. {
  2019. return $this->modularTwig($var);
  2020. }
  2021. /**
  2022. * Gets and sets the modular_twig var that helps identify this page as a modular child page that will need
  2023. * twig processing handled differently from a regular page.
  2024. *
  2025. * @param bool $var true if modular_twig
  2026. *
  2027. * @return bool true if modular_twig
  2028. */
  2029. public function modularTwig($var = null)
  2030. {
  2031. if ($var !== null) {
  2032. $this->modular_twig = (bool)$var;
  2033. if ($var) {
  2034. $this->visible(false);
  2035. // some routable logic
  2036. if (empty($this->header->routable)) {
  2037. $this->routable = false;
  2038. }
  2039. }
  2040. }
  2041. return $this->modular_twig;
  2042. }
  2043. /**
  2044. * Gets the configured state of the processing method.
  2045. *
  2046. * @param string $process the process, eg "twig" or "markdown"
  2047. *
  2048. * @return bool whether or not the processing method is enabled for this Page
  2049. */
  2050. public function shouldProcess($process)
  2051. {
  2052. return (bool)($this->process[$process] ?? false);
  2053. }
  2054. /**
  2055. * Gets and Sets the parent object for this page
  2056. *
  2057. * @param PageInterface $var the parent page object
  2058. *
  2059. * @return PageInterface|null the parent page object if it exists.
  2060. */
  2061. public function parent(PageInterface $var = null)
  2062. {
  2063. if ($var) {
  2064. $this->parent = $var->path();
  2065. return $var;
  2066. }
  2067. /** @var Pages $pages */
  2068. $pages = Grav::instance()['pages'];
  2069. return $pages->get($this->parent);
  2070. }
  2071. /**
  2072. * Gets the top parent object for this page
  2073. *
  2074. * @return PageInterface|null the top parent page object if it exists.
  2075. */
  2076. public function topParent()
  2077. {
  2078. $topParent = $this->parent();
  2079. if (!$topParent) {
  2080. return null;
  2081. }
  2082. while (true) {
  2083. $theParent = $topParent->parent();
  2084. if ($theParent !== null && $theParent->parent() !== null) {
  2085. $topParent = $theParent;
  2086. } else {
  2087. break;
  2088. }
  2089. }
  2090. return $topParent;
  2091. }
  2092. /**
  2093. * Returns children of this page.
  2094. *
  2095. * @return Collection
  2096. */
  2097. public function children()
  2098. {
  2099. /** @var Pages $pages */
  2100. $pages = Grav::instance()['pages'];
  2101. return $pages->children($this->path());
  2102. }
  2103. /**
  2104. * Check to see if this item is the first in an array of sub-pages.
  2105. *
  2106. * @return bool True if item is first.
  2107. */
  2108. public function isFirst()
  2109. {
  2110. $parent = $this->parent();
  2111. $collection = $parent ? $parent->collection('content', false) : null;
  2112. if ($collection instanceof Collection) {
  2113. return $collection->isFirst($this->path());
  2114. }
  2115. return true;
  2116. }
  2117. /**
  2118. * Check to see if this item is the last in an array of sub-pages.
  2119. *
  2120. * @return bool True if item is last
  2121. */
  2122. public function isLast()
  2123. {
  2124. $parent = $this->parent();
  2125. $collection = $parent ? $parent->collection('content', false) : null;
  2126. if ($collection instanceof Collection) {
  2127. return $collection->isLast($this->path());
  2128. }
  2129. return true;
  2130. }
  2131. /**
  2132. * Gets the previous sibling based on current position.
  2133. *
  2134. * @return PageInterface the previous Page item
  2135. */
  2136. public function prevSibling()
  2137. {
  2138. return $this->adjacentSibling(-1);
  2139. }
  2140. /**
  2141. * Gets the next sibling based on current position.
  2142. *
  2143. * @return PageInterface the next Page item
  2144. */
  2145. public function nextSibling()
  2146. {
  2147. return $this->adjacentSibling(1);
  2148. }
  2149. /**
  2150. * Returns the adjacent sibling based on a direction.
  2151. *
  2152. * @param int $direction either -1 or +1
  2153. *
  2154. * @return PageInterface|bool the sibling page
  2155. */
  2156. public function adjacentSibling($direction = 1)
  2157. {
  2158. $parent = $this->parent();
  2159. $collection = $parent ? $parent->collection('content', false) : null;
  2160. if ($collection instanceof Collection) {
  2161. return $collection->adjacentSibling($this->path(), $direction);
  2162. }
  2163. return false;
  2164. }
  2165. /**
  2166. * Returns the item in the current position.
  2167. *
  2168. * @return int the index of the current page.
  2169. */
  2170. public function currentPosition()
  2171. {
  2172. $parent = $this->parent();
  2173. $collection = $parent ? $parent->collection('content', false) : null;
  2174. if ($collection instanceof Collection) {
  2175. return $collection->currentPosition($this->path());
  2176. }
  2177. return 1;
  2178. }
  2179. /**
  2180. * Returns whether or not this page is the currently active page requested via the URL.
  2181. *
  2182. * @return bool True if it is active
  2183. */
  2184. public function active()
  2185. {
  2186. $uri_path = rtrim(urldecode(Grav::instance()['uri']->path()), '/') ?: '/';
  2187. $routes = Grav::instance()['pages']->routes();
  2188. return isset($routes[$uri_path]) && $routes[$uri_path] === $this->path();
  2189. }
  2190. /**
  2191. * Returns whether or not this URI's URL contains the URL of the active page.
  2192. * Or in other words, is this page's URL in the current URL
  2193. *
  2194. * @return bool True if active child exists
  2195. */
  2196. public function activeChild()
  2197. {
  2198. $uri = Grav::instance()['uri'];
  2199. $pages = Grav::instance()['pages'];
  2200. $uri_path = rtrim(urldecode($uri->path()), '/');
  2201. $routes = Grav::instance()['pages']->routes();
  2202. if (isset($routes[$uri_path])) {
  2203. /** @var PageInterface $child_page */
  2204. $child_page = $pages->dispatch($uri->route())->parent();
  2205. if ($child_page) {
  2206. while (!$child_page->root()) {
  2207. if ($this->path() === $child_page->path()) {
  2208. return true;
  2209. }
  2210. $child_page = $child_page->parent();
  2211. }
  2212. }
  2213. }
  2214. return false;
  2215. }
  2216. /**
  2217. * Returns whether or not this page is the currently configured home page.
  2218. *
  2219. * @return bool True if it is the homepage
  2220. */
  2221. public function home()
  2222. {
  2223. $home = Grav::instance()['config']->get('system.home.alias');
  2224. return $this->route() === $home || $this->rawRoute() === $home;
  2225. }
  2226. /**
  2227. * Returns whether or not this page is the root node of the pages tree.
  2228. *
  2229. * @return bool True if it is the root
  2230. */
  2231. public function root()
  2232. {
  2233. return !$this->parent && !$this->name && !$this->visible;
  2234. }
  2235. /**
  2236. * Helper method to return an ancestor page.
  2237. *
  2238. * @param bool $lookup Name of the parent folder
  2239. *
  2240. * @return PageInterface page you were looking for if it exists
  2241. */
  2242. public function ancestor($lookup = null)
  2243. {
  2244. /** @var Pages $pages */
  2245. $pages = Grav::instance()['pages'];
  2246. return $pages->ancestor($this->route, $lookup);
  2247. }
  2248. /**
  2249. * Helper method to return an ancestor page to inherit from. The current
  2250. * page object is returned.
  2251. *
  2252. * @param string $field Name of the parent folder
  2253. *
  2254. * @return PageInterface
  2255. */
  2256. public function inherited($field)
  2257. {
  2258. list($inherited, $currentParams) = $this->getInheritedParams($field);
  2259. $this->modifyHeader($field, $currentParams);
  2260. return $inherited;
  2261. }
  2262. /**
  2263. * Helper method to return an ancestor field only to inherit from. The
  2264. * first occurrence of an ancestor field will be returned if at all.
  2265. *
  2266. * @param string $field Name of the parent folder
  2267. *
  2268. * @return array
  2269. */
  2270. public function inheritedField($field)
  2271. {
  2272. list($inherited, $currentParams) = $this->getInheritedParams($field);
  2273. return $currentParams;
  2274. }
  2275. /**
  2276. * Method that contains shared logic for inherited() and inheritedField()
  2277. *
  2278. * @param string $field Name of the parent folder
  2279. *
  2280. * @return array
  2281. */
  2282. protected function getInheritedParams($field)
  2283. {
  2284. $pages = Grav::instance()['pages'];
  2285. /** @var Pages $pages */
  2286. $inherited = $pages->inherited($this->route, $field);
  2287. $inheritedParams = $inherited ? (array)$inherited->value('header.' . $field) : [];
  2288. $currentParams = (array)$this->value('header.' . $field);
  2289. if ($inheritedParams && is_array($inheritedParams)) {
  2290. $currentParams = array_replace_recursive($inheritedParams, $currentParams);
  2291. }
  2292. return [$inherited, $currentParams];
  2293. }
  2294. /**
  2295. * Helper method to return a page.
  2296. *
  2297. * @param string $url the url of the page
  2298. * @param bool $all
  2299. *
  2300. * @return PageInterface page you were looking for if it exists
  2301. */
  2302. public function find($url, $all = false)
  2303. {
  2304. /** @var Pages $pages */
  2305. $pages = Grav::instance()['pages'];
  2306. return $pages->find($url, $all);
  2307. }
  2308. /**
  2309. * Get a collection of pages in the current context.
  2310. *
  2311. * @param string|array $params
  2312. * @param bool $pagination
  2313. *
  2314. * @return Collection
  2315. * @throws \InvalidArgumentException
  2316. */
  2317. public function collection($params = 'content', $pagination = true)
  2318. {
  2319. if (is_string($params)) {
  2320. $params = (array)$this->value('header.' . $params);
  2321. } elseif (!is_array($params)) {
  2322. throw new \InvalidArgumentException('Argument should be either header variable name or array of parameters');
  2323. }
  2324. if (!isset($params['items'])) {
  2325. return new Collection();
  2326. }
  2327. // See if require published filter is set and use that, if assume published=true
  2328. $only_published = true;
  2329. if (isset($params['filter']['published']) && $params['filter']['published']) {
  2330. $only_published = false;
  2331. } elseif (isset($params['filter']['non-published']) && $params['filter']['non-published']) {
  2332. $only_published = false;
  2333. }
  2334. $collection = $this->evaluate($params['items'], $only_published);
  2335. if (!$collection instanceof Collection) {
  2336. $collection = new Collection();
  2337. }
  2338. $collection->setParams($params);
  2339. /** @var Uri $uri */
  2340. $uri = Grav::instance()['uri'];
  2341. /** @var Config $config */
  2342. $config = Grav::instance()['config'];
  2343. $process_taxonomy = $params['url_taxonomy_filters'] ?? $config->get('system.pages.url_taxonomy_filters');
  2344. if ($process_taxonomy) {
  2345. foreach ((array)$config->get('site.taxonomies') as $taxonomy) {
  2346. if ($uri->param(rawurlencode($taxonomy))) {
  2347. $items = explode(',', $uri->param($taxonomy));
  2348. $collection->setParams(['taxonomies' => [$taxonomy => $items]]);
  2349. foreach ($collection as $page) {
  2350. // Don't filter modular pages
  2351. if ($page->modular()) {
  2352. continue;
  2353. }
  2354. foreach ($items as $item) {
  2355. $item = rawurldecode($item);
  2356. if (empty($page->taxonomy[$taxonomy]) || !\in_array(htmlspecialchars_decode($item, ENT_QUOTES), $page->taxonomy[$taxonomy], true)
  2357. ) {
  2358. $collection->remove($page->path());
  2359. }
  2360. }
  2361. }
  2362. }
  2363. }
  2364. }
  2365. // If a filter or filters are set, filter the collection...
  2366. if (isset($params['filter'])) {
  2367. // remove any inclusive sets from filer:
  2368. $sets = ['published', 'visible', 'modular', 'routable'];
  2369. foreach ($sets as $type) {
  2370. $var = "non-{$type}";
  2371. if (isset($params['filter'][$type], $params['filter'][$var]) && $params['filter'][$type] && $params['filter'][$var]) {
  2372. unset ($params['filter'][$type], $params['filter'][$var]);
  2373. }
  2374. }
  2375. foreach ((array)$params['filter'] as $type => $filter) {
  2376. switch ($type) {
  2377. case 'published':
  2378. if ((bool) $filter) {
  2379. $collection->published();
  2380. }
  2381. break;
  2382. case 'non-published':
  2383. if ((bool) $filter) {
  2384. $collection->nonPublished();
  2385. }
  2386. break;
  2387. case 'visible':
  2388. if ((bool) $filter) {
  2389. $collection->visible();
  2390. }
  2391. break;
  2392. case 'non-visible':
  2393. if ((bool) $filter) {
  2394. $collection->nonVisible();
  2395. }
  2396. break;
  2397. case 'modular':
  2398. if ((bool) $filter) {
  2399. $collection->modular();
  2400. }
  2401. break;
  2402. case 'non-modular':
  2403. if ((bool) $filter) {
  2404. $collection->nonModular();
  2405. }
  2406. break;
  2407. case 'routable':
  2408. if ((bool) $filter) {
  2409. $collection->routable();
  2410. }
  2411. break;
  2412. case 'non-routable':
  2413. if ((bool) $filter) {
  2414. $collection->nonRoutable();
  2415. }
  2416. break;
  2417. case 'type':
  2418. $collection->ofType($filter);
  2419. break;
  2420. case 'types':
  2421. $collection->ofOneOfTheseTypes($filter);
  2422. break;
  2423. case 'access':
  2424. $collection->ofOneOfTheseAccessLevels($filter);
  2425. break;
  2426. }
  2427. }
  2428. }
  2429. if (isset($params['dateRange'])) {
  2430. $start = $params['dateRange']['start'] ?? 0;
  2431. $end = $params['dateRange']['end'] ?? false;
  2432. $field = $params['dateRange']['field'] ?? false;
  2433. $collection->dateRange($start, $end, $field);
  2434. }
  2435. if (isset($params['order'])) {
  2436. $by = $params['order']['by'] ?? 'default';
  2437. $dir = $params['order']['dir'] ?? 'asc';
  2438. $custom = $params['order']['custom'] ?? null;
  2439. $sort_flags = $params['order']['sort_flags'] ?? null;
  2440. if (is_array($sort_flags)) {
  2441. $sort_flags = array_map('constant', $sort_flags); //transform strings to constant value
  2442. $sort_flags = array_reduce($sort_flags, function ($a, $b) {
  2443. return $a | $b;
  2444. }, 0); //merge constant values using bit or
  2445. }
  2446. $collection->order($by, $dir, $custom, $sort_flags);
  2447. }
  2448. /** @var Grav $grav */
  2449. $grav = Grav::instance();
  2450. // New Custom event to handle things like pagination.
  2451. $grav->fireEvent('onCollectionProcessed', new Event(['collection' => $collection]));
  2452. // Slice and dice the collection if pagination is required
  2453. if ($pagination) {
  2454. $params = $collection->params();
  2455. $limit = (int)($params['limit'] ?? 0);
  2456. $start = !empty($params['pagination']) ? ($uri->currentPage() - 1) * $limit : 0;
  2457. if ($limit && $collection->count() > $limit) {
  2458. $collection->slice($start, $limit);
  2459. }
  2460. }
  2461. return $collection;
  2462. }
  2463. /**
  2464. * @param string|array $value
  2465. * @param bool $only_published
  2466. * @return mixed
  2467. */
  2468. public function evaluate($value, $only_published = true)
  2469. {
  2470. // Parse command.
  2471. if (is_string($value)) {
  2472. // Format: @command.param
  2473. $cmd = $value;
  2474. $params = [];
  2475. } elseif (is_array($value) && count($value) == 1 && !is_int(key($value))) {
  2476. // Format: @command.param: { attr1: value1, attr2: value2 }
  2477. $cmd = (string)key($value);
  2478. $params = (array)current($value);
  2479. } else {
  2480. $result = [];
  2481. foreach ((array)$value as $key => $val) {
  2482. if (is_int($key)) {
  2483. $result = $result + $this->evaluate($val, $only_published)->toArray();
  2484. } else {
  2485. $result = $result + $this->evaluate([$key => $val], $only_published)->toArray();
  2486. }
  2487. }
  2488. return new Collection($result);
  2489. }
  2490. /** @var Pages $pages */
  2491. $pages = Grav::instance()['pages'];
  2492. $parts = explode('.', $cmd);
  2493. $current = array_shift($parts);
  2494. /** @var Collection $results */
  2495. $results = new Collection();
  2496. switch ($current) {
  2497. case 'self@':
  2498. case '@self':
  2499. if (!empty($parts)) {
  2500. switch ($parts[0]) {
  2501. case 'modular':
  2502. // @self.modular: false (alternative to @self.children)
  2503. if (!empty($params) && $params[0] === false) {
  2504. $results = $this->children()->nonModular();
  2505. break;
  2506. }
  2507. $results = $this->children()->modular();
  2508. break;
  2509. case 'children':
  2510. $results = $this->children()->nonModular();
  2511. break;
  2512. case 'all':
  2513. $results = $this->children();
  2514. break;
  2515. case 'parent':
  2516. $collection = new Collection();
  2517. $results = $collection->addPage($this->parent());
  2518. break;
  2519. case 'siblings':
  2520. if (!$this->parent()) {
  2521. return new Collection();
  2522. }
  2523. $results = $this->parent()->children()->remove($this->path());
  2524. break;
  2525. case 'descendants':
  2526. $results = $pages->all($this)->remove($this->path())->nonModular();
  2527. break;
  2528. }
  2529. }
  2530. break;
  2531. case 'page@':
  2532. case '@page':
  2533. $page = null;
  2534. if (!empty($params)) {
  2535. $page = $this->find($params[0]);
  2536. }
  2537. // safety check in case page is not found
  2538. if (!isset($page)) {
  2539. return $results;
  2540. }
  2541. // Handle a @page.descendants
  2542. if (!empty($parts)) {
  2543. switch ($parts[0]) {
  2544. case 'modular':
  2545. $results = new Collection();
  2546. foreach ($page->children() as $child) {
  2547. $results = $results->addPage($child);
  2548. }
  2549. $results->modular();
  2550. break;
  2551. case 'page':
  2552. case 'self':
  2553. $results = new Collection();
  2554. $results = $results->addPage($page);
  2555. break;
  2556. case 'descendants':
  2557. $results = $pages->all($page)->remove($page->path())->nonModular();
  2558. break;
  2559. case 'children':
  2560. $results = $page->children()->nonModular();
  2561. break;
  2562. }
  2563. } else {
  2564. $results = $page->children()->nonModular();
  2565. }
  2566. break;
  2567. case 'root@':
  2568. case '@root':
  2569. if (!empty($parts) && $parts[0] === 'descendants') {
  2570. $results = $pages->all($pages->root())->nonModular();
  2571. } else {
  2572. $results = $pages->root()->children()->nonModular();
  2573. }
  2574. break;
  2575. case 'taxonomy@':
  2576. case '@taxonomy':
  2577. // Gets a collection of pages by using one of the following formats:
  2578. // @taxonomy.category: blog
  2579. // @taxonomy.category: [ blog, featured ]
  2580. // @taxonomy: { category: [ blog, featured ], level: 1 }
  2581. /** @var Taxonomy $taxonomy_map */
  2582. $taxonomy_map = Grav::instance()['taxonomy'];
  2583. if (!empty($parts)) {
  2584. $params = [implode('.', $parts) => $params];
  2585. }
  2586. $results = $taxonomy_map->findTaxonomy($params);
  2587. break;
  2588. }
  2589. if ($only_published) {
  2590. $results = $results->published();
  2591. }
  2592. return $results;
  2593. }
  2594. /**
  2595. * Returns whether or not this Page object has a .md file associated with it or if its just a directory.
  2596. *
  2597. * @return bool True if its a page with a .md file associated
  2598. */
  2599. public function isPage()
  2600. {
  2601. if ($this->name) {
  2602. return true;
  2603. }
  2604. return false;
  2605. }
  2606. /**
  2607. * Returns whether or not this Page object is a directory or a page.
  2608. *
  2609. * @return bool True if its a directory
  2610. */
  2611. public function isDir()
  2612. {
  2613. return !$this->isPage();
  2614. }
  2615. /**
  2616. * Returns whether the page exists in the filesystem.
  2617. *
  2618. * @return bool
  2619. */
  2620. public function exists()
  2621. {
  2622. $file = $this->file();
  2623. return $file && $file->exists();
  2624. }
  2625. /**
  2626. * Returns whether or not the current folder exists
  2627. *
  2628. * @return bool
  2629. */
  2630. public function folderExists()
  2631. {
  2632. return file_exists($this->path());
  2633. }
  2634. /**
  2635. * Cleans the path.
  2636. *
  2637. * @param string $path the path
  2638. *
  2639. * @return string the path
  2640. */
  2641. protected function cleanPath($path)
  2642. {
  2643. $lastchunk = strrchr($path, DS);
  2644. if (strpos($lastchunk, ':') !== false) {
  2645. $path = str_replace($lastchunk, '', $path);
  2646. }
  2647. return $path;
  2648. }
  2649. /**
  2650. * Reorders all siblings according to a defined order
  2651. *
  2652. * @param array|null $new_order
  2653. */
  2654. protected function doReorder($new_order)
  2655. {
  2656. if (!$this->_original) {
  2657. return;
  2658. }
  2659. $pages = Grav::instance()['pages'];
  2660. $pages->init();
  2661. $this->_original->path($this->path());
  2662. $parent = $this->parent();
  2663. $siblings = $parent ? $parent->children() : null;
  2664. if ($siblings) {
  2665. $siblings->order('slug', 'asc', $new_order);
  2666. $counter = 0;
  2667. // Reorder all moved pages.
  2668. foreach ($siblings as $slug => $page) {
  2669. $order = (int)trim($page->order(), '.');
  2670. $counter++;
  2671. if ($order) {
  2672. if ($page->path() === $this->path() && $this->folderExists()) {
  2673. // Handle current page; we do want to change ordering number, but nothing else.
  2674. $this->order($counter);
  2675. $this->save(false);
  2676. } else {
  2677. // Handle all the other pages.
  2678. $page = $pages->get($page->path());
  2679. if ($page && $page->folderExists() && !$page->_action) {
  2680. $page = $page->move($this->parent());
  2681. $page->order($counter);
  2682. $page->save(false);
  2683. }
  2684. }
  2685. }
  2686. }
  2687. }
  2688. }
  2689. /**
  2690. * Moves or copies the page in filesystem.
  2691. *
  2692. * @internal
  2693. *
  2694. * @throws \Exception
  2695. */
  2696. protected function doRelocation()
  2697. {
  2698. if (!$this->_original) {
  2699. return;
  2700. }
  2701. if (is_dir($this->_original->path())) {
  2702. if ($this->_action === 'move') {
  2703. Folder::move($this->_original->path(), $this->path());
  2704. } elseif ($this->_action === 'copy') {
  2705. Folder::copy($this->_original->path(), $this->path());
  2706. }
  2707. }
  2708. if ($this->name() !== $this->_original->name()) {
  2709. $path = $this->path();
  2710. if (is_file($path . '/' . $this->_original->name())) {
  2711. rename($path . '/' . $this->_original->name(), $path . '/' . $this->name());
  2712. }
  2713. }
  2714. }
  2715. protected function setPublishState()
  2716. {
  2717. // Handle publishing dates if no explicit published option set
  2718. if (Grav::instance()['config']->get('system.pages.publish_dates') && !isset($this->header->published)) {
  2719. // unpublish if required, if not clear cache right before page should be unpublished
  2720. if ($this->unpublishDate()) {
  2721. if ($this->unpublishDate() < time()) {
  2722. $this->published(false);
  2723. } else {
  2724. $this->published();
  2725. Grav::instance()['cache']->setLifeTime($this->unpublishDate());
  2726. }
  2727. }
  2728. // publish if required, if not clear cache right before page is published
  2729. if ($this->publishDate() && $this->publishDate() > time()) {
  2730. $this->published(false);
  2731. Grav::instance()['cache']->setLifeTime($this->publishDate());
  2732. }
  2733. }
  2734. }
  2735. protected function adjustRouteCase($route)
  2736. {
  2737. $case_insensitive = Grav::instance()['config']->get('system.force_lowercase_urls');
  2738. return $case_insensitive ? mb_strtolower($route) : $route;
  2739. }
  2740. /**
  2741. * Gets the Page Unmodified (original) version of the page.
  2742. *
  2743. * @return PageInterface The original version of the page.
  2744. */
  2745. public function getOriginal()
  2746. {
  2747. return $this->_original;
  2748. }
  2749. /**
  2750. * Gets the action.
  2751. *
  2752. * @return string The Action string.
  2753. */
  2754. public function getAction()
  2755. {
  2756. return $this->_action;
  2757. }
  2758. }