pico.php 11 KB

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