pico.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. <?php
  2. /**
  3. * Pico
  4. *
  5. * @author Gilbert Pellegrom
  6. * @link http://picocms.org
  7. * @license http://opensource.org/licenses/MIT
  8. * @version 0.8
  9. */
  10. class Pico {
  11. private $config;
  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. $content = file_get_contents($file);
  42. } else {
  43. $this->run_hooks('before_404_load_content', array(&$file));
  44. $content = file_get_contents($settings['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((isset($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 = (isset($meta['template']) && $meta['template']) ? $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 Parsedown-extra
  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, 1); // Remove first comment (with meta)
  124. $content = str_replace('%base_url%', $this->base_url(), $content);
  125. $content = (new ParsedownExtra())->text($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. $config = $this->config;
  137. $headers = array(
  138. 'title' => 'Title',
  139. 'description' => 'Description',
  140. 'author' => 'Author',
  141. 'date' => 'Date',
  142. 'robots' => 'Robots',
  143. 'template' => 'Template'
  144. );
  145. // Add support for custom headers by hooking into the headers array
  146. $this->run_hooks('before_read_file_meta', array(&$headers));
  147. foreach ($headers as $field => $regex){
  148. if (preg_match('/^[ \t\/*#@]*' . preg_quote($regex, '/') . ':(.*)$/mi', $content, $match) && $match[1]){
  149. $headers[ $field ] = trim(preg_replace("/\s*(?:\*\/|\?>).*/", '', $match[1]));
  150. } else {
  151. $headers[ $field ] = '';
  152. }
  153. }
  154. if(isset($headers['date'])) $headers['date_formatted'] = utf8_encode(strftime($config['date_format'], strtotime($headers['date'])));
  155. return $headers;
  156. }
  157. /**
  158. * Loads the config
  159. *
  160. * @return array $config an array of config values
  161. */
  162. protected function get_config()
  163. {
  164. $this->config = @include_once(ROOT_DIR .'config.php');
  165. $defaults = array(
  166. 'site_title' => 'Pico',
  167. 'base_url' => $this->base_url(),
  168. 'theme' => 'default',
  169. 'date_format' => '%D %T',
  170. 'twig_config' => array('cache' => false, 'autoescape' => false, 'debug' => false),
  171. 'pages_order_by' => 'alpha',
  172. 'pages_order' => 'asc',
  173. 'excerpt_length' => 50,
  174. 'content_dir' => 'content-sample/',
  175. );
  176. if(is_array($this->config)) $this->config = array_merge($defaults, $this->config);
  177. else $this->config = $defaults;
  178. return $this->config;
  179. }
  180. /**
  181. * Get a list of pages
  182. *
  183. * @param string $base_url the base URL of the site
  184. * @param string $order_by order by "alpha" or "date"
  185. * @param string $order order "asc" or "desc"
  186. * @return array $sorted_pages an array of pages
  187. */
  188. protected function get_pages($base_url, $order_by = 'alpha', $order = 'asc', $excerpt_length = 50)
  189. {
  190. $config = $this->config;
  191. $pages = $this->get_files($config['content_dir'], CONTENT_EXT);
  192. $sorted_pages = array();
  193. $date_id = 0;
  194. foreach($pages as $key=>$page){
  195. // Skip 404
  196. if(basename($page) == '404'. CONTENT_EXT){
  197. unset($pages[$key]);
  198. continue;
  199. }
  200. // Ignore Emacs (and Nano) temp files
  201. if (in_array(substr($page, -1), array('~','#'))) {
  202. unset($pages[$key]);
  203. continue;
  204. }
  205. // Get title and format $page
  206. $page_content = file_get_contents($page);
  207. $page_meta = $this->read_file_meta($page_content);
  208. $page_content = $this->parse_content($page_content);
  209. $url = str_replace($config['content_dir'], $base_url .'/', $page);
  210. $url = str_replace('index'. CONTENT_EXT, '', $url);
  211. $url = str_replace(CONTENT_EXT, '', $url);
  212. $data = array(
  213. 'title' => isset($page_meta['title']) ? $page_meta['title'] : '',
  214. 'url' => $url,
  215. 'author' => isset($page_meta['author']) ? $page_meta['author'] : '',
  216. 'date' => isset($page_meta['date']) ? $page_meta['date'] : '',
  217. 'date_formatted' => isset($page_meta['date']) ? utf8_encode(strftime($config['date_format'], strtotime($page_meta['date']))) : '',
  218. 'content' => $page_content,
  219. 'excerpt' => $this->limit_words(strip_tags($page_content), $excerpt_length),
  220. //this addition allows the 'description' meta to be picked up in content areas... specifically to replace 'excerpt'
  221. 'description' => isset($page_meta['description']) ? $page_meta['description'] : '',
  222. );
  223. // Extend the data provided with each page by hooking into the data array
  224. $this->run_hooks('get_page_data', array(&$data, $page_meta));
  225. if($order_by == 'date' && isset($page_meta['date'])){
  226. $sorted_pages[$page_meta['date'].$date_id] = $data;
  227. $date_id++;
  228. }
  229. else $sorted_pages[$page] = $data;
  230. }
  231. if($order == 'desc') krsort($sorted_pages);
  232. else ksort($sorted_pages);
  233. return $sorted_pages;
  234. }
  235. /**
  236. * Processes any hooks and runs them
  237. *
  238. * @param string $hook_id the ID of the hook
  239. * @param array $args optional arguments
  240. */
  241. protected function run_hooks($hook_id, $args = array())
  242. {
  243. if(!empty($this->plugins)){
  244. foreach($this->plugins as $plugin){
  245. if(is_callable(array($plugin, $hook_id))){
  246. call_user_func_array(array($plugin, $hook_id), $args);
  247. }
  248. }
  249. }
  250. }
  251. /**
  252. * Helper function to work out the base URL
  253. *
  254. * @return string the base url
  255. */
  256. protected function base_url()
  257. {
  258. $config = $this->config;
  259. if(isset($config['base_url']) && $config['base_url']) return $config['base_url'];
  260. $url = '';
  261. $request_url = (isset($_SERVER['REQUEST_URI'])) ? $_SERVER['REQUEST_URI'] : '';
  262. $script_url = (isset($_SERVER['PHP_SELF'])) ? $_SERVER['PHP_SELF'] : '';
  263. if($request_url != $script_url) $url = trim(preg_replace('/'. str_replace('/', '\/', str_replace('index.php', '', $script_url)) .'/', '', $request_url, 1), '/');
  264. $protocol = $this->get_protocol();
  265. return rtrim(str_replace($url, '', $protocol . "://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']), '/');
  266. }
  267. /**
  268. * Tries to guess the server protocol. Used in base_url()
  269. *
  270. * @return string the current protocol
  271. */
  272. protected function get_protocol()
  273. {
  274. $protocol = 'http';
  275. if(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' && $_SERVER['HTTPS'] != ''){
  276. $protocol = 'https';
  277. }
  278. return $protocol;
  279. }
  280. /**
  281. * Helper function to recusively get all files in a directory
  282. *
  283. * @param string $directory start directory
  284. * @param string $ext optional limit to file extensions
  285. * @return array the matched files
  286. */
  287. protected function get_files($directory, $ext = '')
  288. {
  289. $array_items = array();
  290. if($handle = opendir($directory)){
  291. while(false !== ($file = readdir($handle))){
  292. if(in_array(substr($file, -1), array('~', '#'))){
  293. continue;
  294. }
  295. if(preg_match("/^(^\.)/", $file) === 0){
  296. if(is_dir($directory. "/" . $file)){
  297. $array_items = array_merge($array_items, $this->get_files($directory. "/" . $file, $ext));
  298. } else {
  299. $file = $directory . "/" . $file;
  300. if(!$ext || strstr($file, $ext)) $array_items[] = preg_replace("/\/\//si", "/", $file);
  301. }
  302. }
  303. }
  304. closedir($handle);
  305. }
  306. return $array_items;
  307. }
  308. /**
  309. * Helper function to limit the words in a string
  310. *
  311. * @param string $string the given string
  312. * @param int $word_limit the number of words to limit to
  313. * @return string the limited string
  314. */
  315. protected function limit_words($string, $word_limit)
  316. {
  317. $words = explode(' ',$string);
  318. $excerpt = trim(implode(' ', array_splice($words, 0, $word_limit)));
  319. if(count($words) > $word_limit) $excerpt .= '&hellip;';
  320. return $excerpt;
  321. }
  322. }