pico.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. <?php
  2. use \Michelf\MarkdownExtra;
  3. /**
  4. * Pico
  5. *
  6. * @author Gilbert Pellegrom
  7. * @link http://pico.dev7studios.com
  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 = CONTENT_DIR . $url;
  35. else $file = CONTENT_DIR .'index';
  36. // Load the file
  37. if(is_dir($file)) $file = 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. $content = file_get_contents($file);
  42. } else {
  43. $this->run_hooks('before_404_load_content', array(&$file));
  44. $content = file_get_contents(CONTENT_DIR .'404'. CONTENT_EXT);
  45. header($_SERVER['SERVER_PROTOCOL'].' 404 Not Found');
  46. $this->run_hooks('after_404_load_content', array(&$file, &$content));
  47. }
  48. $this->run_hooks('after_load_content', array(&$file, &$content));
  49. $meta = $this->read_file_meta($content);
  50. $this->run_hooks('file_meta', array(&$meta));
  51. $this->run_hooks('before_parse_content', array(&$content));
  52. $content = $this->parse_content($content);
  53. $this->run_hooks('after_parse_content', array(&$content));
  54. $this->run_hooks('content_parsed', array(&$content)); // Depreciated @ v0.8
  55. // Get all the pages
  56. $pages = $this->get_pages($settings['base_url'], $settings['pages_order_by'], $settings['pages_order'], $settings['excerpt_length']);
  57. $prev_page = array();
  58. $current_page = array();
  59. $next_page = array();
  60. while($current_page = current($pages)){
  61. if($meta->Title && ($meta->Title == $current_page['title'])) {
  62. break;
  63. }
  64. next($pages);
  65. }
  66. $prev_page = next($pages);
  67. prev($pages);
  68. $next_page = prev($pages);
  69. $this->run_hooks('get_pages', array(&$pages, &$current_page, &$prev_page, &$next_page));
  70. // Load the theme
  71. $this->run_hooks('before_twig_register');
  72. Twig_Autoloader::register();
  73. $loader = new Twig_Loader_Filesystem(THEMES_DIR . $settings['theme']);
  74. $twig = new Twig_Environment($loader, $settings['twig_config']);
  75. $twig->addExtension(new Twig_Extension_Debug());
  76. $twig_vars = array(
  77. 'config' => $settings,
  78. 'base_dir' => rtrim(ROOT_DIR, '/'),
  79. 'base_url' => $settings['base_url'],
  80. 'theme_dir' => THEMES_DIR . $settings['theme'],
  81. 'theme_url' => $settings['base_url'] .'/'. basename(THEMES_DIR) .'/'. $settings['theme'],
  82. 'site_title' => $settings['site_title'],
  83. 'meta' => $meta,
  84. 'content' => $content,
  85. 'pages' => $pages,
  86. 'prev_page' => $prev_page,
  87. 'current_page' => $current_page,
  88. 'next_page' => $next_page,
  89. 'is_front_page' => $url ? false : true,
  90. );
  91. $template = ($meta->Template !== null) ? $meta->Template : 'index';
  92. $this->run_hooks('before_render', array(&$twig_vars, &$twig, &$template));
  93. $output = $twig->render($template .'.html', $twig_vars);
  94. $this->run_hooks('after_render', array(&$output));
  95. echo $output;
  96. }
  97. /**
  98. * Load any plugins
  99. */
  100. protected function load_plugins()
  101. {
  102. $this->plugins = array();
  103. $plugins = $this->get_files(PLUGINS_DIR, '.php');
  104. if(!empty($plugins)){
  105. foreach($plugins as $plugin){
  106. include_once($plugin);
  107. $plugin_name = preg_replace("/\\.[^.\\s]{3}$/", '', basename($plugin));
  108. if(class_exists($plugin_name)){
  109. $obj = new $plugin_name;
  110. $this->plugins[] = $obj;
  111. }
  112. }
  113. }
  114. }
  115. /**
  116. * Parses the content using Markdown
  117. *
  118. * @param string $content the raw txt content
  119. * @return string $content the Markdown formatted content
  120. */
  121. protected function parse_content($content)
  122. {
  123. $content = preg_replace('#/\*.+?\*/#s', '', $content); // Remove comments and meta
  124. $content = str_replace('%base_url%', $this->base_url(), $content);
  125. $content = MarkdownExtra::defaultTransform($content);
  126. return $content;
  127. }
  128. /**
  129. * Parses the file meta from the txt file header
  130. *
  131. * @param string $content the raw txt content
  132. * @return array $headers an array of meta values
  133. */
  134. protected function read_file_meta($content)
  135. {
  136. return new \Pico\Model\Meta($content);
  137. }
  138. /**
  139. * Loads the config
  140. *
  141. * @return array $config an array of config values
  142. */
  143. protected function get_config()
  144. {
  145. global $config;
  146. @include_once(ROOT_DIR .'config.php');
  147. $defaults = array(
  148. 'site_title' => 'Pico',
  149. 'base_url' => $this->base_url(),
  150. 'theme' => 'default',
  151. 'date_format' => 'jS M Y',
  152. 'twig_config' => array('cache' => false, 'autoescape' => false, 'debug' => false),
  153. 'pages_order_by' => 'alpha',
  154. 'pages_order' => 'asc',
  155. 'excerpt_length' => 50
  156. );
  157. if(is_array($config)) $config = array_merge($defaults, $config);
  158. else $config = $defaults;
  159. return $config;
  160. }
  161. /**
  162. * Get a list of pages
  163. *
  164. * @param string $base_url the base URL of the site
  165. * @param string $order_by order by "alpha" or "date"
  166. * @param string $order order "asc" or "desc"
  167. * @return array $sorted_pages an array of pages
  168. */
  169. protected function get_pages($base_url, $order_by = 'alpha', $order = 'asc', $excerpt_length = 50)
  170. {
  171. global $config;
  172. $pages = $this->get_files(CONTENT_DIR, CONTENT_EXT);
  173. $sorted_pages = array();
  174. $date_id = 0;
  175. foreach($pages as $key=>$page){
  176. // Skip 404
  177. if(basename($page) == '404'. CONTENT_EXT){
  178. unset($pages[$key]);
  179. continue;
  180. }
  181. // Ignore Emacs (and Nano) temp files
  182. if (in_array(substr($page, -1), array('~','#'))) {
  183. unset($pages[$key]);
  184. continue;
  185. }
  186. // Get title and format $page
  187. $page_content = file_get_contents($page);
  188. $page_meta = $this->read_file_meta($page_content);
  189. $page_content = $this->parse_content($page_content);
  190. $url = str_replace(CONTENT_DIR, $base_url .'/', $page);
  191. $url = str_replace('index'. CONTENT_EXT, '', $url);
  192. $url = str_replace(CONTENT_EXT, '', $url);
  193. $data = array(
  194. 'title' => ($page_meta->Title !== null) ? $page_meta->Title : '',
  195. 'url' => $url,
  196. 'author' => ($page_meta->Author !== null) ? $page_meta>Author : '',
  197. 'date' => ($page_meta->Date) ? $page_meta->Date : '',
  198. 'date_formatted' => ($page_meta->Date) ? date($config['date_format'], strtotime($page_meta->Date)) : '',
  199. 'content' => $page_content,
  200. 'excerpt' => $this->limit_words(strip_tags($page_content), $excerpt_length)
  201. );
  202. // Extend the data provided with each page by hooking into the data array
  203. $this->run_hooks('get_page_data', array(&$data, $page_meta));
  204. if($order_by == 'date' && $page_meta->Date !== null){
  205. $sorted_pages[$page_meta->Date.$date_id] = $data;
  206. $date_id++;
  207. }
  208. else $sorted_pages[] = $data;
  209. }
  210. if($order == 'desc') krsort($sorted_pages);
  211. else ksort($sorted_pages);
  212. return $sorted_pages;
  213. }
  214. /**
  215. * Processes any hooks and runs them
  216. *
  217. * @param string $hook_id the ID of the hook
  218. * @param array $args optional arguments
  219. */
  220. protected function run_hooks($hook_id, $args = array())
  221. {
  222. if(!empty($this->plugins)){
  223. foreach($this->plugins as $plugin){
  224. if(is_callable(array($plugin, $hook_id))){
  225. call_user_func_array(array($plugin, $hook_id), $args);
  226. }
  227. }
  228. }
  229. }
  230. /**
  231. * Helper function to work out the base URL
  232. *
  233. * @return string the base url
  234. */
  235. protected function base_url()
  236. {
  237. global $config;
  238. if(isset($config['base_url']) && $config['base_url']) return $config['base_url'];
  239. $url = '';
  240. $request_url = (isset($_SERVER['REQUEST_URI'])) ? $_SERVER['REQUEST_URI'] : '';
  241. $script_url = (isset($_SERVER['PHP_SELF'])) ? $_SERVER['PHP_SELF'] : '';
  242. if($request_url != $script_url) $url = trim(preg_replace('/'. str_replace('/', '\/', str_replace('index.php', '', $script_url)) .'/', '', $request_url, 1), '/');
  243. $protocol = $this->get_protocol();
  244. return rtrim(str_replace($url, '', $protocol . "://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']), '/');
  245. }
  246. /**
  247. * Tries to guess the server protocol. Used in base_url()
  248. *
  249. * @return string the current protocol
  250. */
  251. protected function get_protocol()
  252. {
  253. $protocol = 'http';
  254. if(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off'){
  255. $protocol = 'https';
  256. }
  257. return $protocol;
  258. }
  259. /**
  260. * Helper function to recusively get all files in a directory
  261. *
  262. * @param string $directory start directory
  263. * @param string $ext optional limit to file extensions
  264. * @return array the matched files
  265. */
  266. protected function get_files($directory, $ext = '')
  267. {
  268. $array_items = array();
  269. if($handle = opendir($directory)){
  270. while(false !== ($file = readdir($handle))){
  271. if(preg_match("/^(^\.)/", $file) === 0){
  272. if(is_dir($directory. "/" . $file)){
  273. $array_items = array_merge($array_items, $this->get_files($directory. "/" . $file, $ext));
  274. } else {
  275. $file = $directory . "/" . $file;
  276. if(!$ext || strstr($file, $ext)) $array_items[] = preg_replace("/\/\//si", "/", $file);
  277. }
  278. }
  279. }
  280. closedir($handle);
  281. }
  282. return $array_items;
  283. }
  284. /**
  285. * Helper function to limit the words in a string
  286. *
  287. * @param string $string the given string
  288. * @param int $word_limit the number of words to limit to
  289. * @return string the limited string
  290. */
  291. protected function limit_words($string, $word_limit)
  292. {
  293. $words = explode(' ',$string);
  294. $excerpt = trim(implode(' ', array_splice($words, 0, $word_limit)));
  295. if(count($words) > $word_limit) $excerpt .= '&hellip;';
  296. return $excerpt;
  297. }
  298. }