BxDolVote.php 12 KB

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