PageRenderTime 46ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/www/application/models/post.php

https://github.com/chardcastle/mysite
PHP | 309 lines | 277 code | 15 blank | 17 comment | 5 complexity | 797dc56e84ec9a644ea9755d8f188c0b MD5 | raw file
  1. <?php defined('SYSPATH') or die('No direct script access.');
  2. class Post_Model extends App_Model {
  3. private $urls = array();
  4. protected $db; // database instance
  5. public $posts = array();
  6. public $byDayFormat;
  7. public $totalTimeLineItems = 0;
  8. public function __construct()
  9. {
  10. parent::__construct();
  11. // Get the date format for items shown in grid
  12. $this->byDayFormat = Kohana::config("config.by_day_format");
  13. // Declare usr
  14. $this->urls = Kohana::config("config.data_source_urls");
  15. $this->totalTimeLineItems = $this->db->count_records('kh_timeline');
  16. }
  17. /*
  18. * Look for posts newer than those we already have
  19. * Get the most recent post,
  20. * If there wasn't one, then the table was probably truncated for dev population
  21. //$this->db->query("TRUNCATE TABLE kh_posts");
  22. */
  23. public function searchForNewPosts(){
  24. $this->db->query("TRUNCATE TABLE kh_posts");
  25. $info = "Request for new posts detected";
  26. $mostRecentPost = $this->db->select("*")
  27. ->from("kh_posts")
  28. ->limit(1)
  29. ->orderby("created_dt","desc")
  30. ->get()
  31. ->result_array(true);
  32. //Kohana::log("debug",$this->db->last_query());
  33. $mostRecentPost = (isset($mostRecentPost[0]))?$mostRecentPost[0]->created_dt:false;
  34. if($mostRecentPost != false){
  35. // mark the one that was updated last
  36. $this->db->update('kh_posts',array('is_last_updated'=>1),array('created_dt'=>$mostRecentPost));
  37. $whereStr = "created_dt between {$mostRecentPost} and now()";
  38. $numberOfNewPosts = $this->db->count_records('kh_posts',$whereStr);
  39. $info .= "Looking for posts newer than ".date("d-m-y",$mostRecentPost)."\n";
  40. $additional = "new posts {$whereStr}";
  41. }else{
  42. $additional = "there was not mostRecent value, was the table truncated?\n";
  43. $numberOfNewPosts = 0;
  44. }
  45. // Check to see if we likely to already have new posts
  46. // Check for posts older than one hour
  47. Kohana::log("debug","Theres ".$numberOfNewPosts." {$additional}\n");
  48. // $mostRecentPost might be false, but that's ok, its accepted within model code
  49. if($numberOfNewPosts <= 0){
  50. // return nothing, just capture feeds
  51. // Parse an external atom feed
  52. $obj = new Tumblr_Model;
  53. $tumNo = $obj->captureFeed($this->urls["tumblr"],$mostRecentPost);
  54. $info .= (isset($tumNo)?$tumNo:"Didn't request any")." new Tumblr items\n";
  55. $obj = new Tweet_Model;
  56. $tweNo = $obj->captureFeed($this->urls["tweets"],$mostRecentPost);
  57. $info .= (isset($tweNo)?$tweNo:"Didn't request any")." new Tweet items\n";
  58. $obj = new Git_Model;
  59. $gitNo = $obj->captureFeed($this->urls["github"]["jquery"],$mostRecentPost);
  60. $info .= (isset($gitNo)?$gitNo:"Didn't request any")." new Git items\n";
  61. // update website description
  62. kohana::log("debug",$info);
  63. $this->updateHomeDescription();
  64. }else{
  65. Kohana::log("debug","We already have posts between ".date('d-m-y')." and ".date('d-m-y',$mostRecentPost)."\n");
  66. //
  67. }
  68. }
  69. /*
  70. * Remove all records from timeline
  71. * create new ones based on post source table
  72. * The function befor it, saveNewPosts must always
  73. * leave is_last_update set to true as this function requires it as a pointer
  74. * pointer is reset once complete
  75. * */
  76. public function digestNewPosts(){
  77. $this->posts = array();
  78. // Useful for dev -->
  79. $this->db->query("TRUNCATE TABLE kh_timeline");
  80. // If table is truncated, re-generate home snippet first,
  81. $truncated = false;
  82. if($this->db->count_records('kh_timeline') <= 0){
  83. $sql = "SELECT * FROM kh_posts";
  84. $mostRecentPost = date('d m y');
  85. Kohana::log("debug","A request to process posts from {$mostRecentPost} has been detected");
  86. Kohana::log("debug","Empty table, lets go!\n");
  87. $truncated = true;
  88. $this->makeHomeSnippet();
  89. }else{
  90. // only update timeline table with new records
  91. $sql = <<<SQL
  92. SELECT posts.type,
  93. from_unixtime(posts.created_dt,'%d-%m-%y') AS dateKey,
  94. posts.content,
  95. posts.*
  96. FROM
  97. (select * from kh_posts)
  98. AS posts
  99. INNER JOIN kh_posts AS dates
  100. ON posts.created_dt = dates.created_dt
  101. WHERE posts.is_last_updated = 0
  102. GROUP BY posts.content ORDER BY posts.created_dt DESC
  103. SQL;
  104. // Get the last time the posts were updated
  105. $mostRecentPost = $this->db->query('SELECT created_dt FROM kh_posts ORDER BY created_dt DESC limit 1');
  106. $mostRecentPost = (isset($mostRecentPost[0]))?$mostRecentPost[0]->created_dt:false;
  107. $mostRecentPost = date('d m y',$mostRecentPost);
  108. }
  109. $posts = $this->db->query($sql)->result_array(true);
  110. kohana::log("debug",$this->db->last_query());
  111. if(count($posts) > 0){
  112. foreach($posts as $key => $value){
  113. $serialData = unserialize($value->content);
  114. /* Save month_stamp of M Y as month and year for use in selecting
  115. * post within a range
  116. */
  117. $content = array(
  118. "teaser" => $this->load($serialData,$value,"summary"),
  119. "content" => $this->load($serialData,$value,"full_width"),
  120. "date" => date($this->byDayFormat,$value->created_dt),
  121. "month_stamp" => strtotime(date("M Y",$value->created_dt))
  122. );
  123. // mark as processed in table
  124. $this->db->update("kh_posts",array("is_last_updated"=>1),array("post_id"=>$value->post_id));
  125. kohana::log("debug",$this->db->last_query());
  126. // makde key
  127. $key = $content['date'];
  128. //
  129. if(!array_key_exists($key,$this->posts)){
  130. $this->posts[$key] = array($content);
  131. }else{
  132. $this->posts[$key][] = $content;
  133. }
  134. }
  135. // traverse and stick into table
  136. if(count($this->posts)>0){
  137. foreach($this->posts as $key => $value){
  138. $teaser = array();
  139. $content = array();
  140. kohana::log("debug",print_r($value,true));
  141. foreach($value as $post){
  142. $teaser[] = $post["teaser"];
  143. $content[] = $post["content"];
  144. $month = $post["month_stamp"];
  145. }
  146. $teaser = (count($teaser)>0)?serialize($teaser):serialize(array());
  147. $content = (count($content)>0)?serialize($content):serialize(array());
  148. //$key = strtotime(date("M Y",$key));
  149. $this->db->insert("kh_timeline", array(
  150. "date" => "{$key}",
  151. "teaser" => "{$teaser}",
  152. "content" => "{$content}",
  153. "month_stamp" => "{$month}",
  154. ));
  155. }
  156. }
  157. }
  158. }
  159. public function getNextAndPrevUrls($postId=false,$modelName){
  160. if(!$postId){
  161. return false;
  162. }
  163. // where 1 is the most recent item,
  164. // add to the index to go back in time!
  165. $next = (int)($postId)-1;
  166. $prev = (int)($postId)+1;
  167. $slug = array();
  168. $url = $this->db->query("select slug from kh_timeline where id = ".$next)->result_array();
  169. $url = $url[0]->slug;
  170. //var_dump($url).die();
  171. $slug['next'] = (isset($url[0]) && $url != NULL)?'/'.$url:"/{$modelName}/view/".$next;
  172. //
  173. $url = $this->db->from('kh_timeline')->where(array('id'=> $prev))->select('slug')->get()->result_array(true);
  174. $slug['prev'] = (isset($url[0]) && $url[0]->slug != NULL)?'/'.$url[0]->slug:"/{$modelName}/view/".$prev;
  175. return $slug;
  176. }
  177. public function getPosts($page){
  178. $this->db->select("*")
  179. ->from("kh_posts")
  180. ->limit();
  181. }
  182. private function makeHomeSnippet(){
  183. $view = new View('home_snippet');
  184. $this->db->insert("kh_timeline", array(
  185. "teaser"=>serialize(array($view->render())),
  186. "content"=> serialize(array($view->render())),
  187. "date" => time(),
  188. "month_stamp" => 0
  189. ));
  190. }
  191. /*
  192. * Get the website description from the
  193. * Tumblr account description
  194. */
  195. private function updateHomeDescription(){
  196. $data = file_get_contents($this->urls["homedesc"]);
  197. $data = json_decode($data,true);
  198. $desc = $data["query"]["results"]["tumblelog"]["content"];
  199. if(!$desc){
  200. $desc = "A blog by";
  201. }
  202. $this->db->update("kh_stash",array("value"=>"{$desc}"),array("key"=>"home_desc"));
  203. }
  204. public function getDataSourceUrls(){
  205. return $this->urls;
  206. }
  207. /*
  208. * Use the data to find its type
  209. * use its object to return its requested HTML style.
  210. */
  211. private function load($serialData,$value,$size){
  212. $html = "";
  213. if($value->type == "tumblr"){
  214. /* */
  215. if(!$serialData){
  216. kohana::log("debug","failed to decode");
  217. }else{
  218. kohana::log("debug","Found json");
  219. if(is_array($serialData) && isset($serialData["type"])){
  220. switch($serialData["type"]){
  221. case "photo":
  222. $obj = new Photo_Model;
  223. $html = $obj->loadFromLocalSource($serialData,$size);
  224. break;
  225. case "regular":
  226. $obj = new Regular_Model;
  227. $html = $obj->loadFromLocalSource($serialData,$size);
  228. break;
  229. case "link":
  230. $obj = new Link_Model;
  231. // no size alternative required
  232. $html = $obj->loadFromLocalSource($serialData);
  233. break;
  234. case "video":
  235. $obj = new Video_Model;
  236. // no size alternative required
  237. $html = $obj->loadFromLocalSource($serialData);
  238. break;
  239. case "conversation":
  240. $obj = new Quote_Model;
  241. // no size alternative required
  242. $html = $obj->loadFromLocalSource($serialData);
  243. break;
  244. }
  245. }
  246. }
  247. }else if($value->type == "gitcommit"){
  248. $obj = new Git_Model;
  249. // slight difference in parameter for this object
  250. $html = $obj->loadFromLocalSource($serialData,$value,$size);
  251. }else if($value->type == "tweet"){
  252. $obj = new Tweet_Model;
  253. // slight difference in parameter for this object
  254. $html = $obj->loadFromLocalSource($serialData,$size);
  255. }
  256. return $html;
  257. }
  258. /*
  259. * Get part of the data, for fun
  260. * ! WTH? I don't remember this
  261. */
  262. public function getDataSourceDataSchemea($key){
  263. return (Kohana::config("config.pop"))?"Pop is on":"Pop is off";
  264. }
  265. public function getSiteDescription(){
  266. $data = $this->db->select("value")
  267. ->from("kh_stash")
  268. ->where("key=","home_desc")
  269. ->get()
  270. ->result_array(true);
  271. return $data[0]->value;
  272. }
  273. public function getPost($postId){
  274. return $this->db->select("*")
  275. ->from("kh_timeline")
  276. ->where("id = ",$postId)
  277. ->get()
  278. ->result_array(false);
  279. }
  280. /* */
  281. }