Page.php 87 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992
  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(strpos($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, JSON_UNESCAPED_UNICODE), ['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->route();
  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. user_error('Configuration option \'system.pages.markdown_extra\' is deprecated since Grav 1.5, use \'system.pages.markdown.extra\' instead', E_USER_DEPRECATED);
  676. $defaults['extra'] = $this->markdown_extra ?: $config->get('system.pages.markdown_extra');
  677. }
  678. // Initialize the preferred variant of Parsedown
  679. if ($defaults['extra']) {
  680. $parsedown = new ParsedownExtra($this, $defaults);
  681. } else {
  682. $parsedown = new Parsedown($this, $defaults);
  683. }
  684. $this->content = $parsedown->text($this->content);
  685. }
  686. /**
  687. * Process the Twig page content.
  688. */
  689. private function processTwig()
  690. {
  691. $twig = Grav::instance()['twig'];
  692. $this->content = $twig->processPage($this, $this->content);
  693. }
  694. /**
  695. * Fires the onPageContentProcessed event, and caches the page content using a unique ID for the page
  696. */
  697. public function cachePageContent()
  698. {
  699. $cache = Grav::instance()['cache'];
  700. $cache_id = md5('page' . $this->id());
  701. $cache->save($cache_id, ['content' => $this->content, 'content_meta' => $this->content_meta]);
  702. }
  703. /**
  704. * Needed by the onPageContentProcessed event to get the raw page content
  705. *
  706. * @return string the current page content
  707. */
  708. public function getRawContent()
  709. {
  710. return $this->content;
  711. }
  712. /**
  713. * Needed by the onPageContentProcessed event to set the raw page content
  714. *
  715. * @param $content
  716. */
  717. public function setRawContent($content)
  718. {
  719. $content = $content === null ? '': $content;
  720. $this->content = $content;
  721. }
  722. /**
  723. * Get value from a page variable (used mostly for creating edit forms).
  724. *
  725. * @param string $name Variable name.
  726. * @param mixed $default
  727. *
  728. * @return mixed
  729. */
  730. public function value($name, $default = null)
  731. {
  732. if ($name === 'content') {
  733. return $this->raw_content;
  734. }
  735. if ($name === 'route') {
  736. return $this->parent()->rawRoute();
  737. }
  738. if ($name === 'order') {
  739. $order = $this->order();
  740. return $order ? (int)$this->order() : '';
  741. }
  742. if ($name === 'ordering') {
  743. return (bool)$this->order();
  744. }
  745. if ($name === 'folder') {
  746. return preg_replace(PAGE_ORDER_PREFIX_REGEX, '', $this->folder);
  747. }
  748. if ($name === 'slug') {
  749. return $this->slug();
  750. }
  751. if ($name === 'name') {
  752. $language = $this->language() ? '.' . $this->language() : '';
  753. $name_val = str_replace($language . '.md', '', $this->name());
  754. if ($this->modular()) {
  755. return 'modular/' . $name_val;
  756. }
  757. return $name_val;
  758. }
  759. if ($name === 'media') {
  760. return $this->media()->all();
  761. }
  762. if ($name === 'media.file') {
  763. return $this->media()->files();
  764. }
  765. if ($name === 'media.video') {
  766. return $this->media()->videos();
  767. }
  768. if ($name === 'media.image') {
  769. return $this->media()->images();
  770. }
  771. if ($name === 'media.audio') {
  772. return $this->media()->audios();
  773. }
  774. $path = explode('.', $name);
  775. $scope = array_shift($path);
  776. if ($name === 'frontmatter') {
  777. return $this->frontmatter;
  778. }
  779. if ($scope === 'header') {
  780. $current = $this->header();
  781. foreach ($path as $field) {
  782. if (is_object($current) && isset($current->{$field})) {
  783. $current = $current->{$field};
  784. } elseif (is_array($current) && isset($current[$field])) {
  785. $current = $current[$field];
  786. } else {
  787. return $default;
  788. }
  789. }
  790. return $current;
  791. }
  792. return $default;
  793. }
  794. /**
  795. * Gets and Sets the Page raw content
  796. *
  797. * @param null $var
  798. *
  799. * @return null
  800. */
  801. public function rawMarkdown($var = null)
  802. {
  803. if ($var !== null) {
  804. $this->raw_content = $var;
  805. }
  806. return $this->raw_content;
  807. }
  808. /**
  809. * Get file object to the page.
  810. *
  811. * @return MarkdownFile|null
  812. */
  813. public function file()
  814. {
  815. if ($this->name) {
  816. return MarkdownFile::instance($this->filePath());
  817. }
  818. return null;
  819. }
  820. /**
  821. * Save page if there's a file assigned to it.
  822. *
  823. * @param bool|mixed $reorder Internal use.
  824. */
  825. public function save($reorder = true)
  826. {
  827. // Perform move, copy [or reordering] if needed.
  828. $this->doRelocation();
  829. $file = $this->file();
  830. if ($file) {
  831. $file->filename($this->filePath());
  832. $file->header((array)$this->header());
  833. $file->markdown($this->raw_content);
  834. $file->save();
  835. }
  836. // Perform reorder if required
  837. if ($reorder && is_array($reorder)) {
  838. $this->doReorder($reorder);
  839. }
  840. $this->_original = null;
  841. }
  842. /**
  843. * Prepare move page to new location. Moves also everything that's under the current page.
  844. *
  845. * You need to call $this->save() in order to perform the move.
  846. *
  847. * @param Page $parent New parent page.
  848. *
  849. * @return $this
  850. */
  851. public function move(Page $parent)
  852. {
  853. if (!$this->_original) {
  854. $clone = clone $this;
  855. $this->_original = $clone;
  856. }
  857. $this->_action = 'move';
  858. if ($this->route() === $parent->route()) {
  859. throw new Exception('Failed: Cannot set page parent to self');
  860. }
  861. if (Utils::startsWith($parent->rawRoute(), $this->rawRoute())) {
  862. throw new Exception('Failed: Cannot set page parent to a child of current page');
  863. }
  864. $this->parent($parent);
  865. $this->id(time() . md5($this->filePath()));
  866. if ($parent->path()) {
  867. $this->path($parent->path() . '/' . $this->folder());
  868. }
  869. if ($parent->route()) {
  870. $this->route($parent->route() . '/' . $this->slug());
  871. } else {
  872. $this->route(Grav::instance()['pages']->root()->route() . '/' . $this->slug());
  873. }
  874. $this->raw_route = null;
  875. return $this;
  876. }
  877. /**
  878. * Prepare a copy from the page. Copies also everything that's under the current page.
  879. *
  880. * Returns a new Page object for the copy.
  881. * You need to call $this->save() in order to perform the move.
  882. *
  883. * @param Page $parent New parent page.
  884. *
  885. * @return $this
  886. */
  887. public function copy($parent)
  888. {
  889. $this->move($parent);
  890. $this->_action = 'copy';
  891. return $this;
  892. }
  893. /**
  894. * Get blueprints for the page.
  895. *
  896. * @return Blueprint
  897. */
  898. public function blueprints()
  899. {
  900. $grav = Grav::instance();
  901. /** @var Pages $pages */
  902. $pages = $grav['pages'];
  903. $blueprint = $pages->blueprints($this->blueprintName());
  904. $fields = $blueprint->fields();
  905. $edit_mode = isset($grav['admin']) ? $grav['config']->get('plugins.admin.edit_mode') : null;
  906. // override if you only want 'normal' mode
  907. if (empty($fields) && ($edit_mode === 'auto' || $edit_mode === 'normal')) {
  908. $blueprint = $pages->blueprints('default');
  909. }
  910. // override if you only want 'expert' mode
  911. if (!empty($fields) && $edit_mode === 'expert') {
  912. $blueprint = $pages->blueprints('');
  913. }
  914. return $blueprint;
  915. }
  916. /**
  917. * Get the blueprint name for this page. Use the blueprint form field if set
  918. *
  919. * @return string
  920. */
  921. public function blueprintName()
  922. {
  923. $blueprint_name = filter_input(INPUT_POST, 'blueprint', FILTER_SANITIZE_STRING) ?: $this->template();
  924. return $blueprint_name;
  925. }
  926. /**
  927. * Validate page header.
  928. *
  929. * @throws Exception
  930. */
  931. public function validate()
  932. {
  933. $blueprints = $this->blueprints();
  934. $blueprints->validate($this->toArray());
  935. }
  936. /**
  937. * Filter page header from illegal contents.
  938. */
  939. public function filter()
  940. {
  941. $blueprints = $this->blueprints();
  942. $values = $blueprints->filter($this->toArray());
  943. if ($values && isset($values['header'])) {
  944. $this->header($values['header']);
  945. }
  946. }
  947. /**
  948. * Get unknown header variables.
  949. *
  950. * @return array
  951. */
  952. public function extra()
  953. {
  954. $blueprints = $this->blueprints();
  955. return $blueprints->extra($this->toArray()['header'], 'header.');
  956. }
  957. /**
  958. * Convert page to an array.
  959. *
  960. * @return array
  961. */
  962. public function toArray()
  963. {
  964. return [
  965. 'header' => (array)$this->header(),
  966. 'content' => (string)$this->value('content')
  967. ];
  968. }
  969. /**
  970. * Convert page to YAML encoded string.
  971. *
  972. * @return string
  973. */
  974. public function toYaml()
  975. {
  976. return Yaml::dump($this->toArray(), 20);
  977. }
  978. /**
  979. * Convert page to JSON encoded string.
  980. *
  981. * @return string
  982. */
  983. public function toJson()
  984. {
  985. return json_encode($this->toArray());
  986. }
  987. /**
  988. * @return string
  989. */
  990. protected function getCacheKey()
  991. {
  992. return $this->id();
  993. }
  994. /**
  995. * Gets and sets the associated media as found in the page folder.
  996. *
  997. * @param Media $var Representation of associated media.
  998. *
  999. * @return Media Representation of associated media.
  1000. */
  1001. public function media($var = null)
  1002. {
  1003. if ($var) {
  1004. $this->setMedia($var);
  1005. }
  1006. return $this->getMedia();
  1007. }
  1008. /**
  1009. * Get filesystem path to the associated media.
  1010. *
  1011. * @return string|null
  1012. */
  1013. public function getMediaFolder()
  1014. {
  1015. return $this->path();
  1016. }
  1017. /**
  1018. * Get display order for the associated media.
  1019. *
  1020. * @return array Empty array means default ordering.
  1021. */
  1022. public function getMediaOrder()
  1023. {
  1024. $header = $this->header();
  1025. return isset($header->media_order) ? array_map('trim', explode(',', (string)$header->media_order)) : [];
  1026. }
  1027. /**
  1028. * Gets and sets the name field. If no name field is set, it will return 'default.md'.
  1029. *
  1030. * @param string $var The name of this page.
  1031. *
  1032. * @return string The name of this page.
  1033. */
  1034. public function name($var = null)
  1035. {
  1036. if ($var !== null) {
  1037. $this->name = $var;
  1038. }
  1039. return empty($this->name) ? 'default.md' : $this->name;
  1040. }
  1041. /**
  1042. * Returns child page type.
  1043. *
  1044. * @return string
  1045. */
  1046. public function childType()
  1047. {
  1048. return isset($this->header->child_type) ? (string)$this->header->child_type : '';
  1049. }
  1050. /**
  1051. * Gets and sets the template field. This is used to find the correct Twig template file to render.
  1052. * If no field is set, it will return the name without the .md extension
  1053. *
  1054. * @param string $var the template name
  1055. *
  1056. * @return string the template name
  1057. */
  1058. public function template($var = null)
  1059. {
  1060. if ($var !== null) {
  1061. $this->template = $var;
  1062. }
  1063. if (empty($this->template)) {
  1064. $this->template = ($this->modular() ? 'modular/' : '') . str_replace($this->extension(), '', $this->name());
  1065. }
  1066. return $this->template;
  1067. }
  1068. /**
  1069. * Allows a page to override the output render format, usually the extension provided
  1070. * in the URL. (e.g. `html`, `json`, `xml`, etc).
  1071. *
  1072. * @param null $var
  1073. *
  1074. * @return null
  1075. */
  1076. public function templateFormat($var = null)
  1077. {
  1078. if ($var !== null) {
  1079. $this->template_format = $var;
  1080. }
  1081. if (empty($this->template_format)) {
  1082. $this->template_format = Grav::instance()['uri']->extension('html');
  1083. }
  1084. return $this->template_format;
  1085. }
  1086. /**
  1087. * Gets and sets the extension field.
  1088. *
  1089. * @param null $var
  1090. *
  1091. * @return null|string
  1092. */
  1093. public function extension($var = null)
  1094. {
  1095. if ($var !== null) {
  1096. $this->extension = $var;
  1097. }
  1098. if (empty($this->extension)) {
  1099. $this->extension = '.' . pathinfo($this->name(), PATHINFO_EXTENSION);
  1100. }
  1101. return $this->extension;
  1102. }
  1103. /**
  1104. * Returns the page extension, got from the page `url_extension` config and falls back to the
  1105. * system config `system.pages.append_url_extension`.
  1106. *
  1107. * @return string The extension of this page. For example `.html`
  1108. */
  1109. public function urlExtension()
  1110. {
  1111. if ($this->home()) {
  1112. return '';
  1113. }
  1114. // if not set in the page get the value from system config
  1115. if (empty($this->url_extension)) {
  1116. $this->url_extension = trim(isset($this->header->append_url_extension) ? $this->header->append_url_extension : Grav::instance()['config']->get('system.pages.append_url_extension',
  1117. false));
  1118. }
  1119. return $this->url_extension;
  1120. }
  1121. /**
  1122. * Gets and sets the expires field. If not set will return the default
  1123. *
  1124. * @param int $var The new expires value.
  1125. *
  1126. * @return int The expires value
  1127. */
  1128. public function expires($var = null)
  1129. {
  1130. if ($var !== null) {
  1131. $this->expires = $var;
  1132. }
  1133. return !isset($this->expires) ? Grav::instance()['config']->get('system.pages.expires') : $this->expires;
  1134. }
  1135. /**
  1136. * Gets and sets the cache-control property. If not set it will return the default value (null)
  1137. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control for more details on valid options
  1138. *
  1139. * @param null $var
  1140. * @return null
  1141. */
  1142. public function cacheControl($var = null)
  1143. {
  1144. if ($var !== null) {
  1145. $this->cache_control = $var;
  1146. }
  1147. return !isset($this->cache_control) ? Grav::instance()['config']->get('system.pages.cache_control') : $this->cache_control;
  1148. }
  1149. /**
  1150. * Gets and sets the title for this Page. If no title is set, it will use the slug() to get a name
  1151. *
  1152. * @param string $var the title of the Page
  1153. *
  1154. * @return string the title of the Page
  1155. */
  1156. public function title($var = null)
  1157. {
  1158. if ($var !== null) {
  1159. $this->title = $var;
  1160. }
  1161. if (empty($this->title)) {
  1162. $this->title = ucfirst($this->slug());
  1163. }
  1164. return $this->title;
  1165. }
  1166. /**
  1167. * Gets and sets the menu name for this Page. This is the text that can be used specifically for navigation.
  1168. * If no menu field is set, it will use the title()
  1169. *
  1170. * @param string $var the menu field for the page
  1171. *
  1172. * @return string the menu field for the page
  1173. */
  1174. public function menu($var = null)
  1175. {
  1176. if ($var !== null) {
  1177. $this->menu = $var;
  1178. }
  1179. if (empty($this->menu)) {
  1180. $this->menu = $this->title();
  1181. }
  1182. return $this->menu;
  1183. }
  1184. /**
  1185. * Gets and Sets whether or not this Page is visible for navigation
  1186. *
  1187. * @param bool $var true if the page is visible
  1188. *
  1189. * @return bool true if the page is visible
  1190. */
  1191. public function visible($var = null)
  1192. {
  1193. if ($var !== null) {
  1194. $this->visible = (bool)$var;
  1195. }
  1196. if ($this->visible === null) {
  1197. // Set item visibility in menu if folder is different from slug
  1198. // eg folder = 01.Home and slug = Home
  1199. if (preg_match(PAGE_ORDER_PREFIX_REGEX, $this->folder)) {
  1200. $this->visible = true;
  1201. } else {
  1202. $this->visible = false;
  1203. }
  1204. }
  1205. return $this->visible;
  1206. }
  1207. /**
  1208. * Gets and Sets whether or not this Page is considered published
  1209. *
  1210. * @param bool $var true if the page is published
  1211. *
  1212. * @return bool true if the page is published
  1213. */
  1214. public function published($var = null)
  1215. {
  1216. if ($var !== null) {
  1217. $this->published = (bool)$var;
  1218. }
  1219. // If not published, should not be visible in menus either
  1220. if ($this->published === false) {
  1221. $this->visible = false;
  1222. }
  1223. return $this->published;
  1224. }
  1225. /**
  1226. * Gets and Sets the Page publish date
  1227. *
  1228. * @param string $var string representation of a date
  1229. *
  1230. * @return int unix timestamp representation of the date
  1231. */
  1232. public function publishDate($var = null)
  1233. {
  1234. if ($var !== null) {
  1235. $this->publish_date = Utils::date2timestamp($var, $this->dateformat);
  1236. }
  1237. return $this->publish_date;
  1238. }
  1239. /**
  1240. * Gets and Sets the Page unpublish date
  1241. *
  1242. * @param string $var string representation of a date
  1243. *
  1244. * @return int|null unix timestamp representation of the date
  1245. */
  1246. public function unpublishDate($var = null)
  1247. {
  1248. if ($var !== null) {
  1249. $this->unpublish_date = Utils::date2timestamp($var, $this->dateformat);
  1250. }
  1251. return $this->unpublish_date;
  1252. }
  1253. /**
  1254. * Gets and Sets whether or not this Page is routable, ie you can reach it
  1255. * via a URL.
  1256. * The page must be *routable* and *published*
  1257. *
  1258. * @param bool $var true if the page is routable
  1259. *
  1260. * @return bool true if the page is routable
  1261. */
  1262. public function routable($var = null)
  1263. {
  1264. if ($var !== null) {
  1265. $this->routable = (bool)$var;
  1266. }
  1267. return $this->routable && $this->published();
  1268. }
  1269. public function ssl($var = null)
  1270. {
  1271. if ($var !== null) {
  1272. $this->ssl = (bool)$var;
  1273. }
  1274. return $this->ssl;
  1275. }
  1276. /**
  1277. * Gets and Sets the process setup for this Page. This is multi-dimensional array that consists of
  1278. * a simple array of arrays with the form array("markdown"=>true) for example
  1279. *
  1280. * @param array $var an Array of name value pairs where the name is the process and value is true or false
  1281. *
  1282. * @return array an Array of name value pairs where the name is the process and value is true or false
  1283. */
  1284. public function process($var = null)
  1285. {
  1286. if ($var !== null) {
  1287. $this->process = (array)$var;
  1288. }
  1289. return $this->process;
  1290. }
  1291. /**
  1292. * Returns the state of the debugger override etting for this page
  1293. *
  1294. * @return mixed
  1295. */
  1296. public function debugger()
  1297. {
  1298. if (isset($this->debugger) && $this->debugger === false) {
  1299. return false;
  1300. }
  1301. return true;
  1302. }
  1303. /**
  1304. * Function to merge page metadata tags and build an array of Metadata objects
  1305. * that can then be rendered in the page.
  1306. *
  1307. * @param array $var an Array of metadata values to set
  1308. *
  1309. * @return array an Array of metadata values for the page
  1310. */
  1311. public function metadata($var = null)
  1312. {
  1313. if ($var !== null) {
  1314. $this->metadata = (array)$var;
  1315. }
  1316. // if not metadata yet, process it.
  1317. if (null === $this->metadata) {
  1318. $header_tag_http_equivs = ['content-type', 'default-style', 'refresh', 'x-ua-compatible'];
  1319. $this->metadata = [];
  1320. $metadata = [];
  1321. // Set the Generator tag
  1322. $metadata['generator'] = 'GravCMS';
  1323. // Get initial metadata for the page
  1324. $metadata = array_merge($metadata, Grav::instance()['config']->get('site.metadata'));
  1325. if (isset($this->header->metadata)) {
  1326. // Merge any site.metadata settings in with page metadata
  1327. $metadata = array_merge($metadata, $this->header->metadata);
  1328. }
  1329. // Build an array of meta objects..
  1330. foreach ((array)$metadata as $key => $value) {
  1331. // Lowercase the key
  1332. $key = strtolower($key);
  1333. // If this is a property type metadata: "og", "twitter", "facebook" etc
  1334. // Backward compatibility for nested arrays in metas
  1335. if (is_array($value)) {
  1336. foreach ($value as $property => $prop_value) {
  1337. $prop_key = $key . ':' . $property;
  1338. $this->metadata[$prop_key] = [
  1339. 'name' => $prop_key,
  1340. 'property' => $prop_key,
  1341. 'content' => htmlspecialchars($prop_value, ENT_QUOTES, 'UTF-8')
  1342. ];
  1343. }
  1344. } else {
  1345. // If it this is a standard meta data type
  1346. if ($value) {
  1347. if (in_array($key, $header_tag_http_equivs)) {
  1348. $this->metadata[$key] = [
  1349. 'http_equiv' => $key,
  1350. 'content' => htmlspecialchars($value, ENT_QUOTES, 'UTF-8')
  1351. ];
  1352. } elseif ($key === 'charset') {
  1353. $this->metadata[$key] = ['charset' => htmlspecialchars($value, ENT_QUOTES, 'UTF-8')];
  1354. } else {
  1355. // if it's a social metadata with separator, render as property
  1356. $separator = strpos($key, ':');
  1357. $hasSeparator = $separator && $separator < strlen($key) - 1;
  1358. $entry = [
  1359. 'content' => htmlspecialchars($value, ENT_QUOTES, 'UTF-8')
  1360. ];
  1361. if ($hasSeparator && !Utils::startsWith($key, 'twitter')) {
  1362. $entry['property'] = $key;
  1363. } else {
  1364. $entry['name'] = $key;
  1365. }
  1366. $this->metadata[$key] = $entry;
  1367. }
  1368. }
  1369. }
  1370. }
  1371. }
  1372. return $this->metadata;
  1373. }
  1374. /**
  1375. * Gets and Sets the slug for the Page. The slug is used in the URL routing. If not set it uses
  1376. * the parent folder from the path
  1377. *
  1378. * @param string $var the slug, e.g. 'my-blog'
  1379. *
  1380. * @return string the slug
  1381. */
  1382. public function slug($var = null)
  1383. {
  1384. if ($var !== null && $var !== '') {
  1385. $this->slug = $var;
  1386. }
  1387. if (empty($this->slug)) {
  1388. $this->slug = $this->adjustRouteCase(preg_replace(PAGE_ORDER_PREFIX_REGEX, '', $this->folder)) ?: null;
  1389. }
  1390. return $this->slug;
  1391. }
  1392. /**
  1393. * Get/set order number of this page.
  1394. *
  1395. * @param int $var
  1396. *
  1397. * @return int|bool
  1398. */
  1399. public function order($var = null)
  1400. {
  1401. if ($var !== null) {
  1402. $order = !empty($var) ? sprintf('%02d.', (int)$var) : '';
  1403. $this->folder($order . preg_replace(PAGE_ORDER_PREFIX_REGEX, '', $this->folder));
  1404. return $order;
  1405. }
  1406. preg_match(PAGE_ORDER_PREFIX_REGEX, $this->folder, $order);
  1407. return isset($order[0]) ? $order[0] : false;
  1408. }
  1409. /**
  1410. * Gets the URL for a page - alias of url().
  1411. *
  1412. * @param bool $include_host
  1413. *
  1414. * @return string the permalink
  1415. */
  1416. public function link($include_host = false)
  1417. {
  1418. return $this->url($include_host);
  1419. }
  1420. /**
  1421. * Gets the URL with host information, aka Permalink.
  1422. * @return string The permalink.
  1423. */
  1424. public function permalink()
  1425. {
  1426. return $this->url(true, false, true, true);
  1427. }
  1428. /**
  1429. * Returns the canonical URL for a page
  1430. *
  1431. * @param bool $include_lang
  1432. *
  1433. * @return string
  1434. */
  1435. public function canonical($include_lang = true)
  1436. {
  1437. return $this->url(true, true, $include_lang);
  1438. }
  1439. /**
  1440. * Gets the url for the Page.
  1441. *
  1442. * @param bool $include_host Defaults false, but true would include http://yourhost.com
  1443. * @param bool $canonical True to return the canonical URL
  1444. * @param bool $include_base Include base url on multisite as well as language code
  1445. * @param bool $raw_route
  1446. *
  1447. * @return string The url.
  1448. */
  1449. public function url($include_host = false, $canonical = false, $include_base = true, $raw_route = false)
  1450. {
  1451. // Override any URL when external_url is set
  1452. if (isset($this->external_url)) {
  1453. return $this->external_url;
  1454. }
  1455. $grav = Grav::instance();
  1456. /** @var Pages $pages */
  1457. $pages = $grav['pages'];
  1458. /** @var Config $config */
  1459. $config = $grav['config'];
  1460. // get base route (multisite base and language)
  1461. $route = $include_base ? $pages->baseRoute() : '';
  1462. // add full route if configured to do so
  1463. if (!$include_host && $config->get('system.absolute_urls', false)) {
  1464. $include_host = true;
  1465. }
  1466. if ($canonical) {
  1467. $route .= $this->routeCanonical();
  1468. } elseif ($raw_route) {
  1469. $route .= $this->rawRoute();
  1470. } else {
  1471. $route .= $this->route();
  1472. }
  1473. /** @var Uri $uri */
  1474. $uri = $grav['uri'];
  1475. $url = $uri->rootUrl($include_host) . '/' . trim($route, '/') . $this->urlExtension();
  1476. // trim trailing / if not root
  1477. if ($url !== '/') {
  1478. $url = rtrim($url, '/');
  1479. }
  1480. return Uri::filterPath($url);
  1481. }
  1482. /**
  1483. * Gets the route for the page based on the route headers if available, else from
  1484. * the parents route and the current Page's slug.
  1485. *
  1486. * @param string $var Set new default route.
  1487. *
  1488. * @return string The route for the Page.
  1489. */
  1490. public function route($var = null)
  1491. {
  1492. if ($var !== null) {
  1493. $this->route = $var;
  1494. }
  1495. if (empty($this->route)) {
  1496. $baseRoute = null;
  1497. // calculate route based on parent slugs
  1498. $parent = $this->parent();
  1499. if (isset($parent)) {
  1500. if ($this->hide_home_route && $parent->route() === $this->home_route) {
  1501. $baseRoute = '';
  1502. } else {
  1503. $baseRoute = (string)$parent->route();
  1504. }
  1505. }
  1506. $this->route = isset($baseRoute) ? $baseRoute . '/' . $this->slug() : null;
  1507. if (!empty($this->routes) && isset($this->routes['default'])) {
  1508. $this->routes['aliases'][] = $this->route;
  1509. $this->route = $this->routes['default'];
  1510. return $this->route;
  1511. }
  1512. }
  1513. return $this->route;
  1514. }
  1515. /**
  1516. * Helper method to clear the route out so it regenerates next time you use it
  1517. */
  1518. public function unsetRouteSlug()
  1519. {
  1520. unset($this->route);
  1521. unset($this->slug);
  1522. }
  1523. /**
  1524. * Gets and Sets the page raw route
  1525. *
  1526. * @param null $var
  1527. *
  1528. * @return null|string
  1529. */
  1530. public function rawRoute($var = null)
  1531. {
  1532. if ($var !== null) {
  1533. $this->raw_route = $var;
  1534. }
  1535. if (empty($this->raw_route)) {
  1536. $baseRoute = $this->parent ? (string)$this->parent()->rawRoute() : null;
  1537. $slug = $this->adjustRouteCase(preg_replace(PAGE_ORDER_PREFIX_REGEX, '', $this->folder));
  1538. $this->raw_route = isset($baseRoute) ? $baseRoute . '/' . $slug : null;
  1539. }
  1540. return $this->raw_route;
  1541. }
  1542. /**
  1543. * Gets the route aliases for the page based on page headers.
  1544. *
  1545. * @param array $var list of route aliases
  1546. *
  1547. * @return array The route aliases for the Page.
  1548. */
  1549. public function routeAliases($var = null)
  1550. {
  1551. if ($var !== null) {
  1552. $this->routes['aliases'] = (array)$var;
  1553. }
  1554. if (!empty($this->routes) && isset($this->routes['aliases'])) {
  1555. return $this->routes['aliases'];
  1556. }
  1557. return [];
  1558. }
  1559. /**
  1560. * Gets the canonical route for this page if its set. If provided it will use
  1561. * that value, else if it's `true` it will use the default route.
  1562. *
  1563. * @param null $var
  1564. *
  1565. * @return bool|string
  1566. */
  1567. public function routeCanonical($var = null)
  1568. {
  1569. if ($var !== null) {
  1570. $this->routes['canonical'] = $var;
  1571. }
  1572. if (!empty($this->routes) && isset($this->routes['canonical'])) {
  1573. return $this->routes['canonical'];
  1574. }
  1575. return $this->route();
  1576. }
  1577. /**
  1578. * Gets and sets the identifier for this Page object.
  1579. *
  1580. * @param string $var the identifier
  1581. *
  1582. * @return string the identifier
  1583. */
  1584. public function id($var = null)
  1585. {
  1586. if ($var !== null) {
  1587. // store unique per language
  1588. $active_lang = Grav::instance()['language']->getLanguage() ?: '';
  1589. $id = $active_lang . $var;
  1590. $this->id = $id;
  1591. }
  1592. return $this->id;
  1593. }
  1594. /**
  1595. * Gets and sets the modified timestamp.
  1596. *
  1597. * @param int $var modified unix timestamp
  1598. *
  1599. * @return int modified unix timestamp
  1600. */
  1601. public function modified($var = null)
  1602. {
  1603. if ($var !== null) {
  1604. $this->modified = $var;
  1605. }
  1606. return $this->modified;
  1607. }
  1608. /**
  1609. * Gets the redirect set in the header.
  1610. *
  1611. * @param string $var redirect url
  1612. *
  1613. * @return string
  1614. */
  1615. public function redirect($var = null)
  1616. {
  1617. if ($var !== null) {
  1618. $this->redirect = $var;
  1619. }
  1620. return $this->redirect;
  1621. }
  1622. /**
  1623. * Gets and sets the option to show the etag header for the page.
  1624. *
  1625. * @param boolean $var show etag header
  1626. *
  1627. * @return boolean show etag header
  1628. */
  1629. public function eTag($var = null)
  1630. {
  1631. if ($var !== null) {
  1632. $this->etag = $var;
  1633. }
  1634. if (!isset($this->etag)) {
  1635. $this->etag = (bool)Grav::instance()['config']->get('system.pages.etag');
  1636. }
  1637. return $this->etag;
  1638. }
  1639. /**
  1640. * Gets and sets the option to show the last_modified header for the page.
  1641. *
  1642. * @param boolean $var show last_modified header
  1643. *
  1644. * @return boolean show last_modified header
  1645. */
  1646. public function lastModified($var = null)
  1647. {
  1648. if ($var !== null) {
  1649. $this->last_modified = $var;
  1650. }
  1651. if (!isset($this->last_modified)) {
  1652. $this->last_modified = (bool)Grav::instance()['config']->get('system.pages.last_modified');
  1653. }
  1654. return $this->last_modified;
  1655. }
  1656. /**
  1657. * Gets and sets the path to the .md file for this Page object.
  1658. *
  1659. * @param string $var the file path
  1660. *
  1661. * @return string|null the file path
  1662. */
  1663. public function filePath($var = null)
  1664. {
  1665. if ($var !== null) {
  1666. // Filename of the page.
  1667. $this->name = basename($var);
  1668. // Folder of the page.
  1669. $this->folder = basename(dirname($var));
  1670. // Path to the page.
  1671. $this->path = dirname(dirname($var));
  1672. }
  1673. return $this->path . '/' . $this->folder . '/' . ($this->name ?: '');
  1674. }
  1675. /**
  1676. * Gets the relative path to the .md file
  1677. *
  1678. * @return string The relative file path
  1679. */
  1680. public function filePathClean()
  1681. {
  1682. $path = str_replace(ROOT_DIR, '', $this->filePath());
  1683. return $path;
  1684. }
  1685. /**
  1686. * Returns the clean path to the page file
  1687. */
  1688. public function relativePagePath()
  1689. {
  1690. $path = str_replace('/' . $this->name(), '', $this->filePathClean());
  1691. return $path;
  1692. }
  1693. /**
  1694. * Gets and sets the path to the folder where the .md for this Page object resides.
  1695. * This is equivalent to the filePath but without the filename.
  1696. *
  1697. * @param string $var the path
  1698. *
  1699. * @return string|null the path
  1700. */
  1701. public function path($var = null)
  1702. {
  1703. if ($var !== null) {
  1704. // Folder of the page.
  1705. $this->folder = basename($var);
  1706. // Path to the page.
  1707. $this->path = dirname($var);
  1708. }
  1709. return $this->path ? $this->path . '/' . $this->folder : null;
  1710. }
  1711. /**
  1712. * Get/set the folder.
  1713. *
  1714. * @param string $var Optional path
  1715. *
  1716. * @return string|null
  1717. */
  1718. public function folder($var = null)
  1719. {
  1720. if ($var !== null) {
  1721. $this->folder = $var;
  1722. }
  1723. return $this->folder;
  1724. }
  1725. /**
  1726. * Gets and sets the date for this Page object. This is typically passed in via the page headers
  1727. *
  1728. * @param string $var string representation of a date
  1729. *
  1730. * @return int unix timestamp representation of the date
  1731. */
  1732. public function date($var = null)
  1733. {
  1734. if ($var !== null) {
  1735. $this->date = Utils::date2timestamp($var, $this->dateformat);
  1736. }
  1737. if (!$this->date) {
  1738. $this->date = $this->modified;
  1739. }
  1740. return $this->date;
  1741. }
  1742. /**
  1743. * Gets and sets the date format for this Page object. This is typically passed in via the page headers
  1744. * using typical PHP date string structure - http://php.net/manual/en/function.date.php
  1745. *
  1746. * @param string $var string representation of a date format
  1747. *
  1748. * @return string string representation of a date format
  1749. */
  1750. public function dateformat($var = null)
  1751. {
  1752. if ($var !== null) {
  1753. $this->dateformat = $var;
  1754. }
  1755. return $this->dateformat;
  1756. }
  1757. /**
  1758. * Gets and sets the order by which any sub-pages should be sorted.
  1759. *
  1760. * @param string $var the order, either "asc" or "desc"
  1761. *
  1762. * @return string the order, either "asc" or "desc"
  1763. */
  1764. public function orderDir($var = null)
  1765. {
  1766. if ($var !== null) {
  1767. $this->order_dir = $var;
  1768. }
  1769. if (empty($this->order_dir)) {
  1770. $this->order_dir = 'asc';
  1771. }
  1772. return $this->order_dir;
  1773. }
  1774. /**
  1775. * Gets and sets the order by which the sub-pages should be sorted.
  1776. *
  1777. * default - is the order based on the file system, ie 01.Home before 02.Advark
  1778. * title - is the order based on the title set in the pages
  1779. * date - is the order based on the date set in the pages
  1780. * folder - is the order based on the name of the folder with any numerics omitted
  1781. *
  1782. * @param string $var supported options include "default", "title", "date", and "folder"
  1783. *
  1784. * @return string supported options include "default", "title", "date", and "folder"
  1785. */
  1786. public function orderBy($var = null)
  1787. {
  1788. if ($var !== null) {
  1789. $this->order_by = $var;
  1790. }
  1791. return $this->order_by;
  1792. }
  1793. /**
  1794. * Gets the manual order set in the header.
  1795. *
  1796. * @param string $var supported options include "default", "title", "date", and "folder"
  1797. *
  1798. * @return array
  1799. */
  1800. public function orderManual($var = null)
  1801. {
  1802. if ($var !== null) {
  1803. $this->order_manual = $var;
  1804. }
  1805. return (array)$this->order_manual;
  1806. }
  1807. /**
  1808. * Gets and sets the maxCount field which describes how many sub-pages should be displayed if the
  1809. * sub_pages header property is set for this page object.
  1810. *
  1811. * @param int $var the maximum number of sub-pages
  1812. *
  1813. * @return int the maximum number of sub-pages
  1814. */
  1815. public function maxCount($var = null)
  1816. {
  1817. if ($var !== null) {
  1818. $this->max_count = (int)$var;
  1819. }
  1820. if (empty($this->max_count)) {
  1821. /** @var Config $config */
  1822. $config = Grav::instance()['config'];
  1823. $this->max_count = (int)$config->get('system.pages.list.count');
  1824. }
  1825. return $this->max_count;
  1826. }
  1827. /**
  1828. * Gets and sets the taxonomy array which defines which taxonomies this page identifies itself with.
  1829. *
  1830. * @param array $var an array of taxonomies
  1831. *
  1832. * @return array an array of taxonomies
  1833. */
  1834. public function taxonomy($var = null)
  1835. {
  1836. if ($var !== null) {
  1837. $this->taxonomy = $var;
  1838. }
  1839. return $this->taxonomy;
  1840. }
  1841. /**
  1842. * Gets and sets the modular var that helps identify this page is a modular child
  1843. *
  1844. * @param bool $var true if modular_twig
  1845. *
  1846. * @return bool true if modular_twig
  1847. */
  1848. public function modular($var = null)
  1849. {
  1850. return $this->modularTwig($var);
  1851. }
  1852. /**
  1853. * Gets and sets the modular_twig var that helps identify this page as a modular child page that will need
  1854. * twig processing handled differently from a regular page.
  1855. *
  1856. * @param bool $var true if modular_twig
  1857. *
  1858. * @return bool true if modular_twig
  1859. */
  1860. public function modularTwig($var = null)
  1861. {
  1862. if ($var !== null) {
  1863. $this->modular_twig = (bool)$var;
  1864. if ($var) {
  1865. $this->visible(false);
  1866. // some routable logic
  1867. if (empty($this->header->routable)) {
  1868. $this->routable = false;
  1869. }
  1870. }
  1871. }
  1872. return $this->modular_twig;
  1873. }
  1874. /**
  1875. * Gets the configured state of the processing method.
  1876. *
  1877. * @param string $process the process, eg "twig" or "markdown"
  1878. *
  1879. * @return bool whether or not the processing method is enabled for this Page
  1880. */
  1881. public function shouldProcess($process)
  1882. {
  1883. return isset($this->process[$process]) ? (bool)$this->process[$process] : false;
  1884. }
  1885. /**
  1886. * Gets and Sets the parent object for this page
  1887. *
  1888. * @param Page $var the parent page object
  1889. *
  1890. * @return Page|null the parent page object if it exists.
  1891. */
  1892. public function parent(Page $var = null)
  1893. {
  1894. if ($var) {
  1895. $this->parent = $var->path();
  1896. return $var;
  1897. }
  1898. /** @var Pages $pages */
  1899. $pages = Grav::instance()['pages'];
  1900. return $pages->get($this->parent);
  1901. }
  1902. /**
  1903. * Gets the top parent object for this page
  1904. *
  1905. * @return Page|null the top parent page object if it exists.
  1906. */
  1907. public function topParent()
  1908. {
  1909. $topParent = $this->parent();
  1910. if (!$topParent) {
  1911. return null;
  1912. }
  1913. while (true) {
  1914. $theParent = $topParent->parent();
  1915. if ($theParent !== null && $theParent->parent() !== null) {
  1916. $topParent = $theParent;
  1917. } else {
  1918. break;
  1919. }
  1920. }
  1921. return $topParent;
  1922. }
  1923. /**
  1924. * Returns children of this page.
  1925. *
  1926. * @return \Grav\Common\Page\Collection
  1927. */
  1928. public function children()
  1929. {
  1930. /** @var Pages $pages */
  1931. $pages = Grav::instance()['pages'];
  1932. return $pages->children($this->path());
  1933. }
  1934. /**
  1935. * Check to see if this item is the first in an array of sub-pages.
  1936. *
  1937. * @return boolean True if item is first.
  1938. */
  1939. public function isFirst()
  1940. {
  1941. $collection = $this->parent()->collection('content', false);
  1942. if ($collection instanceof Collection) {
  1943. return $collection->isFirst($this->path());
  1944. }
  1945. return true;
  1946. }
  1947. /**
  1948. * Check to see if this item is the last in an array of sub-pages.
  1949. *
  1950. * @return boolean True if item is last
  1951. */
  1952. public function isLast()
  1953. {
  1954. $collection = $this->parent()->collection('content', false);
  1955. if ($collection instanceof Collection) {
  1956. return $collection->isLast($this->path());
  1957. }
  1958. return true;
  1959. }
  1960. /**
  1961. * Gets the previous sibling based on current position.
  1962. *
  1963. * @return Page the previous Page item
  1964. */
  1965. public function prevSibling()
  1966. {
  1967. return $this->adjacentSibling(-1);
  1968. }
  1969. /**
  1970. * Gets the next sibling based on current position.
  1971. *
  1972. * @return Page the next Page item
  1973. */
  1974. public function nextSibling()
  1975. {
  1976. return $this->adjacentSibling(1);
  1977. }
  1978. /**
  1979. * Returns the adjacent sibling based on a direction.
  1980. *
  1981. * @param integer $direction either -1 or +1
  1982. *
  1983. * @return Page|bool the sibling page
  1984. */
  1985. public function adjacentSibling($direction = 1)
  1986. {
  1987. $collection = $this->parent()->collection('content', false);
  1988. if ($collection instanceof Collection) {
  1989. return $collection->adjacentSibling($this->path(), $direction);
  1990. }
  1991. return false;
  1992. }
  1993. /**
  1994. * Returns the item in the current position.
  1995. *
  1996. * @param string $path the path the item
  1997. *
  1998. * @return Integer the index of the current page.
  1999. */
  2000. public function currentPosition()
  2001. {
  2002. $collection = $this->parent()->collection('content', false);
  2003. if ($collection instanceof Collection) {
  2004. return $collection->currentPosition($this->path());
  2005. }
  2006. return true;
  2007. }
  2008. /**
  2009. * Returns whether or not this page is the currently active page requested via the URL.
  2010. *
  2011. * @return bool True if it is active
  2012. */
  2013. public function active()
  2014. {
  2015. $uri_path = rtrim(urldecode(Grav::instance()['uri']->path()), '/') ?: '/';
  2016. $routes = Grav::instance()['pages']->routes();
  2017. if (isset($routes[$uri_path])) {
  2018. if ($routes[$uri_path] === $this->path()) {
  2019. return true;
  2020. }
  2021. }
  2022. return false;
  2023. }
  2024. /**
  2025. * Returns whether or not this URI's URL contains the URL of the active page.
  2026. * Or in other words, is this page's URL in the current URL
  2027. *
  2028. * @return bool True if active child exists
  2029. */
  2030. public function activeChild()
  2031. {
  2032. $uri = Grav::instance()['uri'];
  2033. $pages = Grav::instance()['pages'];
  2034. $uri_path = rtrim(urldecode($uri->path()), '/');
  2035. $routes = Grav::instance()['pages']->routes();
  2036. if (isset($routes[$uri_path])) {
  2037. /** @var Page $child_page */
  2038. $child_page = $pages->dispatch($uri->route())->parent();
  2039. if ($child_page) {
  2040. while (!$child_page->root()) {
  2041. if ($this->path() === $child_page->path()) {
  2042. return true;
  2043. }
  2044. $child_page = $child_page->parent();
  2045. }
  2046. }
  2047. }
  2048. return false;
  2049. }
  2050. /**
  2051. * Returns whether or not this page is the currently configured home page.
  2052. *
  2053. * @return bool True if it is the homepage
  2054. */
  2055. public function home()
  2056. {
  2057. $home = Grav::instance()['config']->get('system.home.alias');
  2058. $is_home = ($this->route() === $home || $this->rawRoute() === $home);
  2059. return $is_home;
  2060. }
  2061. /**
  2062. * Returns whether or not this page is the root node of the pages tree.
  2063. *
  2064. * @return bool True if it is the root
  2065. */
  2066. public function root()
  2067. {
  2068. if (!$this->parent && !$this->name && !$this->visible) {
  2069. return true;
  2070. }
  2071. return false;
  2072. }
  2073. /**
  2074. * Helper method to return an ancestor page.
  2075. *
  2076. * @param string $url The url of the page
  2077. * @param bool $lookup Name of the parent folder
  2078. *
  2079. * @return \Grav\Common\Page\Page page you were looking for if it exists
  2080. */
  2081. public function ancestor($lookup = null)
  2082. {
  2083. /** @var Pages $pages */
  2084. $pages = Grav::instance()['pages'];
  2085. return $pages->ancestor($this->route, $lookup);
  2086. }
  2087. /**
  2088. * Helper method to return an ancestor page to inherit from. The current
  2089. * page object is returned.
  2090. *
  2091. * @param string $field Name of the parent folder
  2092. *
  2093. * @return Page
  2094. */
  2095. public function inherited($field)
  2096. {
  2097. list($inherited, $currentParams) = $this->getInheritedParams($field);
  2098. $this->modifyHeader($field, $currentParams);
  2099. return $inherited;
  2100. }
  2101. /**
  2102. * Helper method to return an ancestor field only to inherit from. The
  2103. * first occurrence of an ancestor field will be returned if at all.
  2104. *
  2105. * @param string $field Name of the parent folder
  2106. *
  2107. * @return array
  2108. */
  2109. public function inheritedField($field)
  2110. {
  2111. list($inherited, $currentParams) = $this->getInheritedParams($field);
  2112. return $currentParams;
  2113. }
  2114. /**
  2115. * Method that contains shared logic for inherited() and inheritedField()
  2116. *
  2117. * @param string $field Name of the parent folder
  2118. *
  2119. * @return array
  2120. */
  2121. protected function getInheritedParams($field)
  2122. {
  2123. $pages = Grav::instance()['pages'];
  2124. /** @var Pages $pages */
  2125. $inherited = $pages->inherited($this->route, $field);
  2126. $inheritedParams = (array)$inherited->value('header.' . $field);
  2127. $currentParams = (array)$this->value('header.' . $field);
  2128. if ($inheritedParams && is_array($inheritedParams)) {
  2129. $currentParams = array_replace_recursive($inheritedParams, $currentParams);
  2130. }
  2131. return [$inherited, $currentParams];
  2132. }
  2133. /**
  2134. * Helper method to return a page.
  2135. *
  2136. * @param string $url the url of the page
  2137. * @param bool $all
  2138. *
  2139. * @return \Grav\Common\Page\Page page you were looking for if it exists
  2140. */
  2141. public function find($url, $all = false)
  2142. {
  2143. /** @var Pages $pages */
  2144. $pages = Grav::instance()['pages'];
  2145. return $pages->find($url, $all);
  2146. }
  2147. /**
  2148. * Get a collection of pages in the current context.
  2149. *
  2150. * @param string|array $params
  2151. * @param boolean $pagination
  2152. *
  2153. * @return Collection
  2154. * @throws \InvalidArgumentException
  2155. */
  2156. public function collection($params = 'content', $pagination = true)
  2157. {
  2158. if (is_string($params)) {
  2159. $params = (array)$this->value('header.' . $params);
  2160. } elseif (!is_array($params)) {
  2161. throw new \InvalidArgumentException('Argument should be either header variable name or array of parameters');
  2162. }
  2163. if (!isset($params['items'])) {
  2164. return new Collection();
  2165. }
  2166. // See if require published filter is set and use that, if assume published=true
  2167. $only_published = true;
  2168. if (isset($params['filter']['published']) && $params['filter']['published']) {
  2169. $only_published = false;
  2170. } elseif (isset($params['filter']['non-published']) && $params['filter']['non-published']) {
  2171. $only_published = false;
  2172. }
  2173. $collection = $this->evaluate($params['items'], $only_published);
  2174. if (!$collection instanceof Collection) {
  2175. $collection = new Collection();
  2176. }
  2177. $collection->setParams($params);
  2178. /** @var Uri $uri */
  2179. $uri = Grav::instance()['uri'];
  2180. /** @var Config $config */
  2181. $config = Grav::instance()['config'];
  2182. $process_taxonomy = isset($params['url_taxonomy_filters']) ? $params['url_taxonomy_filters'] : $config->get('system.pages.url_taxonomy_filters');
  2183. if ($process_taxonomy) {
  2184. foreach ((array)$config->get('site.taxonomies') as $taxonomy) {
  2185. if ($uri->param(rawurlencode($taxonomy))) {
  2186. $items = explode(',', $uri->param($taxonomy));
  2187. $collection->setParams(['taxonomies' => [$taxonomy => $items]]);
  2188. foreach ($collection as $page) {
  2189. // Don't filter modular pages
  2190. if ($page->modular()) {
  2191. continue;
  2192. }
  2193. foreach ($items as $item) {
  2194. $item = rawurldecode($item);
  2195. if (empty($page->taxonomy[$taxonomy]) || !in_array(htmlspecialchars_decode($item,
  2196. ENT_QUOTES), $page->taxonomy[$taxonomy])
  2197. ) {
  2198. $collection->remove($page->path());
  2199. }
  2200. }
  2201. }
  2202. }
  2203. }
  2204. }
  2205. // If a filter or filters are set, filter the collection...
  2206. if (isset($params['filter'])) {
  2207. // remove any inclusive sets from filer:
  2208. $sets = ['published', 'visible', 'modular', 'routable'];
  2209. foreach ($sets as $type) {
  2210. if (isset($params['filter'][$type]) && isset($params['filter']['non-'.$type])) {
  2211. if ($params['filter'][$type] && $params['filter']['non-'.$type]) {
  2212. unset ($params['filter'][$type]);
  2213. unset ($params['filter']['non-'.$type]);
  2214. }
  2215. }
  2216. }
  2217. foreach ((array)$params['filter'] as $type => $filter) {
  2218. switch ($type) {
  2219. case 'published':
  2220. if ((bool) $filter) {
  2221. $collection->published();
  2222. }
  2223. break;
  2224. case 'non-published':
  2225. if ((bool) $filter) {
  2226. $collection->nonPublished();
  2227. }
  2228. break;
  2229. case 'visible':
  2230. if ((bool) $filter) {
  2231. $collection->visible();
  2232. }
  2233. break;
  2234. case 'non-visible':
  2235. if ((bool) $filter) {
  2236. $collection->nonVisible();
  2237. }
  2238. break;
  2239. case 'modular':
  2240. if ((bool) $filter) {
  2241. $collection->modular();
  2242. }
  2243. break;
  2244. case 'non-modular':
  2245. if ((bool) $filter) {
  2246. $collection->nonModular();
  2247. }
  2248. break;
  2249. case 'routable':
  2250. if ((bool) $filter) {
  2251. $collection->routable();
  2252. }
  2253. break;
  2254. case 'non-routable':
  2255. if ((bool) $filter) {
  2256. $collection->nonRoutable();
  2257. }
  2258. break;
  2259. case 'type':
  2260. $collection->ofType($filter);
  2261. break;
  2262. case 'types':
  2263. $collection->ofOneOfTheseTypes($filter);
  2264. break;
  2265. case 'access':
  2266. $collection->ofOneOfTheseAccessLevels($filter);
  2267. break;
  2268. }
  2269. }
  2270. }
  2271. if (isset($params['dateRange'])) {
  2272. $start = isset($params['dateRange']['start']) ? $params['dateRange']['start'] : 0;
  2273. $end = isset($params['dateRange']['end']) ? $params['dateRange']['end'] : false;
  2274. $field = isset($params['dateRange']['field']) ? $params['dateRange']['field'] : false;
  2275. $collection->dateRange($start, $end, $field);
  2276. }
  2277. if (isset($params['order'])) {
  2278. $by = isset($params['order']['by']) ? $params['order']['by'] : 'default';
  2279. $dir = isset($params['order']['dir']) ? $params['order']['dir'] : 'asc';
  2280. $custom = isset($params['order']['custom']) ? $params['order']['custom'] : null;
  2281. $sort_flags = isset($params['order']['sort_flags']) ? $params['order']['sort_flags'] : null;
  2282. if (is_array($sort_flags)) {
  2283. $sort_flags = array_map('constant', $sort_flags); //transform strings to constant value
  2284. $sort_flags = array_reduce($sort_flags, function ($a, $b) {
  2285. return $a | $b;
  2286. }, 0); //merge constant values using bit or
  2287. }
  2288. $collection->order($by, $dir, $custom, $sort_flags);
  2289. }
  2290. /** @var Grav $grav */
  2291. $grav = Grav::instance()['grav'];
  2292. // New Custom event to handle things like pagination.
  2293. $grav->fireEvent('onCollectionProcessed', new Event(['collection' => $collection]));
  2294. // Slice and dice the collection if pagination is required
  2295. if ($pagination) {
  2296. $params = $collection->params();
  2297. $limit = isset($params['limit']) ? $params['limit'] : 0;
  2298. $start = !empty($params['pagination']) ? ($uri->currentPage() - 1) * $limit : 0;
  2299. if ($limit && $collection->count() > $limit) {
  2300. $collection->slice($start, $limit);
  2301. }
  2302. }
  2303. return $collection;
  2304. }
  2305. /**
  2306. * @param string|array $value
  2307. * @param bool $only_published
  2308. * @return mixed
  2309. * @internal
  2310. */
  2311. public function evaluate($value, $only_published = true)
  2312. {
  2313. // Parse command.
  2314. if (is_string($value)) {
  2315. // Format: @command.param
  2316. $cmd = $value;
  2317. $params = [];
  2318. } elseif (is_array($value) && count($value) == 1 && !is_int(key($value))) {
  2319. // Format: @command.param: { attr1: value1, attr2: value2 }
  2320. $cmd = (string)key($value);
  2321. $params = (array)current($value);
  2322. } else {
  2323. $result = [];
  2324. foreach ((array)$value as $key => $val) {
  2325. if (is_int($key)) {
  2326. $result = $result + $this->evaluate($val)->toArray();
  2327. } else {
  2328. $result = $result + $this->evaluate([$key => $val])->toArray();
  2329. }
  2330. }
  2331. return new Collection($result);
  2332. }
  2333. /** @var Pages $pages */
  2334. $pages = Grav::instance()['pages'];
  2335. $parts = explode('.', $cmd);
  2336. $current = array_shift($parts);
  2337. /** @var Collection $results */
  2338. $results = new Collection();
  2339. switch ($current) {
  2340. case 'self@':
  2341. case '@self':
  2342. if (!empty($parts)) {
  2343. switch ($parts[0]) {
  2344. case 'modular':
  2345. // @self.modular: false (alternative to @self.children)
  2346. if (!empty($params) && $params[0] === false) {
  2347. $results = $this->children()->nonModular();
  2348. break;
  2349. }
  2350. $results = $this->children()->modular();
  2351. break;
  2352. case 'children':
  2353. $results = $this->children()->nonModular();
  2354. break;
  2355. case 'all':
  2356. $results = $this->children();
  2357. break;
  2358. case 'parent':
  2359. $collection = new Collection();
  2360. $results = $collection->addPage($this->parent());
  2361. break;
  2362. case 'siblings':
  2363. if (!$this->parent()) {
  2364. return new Collection();
  2365. }
  2366. $results = $this->parent()->children()->remove($this->path());
  2367. break;
  2368. case 'descendants':
  2369. $results = $pages->all($this)->remove($this->path())->nonModular();
  2370. break;
  2371. }
  2372. }
  2373. break;
  2374. case 'page@':
  2375. case '@page':
  2376. $page = null;
  2377. if (!empty($params)) {
  2378. $page = $this->find($params[0]);
  2379. }
  2380. // safety check in case page is not found
  2381. if (!isset($page)) {
  2382. return $results;
  2383. }
  2384. // Handle a @page.descendants
  2385. if (!empty($parts)) {
  2386. switch ($parts[0]) {
  2387. case 'modular':
  2388. $results = new Collection();
  2389. foreach ($page->children() as $child) {
  2390. $results = $results->addPage($child);
  2391. }
  2392. $results->modular();
  2393. break;
  2394. case 'page':
  2395. case 'self':
  2396. $results = new Collection();
  2397. $results = $results->addPage($page)->nonModular();
  2398. break;
  2399. case 'descendants':
  2400. $results = $pages->all($page)->remove($page->path())->nonModular();
  2401. break;
  2402. case 'children':
  2403. $results = $page->children()->nonModular();
  2404. break;
  2405. }
  2406. } else {
  2407. $results = $page->children()->nonModular();
  2408. }
  2409. break;
  2410. case 'root@':
  2411. case '@root':
  2412. if (!empty($parts) && $parts[0] === 'descendants') {
  2413. $results = $pages->all($pages->root())->nonModular();
  2414. } else {
  2415. $results = $pages->root()->children()->nonModular();
  2416. }
  2417. break;
  2418. case 'taxonomy@':
  2419. case '@taxonomy':
  2420. // Gets a collection of pages by using one of the following formats:
  2421. // @taxonomy.category: blog
  2422. // @taxonomy.category: [ blog, featured ]
  2423. // @taxonomy: { category: [ blog, featured ], level: 1 }
  2424. /** @var Taxonomy $taxonomy_map */
  2425. $taxonomy_map = Grav::instance()['taxonomy'];
  2426. if (!empty($parts)) {
  2427. $params = [implode('.', $parts) => $params];
  2428. }
  2429. $results = $taxonomy_map->findTaxonomy($params);
  2430. break;
  2431. }
  2432. if ($only_published) {
  2433. $results = $results->published();
  2434. }
  2435. return $results;
  2436. }
  2437. /**
  2438. * Returns whether or not this Page object has a .md file associated with it or if its just a directory.
  2439. *
  2440. * @return bool True if its a page with a .md file associated
  2441. */
  2442. public function isPage()
  2443. {
  2444. if ($this->name) {
  2445. return true;
  2446. }
  2447. return false;
  2448. }
  2449. /**
  2450. * Returns whether or not this Page object is a directory or a page.
  2451. *
  2452. * @return bool True if its a directory
  2453. */
  2454. public function isDir()
  2455. {
  2456. return !$this->isPage();
  2457. }
  2458. /**
  2459. * Returns whether the page exists in the filesystem.
  2460. *
  2461. * @return bool
  2462. */
  2463. public function exists()
  2464. {
  2465. $file = $this->file();
  2466. return $file && $file->exists();
  2467. }
  2468. /**
  2469. * Returns whether or not the current folder exists
  2470. *
  2471. * @return bool
  2472. */
  2473. public function folderExists()
  2474. {
  2475. return file_exists($this->path());
  2476. }
  2477. /**
  2478. * Cleans the path.
  2479. *
  2480. * @param string $path the path
  2481. *
  2482. * @return string the path
  2483. */
  2484. protected function cleanPath($path)
  2485. {
  2486. $lastchunk = strrchr($path, DS);
  2487. if (strpos($lastchunk, ':') !== false) {
  2488. $path = str_replace($lastchunk, '', $path);
  2489. }
  2490. return $path;
  2491. }
  2492. /**
  2493. * Reorders all siblings according to a defined order
  2494. *
  2495. * @param $new_order
  2496. */
  2497. protected function doReorder($new_order)
  2498. {
  2499. if (!$this->_original) {
  2500. return;
  2501. }
  2502. $pages = Grav::instance()['pages'];
  2503. $pages->init();
  2504. $this->_original->path($this->path());
  2505. $siblings = $this->parent()->children();
  2506. $siblings->order('slug', 'asc', $new_order);
  2507. $counter = 0;
  2508. // Reorder all moved pages.
  2509. foreach ($siblings as $slug => $page) {
  2510. $order = (int)trim($page->order(), '.');
  2511. $counter++;
  2512. if ($order) {
  2513. if ($page->path() === $this->path() && $this->folderExists()) {
  2514. // Handle current page; we do want to change ordering number, but nothing else.
  2515. $this->order($counter);
  2516. $this->save(false);
  2517. } else {
  2518. // Handle all the other pages.
  2519. $page = $pages->get($page->path());
  2520. if ($page && $page->folderExists() && !$page->_action) {
  2521. $page = $page->move($this->parent());
  2522. $page->order($counter);
  2523. $page->save(false);
  2524. }
  2525. }
  2526. }
  2527. }
  2528. }
  2529. /**
  2530. * Moves or copies the page in filesystem.
  2531. *
  2532. * @internal
  2533. *
  2534. * @throws Exception
  2535. */
  2536. protected function doRelocation()
  2537. {
  2538. if (!$this->_original) {
  2539. return;
  2540. }
  2541. if (is_dir($this->_original->path())) {
  2542. if ($this->_action === 'move') {
  2543. Folder::move($this->_original->path(), $this->path());
  2544. } elseif ($this->_action === 'copy') {
  2545. Folder::copy($this->_original->path(), $this->path());
  2546. }
  2547. }
  2548. if ($this->name() !== $this->_original->name()) {
  2549. $path = $this->path();
  2550. if (is_file($path . '/' . $this->_original->name())) {
  2551. rename($path . '/' . $this->_original->name(), $path . '/' . $this->name());
  2552. }
  2553. }
  2554. }
  2555. protected function setPublishState()
  2556. {
  2557. // Handle publishing dates if no explicit published option set
  2558. if (Grav::instance()['config']->get('system.pages.publish_dates') && !isset($this->header->published)) {
  2559. // unpublish if required, if not clear cache right before page should be unpublished
  2560. if ($this->unpublishDate()) {
  2561. if ($this->unpublishDate() < time()) {
  2562. $this->published(false);
  2563. } else {
  2564. $this->published();
  2565. Grav::instance()['cache']->setLifeTime($this->unpublishDate());
  2566. }
  2567. }
  2568. // publish if required, if not clear cache right before page is published
  2569. if ($this->publishDate() && $this->publishDate() > time()) {
  2570. $this->published(false);
  2571. Grav::instance()['cache']->setLifeTime($this->publishDate());
  2572. }
  2573. }
  2574. }
  2575. protected function adjustRouteCase($route)
  2576. {
  2577. $case_insensitive = Grav::instance()['config']->get('system.force_lowercase_urls');
  2578. if ($case_insensitive) {
  2579. return mb_strtolower($route);
  2580. } else {
  2581. return $route;
  2582. }
  2583. }
  2584. /**
  2585. * Gets the Page Unmodified (original) version of the page.
  2586. *
  2587. * @return Page
  2588. * The original version of the page.
  2589. */
  2590. public function getOriginal()
  2591. {
  2592. return $this->_original;
  2593. }
  2594. /**
  2595. * Gets the action.
  2596. *
  2597. * @return string
  2598. * The Action string.
  2599. */
  2600. public function getAction()
  2601. {
  2602. return $this->_action;
  2603. }
  2604. }