pico.php 10 KB

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