BxCreditsDb.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  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 Credits Credits
  7. * @ingroup UnaModules
  8. *
  9. * @{
  10. */
  11. /*
  12. * Module database queries
  13. */
  14. class BxCreditsDb extends BxBaseModGeneralDb
  15. {
  16. function __construct(&$oConfig)
  17. {
  18. parent::__construct($oConfig);
  19. }
  20. /**
  21. * Bundle related methods.
  22. */
  23. public function getBundle($aParams = array())
  24. {
  25. $CNF = &$this->_oConfig->CNF;
  26. $aMethod = array('name' => 'getAll', 'params' => array(0 => 'query'));
  27. $sSelectClause = "`tb`.*";
  28. $sJoinClause = $sWhereClause = $sLimitClause = "";
  29. $sOrderClause = "`tb`.`order` ASC";
  30. switch($aParams['type']) {
  31. case 'id':
  32. $aMethod['name'] = 'getRow';
  33. $aMethod['params'][1] = array(
  34. 'id' => $aParams['id']
  35. );
  36. $sWhereClause = " AND `tb`.`id`=:id";
  37. break;
  38. case 'order_max':
  39. $aMethod['name'] = 'getOne';
  40. $sSelectClause = "IFNULL(MAX(`tb`.`order`), 0)";
  41. break;
  42. case 'all':
  43. break;
  44. }
  45. if(isset($aParams['active']))
  46. $sWhereClause .= $this->prepareAsString(" AND `tb`.`active`=?", (bool)$aParams['active'] ? 1 : 0);
  47. $sOrderClause = !empty($sOrderClause) ? "ORDER BY " . $sOrderClause : "";
  48. $sLimitClause = !empty($sLimitClause) ? "LIMIT " . $sLimitClause : "";
  49. $aMethod['params'][0] = "SELECT
  50. " . $sSelectClause . "
  51. FROM `" . $CNF['TABLE_BUNDLES'] . "` AS `tb`" . $sJoinClause . "
  52. WHERE 1" . $sWhereClause . " " . $sOrderClause . " " . $sLimitClause;
  53. return call_user_func_array(array($this, $aMethod['name']), $aMethod['params']);
  54. }
  55. public function isBundle($iId)
  56. {
  57. $aSport = $this->getBundle(array('type' => 'id', 'id' => $iId));
  58. return !empty($aSport) && is_array($aSport);
  59. }
  60. public function insertBundle($aSet)
  61. {
  62. $sQuery = "INSERT INTO `" . $this->_oConfig->CNF['TABLE_BUNDLES'] . "` SET " . $this->arrayToSQL($aSet);
  63. return (int)$this->query($sQuery) > 0;
  64. }
  65. public function updateBundle($aSet, $aWhere)
  66. {
  67. $sQuery = "UPDATE `" . $this->_oConfig->CNF['TABLE_BUNDLES'] . "` SET " . $this->arrayToSQL($aSet) . " WHERE " . (!empty($aWhere) ? $this->arrayToSQL($aWhere, ' AND ') : "1");
  68. return (int)$this->query($sQuery) > 0;
  69. }
  70. public function deleteBundle($aWhere)
  71. {
  72. if(empty($aWhere))
  73. return false;
  74. $sQuery = "DELETE FROM `" . $this->_oConfig->CNF['TABLE_BUNDLES'] . "` WHERE " . $this->arrayToSQL($aWhere, ' AND ');
  75. return (int)$this->query($sQuery) > 0;
  76. }
  77. /**
  78. * Order related methods.
  79. */
  80. public function getOrder($aParams = array())
  81. {
  82. $CNF = &$this->_oConfig->CNF;
  83. $aMethod = array('name' => 'getAll', 'params' => array(0 => 'query'));
  84. $sSelectClause = "`to`.*";
  85. $sJoinClause = $sWhereClause = $sOrderClause = $sLimitClause = "";
  86. switch($aParams['type']) {
  87. case 'id':
  88. $aMethod['name'] = 'getRow';
  89. $aMethod['params'][1] = array(
  90. 'id' => $aParams['id']
  91. );
  92. $sWhereClause = " AND `to`.`id`=:id";
  93. break;
  94. case 'row_by':
  95. $aMethod['name'] = 'getRow';
  96. $sWhereClause = " AND " . $this->arrayToSQL($aParams['by'], ' AND ');
  97. break;
  98. case 'all':
  99. break;
  100. }
  101. $sOrderClause = !empty($sOrderClause) ? "ORDER BY " . $sOrderClause : "";
  102. $sLimitClause = !empty($sLimitClause) ? "LIMIT " . $sLimitClause : "";
  103. $aMethod['params'][0] = "SELECT
  104. " . $sSelectClause . "
  105. FROM `" . $CNF['TABLE_ORDERS'] . "` AS `to`" . $sJoinClause . "
  106. WHERE 1" . $sWhereClause . " " . $sOrderClause . " " . $sLimitClause;
  107. return call_user_func_array(array($this, $aMethod['name']), $aMethod['params']);
  108. }
  109. public function isOrder($iId)
  110. {
  111. $aOrder = $this->getOrder(array('type' => 'id', 'id' => $iId));
  112. return !empty($aOrder) && is_array($aOrder);
  113. }
  114. public function isOrderByPbo($iProfileId, $iBundleId, $sOrder)
  115. {
  116. $aOrder = $this->getOrder(array('type' => 'row_by', 'by' => array('profile_id' => $iProfileId, 'bundle_id' => $iBundleId, 'order' => $sOrder)));
  117. return !empty($aOrder) && is_array($aOrder);
  118. }
  119. public function insertOrder($aSet, $sSetAddon = '')
  120. {
  121. $sQuery = "INSERT INTO `" . $this->_oConfig->CNF['TABLE_ORDERS'] . "` SET " . $this->arrayToSQL($aSet) . $sSetAddon;
  122. return (int)$this->query($sQuery) > 0;
  123. }
  124. public function insertOrderDeleted($aSet, $sSetAddon = '')
  125. {
  126. $sQuery = "INSERT INTO `" . $this->_oConfig->CNF['TABLE_ORDERS_DELETED'] . "` SET " . $this->arrayToSQL($aSet) . $sSetAddon;
  127. return (int)$this->query($sQuery) > 0;
  128. }
  129. public function registerOrder($iProfileId, $iBundleId, $iCount, $sOrder, $sLicense, $sType, $sDuration = '', $iTrial = 0)
  130. {
  131. $CNF = &$this->_oConfig->CNF;
  132. $sSetAddon = ', `added`=UNIX_TIMESTAMP()';
  133. return $this->insertOrder(array(
  134. 'profile_id' => $iProfileId,
  135. 'bundle_id' => $iBundleId,
  136. 'count' => $iCount,
  137. 'order' => $sOrder,
  138. 'license' => $sLicense,
  139. 'type' => $sType
  140. ), $sSetAddon);
  141. }
  142. public function updateOrder($aSet, $aWhere)
  143. {
  144. $sQuery = "UPDATE `" . $this->_oConfig->CNF['TABLE_ORDERS'] . "` SET " . $this->arrayToSQL($aSet) . " WHERE " . (!empty($aWhere) ? $this->arrayToSQL($aWhere, ' AND ') : "1");
  145. return (int)$this->query($sQuery) > 0;
  146. }
  147. /**
  148. * Note. Prolong isn't allowed for now.
  149. */
  150. public function prolongOrder($iProfileId, $iItemId, $iItemCount, $sOrder, $sLicense, $sType, $sDuration, $iTrial)
  151. {
  152. return false;
  153. }
  154. public function deleteOrder($aWhere)
  155. {
  156. if(empty($aWhere))
  157. return false;
  158. $sQuery = "DELETE FROM `" . $this->_oConfig->CNF['TABLE_ORDERS'] . "` WHERE " . $this->arrayToSQL($aWhere, ' AND ');
  159. return (int)$this->query($sQuery) > 0;
  160. }
  161. public function unregisterOrder($iProfileId, $iItemId, $sOrder, $sLicense, $sType)
  162. {
  163. $CNF = &$this->_oConfig->CNF;
  164. $aOrder = $this->getOrder(array('type' => 'row_by', 'by' => array(
  165. 'profile_id' => $iProfileId,
  166. 'bundle_id' => $iItemId,
  167. 'order' => $sOrder,
  168. 'license' => $sLicense
  169. )));
  170. if(empty($aOrder) || !is_array($aOrder))
  171. return true;
  172. //--- Move to deleted orders table with 'refund' as reason.
  173. $this->insertOrderDeleted($aOrder, ", `reason`='refund', `deleted`=UNIX_TIMESTAMP()");
  174. return $this->deleteOrder(array('id' => $aOrder[$CNF['FIELD_ID']]));
  175. }
  176. /**
  177. * Profile related methods.
  178. */
  179. public function getProfile($aParams = array())
  180. {
  181. $CNF = &$this->_oConfig->CNF;
  182. $aMethod = array('name' => 'getAll', 'params' => array(0 => 'query'));
  183. $sSelectClause = "`tp`.*";
  184. $sJoinClause = $sWhereClause = $sLimitClause = "";
  185. switch($aParams['type']) {
  186. case 'id':
  187. $aMethod['name'] = 'getRow';
  188. $aMethod['params'][1] = array(
  189. 'id' => $aParams['id']
  190. );
  191. $sWhereClause = " AND `tp`.`id`=:id";
  192. break;
  193. case 'balance':
  194. $aMethod['name'] = 'getOne';
  195. $aMethod['params'][1] = array(
  196. 'id' => $aParams['id']
  197. );
  198. $sSelectClause = "`tp`.`balance`";
  199. $sWhereClause = " AND `tp`.`id`=:id";
  200. break;
  201. }
  202. $sLimitClause = !empty($sLimitClause) ? "LIMIT " . $sLimitClause : $sLimitClause;
  203. $aMethod['params'][0] = "SELECT
  204. " . $sSelectClause . "
  205. FROM `" . $CNF['TABLE_PROFILES'] . "` AS `tp`" . $sJoinClause . "
  206. WHERE 1" . $sWhereClause . " " . $sLimitClause;
  207. return call_user_func_array(array($this, $aMethod['name']), $aMethod['params']);
  208. }
  209. public function isProfile($iId)
  210. {
  211. $aProfile = $this->getProfile(array('type' => 'id', 'id' => $iId));
  212. return !empty($aProfile) && is_array($aProfile);
  213. }
  214. public function insertProfile($aSet)
  215. {
  216. $sQuery = "INSERT INTO `" . $this->_oConfig->CNF['TABLE_PROFILES'] . "` SET " . $this->arrayToSQL($aSet);
  217. return (int)$this->query($sQuery) > 0;
  218. }
  219. public function updateProfile($aSet, $aWhere)
  220. {
  221. $sQuery = "UPDATE `" . $this->_oConfig->CNF['TABLE_PROFILES'] . "` SET " . $this->arrayToSQL($aSet) . " WHERE " . (!empty($aWhere) ? $this->arrayToSQL($aWhere, ' AND ') : "1");
  222. return (int)$this->query($sQuery) > 0;
  223. }
  224. public function updateProfileBalance($iId, $fAmount, $bCleared = false)
  225. {
  226. $CNF = &$this->_oConfig->CNF;
  227. $sBalance = $bCleared ? 'cleared' : 'balance';
  228. if(!$this->isProfile($iId))
  229. return $this->insertProfile(['id' => $iId, $sBalance => $fAmount]);
  230. $sQuery = "UPDATE `" . $CNF['TABLE_PROFILES'] . "` SET `" . $sBalance . "`=`" . $sBalance . "`+:amount WHERE `id`=:id";
  231. return (int)$this->query($sQuery, [
  232. 'id' => $iId,
  233. 'amount' => $fAmount
  234. ]) > 0;
  235. }
  236. public function deleteProfile($aWhere)
  237. {
  238. if(empty($aWhere))
  239. return false;
  240. $sQuery = "DELETE FROM `" . $this->_oConfig->CNF['TABLE_PROFILES'] . "` WHERE " . $this->arrayToSQL($aWhere, ' AND ');
  241. return (int)$this->query($sQuery) > 0;
  242. }
  243. /**
  244. * History related methods.
  245. */
  246. public function getHistory($aParams = array())
  247. {
  248. $CNF = &$this->_oConfig->CNF;
  249. $aMethod = ['name' => 'getAll', 'params' => [0 => 'query']];
  250. $sSelectClause = "`th`.*";
  251. $sJoinClause = $sWhereClause = $sLimitClause = "";
  252. switch($aParams['type']) {
  253. case 'cleared':
  254. $aMethod['name'] = 'getOne';
  255. $aMethod['params'][1] = [
  256. 'profile' => $aParams['profile']
  257. ];
  258. $sSelectClause = "SUM(`th`.`amount`)";
  259. $sWhereClause = " AND `th`.`first_pid`=:profile AND `th`.`direction`='in' AND `th`.`type` IN (" . $this->implode_escape($this->_oConfig->getTransferTypesForClearing()) . ") AND `th`.`cleared`<>'0'";
  260. break;
  261. case 'spent':
  262. $aMethod['name'] = 'getOne';
  263. $aMethod['params'][1] = [
  264. 'profile' => $aParams['profile'],
  265. 'type_cancel' => BX_CREDITS_TRANSFER_TYPE_CANCELLATION
  266. ];
  267. $sSelectClause = "SUM(`th`.`amount`)";
  268. $sJoinClause = " LEFT JOIN `" . $CNF['TABLE_HISTORY'] . "` AS `thc` ON `th`.`order`=`thc`.`order` AND `thc`.`type`=:type_cancel";
  269. $sWhereClause = " AND `th`.`first_pid`=:profile AND `th`.`direction`='out' AND `th`.`type` IN (" . $this->implode_escape($this->_oConfig->getTransferTypesForSpending()) . ") AND ISNULL(`thc`.`id`)";
  270. break;
  271. case 'id':
  272. $aMethod['name'] = 'getRow';
  273. $aMethod['params'][1] = [
  274. 'id' => $aParams['id']
  275. ];
  276. $sWhereClause = " AND `th`.`id`=:id";
  277. break;
  278. case 'row_by':
  279. $aMethod['name'] = 'getRow';
  280. $sWhereClause = " AND " . $this->arrayToSQL($aParams['by'], ' AND ');
  281. break;
  282. case 'clearing':
  283. $aMethod['params'][1] = [
  284. 'clearing' => $aParams['clearing']
  285. ];
  286. $sJoinClause = " LEFT JOIN `" . $CNF['TABLE_PROFILES'] . "` AS `tp` ON `th`.`first_pid`=`tp`.`id`";
  287. $sWhereClause = " AND `th`.`direction`='in' AND `th`.`type` IN (" . $this->implode_escape($this->_oConfig->getTransferTypesForClearing()) . ") AND `th`.`date` < UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL IF(`tp`.`wdw_clearing` <> 0, `tp`.`wdw_clearing`, :clearing) DAY)) AND `th`.`cleared`='0'";
  288. break;
  289. }
  290. $sLimitClause = !empty($sLimitClause) ? "LIMIT " . $sLimitClause : $sLimitClause;
  291. $aMethod['params'][0] = "SELECT
  292. " . $sSelectClause . "
  293. FROM `" . $CNF['TABLE_HISTORY'] . "` AS `th`" . $sJoinClause . "
  294. WHERE 1" . $sWhereClause . " " . $sLimitClause;
  295. return call_user_func_array(array($this, $aMethod['name']), $aMethod['params']);
  296. }
  297. public function isHistory($iId)
  298. {
  299. $aHistory = $this->getHistory(array('type' => 'id', 'id' => $iId));
  300. return !empty($aHistory) && is_array($aHistory);
  301. }
  302. public function insertHistory($aSet)
  303. {
  304. $sQuery = "INSERT INTO `" . $this->_oConfig->CNF['TABLE_HISTORY'] . "` SET " . $this->arrayToSQL($aSet);
  305. return (int)$this->query($sQuery) > 0 ? $this->lastId() : false;
  306. }
  307. public function updateHistory($aSet, $aWhere)
  308. {
  309. $sQuery = "UPDATE `" . $this->_oConfig->CNF['TABLE_HISTORY'] . "` SET " . $this->arrayToSQL($aSet) . " WHERE " . (!empty($aWhere) ? $this->arrayToSQL($aWhere, ' AND ') : "1");
  310. return (int)$this->query($sQuery) > 0;
  311. }
  312. public function deleteHistory($aWhere)
  313. {
  314. if(empty($aWhere))
  315. return false;
  316. $sQuery = "DELETE FROM `" . $this->_oConfig->CNF['TABLE_HISTORY'] . "` WHERE " . $this->arrayToSQL($aWhere, ' AND ');
  317. return (int)$this->query($sQuery) > 0;
  318. }
  319. /**
  320. * Withdrawals related methods.
  321. */
  322. public function getWithdrawal($aParams = [])
  323. {
  324. $CNF = &$this->_oConfig->CNF;
  325. $aMethod = ['name' => 'getAll', 'params' => [0 => 'query']];
  326. $sSelectClause = "`tw`.*";
  327. $sJoinClause = $sWhereClause = $sLimitClause = "";
  328. switch($aParams['type']) {
  329. case 'id':
  330. $aMethod['name'] = 'getRow';
  331. $aMethod['params'][1] = [
  332. 'id' => $aParams['id']
  333. ];
  334. $sWhereClause = " AND `tw`.`id`=:id";
  335. break;
  336. }
  337. $sLimitClause = !empty($sLimitClause) ? "LIMIT " . $sLimitClause : $sLimitClause;
  338. $aMethod['params'][0] = "SELECT
  339. " . $sSelectClause . "
  340. FROM `" . $CNF['TABLE_WITHDRAWALS'] . "` AS `tw`" . $sJoinClause . "
  341. WHERE 1" . $sWhereClause . " " . $sLimitClause;
  342. return call_user_func_array([$this, $aMethod['name']], $aMethod['params']);
  343. }
  344. public function insertWithdrawal($aSet)
  345. {
  346. $sQuery = "INSERT INTO `" . $this->_oConfig->CNF['TABLE_WITHDRAWALS'] . "` SET " . $this->arrayToSQL($aSet);
  347. return (int)$this->query($sQuery) > 0 ? $this->lastId() : false;
  348. }
  349. public function updateWithdrawal($aSet, $aWhere)
  350. {
  351. $sQuery = "UPDATE `" . $this->_oConfig->CNF['TABLE_WITHDRAWALS'] . "` SET " . $this->arrayToSQL($aSet) . " WHERE " . (!empty($aWhere) ? $this->arrayToSQL($aWhere, ' AND ') : "1");
  352. return (int)$this->query($sQuery) > 0;
  353. }
  354. public function deleteWithdrawal($aWhere)
  355. {
  356. if(empty($aWhere))
  357. return false;
  358. $sQuery = "DELETE FROM `" . $this->_oConfig->CNF['TABLE_WITHDRAWALS'] . "` WHERE " . $this->arrayToSQL($aWhere, ' AND ');
  359. return (int)$this->query($sQuery) > 0;
  360. }
  361. /**
  362. * Analytics: credits moved in a period (`to` exclusive), by transfer type and direction.
  363. */
  364. public function getAnalyticsTotals($iFrom, $iTo)
  365. {
  366. return $this->getAll("SELECT `type`, `direction`, SUM(`amount`) AS `amount`, COUNT(*) AS `count` FROM `" . $this->_oConfig->CNF['TABLE_HISTORY'] . "` WHERE `date` >= :from AND `date` < :to GROUP BY `type`, `direction`", [
  367. 'from' => (int)$iFrom,
  368. 'to' => (int)$iTo
  369. ]);
  370. }
  371. /**
  372. * Analytics: the same per time bucket; a row goes to the latest of the bucket starts before it.
  373. */
  374. public function getAnalyticsSeries($iFrom, $iTo, $aStarts)
  375. {
  376. $aStarts = array_values(array_map('intval', $aStarts));
  377. if(empty($aStarts))
  378. return [];
  379. $aBindings = ['from' => (int)$iFrom, 'to' => (int)$iTo];
  380. $aCases = [];
  381. foreach(array_reverse($aStarts) as $i => $iStart) {
  382. $aCases[] = 'WHEN `date` >= :b' . $i . ' THEN :b' . $i . 'v';
  383. $aBindings['b' . $i] = $iStart;
  384. $aBindings['b' . $i . 'v'] = $iStart;
  385. }
  386. return $this->getAll("SELECT CASE " . implode(' ', $aCases) . " ELSE 0 END AS `bucket`, `type`, `direction`, SUM(`amount`) AS `amount` FROM `" . $this->_oConfig->CNF['TABLE_HISTORY'] . "` WHERE `date` >= :from AND `date` < :to GROUP BY `bucket`, `type`, `direction`", $aBindings);
  387. }
  388. /**
  389. * Analytics: profiles that spent the most credits on checkouts in a period (the buyer's side).
  390. */
  391. public function getAnalyticsTopSpenders($iFrom, $iTo, $iLimit)
  392. {
  393. return $this->getAll("SELECT `first_pid` AS `profile_id`, SUM(`amount`) AS `amount` FROM `" . $this->_oConfig->CNF['TABLE_HISTORY'] . "` WHERE `date` >= :from AND `date` < :to AND `type` = :type AND `direction` = :direction GROUP BY `first_pid` ORDER BY `amount` DESC LIMIT " . max(1, min(100, (int)$iLimit)), [
  394. 'from' => (int)$iFrom,
  395. 'to' => (int)$iTo,
  396. 'type' => BX_CREDITS_TRANSFER_TYPE_CHECKOUT,
  397. 'direction' => BX_CREDITS_DIRECTION_OUT
  398. ]);
  399. }
  400. /**
  401. * Analytics: confirmed withdrawals in a period, in credits and in money at their own rate.
  402. */
  403. public function getAnalyticsWithdrawn($iFrom, $iTo)
  404. {
  405. return $this->getRow("SELECT COUNT(*) AS `count`, IFNULL(SUM(`amount`), 0) AS `amount`, IFNULL(SUM(`amount` * `rate`), 0) AS `money` FROM `" . $this->_oConfig->CNF['TABLE_WITHDRAWALS'] . "` WHERE `status` = :status AND `confirmed` >= :from AND `confirmed` < :to", [
  406. 'status' => BX_CREDITS_WITHDRAWAL_STATUS_CONFIRMED,
  407. 'from' => (int)$iFrom,
  408. 'to' => (int)$iTo
  409. ]);
  410. }
  411. /**
  412. * Analytics: credits members hold now, and how many members hold any.
  413. */
  414. public function getAnalyticsBalance()
  415. {
  416. return $this->getRow("SELECT IFNULL(SUM(`balance`), 0) AS `balance`, SUM(`balance` > 0) AS `holders` FROM `" . $this->_oConfig->CNF['TABLE_PROFILES'] . "`");
  417. }
  418. }
  419. /** @} */