Pico.php.txt 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253
  1. <?php
  2. /**
  3. * Pico
  4. *
  5. * Pico is a stupidly simple, blazing fast, flat file CMS.
  6. * - Stupidly Simple: Picos makes creating and maintaining a
  7. * website as simple as editing text files.
  8. * - Blazing Fast: Pico is seriously lightweight and doesn't
  9. * use a database, making it super fast.
  10. * - No Database: Pico is a "flat file" CMS, meaning no
  11. * database woes, no MySQL queries, nothing.
  12. * - Markdown Formatting: Edit your website in your favourite
  13. * text editor using simple Markdown formatting.
  14. * - Twig Templates: Pico uses the Twig templating engine,
  15. * for powerful and flexible themes.
  16. * - Open Source: Pico is completely free and open source,
  17. * released under the MIT license.
  18. * See <http://picocms.org/> for more info.
  19. *
  20. * @author Gilbert Pellegrom
  21. * @author Daniel Rudolf
  22. * @link <http://picocms.org>
  23. * @license The MIT License <http://opensource.org/licenses/MIT>
  24. * @version 1.0
  25. */
  26. class Pico
  27. {
  28. /**
  29. * Sort files in alphabetical ascending order
  30. *
  31. * @see Pico::getFiles()
  32. * @var int
  33. */
  34. const SORT_ASC = 0;
  35. /**
  36. * Sort files in alphabetical descending order
  37. *
  38. * @see Pico::getFiles()
  39. * @var int
  40. */
  41. const SORT_DESC = 1;
  42. /**
  43. * Don't sort files
  44. *
  45. * @see Pico::getFiles()
  46. * @var int
  47. */
  48. const SORT_NONE = 2;
  49. /**
  50. * Root directory of this Pico instance
  51. *
  52. * @see Pico::getRootDir()
  53. * @var string
  54. */
  55. protected $rootDir;
  56. /**
  57. * Config directory of this Pico instance
  58. *
  59. * @see Pico::getConfigDir()
  60. * @var string
  61. */
  62. protected $configDir;
  63. /**
  64. * Plugins directory of this Pico instance
  65. *
  66. * @see Pico::getPluginsDir()
  67. * @var string
  68. */
  69. protected $pluginsDir;
  70. /**
  71. * Themes directory of this Pico instance
  72. *
  73. * @see Pico::getThemesDir()
  74. * @var string
  75. */
  76. protected $themesDir;
  77. /**
  78. * Boolean indicating whether Picos processing started yet
  79. *
  80. * @var boolean
  81. */
  82. protected $locked = false;
  83. /**
  84. * List of loaded plugins
  85. *
  86. * @see Pico::getPlugins()
  87. * @var object[]|null
  88. */
  89. protected $plugins;
  90. /**
  91. * Current configuration of this Pico instance
  92. *
  93. * @see Pico::getConfig()
  94. * @var mixed[]|null
  95. */
  96. protected $config;
  97. /**
  98. * Part of the URL describing the requested contents
  99. *
  100. * @see Pico::getRequestUrl()
  101. * @var string|null
  102. */
  103. protected $requestUrl;
  104. /**
  105. * Absolute path to the content file being served
  106. *
  107. * @see Pico::getRequestFile()
  108. * @var string|null
  109. */
  110. protected $requestFile;
  111. /**
  112. * Raw, not yet parsed contents to serve
  113. *
  114. * @see Pico::getRawContent()
  115. * @var string|null
  116. */
  117. protected $rawContent;
  118. /**
  119. * Meta data of the page to serve
  120. *
  121. * @see Pico::getFileMeta()
  122. * @var string[]|null
  123. */
  124. protected $meta;
  125. /**
  126. * Parsed content being served
  127. *
  128. * @see Pico::getFileContent()
  129. * @var string|null
  130. */
  131. protected $content;
  132. /**
  133. * List of known pages
  134. *
  135. * @see Pico::getPages()
  136. * @var array[]|null
  137. */
  138. protected $pages;
  139. /**
  140. * Data of the page being served
  141. *
  142. * @see Pico::getCurrentPage()
  143. * @var array|null
  144. */
  145. protected $currentPage;
  146. /**
  147. * Data of the previous page relative to the page being served
  148. *
  149. * @see Pico::getPreviousPage()
  150. * @var array|null
  151. */
  152. protected $previousPage;
  153. /**
  154. * Data of the next page relative to the page being served
  155. *
  156. * @see Pico::getNextPage()
  157. * @var array|null
  158. */
  159. protected $nextPage;
  160. /**
  161. * Twig instance used for template parsing
  162. *
  163. * @see Pico::getTwig()
  164. * @var Twig_Environment|null
  165. */
  166. protected $twig;
  167. /**
  168. * Variables passed to the twig template
  169. *
  170. * @see Pico::getTwigVariables
  171. * @var mixed[]|null
  172. */
  173. protected $twigVariables;
  174. /**
  175. * Constructs a new Pico instance
  176. *
  177. * To carry out all the processing in Pico, call {@link Pico::run()}.
  178. *
  179. * @param string $rootDir root directory of this Pico instance
  180. * @param string $configDir config directory of this Pico instance
  181. * @param string $pluginsDir plugins directory of this Pico instance
  182. * @param string $themesDir themes directory of this Pico instance
  183. */
  184. public function __construct($rootDir, $configDir, $pluginsDir, $themesDir)
  185. {
  186. $this->rootDir = rtrim($rootDir, '/') . '/';
  187. $this->configDir = $this->getAbsolutePath($configDir);
  188. $this->pluginsDir = $this->getAbsolutePath($pluginsDir);
  189. $this->themesDir = $this->getAbsolutePath($themesDir);
  190. }
  191. /**
  192. * Returns the root directory of this Pico instance
  193. *
  194. * @return string root directory path
  195. */
  196. public function getRootDir()
  197. {
  198. return $this->rootDir;
  199. }
  200. /**
  201. * Returns the config directory of this Pico instance
  202. *
  203. * @return string config directory path
  204. */
  205. public function getConfigDir()
  206. {
  207. return $this->configDir;
  208. }
  209. /**
  210. * Returns the plugins directory of this Pico instance
  211. *
  212. * @return string plugins directory path
  213. */
  214. public function getPluginsDir()
  215. {
  216. return $this->pluginsDir;
  217. }
  218. /**
  219. * Returns the themes directory of this Pico instance
  220. *
  221. * @return string themes directory path
  222. */
  223. public function getThemesDir()
  224. {
  225. return $this->themesDir;
  226. }
  227. /**
  228. * Runs this Pico instance
  229. *
  230. * Loads plugins, evaluates the config file, does URL routing, parses
  231. * meta headers, processes Markdown, does Twig processing and returns
  232. * the rendered contents.
  233. *
  234. * @return string rendered Pico contents
  235. */
  236. public function run()
  237. {
  238. // lock Pico
  239. $this->locked = true;
  240. // load plugins
  241. $this->loadPlugins();
  242. $this->triggerEvent('onPluginsLoaded', array(&$this->plugins));
  243. // load config
  244. $this->loadConfig();
  245. $this->triggerEvent('onConfigLoaded', array(&$this->config));
  246. // evaluate request url
  247. $this->evaluateRequestUrl();
  248. $this->triggerEvent('onRequestUrl', array(&$this->requestUrl));
  249. // discover requested file
  250. $this->discoverRequestFile();
  251. $this->triggerEvent('onRequestFile', array(&$this->requestFile));
  252. // load raw file content
  253. $this->triggerEvent('onContentLoading', array(&$this->requestFile));
  254. if (file_exists($this->requestFile)) {
  255. $this->rawContent = $this->loadFileContent($this->requestFile);
  256. } else {
  257. $this->triggerEvent('on404ContentLoading', array(&$this->requestFile));
  258. header($_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found');
  259. $this->rawContent = $this->load404Content($this->requestFile);
  260. $this->triggerEvent('on404ContentLoaded', array(&$this->rawContent));
  261. }
  262. $this->triggerEvent('onContentLoaded', array(&$this->rawContent));
  263. // parse file meta
  264. $headers = $this->getMetaHeaders();
  265. $this->triggerEvent('onMetaParsing', array(&$this->rawContent, &$headers));
  266. $this->meta = $this->parseFileMeta($this->rawContent, $headers);
  267. $this->triggerEvent('onMetaParsed', array(&$this->meta));
  268. // parse file content
  269. $this->triggerEvent('onContentParsing', array(&$this->rawContent));
  270. $this->content = $this->prepareFileContent($this->rawContent);
  271. $this->triggerEvent('onContentPrepared', array(&$this->content));
  272. $this->content = $this->parseFileContent($this->content);
  273. $this->triggerEvent('onContentParsed', array(&$this->content));
  274. // read pages
  275. $this->triggerEvent('onPagesLoading');
  276. $this->readPages();
  277. $this->sortPages();
  278. $this->discoverCurrentPage();
  279. $this->triggerEvent('onPagesLoaded', array(
  280. &$this->pages,
  281. &$this->currentPage,
  282. &$this->previousPage,
  283. &$this->nextPage
  284. ));
  285. // register twig
  286. $this->triggerEvent('onTwigRegistration');
  287. $this->registerTwig();
  288. // render template
  289. $this->twigVariables = $this->getTwigVariables();
  290. if (isset($this->meta['template']) && $this->meta['template']) {
  291. $templateName = $this->meta['template'];
  292. } else {
  293. $templateName = 'index';
  294. }
  295. if (file_exists($this->getThemesDir() . $this->getConfig('theme') . '/' . $templateName . '.twig')) {
  296. $templateName .= '.twig';
  297. } else {
  298. $templateName .= '.html';
  299. }
  300. $this->triggerEvent('onPageRendering', array(&$this->twig, &$this->twigVariables, &$templateName));
  301. $output = $this->twig->render($templateName, $this->twigVariables);
  302. $this->triggerEvent('onPageRendered', array(&$output));
  303. return $output;
  304. }
  305. /**
  306. * Loads plugins from Pico::$pluginsDir in alphabetical order
  307. *
  308. * Plugin files may be prefixed by a number (e.g. 00-PicoDeprecated.php)
  309. * to indicate their processing order. You MUST NOT use prefixes between
  310. * 00 and 19 (reserved for built-in plugins).
  311. *
  312. * @see Pico::getPlugin()
  313. * @see Pico::getPlugins()
  314. * @return void
  315. * @throws RuntimeException thrown when a plugin couldn't be loaded
  316. */
  317. protected function loadPlugins()
  318. {
  319. $this->plugins = array();
  320. $pluginFiles = $this->getFiles($this->getPluginsDir(), '.php');
  321. foreach ($pluginFiles as $pluginFile) {
  322. require_once($pluginFile);
  323. $className = preg_replace('/^[0-9]+-/', '', basename($pluginFile, '.php'));
  324. if (class_exists($className)) {
  325. // class name and file name can differ regarding case sensitivity
  326. $plugin = new $className($this);
  327. $className = get_class($plugin);
  328. $this->plugins[$className] = $plugin;
  329. } else {
  330. // TODO: breaks backward compatibility
  331. //throw new RuntimeException("Unable to load plugin '".$className."'");
  332. }
  333. }
  334. }
  335. /**
  336. * Returns the instance of a named plugin
  337. *
  338. * Plugins SHOULD implement {@link PicoPluginInterface}, but you MUST NOT
  339. * rely on it. For more information see {@link PicoPluginInterface}.
  340. *
  341. * @see Pico::loadPlugins()
  342. * @see Pico::getPlugins()
  343. * @param string $pluginName name of the plugin
  344. * @return object instance of the plugin
  345. * @throws RuntimeException thrown when the plugin wasn't found
  346. */
  347. public function getPlugin($pluginName)
  348. {
  349. if (isset($this->plugins[$pluginName])) {
  350. return $this->plugins[$pluginName];
  351. }
  352. throw new RuntimeException("Missing plugin '" . $pluginName . "'");
  353. }
  354. /**
  355. * Returns all loaded plugins
  356. *
  357. * @see Pico::loadPlugins()
  358. * @see Pico::getPlugin()
  359. * @return object[]|null
  360. */
  361. public function getPlugins()
  362. {
  363. return $this->plugins;
  364. }
  365. /**
  366. * Loads the config.php from Pico::$configDir
  367. *
  368. * @see Pico::setConfig()
  369. * @see Pico::getConfig()
  370. * @return void
  371. */
  372. protected function loadConfig()
  373. {
  374. $config = null;
  375. $defaultConfig = array(
  376. 'site_title' => 'Pico',
  377. 'base_url' => '',
  378. 'rewrite_url' => null,
  379. 'theme' => 'default',
  380. 'date_format' => '%D %T',
  381. 'twig_config' => array('cache' => false, 'autoescape' => false, 'debug' => false),
  382. 'pages_order_by' => 'alpha',
  383. 'pages_order' => 'asc',
  384. 'content_dir' => null,
  385. 'content_ext' => '.md',
  386. 'timezone' => ''
  387. );
  388. $configFile = $this->getConfigDir() . 'config.php';
  389. if (file_exists($configFile)) {
  390. require $configFile;
  391. }
  392. $this->config = is_array($this->config) ? $this->config : array();
  393. $this->config += is_array($config) ? $config + $defaultConfig : $defaultConfig;
  394. if (empty($this->config['base_url'])) {
  395. $this->config['base_url'] = $this->getBaseUrl();
  396. }
  397. if (empty($this->config['content_dir'])) {
  398. // try to guess the content directory
  399. if (is_dir($this->getRootDir() . 'content')) {
  400. $this->config['content_dir'] = $this->getRootDir() . 'content/';
  401. } else {
  402. $this->config['content_dir'] = $this->getRootDir() . 'content-sample/';
  403. }
  404. } else {
  405. $this->config['content_dir'] = $this->getAbsolutePath($this->config['content_dir']);
  406. }
  407. if (!empty($this->config['timezone'])) {
  408. date_default_timezone_set($this->config['timezone']);
  409. } else {
  410. // explicitly set a default timezone to prevent a E_NOTICE
  411. // when no timezone is set; the `date_default_timezone_get()`
  412. // function always returns a timezone, at least UTC
  413. $defaultTimezone = date_default_timezone_get();
  414. date_default_timezone_set($defaultTimezone);
  415. }
  416. }
  417. /**
  418. * Sets Picos config before calling Pico::run()
  419. *
  420. * This method allows you to modify Picos config without creating a
  421. * {@path "config/config.php"} or changing some of its variables before
  422. * Pico starts processing.
  423. *
  424. * You can call this method between {@link Pico::__construct()} and
  425. * {@link Pico::run()} only. Options set with this method cannot be
  426. * overwritten by {@path "config/config.php"}.
  427. *
  428. * @see Pico::loadConfig()
  429. * @see Pico::getConfig()
  430. * @param mixed[] $config array with config variables
  431. * @return void
  432. * @throws RuntimeException thrown if Pico already started processing
  433. */
  434. public function setConfig(array $config)
  435. {
  436. if ($this->locked) {
  437. throw new RuntimeException('You cannot modify Picos config after processing has started');
  438. }
  439. $this->config = $config;
  440. }
  441. /**
  442. * Returns either the value of the specified config variable or
  443. * the config array
  444. *
  445. * @see Pico::setConfig()
  446. * @see Pico::loadConfig()
  447. * @param string $configName optional name of a config variable
  448. * @return mixed returns either the value of the named config
  449. * variable, null if the config variable doesn't exist or the config
  450. * array if no config name was supplied
  451. */
  452. public function getConfig($configName = null)
  453. {
  454. if ($configName !== null) {
  455. return isset($this->config[$configName]) ? $this->config[$configName] : null;
  456. } else {
  457. return $this->config;
  458. }
  459. }
  460. /**
  461. * Evaluates the requested URL
  462. *
  463. * Pico 1.0 uses the `QUERY_STRING` routing method (e.g. `/pico/?sub/page`)
  464. * to support SEO-like URLs out-of-the-box with any webserver. You can
  465. * still setup URL rewriting (e.g. using `mod_rewrite` on Apache) to
  466. * basically remove the `?` from URLs, but your rewritten URLs must follow
  467. * the new `QUERY_STRING` principles. URL rewriting requires some special
  468. * configuration on your webserver, but this should be "basic work" for
  469. * any webmaster...
  470. *
  471. * Pico 0.9 and older required Apache with `mod_rewrite` enabled, thus old
  472. * plugins, templates and contents may require you to enable URL rewriting
  473. * to work. If you're upgrading from Pico 0.9, you will probably have to
  474. * update your rewriting rules.
  475. *
  476. * We recommend you to use the `link` filter in templates to create
  477. * internal links, e.g. `{{ "sub/page"|link }}` is equivalent to
  478. * `{{ base_url }}sub/page`. In content files you can still use the
  479. * `%base_url%` variable; e.g. `%base_url%?sub/page` will be automatically
  480. * replaced accordingly.
  481. *
  482. * @see Pico::getRequestUrl()
  483. * @return void
  484. */
  485. protected function evaluateRequestUrl()
  486. {
  487. // use QUERY_STRING; e.g. /pico/?sub/page
  488. // if you want to use rewriting, you MUST make your rules to
  489. // rewrite the URLs to follow the QUERY_STRING method
  490. //
  491. // Note: you MUST NOT call the index page with /pico/?someBooleanParameter;
  492. // use /pico/?someBooleanParameter= or /pico/?index&someBooleanParameter instead
  493. $pathComponent = isset($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : '';
  494. if (($pathComponentLength = strpos($pathComponent, '&')) !== false) {
  495. $pathComponent = substr($pathComponent, 0, $pathComponentLength);
  496. }
  497. $this->requestUrl = (strpos($pathComponent, '=') === false) ? urldecode($pathComponent) : '';
  498. }
  499. /**
  500. * Returns the URL where a user requested the page
  501. *
  502. * @see Pico::evaluateRequestUrl()
  503. * @return string|null request URL
  504. */
  505. public function getRequestUrl()
  506. {
  507. return $this->requestUrl;
  508. }
  509. /**
  510. * Uses the request URL to discover the content file to serve
  511. *
  512. * @see Pico::getRequestFile()
  513. * @return void
  514. */
  515. protected function discoverRequestFile()
  516. {
  517. if (empty($this->requestUrl)) {
  518. $this->requestFile = $this->getConfig('content_dir') . 'index' . $this->getConfig('content_ext');
  519. } else {
  520. // prevent content_dir breakouts using malicious request URLs
  521. // we don't use realpath() here because we neither want to check for file existance
  522. // nor prohibit symlinks which intentionally point to somewhere outside the content_dir
  523. // it is STRONGLY RECOMMENDED to use open_basedir - always, not just with Pico!
  524. $requestUrl = str_replace('\\', '/', $this->requestUrl);
  525. $requestUrlParts = explode('/', $requestUrl);
  526. $requestFileParts = array();
  527. foreach ($requestUrlParts as $requestUrlPart) {
  528. if (($requestUrlPart === '') || ($requestUrlPart === '.')) {
  529. continue;
  530. } elseif ($requestUrlPart === '..') {
  531. array_pop($requestFileParts);
  532. continue;
  533. }
  534. $requestFileParts[] = $requestUrlPart;
  535. }
  536. if (empty($requestFileParts)) {
  537. $this->requestFile = $this->getConfig('content_dir') . 'index' . $this->getConfig('content_ext');
  538. return;
  539. }
  540. // discover the content file to serve
  541. // Note: $requestFileParts neither contains a trailing nor a leading slash
  542. $this->requestFile = $this->getConfig('content_dir') . implode('/', $requestFileParts);
  543. if (is_dir($this->requestFile)) {
  544. // if no index file is found, try a accordingly named file in the previous dir
  545. // if this file doesn't exist either, show the 404 page, but assume the index
  546. // file as being requested (maintains backward compatibility to Pico < 1.0)
  547. $indexFile = $this->requestFile . '/index' . $this->getConfig('content_ext');
  548. if (file_exists($indexFile) || !file_exists($this->requestFile . $this->getConfig('content_ext'))) {
  549. $this->requestFile = $indexFile;
  550. return;
  551. }
  552. }
  553. $this->requestFile .= $this->getConfig('content_ext');
  554. }
  555. }
  556. /**
  557. * Returns the absolute path to the content file to serve
  558. *
  559. * @see Pico::discoverRequestFile()
  560. * @return string|null file path
  561. */
  562. public function getRequestFile()
  563. {
  564. return $this->requestFile;
  565. }
  566. /**
  567. * Returns the raw contents of a file
  568. *
  569. * @see Pico::getRawContent()
  570. * @param string $file file path
  571. * @return string raw contents of the file
  572. */
  573. public function loadFileContent($file)
  574. {
  575. return file_get_contents($file);
  576. }
  577. /**
  578. * Returns the raw contents of the first found 404 file when traversing
  579. * up from the directory the requested file is in
  580. *
  581. * @see Pico::getRawContent()
  582. * @param string $file path to requested (but not existing) file
  583. * @return string raw contents of the 404 file
  584. * @throws RuntimeException thrown when no suitable 404 file is found
  585. */
  586. public function load404Content($file)
  587. {
  588. $errorFileDir = substr($file, strlen($this->getConfig('content_dir')));
  589. do {
  590. $errorFileDir = dirname($errorFileDir);
  591. $errorFile = $errorFileDir . '/404' . $this->getConfig('content_ext');
  592. } while (!file_exists($this->getConfig('content_dir') . $errorFile) && ($errorFileDir !== '.'));
  593. if (!file_exists($this->getConfig('content_dir') . $errorFile)) {
  594. $errorFile = ($errorFileDir === '.') ? '404' . $this->getConfig('content_ext') : $errorFile;
  595. throw new RuntimeException('Required "' . $errorFile . '" not found');
  596. }
  597. return $this->loadFileContent($this->getConfig('content_dir') . $errorFile);
  598. }
  599. /**
  600. * Returns the raw contents, either of the requested or the 404 file
  601. *
  602. * @see Pico::loadFileContent()
  603. * @see Pico::load404Content()
  604. * @return string|null raw contents
  605. */
  606. public function getRawContent()
  607. {
  608. return $this->rawContent;
  609. }
  610. /**
  611. * Returns known meta headers and triggers the onMetaHeaders event
  612. *
  613. * Heads up! Calling this method triggers the `onMetaHeaders` event.
  614. * Keep this in mind to prevent a infinite loop!
  615. *
  616. * @return string[] known meta headers; the array value specifies the
  617. * YAML key to search for, the array key is later used to access the
  618. * found value
  619. */
  620. public function getMetaHeaders()
  621. {
  622. $headers = array(
  623. 'title' => 'Title',
  624. 'description' => 'Description',
  625. 'author' => 'Author',
  626. 'date' => 'Date',
  627. 'robots' => 'Robots',
  628. 'template' => 'Template'
  629. );
  630. $this->triggerEvent('onMetaHeaders', array(&$headers));
  631. return $headers;
  632. }
  633. /**
  634. * Parses the file meta from raw file contents
  635. *
  636. * Meta data MUST start on the first line of the file, either opened and
  637. * closed by `---` or C-style block comments (deprecated). The headers are
  638. * parsed by the YAML component of the Symfony project, keys are lowered.
  639. * If you're a plugin developer, you MUST register new headers during the
  640. * `onMetaHeaders` event first. The implicit availability of headers is
  641. * for users and pure (!) theme developers ONLY.
  642. *
  643. * @see Pico::getFileMeta()
  644. * @see <http://symfony.com/doc/current/components/yaml/introduction.html>
  645. * @param string $rawContent the raw file contents
  646. * @param string[] $headers known meta headers
  647. * @return array parsed meta data
  648. */
  649. public function parseFileMeta($rawContent, array $headers)
  650. {
  651. $meta = array();
  652. $pattern = "/^(\/(\*)|---)[[:blank:]]*(?:\r)?\n"
  653. . "(.*?)(?:\r)?\n(?(2)\*\/|---)[[:blank:]]*(?:(?:\r)?\n|$)/s";
  654. if (preg_match($pattern, $rawContent, $rawMetaMatches)) {
  655. $yamlParser = new \Symfony\Component\Yaml\Parser();
  656. $meta = $yamlParser->parse($rawMetaMatches[3]);
  657. $meta = array_change_key_case($meta, CASE_LOWER);
  658. foreach ($headers as $fieldId => $fieldName) {
  659. $fieldName = strtolower($fieldName);
  660. if (isset($meta[$fieldName])) {
  661. // rename field (e.g. remove whitespaces)
  662. if ($fieldId != $fieldName) {
  663. $meta[$fieldId] = $meta[$fieldName];
  664. unset($meta[$fieldName]);
  665. }
  666. } else {
  667. // guarantee array key existance
  668. $meta[$fieldId] = '';
  669. }
  670. }
  671. if (!empty($meta['date'])) {
  672. $meta['time'] = strtotime($meta['date']);
  673. $meta['date_formatted'] = utf8_encode(strftime($this->getConfig('date_format'), $meta['time']));
  674. } else {
  675. $meta['time'] = $meta['date_formatted'] = '';
  676. }
  677. } else {
  678. // guarantee array key existance
  679. foreach ($headers as $id => $field) {
  680. $meta[$id] = '';
  681. }
  682. $meta['time'] = $meta['date_formatted'] = '';
  683. }
  684. return $meta;
  685. }
  686. /**
  687. * Returns the parsed meta data of the requested page
  688. *
  689. * @see Pico::parseFileMeta()
  690. * @return array|null parsed meta data
  691. */
  692. public function getFileMeta()
  693. {
  694. return $this->meta;
  695. }
  696. /**
  697. * Applies some static preparations to the raw contents of a page,
  698. * e.g. removing the meta header and replacing %base_url%
  699. *
  700. * @see Pico::parseFileContent()
  701. * @see Pico::getFileContent()
  702. * @param string $rawContent raw contents of a page
  703. * @return string contents prepared for parsing
  704. */
  705. public function prepareFileContent($rawContent)
  706. {
  707. // remove meta header
  708. $metaHeaderPattern = "/^(\/(\*)|---)[[:blank:]]*(?:\r)?\n"
  709. . "(.*?)(?:\r)?\n(?(2)\*\/|---)[[:blank:]]*(?:(?:\r)?\n|$)/s";
  710. $content = preg_replace($metaHeaderPattern, '', $rawContent, 1);
  711. // replace %site_title%
  712. $content = str_replace('%site_title%', $this->getConfig('site_title'), $content);
  713. // replace %base_url%
  714. if ($this->isUrlRewritingEnabled()) {
  715. // always use `%base_url%?sub/page` syntax for internal links
  716. // we'll replace the links accordingly, depending on enabled rewriting
  717. $content = str_replace('%base_url%?', $this->getBaseUrl(), $content);
  718. } else {
  719. // actually not necessary, but makes the URL look a little nicer
  720. $content = str_replace('%base_url%?', $this->getBaseUrl() . '?', $content);
  721. }
  722. $content = str_replace('%base_url%', rtrim($this->getBaseUrl(), '/'), $content);
  723. // replace %theme_url%
  724. $themeUrl = $this->getBaseUrl() . basename($this->getThemesDir()) . '/' . $this->getConfig('theme');
  725. $content = str_replace('%theme_url%', $themeUrl, $content);
  726. // replace %meta.*%
  727. $metaKeys = $metaValues = array();
  728. foreach ($this->meta as $metaKey => $metaValue) {
  729. if (is_scalar($metaValue) || ($metaValue === null)) {
  730. $metaKeys[] = '%meta.' . $metaKey . '%';
  731. $metaValues[] = strval($metaValue);
  732. }
  733. }
  734. $content = str_replace($metaKeys, $metaValues, $content);
  735. return $content;
  736. }
  737. /**
  738. * Parses the contents of a page using ParsedownExtra
  739. *
  740. * @see Pico::prepareFileContent()
  741. * @see Pico::getFileContent()
  742. * @param string $content raw contents of a page (Markdown)
  743. * @return string parsed contents (HTML)
  744. */
  745. public function parseFileContent($content)
  746. {
  747. $parsedown = new ParsedownExtra();
  748. return $parsedown->text($content);
  749. }
  750. /**
  751. * Returns the cached contents of the requested page
  752. *
  753. * @see Pico::prepareFileContent()
  754. * @see Pico::parseFileContent()
  755. * @return string|null parsed contents
  756. */
  757. public function getFileContent()
  758. {
  759. return $this->content;
  760. }
  761. /**
  762. * Reads the data of all pages known to Pico
  763. *
  764. * The page data will be an array containing the following values:
  765. * <pre>
  766. * +----------------+--------+------------------------------------------+
  767. * | Array key | Type | Description |
  768. * +----------------+--------+------------------------------------------+
  769. * | id | string | relative path to the content file |
  770. * | url | string | URL to the page |
  771. * | title | string | title of the page (YAML header) |
  772. * | description | string | description of the page (YAML header) |
  773. * | author | string | author of the page (YAML header) |
  774. * | time | string | timestamp derived from the Date header |
  775. * | date | string | date of the page (YAML header) |
  776. * | date_formatted | string | formatted date of the page |
  777. * | raw_content | string | raw, not yet parsed contents of the page |
  778. * | meta | string | parsed meta data of the page |
  779. * +----------------+--------+------------------------------------------+
  780. * </pre>
  781. *
  782. * @see Pico::sortPages()
  783. * @see Pico::getPages()
  784. * @return void
  785. */
  786. protected function readPages()
  787. {
  788. $this->pages = array();
  789. $files = $this->getFiles($this->getConfig('content_dir'), $this->getConfig('content_ext'), Pico::SORT_NONE);
  790. foreach ($files as $i => $file) {
  791. // skip 404 page
  792. if (basename($file) == '404' . $this->getConfig('content_ext')) {
  793. unset($files[$i]);
  794. continue;
  795. }
  796. $id = substr($file, strlen($this->getConfig('content_dir')), -strlen($this->getConfig('content_ext')));
  797. // drop inaccessible pages (e.g. drop "sub.md" if "sub/index.md" exists)
  798. $conflictFile = $this->getConfig('content_dir') . $id . '/index' . $this->getConfig('content_ext');
  799. if (in_array($conflictFile, $files, true)) {
  800. continue;
  801. }
  802. $url = $this->getPageUrl($id);
  803. if ($file != $this->requestFile) {
  804. $rawContent = file_get_contents($file);
  805. $meta = $this->parseFileMeta($rawContent, $this->getMetaHeaders());
  806. } else {
  807. $rawContent = &$this->rawContent;
  808. $meta = &$this->meta;
  809. }
  810. // build page data
  811. // title, description, author and date are assumed to be pretty basic data
  812. // everything else is accessible through $page['meta']
  813. $page = array(
  814. 'id' => $id,
  815. 'url' => $url,
  816. 'title' => &$meta['title'],
  817. 'description' => &$meta['description'],
  818. 'author' => &$meta['author'],
  819. 'time' => &$meta['time'],
  820. 'date' => &$meta['date'],
  821. 'date_formatted' => &$meta['date_formatted'],
  822. 'raw_content' => &$rawContent,
  823. 'meta' => &$meta
  824. );
  825. if ($file == $this->requestFile) {
  826. $page['content'] = &$this->content;
  827. }
  828. unset($rawContent, $meta);
  829. // trigger event
  830. $this->triggerEvent('onSinglePageLoaded', array(&$page));
  831. $this->pages[$id] = $page;
  832. }
  833. }
  834. /**
  835. * Sorts all pages known to Pico
  836. *
  837. * @see Pico::readPages()
  838. * @see Pico::getPages()
  839. * @return void
  840. */
  841. protected function sortPages()
  842. {
  843. // sort pages
  844. $order = $this->getConfig('pages_order');
  845. $alphaSortClosure = function ($a, $b) use ($order) {
  846. $aSortKey = (basename($a['id']) === 'index') ? dirname($a['id']) : $a['id'];
  847. $bSortKey = (basename($b['id']) === 'index') ? dirname($b['id']) : $b['id'];
  848. $cmp = strcmp($aSortKey, $bSortKey);
  849. return $cmp * (($order == 'desc') ? -1 : 1);
  850. };
  851. if ($this->getConfig('pages_order_by') == 'date') {
  852. // sort by date
  853. uasort($this->pages, function ($a, $b) use ($alphaSortClosure, $order) {
  854. if (empty($a['time']) || empty($b['time'])) {
  855. $cmp = (empty($a['time']) - empty($b['time']));
  856. } else {
  857. $cmp = ($b['time'] - $a['time']);
  858. }
  859. if ($cmp === 0) {
  860. // never assume equality; fallback to alphabetical order
  861. return $alphaSortClosure($a, $b);
  862. }
  863. return $cmp * (($order == 'desc') ? 1 : -1);
  864. });
  865. } else {
  866. // sort alphabetically
  867. uasort($this->pages, $alphaSortClosure);
  868. }
  869. }
  870. /**
  871. * Returns the list of known pages
  872. *
  873. * @see Pico::readPages()
  874. * @see Pico::sortPages()
  875. * @return array|null the data of all pages
  876. */
  877. public function getPages()
  878. {
  879. return $this->pages;
  880. }
  881. /**
  882. * Walks through the list of known pages and discovers the requested page
  883. * as well as the previous and next page relative to it
  884. *
  885. * @see Pico::getCurrentPage()
  886. * @see Pico::getPreviousPage()
  887. * @see Pico::getNextPage()
  888. * @return void
  889. */
  890. protected function discoverCurrentPage()
  891. {
  892. $pageIds = array_keys($this->pages);
  893. $contentDir = $this->getConfig('content_dir');
  894. $contentExt = $this->getConfig('content_ext');
  895. $currentPageId = substr($this->requestFile, strlen($contentDir), -strlen($contentExt));
  896. $currentPageIndex = array_search($currentPageId, $pageIds);
  897. if ($currentPageIndex !== false) {
  898. $this->currentPage = &$this->pages[$currentPageId];
  899. if (($this->getConfig('order_by') == 'date') && ($this->getConfig('order') == 'desc')) {
  900. $previousPageOffset = 1;
  901. $nextPageOffset = -1;
  902. } else {
  903. $previousPageOffset = -1;
  904. $nextPageOffset = 1;
  905. }
  906. if (isset($pageIds[$currentPageIndex + $previousPageOffset])) {
  907. $previousPageId = $pageIds[$currentPageIndex + $previousPageOffset];
  908. $this->previousPage = &$this->pages[$previousPageId];
  909. }
  910. if (isset($pageIds[$currentPageIndex + $nextPageOffset])) {
  911. $nextPageId = $pageIds[$currentPageIndex + $nextPageOffset];
  912. $this->nextPage = &$this->pages[$nextPageId];
  913. }
  914. }
  915. }
  916. /**
  917. * Returns the data of the requested page
  918. *
  919. * @see Pico::discoverCurrentPage()
  920. * @return array|null page data
  921. */
  922. public function getCurrentPage()
  923. {
  924. return $this->currentPage;
  925. }
  926. /**
  927. * Returns the data of the previous page relative to the page being served
  928. *
  929. * @see Pico::discoverCurrentPage()
  930. * @return array|null page data
  931. */
  932. public function getPreviousPage()
  933. {
  934. return $this->previousPage;
  935. }
  936. /**
  937. * Returns the data of the next page relative to the page being served
  938. *
  939. * @see Pico::discoverCurrentPage()
  940. * @return array|null page data
  941. */
  942. public function getNextPage()
  943. {
  944. return $this->nextPage;
  945. }
  946. /**
  947. * Registers the twig template engine
  948. *
  949. * @see Pico::getTwig()
  950. * @return void
  951. */
  952. protected function registerTwig()
  953. {
  954. $twigLoader = new Twig_Loader_Filesystem($this->getThemesDir() . $this->getConfig('theme'));
  955. $this->twig = new Twig_Environment($twigLoader, $this->getConfig('twig_config'));
  956. $this->twig->addExtension(new Twig_Extension_Debug());
  957. $this->twig->addFilter(new Twig_SimpleFilter('link', array($this, 'getPageUrl')));
  958. }
  959. /**
  960. * Returns the twig template engine
  961. *
  962. * @see Pico::registerTwig()
  963. * @return Twig_Environment|null twig template engine
  964. */
  965. public function getTwig()
  966. {
  967. return $this->twig;
  968. }
  969. /**
  970. * Returns the variables passed to the template
  971. *
  972. * URLs and paths (namely `base_dir`, `base_url`, `theme_dir` and
  973. * `theme_url`) don't add a trailing slash for historic reasons.
  974. *
  975. * @return mixed[] template variables
  976. */
  977. protected function getTwigVariables()
  978. {
  979. $frontPage = $this->getConfig('content_dir') . 'index' . $this->getConfig('content_ext');
  980. return array(
  981. 'config' => $this->getConfig(),
  982. 'base_dir' => rtrim($this->getRootDir(), '/'),
  983. 'base_url' => rtrim($this->getBaseUrl(), '/'),
  984. 'theme_dir' => $this->getThemesDir() . $this->getConfig('theme'),
  985. 'theme_url' => $this->getBaseUrl() . basename($this->getThemesDir()) . '/' . $this->getConfig('theme'),
  986. 'rewrite_url' => $this->isUrlRewritingEnabled(),
  987. 'site_title' => $this->getConfig('site_title'),
  988. 'meta' => $this->meta,
  989. 'content' => $this->content,
  990. 'pages' => $this->pages,
  991. 'prev_page' => $this->previousPage,
  992. 'current_page' => $this->currentPage,
  993. 'next_page' => $this->nextPage,
  994. 'is_front_page' => ($this->requestFile == $frontPage),
  995. );
  996. }
  997. /**
  998. * Returns the base URL of this Pico instance
  999. *
  1000. * @return string the base url
  1001. */
  1002. public function getBaseUrl()
  1003. {
  1004. $baseUrl = $this->getConfig('base_url');
  1005. if (!empty($baseUrl)) {
  1006. return $baseUrl;
  1007. }
  1008. if (
  1009. (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off')
  1010. || ($_SERVER['SERVER_PORT'] == 443)
  1011. || (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')
  1012. ) {
  1013. $protocol = 'https';
  1014. } else {
  1015. $protocol = 'http';
  1016. }
  1017. $this->config['base_url'] =
  1018. $protocol . "://" . $_SERVER['HTTP_HOST']
  1019. . dirname($_SERVER['SCRIPT_NAME']) . '/';
  1020. return $this->getConfig('base_url');
  1021. }
  1022. /**
  1023. * Returns true if URL rewriting is enabled
  1024. *
  1025. * @return boolean true if URL rewriting is enabled, false otherwise
  1026. */
  1027. public function isUrlRewritingEnabled()
  1028. {
  1029. if (($this->getConfig('rewrite_url') === null) && isset($_SERVER['PICO_URL_REWRITING'])) {
  1030. return (bool) $_SERVER['PICO_URL_REWRITING'];
  1031. } elseif ($this->getConfig('rewrite_url')) {
  1032. return true;
  1033. }
  1034. return false;
  1035. }
  1036. /**
  1037. * Returns the URL to a given page
  1038. *
  1039. * @param string $page identifier of the page to link to
  1040. * @return string URL
  1041. */
  1042. public function getPageUrl($page)
  1043. {
  1044. return $this->getBaseUrl() . ((!$this->isUrlRewritingEnabled() && !empty($page)) ? '?' : '') . $page;
  1045. }
  1046. /**
  1047. * Recursively walks through a directory and returns all containing files
  1048. * matching the specified file extension
  1049. *
  1050. * @param string $directory start directory
  1051. * @param string $fileExtension return files with the given file extension
  1052. * only (optional)
  1053. * @param int $order specify whether and how files should be
  1054. * sorted; use Pico::SORT_ASC for a alphabetical ascending order (this
  1055. * is the default behaviour), Pico::SORT_DESC for a descending order
  1056. * or Pico::SORT_NONE to leave the result unsorted
  1057. * @return array list of found files
  1058. */
  1059. protected function getFiles($directory, $fileExtension = '', $order = self::SORT_ASC)
  1060. {
  1061. $directory = rtrim($directory, '/');
  1062. $result = array();
  1063. // scandir() reads files in alphabetical order
  1064. $files = scandir($directory, $order);
  1065. $fileExtensionLength = strlen($fileExtension);
  1066. if ($files !== false) {
  1067. foreach ($files as $file) {
  1068. // exclude hidden files/dirs starting with a .; this also excludes the special dirs . and ..
  1069. // exclude files ending with a ~ (vim/nano backup) or # (emacs backup)
  1070. if ((substr($file, 0, 1) === '.') || in_array(substr($file, -1), array('~', '#'))) {
  1071. continue;
  1072. }
  1073. if (is_dir($directory . '/' . $file)) {
  1074. // get files recursively
  1075. $result = array_merge($result, $this->getFiles($directory . '/' . $file, $fileExtension, $order));
  1076. } elseif (empty($fileExtension) || (substr($file, -$fileExtensionLength) === $fileExtension)) {
  1077. $result[] = $directory . '/' . $file;
  1078. }
  1079. }
  1080. }
  1081. return $result;
  1082. }
  1083. /**
  1084. * Makes a relative path absolute to Picos root dir
  1085. *
  1086. * This method also guarantees a trailing slash.
  1087. *
  1088. * @param string $path relative or absolute path
  1089. * @return string absolute path
  1090. */
  1091. protected function getAbsolutePath($path)
  1092. {
  1093. if (substr($path, 0, 1) !== '/') {
  1094. $path = $this->getRootDir() . $path;
  1095. }
  1096. return rtrim($path, '/') . '/';
  1097. }
  1098. /**
  1099. * Triggers events on plugins which implement PicoPluginInterface
  1100. *
  1101. * Deprecated events (as used by plugins not implementing
  1102. * {@link IPocPlugin}) are triggered by {@link PicoDeprecated}.
  1103. *
  1104. * @see PicoPluginInterface
  1105. * @see AbstractPicoPlugin
  1106. * @see DummyPlugin
  1107. * @param string $eventName name of the event to trigger
  1108. * @param array $params optional parameters to pass
  1109. * @return void
  1110. */
  1111. protected function triggerEvent($eventName, array $params = array())
  1112. {
  1113. foreach ($this->plugins as $plugin) {
  1114. // only trigger events for plugins that implement PicoPluginInterface
  1115. // deprecated events (plugins for Pico 0.9 and older) will be
  1116. // triggered by the `PicoPluginDeprecated` plugin
  1117. if (is_a($plugin, 'PicoPluginInterface')) {
  1118. $plugin->handleEvent($eventName, $params);
  1119. }
  1120. }
  1121. }
  1122. }