PageRenderTime 835ms CodeModel.GetById 28ms RepoModel.GetById 2ms app.codeStats 0ms

/branches/coding-style/fp-plugins/prettyurls/plugin.prettyurls.php

https://bitbucket.org/alexandrul/flatpress
PHP | 599 lines | 347 code | 193 blank | 59 comment | 75 complexity | 9d2ec6026b4f20b11e52a910d36d8663 MD5 | raw file
Possible License(s): AGPL-1.0, GPL-2.0, MIT
  1. <?php
  2. /*
  3. Plugin Name: PrettyURLs
  4. Plugin URI: http://flatpress.nowherland.it/
  5. Description: Url prettifier (powered by htaccess)
  6. Author: NoWhereMan (E.Vacchi)
  7. Version: 3.0
  8. Author URI: http://www.nowhereland.it
  9. */
  10. /**
  11. * Place where the index is stored
  12. */
  13. define('PRETTYURLS_TITLES', true);
  14. define('PRETTYURLS_PATHINFO', true);
  15. define('PRETTYURLS_CACHE', CACHE_DIR . '%%prettyurls-index.tmp');
  16. define('PRETTYURLS_CATS', CACHE_DIR . '%%prettyurls-cats.tmp');
  17. /**
  18. * File existance check
  19. */
  20. # memo
  21. # register_plugin_setup('plugin_id', 'setup_func');
  22. function plugin_prettyurls_setup() {
  23. if (file_exists(ABS_PATH . '.htaccess'))
  24. return 1;
  25. if (!is_writable(ABS_PATH)) {
  26. return -2;
  27. }
  28. return 1;
  29. }
  30. class Plugin_PrettyURLs {
  31. var $index = array();
  32. var $status = 0;
  33. var $date_handled = false;
  34. var $categories = null;
  35. var $fp_params;
  36. function categories($force=true) {
  37. if ($this->categories)
  38. return;
  39. if ($force || !file_exists(PRETTYURLS_CATS)) {
  40. $d = entry_categories_get('defs');
  41. $list = array();
  42. foreach ($d as $k=>$v) {
  43. $list[$k] = sanitize_title($v);
  44. }
  45. io_write_file(PRETTYURLS_CATS, serialize($list));
  46. } else {
  47. $f = io_load_file(PRETTYURLS_CATS);
  48. $list = unserialize($f);
  49. }
  50. $this->categories = $list;
  51. }
  52. function md5($id, $title) {
  53. $date = date_from_id($id);
  54. return md5($date['y'].$date['m'].$date['d'].$title);
  55. }
  56. function permalink($str, $id) {
  57. global $fpdb, $post;
  58. if (PRETTYURLS_TITLES)
  59. $title = sanitize_title($post['subject']);
  60. else
  61. $title = $id;
  62. $date = date_from_id($id);
  63. // yeah, hackish, I know...
  64. return $this->baseurl . "20{$date['y']}/{$date['m']}/{$date['d']}/$title/";
  65. }
  66. function commentlink($str, $id) {
  67. $link = $this->permalink($str, $id);
  68. return $link . "comments/";
  69. }
  70. function feedlink($str, $type) {
  71. return $this->baseurl . "feed/{$type}/";
  72. }
  73. function commentsfeedlink($str, $type, $id) {
  74. $link = $this->commentlink($str, $id);
  75. return $link . "feed/{$type}/";
  76. }
  77. function staticlink($str, $id) {
  78. return $this->baseurl . "$id/";
  79. }
  80. function categorylink($str, $catid) {
  81. if (PRETTYURLS_TITLES) {
  82. if (@$this->categories[$catid])
  83. return $this->baseurl . "category/{$this->categories[$catid]}/";
  84. else return $str;
  85. } else {
  86. return $this->baseurl . "category/{$catid}/";
  87. }
  88. }
  89. function yearlink($str, $y) {
  90. return $this->baseurl . "20$y/";
  91. }
  92. function monthlink($str, $y, $m) {
  93. return $this->yearlink($str, $y) . "$m/";
  94. }
  95. function daylink($str, $y, $m, $d) {
  96. return $this->monthlink($str, $y, $m) . "$d/";
  97. }
  98. function cache_create() {
  99. $this->index = array();
  100. /*
  101. $o =& entry_init();
  102. $entries = $o->getList();
  103. */
  104. $o = new FPDB_Query(array('start'=>0,'count'=>-1,'fullparse'=>false), null);
  105. #foreach ($entries as $id => $contents) {
  106. while ($o->hasMore()) {
  107. list($id, $contents) = $o->getEntry();
  108. $date = date_from_id($id);
  109. echo $contents['subject'], "\n";
  110. $md5 = md5(sanitize_title($contents['subject']));
  111. $this->index[$date['y']][$date['m']][$date['d']][$md5] = $id;
  112. }
  113. #}
  114. $this->cache_save();
  115. io_write_file(PRETTYURLS_CACHE, 'dummy');
  116. }
  117. function handle_categories($matches) {
  118. if (!$this->categories)
  119. return;
  120. if (PRETTYURLS_TITLES) {
  121. if ($c = array_search($matches[1], $this->categories))
  122. $this->fp_params['cat'] = $c;
  123. } else {
  124. $this->fp_params['cat'] = $matches[1];
  125. }
  126. }
  127. /*
  128. named matches are not supported here
  129. */
  130. function handle_date($matches) {
  131. $this->fp_params['y'] = $matches[1];
  132. if (isset($matches[3])) $this->fp_params['m'] = $matches[3] ;
  133. if (isset($matches[5])) $this->fp_params['d'] = $matches[5];
  134. $this->date_handled = true;
  135. }
  136. function handle_static($matches) {
  137. $this->fp_params['page'] = $matches[1];
  138. $this->status = 2;
  139. }
  140. function handle_entry($matches) {
  141. if (PRETTYURLS_TITLES) {
  142. #isset($this->index[
  143. if ($this->cache_get($this->fp_params['y'],$this->fp_params['m'], $this->fp_params['d'], md5($matches[1]))) {
  144. $this->fp_params['entry'] = $this->index[$this->fp_params['y']][$this->fp_params['m']][$this->fp_params['d']][md5($matches[1])];
  145. } else {
  146. // a bit hackish: we make up a fake url when there is no match,
  147. // so that at the higher level the system will 404...
  148. $this->fp_params['entry'] = 'entry000000-000000';
  149. }
  150. } else {
  151. $this->fp_params['entry'] = $matches[1];
  152. }
  153. }
  154. function handle_page($matches) {
  155. $this->fp_params['paged'] = $matches[1];
  156. $this->status = 2;
  157. }
  158. function handle_comment($matches) {
  159. $this->fp_params['comments'] = true;
  160. }
  161. function handle_feed($matches) {
  162. $this->fp_params['feed'] = isset($matches[2])? $matches[2]:'rss2';
  163. }
  164. /*
  165. * here is where the real work is done.
  166. *
  167. * First we load the cache if exists;
  168. *
  169. * We check then if the GET request contains a 'title'
  170. * if so, we'll need date and time to construct the md5 sum
  171. * with which we index the cache array
  172. *
  173. * If that entry exists, we set $_GET['entry'] to that ID,
  174. * so that FlatPress can find it where it is expected
  175. *
  176. */
  177. function cache_init() {
  178. global $fp_params;
  179. $this->fp_params =& $fp_params;
  180. $this->baseurl = PRETTYURLS_PATHINFO? BLOG_BASEURL . 'index.php/' : BLOG_BASEURL;
  181. if (PRETTYURLS_TITLES) {
  182. #if ($f = io_load_file(PRETTYURLS_CACHE))
  183. $this->index = array(); #unserialize($f);
  184. if (!file_exists(PRETTYURLS_CACHE))
  185. $this->cache_create();
  186. $this->categories(false);
  187. }
  188. if (!defined('MOD_INDEX'))
  189. return;
  190. # this is not working if you reach flatpress via symlink
  191. # unless you don't edit manually defaults.php
  192. if (strpos($_SERVER['REQUEST_URI'], BLOG_ROOT)!==false) {
  193. $url = $_SERVER['REQUEST_URI'];
  194. $del = BLOG_ROOT;
  195. if (strpos($url, 'index.php')!==false)
  196. $del = $del . 'index.php/';
  197. $url = substr($url, strlen($del)-1);
  198. }
  199. // removes querystrings
  200. if (false !== $i = strpos($url, '?'))
  201. $url = substr($url, 0, $i);
  202. // removes anchors
  203. if (false !== $i = strpos($url, '#'))
  204. $url = substr($url, 0, $i);
  205. if (strrpos($url, '/') != (strlen($url)-1)) {
  206. $url .= '/';
  207. }
  208. if ($url=='/')
  209. return;
  210. //date
  211. $url = preg_replace_callback(
  212. '!^/[0-9]{2}(?P<y>[0-9]{2})(/(?P<m>[0-9]{2})(/(?P<d>[0-9]{2}))?)?!',
  213. array(&$this, 'handle_date'),
  214. $url
  215. );
  216. if (!$this->date_handled){
  217. // static page
  218. $url = preg_replace_callback('|^/([a-zA-Z0-9_-]+)/$|', array(&$this, 'handle_static'), $url);
  219. if ($this->status == 2)
  220. return $this->check_url($url);
  221. }
  222. $url = preg_replace_callback('{category/([^/]+)/}', array(&$this, 'handle_categories'), $url);
  223. $url = preg_replace_callback('|page/([0-9]+)/$|', array(&$this, 'handle_page'), $url);
  224. if ($this->status == 2)
  225. return $this->check_url($url);
  226. if ($this->date_handled){
  227. $url = preg_replace_callback('|^/([^/]+)|', array(&$this, 'handle_entry'), $url);
  228. // if status = 2
  229. /*
  230. utils_error(404);
  231. */
  232. $url = preg_replace_callback('|^/comments|', array(&$this, 'handle_comment'), $url);
  233. }
  234. $url = preg_replace_callback('|^/feed(/([^/]*))?|', array(&$this, 'handle_feed'), $url);
  235. $this->check_url($url);
  236. }
  237. function check_url($url) {
  238. if (!empty($url) && $url != '/') {
  239. $this->fp_params = array('entry'=>'entry000000-000000');
  240. }
  241. }
  242. function cache_delete_elem($id, $date) {
  243. # is this a title change?
  244. if (false !== ($ids = $this->cache_get( $date['y'] , $date['m'] , $date['d'] )))
  245. $hash = array_search($id, $ids);
  246. else
  247. return;
  248. if ($hash) {
  249. unset($this->index[ $date['y'] ] [ $date['m'] ][ $date['d'] ][ $hash ]);
  250. if (empty($this->index[ $date['y'] ] [ $date['m'] ][ $date['d'] ])) {
  251. unset($this->index[ $date['y'] ] [ $date['m'] ][ $date['d'] ]);
  252. if (empty($this->index[ $date['y'] ] [ $date['m'] ])) {
  253. unset($this->index[ $date['y'] ] [ $date['m'] ]);
  254. if (empty($this->index[ $date['y'] ])) {
  255. unset($this->index[ $date['y'] ]);
  256. }
  257. }
  258. }
  259. }
  260. $this->cache_save();
  261. }
  262. function cache_add($id, &$arr) {
  263. $date = date_from_id($id);
  264. $title = sanitize_title($arr['subject']);
  265. $this->cache_delete_elem($id, $date);
  266. $this->index[ $date['y'] ] [ $date['m'] ][ $date['d'] ][ md5($title) ] = $id;
  267. $this->cache_save();
  268. return true;
  269. }
  270. function cache_get($y,$m,$d=null,$h=null) {
  271. if (!isset($this->index[$y][$m])) {
  272. $s = @io_load_file(PRETTYURLS_CACHE.$y.$m);
  273. $this->index[$y][$m] = $s? unserialize($s) : false;
  274. }
  275. if (is_null($d))
  276. return $this->index[$y][$m];
  277. if (is_null($h))
  278. return isset($this->index[$y][$m][$d])? $this->index[$y][$m][$d] : false;
  279. if (isset($this->index[$y][$m][$d]))
  280. return isset($this->index[$y][$m][$d][$h]);
  281. else
  282. return false;
  283. }
  284. function cache_delete($id) {
  285. $date = date_from_id($id);
  286. $this->cache_delete_elem($id, $date);
  287. $this->cache_save();
  288. }
  289. function cache_save() {
  290. if ($this->index) {
  291. foreach ($this->index as $year => $months) {
  292. foreach ($months as $month => $days)
  293. io_write_file(PRETTYURLS_CACHE.$year.$month, serialize($days));
  294. }
  295. }
  296. return true;
  297. }
  298. function nextprevlink($nextprev, $v) {
  299. global $fpdb;
  300. $q =& $fpdb->getQuery();
  301. list($caption, $id) = call_user_func(array(&$q, 'get'.$nextprev));
  302. if (!$id)
  303. return array();
  304. if ($q->single) {
  305. $date = date_from_id($id);
  306. $title = sanitize_title($caption);
  307. $url = $this->baseurl . "20{$date['y']}/{$date['m']}/{$date['d']}/$title/";
  308. if ($v>0)
  309. $caption = $caption . ' &raquo ';
  310. else
  311. $caption = ' &laquo ' . $caption;
  312. return array($caption,$url);
  313. }
  314. // else, we build a complete url
  315. /* todo: clean up this mess... which means cleaning up the mess above. oh, my! */
  316. $l = $this->baseurl ;
  317. if ( ( is_numeric($cid = @$this->fp_params['category']) ) ||
  318. is_numeric($cid = @$this->fp_params['cat']) )
  319. $l = $this->categorylink($l, $cid);
  320. if (isset($this->fp_params['y']) && $this->fp_params['y']) {
  321. $l .= '20'. $this->fp_params['y'] . '/';
  322. if (isset($this->fp_params['m']) && $this->fp_params['m']) {
  323. $l .= $this->fp_params['m'] . '/';
  324. if (isset($this->fp_params['d']) && $this->fp_params['d'])
  325. $l .= $this->fp_params['d'] . '/';
  326. }
  327. }
  328. $page = 1;
  329. if (isset($this->fp_params['paged']) && $this->fp_params['paged']>1) $page = $this->fp_params['paged'];
  330. $page += $v;
  331. if ($page > 0) {
  332. $l .= 'page/' . $page . '/';
  333. }
  334. return array($caption,$l);
  335. }
  336. }
  337. global $plugin_prettyurls;
  338. $plugin_prettyurls = new Plugin_PrettyURLs;
  339. $plugin_prettyurls->categories();
  340. if (!defined('MOD_ADMIN_PANEL')){
  341. if (!function_exists('get_nextpage_link')) :
  342. function get_nextpage_link() {
  343. global $plugin_prettyurls;
  344. return $plugin_prettyurls->nextprevlink('NextPage', 1);
  345. }
  346. function get_prevpage_link() {
  347. global $plugin_prettyurls;
  348. return $plugin_prettyurls->nextprevlink('PrevPage',-1);
  349. }
  350. endif;
  351. }
  352. add_filter('post_link', array(&$plugin_prettyurls,'permalink'), 0, 2);
  353. add_filter('comments_link', array(&$plugin_prettyurls, 'commentlink'), 0, 2);
  354. add_filter('feed_link', array(&$plugin_prettyurls, 'feedlink'), 0, 2);
  355. add_filter('post_comments_feed_link', array(&$plugin_prettyurls, 'commentsfeedlink'), 0, 3);
  356. add_filter('category_link', array(&$plugin_prettyurls,'categorylink'), 0, 2);
  357. add_filter('page_link', array(&$plugin_prettyurls, 'staticlink'), 0, 2);
  358. // date related functions
  359. add_filter('year_link', array(&$plugin_prettyurls,'yearlink'), 0, 2);
  360. add_filter('month_link', array(&$plugin_prettyurls,'monthlink'), 0, 3);
  361. add_filter('day_link', array(&$plugin_prettyurls,'daylink'), 0, 4);
  362. if (PRETTYURLS_TITLES) {
  363. add_filter('publish_post', array(&$plugin_prettyurls, 'cache_add'), 5, 2);
  364. add_filter('delete_post', array(&$plugin_prettyurls, 'cache_delete'));
  365. add_action('update_categories', array(&$plugin_prettyurls, 'categories'));
  366. }
  367. add_filter('init', array(&$plugin_prettyurls, 'cache_init'));
  368. if (class_exists('AdminPanelAction')){
  369. class admin_plugin_prettyurls extends AdminPanelAction {
  370. var $langres = 'plugin:prettyurls';
  371. function setup() {
  372. $this->smarty->assign('admin_resource', "plugin:prettyurls/admin.plugin.prettyurls");
  373. $blogroot = BLOG_ROOT;
  374. $f = ABS_PATH . '.htaccess';
  375. $txt = io_load_file($f);
  376. if (!$txt) {
  377. $txt =<<<STR
  378. # Thanks again WP :)
  379. <IfModule mod_rewrite.c>
  380. RewriteEngine On
  381. RewriteBase {$blogroot}
  382. RewriteCond %{REQUEST_FILENAME} !-f
  383. RewriteCond %{REQUEST_FILENAME} !-d
  384. RewriteRule . {$blogroot}index.php [L]
  385. </IfModule>
  386. STR;
  387. }
  388. $this->smarty->assign('cantsave',
  389. ( !is_writable(ABS_PATH) || (file_exists($f) && !is_writable($f)) )
  390. );
  391. $this->smarty->assign('htaccess', $txt);
  392. }
  393. function onsubmit() {
  394. global $fp_config;
  395. if (!empty($_POST['htaccess']) && io_write_file(ABS_PATH.'.htaccess', $_POST['htaccess'])){
  396. $this->smarty->assign('success', 1);
  397. } else {
  398. $this->smarty->assign('success', -1);
  399. }
  400. return 2;
  401. }
  402. }
  403. admin_addpanelaction('plugin', 'prettyurls', true);
  404. }
  405. ?>