BxDolVote.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. <?php defined('BX_DOL') or die('hack attempt');
  2. /**
  3. * Copyright (c) BoonEx Pty Limited - http://www.boonex.com/
  4. * CC-BY License - http://creativecommons.org/licenses/by/3.0/
  5. *
  6. * @defgroup TridentCore Trident Core
  7. * @{
  8. */
  9. define('BX_DOL_VOTE_OLD_VOTES', 365 * 86400); ///< votes older than this number of seconds will be deleted automatically
  10. define('BX_DOL_VOTE_TYPE_STARS', 'stars');
  11. define('BX_DOL_VOTE_TYPE_LIKES', 'likes');
  12. define('BX_DOL_VOTE_USAGE_BLOCK', 'block');
  13. define('BX_DOL_VOTE_USAGE_INLINE', 'inline');
  14. define('BX_DOL_VOTE_USAGE_DEFAULT', BX_DOL_VOTE_USAGE_BLOCK);
  15. /**
  16. * @page objects
  17. * @section votes Votes
  18. * @ref BxDolVote
  19. */
  20. /**
  21. * Vote for any content
  22. *
  23. * Related classes:
  24. * - BxDolVoteQuery - vote database queries
  25. * - BxBaseVote - vote base representation
  26. * - BxTemplVote - custom template representation
  27. *
  28. * AJAX vote for any content. Stars and Plus based representations are supported.
  29. *
  30. * To add vote section to your feature you need to add a record to 'sys_objects_vote' table:
  31. *
  32. * - ID - autoincremented id for internal usage
  33. * - Name - your unique module name, with vendor prefix, lowercase and spaces are underscored
  34. * - TableMain - table name where summary votigs are stored
  35. * - TableTrack - table name where each vote is stored
  36. * - PostTimeout - number of seconds to not allow duplicate vote
  37. * - MinValue - min vote value, 1 by default
  38. * - MaxValue - max vote value, 5 by default
  39. * - IsUndo - is Undo enabled for Plus based votes
  40. * - IsOn - is this vote object enabled
  41. * - TriggerTable - table to be updated upon each vote
  42. * - TriggerFieldId - TriggerTable table field with unique record id, primary key
  43. * - TriggerFieldRate - TriggerTable table field with average rate
  44. * - TriggerFieldRateCount - TriggerTable table field with votes count
  45. * - ClassName - your custom class name, if you overrride default class
  46. * - ClassFile - your custom class path
  47. *
  48. * You can refer to BoonEx modules for sample record in this table.
  49. *
  50. *
  51. *
  52. * @section example Example of usage:
  53. * To get Star based vote you need to have different values for MinValue and MaxValue (for example 1 and 5)
  54. * and IsUndo should be equal to 0. To get Plus(Like) based vote you need to have equal values
  55. * for MinValue and MaxValue (for example 1) and IsUndo should be equal to 1. After filling the other
  56. * paramenters in the table you can show vote in any place, using the following code:
  57. * @code
  58. * $o = BxDolVote::getObjectInstance('system object name', $iYourEntryId);
  59. * if (!$o->isEnabled()) return '';
  60. * echo $o->getElementBlock();
  61. * @endcode
  62. *
  63. *
  64. * @section acl Memberships/ACL:
  65. * - vote
  66. *
  67. *
  68. *
  69. * @section alerts Alerts:
  70. * Alerts type/unit - every module has own type/unit, it equals to ObjectName.
  71. * The following alerts are rised:
  72. *
  73. * - rate - comment was posted
  74. * - $iObjectId - entry id
  75. * - $iSenderId - rater user id
  76. * - $aExtra['rate'] - rate
  77. *
  78. */
  79. class BxDolVote extends BxDolObject
  80. {
  81. public function __construct($sSystem, $iId, $iInit = true)
  82. {
  83. parent::__construct($sSystem, $iId, $iInit);
  84. if(empty($this->_sSystem))
  85. return;
  86. $this->_oQuery = new BxDolVoteQuery($this);
  87. }
  88. /**
  89. * get votes object instanse
  90. * @param $sSys vote object name
  91. * @param $iId associated content id, where vote is available
  92. * @param $iInit perform initialization
  93. * @return null on error, or ready to use class instance
  94. */
  95. public static function getObjectInstance($sSys, $iId, $iInit = true)
  96. {
  97. if(isset($GLOBALS['bxDolClasses']['BxDolVote!' . $sSys . $iId]))
  98. return $GLOBALS['bxDolClasses']['BxDolVote!' . $sSys . $iId];
  99. $aSystems = self::getSystems();
  100. if(!isset($aSystems[$sSys]))
  101. return null;
  102. $sClassName = 'BxTemplVote';
  103. if(!empty($aSystems[$sSys]['class_name'])) {
  104. $sClassName = $aSystems[$sSys]['class_name'];
  105. if(!empty($aSystems[$sSys]['class_file']))
  106. require_once(BX_DIRECTORY_PATH_ROOT . $aSystems[$sSys]['class_file']);
  107. }
  108. $o = new $sClassName($sSys, $iId, $iInit);
  109. return ($GLOBALS['bxDolClasses']['BxDolVote!' . $sSys . $iId] = $o);
  110. }
  111. public static function &getSystems()
  112. {
  113. if(!isset($GLOBALS['bx_dol_vote_systems']))
  114. $GLOBALS['bx_dol_vote_systems'] = BxDolDb::getInstance()->fromCache('sys_objects_vote', 'getAllWithKey', '
  115. SELECT
  116. `ID` as `id`,
  117. `Name` AS `name`,
  118. `TableMain` AS `table_main`,
  119. `TableTrack` AS `table_track`,
  120. `PostTimeout` AS `post_timeout`,
  121. `MinValue` AS `min_value`,
  122. `MaxValue` AS `max_value`,
  123. `IsUndo` AS `is_undo`,
  124. `IsOn` AS `is_on`,
  125. `TriggerTable` AS `trigger_table`,
  126. `TriggerFieldId` AS `trigger_field_id`,
  127. `TriggerFieldRate` AS `trigger_field_rate`,
  128. `TriggerFieldRateCount` AS `trigger_field_count`,
  129. `ClassName` AS `class_name`,
  130. `ClassFile` AS `class_file`
  131. FROM `sys_objects_vote`', 'name');
  132. return $GLOBALS['bx_dol_vote_systems'];
  133. }
  134. /**
  135. * it is called on cron every day or similar period to clean old votes
  136. */
  137. public static function maintenance()
  138. {
  139. $iResult = 0;
  140. $oDb = BxDolDb::getInstance();
  141. $aSystems = self::getSystems();
  142. foreach($aSystems as $aSystem) {
  143. if(!$aSystem['is_on'])
  144. continue;
  145. $sQuery = $oDb->prepare("DELETE FROM `{$aSystem['table_track']}` WHERE `date` < (UNIX_TIMESTAMP() - ?)", BX_DOL_VOTE_OLD_VOTES);
  146. $iDeleted = (int)$oDb->query($sQuery);
  147. if($iDeleted > 0)
  148. $oDb->query("OPTIMIZE TABLE `{$aSystem['table_track']}`");
  149. $iResult += $iDeleted;
  150. }
  151. return $iResult;
  152. }
  153. public function isUndo()
  154. {
  155. return (int)$this->_aSystem['is_undo'] == 1;
  156. }
  157. public function isLikeMode()
  158. {
  159. $iMinValue = $this->getMinValue();
  160. $iMaxValue = $this->getMaxValue();
  161. return $iMinValue == $iMaxValue;
  162. }
  163. public function getMinValue()
  164. {
  165. return (int)$this->_aSystem['min_value'];
  166. }
  167. public function getMaxValue()
  168. {
  169. return (int)$this->_aSystem['max_value'];
  170. }
  171. /**
  172. * Interface functions for outer usage
  173. */
  174. public function getStatCounter()
  175. {
  176. $aVote = $this->_oQuery->getVote($this->getId());
  177. return $aVote['count'];
  178. }
  179. public function getStatRate()
  180. {
  181. $aVote = $this->_oQuery->getVote($this->getId());
  182. return $aVote['rate'];
  183. }
  184. public function getSqlParts($sMainTable, $sMainField)
  185. {
  186. if(!$this->isEnabled())
  187. return array();
  188. return $this->_oQuery->getSqlParts($sMainTable, $sMainField);
  189. }
  190. /**
  191. * Actions functions
  192. */
  193. public function actionVote()
  194. {
  195. if(!$this->isEnabled()) {
  196. $this->_echoResultJson(array('code' => 1));
  197. return;
  198. }
  199. $iObjectId = $this->getId();
  200. $iAuthorId = $this->_getAuthorId();
  201. $iAuthorIp = $this->_getAuthorIp();
  202. $bUndo = $this->isUndo();
  203. $bLikeMode = $this->isLikeMode();
  204. $bVoted = $this->_oQuery->isVoted($iObjectId, $iAuthorId);
  205. $bPerformUndo = $bVoted && $bUndo ? true : false;
  206. if(!$bPerformUndo && !$this->isAllowedVote(true)) {
  207. $this->_echoResultJson(array('code' => 2, 'msg' => $this->msgErrAllowedVote()));
  208. return;
  209. }
  210. if((!$bLikeMode && !$this->_oQuery->isPostTimeoutEnded($iObjectId, $iAuthorIp)) || ($bLikeMode && $bVoted && !$bUndo)) {
  211. $this->_echoResultJson(array('code' => 3, 'msg' => _t('_vote_err_duplicate_vote')));
  212. return;
  213. }
  214. $iValue = bx_get('value');
  215. if($iValue === false) {
  216. $this->_echoResultJson(array('code' => 4));
  217. return;
  218. }
  219. $iValue = bx_process_input($iValue, BX_DATA_INT);
  220. $iMinValue = $this->getMinValue();
  221. if($iValue < $iMinValue)
  222. $iValue = $iMinValue;
  223. $iMaxValue = $this->getMaxValue();
  224. if($iValue > $iMaxValue)
  225. $iValue = $iMaxValue;
  226. if(!$this->_oQuery->putVote($iObjectId, $iAuthorId, $iAuthorIp, $iValue, $bPerformUndo)) {
  227. $this->_echoResultJson(array('code' => 5));
  228. return;
  229. }
  230. $this->_triggerVote();
  231. $oZ = new BxDolAlerts($this->_sSystem, 'rate', $this->getId(), $iAuthorId, array('value' => $iValue, 'undo' => $bPerformUndo));
  232. $oZ->alert();
  233. $aVote = $this->_oQuery->getVote($iObjectId);
  234. $this->_echoResultJson(array(
  235. 'code' => 0,
  236. 'rate' => $aVote['rate'],
  237. 'count' => $aVote['count'],
  238. 'countf' => (int)$aVote['count'] > 0 ? $this->_getLabelCounter($aVote['count']) : '',
  239. 'label_icon' => $bLikeMode ? $this->_getIconDoLike(!$bVoted) : '',
  240. 'label_title' => $bLikeMode ? _t($this->_getTitleDoLike(!$bVoted)) : '',
  241. 'disabled' => !$bVoted && !$bUndo,
  242. ));
  243. }
  244. public function actionGetVotedBy()
  245. {
  246. if (!$this->isEnabled())
  247. return '';
  248. return $this->_getVotedBy();
  249. }
  250. /**
  251. * Permissions functions
  252. */
  253. public function checkAction ($sAction, $isPerformAction = false)
  254. {
  255. $iId = $this->_getAuthorId();
  256. $a = checkActionModule($iId, $sAction, 'system', $isPerformAction);
  257. return $a[CHECK_ACTION_RESULT] === CHECK_ACTION_RESULT_ALLOWED;
  258. }
  259. public function checkActionErrorMsg ($sAction)
  260. {
  261. $iId = $this->_getAuthorId();
  262. $a = checkActionModule($iId, $sAction, 'system');
  263. return $a[CHECK_ACTION_RESULT] !== CHECK_ACTION_RESULT_ALLOWED ? $a[CHECK_ACTION_MESSAGE] : '';
  264. }
  265. public function isAllowedVote($isPerformAction = false)
  266. {
  267. if(isAdmin())
  268. return true;
  269. return $this->checkAction('vote', $isPerformAction);
  270. }
  271. public function msgErrAllowedVote()
  272. {
  273. return $this->checkActionErrorMsg('vote');
  274. }
  275. function onObjectDelete($iObjectId = 0)
  276. {
  277. $this->_oQuery->deleteObjectVotes($iObjectId ? $iObjectId : $this->getId());
  278. }
  279. /**
  280. * Internal functions
  281. */
  282. protected function _getAuthorId ()
  283. {
  284. return isMember() ? bx_get_logged_profile_id() : 0;
  285. }
  286. protected function _getAuthorIp ()
  287. {
  288. return getVisitorIP();
  289. }
  290. protected function _getAuthorInfo($iAuthorId = 0)
  291. {
  292. $oProfile = $this->_getAuthorObject($iAuthorId);
  293. return array(
  294. $oProfile->getDisplayName(),
  295. $oProfile->getUrl(),
  296. $oProfile->getThumb(),
  297. $oProfile->getUnit()
  298. );
  299. }
  300. protected function _getAuthorObject($iAuthorId = 0)
  301. {
  302. $oProfile = BxDolProfile::getInstance($iAuthorId);
  303. if (!$oProfile)
  304. $oProfile = BxDolProfileUndefined::getInstance();
  305. return $oProfile;
  306. }
  307. protected function _getIconDoLike($bVoted)
  308. {
  309. return $bVoted && $this->isUndo() ? 'thumbs-down' : 'thumbs-up';
  310. }
  311. protected function _getTitleDoLike($bVoted)
  312. {
  313. return $bVoted && $this->isUndo() ? '_vote_do_unlike' : '_vote_do_like';
  314. }
  315. protected function _triggerVote()
  316. {
  317. if(!$this->_aSystem['trigger_table'])
  318. return false;
  319. $iId = $this->getId();
  320. if(!$iId)
  321. return false;
  322. return $this->_oQuery->updateTriggerTable($iId);
  323. }
  324. }
  325. /** @} */