pico.php 11 KB

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