pico.php 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  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. foreach ($headers as $field => $regex){
  141. if (preg_match('/^[ \t\/*#@]*' . preg_quote($regex, '/') . ':(.*)$/mi', $content, $match) && $match[1]){
  142. $headers[ $field ] = trim(preg_replace("/\s*(?:\*\/|\?>).*/", '', $match[1]));
  143. } else {
  144. $headers[ $field ] = '';
  145. }
  146. }
  147. if($headers['date']) $headers['date_formatted'] = date($config['date_format'], strtotime($headers['date']));
  148. return $headers;
  149. }
  150. /**
  151. * Loads the config
  152. *
  153. * @return array $config an array of config values
  154. */
  155. private function get_config()
  156. {
  157. if(!file_exists(ROOT_DIR .'config.php')) return array();
  158. global $config;
  159. require_once(ROOT_DIR .'config.php');
  160. $defaults = array(
  161. 'site_title' => 'Pico',
  162. 'base_url' => $this->base_url(),
  163. 'theme' => 'default',
  164. 'date_format' => 'jS M Y',
  165. 'twig_config' => array('cache' => false, 'autoescape' => false, 'debug' => false),
  166. 'pages_order_by' => 'alpha',
  167. 'pages_order' => 'asc',
  168. 'excerpt_length' => 50
  169. );
  170. if(is_array($config)) $config = array_merge($defaults, $config);
  171. else $config = $defaults;
  172. return $config;
  173. }
  174. /**
  175. * Get a list of pages
  176. *
  177. * @param string $base_url the base URL of the site
  178. * @param string $order_by order by "alpha" or "date"
  179. * @param string $order order "asc" or "desc"
  180. * @return array $sorted_pages an array of pages
  181. */
  182. private function get_pages($base_url, $order_by = 'alpha', $order = 'asc', $excerpt_length = 50)
  183. {
  184. global $config;
  185. $pages = $this->get_files(CONTENT_DIR, CONTENT_EXT);
  186. $sorted_pages = array();
  187. $date_id = 0;
  188. foreach($pages as $key=>$page){
  189. // Skip 404
  190. if(basename($page) == '404'. CONTENT_EXT){
  191. unset($pages[$key]);
  192. continue;
  193. }
  194. // Get title and format $page
  195. $page_content = file_get_contents($page);
  196. $page_meta = $this->read_file_meta($page_content);
  197. $page_content = $this->parse_content($page_content);
  198. $url = str_replace(CONTENT_DIR, $base_url .'/', $page);
  199. $url = str_replace('index'. CONTENT_EXT, '', $url);
  200. $url = str_replace(CONTENT_EXT, '', $url);
  201. $data = array(
  202. 'title' => $page_meta['title'],
  203. 'url' => $url,
  204. 'author' => $page_meta['author'],
  205. 'date' => $page_meta['date'],
  206. 'date_formatted' => date($config['date_format'], strtotime($page_meta['date'])),
  207. 'content' => $page_content,
  208. 'excerpt' => $this->limit_words(strip_tags($page_content), $excerpt_length)
  209. );
  210. if($order_by == 'date'){
  211. $sorted_pages[$page_meta['date'].$date_id] = $data;
  212. $date_id++;
  213. }
  214. else $sorted_pages[] = $data;
  215. }
  216. if($order == 'desc') krsort($sorted_pages);
  217. else ksort($sorted_pages);
  218. return $sorted_pages;
  219. }
  220. /**
  221. * Processes any hooks and runs them
  222. *
  223. * @param string $hook_id the ID of the hook
  224. * @param array $args optional arguments
  225. */
  226. private function run_hooks($hook_id, $args = array())
  227. {
  228. if(!empty($this->plugins)){
  229. foreach($this->plugins as $plugin){
  230. if(is_callable(array($plugin, $hook_id))){
  231. call_user_func_array(array($plugin, $hook_id), $args);
  232. }
  233. }
  234. }
  235. }
  236. /**
  237. * Helper function to work out the base URL
  238. *
  239. * @return string the base url
  240. */
  241. private function base_url()
  242. {
  243. global $config;
  244. if(isset($config['base_url']) && $config['base_url']) return $config['base_url'];
  245. $url = '';
  246. $request_url = (isset($_SERVER['REQUEST_URI'])) ? $_SERVER['REQUEST_URI'] : '';
  247. $script_url = (isset($_SERVER['PHP_SELF'])) ? $_SERVER['PHP_SELF'] : '';
  248. if($request_url != $script_url) $url = trim(preg_replace('/'. str_replace('/', '\/', str_replace('index.php', '', $script_url)) .'/', '', $request_url, 1), '/');
  249. $protocol = $this->get_protocol();
  250. return rtrim(str_replace($url, '', $protocol . "://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']), '/');
  251. }
  252. /**
  253. * Tries to guess the server protocol. Used in base_url()
  254. *
  255. * @return string the current protocol
  256. */
  257. private function get_protocol()
  258. {
  259. preg_match("|^HTTP[S]?|is",$_SERVER['SERVER_PROTOCOL'],$m);
  260. return strtolower($m[0]);
  261. }
  262. /**
  263. * Helper function to recusively get all files in a directory
  264. *
  265. * @param string $directory start directory
  266. * @param string $ext optional limit to file extensions
  267. * @return array the matched files
  268. */
  269. private function get_files($directory, $ext = '')
  270. {
  271. $array_items = array();
  272. if($handle = opendir($directory)){
  273. while(false !== ($file = readdir($handle))){
  274. if($file != "." && $file != ".."){
  275. if(is_dir($directory. "/" . $file)){
  276. $array_items = array_merge($array_items, $this->get_files($directory. "/" . $file, $ext));
  277. } else {
  278. $file = $directory . "/" . $file;
  279. if(!$ext || strstr($file, $ext)) $array_items[] = preg_replace("/\/\//si", "/", $file);
  280. }
  281. }
  282. }
  283. closedir($handle);
  284. }
  285. return $array_items;
  286. }
  287. /**
  288. * Helper function to limit the words in a string
  289. *
  290. * @param string $string the given string
  291. * @param int $word_limit the number of words to limit to
  292. * @return string the limited string
  293. */
  294. private function limit_words($string, $word_limit)
  295. {
  296. $words = explode(' ',$string);
  297. return trim(implode(' ', array_splice($words, 0, $word_limit))) .'...';
  298. }
  299. }
  300. ?>