BxDolVote.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  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. $iAuthorId = $this->_getAuthorId();
  183. $iAuthorIp = $this->_getAuthorIp();
  184. $bUndo = $this->isUndo();
  185. $bVoted = $this->isPerformed($iObjectId, $iAuthorId);
  186. $bPerformUndo = $bVoted && $bUndo;
  187. if(!$bPerformUndo && !$this->isAllowedVote())
  188. return ['code' => BX_DOL_OBJECT_ERR_ACCESS_DENIED, 'message' => $this->msgErrAllowedVote()];
  189. if($this->_isDuplicate($iObjectId, $iAuthorId, $iAuthorIp, $bVoted))
  190. return ['code' => BX_DOL_OBJECT_ERR_DUPLICATE, 'message' => _t('_vote_err_duplicate_vote')];
  191. if($bPerformUndo) {
  192. $aTrack = $this->_getTrack($iObjectId, $iAuthorId);
  193. if(!empty($aTrack) && is_array($aTrack))
  194. $aVoteData = array_intersect_key($aTrack, $aVoteData);
  195. }
  196. return $this->_vote($iObjectId, $iAuthorId, $iAuthorIp, $aVoteData, $bPerformUndo, $aRequestParamsData);
  197. }
  198. /**
  199. * Store a vote (or take it back when $bPerformUndo), fire the alerts and the socket event.
  200. * Checks (permissions, duplicates) are the caller's job.
  201. */
  202. protected function _vote($iObjectId, $iAuthorId, $iAuthorIp, $aVoteData, $bPerformUndo, $aRequestParamsData = [])
  203. {
  204. $iObjectAuthorId = $this->getObjectAuthorId($iObjectId);
  205. $iId = $this->_putVoteData($iObjectId, $iAuthorId, $iAuthorIp, $aVoteData, $bPerformUndo);
  206. if($iId === false)
  207. return ['code' => BX_DOL_OBJECT_ERR_CANNOT_PERFORM];
  208. if(!$bPerformUndo)
  209. $this->isAllowedVote(true);
  210. $this->_trigger();
  211. $aAlertExtras = [
  212. 'object_author_id' => $iObjectAuthorId,
  213. 'source' => 'sys_vote_' . $iId,
  214. 'source_mac' => 'sys_vote_' . $iAuthorId . '_' . $iId,
  215. ];
  216. /**
  217. * @hooks
  218. * @hookdef hook-vote-undo 'vote', 'undo' - hook on cancel vote
  219. * - $unit_name - equals `vote`
  220. * - $action - equals `undo`
  221. * - $object_id - vote id
  222. * - $sender_id - profile_id for vote's author
  223. * - $extra_params - array of additional params with the following array keys:
  224. * - `object_system` - [string] system name, ex: bx_posts
  225. * - `object_id` - [int] reported object id
  226. * - `object_author_id` - [int] author's profile_id for reported object_id
  227. * @hook @ref hook-vote-undo
  228. */
  229. bx_alert($this->_sSystem, ($bPerformUndo ? 'un' : '') . 'doVote', $iObjectId, $iAuthorId, array_merge([
  230. 'vote_id' => $iId,
  231. 'vote_author_id' => $iAuthorId
  232. ], $aAlertExtras, $aVoteData));
  233. /**
  234. * @hooks
  235. * @hookdef hook-vote-do 'vote', 'do' - hook on new vote
  236. * - $unit_name - equals `vote`
  237. * - $action - equals `do`
  238. * - $object_id - vote id
  239. * - $sender_id - profile_id for vote's author
  240. * - $extra_params - array of additional params with the following array keys:
  241. * - `object_system` - [string] system name, ex: bx_posts
  242. * - `object_id` - [int] reported object id
  243. * - `object_author_id` - [int] author's profile_id for reported object_id
  244. * @hook @ref hook-vote-do
  245. */
  246. bx_alert('vote', ($bPerformUndo ? 'un' : '') . 'do', $iId, $iAuthorId, array_merge([
  247. 'object_system' => $this->_sSystem,
  248. 'object_id' => $iObjectId
  249. ], $aAlertExtras, $aVoteData));
  250. $aResult = $this->_returnVoteData($iObjectId, $iAuthorId, $iAuthorIp, $aVoteData, !$bPerformUndo, $aRequestParamsData);
  251. if(($oSockets = BxDolSockets::getInstance()) && $oSockets->isEnabled())
  252. $oSockets->sendEvent($this->getSocketName(), $iObjectId, 'voted', json_encode($this->_returnVoteDataForSocket($aResult)));
  253. return $aResult;
  254. }
  255. public function actionGetVotedBy()
  256. {
  257. if (!$this->isEnabled())
  258. return '';
  259. return $this->_getVotedBy();
  260. }
  261. /**
  262. * Internal functions
  263. */
  264. protected function _isDuplicate($iObjectId, $iAuthorId, $iAuthorIp, $bVoted)
  265. {
  266. return false;
  267. }
  268. protected function _isCount($aVote = array())
  269. {
  270. if(empty($aVote))
  271. $aVote = $this->_getVote();
  272. return isset($aVote['count']) && (int)$aVote['count'] != 0;
  273. }
  274. protected function _isAllowedVoteByObject($aObject)
  275. {
  276. return bx_srv($this->_aSystem['module'], 'check_allowed_view_for_profile', [$aObject]) === CHECK_ACTION_RESULT_ALLOWED;
  277. }
  278. protected function _getVoteData()
  279. {
  280. $iValue = bx_get('value');
  281. if($iValue === false)
  282. return false;
  283. $iValue = bx_process_input($iValue, BX_DATA_INT);
  284. $iMinValue = $this->getMinValue();
  285. if($iValue < $iMinValue)
  286. $iValue = $iMinValue;
  287. $iMaxValue = $this->getMaxValue();
  288. if($iValue > $iMaxValue)
  289. $iValue = $iMaxValue;
  290. return array('value' => $iValue);
  291. }
  292. protected function _putVoteData($iObjectId, $iAuthorId, $iAuthorIp, $aData, $bPerformUndo)
  293. {
  294. return $this->_oQuery->putVote($iObjectId, $iAuthorId, $iAuthorIp, $aData, $bPerformUndo);
  295. }
  296. protected function _returnVoteData($iObjectId, $iAuthorId, $iAuthorIp, $aData, $bVoted, $aParams = [])
  297. {
  298. $bUndo = $this->isUndo();
  299. $aVote = $this->_getVote($iObjectId, true);
  300. $aResult = [
  301. 'code' => 0,
  302. 'rate' => $aVote['rate'],
  303. 'count' => $aVote['count'],
  304. 'countf' => (int)$aVote['count'] > 0 ? $this->_getCounterLabel($aVote['count'], $aParams) : '',
  305. 'label_use' => $this->_useIconAs($aParams),
  306. 'label_icon' => $this->_getIconDo($bVoted),
  307. 'label_emoji' => $this->_getEmojiDo($bVoted),
  308. 'label_image' => $this->_getImageDo($bVoted),
  309. 'label_title' => _t($this->_getTitleDo($bVoted)),
  310. 'voted' => $bVoted,
  311. 'disabled' => $bVoted && !$bUndo,
  312. ];
  313. $aResult['api'] = [
  314. 'ts' => microtime(true),
  315. 'performer_id' => $iAuthorId,
  316. 'is_voted' => $aResult['voted'],
  317. 'is_disabled' => $aResult['disabled'],
  318. 'value' => $aResult['voted'] ? $aData['value'] : 0,
  319. 'icon' => $aResult['label_emoji'],
  320. 'title' => $aResult['label_title'],
  321. 'counter' => $this->getVote()
  322. ];
  323. return $aResult;
  324. }
  325. protected function _returnVoteDataForSocket($aData, $aMask = [])
  326. {
  327. if(empty($aMask) || !is_array($aMask))
  328. $aMask = ['code', 'rate', 'count', 'countf', 'api'];
  329. return array_intersect_key($aData, array_flip($aMask));
  330. }
  331. protected function _prepareRequestParamsData($aParams, $aParamsAdd = array())
  332. {
  333. if(isset($aParams['is_voted']))
  334. $aParamsAdd['is_voted'] = $aParams['is_voted'];
  335. return parent::_prepareRequestParamsData($aParams, $aParamsAdd);
  336. }
  337. protected function _isVote($iObjectId = 0, $bForceGet = false)
  338. {
  339. $aVote = $this->_getVote($iObjectId, $bForceGet);
  340. return (int)$aVote['count'] > 0;
  341. }
  342. protected function _getIconDo($bVoted)
  343. {
  344. return '';
  345. }
  346. protected function _getImageDo($bVoted)
  347. {
  348. return '';
  349. }
  350. protected function _getEmojiDo($bVoted)
  351. {
  352. return '';
  353. }
  354. protected function _getTitleDo($bVoted)
  355. {
  356. return '';
  357. }
  358. protected function _getTitleDoBy($aParams = [])
  359. {
  360. return _t('_vote_do_by');
  361. }
  362. protected function _useIconAs($aParams = [])
  363. {
  364. return 'emoji';
  365. }
  366. }
  367. /** @} */