BxDolScore.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594
  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 BxDolObject
  75. {
  76. protected static $_sCounterStyleSimple = 'simple'; // total counter only.
  77. protected static $_sCounterStyleDivided = 'divided'; // counters [icon + counter] divided by action (up/down).
  78. protected $_aScore;
  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->_oQuery = new BxDolScoreQuery($this);
  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 = 'BxDolScore!' . $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 = 'BxTemplScore';
  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, $iInit, $oTemplate);
  111. return ($GLOBALS['bxDolClasses'][$sKey] = $o);
  112. }
  113. public static function &getSystems()
  114. {
  115. $sKey = 'bx_dol_cache_memory_score_systems';
  116. if(!isset($GLOBALS[$sKey]))
  117. $GLOBALS[$sKey] = BxDolDb::getInstance()->fromCache('sys_objects_score', 'getAllWithKey', '
  118. SELECT
  119. `id` as `id`,
  120. `name` AS `name`,
  121. `module` AS `module`,
  122. `table_main` AS `table_main`,
  123. `table_track` AS `table_track`,
  124. `post_timeout` AS `post_timeout`,
  125. `pruning` AS `pruning`,
  126. `is_undo` AS `is_undo`,
  127. `is_on` AS `is_on`,
  128. `trigger_table` AS `trigger_table`,
  129. `trigger_field_id` AS `trigger_field_id`,
  130. `trigger_field_author` AS `trigger_field_author`,
  131. `trigger_field_score` AS `trigger_field_score`,
  132. `trigger_field_cup` AS `trigger_field_cup`,
  133. `trigger_field_cdown` AS `trigger_field_cdown`,
  134. `class_name` AS `class_name`,
  135. `class_file` AS `class_file`
  136. FROM `sys_objects_score`', 'name');
  137. return $GLOBALS[$sKey];
  138. }
  139. public static function onAuthorDelete ($iAuthorId)
  140. {
  141. $aSystems = self::getSystems();
  142. foreach($aSystems as $sSystem => $aSystem)
  143. self::getObjectInstance($sSystem, 0)->getQueryObject()->deleteAuthorEntries($iAuthorId);
  144. return true;
  145. }
  146. public function isPerformed($iObjectId, $iAuthorId, $iAuthorIp = 0)
  147. {
  148. return parent::isPerformed($iObjectId, $iAuthorId) && !$this->_oQuery->isPostTimeoutEnded($iObjectId, $iAuthorId, $iAuthorIp);
  149. }
  150. public function getObjectAuthorId($iObjectId = 0)
  151. {
  152. if(empty($this->_aSystem['trigger_field_author']))
  153. return 0;
  154. return $this->_oQuery->getObjectAuthorId($iObjectId ? $iObjectId : $this->getId());
  155. }
  156. /**
  157. * Interface functions for outer usage
  158. */
  159. public function isUndo()
  160. {
  161. return (int)$this->_aSystem['is_undo'] == 1;
  162. }
  163. public function getStatCounterUp()
  164. {
  165. $aScore = $this->_getVote();
  166. return $aScore['count_up'];
  167. }
  168. public function getStatCounterDown()
  169. {
  170. $aScore = $this->_getVote();
  171. return $aScore['count_down'];
  172. }
  173. public function getStatScore()
  174. {
  175. $aScore = $this->_getVote();
  176. return $aScore['score'];
  177. }
  178. public function getSocketName()
  179. {
  180. return $this->_sSystem . '_scores';
  181. }
  182. /**
  183. * Actions functions
  184. */
  185. public function actionVoteUp()
  186. {
  187. if(!$this->isEnabled())
  188. return echoJson(array('code' => 1, 'message' => _t('_sys_score_err_not_enabled')));
  189. $aVoteData = ['type' => BX_DOL_SCORE_DO_UP];
  190. $aRequestParamsData = $this->_getRequestParamsData();
  191. return echoJson($this->vote($aVoteData, $aRequestParamsData));
  192. }
  193. public function actionVoteDown()
  194. {
  195. if(!$this->isEnabled())
  196. return echoJson(array('code' => 1, 'message' => _t('_sys_score_err_not_enabled')));
  197. $aVoteData = ['type' => BX_DOL_SCORE_DO_DOWN];
  198. $aRequestParamsData = $this->_getRequestParamsData();
  199. return echoJson($this->vote($aVoteData, $aRequestParamsData));
  200. }
  201. public function actionGetVotedBy()
  202. {
  203. if (!$this->isEnabled())
  204. return '';
  205. $aParams = $this->_getRequestParamsData();
  206. if(($sType = bx_get('type')) !== false) {
  207. $sType = bx_process_input($sType);
  208. if(in_array($sType, [BX_DOL_SCORE_DO_UP, BX_DOL_SCORE_DO_DOWN]))
  209. $aParams['type'] = $sType;
  210. }
  211. return $this->_getVotedBy($aParams);
  212. }
  213. public function vote($aVoteData = [], $aRequestParamsData = [])
  214. {
  215. if(!$this->isAllowedVote(true))
  216. return ['code' => BX_DOL_OBJECT_ERR_ACCESS_DENIED, 'message' => $this->msgErrAllowedVote()];
  217. $sType = $aVoteData['type'];
  218. $iObjectId = $this->getId();
  219. $iObjectAuthorId = $this->getObjectAuthorId($iObjectId);
  220. $iAuthorId = $this->_getAuthorId();
  221. $iAuthorIp = $this->_getAuthorIp();
  222. $bUndo = $this->isUndo();
  223. $bVoted = $this->isPerformed($iObjectId, $iAuthorId, $iAuthorIp);
  224. $bPerformUndo = $bVoted && $bUndo;
  225. if(!$bPerformUndo && !$this->isAllowedVote())
  226. return ['code' => BX_DOL_OBJECT_ERR_ACCESS_DENIED, 'message' => $this->msgErrAllowedVote()];
  227. if($bVoted && !$bUndo)
  228. return ['code' => BX_DOL_OBJECT_ERR_DUPLICATE, 'message' => _t('_sys_score_err_duplicate_vote')];
  229. if($bPerformUndo) {
  230. $aTrack = $this->_getTrack($iObjectId, $iAuthorId);
  231. if(!empty($aTrack) && is_array($aTrack))
  232. $aVoteData = array_intersect_key($aTrack, $aVoteData);
  233. }
  234. $iId = $this->_putVoteData($iObjectId, $iAuthorId, $iAuthorIp, $aVoteData, $bPerformUndo);
  235. if($iId === false)
  236. return ['code' => BX_DOL_OBJECT_ERR_CANNOT_PERFORM];
  237. if(!$bPerformUndo)
  238. $this->isAllowedVote(true);
  239. $this->_trigger();
  240. $sTypeUc = ucfirst($sType);
  241. /**
  242. * @hooks
  243. * @hookdef hook-bx_dol_score-doVoteUp '{object_name}', 'doVoteUp' - hook after score vote
  244. * - $unit_name - score object name
  245. * - $action - equals `doVoteUp`
  246. * - $object_id - object id which got a vote
  247. * - $sender_id - profile id who voted
  248. * - $extra_params - array of additional params with the following array keys:
  249. * - `score_id` - [int] vote id
  250. * - `score_author_id` - [int] profile id who voted
  251. * - `object_author_id` - [int] author id of the object which got a vote
  252. * @hook @ref hook-bx_dol_score-doVoteUp
  253. */
  254. /**
  255. * @hooks
  256. * @hookdef hook-bx_dol_score-doVoteDown '{object_name}', 'doVoteDown' - hook after score vote
  257. * It's equivalent to @ref hook-bx_dol_score-doVoteUp
  258. * @hook @ref hook-bx_dol_score-doVoteDown
  259. */
  260. /**
  261. * @hooks
  262. * @hookdef hook-bx_dol_score-undoVoteUp '{object_name}', 'undoVoteUp' - hook after undo score vote
  263. * It's equivalent to @ref hook-bx_dol_score-doVoteUp
  264. * @hook @ref hook-bx_dol_score-undoVoteUp
  265. */
  266. /**
  267. * @hooks
  268. * @hookdef hook-bx_dol_score-undoVoteDown '{object_name}', 'undoVoteDown' - hook after undo score vote
  269. * It's equivalent to @ref hook-bx_dol_score-doVoteUp
  270. * @hook @ref hook-bx_dol_score-undoVoteDown
  271. */
  272. bx_alert($this->_sSystem, ($bPerformUndo ? 'un' : '') . 'doVote' . $sTypeUc, $iObjectId, $iAuthorId, [
  273. 'score_id' => $iId,
  274. 'score_author_id' => $iAuthorId,
  275. 'object_author_id' => $iObjectAuthorId
  276. ]);
  277. /**
  278. * @hooks
  279. * @hookdef hook-score-doUp 'score', 'doUp' - hook after score vote
  280. * - $unit_name - equals `score`
  281. * - $action - equals `doUp`
  282. * - $object_id - score vote id
  283. * - $sender_id - profile id who voted
  284. * - $extra_params - array of additional params with the following array keys:
  285. * - `object_system` - [string] vote object name
  286. * - `object_id` - [int] object id which got a vote
  287. * - `object_author_id` - [int] author id of the object which got a vote
  288. * @hook @ref hook-score-doUp
  289. */
  290. /**
  291. * @hooks
  292. * @hookdef hook-score-doDown 'score', 'doDown' - hook after score vote
  293. * It's equivalent to @ref hook-score-doUp
  294. * @hook @ref hook-score-doDown
  295. */
  296. /**
  297. * @hooks
  298. * @hookdef hook-score-undoUp 'score', 'undoUp' - hook after undo score vote
  299. * It's equivalent to @ref hook-score-doUp
  300. * @hook @ref hook-score-undoUp
  301. */
  302. /**
  303. * @hooks
  304. * @hookdef hook-score-undoDown 'score', 'undoDown' - hook after undo score vote
  305. * It's equivalent to @ref hook-score-doUp
  306. * @hook @ref hook-score-undoDown
  307. */
  308. bx_alert('score', ($bPerformUndo ? 'un' : '') . 'do' . $sTypeUc, $iId, $iAuthorId, [
  309. 'object_system' => $this->_sSystem,
  310. 'object_id' => $iObjectId,
  311. 'object_author_id' => $iObjectAuthorId
  312. ]);
  313. $aRequestParamsData['show_script'] = false;
  314. $bVoted = !$bVoted;
  315. $aScore = $this->_getVote($iObjectId, true);
  316. $iCup = (int)$aScore['count_up'];
  317. $iCdown = (int)$aScore['count_down'];
  318. $aResult = [
  319. 'code' => 0,
  320. 'type' => $sType,
  321. 'score' => $aScore['score'],
  322. 'scoref' => $iCup > 0 || $iCdown > 0 ? $this->_getCounterLabel($aScore['score'], $aRequestParamsData) : '',
  323. 'cup' => $iCup,
  324. 'cdown' => $iCdown,
  325. 'counter' => $this->getCounter($aRequestParamsData),
  326. 'label_icon' => $this->_getIconDo($sType),
  327. 'label_title' => _t($this->_getTitleDo($sType)),
  328. 'voted' => $bVoted,
  329. 'disabled' => $bVoted && !$bUndo,
  330. ];
  331. $aResult['api'] = [
  332. 'performer_id' => $iAuthorId,
  333. 'is_voted' => $aResult['voted'],
  334. 'is_disabled' => $aResult['disabled'],
  335. $sType => [
  336. 'icon' => $aResult['label_icon'],
  337. 'title' => $aResult['label_title'],
  338. ],
  339. 'counter' => $this->getVote()
  340. ];
  341. if(($oSockets = BxDolSockets::getInstance()) && $oSockets->isEnabled())
  342. $oSockets->sendEvent($this->getSocketName(), $iObjectId, 'voted', json_encode($this->_returnVoteDataForSocket($aResult)));
  343. return $aResult;
  344. }
  345. /**
  346. * Permissions functions
  347. */
  348. public function isAllowedVote($isPerformAction = false)
  349. {
  350. if(isAdmin())
  351. return true;
  352. if(!$this->checkAction('vote', $isPerformAction))
  353. return false;
  354. $aObject = $this->_oQuery->getObjectInfo($this->_iId);
  355. if(empty($aObject) || !is_array($aObject))
  356. return false;
  357. return $this->_isAllowedVoteByObject($aObject);
  358. }
  359. public function msgErrAllowedVote()
  360. {
  361. $sMsg = $this->checkActionErrorMsg('vote');
  362. if(empty($sMsg))
  363. $sMsg = _t('_sys_txt_access_denied');
  364. return $sMsg;
  365. }
  366. public function isAllowedVoteView($isPerformAction = false)
  367. {
  368. if(isAdmin())
  369. return true;
  370. return $this->checkAction('vote_view', $isPerformAction);
  371. }
  372. public function msgErrAllowedVoteView()
  373. {
  374. return $this->checkActionErrorMsg('vote_view');
  375. }
  376. public function isAllowedVoteViewVoters($isPerformAction = false)
  377. {
  378. if(isAdmin())
  379. return true;
  380. return $this->checkAction('vote_view_voters', $isPerformAction);
  381. }
  382. public function msgErrAllowedVoteViewVoters()
  383. {
  384. return $this->checkActionErrorMsg('vote_view_voters');
  385. }
  386. /**
  387. * Internal functions
  388. */
  389. protected function _isAllowedVoteByObject($aObject)
  390. {
  391. return bx_srv($this->_aSystem['module'], 'check_allowed_view_for_profile', [$aObject]) === CHECK_ACTION_RESULT_ALLOWED;
  392. }
  393. protected function _putVoteData($iObjectId, $iAuthorId, $iAuthorIp, $aData, $bPerformUndo)
  394. {
  395. return $this->_oQuery->putVote($iObjectId, $iAuthorId, $iAuthorIp, $aData, $bPerformUndo);
  396. }
  397. protected function _returnVoteDataForSocket($aData, $aMask = [])
  398. {
  399. if(empty($aMask) || !is_array($aMask))
  400. $aMask = ['code', 'type', 'score', 'scoref', 'cup', 'cdown', 'counter', 'api'];
  401. return array_intersect_key($aData, array_flip($aMask));
  402. }
  403. protected function _getVote($iObjectId = 0, $bForceGet = false)
  404. {
  405. if(!empty($this->_aScore) && !$bForceGet)
  406. return $this->_aScore;
  407. if(empty($iObjectId))
  408. $iObjectId = $this->getId();
  409. $this->_aScore = $this->_oQuery->getScore($iObjectId);
  410. return $this->_aScore;
  411. }
  412. protected function _isVote($iObjectId = 0, $bForceGet = false)
  413. {
  414. $aScore = $this->_getVote($iObjectId, $bForceGet);
  415. return $this->_isCount($aScore);
  416. }
  417. protected function _isCount($aScore = [])
  418. {
  419. if(empty($aScore))
  420. $aScore = $this->_getVote();
  421. return (isset($aScore['count_up']) && (int)$aScore['count_up'] != 0) || (isset($aScore['count_down']) && (int)$aScore['count_down'] != 0);
  422. }
  423. protected function _getTrack($iObjectId, $iAuthorId)
  424. {
  425. return $this->_oQuery->getTrack($iObjectId, $iAuthorId);
  426. }
  427. /**
  428. * Note. By default image based controls aren't used.
  429. * Therefore it can be overwritten in custom template.
  430. */
  431. protected function _getImageDo($sType)
  432. {
  433. $sResult = '';
  434. switch($sType) {
  435. case BX_DOL_SCORE_DO_UP:
  436. $sResult = '';
  437. break;
  438. case BX_DOL_SCORE_DO_DOWN:
  439. $sResult = '';
  440. break;
  441. }
  442. return $sResult;
  443. }
  444. protected function _getIconDo($sType = '')
  445. {
  446. $sResult = '';
  447. switch($sType) {
  448. case BX_DOL_SCORE_DO_UP:
  449. $sResult = 'arrow-up';
  450. break;
  451. case BX_DOL_SCORE_DO_DOWN:
  452. $sResult = 'arrow-down';
  453. break;
  454. default:
  455. $sResult = 'arrows-alt-v';
  456. }
  457. return $sResult;
  458. }
  459. protected function _getTitleDo($sType)
  460. {
  461. $sResult = '';
  462. switch($sType) {
  463. case BX_DOL_SCORE_DO_UP:
  464. $sResult = '_sys_score_do_up';
  465. break;
  466. case BX_DOL_SCORE_DO_DOWN:
  467. $sResult = '_sys_score_do_down';
  468. break;
  469. }
  470. return $sResult;
  471. }
  472. protected function _getTitleDoBy()
  473. {
  474. return '_sys_score_do_by';
  475. }
  476. protected function _encodeElementParams($aParams)
  477. {
  478. if(empty($aParams) || !is_array($aParams))
  479. return '';
  480. return urlencode(base64_encode(serialize($aParams)));
  481. }
  482. protected function _decodeElementParams($sParams, $bMergeWithDefaults = true)
  483. {
  484. $aParams = array();
  485. if(!empty($sParams))
  486. $aParams = unserialize(base64_decode(urldecode($sParams)));
  487. if(empty($aParams) || !is_array($aParams))
  488. $aParams = array();
  489. if($bMergeWithDefaults)
  490. $aParams = array_merge($this->_aElementDefaults, $aParams);
  491. return $aParams;
  492. }
  493. }
  494. /** @} */