Pico.php 91 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573
  1. <?php
  2. /**
  3. * This file is part of Pico. It's copyrighted by the contributors recorded
  4. * in the version control history of the file, available from the following
  5. * original location:
  6. *
  7. * <https://github.com/picocms/Pico/blob/master/lib/Pico.php>
  8. *
  9. * The file has been renamed in the past; the version control history of the
  10. * original file applies accordingly, available from the following original
  11. * location:
  12. *
  13. * <https://github.com/picocms/Pico/blob/adc356251ecd79689935ec1446c7c846db167d46/lib/pico.php>
  14. *
  15. * SPDX-License-Identifier: MIT
  16. * License-Filename: LICENSE
  17. */
  18. /**
  19. * Pico
  20. *
  21. * Pico is a stupidly simple, blazing fast, flat file CMS.
  22. *
  23. * - Stupidly Simple: Pico makes creating and maintaining a
  24. * website as simple as editing text files.
  25. * - Blazing Fast: Pico is seriously lightweight and doesn't
  26. * use a database, making it super fast.
  27. * - No Database: Pico is a "flat file" CMS, meaning no
  28. * database woes, no MySQL queries, nothing.
  29. * - Markdown Formatting: Edit your website in your favourite
  30. * text editor using simple Markdown formatting.
  31. * - Twig Templates: Pico uses the Twig templating engine,
  32. * for powerful and flexible themes.
  33. * - Open Source: Pico is completely free and open source,
  34. * released under the MIT license.
  35. *
  36. * See <http://picocms.org/> for more info.
  37. *
  38. * @author Gilbert Pellegrom
  39. * @author Daniel Rudolf
  40. * @link http://picocms.org
  41. * @license http://opensource.org/licenses/MIT The MIT License
  42. * @version 2.0
  43. */
  44. class Pico
  45. {
  46. /**
  47. * Pico version
  48. *
  49. * @var string
  50. */
  51. const VERSION = '2.0.5-beta.1';
  52. /**
  53. * Pico version ID
  54. *
  55. * @var int
  56. */
  57. const VERSION_ID = 20005;
  58. /**
  59. * Pico API version
  60. *
  61. * @var int
  62. */
  63. const API_VERSION = 2;
  64. /**
  65. * Sort files in alphabetical ascending order
  66. *
  67. * @see Pico::getFiles()
  68. * @var int
  69. */
  70. const SORT_ASC = 0;
  71. /**
  72. * Sort files in alphabetical descending order
  73. *
  74. * @see Pico::getFiles()
  75. * @var int
  76. */
  77. const SORT_DESC = 1;
  78. /**
  79. * Don't sort files
  80. *
  81. * @see Pico::getFiles()
  82. * @var int
  83. */
  84. const SORT_NONE = 2;
  85. /**
  86. * Root directory of this Pico instance
  87. *
  88. * @see Pico::getRootDir()
  89. * @var string
  90. */
  91. protected $rootDir;
  92. /**
  93. * Vendor directory of this Pico instance
  94. *
  95. * @see Pico::getVendorDir()
  96. * @var string
  97. */
  98. protected $vendorDir;
  99. /**
  100. * Config directory of this Pico instance
  101. *
  102. * @see Pico::getConfigDir()
  103. * @var string
  104. */
  105. protected $configDir;
  106. /**
  107. * Plugins directory of this Pico instance
  108. *
  109. * @see Pico::getPluginsDir()
  110. * @var string
  111. */
  112. protected $pluginsDir;
  113. /**
  114. * Themes directory of this Pico instance
  115. *
  116. * @see Pico::getThemesDir()
  117. * @var string
  118. */
  119. protected $themesDir;
  120. /**
  121. * Boolean indicating whether Pico started processing yet
  122. *
  123. * @var bool
  124. */
  125. protected $locked = false;
  126. /**
  127. * List of loaded plugins
  128. *
  129. * @see Pico::getPlugins()
  130. * @var object[]
  131. */
  132. protected $plugins = array();
  133. /**
  134. * List of loaded plugins using the current API version
  135. *
  136. * @var PicoPluginInterface[]
  137. */
  138. protected $nativePlugins = array();
  139. /**
  140. * Boolean indicating whether Pico loads plugins from the filesystem
  141. *
  142. * @see Pico::loadPlugins()
  143. * @see Pico::loadLocalPlugins()
  144. * @var bool
  145. */
  146. protected $enableLocalPlugins = true;
  147. /**
  148. * Current configuration of this Pico instance
  149. *
  150. * @see Pico::getConfig()
  151. * @var array|null
  152. */
  153. protected $config;
  154. /**
  155. * Part of the URL describing the requested contents
  156. *
  157. * @see Pico::getRequestUrl()
  158. * @var string|null
  159. */
  160. protected $requestUrl;
  161. /**
  162. * Absolute path to the content file being served
  163. *
  164. * @see Pico::getRequestFile()
  165. * @var string|null
  166. */
  167. protected $requestFile;
  168. /**
  169. * Raw, not yet parsed contents to serve
  170. *
  171. * @see Pico::getRawContent()
  172. * @var string|null
  173. */
  174. protected $rawContent;
  175. /**
  176. * Boolean indicating whether Pico is serving a 404 page
  177. *
  178. * @see Pico::is404Content()
  179. * @var bool
  180. */
  181. protected $is404Content = false;
  182. /**
  183. * Symfony YAML instance used for meta header parsing
  184. *
  185. * @see Pico::getYamlParser()
  186. * @var \Symfony\Component\Yaml\Parser|null
  187. */
  188. protected $yamlParser;
  189. /**
  190. * List of known meta headers
  191. *
  192. * @see Pico::getMetaHeaders()
  193. * @var string[]|null
  194. */
  195. protected $metaHeaders;
  196. /**
  197. * Meta data of the page to serve
  198. *
  199. * @see Pico::getFileMeta()
  200. * @var array|null
  201. */
  202. protected $meta;
  203. /**
  204. * Parsedown Extra instance used for markdown parsing
  205. *
  206. * @see Pico::getParsedown()
  207. * @var Parsedown|null
  208. */
  209. protected $parsedown;
  210. /**
  211. * Parsed content being served
  212. *
  213. * @see Pico::getFileContent()
  214. * @var string|null
  215. */
  216. protected $content;
  217. /**
  218. * List of known pages
  219. *
  220. * @see Pico::getPages()
  221. * @var array[]|null
  222. */
  223. protected $pages;
  224. /**
  225. * Data of the page being served
  226. *
  227. * @see Pico::getCurrentPage()
  228. * @var array|null
  229. */
  230. protected $currentPage;
  231. /**
  232. * Data of the previous page relative to the page being served
  233. *
  234. * @see Pico::getPreviousPage()
  235. * @var array|null
  236. */
  237. protected $previousPage;
  238. /**
  239. * Data of the next page relative to the page being served
  240. *
  241. * @see Pico::getNextPage()
  242. * @var array|null
  243. */
  244. protected $nextPage;
  245. /**
  246. * Tree structure of known pages
  247. *
  248. * @see Pico::getPageTree()
  249. * @var array[]|null
  250. */
  251. protected $pageTree;
  252. /**
  253. * Twig instance used for template parsing
  254. *
  255. * @see Pico::getTwig()
  256. * @var Twig_Environment|null
  257. */
  258. protected $twig;
  259. /**
  260. * Variables passed to the twig template
  261. *
  262. * @see Pico::getTwigVariables()
  263. * @var array|null
  264. */
  265. protected $twigVariables;
  266. /**
  267. * Name of the Twig template to render
  268. *
  269. * @see Pico::getTwigTemplate()
  270. * @var string|null
  271. */
  272. protected $twigTemplate;
  273. /**
  274. * Constructs a new Pico instance
  275. *
  276. * To carry out all the processing in Pico, call {@see Pico::run()}.
  277. *
  278. * @param string $rootDir root dir of this Pico instance
  279. * @param string $configDir config dir of this Pico instance
  280. * @param string $pluginsDir plugins dir of this Pico instance
  281. * @param string $themesDir themes dir of this Pico instance
  282. * @param bool $enableLocalPlugins enables (TRUE; default) or disables
  283. * (FALSE) loading plugins from the filesystem
  284. */
  285. public function __construct($rootDir, $configDir, $pluginsDir, $themesDir, $enableLocalPlugins = true)
  286. {
  287. $this->rootDir = rtrim($rootDir, '/\\') . '/';
  288. $this->vendorDir = dirname(__DIR__) . '/';
  289. $this->configDir = $this->getAbsolutePath($configDir);
  290. $this->pluginsDir = $this->getAbsolutePath($pluginsDir);
  291. $this->themesDir = $this->getAbsolutePath($themesDir);
  292. $this->enableLocalPlugins = (bool) $enableLocalPlugins;
  293. }
  294. /**
  295. * Returns the root directory of this Pico instance
  296. *
  297. * @return string root directory path
  298. */
  299. public function getRootDir()
  300. {
  301. return $this->rootDir;
  302. }
  303. /**
  304. * Returns the vendor directory of this Pico instance
  305. *
  306. * @return string vendor directory path
  307. */
  308. public function getVendorDir()
  309. {
  310. return $this->vendorDir;
  311. }
  312. /**
  313. * Returns the config directory of this Pico instance
  314. *
  315. * @return string config directory path
  316. */
  317. public function getConfigDir()
  318. {
  319. return $this->configDir;
  320. }
  321. /**
  322. * Returns the plugins directory of this Pico instance
  323. *
  324. * @return string plugins directory path
  325. */
  326. public function getPluginsDir()
  327. {
  328. return $this->pluginsDir;
  329. }
  330. /**
  331. * Returns the themes directory of this Pico instance
  332. *
  333. * @return string themes directory path
  334. */
  335. public function getThemesDir()
  336. {
  337. return $this->themesDir;
  338. }
  339. /**
  340. * Runs this Pico instance
  341. *
  342. * Loads plugins, evaluates the config file, does URL routing, parses
  343. * meta headers, processes Markdown, does Twig processing and returns
  344. * the rendered contents.
  345. *
  346. * @return string rendered Pico contents
  347. *
  348. * @throws Exception thrown when a irrecoverable error occurs
  349. */
  350. public function run()
  351. {
  352. // check lock
  353. if ($this->locked) {
  354. throw new LogicException('You cannot run the same Pico instance multiple times');
  355. }
  356. // lock Pico
  357. $this->locked = true;
  358. // load plugins
  359. $this->loadPlugins();
  360. $this->sortPlugins();
  361. $this->triggerEvent('onPluginsLoaded', array($this->plugins));
  362. // load config
  363. $this->loadConfig();
  364. $this->triggerEvent('onConfigLoaded', array(&$this->config));
  365. // check content dir
  366. if (!is_dir($this->getConfig('content_dir'))) {
  367. throw new RuntimeException('Invalid content directory "' . $this->getConfig('content_dir') . '"');
  368. }
  369. // evaluate request url
  370. $this->evaluateRequestUrl();
  371. $this->triggerEvent('onRequestUrl', array(&$this->requestUrl));
  372. // discover requested file
  373. $this->requestFile = $this->resolveFilePath($this->requestUrl);
  374. $this->triggerEvent('onRequestFile', array(&$this->requestFile));
  375. // load raw file content
  376. $this->triggerEvent('onContentLoading');
  377. $hiddenFileRegex = '/(?:^|\/)(?:_|404' . preg_quote($this->getConfig('content_ext'), '/') . '$)/';
  378. if (file_exists($this->requestFile) && !preg_match($hiddenFileRegex, $this->requestFile)) {
  379. $this->rawContent = $this->loadFileContent($this->requestFile);
  380. } else {
  381. $this->triggerEvent('on404ContentLoading');
  382. $serverProtocol = !empty($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.1';
  383. header($serverProtocol . ' 404 Not Found');
  384. $this->rawContent = $this->load404Content($this->requestFile);
  385. $this->is404Content = true;
  386. $this->triggerEvent('on404ContentLoaded', array(&$this->rawContent));
  387. }
  388. $this->triggerEvent('onContentLoaded', array(&$this->rawContent));
  389. // parse file meta
  390. $this->triggerEvent('onMetaParsing');
  391. $this->meta = $this->parseFileMeta($this->rawContent, $this->getMetaHeaders());
  392. $this->triggerEvent('onMetaParsed', array(&$this->meta));
  393. // parse file content
  394. $this->triggerEvent('onContentParsing');
  395. $markdown = $this->prepareFileContent($this->rawContent, $this->meta);
  396. $this->triggerEvent('onContentPrepared', array(&$markdown));
  397. $this->content = $this->parseFileContent($markdown);
  398. $this->triggerEvent('onContentParsed', array(&$this->content));
  399. // read pages
  400. $this->triggerEvent('onPagesLoading');
  401. $this->readPages();
  402. $this->triggerEvent('onPagesDiscovered', array(&$this->pages));
  403. $this->sortPages();
  404. $this->triggerEvent('onPagesLoaded', array(&$this->pages));
  405. $this->discoverPageSiblings();
  406. $this->discoverCurrentPage();
  407. $this->triggerEvent(
  408. 'onCurrentPageDiscovered',
  409. array(&$this->currentPage, &$this->previousPage, &$this->nextPage)
  410. );
  411. $this->buildPageTree();
  412. $this->triggerEvent('onPageTreeBuilt', array(&$this->pageTree));
  413. // render template
  414. $this->twigVariables = $this->getTwigVariables();
  415. $this->twigTemplate = $this->getTwigTemplate();
  416. $this->triggerEvent('onPageRendering', array(&$this->twigTemplate, &$this->twigVariables));
  417. $output = $this->getTwig()->render($this->twigTemplate, $this->twigVariables);
  418. $this->triggerEvent('onPageRendered', array(&$output));
  419. return $output;
  420. }
  421. /**
  422. * Loads plugins from vendor/pico-plugin.php and Pico::$pluginsDir
  423. *
  424. * See {@see Pico::loadComposerPlugins()} for details about plugins loaded
  425. * from `vendor/pico-plugin.php` (i.e. plugins that were installed using
  426. * composer), and {@see Pico::loadLocalPlugins()} for details about plugins
  427. * installed to {@see Pico::$pluginsDir}. Pico loads plugins from the
  428. * filesystem only if {@see Pico::$enableLocalPlugins} is set to TRUE
  429. * (this is the default).
  430. *
  431. * Pico always loads plugins from `vendor/pico-plugin.php` first and
  432. * ignores conflicting plugins in {@see Pico::$pluginsDir}.
  433. *
  434. * The official PicoDeprecated plugin must be loaded when plugins that use
  435. * an older API version than Pico's API version ({@see Pico::API_VERSION})
  436. * are loaded.
  437. *
  438. * Please note that Pico will change the processing order when needed to
  439. * incorporate plugin dependencies. See {@see Pico::sortPlugins()} for
  440. * details.
  441. *
  442. * @see Pico::loadPlugin()
  443. * @see Pico::getPlugin()
  444. * @see Pico::getPlugins()
  445. *
  446. * @return void
  447. *
  448. * @throws RuntimeException thrown when a plugin couldn't be loaded
  449. */
  450. protected function loadPlugins()
  451. {
  452. $composerPlugins = $this->loadComposerPlugins();
  453. if ($this->enableLocalPlugins) {
  454. $this->loadLocalPlugins($composerPlugins);
  455. }
  456. if (!isset($this->plugins['PicoDeprecated']) && (count($this->plugins) !== count($this->nativePlugins))) {
  457. throw new RuntimeException(
  458. "Plugins using an older API than version " . static::API_VERSION . " found, "
  459. . "but PicoDeprecated isn't loaded"
  460. );
  461. }
  462. }
  463. /**
  464. * Loads plugins from vendor/pico-plugin.php
  465. *
  466. * This method loads all plugins installed using composer and Pico's
  467. * `picocms/composer-installer` installer by reading the `pico-plugin.php`
  468. * in composer's `vendor` dir.
  469. *
  470. * @see Pico::loadPlugins()
  471. * @see Pico::loadLocalPlugins()
  472. *
  473. * @param string[] $pluginBlacklist class names of plugins not to load
  474. *
  475. * @return string[] installer names of the loaded plugins
  476. */
  477. protected function loadComposerPlugins(array $pluginBlacklist = array())
  478. {
  479. $composerPlugins = array();
  480. if (file_exists($this->getVendorDir() . 'vendor/pico-plugin.php')) {
  481. // composer root package
  482. $composerPlugins = require($this->getVendorDir() . 'vendor/pico-plugin.php') ?: array();
  483. } elseif (file_exists($this->getVendorDir() . '../../../vendor/pico-plugin.php')) {
  484. // composer dependency package
  485. $composerPlugins = require($this->getVendorDir() . '../../../vendor/pico-plugin.php') ?: array();
  486. }
  487. $pluginBlacklist = array_fill_keys($pluginBlacklist, true);
  488. $loadedPlugins = array();
  489. foreach ($composerPlugins as $package => $pluginData) {
  490. $loadedPlugins[] = $pluginData['installerName'];
  491. foreach ($pluginData['classNames'] as $className) {
  492. $plugin = new $className($this);
  493. $className = get_class($plugin);
  494. if (isset($this->plugins[$className]) || isset($pluginBlacklist[$className])) {
  495. continue;
  496. }
  497. if (!($plugin instanceof PicoPluginInterface)) {
  498. throw new RuntimeException(
  499. "Unable to load plugin '" . $className . "' via 'vendor/pico-plugin.php': "
  500. . "Plugins installed by composer must implement 'PicoPluginInterface'"
  501. );
  502. }
  503. $this->plugins[$className] = $plugin;
  504. if (defined($className . '::API_VERSION') && ($className::API_VERSION >= static::API_VERSION)) {
  505. $this->nativePlugins[$className] = $plugin;
  506. }
  507. }
  508. }
  509. return $loadedPlugins;
  510. }
  511. /**
  512. * Loads plugins from Pico::$pluginsDir in alphabetical order
  513. *
  514. * Pico tries to load plugins from `<plugin name>/<plugin name>.php` and
  515. * `<plugin name>.php` only. Plugin names are treated case insensitive.
  516. * Pico will throw a RuntimeException if it can't load a plugin.
  517. *
  518. * Plugin files MAY be prefixed by a number (e.g. `00-PicoDeprecated.php`)
  519. * to indicate their processing order. Plugins without a prefix will be
  520. * loaded last. If you want to use a prefix, you MUST NOT use the reserved
  521. * prefixes `00` to `09`. Prefixes are completely optional, however, you
  522. * SHOULD take the following prefix classification into consideration:
  523. * - 10 to 19: Reserved
  524. * - 20 to 39: Low level code helper plugins
  525. * - 40 to 59: Plugins manipulating routing or the pages array
  526. * - 60 to 79: Plugins hooking into template or markdown parsing
  527. * - 80 to 99: Plugins using the `onPageRendered` event
  528. *
  529. * @see Pico::loadPlugins()
  530. * @see Pico::loadComposerPlugins()
  531. *
  532. * @param string[] $pluginBlacklist class names of plugins not to load
  533. *
  534. * @return void
  535. *
  536. * @throws RuntimeException thrown when a plugin couldn't be loaded
  537. */
  538. protected function loadLocalPlugins(array $pluginBlacklist = array())
  539. {
  540. // scope isolated require()
  541. $includeClosure = function ($pluginFile) {
  542. require($pluginFile);
  543. };
  544. if (PHP_VERSION_ID >= 50400) {
  545. $includeClosure = $includeClosure->bindTo(null);
  546. }
  547. $pluginBlacklist = array_fill_keys($pluginBlacklist, true);
  548. $files = scandir($this->getPluginsDir()) ?: array();
  549. foreach ($files as $file) {
  550. if ($file[0] === '.') {
  551. continue;
  552. }
  553. $className = $pluginFile = null;
  554. if (is_dir($this->getPluginsDir() . $file)) {
  555. $className = preg_replace('/^[0-9]+-/', '', $file);
  556. $pluginFile = $file . '/' . $className . '.php';
  557. if (!file_exists($this->getPluginsDir() . $pluginFile)) {
  558. throw new RuntimeException(
  559. "Unable to load plugin '" . $className . "' from '" . $pluginFile . "': File not found"
  560. );
  561. }
  562. } elseif (substr($file, -4) === '.php') {
  563. $className = preg_replace('/^[0-9]+-/', '', substr($file, 0, -4));
  564. $pluginFile = $file;
  565. } else {
  566. throw new RuntimeException("Unable to load plugin from '" . $file . "': Not a valid plugin file");
  567. }
  568. if (isset($this->plugins[$className]) || isset($pluginBlacklist[$className])) {
  569. continue;
  570. }
  571. $includeClosure($this->getPluginsDir() . $pluginFile);
  572. if (class_exists($className, false)) {
  573. // class name and file name can differ regarding case sensitivity
  574. $plugin = new $className($this);
  575. $className = get_class($plugin);
  576. $this->plugins[$className] = $plugin;
  577. if ($plugin instanceof PicoPluginInterface) {
  578. if (defined($className . '::API_VERSION') && ($className::API_VERSION >= static::API_VERSION)) {
  579. $this->nativePlugins[$className] = $plugin;
  580. }
  581. }
  582. } else {
  583. throw new RuntimeException(
  584. "Unable to load plugin '" . $className . "' from '" . $pluginFile . "': Plugin class not found"
  585. );
  586. }
  587. }
  588. }
  589. /**
  590. * Manually loads a plugin
  591. *
  592. * Manually loaded plugins MUST implement {@see PicoPluginInterface}. They
  593. * are simply appended to the plugins array without any additional checks,
  594. * so you might get unexpected results, depending on *when* you're loading
  595. * a plugin. You SHOULD NOT load plugins after a event has been triggered
  596. * by Pico. In-depth knowledge of Pico's inner workings is strongly advised
  597. * otherwise, and you MUST NOT rely on {@see PicoDeprecated} to maintain
  598. * backward compatibility in such cases.
  599. *
  600. * If you e.g. load a plugin after the `onPluginsLoaded` event, Pico
  601. * doesn't guarantee the plugin's order ({@see Pico::sortPlugins()}).
  602. * Already triggered events won't get triggered on the manually loaded
  603. * plugin. Thus you SHOULD load plugins either before {@see Pico::run()}
  604. * is called, or via the constructor of another plugin (i.e. the plugin's
  605. * `__construct()` method; plugins are instanced in
  606. * {@see Pico::loadPlugins()}).
  607. *
  608. * This method triggers the `onPluginManuallyLoaded` event.
  609. *
  610. * @see Pico::loadPlugins()
  611. * @see Pico::getPlugin()
  612. * @see Pico::getPlugins()
  613. *
  614. * @param PicoPluginInterface|string $plugin either the class name of a
  615. * plugin to instantiate or a plugin instance
  616. *
  617. * @return PicoPluginInterface instance of the loaded plugin
  618. *
  619. * @throws RuntimeException thrown when a plugin couldn't be loaded
  620. */
  621. public function loadPlugin($plugin)
  622. {
  623. if (!is_object($plugin)) {
  624. $className = (string) $plugin;
  625. if (class_exists($className)) {
  626. $plugin = new $className($this);
  627. } else {
  628. throw new RuntimeException("Unable to load plugin '" . $className . "': Class not found");
  629. }
  630. }
  631. $className = get_class($plugin);
  632. if (!($plugin instanceof PicoPluginInterface)) {
  633. throw new RuntimeException(
  634. "Unable to load plugin '" . $className . "': "
  635. . "Manually loaded plugins must implement 'PicoPluginInterface'"
  636. );
  637. }
  638. $this->plugins[$className] = $plugin;
  639. if (defined($className . '::API_VERSION') && ($className::API_VERSION >= static::API_VERSION)) {
  640. $this->nativePlugins[$className] = $plugin;
  641. }
  642. // trigger onPluginManuallyLoaded event
  643. // the event is also triggered on the newly loaded plugin, allowing you to distinguish manual and auto loading
  644. $this->triggerEvent('onPluginManuallyLoaded', array($plugin));
  645. return $plugin;
  646. }
  647. /**
  648. * Sorts all loaded plugins using a plugin dependency topology
  649. *
  650. * Execution order matters: if plugin A depends on plugin B, it usually
  651. * means that plugin B does stuff which plugin A requires. However, Pico
  652. * loads plugins in alphabetical order, so events might get fired on
  653. * plugin A before plugin B.
  654. *
  655. * Hence plugins need to be sorted. Pico sorts plugins using a dependency
  656. * topology, this means that it moves all plugins, on which a plugin
  657. * depends, in front of that plugin. The order isn't touched apart from
  658. * that, so they are still sorted alphabetically, as long as this doesn't
  659. * interfere with the dependency topology. Circular dependencies are being
  660. * ignored; their behavior is undefiend. Missing dependencies are being
  661. * ignored until you try to enable the dependant plugin.
  662. *
  663. * This method bases on Marc J. Schmidt's Topological Sort library in
  664. * version 1.1.0, licensed under the MIT license. It uses the `ArraySort`
  665. * implementation (class `\MJS\TopSort\Implementations\ArraySort`).
  666. *
  667. * @see Pico::loadPlugins()
  668. * @see Pico::getPlugins()
  669. * @see https://github.com/marcj/topsort.php
  670. * Marc J. Schmidt's Topological Sort / Dependency resolver in PHP
  671. * @see https://github.com/marcj/topsort.php/blob/1.1.0/src/Implementations/ArraySort.php
  672. * \MJS\TopSort\Implementations\ArraySort class
  673. *
  674. * @return void
  675. */
  676. protected function sortPlugins()
  677. {
  678. $plugins = $this->plugins;
  679. $nativePlugins = $this->nativePlugins;
  680. $sortedPlugins = array();
  681. $sortedNativePlugins = array();
  682. $visitedPlugins = array();
  683. $visitPlugin = function ($plugin) use (
  684. $plugins,
  685. $nativePlugins,
  686. &$sortedPlugins,
  687. &$sortedNativePlugins,
  688. &$visitedPlugins,
  689. &$visitPlugin
  690. ) {
  691. $pluginName = get_class($plugin);
  692. // skip already visited plugins and ignore circular dependencies
  693. if (!isset($visitedPlugins[$pluginName])) {
  694. $visitedPlugins[$pluginName] = true;
  695. $dependencies = array();
  696. if ($plugin instanceof PicoPluginInterface) {
  697. $dependencies = $plugin->getDependencies();
  698. }
  699. if (!isset($nativePlugins[$pluginName])) {
  700. $dependencies[] = 'PicoDeprecated';
  701. }
  702. foreach ($dependencies as $dependency) {
  703. // ignore missing dependencies
  704. // this is only a problem when the user tries to enable this plugin
  705. if (isset($plugins[$dependency])) {
  706. $visitPlugin($plugins[$dependency]);
  707. }
  708. }
  709. $sortedPlugins[$pluginName] = $plugin;
  710. if (isset($nativePlugins[$pluginName])) {
  711. $sortedNativePlugins[$pluginName] = $plugin;
  712. }
  713. }
  714. };
  715. if (isset($this->plugins['PicoDeprecated'])) {
  716. $visitPlugin($this->plugins['PicoDeprecated']);
  717. }
  718. foreach ($this->plugins as $plugin) {
  719. $visitPlugin($plugin);
  720. }
  721. $this->plugins = $sortedPlugins;
  722. $this->nativePlugins = $sortedNativePlugins;
  723. }
  724. /**
  725. * Returns the instance of a named plugin
  726. *
  727. * Plugins SHOULD implement {@see PicoPluginInterface}, but you MUST NOT
  728. * rely on it. For more information see {@see PicoPluginInterface}.
  729. *
  730. * @see Pico::loadPlugins()
  731. * @see Pico::getPlugins()
  732. *
  733. * @param string $pluginName name of the plugin
  734. *
  735. * @return object instance of the plugin
  736. *
  737. * @throws RuntimeException thrown when the plugin wasn't found
  738. */
  739. public function getPlugin($pluginName)
  740. {
  741. if (isset($this->plugins[$pluginName])) {
  742. return $this->plugins[$pluginName];
  743. }
  744. throw new RuntimeException("Missing plugin '" . $pluginName . "'");
  745. }
  746. /**
  747. * Returns all loaded plugins
  748. *
  749. * @see Pico::loadPlugins()
  750. * @see Pico::getPlugin()
  751. *
  752. * @return object[]|null
  753. */
  754. public function getPlugins()
  755. {
  756. return $this->plugins;
  757. }
  758. /**
  759. * Loads the config.yml and any other *.yml from Pico::$configDir
  760. *
  761. * After loading {@path "config/config.yml"}, Pico proceeds with any other
  762. * existing `config/*.yml` file in alphabetical order. The file order is
  763. * crucial: Config values which have been set already, cannot be
  764. * overwritten by a succeeding file. This is also true for arrays, i.e.
  765. * when specifying `test: { foo: bar }` in `config/a.yml` and
  766. * `test: { baz: 42 }` in `config/b.yml`, `{{ config.test.baz }}` will be
  767. * undefined!
  768. *
  769. * @see Pico::setConfig()
  770. * @see Pico::getConfig()
  771. *
  772. * @return void
  773. */
  774. protected function loadConfig()
  775. {
  776. // load config closure
  777. $yamlParser = $this->getYamlParser();
  778. $loadConfigClosure = function ($configFile) use ($yamlParser) {
  779. $yaml = file_get_contents($configFile);
  780. $config = $yamlParser->parse($yaml);
  781. return is_array($config) ? $config : array();
  782. };
  783. // load main config file (config/config.yml)
  784. $this->config = is_array($this->config) ? $this->config : array();
  785. if (file_exists($this->getConfigDir() . 'config.yml')) {
  786. $this->config += $loadConfigClosure($this->getConfigDir() . 'config.yml');
  787. }
  788. // merge $config of config/*.yml files
  789. $configFiles = $this->getFilesGlob($this->getConfigDir() . '*.yml');
  790. foreach ($configFiles as $configFile) {
  791. if ($configFile !== $this->getConfigDir() . 'config.yml') {
  792. $this->config += $loadConfigClosure($configFile);
  793. }
  794. }
  795. // merge default config
  796. $this->config += array(
  797. 'site_title' => 'Pico',
  798. 'base_url' => '',
  799. 'rewrite_url' => null,
  800. 'debug' => null,
  801. 'timezone' => null,
  802. 'theme' => 'default',
  803. 'theme_url' => null,
  804. 'twig_config' => null,
  805. 'date_format' => '%D %T',
  806. 'pages_order_by' => 'alpha',
  807. 'pages_order' => 'asc',
  808. 'content_dir' => null,
  809. 'content_ext' => '.md',
  810. 'content_config' => null
  811. );
  812. if (!$this->config['base_url']) {
  813. $this->config['base_url'] = $this->getBaseUrl();
  814. } else {
  815. $this->config['base_url'] = rtrim($this->config['base_url'], '/') . '/';
  816. }
  817. if ($this->config['rewrite_url'] === null) {
  818. $this->config['rewrite_url'] = $this->isUrlRewritingEnabled();
  819. }
  820. if ($this->config['debug'] === null) {
  821. $this->config['debug'] = $this->isDebugModeEnabled();
  822. }
  823. if (!$this->config['timezone']) {
  824. // explicitly set a default timezone to prevent a E_NOTICE when no timezone is set;
  825. // the `date_default_timezone_get()` function always returns a timezone, at least UTC
  826. $this->config['timezone'] = @date_default_timezone_get();
  827. }
  828. date_default_timezone_set($this->config['timezone']);
  829. if (!$this->config['theme_url']) {
  830. $this->config['theme_url'] = $this->getBaseThemeUrl();
  831. } elseif (preg_match('#^[A-Za-z][A-Za-z0-9+\-.]*://#', $this->config['theme_url'])) {
  832. $this->config['theme_url'] = rtrim($this->config['theme_url'], '/') . '/';
  833. } else {
  834. $this->config['theme_url'] = $this->getBaseUrl() . rtrim($this->config['theme_url'], '/') . '/';
  835. }
  836. $defaultTwigConfig = array(
  837. 'autoescape' => false,
  838. 'strict_variables' => false,
  839. 'debug' => null,
  840. 'cache' => false,
  841. 'auto_reload' => null
  842. );
  843. if (!is_array($this->config['twig_config'])) {
  844. $this->config['twig_config'] = $defaultTwigConfig;
  845. } else {
  846. $this->config['twig_config'] += $defaultTwigConfig;
  847. if ($this->config['twig_config']['cache']) {
  848. $this->config['twig_config']['cache'] = $this->getAbsolutePath($this->config['twig_config']['cache']);
  849. }
  850. if ($this->config['twig_config']['debug'] === null) {
  851. $this->config['twig_config']['debug'] = $this->isDebugModeEnabled();
  852. }
  853. }
  854. if (!$this->config['content_dir']) {
  855. // try to guess the content directory
  856. if (is_file($this->getRootDir() . 'content/index' . $this->config['content_ext'])) {
  857. $this->config['content_dir'] = $this->getRootDir() . 'content/';
  858. } elseif (is_file($this->getRootDir() . 'content-sample/index' . $this->config['content_ext'])) {
  859. $this->config['content_dir'] = $this->getRootDir() . 'content-sample/';
  860. } else {
  861. $this->config['content_dir'] = $this->getVendorDir() . 'content-sample/';
  862. }
  863. } else {
  864. $this->config['content_dir'] = $this->getAbsolutePath($this->config['content_dir']);
  865. }
  866. $defaultContentConfig = array('extra' => true, 'breaks' => false, 'escape' => false, 'auto_urls' => true);
  867. if (!is_array($this->config['content_config'])) {
  868. $this->config['content_config'] = $defaultContentConfig;
  869. } else {
  870. $this->config['content_config'] += $defaultContentConfig;
  871. }
  872. }
  873. /**
  874. * Sets Pico's config before calling Pico::run()
  875. *
  876. * This method allows you to modify Pico's config without creating a
  877. * {@path "config/config.yml"} or changing some of its variables before
  878. * Pico starts processing.
  879. *
  880. * You can call this method between {@see Pico::__construct()} and
  881. * {@see Pico::run()} only. Options set with this method cannot be
  882. * overwritten by {@path "config/config.yml"}.
  883. *
  884. * @see Pico::loadConfig()
  885. * @see Pico::getConfig()
  886. *
  887. * @param array $config array with config variables
  888. *
  889. * @return void
  890. *
  891. * @throws LogicException thrown if Pico already started processing
  892. */
  893. public function setConfig(array $config)
  894. {
  895. if ($this->locked) {
  896. throw new LogicException("You cannot modify Pico's config after processing has started");
  897. }
  898. $this->config = $config;
  899. }
  900. /**
  901. * Returns either the value of the specified config variable or
  902. * the config array
  903. *
  904. * @see Pico::setConfig()
  905. * @see Pico::loadConfig()
  906. *
  907. * @param string $configName optional name of a config variable
  908. * @param mixed $default optional default value to return when the
  909. * named config variable doesn't exist
  910. *
  911. * @return mixed if no name of a config variable has been supplied, the
  912. * config array is returned; otherwise it returns either the value of
  913. * the named config variable, or, if the named config variable doesn't
  914. * exist, the provided default value or NULL
  915. */
  916. public function getConfig($configName = null, $default = null)
  917. {
  918. if ($configName !== null) {
  919. return isset($this->config[$configName]) ? $this->config[$configName] : $default;
  920. } else {
  921. return $this->config;
  922. }
  923. }
  924. /**
  925. * Evaluates the requested URL
  926. *
  927. * Pico uses the `QUERY_STRING` routing method (e.g. `/pico/?sub/page`)
  928. * to support SEO-like URLs out-of-the-box with any webserver. You can
  929. * still setup URL rewriting to basically remove the `?` from URLs.
  930. * However, URL rewriting requires some special configuration of your
  931. * webserver, but this should be "basic work" for any webmaster...
  932. *
  933. * With Pico 1.0 you had to setup URL rewriting (e.g. using `mod_rewrite`
  934. * on Apache) in a way that rewritten URLs follow the `QUERY_STRING`
  935. * principles. Starting with version 2.0, Pico additionally supports the
  936. * `REQUEST_URI` routing method, what allows you to simply rewrite all
  937. * requests to just `index.php`. Pico then reads the requested page from
  938. * the `REQUEST_URI` environment variable provided by the webserver.
  939. * Please note that `QUERY_STRING` takes precedence over `REQUEST_URI`.
  940. *
  941. * Pico 0.9 and older required Apache with `mod_rewrite` enabled, thus old
  942. * plugins, templates and contents may require you to enable URL rewriting
  943. * to work. If you're upgrading from Pico 0.9, you will probably have to
  944. * update your rewriting rules.
  945. *
  946. * We recommend you to use the `link` filter in templates to create
  947. * internal links, e.g. `{{ "sub/page"|link }}` is equivalent to
  948. * `{{ base_url }}/sub/page` and `{{ base_url }}?sub/page`, depending on
  949. * enabled URL rewriting. In content files you can use the `%base_url%`
  950. * variable; e.g. `%base_url%?sub/page` will be replaced accordingly.
  951. *
  952. * Heads up! Pico always interprets the first parameter as name of the
  953. * requested page (provided that the parameter has no value). According to
  954. * that you MUST NOT call Pico with a parameter without value as first
  955. * parameter (e.g. http://example.com/pico/?someBooleanParam), otherwise
  956. * Pico interprets `someBooleanParam` as name of the requested page. Use
  957. * `/pico/?someBooleanParam=` or `/pico/?index&someBooleanParam` instead.
  958. *
  959. * @see Pico::getRequestUrl()
  960. *
  961. * @return void
  962. */
  963. protected function evaluateRequestUrl()
  964. {
  965. // use QUERY_STRING; e.g. /pico/?sub/page
  966. $pathComponent = isset($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : '';
  967. if ($pathComponent) {
  968. $pathComponent = strstr($pathComponent, '&', true) ?: $pathComponent;
  969. if (strpos($pathComponent, '=') === false) {
  970. $this->requestUrl = trim(rawurldecode($pathComponent), '/');
  971. }
  972. }
  973. // use REQUEST_URI (requires URL rewriting); e.g. /pico/sub/page
  974. if (($this->requestUrl === null) && $this->isUrlRewritingEnabled()) {
  975. $scriptName = isset($_SERVER['SCRIPT_NAME']) ? $_SERVER['SCRIPT_NAME'] : '/index.php';
  976. $basePath = dirname($scriptName);
  977. $basePath = !in_array($basePath, array('.', '/', '\\'), true) ? $basePath . '/' : '/';
  978. $basePathLength = strlen($basePath);
  979. $requestUri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '';
  980. if ($requestUri && (substr($requestUri, 0, $basePathLength) === $basePath)) {
  981. $requestUri = substr($requestUri, $basePathLength);
  982. if ($requestUri && (($queryStringPos = strpos($requestUri, '?')) !== false)) {
  983. $requestUri = substr($requestUri, 0, $queryStringPos);
  984. }
  985. if ($requestUri && ($requestUri !== basename($scriptName))) {
  986. $this->requestUrl = rtrim(rawurldecode($requestUri), '/');
  987. }
  988. }
  989. }
  990. if ($this->requestUrl === null) {
  991. $this->requestUrl = '';
  992. }
  993. }
  994. /**
  995. * Returns the URL where a user requested the page
  996. *
  997. * @see Pico::evaluateRequestUrl()
  998. *
  999. * @return string|null request URL
  1000. */
  1001. public function getRequestUrl()
  1002. {
  1003. return $this->requestUrl;
  1004. }
  1005. /**
  1006. * Resolves a given file path to its corresponding content file
  1007. *
  1008. * This method also prevents `content_dir` breakouts using malicious
  1009. * request URLs. We don't use `realpath()`, because we neither want to
  1010. * check for file existance, nor prohibit symlinks which intentionally
  1011. * point to somewhere outside the `content_dir` folder. It is STRONGLY
  1012. * RECOMMENDED to use PHP's `open_basedir` feature - always, not just
  1013. * with Pico!
  1014. *
  1015. * @see Pico::getRequestFile()
  1016. *
  1017. * @param string $requestUrl path name (likely from a URL) to resolve
  1018. *
  1019. * @return string path to the resolved content file
  1020. */
  1021. public function resolveFilePath($requestUrl)
  1022. {
  1023. $contentDir = $this->getConfig('content_dir');
  1024. $contentExt = $this->getConfig('content_ext');
  1025. if (!$requestUrl) {
  1026. return $contentDir . 'index' . $contentExt;
  1027. } else {
  1028. // normalize path and prevent content_dir breakouts
  1029. $requestFile = $this->getNormalizedPath($requestUrl, false, false);
  1030. // discover the content file to serve
  1031. if (!$requestFile) {
  1032. return $contentDir . 'index' . $contentExt;
  1033. } elseif (is_dir($contentDir . $requestFile)) {
  1034. // if no index file is found, try a accordingly named file in the previous dir
  1035. // if this file doesn't exist either, show the 404 page, but assume the index
  1036. // file as being requested (maintains backward compatibility to Pico < 1.0)
  1037. $indexFile = $contentDir . $requestFile . '/index' . $contentExt;
  1038. if (file_exists($indexFile) || !file_exists($contentDir . $requestFile . $contentExt)) {
  1039. return $indexFile;
  1040. }
  1041. }
  1042. return $contentDir . $requestFile . $contentExt;
  1043. }
  1044. }
  1045. /**
  1046. * Returns the absolute path to the content file to serve
  1047. *
  1048. * @see Pico::resolveFilePath()
  1049. *
  1050. * @return string|null file pat
  1051. */
  1052. public function getRequestFile()
  1053. {
  1054. return $this->requestFile;
  1055. }
  1056. /**
  1057. * Returns the raw contents of a file
  1058. *
  1059. * @see Pico::getRawContent()
  1060. *
  1061. * @param string $file file path
  1062. *
  1063. * @return string raw contents of the file
  1064. */
  1065. public function loadFileContent($file)
  1066. {
  1067. return file_get_contents($file);
  1068. }
  1069. /**
  1070. * Returns the raw contents of the first found 404 file when traversing
  1071. * up from the directory the requested file is in
  1072. *
  1073. * If no suitable `404.md` is found, fallback to a built-in error message.
  1074. *
  1075. * @see Pico::getRawContent()
  1076. *
  1077. * @param string $file path to requested (but not existing) file
  1078. *
  1079. * @return string raw contents of the 404 file
  1080. */
  1081. public function load404Content($file)
  1082. {
  1083. $contentDir = $this->getConfig('content_dir');
  1084. $contentDirLength = strlen($contentDir);
  1085. $contentExt = $this->getConfig('content_ext');
  1086. if (substr($file, 0, $contentDirLength) === $contentDir) {
  1087. $errorFileDir = substr($file, $contentDirLength);
  1088. while ($errorFileDir !== '.') {
  1089. $errorFileDir = dirname($errorFileDir);
  1090. $errorFile = $errorFileDir . '/404' . $contentExt;
  1091. if (file_exists($contentDir . $errorFile)) {
  1092. return $this->loadFileContent($contentDir . $errorFile);
  1093. }
  1094. }
  1095. } elseif (file_exists($contentDir . '404' . $contentExt)) {
  1096. // provided that the requested file is not in the regular
  1097. // content directory, fallback to Pico's global `404.md`
  1098. return $this->loadFileContent($contentDir . '404' . $contentExt);
  1099. }
  1100. // fallback to built-in error message
  1101. $rawErrorContent = "---\n"
  1102. . "Title: Error 404\n"
  1103. . "Robots: noindex,nofollow\n"
  1104. . "---\n\n"
  1105. . "# Error 404\n\n"
  1106. . "Woops. Looks like this page doesn't exist.\n";
  1107. return $rawErrorContent;
  1108. }
  1109. /**
  1110. * Returns the raw contents, either of the requested or the 404 file
  1111. *
  1112. * @see Pico::loadFileContent()
  1113. * @see Pico::load404Content()
  1114. *
  1115. * @return string|null raw contents
  1116. */
  1117. public function getRawContent()
  1118. {
  1119. return $this->rawContent;
  1120. }
  1121. /**
  1122. * Returns TRUE when Pico is serving a 404 page
  1123. *
  1124. * @see Pico::load404Content()
  1125. *
  1126. * @return bool TRUE if Pico is serving a 404 page, FALSE otherwise
  1127. */
  1128. public function is404Content()
  1129. {
  1130. return $this->is404Content;
  1131. }
  1132. /**
  1133. * Returns known meta headers
  1134. *
  1135. * This method triggers the `onMetaHeaders` event when the known meta
  1136. * headers weren't assembled yet.
  1137. *
  1138. * @return string[] known meta headers; the array key specifies the YAML
  1139. * key to search for, the array value is later used to access the
  1140. * found value
  1141. */
  1142. public function getMetaHeaders()
  1143. {
  1144. if ($this->metaHeaders === null) {
  1145. $this->metaHeaders = array(
  1146. 'Title' => 'title',
  1147. 'Description' => 'description',
  1148. 'Author' => 'author',
  1149. 'Date' => 'date',
  1150. 'Formatted Date' => 'date_formatted',
  1151. 'Time' => 'time',
  1152. 'Robots' => 'robots',
  1153. 'Template' => 'template',
  1154. 'Hidden' => 'hidden'
  1155. );
  1156. $this->triggerEvent('onMetaHeaders', array(&$this->metaHeaders));
  1157. }
  1158. return $this->metaHeaders;
  1159. }
  1160. /**
  1161. * Returns the Symfony YAML parser
  1162. *
  1163. * This method triggers the `onYamlParserRegistered` event when the Symfony
  1164. * YAML parser wasn't initiated yet.
  1165. *
  1166. * @return \Symfony\Component\Yaml\Parser Symfony YAML parser
  1167. */
  1168. public function getYamlParser()
  1169. {
  1170. if ($this->yamlParser === null) {
  1171. $this->yamlParser = new \Symfony\Component\Yaml\Parser();
  1172. $this->triggerEvent('onYamlParserRegistered', array(&$this->yamlParser));
  1173. }
  1174. return $this->yamlParser;
  1175. }
  1176. /**
  1177. * Parses the file meta from raw file contents
  1178. *
  1179. * Meta data MUST start on the first line of the file, either opened and
  1180. * closed by `---` or C-style block comments (deprecated). The headers are
  1181. * parsed by the YAML component of the Symfony project. If you're a plugin
  1182. * developer, you MUST register new headers during the `onMetaHeaders`
  1183. * event first. The implicit availability of headers is for users and
  1184. * pure (!) theme developers ONLY.
  1185. *
  1186. * @see Pico::getFileMeta()
  1187. *
  1188. * @param string $rawContent the raw file contents
  1189. * @param string[] $headers known meta headers
  1190. *
  1191. * @return array parsed meta data
  1192. *
  1193. * @throws \Symfony\Component\Yaml\Exception\ParseException thrown when the
  1194. * meta data is invalid
  1195. */
  1196. public function parseFileMeta($rawContent, array $headers)
  1197. {
  1198. $meta = array();
  1199. $pattern = "/^(\/(\*)|---)[[:blank:]]*(?:\r)?\n"
  1200. . "(?:(.*?)(?:\r)?\n)?(?(2)\*\/|---)[[:blank:]]*(?:(?:\r)?\n|$)/s";
  1201. if (preg_match($pattern, $rawContent, $rawMetaMatches) && isset($rawMetaMatches[3])) {
  1202. $meta = $this->getYamlParser()->parse($rawMetaMatches[3]) ?: array();
  1203. $meta = is_array($meta) ? $meta : array('title' => $meta);
  1204. foreach ($headers as $name => $key) {
  1205. if (isset($meta[$name])) {
  1206. // rename field (e.g. remove whitespaces)
  1207. if ($key != $name) {
  1208. $meta[$key] = $meta[$name];
  1209. unset($meta[$name]);
  1210. }
  1211. } elseif (!isset($meta[$key])) {
  1212. // guarantee array key existance
  1213. $meta[$key] = '';
  1214. }
  1215. }
  1216. if (!empty($meta['date']) || !empty($meta['time'])) {
  1217. // workaround for issue #336
  1218. // Symfony YAML interprets ISO-8601 datetime strings and returns timestamps instead of the string
  1219. // this behavior conforms to the YAML standard, i.e. this is no bug of Symfony YAML
  1220. if (is_int($meta['date'])) {
  1221. $meta['time'] = $meta['date'];
  1222. $meta['date'] = '';
  1223. }
  1224. if (empty($meta['time'])) {
  1225. $meta['time'] = strtotime($meta['date']) ?: '';
  1226. } elseif (empty($meta['date'])) {
  1227. $rawDateFormat = (date('H:i:s', $meta['time']) === '00:00:00') ? 'Y-m-d' : 'Y-m-d H:i:s';
  1228. $meta['date'] = date($rawDateFormat, $meta['time']);
  1229. }
  1230. } else {
  1231. $meta['date'] = $meta['time'] = '';
  1232. }
  1233. if (empty($meta['date_formatted'])) {
  1234. $dateFormat = $this->getConfig('date_format');
  1235. $meta['date_formatted'] = $meta['time'] ? utf8_encode(strftime($dateFormat, $meta['time'])) : '';
  1236. }
  1237. } else {
  1238. // guarantee array key existance
  1239. $meta = array_fill_keys($headers, '');
  1240. }
  1241. return $meta;
  1242. }
  1243. /**
  1244. * Returns the parsed meta data of the requested page
  1245. *
  1246. * @see Pico::parseFileMeta()
  1247. *
  1248. * @return array|null parsed meta data
  1249. */
  1250. public function getFileMeta()
  1251. {
  1252. return $this->meta;
  1253. }
  1254. /**
  1255. * Returns the Parsedown markdown parser
  1256. *
  1257. * This method triggers the `onParsedownRegistered` event when the
  1258. * Parsedown markdown parser wasn't initiated yet.
  1259. *
  1260. * @return Parsedown Parsedown markdown parser
  1261. */
  1262. public function getParsedown()
  1263. {
  1264. if ($this->parsedown === null) {
  1265. $className = $this->config['content_config']['extra'] ? 'ParsedownExtra' : 'Parsedown';
  1266. $this->parsedown = new $className();
  1267. $this->parsedown->setBreaksEnabled((bool) $this->config['content_config']['breaks']);
  1268. $this->parsedown->setMarkupEscaped((bool) $this->config['content_config']['escape']);
  1269. $this->parsedown->setUrlsLinked((bool) $this->config['content_config']['auto_urls']);
  1270. $this->triggerEvent('onParsedownRegistered', array(&$this->parsedown));
  1271. }
  1272. return $this->parsedown;
  1273. }
  1274. /**
  1275. * Applies some static preparations to the raw contents of a page
  1276. *
  1277. * This method removes the meta header and replaces `%...%` placeholders
  1278. * by calling the {@see Pico::substituteFileContent()} method.
  1279. *
  1280. * @see Pico::substituteFileContent()
  1281. * @see Pico::parseFileContent()
  1282. * @see Pico::getFileContent()
  1283. *
  1284. * @param string $rawContent raw contents of a page
  1285. * @param array $meta meta data to use for %meta.*% replacement
  1286. *
  1287. * @return string prepared Markdown contents
  1288. */
  1289. public function prepareFileContent($rawContent, array $meta = array())
  1290. {
  1291. // remove meta header
  1292. $metaHeaderPattern = "/^(\/(\*)|---)[[:blank:]]*(?:\r)?\n"
  1293. . "(?:(.*?)(?:\r)?\n)?(?(2)\*\/|---)[[:blank:]]*(?:(?:\r)?\n|$)/s";
  1294. $markdown = preg_replace($metaHeaderPattern, '', $rawContent, 1);
  1295. // replace placeholders
  1296. $markdown = $this->substituteFileContent($markdown, $meta);
  1297. return $markdown;
  1298. }
  1299. /**
  1300. * Replaces all %...% placeholders in a page's contents
  1301. *
  1302. * @param string $markdown Markdown contents of a page
  1303. * @param array $meta meta data to use for %meta.*% replacement
  1304. *
  1305. * @return string substituted Markdown contents
  1306. */
  1307. public function substituteFileContent($markdown, array $meta = array())
  1308. {
  1309. $variables = array();
  1310. // replace %version%
  1311. $variables['%version%'] = static::VERSION;
  1312. // replace %site_title%
  1313. $variables['%site_title%'] = $this->getConfig('site_title');
  1314. // replace %base_url%
  1315. if ($this->isUrlRewritingEnabled()) {
  1316. // always use `%base_url%?sub/page` syntax for internal links
  1317. // we'll replace the links accordingly, depending on enabled rewriting
  1318. $variables['%base_url%?'] = $this->getBaseUrl();
  1319. } else {
  1320. // actually not necessary, but makes the URL look a little nicer
  1321. $variables['%base_url%?'] = $this->getBaseUrl() . '?';
  1322. }
  1323. $variables['%base_url%'] = rtrim($this->getBaseUrl(), '/');
  1324. // replace %theme_url%
  1325. $variables['%theme_url%'] = $this->getBaseThemeUrl() . $this->getConfig('theme');
  1326. // replace %meta.*%
  1327. if ($meta) {
  1328. foreach ($meta as $metaKey => $metaValue) {
  1329. if (is_scalar($metaValue) || ($metaValue === null)) {
  1330. $variables['%meta.' . $metaKey . '%'] = (string) $metaValue;
  1331. }
  1332. }
  1333. }
  1334. // replace %config.*%
  1335. foreach ($this->config as $configKey => $configValue) {
  1336. if (is_scalar($configValue) || ($configValue === null)) {
  1337. $variables['%config.' . $configKey . '%'] = (string) $configValue;
  1338. }
  1339. }
  1340. return str_replace(array_keys($variables), $variables, $markdown);
  1341. }
  1342. /**
  1343. * Parses the contents of a page using ParsedownExtra
  1344. *
  1345. * @see Pico::prepareFileContent()
  1346. * @see Pico::substituteFileContent()
  1347. * @see Pico::getFileContent()
  1348. *
  1349. * @param string $markdown Markdown contents of a page
  1350. *
  1351. * @return string parsed contents (HTML)
  1352. */
  1353. public function parseFileContent($markdown)
  1354. {
  1355. return $this->getParsedown()->text($markdown);
  1356. }
  1357. /**
  1358. * Returns the cached contents of the requested page
  1359. *
  1360. * @see Pico::prepareFileContent()
  1361. * @see Pico::substituteFileContent()
  1362. * @see Pico::parseFileContent()
  1363. *
  1364. * @return string|null parsed contents
  1365. */
  1366. public function getFileContent()
  1367. {
  1368. return $this->content;
  1369. }
  1370. /**
  1371. * Reads the data of all pages known to Pico
  1372. *
  1373. * The page data will be an array containing the following values:
  1374. *
  1375. * | Array key | Type | Description |
  1376. * | -------------- | ------- | ---------------------------------------- |
  1377. * | id | string | relative path to the content file |
  1378. * | url | string | URL to the page |
  1379. * | title | string | title of the page (YAML header) |
  1380. * | description | string | description of the page (YAML header) |
  1381. * | author | string | author of the page (YAML header) |
  1382. * | time | int | timestamp derived from the Date header |
  1383. * | date | string | date of the page (YAML header) |
  1384. * | date_formatted | string | formatted date of the page |
  1385. * | hidden | bool | this page shouldn't be visible |
  1386. * | raw_content | string | raw, not yet parsed contents of the page |
  1387. * | meta | string[] | parsed meta data of the page |
  1388. * | previous_page | &array[] | reference to the previous page |
  1389. * | next_page | &array[] | reference to the next page |
  1390. * | tree_node | &array[] | reference to the page's tree node |
  1391. *
  1392. * Please note that the `previous_page` and `next_page` keys don't
  1393. * exist until the `onCurrentPageDiscovered` event is triggered
  1394. * ({@see Pico::discoverPageSiblings()}). The `tree_node` key doesn't
  1395. * exit until the `onPageTreeBuilt` event is triggered
  1396. * ({@see Pico::buildPageTree()}).
  1397. *
  1398. * @see Pico::sortPages()
  1399. * @see Pico::discoverPageSiblings()
  1400. * @see Pico::getPages()
  1401. *
  1402. * @return void
  1403. */
  1404. protected function readPages()
  1405. {
  1406. $contentDir = $this->getConfig('content_dir');
  1407. $contentExt = $this->getConfig('content_ext');
  1408. $this->pages = array();
  1409. $files = $this->getFiles($contentDir, $contentExt, self::SORT_NONE);
  1410. foreach ($files as $i => $file) {
  1411. // skip 404 page
  1412. if (basename($file) === '404' . $contentExt) {
  1413. unset($files[$i]);
  1414. continue;
  1415. }
  1416. $id = substr($file, strlen($contentDir), -strlen($contentExt));
  1417. // trigger onSinglePageLoading event
  1418. // skip inaccessible pages (e.g. drop "sub.md" if "sub/index.md" exists) by default
  1419. $conflictFile = $contentDir . $id . '/index' . $contentExt;
  1420. $skipFile = in_array($conflictFile, $files, true) ?: null;
  1421. $this->triggerEvent('onSinglePageLoading', array($id, &$skipFile));
  1422. if ($skipFile) {
  1423. continue;
  1424. }
  1425. $url = $this->getPageUrl($id);
  1426. if ($file !== $this->requestFile) {
  1427. $rawContent = $this->loadFileContent($file);
  1428. // trigger onSinglePageContent event
  1429. $this->triggerEvent('onSinglePageContent', array($id, &$rawContent));
  1430. $headers = $this->getMetaHeaders();
  1431. try {
  1432. $meta = $this->parseFileMeta($rawContent, $headers);
  1433. } catch (\Symfony\Component\Yaml\Exception\ParseException $e) {
  1434. $meta = $this->parseFileMeta('', $headers);
  1435. $meta['YAML_ParseError'] = $e->getMessage();
  1436. }
  1437. } else {
  1438. $rawContent = &$this->rawContent;
  1439. $meta = &$this->meta;
  1440. }
  1441. // build page data
  1442. // title, description, author and date are assumed to be pretty basic data
  1443. // everything else is accessible through $page['meta']
  1444. $page = array(
  1445. 'id' => $id,
  1446. 'url' => $url,
  1447. 'title' => &$meta['title'],
  1448. 'description' => &$meta['description'],
  1449. 'author' => &$meta['author'],
  1450. 'time' => &$meta['time'],
  1451. 'date' => &$meta['date'],
  1452. 'date_formatted' => &$meta['date_formatted'],
  1453. 'hidden' => (preg_match('/(?:^|\/)_/', $id) || $meta['hidden']),
  1454. 'raw_content' => &$rawContent,
  1455. 'meta' => &$meta
  1456. );
  1457. if ($file === $this->requestFile) {
  1458. $page['content'] = &$this->content;
  1459. }
  1460. unset($rawContent, $meta);
  1461. // trigger onSinglePageLoaded event
  1462. $this->triggerEvent('onSinglePageLoaded', array(&$page));
  1463. if ($page !== null) {
  1464. $this->pages[$id] = $page;
  1465. }
  1466. }
  1467. }
  1468. /**
  1469. * Sorts all pages known to Pico
  1470. *
  1471. * @see Pico::readPages()
  1472. * @see Pico::getPages()
  1473. *
  1474. * @return void
  1475. */
  1476. protected function sortPages()
  1477. {
  1478. // sort pages
  1479. $order = strtolower($this->getConfig('pages_order'));
  1480. $orderBy = strtolower($this->getConfig('pages_order_by'));
  1481. if (($orderBy !== 'alpha') && ($orderBy !== 'date') && ($orderBy !== 'meta')) {
  1482. return;
  1483. }
  1484. $alphaSortClosure = function ($a, $b) use ($order) {
  1485. if (!empty($a['hidden']) xor !empty($b['hidden'])) {
  1486. return (!empty($a['hidden']) - !empty($b['hidden'])) * (($order === 'desc') ? -1 : 1);
  1487. }
  1488. $aSortKey = (basename($a['id']) === 'index') ? dirname($a['id']) : $a['id'];
  1489. $bSortKey = (basename($b['id']) === 'index') ? dirname($b['id']) : $b['id'];
  1490. $cmp = strcmp($aSortKey, $bSortKey);
  1491. return $cmp * (($order === 'desc') ? -1 : 1);
  1492. };
  1493. if ($orderBy === 'meta') {
  1494. // sort by arbitrary meta value
  1495. $orderByMeta = $this->getConfig('pages_order_by_meta');
  1496. uasort($this->pages, function ($a, $b) use ($alphaSortClosure, $order, $orderByMeta) {
  1497. $aSortValue = isset($a['meta'][$orderByMeta]) ? $a['meta'][$orderByMeta] : null;
  1498. $aSortValueNull = ($aSortValue === null);
  1499. $bSortValue = isset($b['meta'][$orderByMeta]) ? $b['meta'][$orderByMeta] : null;
  1500. $bSortValueNull = ($bSortValue === null);
  1501. $cmp = 0;
  1502. if ($aSortValueNull || $bSortValueNull) {
  1503. $cmp = ($aSortValueNull - $bSortValueNull);
  1504. } elseif ($aSortValue != $bSortValue) {
  1505. $cmp = ($aSortValue > $bSortValue) ? 1 : -1;
  1506. }
  1507. if ($cmp === 0) {
  1508. // never assume equality; fallback to alphabetical order
  1509. return $alphaSortClosure($a, $b);
  1510. }
  1511. return $cmp * (($order === 'desc') ? -1 : 1);
  1512. });
  1513. } elseif ($orderBy === 'date') {
  1514. // sort by date
  1515. uasort($this->pages, function ($a, $b) use ($alphaSortClosure, $order) {
  1516. if (!empty($a['hidden']) xor !empty($b['hidden'])) {
  1517. return $alphaSortClosure($a, $b);
  1518. }
  1519. if (!$a['time'] || !$b['time']) {
  1520. $cmp = (!$a['time'] - !$b['time']);
  1521. } else {
  1522. $cmp = ($b['time'] - $a['time']);
  1523. }
  1524. if ($cmp === 0) {
  1525. // never assume equality; fallback to alphabetical order
  1526. return $alphaSortClosure($a, $b);
  1527. }
  1528. return $cmp * (($order === 'desc') ? 1 : -1);
  1529. });
  1530. } else {
  1531. // sort alphabetically
  1532. uasort($this->pages, $alphaSortClosure);
  1533. }
  1534. }
  1535. /**
  1536. * Walks through the list of all known pages and discovers the previous and
  1537. * next page respectively
  1538. *
  1539. * @see Pico::readPages()
  1540. * @see Pico::getPages()
  1541. *
  1542. * @return void
  1543. */
  1544. protected function discoverPageSiblings()
  1545. {
  1546. if (($this->getConfig('order_by') === 'date') && ($this->getConfig('order') === 'desc')) {
  1547. $precedingPageKey = 'next_page';
  1548. $succeedingPageKey = 'previous_page';
  1549. } else {
  1550. $precedingPageKey = 'previous_page';
  1551. $succeedingPageKey = 'next_page';
  1552. }
  1553. $precedingPageId = null;
  1554. foreach ($this->pages as $id => &$pageData) {
  1555. $pageData[$precedingPageKey] = null;
  1556. $pageData[$succeedingPageKey] = null;
  1557. if (!empty($pageData['hidden'])) {
  1558. continue;
  1559. }
  1560. if ($precedingPageId !== null) {
  1561. $precedingPageData = &$this->pages[$precedingPageId];
  1562. $pageData[$precedingPageKey] = &$precedingPageData;
  1563. $precedingPageData[$succeedingPageKey] = &$pageData;
  1564. }
  1565. $precedingPageId = $id;
  1566. }
  1567. }
  1568. /**
  1569. * Returns the list of known pages
  1570. *
  1571. * @see Pico::readPages()
  1572. *
  1573. * @return array[]|null the data of all pages
  1574. */
  1575. public function getPages()
  1576. {
  1577. return $this->pages;
  1578. }
  1579. /**
  1580. * Discovers the page data of the requested page as well as the previous
  1581. * and next page relative to it
  1582. *
  1583. * @see Pico::getCurrentPage()
  1584. * @see Pico::getPreviousPage()
  1585. * @see Pico::getNextPage()
  1586. *
  1587. * @return void
  1588. */
  1589. protected function discoverCurrentPage()
  1590. {
  1591. $currentPageId = $this->getPageId($this->requestFile);
  1592. if ($currentPageId && isset($this->pages[$currentPageId])) {
  1593. $this->currentPage = &$this->pages[$currentPageId];
  1594. $this->previousPage = &$this->pages[$currentPageId]['previous_page'];
  1595. $this->nextPage = &$this->pages[$currentPageId]['next_page'];
  1596. }
  1597. }
  1598. /**
  1599. * Returns the data of the requested page
  1600. *
  1601. * @see Pico::discoverCurrentPage()
  1602. *
  1603. * @return array|null page data
  1604. */
  1605. public function getCurrentPage()
  1606. {
  1607. return $this->currentPage;
  1608. }
  1609. /**
  1610. * Returns the data of the previous page relative to the page being served
  1611. *
  1612. * @see Pico::discoverCurrentPage()
  1613. *
  1614. * @return array|null page data
  1615. */
  1616. public function getPreviousPage()
  1617. {
  1618. return $this->previousPage;
  1619. }
  1620. /**
  1621. * Returns the data of the next page relative to the page being served
  1622. *
  1623. * @see Pico::discoverCurrentPage()
  1624. *
  1625. * @return array|null page data
  1626. */
  1627. public function getNextPage()
  1628. {
  1629. return $this->nextPage;
  1630. }
  1631. /**
  1632. * Builds a tree structure containing all known pages
  1633. *
  1634. * Pico's page tree is a list of all the tree's branches (no matter the
  1635. * depth). Thus, by iterating a array element, you get the nodes of a given
  1636. * branch. All leaf nodes do represent a page, but inner nodes may or may
  1637. * not represent a page (e.g. if there's a `sub/page.md`, but neither a
  1638. * `sub/index.md` nor a `sub.md`, the inner node `sub`, that is the parent
  1639. * of the `sub/page` node, represents no page itself).
  1640. *
  1641. * A page's file path describes its node's path in the tree (e.g. the page
  1642. * `sub/page.md` is represented by the `sub/page` node, thus a child of the
  1643. * `sub` node and a element of the `sub` branch). However, the index page
  1644. * of a folder (e.g. `sub/index.md`), is *not* a node of the `sub` branch,
  1645. * but rather of the `/` branch. The page's node is not `sub/index`, but
  1646. * `sub`. If two pages are described by the same node (e.g. if both a
  1647. * `sub/index.md` and a `sub.md` exist), the index page takes precedence.
  1648. * Pico's main index page (i.e. `index.md`) is represented by the tree's
  1649. * root node `/` and a special case: it is the only node of the `` (i.e.
  1650. * the empty string) branch.
  1651. *
  1652. * A node is represented by an array with the keys `id`, `page` and
  1653. * `children`. The `id` key contains a string with the node's name. If the
  1654. * node represents a page, the `page` key is a reference to the page's
  1655. * data array. If the node is a inner node, the `children` key is a
  1656. * reference to its matching branch (i.e. a list of the node's children).
  1657. * The order of a node's children matches the order in Pico's pages array.
  1658. *
  1659. * If you want to walk the whole page tree, start with the tree's root node
  1660. * at `$pageTree[""]["/"]`, or rather, use `$pages["index"]["tree_node"]`.
  1661. * The root node's `children` key is a reference to the `/` branch at
  1662. * `$pageTree["/"]`, that is a list of the root node's direct child nodes
  1663. * and their siblings.
  1664. *
  1665. * You MUST NOT iterate the page tree itself (i.e. the list of the tree's
  1666. * branches), its order is undefined and the array will be replaced by a
  1667. * non-iterable data structure with Pico 3.0.
  1668. *
  1669. * @see Pico::getPageTree()
  1670. *
  1671. * @return void
  1672. */
  1673. protected function buildPageTree()
  1674. {
  1675. $this->pageTree = array();
  1676. foreach ($this->pages as $id => &$pageData) {
  1677. // main index page
  1678. if ($id === 'index') {
  1679. $this->pageTree['']['/']['id'] = '/';
  1680. $this->pageTree['']['/']['page'] = &$pageData;
  1681. $pageData['tree_node'] = &$this->pageTree['']['/'];
  1682. continue;
  1683. }
  1684. // get a page's node and branch
  1685. $basename = basename($id);
  1686. $branch = dirname($id);
  1687. $isIndexPage = ($basename === 'index');
  1688. if ($isIndexPage) {
  1689. $basename = basename($branch);
  1690. $branch = dirname($branch);
  1691. }
  1692. $branch = ($branch !== '.') ? $branch : '/';
  1693. $node = ($branch !== '/') ? $branch . '/' . $basename : $basename;
  1694. // skip inaccessible pages (e.g. drop "sub.md" if "sub/index.md" exists)
  1695. if (isset($this->pageTree[$branch][$node]['page']) && !$isIndexPage) {
  1696. continue;
  1697. }
  1698. // add node to page tree
  1699. $isNewBranch = !isset($this->pageTree[$branch]);
  1700. $this->pageTree[$branch][$node]['id'] = $node;
  1701. $this->pageTree[$branch][$node]['page'] = &$pageData;
  1702. $pageData['tree_node'] = &$this->pageTree[$branch][$node];
  1703. // add parent nodes to page tree, if necessary
  1704. while ($isNewBranch && $branch) {
  1705. $parentNode = $branch;
  1706. $parentBranch = ($branch !== '/') ? dirname($parentNode) : '';
  1707. $parentBranch = ($parentBranch !== '.') ? $parentBranch : '/';
  1708. $isNewBranch = !isset($this->pageTree[$parentBranch]);
  1709. $this->pageTree[$parentBranch][$parentNode]['id'] = $parentNode;
  1710. $this->pageTree[$parentBranch][$parentNode]['children'] = &$this->pageTree[$branch];
  1711. $branch = $parentBranch;
  1712. }
  1713. }
  1714. }
  1715. /**
  1716. * Returns a tree structure of known pages
  1717. *
  1718. * @see Pico::buildPageTree()
  1719. *
  1720. * @return array[]|null the tree structure of all pages
  1721. */
  1722. public function getPageTree()
  1723. {
  1724. return $this->pageTree;
  1725. }
  1726. /**
  1727. * Returns the Twig template engine
  1728. *
  1729. * This method triggers the `onTwigRegistered` event when the Twig template
  1730. * engine wasn't initiated yet. When initiating Twig, this method also
  1731. * registers Pico's core Twig filter `content` as well as Pico's
  1732. * {@see PicoTwigExtension} Twig extension.
  1733. *
  1734. * @see Pico::getTwig()
  1735. * @see http://twig.sensiolabs.org/ Twig website
  1736. * @see https://github.com/twigphp/Twig Twig on GitHub
  1737. *
  1738. * @return Twig_Environment|null Twig template engine
  1739. */
  1740. public function getTwig()
  1741. {
  1742. if ($this->twig === null) {
  1743. $twigConfig = $this->getConfig('twig_config');
  1744. $twigLoader = new Twig_Loader_Filesystem($this->getThemesDir() . $this->getConfig('theme'));
  1745. $this->twig = new Twig_Environment($twigLoader, $twigConfig);
  1746. $this->twig->addExtension(new PicoTwigExtension($this));
  1747. if (!empty($twigConfig['debug'])) {
  1748. $this->twig->addExtension(new Twig_Extension_Debug());
  1749. }
  1750. // register content filter
  1751. // we pass the $pages array by reference to prevent multiple parser runs for the same page
  1752. // this is the reason why we can't register this filter as part of PicoTwigExtension
  1753. $pico = $this;
  1754. $pages = &$this->pages;
  1755. $this->twig->addFilter(new Twig_SimpleFilter('content', function ($page) use ($pico, &$pages) {
  1756. if (isset($pages[$page])) {
  1757. $pageData = &$pages[$page];
  1758. if (!isset($pageData['content'])) {
  1759. $pageData['content'] = $pico->prepareFileContent($pageData['raw_content'], $pageData['meta']);
  1760. $pageData['content'] = $pico->parseFileContent($pageData['content']);
  1761. }
  1762. return $pageData['content'];
  1763. }
  1764. return null;
  1765. }));
  1766. // trigger onTwigRegistration event
  1767. $this->triggerEvent('onTwigRegistered', array(&$this->twig));
  1768. }
  1769. return $this->twig;
  1770. }
  1771. /**
  1772. * Returns the variables passed to the template
  1773. *
  1774. * URLs and paths (namely `base_dir`, `base_url`, `theme_dir` and
  1775. * `theme_url`) don't add a trailing slash for historic reasons.
  1776. *
  1777. * @return array template variables
  1778. */
  1779. protected function getTwigVariables()
  1780. {
  1781. return array(
  1782. 'config' => $this->getConfig(),
  1783. 'base_dir' => rtrim($this->getRootDir(), '/'),
  1784. 'base_url' => rtrim($this->getBaseUrl(), '/'),
  1785. 'theme_dir' => $this->getThemesDir() . $this->getConfig('theme'),
  1786. 'theme_url' => $this->getBaseThemeUrl() . $this->getConfig('theme'),
  1787. 'site_title' => $this->getConfig('site_title'),
  1788. 'meta' => $this->meta,
  1789. 'content' => $this->content,
  1790. 'pages' => $this->pages,
  1791. 'previous_page' => $this->previousPage,
  1792. 'current_page' => $this->currentPage,
  1793. 'next_page' => $this->nextPage,
  1794. 'version' => static::VERSION
  1795. );
  1796. }
  1797. /**
  1798. * Returns the name of the Twig template to render
  1799. *
  1800. * @return string template name
  1801. */
  1802. protected function getTwigTemplate()
  1803. {
  1804. $templateName = !empty($this->meta['template']) ? $this->meta['template'] : 'index';
  1805. return $templateName . '.twig';
  1806. }
  1807. /**
  1808. * Returns the base URL of this Pico instance
  1809. *
  1810. * Security Notice: You MUST configure Pico's base URL explicitly when
  1811. * using the base URL in contexts that are potentially vulnerable to
  1812. * HTTP Host Header Injection attacks (e.g. when generating emails).
  1813. *
  1814. * @return string the base url
  1815. */
  1816. public function getBaseUrl()
  1817. {
  1818. $baseUrl = $this->getConfig('base_url');
  1819. if ($baseUrl) {
  1820. return $baseUrl;
  1821. }
  1822. $host = 'localhost';
  1823. if (!empty($_SERVER['HTTP_X_FORWARDED_HOST'])) {
  1824. $host = $_SERVER['HTTP_X_FORWARDED_HOST'];
  1825. } elseif (!empty($_SERVER['HTTP_HOST'])) {
  1826. $host = $_SERVER['HTTP_HOST'];
  1827. } elseif (!empty($_SERVER['SERVER_NAME'])) {
  1828. $host = $_SERVER['SERVER_NAME'];
  1829. }
  1830. $port = 80;
  1831. if (!empty($_SERVER['HTTP_X_FORWARDED_PORT'])) {
  1832. $port = (int) $_SERVER['HTTP_X_FORWARDED_PORT'];
  1833. } elseif (!empty($_SERVER['SERVER_PORT'])) {
  1834. $port = (int) $_SERVER['SERVER_PORT'];
  1835. }
  1836. $hostPortPosition = ($host[0] === '[') ? strpos($host, ':', strrpos($host, ']') ?: 0) : strrpos($host, ':');
  1837. if ($hostPortPosition !== false) {
  1838. $port = (int) substr($host, $hostPortPosition + 1);
  1839. $host = substr($host, 0, $hostPortPosition);
  1840. }
  1841. $protocol = 'http';
  1842. if (!empty($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
  1843. $secureProxyHeader = strtolower(current(explode(',', $_SERVER['HTTP_X_FORWARDED_PROTO'])));
  1844. $protocol = in_array($secureProxyHeader, array('https', 'on', 'ssl', '1'), true) ? 'https' : 'http';
  1845. } elseif (!empty($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] !== 'off')) {
  1846. $protocol = 'https';
  1847. } elseif ($port === 443) {
  1848. $protocol = 'https';
  1849. }
  1850. $basePath = isset($_SERVER['SCRIPT_NAME']) ? dirname($_SERVER['SCRIPT_NAME']) : '/';
  1851. $basePath = !in_array($basePath, array('.', '/', '\\'), true) ? $basePath . '/' : '/';
  1852. if ((($protocol === 'http') && ($port !== 80)) || (($protocol === 'https') && ($port !== 443))) {
  1853. $host = $host . ':' . $port;
  1854. }
  1855. $this->config['base_url'] = $protocol . "://" . $host . $basePath;
  1856. return $this->config['base_url'];
  1857. }
  1858. /**
  1859. * Returns TRUE if URL rewriting is enabled
  1860. *
  1861. * @return bool TRUE if URL rewriting is enabled, FALSE otherwise
  1862. */
  1863. public function isUrlRewritingEnabled()
  1864. {
  1865. $urlRewritingEnabled = $this->getConfig('rewrite_url');
  1866. if ($urlRewritingEnabled !== null) {
  1867. return $urlRewritingEnabled;
  1868. }
  1869. if (isset($_SERVER['PICO_URL_REWRITING'])) {
  1870. $this->config['rewrite_url'] = (bool) $_SERVER['PICO_URL_REWRITING'];
  1871. } elseif (isset($_SERVER['REDIRECT_PICO_URL_REWRITING'])) {
  1872. $this->config['rewrite_url'] = (bool) $_SERVER['REDIRECT_PICO_URL_REWRITING'];
  1873. } else {
  1874. $this->config['rewrite_url'] = false;
  1875. }
  1876. return $this->config['rewrite_url'];
  1877. }
  1878. /**
  1879. * Returns TRUE if Pico's debug mode is enabled
  1880. *
  1881. * @return bool TRUE if Pico's debug mode is enabled, FALSE otherwise
  1882. */
  1883. public function isDebugModeEnabled()
  1884. {
  1885. $debugModeEnabled = $this->getConfig('debug');
  1886. if ($debugModeEnabled !== null) {
  1887. return $debugModeEnabled;
  1888. }
  1889. if (isset($_SERVER['PICO_DEBUG'])) {
  1890. $this->config['debug'] = (bool) $_SERVER['PICO_DEBUG'];
  1891. } elseif (isset($_SERVER['REDIRECT_PICO_DEBUG'])) {
  1892. $this->config['debug'] = (bool) $_SERVER['REDIRECT_PICO_DEBUG'];
  1893. } else {
  1894. $this->config['debug'] = false;
  1895. }
  1896. return $this->config['debug'];
  1897. }
  1898. /**
  1899. * Returns the URL to a given page
  1900. *
  1901. * This method can be used in Twig templates by applying the `link` filter
  1902. * to a string representing a page ID.
  1903. *
  1904. * @param string $page ID of the page to link to
  1905. * @param array|string|null $queryData either an array of properties to
  1906. * create a URL-encoded query string from, or a already encoded string
  1907. * @param bool $dropIndex if the last path component is
  1908. * "index", passing TRUE (default) will remove this path component
  1909. *
  1910. * @return string URL
  1911. */
  1912. public function getPageUrl($page, $queryData = null, $dropIndex = true)
  1913. {
  1914. if (is_array($queryData)) {
  1915. $queryData = http_build_query($queryData, '', '&');
  1916. } elseif (($queryData !== null) && !is_string($queryData)) {
  1917. throw new InvalidArgumentException(
  1918. 'Argument 2 passed to ' . get_called_class() . '::getPageUrl() must be of the type array or string, '
  1919. . (is_object($queryData) ? get_class($queryData) : gettype($queryData)) . ' given'
  1920. );
  1921. }
  1922. // drop "index"
  1923. if ($dropIndex) {
  1924. if ($page === 'index') {
  1925. $page = '';
  1926. } elseif (($pagePathLength = strrpos($page, '/')) !== false) {
  1927. if (substr($page, $pagePathLength + 1) === 'index') {
  1928. $page = substr($page, 0, $pagePathLength);
  1929. }
  1930. }
  1931. }
  1932. if ($queryData) {
  1933. $queryData = ($this->isUrlRewritingEnabled() || !$page) ? '?' . $queryData : '&' . $queryData;
  1934. } else {
  1935. $queryData = '';
  1936. }
  1937. if (!$page) {
  1938. return $this->getBaseUrl() . $queryData;
  1939. } elseif (!$this->isUrlRewritingEnabled()) {
  1940. return $this->getBaseUrl() . '?' . rawurlencode($page) . $queryData;
  1941. } else {
  1942. return $this->getBaseUrl() . implode('/', array_map('rawurlencode', explode('/', $page))) . $queryData;
  1943. }
  1944. }
  1945. /**
  1946. * Returns the page ID of a given content file
  1947. *
  1948. * @param string $path path to the content file
  1949. *
  1950. * @return string|null either the corresponding page ID or NULL
  1951. */
  1952. public function getPageId($path)
  1953. {
  1954. $contentDir = $this->getConfig('content_dir');
  1955. $contentDirLength = strlen($contentDir);
  1956. if (substr($path, 0, $contentDirLength) !== $contentDir) {
  1957. return null;
  1958. }
  1959. $contentExt = $this->getConfig('content_ext');
  1960. $contentExtLength = strlen($contentExt);
  1961. if (substr($path, -$contentExtLength) !== $contentExt) {
  1962. return null;
  1963. }
  1964. return substr($path, $contentDirLength, -$contentExtLength) ?: null;
  1965. }
  1966. /**
  1967. * Returns the URL of the themes folder of this Pico instance
  1968. *
  1969. * We assume that the themes folder is a arbitrary deep sub folder of the
  1970. * script's base path (i.e. the directory {@path "index.php"} is in resp.
  1971. * the `httpdocs` directory). Usually the script's base path is identical
  1972. * to {@see Pico::$rootDir}, but this may aberrate when Pico got installed
  1973. * as a composer dependency. However, ultimately it allows us to use
  1974. * {@see Pico::getBaseUrl()} as origin of the theme URL. Otherwise Pico
  1975. * falls back to the basename of {@see Pico::$themesDir} (i.e. assuming
  1976. * that `Pico::$themesDir` is `foo/bar/baz`, the base URL of the themes
  1977. * folder will be `baz/`; this ensures BC to Pico < 2.0). Pico's base URL
  1978. * always gets prepended appropriately.
  1979. *
  1980. * @return string the URL of the themes folder
  1981. */
  1982. public function getBaseThemeUrl()
  1983. {
  1984. $themeUrl = $this->getConfig('theme_url');
  1985. if ($themeUrl) {
  1986. return $themeUrl;
  1987. }
  1988. if (isset($_SERVER['SCRIPT_FILENAME']) && ($_SERVER['SCRIPT_FILENAME'] !== 'index.php')) {
  1989. $basePath = dirname($_SERVER['SCRIPT_FILENAME']);
  1990. $basePath = !in_array($basePath, array('.', '/', '\\'), true) ? $basePath . '/' : '/';
  1991. $basePathLength = strlen($basePath);
  1992. if (substr($this->getThemesDir(), 0, $basePathLength) === $basePath) {
  1993. $this->config['theme_url'] = $this->getBaseUrl() . substr($this->getThemesDir(), $basePathLength);
  1994. return $this->config['theme_url'];
  1995. }
  1996. }
  1997. $this->config['theme_url'] = $this->getBaseUrl() . basename($this->getThemesDir()) . '/';
  1998. return $this->config['theme_url'];
  1999. }
  2000. /**
  2001. * Filters a URL GET parameter with a specified filter
  2002. *
  2003. * This method is just an alias for {@see Pico::filterVariable()}, see
  2004. * {@see Pico::filterVariable()} for a detailed description. It can be
  2005. * used in Twig templates by calling the `url_param` function.
  2006. *
  2007. * @see Pico::filterVariable()
  2008. *
  2009. * @param string $name name of the URL GET parameter
  2010. * to filter
  2011. * @param int|string $filter the filter to apply
  2012. * @param mixed|array $options either a associative options
  2013. * array to be used by the filter or a scalar default value
  2014. * @param int|string|int[]|string[] $flags flags and flag strings to be
  2015. * used by the filter
  2016. *
  2017. * @return mixed either the filtered data, FALSE if the filter fails, or
  2018. * NULL if the URL GET parameter doesn't exist and no default value is
  2019. * given
  2020. */
  2021. public function getUrlParameter($name, $filter = '', $options = null, $flags = null)
  2022. {
  2023. $variable = (isset($_GET[$name]) && is_scalar($_GET[$name])) ? $_GET[$name] : null;
  2024. return $this->filterVariable($variable, $filter, $options, $flags);
  2025. }
  2026. /**
  2027. * Filters a HTTP POST parameter with a specified filter
  2028. *
  2029. * This method is just an alias for {@see Pico::filterVariable()}, see
  2030. * {@see Pico::filterVariable()} for a detailed description. It can be
  2031. * used in Twig templates by calling the `form_param` function.
  2032. *
  2033. * @see Pico::filterVariable()
  2034. *
  2035. * @param string $name name of the HTTP POST
  2036. * parameter to filter
  2037. * @param int|string $filter the filter to apply
  2038. * @param mixed|array $options either a associative options
  2039. * array to be used by the filter or a scalar default value
  2040. * @param int|string|int[]|string[] $flags flags and flag strings to be
  2041. * used by the filter
  2042. *
  2043. * @return mixed either the filtered data, FALSE if the filter fails, or
  2044. * NULL if the HTTP POST parameter doesn't exist and no default value
  2045. * is given
  2046. */
  2047. public function getFormParameter($name, $filter = '', $options = null, $flags = null)
  2048. {
  2049. $variable = (isset($_POST[$name]) && is_scalar($_POST[$name])) ? $_POST[$name] : null;
  2050. return $this->filterVariable($variable, $filter, $options, $flags);
  2051. }
  2052. /**
  2053. * Filters a variable with a specified filter
  2054. *
  2055. * This method basically wraps around PHP's `filter_var()` function. It
  2056. * filters data by either validating or sanitizing it. This is especially
  2057. * useful when the data source contains unknown (or foreign) data, like
  2058. * user supplied input. Validation is used to validate or check if the data
  2059. * meets certain qualifications, but will not change the data itself.
  2060. * Sanitization will sanitize the data, so it may alter it by removing
  2061. * undesired characters. It doesn't actually validate the data! The
  2062. * behaviour of most filters can optionally be tweaked by flags.
  2063. *
  2064. * Heads up! Input validation is hard! Always validate your input data the
  2065. * most paranoid way you can imagine. Always prefer validation filters over
  2066. * sanitization filters; be very careful with sanitization filters, you
  2067. * might create cross-site scripting vulnerabilities!
  2068. *
  2069. * @see https://secure.php.net/manual/en/function.filter-var.php
  2070. * PHP's `filter_var()` function
  2071. * @see https://secure.php.net/manual/en/filter.filters.validate.php
  2072. * Validate filters
  2073. * @see https://secure.php.net/manual/en/filter.filters.sanitize.php
  2074. * Sanitize filters
  2075. *
  2076. * @param mixed $variable value to filter
  2077. * @param int|string $filter ID (int) or name (string) of
  2078. * the filter to apply; if omitted, the method will return FALSE
  2079. * @param mixed|array $options either a associative array
  2080. * of options to be used by the filter (e.g. `array('default' => 42)`),
  2081. * or a scalar default value that will be returned when the passed
  2082. * value is NULL (optional)
  2083. * @param int|string|int[]|string[] $flags either a bitwise disjunction
  2084. * of flags or a string with the significant part of a flag constant
  2085. * (the constant name is the result of "FILTER_FLAG_" and the given
  2086. * string in ASCII-only uppercase); you may also pass an array of flags
  2087. * and flag strings (optional)
  2088. *
  2089. * @return mixed with a validation filter, the method either returns the
  2090. * validated value or, provided that the value wasn't valid, the given
  2091. * default value or FALSE; with a sanitization filter, the method
  2092. * returns the sanitized value; if no value (i.e. NULL) was given, the
  2093. * method always returns either the provided default value or NULL
  2094. */
  2095. protected function filterVariable($variable, $filter = '', $options = null, $flags = null)
  2096. {
  2097. $defaultValue = null;
  2098. if (is_array($options)) {
  2099. $defaultValue = isset($options['default']) ? $options['default'] : null;
  2100. } elseif ($options !== null) {
  2101. $defaultValue = $options;
  2102. $options = array('default' => $defaultValue);
  2103. }
  2104. if ($variable === null) {
  2105. return $defaultValue;
  2106. }
  2107. $filter = $filter ? (is_string($filter) ? filter_id($filter) : (int) $filter) : false;
  2108. if (!$filter) {
  2109. return false;
  2110. }
  2111. $filterOptions = array('options' => $options, 'flags' => 0);
  2112. foreach ((array) $flags as $flag) {
  2113. if (is_numeric($flag)) {
  2114. $filterOptions['flags'] |= (int) $flag;
  2115. } elseif (is_string($flag)) {
  2116. $flag = strtoupper(preg_replace('/[^a-zA-Z0-9_]/', '', $flag));
  2117. if (($flag === 'NULL_ON_FAILURE') && ($filter === FILTER_VALIDATE_BOOLEAN)) {
  2118. $filterOptions['flags'] |= FILTER_NULL_ON_FAILURE;
  2119. } else {
  2120. $filterOptions['flags'] |= (int) constant('FILTER_FLAG_' . $flag);
  2121. }
  2122. }
  2123. }
  2124. return filter_var($variable, $filter, $filterOptions);
  2125. }
  2126. /**
  2127. * Recursively walks through a directory and returns all containing files
  2128. * matching the specified file extension
  2129. *
  2130. * @param string $directory start directory
  2131. * @param string $fileExtension return files with the given file extension
  2132. * only (optional)
  2133. * @param int $order specify whether and how files should be
  2134. * sorted; use Pico::SORT_ASC for a alphabetical ascending order (this
  2135. * is the default behaviour), Pico::SORT_DESC for a descending order
  2136. * or Pico::SORT_NONE to leave the result unsorted
  2137. *
  2138. * @return array list of found files
  2139. */
  2140. public function getFiles($directory, $fileExtension = '', $order = self::SORT_ASC)
  2141. {
  2142. $directory = rtrim($directory, '/');
  2143. $result = array();
  2144. // scandir() reads files in alphabetical order
  2145. $files = scandir($directory, $order);
  2146. $fileExtensionLength = strlen($fileExtension);
  2147. if ($files !== false) {
  2148. foreach ($files as $file) {
  2149. // exclude hidden files/dirs starting with a .; this also excludes the special dirs . and ..
  2150. // exclude files ending with a ~ (vim/nano backup) or # (emacs backup)
  2151. if (($file[0] === '.') || in_array(substr($file, -1), array('~', '#'), true)) {
  2152. continue;
  2153. }
  2154. if (is_dir($directory . '/' . $file)) {
  2155. // get files recursively
  2156. $result = array_merge($result, $this->getFiles($directory . '/' . $file, $fileExtension, $order));
  2157. } elseif (!$fileExtension || (substr($file, -$fileExtensionLength) === $fileExtension)) {
  2158. $result[] = $directory . '/' . $file;
  2159. }
  2160. }
  2161. }
  2162. return $result;
  2163. }
  2164. /**
  2165. * Returns all files in a directory matching a libc glob() pattern
  2166. *
  2167. * @see https://secure.php.net/manual/en/function.glob.php
  2168. * PHP's glob() function
  2169. *
  2170. * @param string $pattern the pattern to search for; see PHP's glob()
  2171. * function for details
  2172. * @param int $order specify whether and how files should be sorted;
  2173. * use Pico::SORT_ASC for a alphabetical ascending order (this is the
  2174. * default behaviour), Pico::SORT_DESC for a descending order or
  2175. * Pico::SORT_NONE to leave the result unsorted
  2176. *
  2177. * @return array list of found files
  2178. */
  2179. public function getFilesGlob($pattern, $order = self::SORT_ASC)
  2180. {
  2181. $result = array();
  2182. $sortFlag = ($order === self::SORT_NONE) ? GLOB_NOSORT : 0;
  2183. $files = glob($pattern, GLOB_MARK | $sortFlag);
  2184. if ($files) {
  2185. foreach ($files as $file) {
  2186. // exclude dirs and files ending with a ~ (vim/nano backup) or # (emacs backup)
  2187. if (in_array(substr($file, -1), array('/', '~', '#'), true)) {
  2188. continue;
  2189. }
  2190. $result[] = $file;
  2191. }
  2192. }
  2193. return ($order === self::SORT_DESC) ? array_reverse($result) : $result;
  2194. }
  2195. /**
  2196. * Makes a relative path absolute to Pico's root dir
  2197. *
  2198. * This method also guarantees a trailing slash.
  2199. *
  2200. * @param string $path relative or absolute path
  2201. * @param string $basePath treat relative paths relative to the given path;
  2202. * defaults to Pico::$rootDir
  2203. *
  2204. * @return string absolute path
  2205. */
  2206. public function getAbsolutePath($path, $basePath = null)
  2207. {
  2208. if ($basePath === null) {
  2209. $basePath = $this->getRootDir();
  2210. }
  2211. if (DIRECTORY_SEPARATOR === '\\') {
  2212. if (preg_match('/^(?>[a-zA-Z]:\\\\|\\\\\\\\)/', $path) !== 1) {
  2213. $path = $basePath . $path;
  2214. }
  2215. } else {
  2216. if ($path[0] !== '/') {
  2217. $path = $basePath . $path;
  2218. }
  2219. }
  2220. return rtrim($path, '/\\') . '/';
  2221. }
  2222. /**
  2223. * Normalizes a path by taking care of '', '.' and '..' parts
  2224. *
  2225. * @param string $path path to normalize
  2226. * @param bool $allowsAbsolutePath whether absolute paths are allowed
  2227. * @param bool $endSlash whether to add a trailing slash to the
  2228. * normalized path or not (defaults to TRUE)
  2229. *
  2230. * @return string normalized path
  2231. *
  2232. * @throws UnexpectedValueException thrown when a absolute path is passed
  2233. * although absolute paths aren't allowed
  2234. */
  2235. public function getNormalizedPath($path, $allowsAbsolutePath = false, $endSlash = true)
  2236. {
  2237. $absolutePath = '';
  2238. if (DIRECTORY_SEPARATOR === '\\') {
  2239. if (preg_match('/^(?>[a-zA-Z]:\\\\|\\\\\\\\)/', $path, $pathMatches) === 1) {
  2240. $absolutePath = $pathMatches[0];
  2241. $path = substr($path, strlen($absolutePath));
  2242. }
  2243. } else {
  2244. if ($path[0] === '/') {
  2245. $absolutePath = '/';
  2246. $path = substr($path, 1);
  2247. }
  2248. }
  2249. if ($absolutePath && !$allowsAbsolutePath) {
  2250. throw new UnexpectedValueException(
  2251. 'Argument 1 passed to ' . __METHOD__ . ' must be a relative path, absolute path "' . $path . '" given'
  2252. );
  2253. }
  2254. $path = str_replace('\\', '/', $path);
  2255. $pathParts = explode('/', $path);
  2256. $resultParts = array();
  2257. foreach ($pathParts as $pathPart) {
  2258. if (($pathPart === '') || ($pathPart === '.')) {
  2259. continue;
  2260. } elseif ($pathPart === '..') {
  2261. array_pop($resultParts);
  2262. continue;
  2263. }
  2264. $resultParts[] = $pathPart;
  2265. }
  2266. if (!$resultParts) {
  2267. return $absolutePath ?: '/';
  2268. }
  2269. return $absolutePath . implode('/', $resultParts) . ($endSlash ? '/' : '');
  2270. }
  2271. /**
  2272. * Triggers events on plugins using the current API version
  2273. *
  2274. * Plugins using older API versions are handled by {@see PicoDeprecated}.
  2275. * Please note that {@see PicoDeprecated} also triggers custom events on
  2276. * plugins using older API versions, thus you can safely use this method
  2277. * to trigger custom events on all loaded plugins, no matter what API
  2278. * version - the event will be triggered in any case.
  2279. *
  2280. * You MUST NOT trigger events of Pico's core with a plugin!
  2281. *
  2282. * @see PicoPluginInterface
  2283. * @see AbstractPicoPlugin
  2284. * @see DummyPlugin
  2285. *
  2286. * @param string $eventName name of the event to trigger
  2287. * @param array $params optional parameters to pass
  2288. *
  2289. * @return void
  2290. */
  2291. public function triggerEvent($eventName, array $params = array())
  2292. {
  2293. foreach ($this->nativePlugins as $plugin) {
  2294. $plugin->handleEvent($eventName, $params);
  2295. }
  2296. }
  2297. }