BxDolVote.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. <?php defined('BX_DOL') or die('hack attempt');
  2. /**
  3. * Copyright (c) UNA, Inc - https://una.io
  4. * MIT License - https://opensource.org/licenses/MIT
  5. *
  6. * @defgroup UnaCore UNA Core
  7. * @{
  8. */
  9. bx_import('BxDolAcl');
  10. define('BX_DOL_VOTE_TYPE_STARS', 'stars');
  11. define('BX_DOL_VOTE_TYPE_LIKES', 'likes');
  12. define('BX_DOL_VOTE_TYPE_REACTIONS', 'reactions');
  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. * Vote for any content
  18. *
  19. * Related classes:
  20. * - BxDolVoteQuery - vote database queries
  21. * - BxBaseVote - vote base representation
  22. * - BxTemplVote - custom template representation
  23. *
  24. * AJAX vote for any content. Stars and Plus based representations are supported.
  25. *
  26. * To add vote section to your feature you need to add a record to 'sys_objects_vote' table:
  27. *
  28. * - ID - autoincremented id for internal usage
  29. * - Name - your unique module name, with vendor prefix, lowercase and spaces are underscored
  30. * - TableMain - table name where summary votigs are stored
  31. * - TableTrack - table name where each vote is stored
  32. * - PostTimeout - number of seconds to not allow duplicate vote
  33. * - MinValue - min vote value, 1 by default
  34. * - MaxValue - max vote value, 5 by default
  35. * - IsUndo - is Undo enabled for Plus based votes
  36. * - IsOn - is this vote object enabled
  37. * - TriggerTable - table to be updated upon each vote
  38. * - TriggerFieldId - TriggerTable table field with unique record id, primary key
  39. * - TriggerFieldRate - TriggerTable table field with average rate
  40. * - TriggerFieldRateCount - TriggerTable table field with votes count
  41. * - ClassName - your custom class name, if you overrride default class
  42. * - ClassFile - your custom class path
  43. *
  44. * You can refer to BoonEx modules for sample record in this table.
  45. *
  46. *
  47. *
  48. * @section example Example of usage:
  49. * To get Star based vote you need to have different values for MinValue and MaxValue (for example 1 and 5)
  50. * and IsUndo should be equal to 0. To get Plus(Like) based vote you need to have equal values
  51. * for MinValue and MaxValue (for example 1) and IsUndo should be equal to 1. After filling the other
  52. * paramenters in the table you can show vote in any place, using the following code:
  53. * @code
  54. * $o = BxDolVote::getObjectInstance('system object name', $iYourEntryId);
  55. * if (!$o->isEnabled()) return '';
  56. * echo $o->getElementBlock();
  57. * @endcode
  58. *
  59. *
  60. * @section acl Memberships/ACL:
  61. * - vote
  62. *
  63. *
  64. *
  65. * @section alerts Alerts:
  66. * Alerts type/unit - every module has own type/unit, it equals to ObjectName.
  67. * The following alerts are rised:
  68. *
  69. * - rate - comment was posted
  70. * - $iObjectId - entry id
  71. * - $iSenderId - rater user id
  72. * - $aExtra['rate'] - rate
  73. *
  74. */
  75. class BxDolVote extends BxDolObjectVote
  76. {
  77. protected $_sType;
  78. protected function __construct($sSystem, $iId, $iInit = true, $oTemplate = false)
  79. {
  80. parent::__construct($sSystem, $iId, $iInit, $oTemplate);
  81. if(empty($this->_sSystem))
  82. return;
  83. }
  84. /**
  85. * get votes object instanse
  86. * @param $sSys vote object name
  87. * @param $iId associated content id, where vote is available
  88. * @param $iInit perform initialization
  89. * @return null on error, or ready to use class instance
  90. */
  91. public static function getObjectInstance($sSys, $iId, $iInit = true, $oTemplate = false)
  92. {
  93. $sKey = 'BxDolVote!' . $sSys . $iId . ($oTemplate ? $oTemplate->getClassName() : '');
  94. if(isset($GLOBALS['bxDolClasses'][$sKey]))
  95. return $GLOBALS['bxDolClasses'][$sKey];
  96. $aSystems = self::getSystems();
  97. if(!isset($aSystems[$sSys]))
  98. return null;
  99. $sClassName = 'BxTemplVoteLikes';
  100. if(!empty($aSystems[$sSys]['class_name'])) {
  101. $sClassName = $aSystems[$sSys]['class_name'];
  102. if(!empty($aSystems[$sSys]['class_file']))
  103. require_once(BX_DIRECTORY_PATH_ROOT . $aSystems[$sSys]['class_file']);
  104. }
  105. $o = new $sClassName($sSys, $iId, false, $oTemplate);
  106. if($iInit && method_exists($o, 'init'))
  107. $o->init($iId);
  108. return ($GLOBALS['bxDolClasses'][$sKey] = $o);
  109. }
  110. public static function &getSystems()
  111. {
  112. $sKey = 'bx_dol_cache_memory_vote_systems';
  113. if(!isset($GLOBALS[$sKey]))
  114. $GLOBALS[$sKey] = BxDolDb::getInstance()->fromCache('sys_objects_vote', 'getAllWithKey', '
  115. SELECT
  116. `ID` as `id`,
  117. `Name` AS `name`,
  118. `Module` AS `module`,
  119. `TableMain` AS `table_main`,
  120. `TableTrack` AS `table_track`,
  121. `PostTimeout` AS `post_timeout`,
  122. `MinValue` AS `min_value`,
  123. `MaxValue` AS `max_value`,
  124. `Pruning` AS `pruning`,
  125. `IsUndo` AS `is_undo`,
  126. `IsOn` AS `is_on`,
  127. `TriggerTable` AS `trigger_table`,
  128. `TriggerFieldId` AS `trigger_field_id`,
  129. `TriggerFieldAuthor` AS `trigger_field_author`,
  130. `TriggerFieldRate` AS `trigger_field_rate`,
  131. `TriggerFieldRateCount` AS `trigger_field_count`,
  132. `ClassName` AS `class_name`,
  133. `ClassFile` AS `class_file`
  134. FROM `sys_objects_vote`', 'name');
  135. return $GLOBALS[$sKey];
  136. }
  137. /**
  138. * Interface functions for outer usage
  139. */
  140. public function getType()
  141. {
  142. return $this->_sType;
  143. }
  144. public function getMinValue()
  145. {
  146. return (int)$this->_aSystem['min_value'];
  147. }
  148. public function getMaxValue()
  149. {
  150. return (int)$this->_aSystem['max_value'];
  151. }
  152. public function getStatCounter()
  153. {
  154. $aVote = $this->_getVote();
  155. return $aVote['count'];
  156. }
  157. public function getStatRate()
  158. {
  159. $aVote = $this->_getVote();
  160. return $aVote['rate'];
  161. }
  162. public function getSocketName()
  163. {
  164. return $this->_sSystem . '_' . $this->_sType;
  165. }
  166. /**
  167. * Actions functions
  168. */
  169. public function actionVote()
  170. {
  171. if(!$this->isEnabled())
  172. return echoJson(['code' => BX_DOL_OBJECT_ERR_NOT_AVAILABLE, 'message' => _t('_vote_err_not_enabled')]);
  173. $aVoteData = $this->_getVoteData();
  174. $aRequestParamsData = $this->_getRequestParamsData();
  175. if($aVoteData === false)
  176. return echoJson(['code' => BX_DOL_OBJECT_ERR_WRONG_DATE]);
  177. return echoJson($this->vote($aVoteData, $aRequestParamsData));
  178. }
  179. public function vote($aVoteData = [], $aRequestParamsData = [])
  180. {
  181. $iObjectId = $this->getId();
  182. $iObjectAuthorId = $this->getObjectAuthorId($iObjectId);
  183. $iAuthorId = $this->_getAuthorId();
  184. $iAuthorIp = $this->_getAuthorIp();
  185. $bUndo = $this->isUndo();
  186. $bVoted = $this->isPerformed($iObjectId, $iAuthorId);
  187. $bPerformUndo = $bVoted && $bUndo;
  188. if(!$bPerformUndo && !$this->isAllowedVote())
  189. return ['code' => BX_DOL_OBJECT_ERR_ACCESS_DENIED, 'message' => $this->msgErrAllowedVote()];
  190. if($this->_isDuplicate($iObjectId, $iAuthorId, $iAuthorIp, $bVoted))
  191. return ['code' => BX_DOL_OBJECT_ERR_DUPLICATE, 'message' => _t('_vote_err_duplicate_vote')];
  192. if($bPerformUndo) {
  193. $aTrack = $this->_getTrack($iObjectId, $iAuthorId);
  194. if(!empty($aTrack) && is_array($aTrack))
  195. $aVoteData = array_intersect_key($aTrack, $aVoteData);
  196. }
  197. $iId = $this->_putVoteData($iObjectId, $iAuthorId, $iAuthorIp, $aVoteData, $bPerformUndo);
  198. if($iId === false)
  199. return ['code' => BX_DOL_OBJECT_ERR_CANNOT_PERFORM];
  200. if(!$bPerformUndo)
  201. $this->isAllowedVote(true);
  202. $this->_trigger();
  203. /**
  204. * @hooks
  205. * @hookdef hook-vote-undo 'vote', 'undo' - hook on cancel vote
  206. * - $unit_name - equals `vote`
  207. * - $action - equals `undo`
  208. * - $object_id - vote id
  209. * - $sender_id - profile_id for vote's author
  210. * - $extra_params - array of additional params with the following array keys:
  211. * - `object_system` - [string] system name, ex: bx_posts
  212. * - `object_id` - [int] reported object id
  213. * - `object_author_id` - [int] author's profile_id for reported object_id
  214. * @hook @ref hook-vote-undo
  215. */
  216. bx_alert($this->_sSystem, ($bPerformUndo ? 'un' : '') . 'doVote', $iObjectId, $iAuthorId, array_merge(['vote_id' => $iId, 'vote_author_id' => $iAuthorId, 'object_author_id' => $iObjectAuthorId], $aVoteData));
  217. /**
  218. * @hooks
  219. * @hookdef hook-vote-do 'vote', 'do' - hook on new vote
  220. * - $unit_name - equals `vote`
  221. * - $action - equals `do`
  222. * - $object_id - vote id
  223. * - $sender_id - profile_id for vote's author
  224. * - $extra_params - array of additional params with the following array keys:
  225. * - `object_system` - [string] system name, ex: bx_posts
  226. * - `object_id` - [int] reported object id
  227. * - `object_author_id` - [int] author's profile_id for reported object_id
  228. * @hook @ref hook-vote-do
  229. */
  230. bx_alert('vote', ($bPerformUndo ? 'un' : '') . 'do', $iId, $iAuthorId, array_merge(['object_system' => $this->_sSystem, 'object_id' => $iObjectId, 'object_author_id' => $iObjectAuthorId], $aVoteData));
  231. $aResult = $this->_returnVoteData($iObjectId, $iAuthorId, $iAuthorIp, $aVoteData, !$bVoted, $aRequestParamsData);
  232. if(($oSockets = BxDolSockets::getInstance()) && $oSockets->isEnabled())
  233. $oSockets->sendEvent($this->getSocketName(), $iObjectId, 'voted', json_encode($this->_returnVoteDataForSocket($aResult)));
  234. return $aResult;
  235. }
  236. public function actionGetVotedBy()
  237. {
  238. if (!$this->isEnabled())
  239. return '';
  240. return $this->_getVotedBy();
  241. }
  242. /**
  243. * Internal functions
  244. */
  245. protected function _isDuplicate($iObjectId, $iAuthorId, $iAuthorIp, $bVoted)
  246. {
  247. return false;
  248. }
  249. protected function _isCount($aVote = array())
  250. {
  251. if(empty($aVote))
  252. $aVote = $this->_getVote();
  253. return isset($aVote['count']) && (int)$aVote['count'] != 0;
  254. }
  255. protected function _isAllowedVoteByObject($aObject)
  256. {
  257. return bx_srv($this->_aSystem['module'], 'check_allowed_view_for_profile', [$aObject]) === CHECK_ACTION_RESULT_ALLOWED;
  258. }
  259. protected function _getVoteData()
  260. {
  261. $iValue = bx_get('value');
  262. if($iValue === false)
  263. return false;
  264. $iValue = bx_process_input($iValue, BX_DATA_INT);
  265. $iMinValue = $this->getMinValue();
  266. if($iValue < $iMinValue)
  267. $iValue = $iMinValue;
  268. $iMaxValue = $this->getMaxValue();
  269. if($iValue > $iMaxValue)
  270. $iValue = $iMaxValue;
  271. return array('value' => $iValue);
  272. }
  273. protected function _putVoteData($iObjectId, $iAuthorId, $iAuthorIp, $aData, $bPerformUndo)
  274. {
  275. return $this->_oQuery->putVote($iObjectId, $iAuthorId, $iAuthorIp, $aData, $bPerformUndo);
  276. }
  277. protected function _returnVoteData($iObjectId, $iAuthorId, $iAuthorIp, $aData, $bVoted, $aParams = [])
  278. {
  279. $bUndo = $this->isUndo();
  280. $aVote = $this->_getVote($iObjectId, true);
  281. $aResult = [
  282. 'code' => 0,
  283. 'rate' => $aVote['rate'],
  284. 'count' => $aVote['count'],
  285. 'countf' => (int)$aVote['count'] > 0 ? $this->_getCounterLabel($aVote['count'], $aParams) : '',
  286. 'label_use' => $this->_useIconAs($aParams),
  287. 'label_icon' => $this->_getIconDo($bVoted),
  288. 'label_emoji' => $this->_getEmojiDo($bVoted),
  289. 'label_image' => $this->_getImageDo($bVoted),
  290. 'label_title' => _t($this->_getTitleDo($bVoted)),
  291. 'voted' => $bVoted,
  292. 'disabled' => $bVoted && !$bUndo,
  293. ];
  294. $aResult['api'] = [
  295. 'performer_id' => $iAuthorId,
  296. 'is_voted' => $aResult['voted'],
  297. 'is_disabled' => $aResult['disabled'],
  298. 'value' => $aResult['voted'] ? $aData['value'] : 0,
  299. 'icon' => $aResult['label_emoji'],
  300. 'title' => $aResult['label_title'],
  301. 'counter' => $this->getVote()
  302. ];
  303. return $aResult;
  304. }
  305. protected function _returnVoteDataForSocket($aData, $aMask = [])
  306. {
  307. if(empty($aMask) || !is_array($aMask))
  308. $aMask = ['code', 'rate', 'count', 'countf', 'api'];
  309. return array_intersect_key($aData, array_flip($aMask));
  310. }
  311. protected function _prepareRequestParamsData($aParams, $aParamsAdd = array())
  312. {
  313. if(isset($aParams['is_voted']))
  314. $aParamsAdd['is_voted'] = $aParams['is_voted'];
  315. return parent::_prepareRequestParamsData($aParams, $aParamsAdd);
  316. }
  317. protected function _isVote($iObjectId = 0, $bForceGet = false)
  318. {
  319. $aVote = $this->_getVote($iObjectId, $bForceGet);
  320. return (int)$aVote['count'] > 0;
  321. }
  322. protected function _getIconDo($bVoted)
  323. {
  324. return '';
  325. }
  326. protected function _getImageDo($bVoted)
  327. {
  328. return '';
  329. }
  330. protected function _getEmojiDo($bVoted)
  331. {
  332. return '';
  333. }
  334. protected function _getTitleDo($bVoted)
  335. {
  336. return '';
  337. }
  338. protected function _getTitleDoBy($aParams = [])
  339. {
  340. return _t('_vote_do_by');
  341. }
  342. protected function _useIconAs($aParams = [])
  343. {
  344. return 'emoji';
  345. }
  346. }
  347. /** @} */