Page.php 87 KB

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