BxDolVote.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  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 BxDolObject
  76. {
  77. protected $_sType;
  78. protected $_aVote;
  79. protected $_aElementDefaults;
  80. protected $_aElementDefaultsApi;
  81. protected $_aElementParamsApi; //--- Params from DefaultsApi array to be passed to Api
  82. protected function __construct($sSystem, $iId, $iInit = true, $oTemplate = false)
  83. {
  84. parent::__construct($sSystem, $iId, $iInit, $oTemplate);
  85. if(empty($this->_sSystem))
  86. return;
  87. $this->_aVote = [];
  88. }
  89. /**
  90. * get votes object instanse
  91. * @param $sSys vote object name
  92. * @param $iId associated content id, where vote is available
  93. * @param $iInit perform initialization
  94. * @return null on error, or ready to use class instance
  95. */
  96. public static function getObjectInstance($sSys, $iId, $iInit = true, $oTemplate = false)
  97. {
  98. $sKey = 'BxDolVote!' . $sSys . $iId . ($oTemplate ? $oTemplate->getClassName() : '');
  99. if(isset($GLOBALS['bxDolClasses'][$sKey]))
  100. return $GLOBALS['bxDolClasses'][$sKey];
  101. $aSystems = self::getSystems();
  102. if(!isset($aSystems[$sSys]))
  103. return null;
  104. $sClassName = 'BxTemplVoteLikes';
  105. if(!empty($aSystems[$sSys]['class_name'])) {
  106. $sClassName = $aSystems[$sSys]['class_name'];
  107. if(!empty($aSystems[$sSys]['class_file']))
  108. require_once(BX_DIRECTORY_PATH_ROOT . $aSystems[$sSys]['class_file']);
  109. }
  110. $o = new $sClassName($sSys, $iId, false, $oTemplate);
  111. if($iInit && method_exists($o, 'init'))
  112. $o->init($iId);
  113. return ($GLOBALS['bxDolClasses'][$sKey] = $o);
  114. }
  115. public static function &getSystems()
  116. {
  117. $sKey = 'bx_dol_cache_memory_vote_systems';
  118. if(!isset($GLOBALS[$sKey]))
  119. $GLOBALS[$sKey] = BxDolDb::getInstance()->fromCache('sys_objects_vote', 'getAllWithKey', '
  120. SELECT
  121. `ID` as `id`,
  122. `Name` AS `name`,
  123. `Module` AS `module`,
  124. `TableMain` AS `table_main`,
  125. `TableTrack` AS `table_track`,
  126. `PostTimeout` AS `post_timeout`,
  127. `MinValue` AS `min_value`,
  128. `MaxValue` AS `max_value`,
  129. `Pruning` AS `pruning`,
  130. `IsUndo` AS `is_undo`,
  131. `IsOn` AS `is_on`,
  132. `TriggerTable` AS `trigger_table`,
  133. `TriggerFieldId` AS `trigger_field_id`,
  134. `TriggerFieldAuthor` AS `trigger_field_author`,
  135. `TriggerFieldRate` AS `trigger_field_rate`,
  136. `TriggerFieldRateCount` AS `trigger_field_count`,
  137. `ClassName` AS `class_name`,
  138. `ClassFile` AS `class_file`
  139. FROM `sys_objects_vote`', 'name');
  140. return $GLOBALS[$sKey];
  141. }
  142. public static function onAuthorDelete ($iAuthorId)
  143. {
  144. $aSystems = self::getSystems();
  145. foreach($aSystems as $sSystem => $aSystem)
  146. self::getObjectInstance($sSystem, 0)->getQueryObject()->deleteAuthorEntries($iAuthorId);
  147. return true;
  148. }
  149. public function getObjectAuthorId($iObjectId = 0)
  150. {
  151. if(empty($this->_aSystem['trigger_field_author']))
  152. return 0;
  153. return $this->_oQuery->getObjectAuthorId($iObjectId ? $iObjectId : $this->getId());
  154. }
  155. /**
  156. * Interface functions for outer usage
  157. */
  158. public function isUndo()
  159. {
  160. return (int)$this->_aSystem['is_undo'] == 1;
  161. }
  162. public function getType()
  163. {
  164. return $this->_sType;
  165. }
  166. public function getMinValue()
  167. {
  168. return (int)$this->_aSystem['min_value'];
  169. }
  170. public function getMaxValue()
  171. {
  172. return (int)$this->_aSystem['max_value'];
  173. }
  174. public function getStatCounter()
  175. {
  176. $aVote = $this->_getVote();
  177. return $aVote['count'];
  178. }
  179. public function getStatRate()
  180. {
  181. $aVote = $this->_getVote();
  182. return $aVote['rate'];
  183. }
  184. public function getSocketName()
  185. {
  186. return $this->_sSystem . '_' . $this->_sType;
  187. }
  188. /**
  189. * Actions functions
  190. */
  191. public function actionVote()
  192. {
  193. if(!$this->isEnabled())
  194. return echoJson(['code' => BX_DOL_OBJECT_ERR_NOT_AVAILABLE, 'message' => _t('_vote_err_not_enabled')]);
  195. $aVoteData = $this->_getVoteData();
  196. $aRequestParamsData = $this->_getRequestParamsData();
  197. if($aVoteData === false)
  198. return echoJson(['code' => BX_DOL_OBJECT_ERR_WRONG_DATE]);
  199. return echoJson($this->vote($aVoteData, $aRequestParamsData));
  200. }
  201. public function vote($aVoteData = [], $aRequestParamsData = [])
  202. {
  203. $iObjectId = $this->getId();
  204. $iObjectAuthorId = $this->getObjectAuthorId($iObjectId);
  205. $iAuthorId = $this->_getAuthorId();
  206. $iAuthorIp = $this->_getAuthorIp();
  207. $bUndo = $this->isUndo();
  208. $bVoted = $this->isPerformed($iObjectId, $iAuthorId);
  209. $bPerformUndo = $bVoted && $bUndo;
  210. if(!$bPerformUndo && !$this->isAllowedVote())
  211. return ['code' => BX_DOL_OBJECT_ERR_ACCESS_DENIED, 'message' => $this->msgErrAllowedVote()];
  212. if($this->_isDuplicate($iObjectId, $iAuthorId, $iAuthorIp, $bVoted))
  213. return ['code' => BX_DOL_OBJECT_ERR_DUPLICATE, 'message' => _t('_vote_err_duplicate_vote')];
  214. if($bPerformUndo) {
  215. $aTrack = $this->_getTrack($iObjectId, $iAuthorId);
  216. if(!empty($aTrack) && is_array($aTrack))
  217. $aVoteData = array_intersect_key($aTrack, $aVoteData);
  218. }
  219. $iId = $this->_putVoteData($iObjectId, $iAuthorId, $iAuthorIp, $aVoteData, $bPerformUndo);
  220. if($iId === false)
  221. return ['code' => BX_DOL_OBJECT_ERR_CANNOT_PERFORM];
  222. if(!$bPerformUndo)
  223. $this->isAllowedVote(true);
  224. $this->_trigger();
  225. /**
  226. * @hooks
  227. * @hookdef hook-vote-undo 'vote', 'undo' - hook on cancel vote
  228. * - $unit_name - equals `vote`
  229. * - $action - equals `undo`
  230. * - $object_id - vote id
  231. * - $sender_id - profile_id for vote's author
  232. * - $extra_params - array of additional params with the following array keys:
  233. * - `object_system` - [string] system name, ex: bx_posts
  234. * - `object_id` - [int] reported object id
  235. * - `object_author_id` - [int] author's profile_id for reported object_id
  236. * @hook @ref hook-vote-undo
  237. */
  238. bx_alert($this->_sSystem, ($bPerformUndo ? 'un' : '') . 'doVote', $iObjectId, $iAuthorId, array_merge(['vote_id' => $iId, 'vote_author_id' => $iAuthorId, 'object_author_id' => $iObjectAuthorId], $aVoteData));
  239. /**
  240. * @hooks
  241. * @hookdef hook-vote-do 'vote', 'do' - hook on new vote
  242. * - $unit_name - equals `vote`
  243. * - $action - equals `do`
  244. * - $object_id - vote id
  245. * - $sender_id - profile_id for vote's author
  246. * - $extra_params - array of additional params with the following array keys:
  247. * - `object_system` - [string] system name, ex: bx_posts
  248. * - `object_id` - [int] reported object id
  249. * - `object_author_id` - [int] author's profile_id for reported object_id
  250. * @hook @ref hook-vote-do
  251. */
  252. bx_alert('vote', ($bPerformUndo ? 'un' : '') . 'do', $iId, $iAuthorId, array_merge(['object_system' => $this->_sSystem, 'object_id' => $iObjectId, 'object_author_id' => $iObjectAuthorId], $aVoteData));
  253. $aResult = $this->_returnVoteData($iObjectId, $iAuthorId, $iAuthorIp, $aVoteData, !$bVoted, $aRequestParamsData);
  254. if(($oSockets = BxDolSockets::getInstance()) && $oSockets->isEnabled())
  255. $oSockets->sendEvent($this->getSocketName(), $iObjectId, 'voted', json_encode($this->_returnVoteDataForSocket($aResult)));
  256. return $aResult;
  257. }
  258. public function actionGetVotedBy()
  259. {
  260. if (!$this->isEnabled())
  261. return '';
  262. return $this->_getVotedBy();
  263. }
  264. /**
  265. * Permissions functions
  266. */
  267. public function isAllowedVote($isPerformAction = false)
  268. {
  269. if(isAdmin())
  270. return true;
  271. if(!$this->checkAction('vote', $isPerformAction))
  272. return false;
  273. $aObject = $this->_oQuery->getObjectInfo($this->_iId);
  274. if(empty($aObject) || !is_array($aObject))
  275. return false;
  276. return $this->_isAllowedVoteByObject($aObject);
  277. }
  278. public function msgErrAllowedVote()
  279. {
  280. $sMsg = $this->checkActionErrorMsg('vote');
  281. if(empty($sMsg))
  282. $sMsg = _t('_sys_txt_access_denied');
  283. return $sMsg;
  284. }
  285. public function isAllowedVoteView($isPerformAction = false)
  286. {
  287. if(isAdmin())
  288. return true;
  289. return $this->checkAction('vote_view', $isPerformAction);
  290. }
  291. public function msgErrAllowedVoteView()
  292. {
  293. return $this->checkActionErrorMsg('vote_view');
  294. }
  295. public function isAllowedVoteViewVoters($isPerformAction = false)
  296. {
  297. if(isAdmin())
  298. return true;
  299. return $this->checkAction('vote_view_voters', $isPerformAction);
  300. }
  301. public function msgErrAllowedVoteViewVoters()
  302. {
  303. return $this->checkActionErrorMsg('vote_view_voters');
  304. }
  305. /**
  306. * Internal functions
  307. */
  308. protected function _isDuplicate($iObjectId, $iAuthorId, $iAuthorIp, $bVoted)
  309. {
  310. return false;
  311. }
  312. protected function _isCount($aVote = array())
  313. {
  314. if(empty($aVote))
  315. $aVote = $this->_getVote();
  316. return isset($aVote['count']) && (int)$aVote['count'] != 0;
  317. }
  318. protected function _isAllowedVoteByObject($aObject)
  319. {
  320. return bx_srv($this->_aSystem['module'], 'check_allowed_view_for_profile', [$aObject]) === CHECK_ACTION_RESULT_ALLOWED;
  321. }
  322. protected function _getVoteData()
  323. {
  324. $iValue = bx_get('value');
  325. if($iValue === false)
  326. return false;
  327. $iValue = bx_process_input($iValue, BX_DATA_INT);
  328. $iMinValue = $this->getMinValue();
  329. if($iValue < $iMinValue)
  330. $iValue = $iMinValue;
  331. $iMaxValue = $this->getMaxValue();
  332. if($iValue > $iMaxValue)
  333. $iValue = $iMaxValue;
  334. return array('value' => $iValue);
  335. }
  336. protected function _putVoteData($iObjectId, $iAuthorId, $iAuthorIp, $aData, $bPerformUndo)
  337. {
  338. return $this->_oQuery->putVote($iObjectId, $iAuthorId, $iAuthorIp, $aData, $bPerformUndo);
  339. }
  340. protected function _returnVoteData($iObjectId, $iAuthorId, $iAuthorIp, $aData, $bVoted, $aParams = [])
  341. {
  342. $bUndo = $this->isUndo();
  343. $aVote = $this->_getVote($iObjectId, true);
  344. $aResult = [
  345. 'code' => 0,
  346. 'rate' => $aVote['rate'],
  347. 'count' => $aVote['count'],
  348. 'countf' => (int)$aVote['count'] > 0 ? $this->_getCounterLabel($aVote['count'], $aParams) : '',
  349. 'label_use' => $this->_useIconAs($aParams),
  350. 'label_icon' => $this->_getIconDo($bVoted),
  351. 'label_emoji' => $this->_getEmojiDo($bVoted),
  352. 'label_image' => $this->_getImageDo($bVoted),
  353. 'label_title' => _t($this->_getTitleDo($bVoted)),
  354. 'voted' => $bVoted,
  355. 'disabled' => $bVoted && !$bUndo,
  356. ];
  357. $aResult['api'] = [
  358. 'performer_id' => $iAuthorId,
  359. 'is_voted' => $aResult['voted'],
  360. 'is_disabled' => $aResult['disabled'],
  361. 'value' => $aResult['voted'] ? $aData['value'] : 0,
  362. 'icon' => $aResult['label_emoji'],
  363. 'title' => $aResult['label_title'],
  364. 'counter' => $this->getVote()
  365. ];
  366. return $aResult;
  367. }
  368. protected function _returnVoteDataForSocket($aData, $aMask = [])
  369. {
  370. if(empty($aMask) || !is_array($aMask))
  371. $aMask = ['code', 'rate', 'count', 'countf', 'api'];
  372. return array_intersect_key($aData, array_flip($aMask));
  373. }
  374. protected function _prepareRequestParamsData($aParams, $aParamsAdd = array())
  375. {
  376. if(isset($aParams['is_voted']))
  377. $aParamsAdd['is_voted'] = $aParams['is_voted'];
  378. return parent::_prepareRequestParamsData($aParams, $aParamsAdd);
  379. }
  380. protected function _getVote($iObjectId = 0, $bForceGet = false)
  381. {
  382. if(!empty($this->_aVote) && !$bForceGet)
  383. return $this->_aVote;
  384. if(empty($iObjectId))
  385. $iObjectId = $this->getId();
  386. $this->_aVote = $this->_oQuery->getVote($iObjectId);
  387. return $this->_aVote;
  388. }
  389. protected function _isVote($iObjectId = 0, $bForceGet = false)
  390. {
  391. $aVote = $this->_getVote($iObjectId, $bForceGet);
  392. return (int)$aVote['count'] > 0;
  393. }
  394. protected function _getTrack($iObjectId, $iAuthorId)
  395. {
  396. return $this->_oQuery->getTrack($iObjectId, $iAuthorId);
  397. }
  398. protected function _getIconDo($bVoted)
  399. {
  400. return '';
  401. }
  402. protected function _getImageDo($bVoted)
  403. {
  404. return '';
  405. }
  406. protected function _getEmojiDo($bVoted)
  407. {
  408. return '';
  409. }
  410. protected function _getTitleDo($bVoted)
  411. {
  412. return '';
  413. }
  414. protected function _getTitleDoBy($aParams = [])
  415. {
  416. return _t('_vote_do_by');
  417. }
  418. protected function _useIconAs($aParams = [])
  419. {
  420. return 'emoji';
  421. }
  422. }
  423. /** @} */