Pico.php.txt 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243
  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. $defaultConfig = array(
  375. 'site_title' => 'Pico',
  376. 'base_url' => '',
  377. 'rewrite_url' => null,
  378. 'theme' => 'default',
  379. 'date_format' => '%D %T',
  380. 'twig_config' => array('cache' => false, 'autoescape' => false, 'debug' => false),
  381. 'pages_order_by' => 'alpha',
  382. 'pages_order' => 'asc',
  383. 'content_dir' => $this->getRootDir() . 'content-sample/',
  384. 'content_ext' => '.md',
  385. 'timezone' => ''
  386. );
  387. $configFile = $this->getConfigDir() . 'config.php';
  388. $config = file_exists($configFile) ? require($configFile) : null;
  389. $this->config = is_array($this->config) ? $this->config : array();
  390. $this->config += is_array($config) ? $config + $defaultConfig : $defaultConfig;
  391. if (empty($this->config['base_url'])) {
  392. $this->config['base_url'] = $this->getBaseUrl();
  393. }
  394. if (!empty($this->config['content_dir'])) {
  395. $this->config['content_dir'] = $this->getAbsolutePath($this->config['content_dir']);
  396. }
  397. if (!empty($this->config['timezone'])) {
  398. date_default_timezone_set($this->config['timezone']);
  399. } else {
  400. // explicitly set a default timezone to prevent a E_NOTICE
  401. // when no timezone is set; the `date_default_timezone_get()`
  402. // function always returns a timezone, at least UTC
  403. $defaultTimezone = date_default_timezone_get();
  404. date_default_timezone_set($defaultTimezone);
  405. }
  406. }
  407. /**
  408. * Sets Picos config before calling Pico::run()
  409. *
  410. * This method allows you to modify Picos config without creating a
  411. * {@path "config/config.php"} or changing some of its variables before
  412. * Pico starts processing.
  413. *
  414. * You can call this method between {@link Pico::__construct()} and
  415. * {@link Pico::run()} only. Options set with this method cannot be
  416. * overwritten by {@path "config/config.php"}.
  417. *
  418. * @see Pico::loadConfig()
  419. * @see Pico::getConfig()
  420. * @param mixed[] $config array with config variables
  421. * @return void
  422. * @throws RuntimeException thrown if Pico already started processing
  423. */
  424. public function setConfig(array $config)
  425. {
  426. if ($this->locked) {
  427. throw new RuntimeException('You cannot modify Picos config after processing has started');
  428. }
  429. $this->config = $config;
  430. }
  431. /**
  432. * Returns either the value of the specified config variable or
  433. * the config array
  434. *
  435. * @see Pico::setConfig()
  436. * @see Pico::loadConfig()
  437. * @param string $configName optional name of a config variable
  438. * @return mixed returns either the value of the named config
  439. * variable, null if the config variable doesn't exist or the config
  440. * array if no config name was supplied
  441. */
  442. public function getConfig($configName = null)
  443. {
  444. if ($configName !== null) {
  445. return isset($this->config[$configName]) ? $this->config[$configName] : null;
  446. } else {
  447. return $this->config;
  448. }
  449. }
  450. /**
  451. * Evaluates the requested URL
  452. *
  453. * Pico 1.0 uses the `QUERY_STRING` routing method (e.g. `/pico/?sub/page`)
  454. * to support SEO-like URLs out-of-the-box with any webserver. You can
  455. * still setup URL rewriting (e.g. using `mod_rewrite` on Apache) to
  456. * basically remove the `?` from URLs, but your rewritten URLs must follow
  457. * the new `QUERY_STRING` principles. URL rewriting requires some special
  458. * configuration on your webserver, but this should be "basic work" for
  459. * any webmaster...
  460. *
  461. * Pico 0.9 and older required Apache with `mod_rewrite` enabled, thus old
  462. * plugins, templates and contents may require you to enable URL rewriting
  463. * to work. If you're upgrading from Pico 0.9, you will probably have to
  464. * update your rewriting rules.
  465. *
  466. * We recommend you to use the `link` filter in templates to create
  467. * internal links, e.g. `{{ "sub/page"|link }}` is equivalent to
  468. * `{{ base_url }}sub/page`. In content files you can still use the
  469. * `%base_url%` variable; e.g. `%base_url%?sub/page` will be automatically
  470. * replaced accordingly.
  471. *
  472. * @see Pico::getRequestUrl()
  473. * @return void
  474. */
  475. protected function evaluateRequestUrl()
  476. {
  477. // use QUERY_STRING; e.g. /pico/?sub/page
  478. // if you want to use rewriting, you MUST make your rules to
  479. // rewrite the URLs to follow the QUERY_STRING method
  480. //
  481. // Note: you MUST NOT call the index page with /pico/?someBooleanParameter;
  482. // use /pico/?someBooleanParameter= or /pico/?index&someBooleanParameter instead
  483. $pathComponent = isset($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : '';
  484. if (($pathComponentLength = strpos($pathComponent, '&')) !== false) {
  485. $pathComponent = substr($pathComponent, 0, $pathComponentLength);
  486. }
  487. $this->requestUrl = (strpos($pathComponent, '=') === false) ? urldecode($pathComponent) : '';
  488. }
  489. /**
  490. * Returns the URL where a user requested the page
  491. *
  492. * @see Pico::evaluateRequestUrl()
  493. * @return string|null request URL
  494. */
  495. public function getRequestUrl()
  496. {
  497. return $this->requestUrl;
  498. }
  499. /**
  500. * Uses the request URL to discover the content file to serve
  501. *
  502. * @see Pico::getRequestFile()
  503. * @return void
  504. */
  505. protected function discoverRequestFile()
  506. {
  507. if (empty($this->requestUrl)) {
  508. $this->requestFile = $this->getConfig('content_dir') . 'index' . $this->getConfig('content_ext');
  509. } else {
  510. // prevent content_dir breakouts using malicious request URLs
  511. // we don't use realpath() here because we neither want to check for file existance
  512. // nor prohibit symlinks which intentionally point to somewhere outside the content_dir
  513. // it is STRONGLY RECOMMENDED to use open_basedir - always, not just with Pico!
  514. $requestUrl = str_replace('\\', '/', $this->requestUrl);
  515. $requestUrlParts = explode('/', $requestUrl);
  516. $requestFileParts = array();
  517. foreach ($requestUrlParts as $requestUrlPart) {
  518. if (($requestUrlPart === '') || ($requestUrlPart === '.')) {
  519. continue;
  520. } elseif ($requestUrlPart === '..') {
  521. array_pop($requestFileParts);
  522. continue;
  523. }
  524. $requestFileParts[] = $requestUrlPart;
  525. }
  526. if (empty($requestFileParts)) {
  527. $this->requestFile = $this->getConfig('content_dir') . 'index' . $this->getConfig('content_ext');
  528. return;
  529. }
  530. // discover the content file to serve
  531. // Note: $requestFileParts neither contains a trailing nor a leading slash
  532. $this->requestFile = $this->getConfig('content_dir') . implode('/', $requestFileParts);
  533. if (is_dir($this->requestFile)) {
  534. // if no index file is found, try a accordingly named file in the previous dir
  535. // if this file doesn't exist either, show the 404 page, but assume the index
  536. // file as being requested (maintains backward compatibility to Pico < 1.0)
  537. $indexFile = $this->requestFile . '/index' . $this->getConfig('content_ext');
  538. if (file_exists($indexFile) || !file_exists($this->requestFile . $this->getConfig('content_ext'))) {
  539. $this->requestFile = $indexFile;
  540. return;
  541. }
  542. }
  543. $this->requestFile .= $this->getConfig('content_ext');
  544. }
  545. }
  546. /**
  547. * Returns the absolute path to the content file to serve
  548. *
  549. * @see Pico::discoverRequestFile()
  550. * @return string|null file path
  551. */
  552. public function getRequestFile()
  553. {
  554. return $this->requestFile;
  555. }
  556. /**
  557. * Returns the raw contents of a file
  558. *
  559. * @see Pico::getRawContent()
  560. * @param string $file file path
  561. * @return string raw contents of the file
  562. */
  563. public function loadFileContent($file)
  564. {
  565. return file_get_contents($file);
  566. }
  567. /**
  568. * Returns the raw contents of the first found 404 file when traversing
  569. * up from the directory the requested file is in
  570. *
  571. * @see Pico::getRawContent()
  572. * @param string $file path to requested (but not existing) file
  573. * @return string raw contents of the 404 file
  574. * @throws RuntimeException thrown when no suitable 404 file is found
  575. */
  576. public function load404Content($file)
  577. {
  578. $errorFileDir = substr($file, strlen($this->getConfig('content_dir')));
  579. do {
  580. $errorFileDir = dirname($errorFileDir);
  581. $errorFile = $errorFileDir . '/404' . $this->getConfig('content_ext');
  582. } while (!file_exists($this->getConfig('content_dir') . $errorFile) && ($errorFileDir !== '.'));
  583. if (!file_exists($this->getConfig('content_dir') . $errorFile)) {
  584. $errorFile = ($errorFileDir === '.') ? '404' . $this->getConfig('content_ext') : $errorFile;
  585. throw new RuntimeException('Required "' . $errorFile . '" not found');
  586. }
  587. return $this->loadFileContent($this->getConfig('content_dir') . $errorFile);
  588. }
  589. /**
  590. * Returns the raw contents, either of the requested or the 404 file
  591. *
  592. * @see Pico::loadFileContent()
  593. * @see Pico::load404Content()
  594. * @return string|null raw contents
  595. */
  596. public function getRawContent()
  597. {
  598. return $this->rawContent;
  599. }
  600. /**
  601. * Returns known meta headers and triggers the onMetaHeaders event
  602. *
  603. * Heads up! Calling this method triggers the `onMetaHeaders` event.
  604. * Keep this in mind to prevent a infinite loop!
  605. *
  606. * @return string[] known meta headers; the array value specifies the
  607. * YAML key to search for, the array key is later used to access the
  608. * found value
  609. */
  610. public function getMetaHeaders()
  611. {
  612. $headers = array(
  613. 'title' => 'Title',
  614. 'description' => 'Description',
  615. 'author' => 'Author',
  616. 'date' => 'Date',
  617. 'robots' => 'Robots',
  618. 'template' => 'Template'
  619. );
  620. $this->triggerEvent('onMetaHeaders', array(&$headers));
  621. return $headers;
  622. }
  623. /**
  624. * Parses the file meta from raw file contents
  625. *
  626. * Meta data MUST start on the first line of the file, either opened and
  627. * closed by `---` or C-style block comments (deprecated). The headers are
  628. * parsed by the YAML component of the Symfony project, keys are lowered.
  629. * If you're a plugin developer, you MUST register new headers during the
  630. * `onMetaHeaders` event first. The implicit availability of headers is
  631. * for users and pure (!) theme developers ONLY.
  632. *
  633. * @see Pico::getFileMeta()
  634. * @see <http://symfony.com/doc/current/components/yaml/introduction.html>
  635. * @param string $rawContent the raw file contents
  636. * @param string[] $headers known meta headers
  637. * @return array parsed meta data
  638. */
  639. public function parseFileMeta($rawContent, array $headers)
  640. {
  641. $meta = array();
  642. $pattern = "/^(\/(\*)|---)[[:blank:]]*(?:\r)?\n"
  643. . "(.*?)(?:\r)?\n(?(2)\*\/|---)[[:blank:]]*(?:(?:\r)?\n|$)/s";
  644. if (preg_match($pattern, $rawContent, $rawMetaMatches)) {
  645. $yamlParser = new \Symfony\Component\Yaml\Parser();
  646. $meta = $yamlParser->parse($rawMetaMatches[3]);
  647. $meta = array_change_key_case($meta, CASE_LOWER);
  648. foreach ($headers as $fieldId => $fieldName) {
  649. $fieldName = strtolower($fieldName);
  650. if (isset($meta[$fieldName])) {
  651. // rename field (e.g. remove whitespaces)
  652. if ($fieldId != $fieldName) {
  653. $meta[$fieldId] = $meta[$fieldName];
  654. unset($meta[$fieldName]);
  655. }
  656. } else {
  657. // guarantee array key existance
  658. $meta[$fieldId] = '';
  659. }
  660. }
  661. if (!empty($meta['date'])) {
  662. $meta['time'] = strtotime($meta['date']);
  663. $meta['date_formatted'] = utf8_encode(strftime($this->getConfig('date_format'), $meta['time']));
  664. } else {
  665. $meta['time'] = $meta['date_formatted'] = '';
  666. }
  667. } else {
  668. // guarantee array key existance
  669. foreach ($headers as $id => $field) {
  670. $meta[$id] = '';
  671. }
  672. $meta['time'] = $meta['date_formatted'] = '';
  673. }
  674. return $meta;
  675. }
  676. /**
  677. * Returns the parsed meta data of the requested page
  678. *
  679. * @see Pico::parseFileMeta()
  680. * @return array|null parsed meta data
  681. */
  682. public function getFileMeta()
  683. {
  684. return $this->meta;
  685. }
  686. /**
  687. * Applies some static preparations to the raw contents of a page,
  688. * e.g. removing the meta header and replacing %base_url%
  689. *
  690. * @see Pico::parseFileContent()
  691. * @see Pico::getFileContent()
  692. * @param string $rawContent raw contents of a page
  693. * @return string contents prepared for parsing
  694. */
  695. public function prepareFileContent($rawContent)
  696. {
  697. // remove meta header
  698. $metaHeaderPattern = "/^(\/(\*)|---)[[:blank:]]*(?:\r)?\n"
  699. . "(.*?)(?:\r)?\n(?(2)\*\/|---)[[:blank:]]*(?:(?:\r)?\n|$)/s";
  700. $content = preg_replace($metaHeaderPattern, '', $rawContent, 1);
  701. // replace %site_title%
  702. $content = str_replace('%site_title%', $this->getConfig('site_title'), $content);
  703. // replace %base_url%
  704. if ($this->isUrlRewritingEnabled()) {
  705. // always use `%base_url%?sub/page` syntax for internal links
  706. // we'll replace the links accordingly, depending on enabled rewriting
  707. $content = str_replace('%base_url%?', $this->getBaseUrl(), $content);
  708. } else {
  709. // actually not necessary, but makes the URL look a little nicer
  710. $content = str_replace('%base_url%?', $this->getBaseUrl() . '?', $content);
  711. }
  712. $content = str_replace('%base_url%', rtrim($this->getBaseUrl(), '/'), $content);
  713. // replace %theme_url%
  714. $themeUrl = $this->getBaseUrl() . basename($this->getThemesDir()) . '/' . $this->getConfig('theme');
  715. $content = str_replace('%theme_url%', $themeUrl, $content);
  716. // replace %meta.*%
  717. $metaKeys = $metaValues = array();
  718. foreach ($this->meta as $metaKey => $metaValue) {
  719. if (is_scalar($metaValue) || ($metaValue === null)) {
  720. $metaKeys[] = '%meta.' . $metaKey . '%';
  721. $metaValues[] = strval($metaValue);
  722. }
  723. }
  724. $content = str_replace($metaKeys, $metaValues, $content);
  725. return $content;
  726. }
  727. /**
  728. * Parses the contents of a page using ParsedownExtra
  729. *
  730. * @see Pico::prepareFileContent()
  731. * @see Pico::getFileContent()
  732. * @param string $content raw contents of a page (Markdown)
  733. * @return string parsed contents (HTML)
  734. */
  735. public function parseFileContent($content)
  736. {
  737. $parsedown = new ParsedownExtra();
  738. return $parsedown->text($content);
  739. }
  740. /**
  741. * Returns the cached contents of the requested page
  742. *
  743. * @see Pico::prepareFileContent()
  744. * @see Pico::parseFileContent()
  745. * @return string|null parsed contents
  746. */
  747. public function getFileContent()
  748. {
  749. return $this->content;
  750. }
  751. /**
  752. * Reads the data of all pages known to Pico
  753. *
  754. * The page data will be an array containing the following values:
  755. * <pre>
  756. * +----------------+--------+------------------------------------------+
  757. * | Array key | Type | Description |
  758. * +----------------+--------+------------------------------------------+
  759. * | id | string | relative path to the content file |
  760. * | url | string | URL to the page |
  761. * | title | string | title of the page (YAML header) |
  762. * | description | string | description of the page (YAML header) |
  763. * | author | string | author of the page (YAML header) |
  764. * | time | string | timestamp derived from the Date header |
  765. * | date | string | date of the page (YAML header) |
  766. * | date_formatted | string | formatted date of the page |
  767. * | raw_content | string | raw, not yet parsed contents of the page |
  768. * | meta | string | parsed meta data of the page |
  769. * +----------------+--------+------------------------------------------+
  770. * </pre>
  771. *
  772. * @see Pico::sortPages()
  773. * @see Pico::getPages()
  774. * @return void
  775. */
  776. protected function readPages()
  777. {
  778. $this->pages = array();
  779. $files = $this->getFiles($this->getConfig('content_dir'), $this->getConfig('content_ext'), Pico::SORT_NONE);
  780. foreach ($files as $i => $file) {
  781. // skip 404 page
  782. if (basename($file) == '404' . $this->getConfig('content_ext')) {
  783. unset($files[$i]);
  784. continue;
  785. }
  786. $id = substr($file, strlen($this->getConfig('content_dir')), -strlen($this->getConfig('content_ext')));
  787. // drop inaccessible pages (e.g. drop "sub.md" if "sub/index.md" exists)
  788. $conflictFile = $this->getConfig('content_dir') . $id . '/index' . $this->getConfig('content_ext');
  789. if (in_array($conflictFile, $files, true)) {
  790. continue;
  791. }
  792. $url = $this->getPageUrl($id);
  793. if ($file != $this->requestFile) {
  794. $rawContent = file_get_contents($file);
  795. $meta = $this->parseFileMeta($rawContent, $this->getMetaHeaders());
  796. } else {
  797. $rawContent = &$this->rawContent;
  798. $meta = &$this->meta;
  799. }
  800. // build page data
  801. // title, description, author and date are assumed to be pretty basic data
  802. // everything else is accessible through $page['meta']
  803. $page = array(
  804. 'id' => $id,
  805. 'url' => $url,
  806. 'title' => &$meta['title'],
  807. 'description' => &$meta['description'],
  808. 'author' => &$meta['author'],
  809. 'time' => &$meta['time'],
  810. 'date' => &$meta['date'],
  811. 'date_formatted' => &$meta['date_formatted'],
  812. 'raw_content' => &$rawContent,
  813. 'meta' => &$meta
  814. );
  815. if ($file == $this->requestFile) {
  816. $page['content'] = &$this->content;
  817. }
  818. unset($rawContent, $meta);
  819. // trigger event
  820. $this->triggerEvent('onSinglePageLoaded', array(&$page));
  821. $this->pages[$id] = $page;
  822. }
  823. }
  824. /**
  825. * Sorts all pages known to Pico
  826. *
  827. * @see Pico::readPages()
  828. * @see Pico::getPages()
  829. * @return void
  830. */
  831. protected function sortPages()
  832. {
  833. // sort pages
  834. $order = $this->getConfig('pages_order');
  835. $alphaSortClosure = function ($a, $b) use ($order) {
  836. $aSortKey = (basename($a['id']) === 'index') ? dirname($a['id']) : $a['id'];
  837. $bSortKey = (basename($b['id']) === 'index') ? dirname($b['id']) : $b['id'];
  838. $cmp = strcmp($aSortKey, $bSortKey);
  839. return $cmp * (($order == 'desc') ? -1 : 1);
  840. };
  841. if ($this->getConfig('pages_order_by') == 'date') {
  842. // sort by date
  843. uasort($this->pages, function ($a, $b) use ($alphaSortClosure, $order) {
  844. if (empty($a['time']) || empty($b['time'])) {
  845. $cmp = (empty($a['time']) - empty($b['time']));
  846. } else {
  847. $cmp = ($b['time'] - $a['time']);
  848. }
  849. if ($cmp === 0) {
  850. // never assume equality; fallback to alphabetical order
  851. return $alphaSortClosure($a, $b);
  852. }
  853. return $cmp * (($order == 'desc') ? 1 : -1);
  854. });
  855. } else {
  856. // sort alphabetically
  857. uasort($this->pages, $alphaSortClosure);
  858. }
  859. }
  860. /**
  861. * Returns the list of known pages
  862. *
  863. * @see Pico::readPages()
  864. * @see Pico::sortPages()
  865. * @return array|null the data of all pages
  866. */
  867. public function getPages()
  868. {
  869. return $this->pages;
  870. }
  871. /**
  872. * Walks through the list of known pages and discovers the requested page
  873. * as well as the previous and next page relative to it
  874. *
  875. * @see Pico::getCurrentPage()
  876. * @see Pico::getPreviousPage()
  877. * @see Pico::getNextPage()
  878. * @return void
  879. */
  880. protected function discoverCurrentPage()
  881. {
  882. $pageIds = array_keys($this->pages);
  883. $contentDir = $this->getConfig('content_dir');
  884. $contentExt = $this->getConfig('content_ext');
  885. $currentPageId = substr($this->requestFile, strlen($contentDir), -strlen($contentExt));
  886. $currentPageIndex = array_search($currentPageId, $pageIds);
  887. if ($currentPageIndex !== false) {
  888. $this->currentPage = &$this->pages[$currentPageId];
  889. if (($this->getConfig('order_by') == 'date') && ($this->getConfig('order') == 'desc')) {
  890. $previousPageOffset = 1;
  891. $nextPageOffset = -1;
  892. } else {
  893. $previousPageOffset = -1;
  894. $nextPageOffset = 1;
  895. }
  896. if (isset($pageIds[$currentPageIndex + $previousPageOffset])) {
  897. $previousPageId = $pageIds[$currentPageIndex + $previousPageOffset];
  898. $this->previousPage = &$this->pages[$previousPageId];
  899. }
  900. if (isset($pageIds[$currentPageIndex + $nextPageOffset])) {
  901. $nextPageId = $pageIds[$currentPageIndex + $nextPageOffset];
  902. $this->nextPage = &$this->pages[$nextPageId];
  903. }
  904. }
  905. }
  906. /**
  907. * Returns the data of the requested page
  908. *
  909. * @see Pico::discoverCurrentPage()
  910. * @return array|null page data
  911. */
  912. public function getCurrentPage()
  913. {
  914. return $this->currentPage;
  915. }
  916. /**
  917. * Returns the data of the previous page relative to the page being served
  918. *
  919. * @see Pico::discoverCurrentPage()
  920. * @return array|null page data
  921. */
  922. public function getPreviousPage()
  923. {
  924. return $this->previousPage;
  925. }
  926. /**
  927. * Returns the data of the next page relative to the page being served
  928. *
  929. * @see Pico::discoverCurrentPage()
  930. * @return array|null page data
  931. */
  932. public function getNextPage()
  933. {
  934. return $this->nextPage;
  935. }
  936. /**
  937. * Registers the twig template engine
  938. *
  939. * @see Pico::getTwig()
  940. * @return void
  941. */
  942. protected function registerTwig()
  943. {
  944. $twigLoader = new Twig_Loader_Filesystem($this->getThemesDir() . $this->getConfig('theme'));
  945. $this->twig = new Twig_Environment($twigLoader, $this->getConfig('twig_config'));
  946. $this->twig->addExtension(new Twig_Extension_Debug());
  947. $this->twig->addFilter(new Twig_SimpleFilter('link', array($this, 'getPageUrl')));
  948. }
  949. /**
  950. * Returns the twig template engine
  951. *
  952. * @see Pico::registerTwig()
  953. * @return Twig_Environment|null twig template engine
  954. */
  955. public function getTwig()
  956. {
  957. return $this->twig;
  958. }
  959. /**
  960. * Returns the variables passed to the template
  961. *
  962. * URLs and paths (namely `base_dir`, `base_url`, `theme_dir` and
  963. * `theme_url`) don't add a trailing slash for historic reasons.
  964. *
  965. * @return mixed[] template variables
  966. */
  967. protected function getTwigVariables()
  968. {
  969. $frontPage = $this->getConfig('content_dir') . 'index' . $this->getConfig('content_ext');
  970. return array(
  971. 'config' => $this->getConfig(),
  972. 'base_dir' => rtrim($this->getRootDir(), '/'),
  973. 'base_url' => rtrim($this->getBaseUrl(), '/'),
  974. 'theme_dir' => $this->getThemesDir() . $this->getConfig('theme'),
  975. 'theme_url' => $this->getBaseUrl() . basename($this->getThemesDir()) . '/' . $this->getConfig('theme'),
  976. 'rewrite_url' => $this->isUrlRewritingEnabled(),
  977. 'site_title' => $this->getConfig('site_title'),
  978. 'meta' => $this->meta,
  979. 'content' => $this->content,
  980. 'pages' => $this->pages,
  981. 'prev_page' => $this->previousPage,
  982. 'current_page' => $this->currentPage,
  983. 'next_page' => $this->nextPage,
  984. 'is_front_page' => ($this->requestFile == $frontPage),
  985. );
  986. }
  987. /**
  988. * Returns the base URL of this Pico instance
  989. *
  990. * @return string the base url
  991. */
  992. public function getBaseUrl()
  993. {
  994. $baseUrl = $this->getConfig('base_url');
  995. if (!empty($baseUrl)) {
  996. return $baseUrl;
  997. }
  998. if (
  999. (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off')
  1000. || ($_SERVER['SERVER_PORT'] == 443)
  1001. || (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')
  1002. ) {
  1003. $protocol = 'https';
  1004. } else {
  1005. $protocol = 'http';
  1006. }
  1007. $this->config['base_url'] =
  1008. $protocol . "://" . $_SERVER['HTTP_HOST']
  1009. . dirname($_SERVER['SCRIPT_NAME']) . '/';
  1010. return $this->getConfig('base_url');
  1011. }
  1012. /**
  1013. * Returns true if URL rewriting is enabled
  1014. *
  1015. * @return boolean true if URL rewriting is enabled, false otherwise
  1016. */
  1017. public function isUrlRewritingEnabled()
  1018. {
  1019. if (($this->getConfig('rewrite_url') === null) && isset($_SERVER['PICO_URL_REWRITING'])) {
  1020. return (bool) $_SERVER['PICO_URL_REWRITING'];
  1021. } elseif ($this->getConfig('rewrite_url')) {
  1022. return true;
  1023. }
  1024. return false;
  1025. }
  1026. /**
  1027. * Returns the URL to a given page
  1028. *
  1029. * @param string $page identifier of the page to link to
  1030. * @return string URL
  1031. */
  1032. public function getPageUrl($page)
  1033. {
  1034. return $this->getBaseUrl() . ((!$this->isUrlRewritingEnabled() && !empty($page)) ? '?' : '') . $page;
  1035. }
  1036. /**
  1037. * Recursively walks through a directory and returns all containing files
  1038. * matching the specified file extension
  1039. *
  1040. * @param string $directory start directory
  1041. * @param string $fileExtension return files with the given file extension
  1042. * only (optional)
  1043. * @param int $order specify whether and how files should be
  1044. * sorted; use Pico::SORT_ASC for a alphabetical ascending order (this
  1045. * is the default behaviour), Pico::SORT_DESC for a descending order
  1046. * or Pico::SORT_NONE to leave the result unsorted
  1047. * @return array list of found files
  1048. */
  1049. protected function getFiles($directory, $fileExtension = '', $order = self::SORT_ASC)
  1050. {
  1051. $directory = rtrim($directory, '/');
  1052. $result = array();
  1053. // scandir() reads files in alphabetical order
  1054. $files = scandir($directory, $order);
  1055. $fileExtensionLength = strlen($fileExtension);
  1056. if ($files !== false) {
  1057. foreach ($files as $file) {
  1058. // exclude hidden files/dirs starting with a .; this also excludes the special dirs . and ..
  1059. // exclude files ending with a ~ (vim/nano backup) or # (emacs backup)
  1060. if ((substr($file, 0, 1) === '.') || in_array(substr($file, -1), array('~', '#'))) {
  1061. continue;
  1062. }
  1063. if (is_dir($directory . '/' . $file)) {
  1064. // get files recursively
  1065. $result = array_merge($result, $this->getFiles($directory . '/' . $file, $fileExtension, $order));
  1066. } elseif (empty($fileExtension) || (substr($file, -$fileExtensionLength) === $fileExtension)) {
  1067. $result[] = $directory . '/' . $file;
  1068. }
  1069. }
  1070. }
  1071. return $result;
  1072. }
  1073. /**
  1074. * Makes a relative path absolute to Picos root dir
  1075. *
  1076. * This method also guarantees a trailing slash.
  1077. *
  1078. * @param string $path relative or absolute path
  1079. * @return string absolute path
  1080. */
  1081. protected function getAbsolutePath($path)
  1082. {
  1083. if (substr($path, 0, 1) !== '/') {
  1084. $path = $this->getRootDir() . $path;
  1085. }
  1086. return rtrim($path, '/') . '/';
  1087. }
  1088. /**
  1089. * Triggers events on plugins which implement PicoPluginInterface
  1090. *
  1091. * Deprecated events (as used by plugins not implementing
  1092. * {@link IPocPlugin}) are triggered by {@link PicoDeprecated}.
  1093. *
  1094. * @see PicoPluginInterface
  1095. * @see AbstractPicoPlugin
  1096. * @see DummyPlugin
  1097. * @param string $eventName name of the event to trigger
  1098. * @param array $params optional parameters to pass
  1099. * @return void
  1100. */
  1101. protected function triggerEvent($eventName, array $params = array())
  1102. {
  1103. foreach ($this->plugins as $plugin) {
  1104. // only trigger events for plugins that implement PicoPluginInterface
  1105. // deprecated events (plugins for Pico 0.9 and older) will be
  1106. // triggered by the `PicoPluginDeprecated` plugin
  1107. if (is_a($plugin, 'PicoPluginInterface')) {
  1108. $plugin->handleEvent($eventName, $params);
  1109. }
  1110. }
  1111. }
  1112. }