BxDolScore.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  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 $_aScore;
  77. protected $_aElementDefaults;
  78. protected $_aElementDefaultsApi;
  79. protected $_aElementParamsApi; //--- Params from DefaultsApi array to be passed to Api
  80. protected function __construct($sSystem, $iId, $iInit = true, $oTemplate = false)
  81. {
  82. parent::__construct($sSystem, $iId, $iInit, $oTemplate);
  83. if(empty($this->_sSystem))
  84. return;
  85. $this->_oQuery = new BxDolScoreQuery($this);
  86. }
  87. /**
  88. * get votes object instanse
  89. * @param $sSys vote object name
  90. * @param $iId associated content id, where vote is available
  91. * @param $iInit perform initialization
  92. * @return null on error, or ready to use class instance
  93. */
  94. public static function getObjectInstance($sSys, $iId, $iInit = true, $oTemplate = false)
  95. {
  96. $sKey = 'BxDolScore!' . $sSys . $iId . ($oTemplate ? $oTemplate->getClassName() : '');
  97. if(isset($GLOBALS['bxDolClasses'][$sKey]))
  98. return $GLOBALS['bxDolClasses'][$sKey];
  99. $aSystems = self::getSystems();
  100. if(!isset($aSystems[$sSys]))
  101. return null;
  102. $sClassName = 'BxTemplScore';
  103. if(!empty($aSystems[$sSys]['class_name'])) {
  104. $sClassName = $aSystems[$sSys]['class_name'];
  105. if(!empty($aSystems[$sSys]['class_file']))
  106. require_once(BX_DIRECTORY_PATH_ROOT . $aSystems[$sSys]['class_file']);
  107. }
  108. $o = new $sClassName($sSys, $iId, $iInit, $oTemplate);
  109. return ($GLOBALS['bxDolClasses'][$sKey] = $o);
  110. }
  111. public static function &getSystems()
  112. {
  113. $sKey = 'bx_dol_cache_memory_score_systems';
  114. if(!isset($GLOBALS[$sKey]))
  115. $GLOBALS[$sKey] = BxDolDb::getInstance()->fromCache('sys_objects_score', 'getAllWithKey', '
  116. SELECT
  117. `id` as `id`,
  118. `name` AS `name`,
  119. `module` AS `module`,
  120. `table_main` AS `table_main`,
  121. `table_track` AS `table_track`,
  122. `post_timeout` AS `post_timeout`,
  123. `pruning` AS `pruning`,
  124. `is_on` AS `is_on`,
  125. `trigger_table` AS `trigger_table`,
  126. `trigger_field_id` AS `trigger_field_id`,
  127. `trigger_field_author` AS `trigger_field_author`,
  128. `trigger_field_score` AS `trigger_field_score`,
  129. `trigger_field_cup` AS `trigger_field_cup`,
  130. `trigger_field_cdown` AS `trigger_field_cdown`,
  131. `class_name` AS `class_name`,
  132. `class_file` AS `class_file`
  133. FROM `sys_objects_score`', 'name');
  134. return $GLOBALS[$sKey];
  135. }
  136. public static function onAuthorDelete ($iAuthorId)
  137. {
  138. $aSystems = self::getSystems();
  139. foreach($aSystems as $sSystem => $aSystem)
  140. self::getObjectInstance($sSystem, 0)->getQueryObject()->deleteAuthorEntries($iAuthorId);
  141. return true;
  142. }
  143. public function isPerformed($iObjectId, $iAuthorId, $iAuthorIp = 0)
  144. {
  145. return parent::isPerformed($iObjectId, $iAuthorId) && !$this->_oQuery->isPostTimeoutEnded($iObjectId, $iAuthorId, $iAuthorIp);
  146. }
  147. public function getObjectAuthorId($iObjectId = 0)
  148. {
  149. if(empty($this->_aSystem['trigger_field_author']))
  150. return 0;
  151. return $this->_oQuery->getObjectAuthorId($iObjectId ? $iObjectId : $this->getId());
  152. }
  153. /**
  154. * Interface functions for outer usage
  155. */
  156. public function getStatCounterUp()
  157. {
  158. $aScore = $this->_getVote();
  159. return $aScore['count_up'];
  160. }
  161. public function getStatCounterDown()
  162. {
  163. $aScore = $this->_getVote();
  164. return $aScore['count_down'];
  165. }
  166. public function getStatScore()
  167. {
  168. $aScore = $this->_getVote();
  169. return $aScore['score'];
  170. }
  171. public function getSocketName()
  172. {
  173. return $this->_sSystem . '_scores';
  174. }
  175. /**
  176. * Actions functions
  177. */
  178. public function actionVoteUp()
  179. {
  180. if(!$this->isEnabled())
  181. return echoJson(array('code' => 1, 'message' => _t('_sys_score_err_not_enabled')));
  182. $aVoteData = ['type' => BX_DOL_SCORE_DO_UP];
  183. $aRequestParamsData = $this->_getRequestParamsData();
  184. return echoJson($this->vote($aVoteData, $aRequestParamsData));
  185. }
  186. public function actionVoteDown()
  187. {
  188. if(!$this->isEnabled())
  189. return echoJson(array('code' => 1, 'message' => _t('_sys_score_err_not_enabled')));
  190. $aVoteData = ['type' => BX_DOL_SCORE_DO_DOWN];
  191. $aRequestParamsData = $this->_getRequestParamsData();
  192. return echoJson($this->vote($aVoteData, $aRequestParamsData));
  193. }
  194. public function actionGetVotedBy()
  195. {
  196. if (!$this->isEnabled())
  197. return '';
  198. $aParams = $this->_getRequestParamsData();
  199. return $this->_getVotedBy($aParams);
  200. }
  201. public function vote($aVoteData = [], $aRequestParamsData = [])
  202. {
  203. if(!$this->isAllowedVote(true))
  204. return ['code' => BX_DOL_OBJECT_ERR_ACCESS_DENIED, 'message' => $this->msgErrAllowedVote()];
  205. $sType = $aVoteData['type'];
  206. $iObjectId = $this->getId();
  207. $iObjectAuthorId = $this->getObjectAuthorId($iObjectId);
  208. $iAuthorId = $this->_getAuthorId();
  209. $iAuthorIp = $this->_getAuthorIp();
  210. $bVoted = $this->isPerformed($iObjectId, $iAuthorId, $iAuthorIp);
  211. if($bVoted)
  212. return ['code' => BX_DOL_OBJECT_ERR_DUPLICATE, 'message' => _t('_sys_score_err_duplicate_vote')];
  213. $iId = $this->_oQuery->putVote($iObjectId, $iAuthorId, $iAuthorIp, $sType);
  214. if($iId === false)
  215. return ['code' => BX_DOL_OBJECT_ERR_CANNOT_PERFORM];
  216. $this->_trigger();
  217. $sTypeUc = ucfirst($sType);
  218. bx_alert($this->_sSystem, 'doVote' . $sTypeUc, $iObjectId, $iAuthorId, array('score_id' => $iId, 'score_author_id' => $iAuthorId, 'object_author_id' => $iObjectAuthorId));
  219. bx_alert('score', 'do' . $sTypeUc, $iId, $iAuthorId, array('object_system' => $this->_sSystem, 'object_id' => $iObjectId, 'object_author_id' => $iObjectAuthorId));
  220. $aRequestParamsData['show_script'] = false;
  221. $aScore = $this->_getVote($iObjectId, true);
  222. $iCup = (int)$aScore['count_up'];
  223. $iCdown = (int)$aScore['count_down'];
  224. $aResult = [
  225. 'code' => 0,
  226. 'type' => $sType,
  227. 'score' => $aScore['score'],
  228. 'scoref' => $iCup > 0 || $iCdown > 0 ? $this->_getCounterLabel($aScore['score'], $aRequestParamsData) : '',
  229. 'cup' => $iCup,
  230. 'cdown' => $iCdown,
  231. 'counter' => $this->getCounter($aRequestParamsData),
  232. 'label_icon' => $this->_getIconDo($sType),
  233. 'label_title' => _t($this->_getTitleDo($sType)),
  234. 'voted' => !$bVoted,
  235. 'disabled' => !$bVoted,
  236. ];
  237. if(($oSockets = BxDolSockets::getInstance()) && $oSockets->isEnabled())
  238. $oSockets->sendEvent($this->getSocketName(), $iObjectId, 'voted', json_encode($this->_returnVoteDataForSocket($aResult)));
  239. return $aResult;
  240. }
  241. /**
  242. * Permissions functions
  243. */
  244. public function isAllowedVote($isPerformAction = false)
  245. {
  246. if(isAdmin())
  247. return true;
  248. if(!$this->checkAction('vote', $isPerformAction))
  249. return false;
  250. $aObject = $this->_oQuery->getObjectInfo($this->_iId);
  251. if(empty($aObject) || !is_array($aObject))
  252. return false;
  253. return bx_srv($this->_aSystem['module'], 'check_allowed_view_for_profile', [$aObject]) === CHECK_ACTION_RESULT_ALLOWED;
  254. }
  255. public function msgErrAllowedVote()
  256. {
  257. $sMsg = $this->checkActionErrorMsg('vote');
  258. if(empty($sMsg))
  259. $sMsg = _t('_sys_txt_access_denied');
  260. return $sMsg;
  261. }
  262. public function isAllowedVoteView($isPerformAction = false)
  263. {
  264. if(isAdmin())
  265. return true;
  266. return $this->checkAction('vote_view', $isPerformAction);
  267. }
  268. public function msgErrAllowedVoteView()
  269. {
  270. return $this->checkActionErrorMsg('vote_view');
  271. }
  272. public function isAllowedVoteViewVoters($isPerformAction = false)
  273. {
  274. if(isAdmin())
  275. return true;
  276. return $this->checkAction('vote_view_voters', $isPerformAction);
  277. }
  278. public function msgErrAllowedVoteViewVoters()
  279. {
  280. return $this->checkActionErrorMsg('vote_view_voters');
  281. }
  282. /**
  283. * Internal functions
  284. */
  285. protected function _returnVoteDataForSocket($aData, $aMask = [])
  286. {
  287. if(empty($aMask) || !is_array($aMask))
  288. $aMask = ['code', 'type', 'score', 'scoref', 'cup', 'cdown', 'counter'];
  289. return array_intersect_key($aData, array_flip($aMask));
  290. }
  291. protected function _getVote($iObjectId = 0, $bForceGet = false)
  292. {
  293. if(!empty($this->_aScore) && !$bForceGet)
  294. return $this->_aScore;
  295. if(empty($iObjectId))
  296. $iObjectId = $this->getId();
  297. $this->_aScore = $this->_oQuery->getScore($iObjectId);
  298. return $this->_aScore;
  299. }
  300. protected function _isVote($iObjectId = 0, $bForceGet = false)
  301. {
  302. $aScore = $this->_getVote($iObjectId, $bForceGet);
  303. return (int)$aScore['count'] > 0;
  304. }
  305. protected function _isCount($aScore = [])
  306. {
  307. if(empty($aScore))
  308. $aScore = $this->_getVote();
  309. return isset($aScore['count']) && (int)$aScore['count'] != 0;
  310. }
  311. protected function _getTrack($iObjectId, $iAuthorId)
  312. {
  313. return $this->_oQuery->getTrack($iObjectId, $iAuthorId);
  314. }
  315. /**
  316. * Note. By default image based controls aren't used.
  317. * Therefore it can be overwritten in custom template.
  318. */
  319. protected function _getImageDo($sType)
  320. {
  321. $sResult = '';
  322. switch($sType) {
  323. case BX_DOL_SCORE_DO_UP:
  324. $sResult = '';
  325. break;
  326. case BX_DOL_SCORE_DO_DOWN:
  327. $sResult = '';
  328. break;
  329. }
  330. return $sResult;
  331. }
  332. protected function _getIconDo($sType = '')
  333. {
  334. $sResult = '';
  335. switch($sType) {
  336. case BX_DOL_SCORE_DO_UP:
  337. $sResult = 'arrow-up';
  338. break;
  339. case BX_DOL_SCORE_DO_DOWN:
  340. $sResult = 'arrow-down';
  341. break;
  342. default:
  343. $sResult = 'arrows-alt-v';
  344. }
  345. return $sResult;
  346. }
  347. protected function _getTitleDo($sType)
  348. {
  349. $sResult = '';
  350. switch($sType) {
  351. case BX_DOL_SCORE_DO_UP:
  352. $sResult = '_sys_score_do_up';
  353. break;
  354. case BX_DOL_SCORE_DO_DOWN:
  355. $sResult = '_sys_score_do_down';
  356. break;
  357. }
  358. return $sResult;
  359. }
  360. protected function _getTitleDoBy()
  361. {
  362. return '_sys_score_do_by';
  363. }
  364. protected function _encodeElementParams($aParams)
  365. {
  366. if(empty($aParams) || !is_array($aParams))
  367. return '';
  368. return urlencode(base64_encode(serialize($aParams)));
  369. }
  370. protected function _decodeElementParams($sParams, $bMergeWithDefaults = true)
  371. {
  372. $aParams = array();
  373. if(!empty($sParams))
  374. $aParams = unserialize(base64_decode(urldecode($sParams)));
  375. if(empty($aParams) || !is_array($aParams))
  376. $aParams = array();
  377. if($bMergeWithDefaults)
  378. $aParams = array_merge($this->_aElementDefaults, $aParams);
  379. return $aParams;
  380. }
  381. }
  382. /** @} */