PageRenderTime 47ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/pico.php

https://gitlab.com/Blueprint-Marketing/Pico
PHP | 402 lines | 269 code | 49 blank | 84 comment | 51 complexity | 0cc3805f2509fa030ecadc6135d712ee MD5 | raw file
  1. <?php
  2. /**
  3. * Pico
  4. *
  5. * @author Gilbert Pellegrom
  6. * @link http://picocms.org
  7. * @license http://opensource.org/licenses/MIT
  8. * @version 0.8
  9. */
  10. class Pico
  11. {
  12. private $config;
  13. private $plugins;
  14. /**
  15. * The constructor carries out all the processing in Pico.
  16. * Does URL routing, Markdown processing and Twig processing.
  17. */
  18. public function __construct()
  19. {
  20. // Load plugins
  21. $this->load_plugins();
  22. $this->run_hooks('plugins_loaded');
  23. // Load the settings
  24. $settings = $this->get_config();
  25. $this->run_hooks('config_loaded', array(&$settings));
  26. // Get request url and script url
  27. $url = '';
  28. $request_url = (isset($_SERVER['REQUEST_URI'])) ? $_SERVER['REQUEST_URI'] : '';
  29. $script_url = (isset($_SERVER['PHP_SELF'])) ? $_SERVER['PHP_SELF'] : '';
  30. // Get our url path and trim the / of the left and the right
  31. if ($request_url != $script_url) {
  32. $url = trim(preg_replace('/' . str_replace('/', '\/', str_replace('index.php', '', $script_url)) . '/', '',
  33. $request_url, 1), '/');
  34. }
  35. $url = preg_replace('/\?.*/', '', $url); // Strip query string
  36. $this->run_hooks('request_url', array(&$url));
  37. // Get the file path
  38. if ($url) {
  39. $file = $settings['content_dir'] . $url;
  40. } else {
  41. $file = $settings['content_dir'] . 'index';
  42. }
  43. // Load the file
  44. if (is_dir($file)) {
  45. $file = $settings['content_dir'] . $url . '/index' . CONTENT_EXT;
  46. } else {
  47. $file .= CONTENT_EXT;
  48. }
  49. $this->run_hooks('before_load_content', array(&$file));
  50. if (file_exists($file)) {
  51. $content = file_get_contents($file);
  52. } else {
  53. $this->run_hooks('before_404_load_content', array(&$file));
  54. $content = file_get_contents($settings['content_dir'] . '404' . CONTENT_EXT);
  55. header($_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found');
  56. $this->run_hooks('after_404_load_content', array(&$file, &$content));
  57. }
  58. $this->run_hooks('after_load_content', array(&$file, &$content));
  59. $meta = $this->read_file_meta($content);
  60. $this->run_hooks('file_meta', array(&$meta));
  61. $this->run_hooks('before_parse_content', array(&$content));
  62. $content = $this->parse_content($content);
  63. $this->run_hooks('after_parse_content', array(&$content));
  64. $this->run_hooks('content_parsed', array(&$content)); // Depreciated @ v0.8
  65. // Get all the pages
  66. $pages = $this->get_pages($settings['base_url'], $settings['pages_order_by'], $settings['pages_order'],
  67. $settings['excerpt_length']);
  68. $prev_page = array();
  69. $current_page = array();
  70. $next_page = array();
  71. while ($current_page = current($pages)) {
  72. if ((isset($meta['title'])) && ($meta['title'] == $current_page['title'])) {
  73. break;
  74. }
  75. next($pages);
  76. }
  77. $prev_page = next($pages);
  78. prev($pages);
  79. $next_page = prev($pages);
  80. $this->run_hooks('get_pages', array(&$pages, &$current_page, &$prev_page, &$next_page));
  81. // Load the theme
  82. $this->run_hooks('before_twig_register');
  83. Twig_Autoloader::register();
  84. $loader = new Twig_Loader_Filesystem(THEMES_DIR . $settings['theme']);
  85. $twig = new Twig_Environment($loader, $settings['twig_config']);
  86. $twig->addExtension(new Twig_Extension_Debug());
  87. $twig_vars = array(
  88. 'config' => $settings,
  89. 'base_dir' => rtrim(ROOT_DIR, '/'),
  90. 'base_url' => $settings['base_url'],
  91. 'theme_dir' => THEMES_DIR . $settings['theme'],
  92. 'theme_url' => $settings['base_url'] . '/' . basename(THEMES_DIR) . '/' . $settings['theme'],
  93. 'site_title' => $settings['site_title'],
  94. 'meta' => $meta,
  95. 'content' => $content,
  96. 'pages' => $pages,
  97. 'prev_page' => $prev_page,
  98. 'current_page' => $current_page,
  99. 'next_page' => $next_page,
  100. 'is_front_page' => $url ? false : true,
  101. );
  102. $template = (isset($meta['template']) && $meta['template']) ? $meta['template'] : 'index';
  103. $this->run_hooks('before_render', array(&$twig_vars, &$twig, &$template));
  104. $output = $twig->render($template . '.html', $twig_vars);
  105. $this->run_hooks('after_render', array(&$output));
  106. echo $output;
  107. }
  108. /**
  109. * Load any plugins
  110. */
  111. protected function load_plugins()
  112. {
  113. $this->plugins = array();
  114. $plugins = $this->get_files(PLUGINS_DIR, '.php');
  115. if (!empty($plugins)) {
  116. foreach ($plugins as $plugin) {
  117. include_once($plugin);
  118. $plugin_name = preg_replace("/\\.[^.\\s]{3}$/", '', basename($plugin));
  119. if (class_exists($plugin_name)) {
  120. $obj = new $plugin_name;
  121. $this->plugins[] = $obj;
  122. }
  123. }
  124. }
  125. }
  126. /**
  127. * Parses the content using Parsedown-extra
  128. *
  129. * @param string $content the raw txt content
  130. * @return string $content the Markdown formatted content
  131. */
  132. protected function parse_content($content)
  133. {
  134. $content = preg_replace('#/\*.+?\*/#s', '', $content, 1); // Remove first comment (with meta)
  135. $content = str_replace('%base_url%', $this->base_url(), $content);
  136. $Parsedown = new ParsedownExtra();
  137. $content= $Parsedown->text($content);
  138. return $content;
  139. }
  140. /**
  141. * Parses the file meta from the txt file header
  142. *
  143. * @param string $content the raw txt content
  144. * @return array $headers an array of meta values
  145. */
  146. protected function read_file_meta($content)
  147. {
  148. $config = $this->config;
  149. $headers = array(
  150. 'title' => 'Title',
  151. 'description' => 'Description',
  152. 'author' => 'Author',
  153. 'date' => 'Date',
  154. 'robots' => 'Robots',
  155. 'template' => 'Template'
  156. );
  157. // Add support for custom headers by hooking into the headers array
  158. $this->run_hooks('before_read_file_meta', array(&$headers));
  159. foreach ($headers as $field => $regex) {
  160. if (preg_match('/^[ \t\/*#@]*' . preg_quote($regex, '/') . ':(.*)$/mi', $content, $match) && $match[1]) {
  161. $headers[$field] = trim(preg_replace("/\s*(?:\*\/|\?>).*/", '', $match[1]));
  162. } else {
  163. $headers[$field] = '';
  164. }
  165. }
  166. if (isset($headers['date'])) {
  167. $headers['date_formatted'] = utf8_encode(strftime($config['date_format'], strtotime($headers['date'])));
  168. }
  169. return $headers;
  170. }
  171. /**
  172. * Loads the config
  173. *
  174. * @return array $config an array of config values
  175. */
  176. protected function get_config()
  177. {
  178. $this->config = @include_once(ROOT_DIR . 'config.php');
  179. $defaults = array(
  180. 'site_title' => 'Pico',
  181. 'base_url' => $this->base_url(),
  182. 'theme' => 'default',
  183. 'date_format' => '%D %T',
  184. 'twig_config' => array('cache' => false, 'autoescape' => false, 'debug' => false),
  185. 'pages_order_by' => 'alpha',
  186. 'pages_order' => 'asc',
  187. 'excerpt_length' => 50,
  188. 'content_dir' => 'content-sample/',
  189. );
  190. if (is_array($this->config)) {
  191. $this->config = array_merge($defaults, $this->config);
  192. } else {
  193. $this->config = $defaults;
  194. }
  195. return $this->config;
  196. }
  197. /**
  198. * Get a list of pages
  199. *
  200. * @param string $base_url the base URL of the site
  201. * @param string $order_by order by "alpha" or "date"
  202. * @param string $order order "asc" or "desc"
  203. * @return array $sorted_pages an array of pages
  204. */
  205. protected function get_pages($base_url, $order_by = 'alpha', $order = 'asc', $excerpt_length = 50)
  206. {
  207. $config = $this->config;
  208. $pages = $this->get_files($config['content_dir'], CONTENT_EXT);
  209. $sorted_pages = array();
  210. $date_id = 0;
  211. foreach ($pages as $key => $page) {
  212. // Skip 404
  213. if (basename($page) == '404' . CONTENT_EXT) {
  214. unset($pages[$key]);
  215. continue;
  216. }
  217. // Ignore Emacs (and Nano) temp files
  218. if (in_array(substr($page, -1), array('~', '#'))) {
  219. unset($pages[$key]);
  220. continue;
  221. }
  222. // Get title and format $page
  223. $page_content = file_get_contents($page);
  224. $page_meta = $this->read_file_meta($page_content);
  225. $page_content = $this->parse_content($page_content);
  226. $url = str_replace($config['content_dir'], $base_url . '/', $page);
  227. $url = str_replace('index' . CONTENT_EXT, '', $url);
  228. $url = str_replace(CONTENT_EXT, '', $url);
  229. $data = array(
  230. 'title' => isset($page_meta['title']) ? $page_meta['title'] : '',
  231. 'url' => $url,
  232. 'author' => isset($page_meta['author']) ? $page_meta['author'] : '',
  233. 'date' => isset($page_meta['date']) ? $page_meta['date'] : '',
  234. 'date_formatted' => isset($page_meta['date']) ? utf8_encode(strftime($config['date_format'],
  235. strtotime($page_meta['date']))) : '',
  236. 'content' => $page_content,
  237. 'excerpt' => $this->limit_words(strip_tags($page_content), $excerpt_length),
  238. //this addition allows the 'description' meta to be picked up in content areas... specifically to replace 'excerpt'
  239. 'description' => isset($page_meta['description']) ? $page_meta['description'] : '',
  240. );
  241. // Extend the data provided with each page by hooking into the data array
  242. $this->run_hooks('get_page_data', array(&$data, $page_meta));
  243. if ($order_by == 'date' && isset($page_meta['date'])) {
  244. $sorted_pages[$page_meta['date'] . $date_id] = $data;
  245. $date_id++;
  246. } else {
  247. $sorted_pages[$page] = $data;
  248. }
  249. }
  250. if ($order == 'desc') {
  251. krsort($sorted_pages);
  252. } else {
  253. ksort($sorted_pages);
  254. }
  255. return $sorted_pages;
  256. }
  257. /**
  258. * Processes any hooks and runs them
  259. *
  260. * @param string $hook_id the ID of the hook
  261. * @param array $args optional arguments
  262. */
  263. protected function run_hooks($hook_id, $args = array())
  264. {
  265. if (!empty($this->plugins)) {
  266. foreach ($this->plugins as $plugin) {
  267. if (is_callable(array($plugin, $hook_id))) {
  268. call_user_func_array(array($plugin, $hook_id), $args);
  269. }
  270. }
  271. }
  272. }
  273. /**
  274. * Helper function to work out the base URL
  275. *
  276. * @return string the base url
  277. */
  278. protected function base_url()
  279. {
  280. $config = $this->config;
  281. if (isset($config['base_url']) && $config['base_url']) {
  282. return $config['base_url'];
  283. }
  284. $url = '';
  285. $request_url = (isset($_SERVER['REQUEST_URI'])) ? $_SERVER['REQUEST_URI'] : '';
  286. $script_url = (isset($_SERVER['PHP_SELF'])) ? $_SERVER['PHP_SELF'] : '';
  287. if ($request_url != $script_url) {
  288. $url = trim(preg_replace('/' . str_replace('/', '\/', str_replace('index.php', '', $script_url)) . '/', '',
  289. $request_url, 1), '/');
  290. }
  291. $protocol = $this->get_protocol();
  292. return rtrim(str_replace($url, '', $protocol . "://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']), '/');
  293. }
  294. /**
  295. * Tries to guess the server protocol. Used in base_url()
  296. *
  297. * @return string the current protocol
  298. */
  299. protected function get_protocol()
  300. {
  301. $protocol = 'http';
  302. if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' && $_SERVER['HTTPS'] != '') {
  303. $protocol = 'https';
  304. }
  305. return $protocol;
  306. }
  307. /**
  308. * Helper function to recusively get all files in a directory
  309. *
  310. * @param string $directory start directory
  311. * @param string $ext optional limit to file extensions
  312. * @return array the matched files
  313. */
  314. protected function get_files($directory, $ext = '')
  315. {
  316. $array_items = array();
  317. if ($handle = opendir($directory)) {
  318. while (false !== ($file = readdir($handle))) {
  319. if (in_array(substr($file, -1), array('~', '#'))) {
  320. continue;
  321. }
  322. if (preg_match("/^(^\.)/", $file) === 0) {
  323. if (is_dir($directory . "/" . $file)) {
  324. $array_items = array_merge($array_items, $this->get_files($directory . "/" . $file, $ext));
  325. } else {
  326. $file = $directory . "/" . $file;
  327. if (!$ext || strstr($file, $ext)) {
  328. $array_items[] = preg_replace("/\/\//si", "/", $file);
  329. }
  330. }
  331. }
  332. }
  333. closedir($handle);
  334. }
  335. return $array_items;
  336. }
  337. /**
  338. * Helper function to limit the words in a string
  339. *
  340. * @param string $string the given string
  341. * @param int $word_limit the number of words to limit to
  342. * @return string the limited string
  343. */
  344. protected function limit_words($string, $word_limit)
  345. {
  346. $words = explode(' ', $string);
  347. $excerpt = trim(implode(' ', array_splice($words, 0, $word_limit)));
  348. if (count($words) > $word_limit) {
  349. $excerpt .= '&hellip;';
  350. }
  351. return $excerpt;
  352. }
  353. }