BxDolAclQuery.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  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. /**
  10. * Database queries for ACL
  11. * @see BxDolAcl
  12. */
  13. class BxDolAclQuery extends BxDolDb implements iBxDolSingleton
  14. {
  15. protected function __construct()
  16. {
  17. if (isset($GLOBALS['bxDolClasses'][get_class($this)]))
  18. trigger_error ('Multiple instances are not allowed for the class: ' . get_class($this), E_USER_ERROR);
  19. parent::__construct();
  20. }
  21. /**
  22. * Prevent cloning the instance
  23. */
  24. public function __clone()
  25. {
  26. if (isset($GLOBALS['bxDolClasses'][get_class($this)]))
  27. trigger_error('Clone is not allowed for the class: ' . get_class($this), E_USER_ERROR);
  28. }
  29. /**
  30. * Get singleton instance of the class
  31. */
  32. static function getInstance()
  33. {
  34. if(!isset($GLOBALS['bxDolClasses'][__CLASS__]))
  35. $GLOBALS['bxDolClasses'][__CLASS__] = new BxDolAclQuery();
  36. return $GLOBALS['bxDolClasses'][__CLASS__];
  37. }
  38. function getLevels($aParams, &$aItems, $bReturnCount = true)
  39. {
  40. $aMethod = array('name' => 'getAll', 'params' => array(0 => 'query'));
  41. $sSelectClause = $sJoinClause = $sWhereClause = $sOrderClause = $sLimitClause = "";
  42. if(!isset($aParams['order']) || empty($aParams['order']))
  43. $sOrderClause = "ORDER BY `tal`.`Order` ASC";
  44. switch($aParams['type']) {
  45. case 'by_id':
  46. $aMethod['name'] = 'getRow';
  47. $aMethod['params'][1] = array(
  48. 'id' => $aParams['value']
  49. );
  50. $sWhereClause .= "AND `tal`.`ID`=:id";
  51. $sLimitClause .= "LIMIT 1";
  52. break;
  53. case 'all_active':
  54. $sWhereClause .= "AND `tal`.`Active`='yes'";
  55. break;
  56. case 'all_active_purchasble_pair':
  57. $aMethod['name'] = "getPairs";
  58. $aMethod['params'][1] = 'id';
  59. $aMethod['params'][2] = 'name';
  60. $sWhereClause .= "AND `tal`.`Active`='yes' AND `tal`.`Purchasable`='yes'";
  61. break;
  62. case 'all_active_pair':
  63. $aMethod['name'] = "getPairs";
  64. $aMethod['params'][1] = 'id';
  65. $aMethod['params'][2] = 'name';
  66. $sWhereClause .= "AND `tal`.`Active`='yes'";
  67. break;
  68. case 'all_active_not_automatic_pair':
  69. $aMethod['name'] = "getPairs";
  70. $aMethod['params'][1] = 'id';
  71. $aMethod['params'][2] = 'name';
  72. $sWhereClause .= "AND `tal`.`Active`='yes' AND `tal`.`ID` NOT IN (" . $this->implode_escape(array(
  73. MEMBERSHIP_ID_NON_MEMBER,
  74. MEMBERSHIP_ID_ACCOUNT,
  75. MEMBERSHIP_ID_UNCONFIRMED,
  76. MEMBERSHIP_ID_PENDING,
  77. MEMBERSHIP_ID_SUSPENDED
  78. )) . ")";
  79. break;
  80. case 'all_pair':
  81. $aMethod['name'] = "getPairs";
  82. $aMethod['params'][1] = 'id';
  83. $aMethod['params'][2] = 'name';
  84. break;
  85. case 'all_order_id':
  86. $sOrderClause = "ORDER BY `tal`.`ID` ASC";
  87. break;
  88. case 'all':
  89. break;
  90. }
  91. $aMethod['params'][0] = "SELECT " . ($bReturnCount ? "SQL_CALC_FOUND_ROWS" : "") . "
  92. `tal`.`ID` AS `id`,
  93. `tal`.`Name` AS `name`,
  94. `tal`.`Icon` AS `icon`,
  95. `tal`.`Description` AS `description`,
  96. `tal`.`Active` AS `active`,
  97. `tal`.`Purchasable` AS `purchasable`,
  98. `tal`.`Removable` AS `removable`,
  99. `tal`.`QuotaSize` AS `quota_size`,
  100. `tal`.`QuotaNumber` AS `quota_number`,
  101. `tal`.`QuotaMaxFileSize` AS `quota_max_file_size`,
  102. `tal`.`Order` AS `order`" . $sSelectClause . "
  103. FROM `sys_acl_levels` AS `tal` " . $sJoinClause . "
  104. WHERE 1 " . $sWhereClause . " " . $sOrderClause . " " . $sLimitClause;
  105. $aItems = call_user_func_array(array($this, $aMethod['name']), $aMethod['params']);
  106. if(!$bReturnCount)
  107. return !empty($aItems);
  108. return (int)$this->getOne("SELECT FOUND_ROWS()");
  109. }
  110. function getActions($aParams, &$aItems, $bReturnCount = true)
  111. {
  112. $sMemoryKey = '';
  113. $aMethod = array('name' => 'getAll', 'params' => array(0 => 'query'));
  114. $sSelectClause = $sJoinClause = $sWhereClause = $sGroupClause = $sOrderClause = $sLimitClause = "";
  115. if(!isset($aParams['order']) || empty($aParams['order']))
  116. $sOrderClause = "ORDER BY `taa`.`Title` ASC";
  117. switch($aParams['type']) {
  118. case 'by_names_and_module':
  119. $aMethod['params'][1] = array(
  120. 'module' => $aParams['module']
  121. );
  122. $sWhereClause .= " AND `taa`.`Name` IN(" . $this->implode_escape($aParams['value']) . ") AND `taa`.`Module` = :module ";
  123. $sMemoryKey = 'BxDolAclQuery::getActions' . $aParams['type'] . $aParams['module'] . $sWhereClause;
  124. break;
  125. case 'by_names':
  126. $sWhereClause .= " AND `taa`.`Name` IN(" . $this->implode_escape($aParams['value']) . ")";
  127. break;
  128. case 'by_level_id':
  129. $aMethod['params'][1] = array(
  130. 'level_id' => $aParams['value'],
  131. 'level_code' => pow(2, ($aParams['value'] - 1))
  132. );
  133. $sSelectClause .= ", `tam`.`AllowedCount` AS `allowed_count`, `tam`.`AllowedPeriodLen` AS `allowed_period_len`, `tam`.`AllowedPeriodStart` AS `allowed_period_start`, `tam`.`AllowedPeriodEnd` AS `allowed_period_end`, `tam`.`AdditionalParamValue` AS `additional_param_value` ";
  134. $sJoinClause .= "LEFT JOIN `sys_acl_matrix` AS `tam` ON `taa`.`ID`=`tam`.`IDAction` ";
  135. $sWhereClause .= "AND `tam`.`IDLevel`=:level_id AND (`taa`.`DisabledForLevels`='0' OR `taa`.`DisabledForLevels`&:level_code=0)";
  136. break;
  137. case 'by_level_id_key_id':
  138. $aMethod['name'] = 'getAllWithKey';
  139. $aMethod['params'][1] = 'id';
  140. $aMethod['params'][2] = array(
  141. 'level_id' => $aParams['value']
  142. );
  143. $sSelectClause .= ", `tam`.`AllowedCount` AS `allowed_count`, `tam`.`AllowedPeriodLen` AS `allowed_period_len` ";
  144. $sJoinClause .= "LEFT JOIN `sys_acl_matrix` AS `tam` ON `taa`.`ID`=`tam`.`IDAction` ";
  145. $sWhereClause .= "AND `tam`.`IDLevel`=:level_id";
  146. break;
  147. case 'counter_by_modules':
  148. $aMethod['name'] = 'getPairs';
  149. $aMethod['params'][1] = 'module';
  150. $aMethod['params'][2] = 'counter';
  151. $sSelectClause = ", COUNT(*) AS `counter`";
  152. $sGroupClause = "GROUP BY `taa`.`Module`";
  153. break;
  154. case 'counter_by_levels':
  155. $aMethod['name'] = 'getPairs';
  156. $aMethod['params'][1] = 'level_id';
  157. $aMethod['params'][2] = 'counter';
  158. $sSelectClause = ", `tam`.`IDLevel` AS `level_id`, COUNT(`tam`.`IDAction`) AS `counter`";
  159. $sJoinClause = "LEFT JOIN `sys_acl_matrix` AS `tam` ON `taa`.`ID`=`tam`.`IDAction` AND (`taa`.`DisabledForLevels`='0' OR `taa`.`DisabledForLevels`&POW(2, `tam`.`IDLevel`-1)=0) ";
  160. $sGroupClause = "GROUP BY `tam`.`IDLevel`";
  161. break;
  162. }
  163. $aMethod['params'][0] = "SELECT " . ($bReturnCount ? "SQL_CALC_FOUND_ROWS" : "") . "
  164. `taa`.`ID` AS `id`,
  165. `taa`.`Module` AS `module`,
  166. `taa`.`Name` AS `name`,
  167. `taa`.`Title` AS `title`,
  168. `taa`.`Countable` AS `countable`,
  169. `taa`.`DisabledForLevels` AS `disabled_for_levels`" . $sSelectClause . "
  170. FROM `sys_acl_actions` AS `taa` " . $sJoinClause . "
  171. WHERE 1 " . $sWhereClause . " " . $sGroupClause . " " . $sOrderClause . " " . $sLimitClause;
  172. if ($sMemoryKey) {
  173. array_unshift($aMethod['params'], $sMemoryKey, $aMethod['name']);
  174. $aItems = call_user_func_array(array($this, 'fromMemory'), $aMethod['params']);
  175. return $bReturnCount ? count($aItems) : !empty($aItems);
  176. }
  177. $aItems = call_user_func_array(array($this, $aMethod['name']), $aMethod['params']);
  178. if(!$bReturnCount)
  179. return !empty($aItems);
  180. return (int)$this->getOne("SELECT FOUND_ROWS()");
  181. }
  182. /**
  183. * Fetch the last purchased/assigned membership that is still active for the given profile.
  184. *
  185. * NOTE. Don't use cache here, because it's causing an error, if a number of memberrship levels are purchased at the same time.
  186. * fromMemory returns the same DateExpires because setMembership (old buyMembership) function is called in cycle in the same session.
  187. */
  188. function getLevelCurrent($iProfileId, $iTime = 0)
  189. {
  190. $iTime = $iTime == 0 ? time() : (int)$iTime;
  191. $sSql = $this->prepare("
  192. SELECT `sys_acl_levels_members`.`IDLevel` as `id`,
  193. `sys_acl_levels`.`Name` AS `name`,
  194. `sys_acl_levels`.`QuotaSize` AS `quota_size`,
  195. `sys_acl_levels`.`QuotaNumber` AS `quota_number`,
  196. `sys_acl_levels`.`QuotaMaxFileSize` AS `quota_max_file_size`,
  197. UNIX_TIMESTAMP(`sys_acl_levels_members`.`DateStarts`) as `date_starts`,
  198. UNIX_TIMESTAMP(`sys_acl_levels_members`.`DateExpires`) as `date_expires`,
  199. `sys_acl_levels_members`.`TransactionID` AS `transaction_id`,
  200. `sys_profiles`.`status`
  201. FROM `sys_acl_levels_members`
  202. RIGHT JOIN `sys_profiles` ON `sys_acl_levels_members`.IDMember = `sys_profiles`.`id`
  203. AND (`sys_acl_levels_members`.DateStarts IS NULL OR `sys_acl_levels_members`.DateStarts <= FROM_UNIXTIME(?))
  204. AND (`sys_acl_levels_members`.DateExpires IS NULL OR `sys_acl_levels_members`.DateExpires > FROM_UNIXTIME(?))
  205. LEFT JOIN `sys_acl_levels` ON `sys_acl_levels_members`.IDLevel = `sys_acl_levels`.ID
  206. WHERE `sys_profiles`.`id` = ?
  207. ORDER BY `sys_acl_levels_members`.DateStarts DESC
  208. LIMIT 1", $iTime, $iTime, $iProfileId);
  209. return $this->fromMemory('BxDolAclQuery::getLevelCurrent' . $iProfileId . $iTime, 'getRow', $sSql);
  210. }
  211. function getLevelByIdCached($iLevel)
  212. {
  213. $sQuery = $this->prepare("SELECT
  214. `tal`.`ID` AS `id`,
  215. `tal`.`Name` AS `name`,
  216. `tal`.`QuotaSize` AS `quota_size`,
  217. `tal`.`QuotaNumber` AS `quota_number`,
  218. `tal`.`QuotaMaxFileSize` AS `quota_max_file_size`
  219. FROM `sys_acl_levels` AS `tal`
  220. WHERE `tal`.`ID`=?
  221. LIMIT 1", $iLevel);
  222. return $this->fromCache('sys_acl_levels' . $iLevel, 'getRow', $sQuery);
  223. }
  224. function getAction($iMembershipId, $iActionId)
  225. {
  226. $sQuery = $this->prepare("SELECT
  227. `tam`.`IDAction` AS `id`,
  228. `taa`.`Name` AS `name`,
  229. `taa`.`Title` AS `title`,
  230. `tam`.`AllowedCount` AS `allowed_count`,
  231. `tam`.`AllowedPeriodLen` AS `allowed_period_len`,
  232. UNIX_TIMESTAMP(`tam`.`AllowedPeriodStart`) as `allowed_period_start`,
  233. UNIX_TIMESTAMP(`tam`.`AllowedPeriodEnd`) as `allowed_period_end`,
  234. `tam`.`AdditionalParamValue` AS `additional_param_value`
  235. FROM `sys_acl_actions` AS `taa`
  236. LEFT JOIN `sys_acl_matrix` AS `tam` ON `tam`.`IDAction` = `taa`.`ID` AND `tam`.`IDLevel` = ?
  237. WHERE `taa`.`ID` = ?", $iMembershipId, $iActionId);
  238. return $this->fromMemory('BxDolAclQuery::getAction' . $iMembershipId . $iActionId, 'getRow', $sQuery);
  239. }
  240. function getActionTrack($iActionId, $iProfileId)
  241. {
  242. $sQuery = $this->prepare("SELECT
  243. `taat`.`ActionsLeft` AS `actions_left`,
  244. UNIX_TIMESTAMP(`taat`.`ValidSince`) as `valid_since`
  245. FROM `sys_acl_actions_track` AS `taat`
  246. WHERE `taat`.`IDAction`=? AND `taat`.`IDMember`=?", $iActionId, $iProfileId);
  247. return $this->getRow($sQuery);
  248. }
  249. function insertActionTarck($iActionId, $iProfileId, $iActionsLeft, $iValidSince)
  250. {
  251. $sQuery = $this->prepare("INSERT INTO `sys_acl_actions_track`(`IDAction`, `IDMember`, `ActionsLeft`, `ValidSince`) VALUES (?, ?, ?, FROM_UNIXTIME(?))", $iActionId, $iProfileId, $iActionsLeft, $iValidSince);
  252. return (int)$this->query($sQuery) > 0;
  253. }
  254. function updateActionTrack($iActionId, $iProfileId, $iActionsLeft, $iValidSince = 0)
  255. {
  256. $aBindings = array(
  257. 'actions_left' => $iActionsLeft,
  258. 'action_id' => $iActionId,
  259. 'member_id' => $iProfileId
  260. );
  261. $sUpdateAddon = "";
  262. if($iValidSince != 0) {
  263. $aBindings['valid_since'] = $iValidSince;
  264. $sUpdateAddon = ", ValidSince=FROM_UNIXTIME(:valid_since)";
  265. }
  266. $sQuery = "UPDATE `sys_acl_actions_track` SET `ActionsLeft`=:actions_left" . $sUpdateAddon . " WHERE `IDAction`=:action_id AND `IDMember`=:member_id";
  267. return (int)$this->query($sQuery, $aBindings) > 0;
  268. }
  269. function insertLevelByProfileId($iProfileId, $iMembershipId, $iDateStarts, $aPeriod, $sTransactionId)
  270. {
  271. $aBindings = array(
  272. 'member_id' => $iProfileId,
  273. 'level_id' => $iMembershipId,
  274. 'transaction_id' => $sTransactionId,
  275. 'date_starts' => $iDateStarts
  276. );
  277. $sSetClause = '';
  278. if((int)$aPeriod['period'] != 0) {
  279. $aBindings['period'] = (int)$aPeriod['period'];
  280. switch($aPeriod['period_unit']) {
  281. case MEMBERSHIP_PERIOD_UNIT_DAY:
  282. case MEMBERSHIP_PERIOD_UNIT_WEEK:
  283. if($aPeriod['period_unit'] == MEMBERSHIP_PERIOD_UNIT_WEEK)
  284. $aBindings['period'] *= 7;
  285. $sSetClause = ", `DateExpires`=DATE_ADD(FROM_UNIXTIME(:date_starts), INTERVAL :period DAY)";
  286. break;
  287. case MEMBERSHIP_PERIOD_UNIT_MONTH:
  288. $sSetClause = ", `DateExpires`=DATE_ADD(FROM_UNIXTIME(:date_starts), INTERVAL :period MONTH)";
  289. break;
  290. case MEMBERSHIP_PERIOD_UNIT_YEAR:
  291. $sSetClause = ", `DateExpires`=DATE_ADD(FROM_UNIXTIME(:date_starts), INTERVAL :period YEAR)";
  292. break;
  293. }
  294. }
  295. $sQuery = $this->prepare("INSERT `sys_acl_levels_members` SET `IDMember`=:member_id, `IDLevel`=:level_id, `DateStarts`=FROM_UNIXTIME(:date_starts), `TransactionID`=:transaction_id" . $sSetClause);
  296. return (int)$this->query($sQuery, $aBindings) > 0;
  297. }
  298. function deleteLevelByProfileId($iProfileId, $bAll = false)
  299. {
  300. $sQuery = $this->prepare("DELETE FROM `sys_acl_levels_members` WHERE `IDMember` = ? " . ($bAll ? "" : " AND (`DateExpires` IS NULL OR `DateExpires` > NOW())"), $iProfileId);
  301. return (int)$this->query($sQuery) > 0;
  302. }
  303. function deleteLevelBy($aWhere)
  304. {
  305. if(empty($aWhere))
  306. return false;
  307. $sQuery = "DELETE FROM `sys_acl_levels_members` WHERE " . $this->arrayToSQL($aWhere, ' AND ');
  308. return (int)$this->query($sQuery) > 0;
  309. }
  310. function maintenance($iDaysToCleanMemLevels = 0)
  311. {
  312. $sQuery = $this->prepare("DELETE FROM `sys_acl_levels_members` WHERE `DateExpires` < NOW() - INTERVAL ? DAY", $iDaysToCleanMemLevels);
  313. if ($iDeleteMemLevels = $this->query($sQuery))
  314. $this->query("OPTIMIZE TABLE `sys_acl_levels_members`");
  315. return $iDeleteMemLevels;
  316. }
  317. function clearActionsTracksForMember($iMemberId)
  318. {
  319. $sQuery = $this->prepare("DELETE FROM `sys_acl_actions_track` WHERE `IDMember` = ?", (int)$iMemberId);
  320. return $this->query($sQuery);
  321. }
  322. function getContentByLevelAsSQLPart($sContentTable, $sContentField, $mixedLevelId)
  323. {
  324. $sJoin = $sWhere = "";
  325. if(is_array($mixedLevelId))
  326. $sWhere .= " AND `tlm`.`IDLevel` IN (" . $this->implode_escape($mixedLevelId) . ")";
  327. else
  328. $sWhere .= $this->prepareAsString(" AND `tlm`.`IDLevel` = ?", (int)$mixedLevelId);
  329. $sWhere .= " AND (`tlm`.`DateStarts` IS NULL OR `tlm`.`DateStarts` <= NOW()) AND (`tlm`.`DateExpires` IS NULL OR `tlm`.`DateExpires` > NOW())";
  330. $sJoin .= " INNER JOIN `sys_acl_levels_members` AS `tlm` ON `" . $sContentTable . "`.`" . $sContentField . "`=`tlm`.`IDMember`";
  331. $sJoin .= " INNER JOIN `sys_acl_levels` AS `tl` ON `tlm`.`IDLevel`=`tl`.`ID`";
  332. return array(
  333. 'where' => $sWhere,
  334. 'join' => $sJoin
  335. );
  336. }
  337. function getProfilesByMembership($mixedLevelId)
  338. {
  339. $aSqlParts = $this->getContentByLevelAsSQLPart('sys_profiles', 'id', $mixedLevelId);
  340. $sSql = $this->prepare("SELECT `sys_profiles`.* FROM `sys_profiles`" . $aSqlParts['join'] . " WHERE 1" . $aSqlParts['where']);
  341. return $this->getAll($sSql);
  342. }
  343. }
  344. /** @} */