BxDolScore.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  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_SCORE_USAGE_BLOCK', 'block');
  11. define('BX_DOL_SCORE_USAGE_INLINE', 'inline');
  12. define('BX_DOL_SCORE_USAGE_DEFAULT', BX_DOL_SCORE_USAGE_BLOCK);
  13. define('BX_DOL_SCORE_DO_UP', 'up');
  14. define('BX_DOL_SCORE_DO_DOWN', 'down');
  15. /**
  16. * Score for any content
  17. *
  18. * Related classes:
  19. * - BxDolScoreQuery - vote database queries
  20. * - BxBaseScore - vote base representation
  21. * - BxTemplScore - custom template representation
  22. *
  23. * AJAX vote for any content. Stars and Plus based representations are supported.
  24. *
  25. * To add vote section to your feature you need to add a record to 'sys_objects_vote' table:
  26. *
  27. * - ID - autoincremented id for internal usage
  28. * - Name - your unique module name, with vendor prefix, lowercase and spaces are underscored
  29. * - TableMain - table name where summary votigs are stored
  30. * - TableTrack - table name where each vote is stored
  31. * - PostTimeout - number of seconds to not allow duplicate vote
  32. * - MinValue - min vote value, 1 by default
  33. * - MaxValue - max vote value, 5 by default
  34. * - IsUndo - is Undo enabled for Plus based votes
  35. * - IsOn - is this vote object enabled
  36. * - TriggerTable - table to be updated upon each vote
  37. * - TriggerFieldId - TriggerTable table field with unique record id, primary key
  38. * - TriggerFieldRate - TriggerTable table field with average rate
  39. * - TriggerFieldRateCount - TriggerTable table field with votes count
  40. * - ClassName - your custom class name, if you overrride default class
  41. * - ClassFile - your custom class path
  42. *
  43. * You can refer to BoonEx modules for sample record in this table.
  44. *
  45. *
  46. *
  47. * @section example Example of usage:
  48. * To get Star based vote you need to have different values for MinValue and MaxValue (for example 1 and 5)
  49. * and IsUndo should be equal to 0. To get Plus(Like) based vote you need to have equal values
  50. * for MinValue and MaxValue (for example 1) and IsUndo should be equal to 1. After filling the other
  51. * paramenters in the table you can show vote in any place, using the following code:
  52. * @code
  53. * $o = BxDolScore::getObjectInstance('system object name', $iYourEntryId);
  54. * if (!$o->isEnabled()) return '';
  55. * echo $o->getElementBlock();
  56. * @endcode
  57. *
  58. *
  59. * @section acl Memberships/ACL:
  60. * - vote
  61. *
  62. *
  63. *
  64. * @section alerts Alerts:
  65. * Alerts type/unit - every module has own type/unit, it equals to ObjectName.
  66. * The following alerts are rised:
  67. *
  68. * - rate - comment was posted
  69. * - $iObjectId - entry id
  70. * - $iSenderId - rater user id
  71. * - $aExtra['rate'] - rate
  72. *
  73. */
  74. class BxDolScore extends BxDolObjectVote
  75. {
  76. protected static $_sCounterStyleSimple = 'simple'; // total counter only.
  77. protected static $_sCounterStyleDivided = 'divided'; // counters [icon + counter] divided by action (up/down).
  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. $this->_oQuery = new BxDolScoreQuery($this);
  84. }
  85. /**
  86. * get votes object instanse
  87. * @param $sSys vote object name
  88. * @param $iId associated content id, where vote is available
  89. * @param $iInit perform initialization
  90. * @return null on error, or ready to use class instance
  91. */
  92. public static function getObjectInstance($sSys, $iId, $iInit = true, $oTemplate = false)
  93. {
  94. $sKey = 'BxDolScore!' . $sSys . $iId . ($oTemplate ? $oTemplate->getClassName() : '');
  95. if(isset($GLOBALS['bxDolClasses'][$sKey]))
  96. return $GLOBALS['bxDolClasses'][$sKey];
  97. $aSystems = self::getSystems();
  98. if(!isset($aSystems[$sSys]))
  99. return null;
  100. $sClassName = 'BxTemplScore';
  101. if(!empty($aSystems[$sSys]['class_name'])) {
  102. $sClassName = $aSystems[$sSys]['class_name'];
  103. if(!empty($aSystems[$sSys]['class_file']))
  104. require_once(BX_DIRECTORY_PATH_ROOT . $aSystems[$sSys]['class_file']);
  105. }
  106. $o = new $sClassName($sSys, $iId, $iInit, $oTemplate);
  107. return ($GLOBALS['bxDolClasses'][$sKey] = $o);
  108. }
  109. public static function &getSystems()
  110. {
  111. $sKey = 'bx_dol_cache_memory_score_systems';
  112. if(!isset($GLOBALS[$sKey]))
  113. $GLOBALS[$sKey] = BxDolDb::getInstance()->fromCache('sys_objects_score', 'getAllWithKey', '
  114. SELECT
  115. `id` as `id`,
  116. `name` AS `name`,
  117. `module` AS `module`,
  118. `table_main` AS `table_main`,
  119. `table_track` AS `table_track`,
  120. `post_timeout` AS `post_timeout`,
  121. `pruning` AS `pruning`,
  122. `is_undo` AS `is_undo`,
  123. `is_on` AS `is_on`,
  124. `trigger_table` AS `trigger_table`,
  125. `trigger_field_id` AS `trigger_field_id`,
  126. `trigger_field_author` AS `trigger_field_author`,
  127. `trigger_field_score` AS `trigger_field_score`,
  128. `trigger_field_cup` AS `trigger_field_cup`,
  129. `trigger_field_cdown` AS `trigger_field_cdown`,
  130. `class_name` AS `class_name`,
  131. `class_file` AS `class_file`
  132. FROM `sys_objects_score`', 'name');
  133. return $GLOBALS[$sKey];
  134. }
  135. public function isPerformed($iObjectId, $iAuthorId, $iAuthorIp = 0)
  136. {
  137. return parent::isPerformed($iObjectId, $iAuthorId) && !$this->_oQuery->isPostTimeoutEnded($iObjectId, $iAuthorId, $iAuthorIp);
  138. }
  139. /**
  140. * Interface functions for outer usage
  141. */
  142. public function getStatCounterUp()
  143. {
  144. $aScore = $this->_getVote();
  145. return $aScore['count_up'];
  146. }
  147. public function getStatCounterDown()
  148. {
  149. $aScore = $this->_getVote();
  150. return $aScore['count_down'];
  151. }
  152. public function getStatScore()
  153. {
  154. $aScore = $this->_getVote();
  155. return $aScore['score'];
  156. }
  157. public function getSocketName()
  158. {
  159. return $this->_sSystem . '_scores';
  160. }
  161. /**
  162. * Actions functions
  163. */
  164. public function actionVoteUp()
  165. {
  166. if(!$this->isEnabled())
  167. return echoJson(array('code' => 1, 'message' => _t('_sys_score_err_not_enabled')));
  168. $aVoteData = ['type' => BX_DOL_SCORE_DO_UP];
  169. $aRequestParamsData = $this->_getRequestParamsData();
  170. return echoJson($this->vote($aVoteData, $aRequestParamsData));
  171. }
  172. public function actionVoteDown()
  173. {
  174. if(!$this->isEnabled())
  175. return echoJson(array('code' => 1, 'message' => _t('_sys_score_err_not_enabled')));
  176. $aVoteData = ['type' => BX_DOL_SCORE_DO_DOWN];
  177. $aRequestParamsData = $this->_getRequestParamsData();
  178. return echoJson($this->vote($aVoteData, $aRequestParamsData));
  179. }
  180. public function actionGetVotedBy()
  181. {
  182. if (!$this->isEnabled())
  183. return '';
  184. $aParams = $this->_getRequestParamsData();
  185. if(($sType = bx_get('type')) !== false) {
  186. $sType = bx_process_input($sType);
  187. if(in_array($sType, [BX_DOL_SCORE_DO_UP, BX_DOL_SCORE_DO_DOWN]))
  188. $aParams['type'] = $sType;
  189. }
  190. return $this->_getVotedBy($aParams);
  191. }
  192. public function vote($aVoteData = [], $aRequestParamsData = [])
  193. {
  194. if(!$this->isAllowedVote(true))
  195. return ['code' => BX_DOL_OBJECT_ERR_ACCESS_DENIED, 'message' => $this->msgErrAllowedVote()];
  196. $sType = $aVoteData['type'];
  197. $iObjectId = $this->getId();
  198. $iObjectAuthorId = $this->getObjectAuthorId($iObjectId);
  199. $iAuthorId = $this->_getAuthorId();
  200. $iAuthorIp = $this->_getAuthorIp();
  201. $bUndo = $this->isUndo();
  202. $bVoted = $this->isPerformed($iObjectId, $iAuthorId, $iAuthorIp);
  203. $bPerformUndo = $bVoted && $bUndo;
  204. if(!$bPerformUndo && !$this->isAllowedVote())
  205. return ['code' => BX_DOL_OBJECT_ERR_ACCESS_DENIED, 'message' => $this->msgErrAllowedVote()];
  206. if($bVoted && !$bUndo)
  207. return ['code' => BX_DOL_OBJECT_ERR_DUPLICATE, 'message' => _t('_sys_score_err_duplicate_vote')];
  208. if($bPerformUndo) {
  209. $aTrack = $this->_getTrack($iObjectId, $iAuthorId);
  210. if(!empty($aTrack) && is_array($aTrack))
  211. $aVoteData = array_intersect_key($aTrack, $aVoteData);
  212. }
  213. $iId = $this->_putVoteData($iObjectId, $iAuthorId, $iAuthorIp, $aVoteData, $bPerformUndo);
  214. if($iId === false)
  215. return ['code' => BX_DOL_OBJECT_ERR_CANNOT_PERFORM];
  216. if(!$bPerformUndo)
  217. $this->isAllowedVote(true);
  218. $this->_trigger();
  219. $sTypeUc = ucfirst($sType);
  220. $aAlertExtras = [
  221. 'object_author_id' => $iObjectAuthorId,
  222. 'source' => 'sys_score_' . $iId,
  223. 'source_mac' => 'sys_score_' . $iAuthorId . '_' . $iId,
  224. ];
  225. /**
  226. * @hooks
  227. * @hookdef hook-bx_dol_score-doVoteUp '{object_name}', 'doVoteUp' - hook after score vote
  228. * - $unit_name - score object name
  229. * - $action - equals `doVoteUp`
  230. * - $object_id - object id which got a vote
  231. * - $sender_id - profile id who voted
  232. * - $extra_params - array of additional params with the following array keys:
  233. * - `score_id` - [int] vote id
  234. * - `score_author_id` - [int] profile id who voted
  235. * - `object_author_id` - [int] author id of the object which got a vote
  236. * @hook @ref hook-bx_dol_score-doVoteUp
  237. */
  238. /**
  239. * @hooks
  240. * @hookdef hook-bx_dol_score-doVoteDown '{object_name}', 'doVoteDown' - hook after score vote
  241. * It's equivalent to @ref hook-bx_dol_score-doVoteUp
  242. * @hook @ref hook-bx_dol_score-doVoteDown
  243. */
  244. /**
  245. * @hooks
  246. * @hookdef hook-bx_dol_score-undoVoteUp '{object_name}', 'undoVoteUp' - hook after undo score vote
  247. * It's equivalent to @ref hook-bx_dol_score-doVoteUp
  248. * @hook @ref hook-bx_dol_score-undoVoteUp
  249. */
  250. /**
  251. * @hooks
  252. * @hookdef hook-bx_dol_score-undoVoteDown '{object_name}', 'undoVoteDown' - hook after undo score vote
  253. * It's equivalent to @ref hook-bx_dol_score-doVoteUp
  254. * @hook @ref hook-bx_dol_score-undoVoteDown
  255. */
  256. bx_alert($this->_sSystem, ($bPerformUndo ? 'un' : '') . 'doVote' . $sTypeUc, $iObjectId, $iAuthorId, array_merge([
  257. 'score_id' => $iId,
  258. 'score_author_id' => $iAuthorId
  259. ], $aAlertExtras));
  260. /**
  261. * @hooks
  262. * @hookdef hook-score-doUp 'score', 'doUp' - hook after score vote
  263. * - $unit_name - equals `score`
  264. * - $action - equals `doUp`
  265. * - $object_id - score vote id
  266. * - $sender_id - profile id who voted
  267. * - $extra_params - array of additional params with the following array keys:
  268. * - `object_system` - [string] vote object name
  269. * - `object_id` - [int] object id which got a vote
  270. * - `object_author_id` - [int] author id of the object which got a vote
  271. * @hook @ref hook-score-doUp
  272. */
  273. /**
  274. * @hooks
  275. * @hookdef hook-score-doDown 'score', 'doDown' - hook after score vote
  276. * It's equivalent to @ref hook-score-doUp
  277. * @hook @ref hook-score-doDown
  278. */
  279. /**
  280. * @hooks
  281. * @hookdef hook-score-undoUp 'score', 'undoUp' - hook after undo score vote
  282. * It's equivalent to @ref hook-score-doUp
  283. * @hook @ref hook-score-undoUp
  284. */
  285. /**
  286. * @hooks
  287. * @hookdef hook-score-undoDown 'score', 'undoDown' - hook after undo score vote
  288. * It's equivalent to @ref hook-score-doUp
  289. * @hook @ref hook-score-undoDown
  290. */
  291. bx_alert('score', ($bPerformUndo ? 'un' : '') . 'do' . $sTypeUc, $iId, $iAuthorId, array_merge([
  292. 'object_system' => $this->_sSystem,
  293. 'object_id' => $iObjectId
  294. ], $aAlertExtras));
  295. $aRequestParamsData['show_script'] = false;
  296. $bVoted = !$bVoted;
  297. $aScore = $this->_getVote($iObjectId, true);
  298. $iCup = (int)$aScore['count_up'];
  299. $iCdown = (int)$aScore['count_down'];
  300. $aResult = [
  301. 'code' => 0,
  302. 'type' => $sType,
  303. 'score' => $aScore['score'],
  304. 'scoref' => $iCup > 0 || $iCdown > 0 ? $this->_getCounterLabel($aScore['score'], $aRequestParamsData) : '',
  305. 'cup' => $iCup,
  306. 'cdown' => $iCdown,
  307. 'counter' => $this->getCounter($aRequestParamsData),
  308. 'label_icon' => $this->_getIconDo($sType),
  309. 'label_title' => _t($this->_getTitleDo($sType)),
  310. 'voted' => $bVoted,
  311. 'disabled' => $bVoted && !$bUndo,
  312. ];
  313. $aResult['api'] = [
  314. 'ts' => microtime(true),
  315. 'performer_id' => $iAuthorId,
  316. 'is_voted' => $aResult['voted'], //TODO: Remove after 14.0.0-RC3 is released.
  317. 'is_disabled' => $aResult['disabled'], //TODO: Remove after 14.0.0-RC3 is released.
  318. $sType => [
  319. 'is_voted' => $aResult['voted'],
  320. 'is_disabled' => $aResult['disabled'],
  321. 'icon' => $aResult['label_icon'],
  322. 'title' => $aResult['label_title'],
  323. ],
  324. 'counter' => $this->getVote()
  325. ];
  326. if(($oSockets = BxDolSockets::getInstance()) && $oSockets->isEnabled())
  327. $oSockets->sendEvent($this->getSocketName(), $iObjectId, 'voted', json_encode($this->_returnVoteDataForSocket($aResult)));
  328. return $aResult;
  329. }
  330. /**
  331. * Internal functions
  332. */
  333. protected function _isAllowedVoteByObject($aObject)
  334. {
  335. return bx_srv($this->_aSystem['module'], 'check_allowed_view_for_profile', [$aObject]) === CHECK_ACTION_RESULT_ALLOWED;
  336. }
  337. protected function _putVoteData($iObjectId, $iAuthorId, $iAuthorIp, $aData, $bPerformUndo)
  338. {
  339. return $this->_oQuery->putVote($iObjectId, $iAuthorId, $iAuthorIp, $aData, $bPerformUndo);
  340. }
  341. protected function _returnVoteDataForSocket($aData, $aMask = [])
  342. {
  343. if(empty($aMask) || !is_array($aMask))
  344. $aMask = ['code', 'type', 'score', 'scoref', 'cup', 'cdown', 'counter', 'api'];
  345. return array_intersect_key($aData, array_flip($aMask));
  346. }
  347. protected function _isVote($iObjectId = 0, $bForceGet = false)
  348. {
  349. $aScore = $this->_getVote($iObjectId, $bForceGet);
  350. return $this->_isCount($aScore);
  351. }
  352. protected function _isCount($aScore = [])
  353. {
  354. if(empty($aScore))
  355. $aScore = $this->_getVote();
  356. return (isset($aScore['count_up']) && (int)$aScore['count_up'] != 0) || (isset($aScore['count_down']) && (int)$aScore['count_down'] != 0);
  357. }
  358. /**
  359. * Note. By default image based controls aren't used.
  360. * Therefore it can be overwritten in custom template.
  361. */
  362. protected function _getImageDo($sType)
  363. {
  364. $sResult = '';
  365. switch($sType) {
  366. case BX_DOL_SCORE_DO_UP:
  367. $sResult = '';
  368. break;
  369. case BX_DOL_SCORE_DO_DOWN:
  370. $sResult = '';
  371. break;
  372. }
  373. return $sResult;
  374. }
  375. protected function _getIconDo($sType = '')
  376. {
  377. $sResult = '';
  378. switch($sType) {
  379. case BX_DOL_SCORE_DO_UP:
  380. $sResult = 'arrow-up';
  381. break;
  382. case BX_DOL_SCORE_DO_DOWN:
  383. $sResult = 'arrow-down';
  384. break;
  385. default:
  386. $sResult = 'arrows-alt-v';
  387. }
  388. return $sResult;
  389. }
  390. protected function _getTitleDo($sType)
  391. {
  392. $sResult = '';
  393. switch($sType) {
  394. case BX_DOL_SCORE_DO_UP:
  395. $sResult = '_sys_score_do_up';
  396. break;
  397. case BX_DOL_SCORE_DO_DOWN:
  398. $sResult = '_sys_score_do_down';
  399. break;
  400. }
  401. return $sResult;
  402. }
  403. protected function _getTitleDoBy()
  404. {
  405. return '_sys_score_do_by';
  406. }
  407. protected function _encodeElementParams($aParams)
  408. {
  409. if(empty($aParams) || !is_array($aParams))
  410. return '';
  411. return urlencode(base64_encode(json_encode($aParams)));
  412. }
  413. protected function _decodeElementParams($sParams, $bMergeWithDefaults = true)
  414. {
  415. $aParams = array();
  416. if(!empty($sParams))
  417. $aParams = json_decode(base64_decode(urldecode($sParams)), true);
  418. if(empty($aParams) || !is_array($aParams))
  419. $aParams = array();
  420. if($bMergeWithDefaults)
  421. $aParams = array_merge($this->_aElementDefaults, $aParams);
  422. return $aParams;
  423. }
  424. }
  425. /** @} */