PageRenderTime 57ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/application/models/UserHasFavourites.php

https://github.com/tavishvaidya/site
PHP | 659 lines | 475 code | 87 blank | 97 comment | 80 complexity | 807c4136536e5837d1e512c5eae4c5f1 MD5 | raw file
  1. <?php
  2. /**
  3. * UserHasFavourites -> UserHasFavourites database model for user favourites table.
  4. *
  5. * Copyright (c) <2010> Jari Korpela
  6. *
  7. * This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License
  8. * as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
  11. * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
  12. * more details.
  13. *
  14. * You should have received a copy of the GNU General Public License along with this program; if not, write to the Free
  15. * Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  16. *
  17. * License text found in /license/
  18. */
  19. /**
  20. * UserHasFavourites - class
  21. *
  22. * @package models
  23. * @author Jari Korpela
  24. * @copyright 2010 Jari Korpela
  25. * @license GPL v2
  26. * @version 1.0
  27. */
  28. class Default_Model_UserHasFavourites extends Zend_Db_Table_Abstract
  29. {
  30. // Name of table
  31. protected $_name = 'usr_has_fvr';
  32. // Primary keys of table
  33. protected $_primary = array('id_cnt','id_usr');
  34. protected $_referenceMap = array(
  35. 'FavouritesContent' => array(
  36. 'columns' => array('id_cnt'),
  37. 'refTableClass' => 'Default_Model_Content',
  38. 'refColumns' => array('id_cnt')
  39. ),
  40. 'FavouritesUser' => array(
  41. 'columns' => array('id_usr'),
  42. 'refTableClass' => 'Default_Model_User',
  43. 'refColumns' => array('id_usr')
  44. ),
  45. );
  46. //Get all favourite content ID:s that user has
  47. public function getAllFavouriteContentIdsFromUser($id_usr = 0)
  48. {
  49. if($id_usr != 0) {
  50. $select = $this->select()
  51. ->from($this, array('id_cnt'))
  52. ->where('id_usr = ?',$id_usr);
  53. $result = $this->fetchAll($select)->toArray();
  54. return $result;
  55. } else {
  56. return NULL;
  57. }
  58. }
  59. public function getAllFavouriteContentIdsFromUserWithLastChecked($id_usr = 0)
  60. {
  61. if($id_usr != 0) {
  62. $select = $this->select()
  63. ->from($this, array('id_cnt','last_checked'))
  64. ->where('id_usr = ?',$id_usr);
  65. $result = $this->fetchAll($select)->toArray();
  66. $return = array();
  67. foreach($result as $res) {
  68. $return[$res['id_cnt']] = $res['last_checked'];
  69. }
  70. return $return;
  71. } else {
  72. return NULL;
  73. }
  74. }
  75. //Get all user ID:s that have same favourite content ID:s
  76. public function getAllUserIdsFromFavouriteContent($id_cnt = 0)
  77. {
  78. if($id_cnt != 0) {
  79. $select = $this->select()
  80. ->from($this, array('id_usr'))
  81. ->where('id_cnt = ?',$id_cnt);
  82. $result = $this->fetchAll($select)->toArray();
  83. return $result;
  84. } else {
  85. return NULL;
  86. }
  87. }
  88. //Get favourites count by user
  89. public function getFavouritesCountByUser($id_usr = 0)
  90. {
  91. if($id_usr != 0) {
  92. $select = $this->select()
  93. ->from($this, array('favourites_count' => 'COUNT(id_cnt)'))
  94. ->where('id_usr = ?',$id_usr);
  95. $result = $this->fetchAll($select)->toArray();
  96. return $result;
  97. } else {
  98. return NULL;
  99. }
  100. }
  101. //Get users count by favourite content
  102. public function getUsersCountByFavouriteContent($id_cnt = 0)
  103. {
  104. if($id_cnt != 0) {
  105. $select = $this->select()
  106. ->from($this, array('users_count_fvr' => 'COUNT(id_usr)'))
  107. ->where('id_cnt = ?',$id_cnt);
  108. $result = $this->fetchAll($select)->toArray();
  109. return $result;
  110. } else {
  111. return NULL;
  112. }
  113. }
  114. //Check if user has content favourited
  115. public function checkIfUserHasFavouriteContent($id_usr = 0)
  116. {
  117. $return = false;
  118. if($id_usr != 0) {
  119. $select = $this->select()
  120. ->from($this, array('*'))
  121. ->where('id_usr = ?',$id_usr);
  122. $this->fetchAll($select)->count() == 0 ? $return = false : $return = true;
  123. }
  124. return $return;
  125. }
  126. //Check if content is added to favourites by any user
  127. public function checkIfContentIsFavourited($id_cnt = 0)
  128. {
  129. $return = false;
  130. if($id_cnt != 0) {
  131. $select = $this->select()
  132. ->from($this, array('*'))
  133. ->where('id_cnt = ?',$id_cnt);
  134. $this->fetchAll($select)->count() == 0 ? $return = false : $return = true;
  135. }
  136. return $return;
  137. }
  138. //Check if content is added to user favourites
  139. public function checkIfContentIsUsersFavourite($id_cnt = 0, $id_usr = 0)
  140. {
  141. $return = false;
  142. if($id_cnt != 0 && $id_usr != 0) {
  143. $select = $this->select()
  144. ->from($this, array('*'))
  145. ->where('id_cnt = ?',$id_cnt)
  146. ->where('id_usr = ?',$id_usr);
  147. $this->fetchAll($select)->count() == 0 ? $return = false : $return = true;
  148. }
  149. return $return;
  150. }
  151. //Add content to favourites
  152. public function addContentToFavourites($id_cnt = 0, $id_usr = 0)
  153. {
  154. $return = false;
  155. if($id_cnt != 0 && $id_usr != 0) {
  156. $content = $this->createRow();
  157. $content->id_cnt = $id_cnt;
  158. $content->id_usr = $id_usr;
  159. $content->last_checked = new Zend_Db_Expr('NOW()');
  160. if(!$content->save()) {
  161. $return = false;
  162. } else {
  163. $return = true;
  164. }
  165. }
  166. return $return;
  167. }
  168. //Removes all favourite content from user by user id
  169. //This is used when user wants to remove all of his favourite content
  170. public function removeAllFavouriteContentByUserId($id_usr = 0)
  171. {
  172. $return = false;
  173. if($id_usr != 0) {
  174. $where = $this->getAdapter()->quoteInto('id_usr = ?', (int)$id_usr);
  175. if(!$this->delete($where)) {
  176. $return = false;
  177. } else {
  178. $return = true;
  179. }
  180. }
  181. return $return;
  182. }
  183. //Removes favourite content from user by user id
  184. //This is used when user wants to remove single content from his favourite list
  185. public function removeUserFavouriteContent($id_cnt = 0, $id_usr = 0)
  186. {
  187. $return = false;
  188. if($id_cnt != 0 && $id_usr != 0) {
  189. $where[] = $this->getAdapter()->quoteInto('id_usr = ?', (int)$id_usr);
  190. $where[] = $this->getAdapter()->quoteInto('id_cnt = ?', (int)$id_cnt);
  191. if(!$this->delete($where)) {
  192. $return = false;
  193. } else {
  194. $return = true;
  195. }
  196. }
  197. return $return;
  198. }
  199. //Removes all favourite content from users by content id
  200. //If content is deleted this is used to remove references to deleted content
  201. public function removeAllContentFromFavouritesByContentId($id_cnt = 0)
  202. {
  203. if($id_cnt != 0) {
  204. $where = $this->getAdapter()->quoteInto('id_cnt = ?', (int)$id_cnt);
  205. $this->delete($where);
  206. }
  207. return ($this->fetchAll($where)->count()) ? false : true;
  208. }
  209. /*
  210. * Functions that are related to content following
  211. */
  212. public function updateLastChecked($id_usr, $id_cnt) {
  213. $this->update(array('last_checked' => new Zend_Db_Expr('NOW()')),
  214. "id_usr = $id_usr and id_cnt = $id_cnt");
  215. return;
  216. }
  217. public function getFollows() {
  218. $select = $this->_db->select()->from('follows_flw',array('bit','name'));
  219. $result = $this->_db->fetchAssoc($select);
  220. $returnArray = array();
  221. foreach($result as $key => $value) {
  222. $returnArray[$key] = $value['name'];
  223. }
  224. return $returnArray;
  225. }
  226. private function _getProfileSettingsForFollows($id_usr,$type = 'all') {
  227. $userProfileModel = new Default_Model_UserProfiles();
  228. $return = array();
  229. if($type == "all") $types = array('own_follows','fvr_follows');
  230. else $types = array($type);
  231. foreach($types as $type) {
  232. $list['profile_value_usp'] = 0;
  233. if($value = $userProfileModel->getUserProfileValue($id_usr, $type))
  234. $list = $value->toArray();
  235. $return[$type] = $list['profile_value_usp'];
  236. }
  237. //print_r($return);
  238. return $return;
  239. }
  240. private function _simplifyArray($array) {
  241. $newArray = array();
  242. function simplify($item,$key,$array){$array[] = $item;}
  243. array_walk_recursive($array,"simplify",&$newArray);
  244. return $newArray;
  245. }
  246. public function getWhatUserIsFollowing($id_usr = 0, $type = 'all') {
  247. $follows = $this->getFollows();
  248. if($type = "all")
  249. $settings = $this->_getProfileSettingsForFollows($id_usr);
  250. else $settings = $this->_getProfileSettingsForFollows($id_usr,$type);
  251. $following = array();
  252. foreach($settings as $key => $set) {
  253. foreach($follows as $b => $follow) {
  254. if($b & $set) $following[$key][$b] = $follow;
  255. }
  256. }
  257. return $following;
  258. }
  259. public function getUsersWhoFollowContent($id_cnt) {
  260. $favouriteModel = new Default_Model_UserHasFavourites();
  261. $userProfileModel = new Default_Model_UserProfiles();
  262. $contentHasUserModel = new Default_Model_ContentHasUser();
  263. $favouriteIds = $this->_simplifyArray($favouriteModel->getAllUserIdsFromFavouriteContent($id_cnt));
  264. $ownerIds = $this->_simplifyArray($contentHasUserModel->getContentOwners($id_cnt));
  265. $mergedIds = array_merge($favouriteIds,$ownerIds);
  266. $followingUsers = array_keys($userProfileModel->getUsersWhoFollowContents($mergedIds));
  267. return $followingUsers;
  268. }
  269. public function getAllUpdatedContents($id_usr) {
  270. $followsToFetch = $this->getWhatUserIsFollowing($id_usr);
  271. //print_r($followsToFetch);die;
  272. $updatedContents = array();
  273. if(isset($followsToFetch['own_follows'])) {
  274. $updatedContents['own'] = $this->_fetchUpdatedContents($id_usr,$followsToFetch['own_follows'],"own");
  275. }
  276. if(isset($followsToFetch['fvr_follows'])) {
  277. $updatedContents['fvr'] = $this->_fetchUpdatedContents($id_usr,$followsToFetch['fvr_follows'],"fvr");
  278. }
  279. if($this->_noNewContents($updatedContents)) return false;
  280. //print_r($updatedContents);die;
  281. $sortedUpdated = array();
  282. $uniqueUsers = array();
  283. $actorUsers = array();
  284. foreach($updatedContents as $k => $binArray) {
  285. foreach($binArray as $bin => $contentArray) {
  286. if(is_array($contentArray)) {
  287. foreach($contentArray as $info) {
  288. $actorUsers[$info['id_cnt']]['users'][] = $info['id_usr'];
  289. $actorUsers[$info['id_cnt']]['bin'][] = $bin;
  290. $actorUsers[$info['id_cnt']]['time'][] = $info['time'];
  291. $uniqueUsers[$info['id_usr']] = 1;
  292. if(!isset($sortedUpdated[$k][$info['id_cnt']])) $sortedUpdated[$k][$info['id_cnt']] = array('time' => $info['time'], 'id_usr' => $info['id_usr']);
  293. else if(strtotime($sortedUpdated[$k][$info['id_cnt']]['time']) < strtotime($info['time']))
  294. $sortedUpdated[$k][$info['id_cnt']] = array('time' => $info['time'], 'id_usr' => $info['id_usr']);
  295. }
  296. }
  297. }
  298. }
  299. $userModel = new Default_Model_User();
  300. $actorUsersInfo = $userModel->getUserInfo(array_keys($uniqueUsers));
  301. $actorList = array();
  302. foreach($actorUsers as $id_cnt => $dataArray) {
  303. foreach($dataArray['users'] as $index => $id_usr) {
  304. foreach($actorUsersInfo as $info) {
  305. if($info['id_usr'] == $id_usr) {
  306. $actorList[$id_cnt]['info'][$id_usr] = $info;
  307. $actorList[$id_cnt]['users'][] = $id_usr;
  308. $actorList[$id_cnt]['bin'][] = $dataArray['bin'][$index];
  309. $actorList[$id_cnt]['time'][] = $dataArray['time'][$index];
  310. continue 2;
  311. }
  312. }
  313. }
  314. }
  315. //print_r($actorUsers);die;
  316. //print_r($actorUsersInfo);
  317. //print_r($actorList);die;
  318. //print_r($sortedUpdated);die;
  319. foreach($sortedUpdated as $k => $contentArray) {
  320. foreach($contentArray as $id => $info) {
  321. $sortedUpdated[$k][$id] = $info['time'];
  322. }
  323. }
  324. //print_r($sortedUpdated);die;
  325. function compare($a,$b){if($a==$b)return(0);return((strtotime($a)>strtotime($b))?-1:1);}
  326. foreach($sortedUpdated as $key => $val) {uasort($sortedUpdated[$key],"compare");}
  327. $countsContents = array();
  328. foreach($updatedContents as $k => $binArray) {
  329. foreach($binArray as $l => $timeArray) {
  330. if(is_array($timeArray)) {
  331. foreach($timeArray as $time => $info) {
  332. $countsContents[$k][$l][$time] = $info['id_cnt'];
  333. }
  334. }
  335. }
  336. }
  337. $updatedCounts = $this->_getCounts($countsContents);
  338. //print_r($updatedCounts);die;
  339. $updated = $this->_getContentInfo($updatedCounts);
  340. $followable = $this->getFollows();
  341. //print_r($updated);die;
  342. $merge = array();
  343. foreach($updated as $k => $contentArray) {
  344. foreach($contentArray as $id_cnt => $info) {
  345. $merge[$k][$id_cnt]['original'] = $info;
  346. $merge[$k][$id_cnt]['translated'] = null;
  347. $total = 0;
  348. foreach($updatedCounts as $l => $binArray) {
  349. foreach($binArray as $bin => $contentArray) {
  350. if(isset($contentArray[$id_cnt])) {
  351. $total += $contentArray[$id_cnt];
  352. $merge[$l][$id_cnt]['updates']['bins'][$followable[$bin]]['amount'] = $contentArray[$id_cnt];
  353. }
  354. }
  355. }
  356. $merge[$k][$id_cnt]['updates']['total'] = $total;
  357. foreach($actorList[$id_cnt]['time'] as $index => $data) {
  358. $followBinName = $followable[$actorList[$id_cnt]['bin'][$index]];
  359. $userId = $actorList[$id_cnt]['users'][$index];
  360. $userInfo = $actorList[$id_cnt]['info'][$userId];
  361. $userInfo = array_merge($userInfo, array('time' => $data));
  362. $merge[$k][$id_cnt]['updates']['bins'][$followBinName]['values'][] = $userInfo;
  363. }
  364. }
  365. }
  366. //print_r($followable);die;
  367. $contents = array();
  368. //print_r($merge);die;
  369. //print_r($sortedUpdated);die;
  370. //print_r($actorList);die;
  371. foreach($sortedUpdated as $k => $contentArray) {
  372. foreach($contentArray as $id => $time) {
  373. $contents[$k][$id] = $merge[$k][$id];
  374. $userId = $actorList[$id]['users'][0];
  375. $bin = $followable[$actorList[$id]['bin'][0]];
  376. $contents[$k][$id]['updates']['latest'] = array_merge($actorList[$id]['info'][$userId], array('time' => $time, 'bin' => $bin));
  377. }
  378. }
  379. //print_r($contents);die;
  380. //print_r($merge);
  381. //print_r($updatedCounts);print_r($updated);
  382. //die;
  383. return $contents;
  384. }
  385. private function _noNewContents($updatedContents) {
  386. foreach($updatedContents as $arrayBin) {
  387. foreach($arrayBin as $value) {
  388. if(is_array($value)) return false;
  389. }
  390. }
  391. return true;
  392. }
  393. private function _getContentInfo($updatedCounts) {
  394. //print_r($updatedCounts);die;
  395. $uniqueContents = array();
  396. $contentsToFetch = array();
  397. $contents = array();
  398. foreach($updatedCounts as $k => $arrayBin) {
  399. foreach($arrayBin as $bin => $arrayContent) {
  400. if(is_array($arrayContent)) {
  401. foreach($arrayContent as $cnt_id => $count) {
  402. $uniqueContents[$k][$cnt_id] = 1;
  403. $contentsToFetch[$cnt_id] = 1;
  404. }
  405. }
  406. }
  407. }
  408. $contentsToFetch = array_keys($contentsToFetch);
  409. $contentModel = new Default_Model_Content();
  410. $contentInfo = $contentModel->getContentRows($contentsToFetch);
  411. foreach($contentInfo as $k => $content) {
  412. foreach($uniqueContents as $l => $arrayContents) {
  413. if(isset($arrayContents[$content['id_cnt']])) {
  414. $contents[$l][$content['id_cnt']] = $content;
  415. continue 2;
  416. }
  417. }
  418. }
  419. return $contents;
  420. }
  421. /**
  422. *
  423. * @param unknown_type $contents
  424. */
  425. private function _getCounts($contents) {
  426. $counts = array();
  427. foreach($contents as $k => $arrayBin) {
  428. foreach($arrayBin as $bin => $arrayContent) {
  429. $counts[$k][$bin] = empty($arrayContent) ? null : array_count_values($arrayContent);
  430. }
  431. }
  432. return $counts;
  433. }
  434. /**
  435. *
  436. * @param unknown_type $id_usr
  437. * @param unknown_type $follows
  438. * @param unknown_type $type
  439. */
  440. private function _fetchUpdatedContents($id_usr,$follows, $type) {
  441. $contents = array();
  442. $updatedContents = array();
  443. if($type == "own") {
  444. $userModel = new Default_Model_User();
  445. $contents = $userModel->getUsersContentsLastCheck($id_usr);
  446. $contents = $contents[$id_usr];
  447. }
  448. //print_r($contents);die;
  449. if($type == "fvr") {
  450. $contents = $this->getAllFavouriteContentIdsFromUserWithLastChecked($id_usr);
  451. }
  452. //print_r($contents);die;
  453. foreach($follows as $bin => $follow) {
  454. if($follow == "comment") { $temp = $this->_getNewComments($contents); }
  455. elseif($follow == "rating") { $temp = $this->_getNewRatings($contents); }
  456. elseif($follow == "linking") { $temp = $this->_getNewLinkings($contents); }
  457. elseif($follow == "translation") { $temp = $this->_getNewTranslations($contents); }
  458. elseif($follow == "modified") { $temp = $this->_getModified($contents); }
  459. if(empty($temp)) $temp = null;
  460. $updatedContents[$bin] = $temp;
  461. }
  462. //print_r($updatedContents);die;
  463. return $updatedContents;
  464. }
  465. /**
  466. *
  467. * @param unknown_type $contentIds
  468. */
  469. private function _getNewComments($contentIds) {
  470. $sqlIds = array_keys($contentIds);
  471. $select = $this->_db->select()->from(array('cmt' => 'comments_cmt'),
  472. array('id_target_cmt',
  473. 'created_cmt',
  474. 'id_usr_cmt'))
  475. ->where('id_target_cmt IN (?)',$sqlIds)
  476. ->where('type_cmt = ?',2)
  477. ->order(array('created_cmt desc'))
  478. ;
  479. $result = $this->_db->fetchAll($select);
  480. $newComments = array();
  481. foreach($result as $res) {
  482. if(strtotime($res['created_cmt']) > strtotime($contentIds[$res['id_target_cmt']]))
  483. $newComments[] = array('id_cnt' => $res['id_target_cmt'],
  484. 'id_usr' => $res['id_usr_cmt'],
  485. 'time' => $res['created_cmt']);
  486. }
  487. return $newComments;
  488. }
  489. /**
  490. *
  491. * @param unknown_type $contentIds
  492. */
  493. private function _getNewRatings($contentIds) {
  494. $sqlIds = array_keys($contentIds);
  495. $select = $this->_db->select()->from(array('crt' => 'content_ratings_crt'),
  496. array('id_cnt_crt',
  497. 'created_crt',
  498. 'id_usr_crt'))
  499. ->where('id_cnt_crt IN (?)',$sqlIds)
  500. ->order(array('created_crt desc'))
  501. ;
  502. $result = $this->_db->fetchAll($select);
  503. $newRatings = array();
  504. foreach($result as $res) {
  505. if(strtotime($res['created_crt']) > strtotime($contentIds[$res['id_cnt_crt']]))
  506. $newRatings[] = array('id_cnt' => $res['id_cnt_crt'],
  507. 'id_usr' => $res['id_usr_crt'],
  508. 'time' => $res['created_crt']);
  509. }
  510. return $newRatings;
  511. }
  512. /**
  513. *
  514. * @param unknown_type $contentIds
  515. */
  516. private function _getNewLinkings($contentIds) {
  517. $sqlIds = array_keys($contentIds);
  518. $select = $this->_db->select()->from(array('chc' => 'cnt_has_cnt'),
  519. array('id_parent_cnt',
  520. 'created_cnt'))
  521. ->join(array('chu' => 'cnt_has_usr'),
  522. 'chc.id_child_cnt = chu.id_cnt',
  523. array('id_usr' => 'chu.id_usr'))
  524. ->where('id_parent_cnt IN (?)',$sqlIds)
  525. ->where('chu.owner_cnt_usr = 1')
  526. ->order(array('created_cnt desc'))
  527. ;
  528. $result = $this->_db->fetchAll($select);
  529. $newLinkings = array();
  530. foreach($result as $res) {
  531. if(strtotime($res['created_cnt']) > strtotime($contentIds[$res['id_parent_cnt']]))
  532. $newLinkings[] = array('id_cnt' => $res['id_parent_cnt'],
  533. 'id_usr' => $res['id_usr'],
  534. 'time' => $res['created_cnt']);
  535. }
  536. return $newLinkings;
  537. }
  538. /**
  539. * This function is yet to be implemented when translation feature is available.
  540. * @param $contentIds
  541. */
  542. private function _getNewTranslations($contentIds) {
  543. return;
  544. }
  545. /**
  546. *
  547. * @param array $contentIds
  548. */
  549. private function _getModified($contentIds) {
  550. $sqlIds = array_keys($contentIds);
  551. $select = $this->_db->select()->from(array('cnt' => 'contents_cnt'),
  552. array('id_cnt',
  553. 'modified_cnt'))
  554. ->join(array('chu' => 'cnt_has_usr'),
  555. 'cnt.id_cnt = chu.id_cnt',
  556. array('id_usr' => 'chu.id_usr'))
  557. ->where('cnt.id_cnt IN (?)',$sqlIds)
  558. ->where('chu.owner_cnt_usr = 1')
  559. ->order(array('modified_cnt desc'))
  560. ;
  561. $result = $this->_db->fetchAll($select);
  562. $newLinkings = array();
  563. foreach($result as $res) {
  564. if(strtotime($res['modified_cnt']) > strtotime($contentIds[$res['id_cnt']]))
  565. $newLinkings[] = array('id_cnt' => $res['id_cnt'],
  566. 'id_usr' => $res['id_usr'],
  567. 'time' => $res['modified_cnt']);
  568. }
  569. return $newLinkings;
  570. }
  571. } // end of class
  572. ?>