BxDolProfileQuery.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  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. * All queries related to profiles
  11. */
  12. class BxDolProfileQuery extends BxDolDb implements iBxDolSingleton
  13. {
  14. protected function __construct()
  15. {
  16. if (isset($GLOBALS['bxDolClasses'][get_class($this)]))
  17. trigger_error ('Multiple instances are not allowed for the class: ' . get_class($this), E_USER_ERROR);
  18. parent::__construct();
  19. }
  20. /**
  21. * Prevent cloning the instance
  22. */
  23. public function __clone()
  24. {
  25. if (isset($GLOBALS['bxDolClasses'][get_class($this)]))
  26. trigger_error('Clone is not allowed for the class: ' . get_class($this), E_USER_ERROR);
  27. }
  28. /**
  29. * Get singleton instance of the class
  30. */
  31. public static function getInstance()
  32. {
  33. if(!isset($GLOBALS['bxDolClasses'][__CLASS__]))
  34. $GLOBALS['bxDolClasses'][__CLASS__] = new BxDolProfileQuery();
  35. return $GLOBALS['bxDolClasses'][__CLASS__];
  36. }
  37. /**
  38. * Get all account profiles.
  39. * @param string $iAccountId account id
  40. * @return profile array
  41. */
  42. public function getProfilesByAccount ($iAccountId)
  43. {
  44. if (!$iAccountId)
  45. return array();
  46. $oAccountQuery = BxDolAccountQuery::getInstance();
  47. $aAccountInfo = $oAccountQuery->getInfoById($iAccountId);
  48. $sSql = $this->prepare("SELECT * FROM `sys_profiles` WHERE `account_id` = ? ORDER BY `id` = ? DESC", $iAccountId, $aAccountInfo['profile_id']);
  49. return $this->getAllWithKey($sSql, 'id');
  50. }
  51. /**
  52. * Get profile(s) by params
  53. * @param array $aParams browse params
  54. * @return array with profile(s)
  55. */
  56. public function getProfiles($aParams)
  57. {
  58. $aMethod = ['name' => 'getAll', 'params' => [0 => 'query']];
  59. $sFieldsClause = "`tp`.*";
  60. $sJoinClause = $sWhereClause = $sGroupClause = "";
  61. $sOrderClause = "`tp`.`id` ASC";
  62. switch($aParams['type']) {
  63. case 'id':
  64. $aMethod['name'] = 'getRow';
  65. $aMethod['params'][1] = [
  66. 'id' => $aParams['id']
  67. ];
  68. $sWhereClause = " AND `tp`.`id`=:id";
  69. break;
  70. case 'active':
  71. $sWhereClause = " AND `tp`.`status`='active'";
  72. if(isset($aParams['types'])) {
  73. if(!is_array($aParams['types']))
  74. $aParams['types'] = [$aParams['types']];
  75. $sWhereClause .= " AND `tp`.`type` IN (" . $this->implode_escape($aParams['types']) . ")";
  76. }
  77. break;
  78. case 'id_by_module_content_id':
  79. $sFieldsClause = "`tp`.`id`";
  80. $sWhereClause = $this->prepareAsString(" AND `tp`.`type`=?", $aParams['module']);
  81. if(!is_array($aParams['content_id'])) {
  82. $aMethod['name'] = 'getOne';
  83. $sWhereClause .= $this->prepareAsString(" AND `tp`.`content_id`=?", $aParams['content_id']);
  84. }
  85. else {
  86. $aMethod['name'] = 'getColumn';
  87. $sWhereClause .= " AND `tp`.`content_id` IN (" . $this->implode_escape($aParams['content_id']) . ")";
  88. }
  89. break;
  90. case 'id_to_type':
  91. $aMethod['name'] = 'getPairs';
  92. $aMethod['params'][1] = 'id';
  93. $aMethod['params'][2] = 'type';
  94. $sWhereClause = " AND `tp`.`id` IN (" . $this->implode_escape($aParams['ids']) . ")";
  95. break;
  96. case 'all':
  97. break;
  98. }
  99. $sGroupClause = $sGroupClause ? "GROUP BY " . $sGroupClause : "";
  100. $sOrderClause = $sOrderClause ? "ORDER BY " . $sOrderClause : "";
  101. $aMethod['params'][0] = "SELECT
  102. " . $sFieldsClause . "
  103. FROM `sys_profiles` AS `tp`" . $sJoinClause . "
  104. WHERE 1" . $sWhereClause . " " . $sGroupClause . " " . $sOrderClause;
  105. return call_user_func_array([$this, $aMethod['name']], $aMethod['params']);
  106. }
  107. /**
  108. * Get profile by content id, type and account.
  109. * @param string $iAccountId account id
  110. * @return array if aprofile ids, key is profile id
  111. */
  112. public function getProfileByContentTypeAccount ($iContentId, $sType, $iAccountId)
  113. {
  114. $sSql = $this->prepare("SELECT * FROM `sys_profiles` WHERE `account_id` = ? AND `type` = ? AND `content_id` = ?", $iAccountId, $sType, $iContentId);
  115. return $this->getRow($sSql);
  116. }
  117. /**
  118. * Get profile by content id and type.
  119. * @param string $iAccountId account id
  120. * @return array if aprofile ids, key is profile id
  121. */
  122. public function getProfileByContentAndType ($iContentId, $sType, $bClearCache = false)
  123. {
  124. if (!$iContentId)
  125. return false;
  126. $sKey = 'BxDolProfileQuery::getProfileByContentAndType' . $iContentId . $sType;
  127. if ($bClearCache)
  128. $this->cleanMemory($sKey);
  129. $sSql = $this->prepare("SELECT * FROM `sys_profiles` WHERE `content_id` = ? AND `type` = ?", $iContentId, $sType);
  130. $mixedResult = $this->fromMemory($sKey, 'getRow', $sSql);
  131. if (!$mixedResult)
  132. $this->cleanMemory($sKey);
  133. return $mixedResult;
  134. }
  135. public function getConnectedProfilesByType ($aSqlParts, $sType, $iStart, $iLimit)
  136. {
  137. if(empty($aSqlParts['join']))
  138. return array();
  139. $aBindings = array();
  140. $sSelectClause = '';
  141. if(!empty($aSqlParts['fields']))
  142. foreach($aSqlParts['fields'] as $sName => $sField)
  143. $sSelectClause .= ', ' . $sField;
  144. $sWhereClause = '';
  145. if(!empty($sType)) {
  146. $sWhereClause = ' AND `sys_profiles`.`type`=:type';
  147. $aBindings['type'] = $sType;
  148. }
  149. $sOrderClause = '';
  150. if(!empty($aSqlParts['fields']['added']))
  151. $sOrderClause = ' ORDER BY ' . $aSqlParts['fields']['added'] . ' DESC';
  152. $sLimitClause = '';
  153. if(!empty($iLimit))
  154. $sLimitClause = $this->prepareAsString(' LIMIT ?, ?', $iStart, $iLimit);
  155. return $this->getAllWithKey("SELECT `sys_profiles`.*" . $sSelectClause . " FROM `sys_profiles` " . $aSqlParts['join'] . " WHERE 1" . $sWhereClause . $sOrderClause . $sLimitClause, 'id', $aBindings);
  156. }
  157. /**
  158. * Insert account and content id association. Also if currect profile id is not defined - it updates current profile id in account.
  159. * @param $iAccountId account id
  160. * @param $iContentId content id
  161. * @param $sStatus profile status
  162. * @param $sType profile content type
  163. * @return inserted profile's id
  164. */
  165. public function insertProfile ($iAccountId, $iContentId, $sStatus, $sType = 'system')
  166. {
  167. $sSql = $this->prepare("INSERT INTO `sys_profiles` SET `account_id` = ?, `type` = ?, `content_id` = ?, `status` = ?", $iAccountId, $sType, $iContentId, $sStatus);
  168. if (!$this->query($sSql))
  169. return false;
  170. $iProfileId = $this->lastId();
  171. $this->getCurrentProfileByAccount($iAccountId); // it updates current profile id automatically if it is not defined
  172. return $iProfileId;
  173. }
  174. /**
  175. * Update profile's account id
  176. * @param $iProfileId profile id
  177. * @param $iAccountId new Account ID
  178. * @return true on success or false otherwise
  179. */
  180. public function changeAccountId ($iProfileId, $iAccountId)
  181. {
  182. $aInfoOld = $this->getInfoById($iProfileId);
  183. $bRet = $this->_updateField ($iProfileId, 'account_id', $iAccountId);
  184. if ($bRet && $aInfoOld) {
  185. // invalidate profile switcher cache for old and new account
  186. bx_content_cache_del("profile_switcher_" . $aInfoOld['account_id'] . "_0");
  187. bx_content_cache_del("profile_switcher_" . $aInfoOld['account_id'] . "_1");
  188. bx_content_cache_del("profile_switcher_" . $iAccountId . "_0");
  189. bx_content_cache_del("profile_switcher_" . $iAccountId . "_1");
  190. }
  191. return $bRet;
  192. }
  193. /**
  194. * Update profile's status
  195. * @param $iProfileId profile id
  196. * @param $sStatus profile status
  197. * @return true on success or false otherwise
  198. */
  199. public function changeStatus ($iProfileId, $sStatus)
  200. {
  201. return $this->_updateField ($iProfileId, 'status', $sStatus);
  202. }
  203. /**
  204. * Update profile's content filter value (watch)
  205. * @param $iProfileId profile id
  206. * @param $iValue bitmask of selected items
  207. * @return true on success or false otherwise
  208. */
  209. public function changeCfwValue ($iProfileId, $iValue)
  210. {
  211. return $this->_updateField ($iProfileId, 'cfw_value', $iValue);
  212. }
  213. /**
  214. * Update profile's content filter items (watch)
  215. * @param $iProfileId profile id
  216. * @param $iValue bitmask of available items
  217. * @return true on success or false otherwise
  218. */
  219. public function changeCfwItems ($iProfileId, $iValue)
  220. {
  221. return $this->_updateField ($iProfileId, 'cfw_items', $iValue);
  222. }
  223. /**
  224. * Update profile's content filter items (use)
  225. * @param $iProfileId profile id
  226. * @param $iValue bitmask of available items
  227. * @return true on success or false otherwise
  228. */
  229. public function changeCfuItems ($iProfileId, $iValue)
  230. {
  231. return $this->_updateField ($iProfileId, 'cfu_items', $iValue);
  232. }
  233. /**
  234. * Get current account profile.
  235. * @param string $iAccountId account id
  236. * @return current account's profile id
  237. */
  238. public function getCurrentProfileByAccount ($iAccountId, $bClearCache = false)
  239. {
  240. if (!$iAccountId)
  241. return false;
  242. $sKey = 'BxDolProfileQuery::getCurrentProfileByAccount' . $iAccountId;
  243. if ($bClearCache)
  244. $this->cleanMemory($sKey);
  245. $sSql = $this->prepare("SELECT `profile_id` FROM `sys_accounts` AS `a` INNER JOIN `sys_profiles` AS `p` ON (`a`.`profile_id` = `p`.`id`) WHERE `a`.`id` = ? LIMIT 1", $iAccountId);
  246. $iProfileId = $this->fromMemory($sKey, 'getOne', $sSql);
  247. if (!$iProfileId) {
  248. $this->cleanMemory($sKey);
  249. $sSql = $this->prepare("SELECT `id` FROM `sys_profiles` WHERE `account_id` = ? ORDER BY FIELD(`type`, 'system', 'bx_organizations', 'bx_persons') DESC LIMIT 1", $iAccountId);
  250. $iProfileId = $this->getOne($sSql);
  251. if (!$iProfileId)
  252. return false;
  253. if (!BxDolAccountQuery::getInstance()->updateCurrentProfile($iAccountId, $iProfileId))
  254. return false;
  255. }
  256. return $iProfileId;
  257. }
  258. /**
  259. * Get profile by specified field name and value.
  260. * It is for internal usage only.
  261. * Use other funtions to get profile info, like getInfoById, etc.
  262. * @param string $sField database field name
  263. * @param mixed $sValue database field value
  264. * @return array with porfile info
  265. */
  266. protected function _getDataByField ($sField, $sValue)
  267. {
  268. $sSql = $this->prepare("SELECT * FROM `sys_profiles` WHERE `$sField` = ? LIMIT 1", $sValue);
  269. return $this->fromMemory('sys_profiles_' . $sField . '_' . $sValue, 'getRow', $sSql);
  270. }
  271. /**
  272. * get profile id by id
  273. */
  274. public function getIdById($iId, $bClearCache = false)
  275. {
  276. if (!$iId)
  277. return false;
  278. $sKey = 'BxDolProfileQuery::getIdById' . $iId;
  279. if ($bClearCache)
  280. $this->cleanMemory($sKey);
  281. $sSql = $this->prepare("SELECT `id` FROM `sys_profiles` WHERE `id` = ? LIMIT 1", $iId);
  282. $mixedResult = $this->fromMemory($sKey, 'getOne', $sSql);
  283. if (!$mixedResult)
  284. $this->cleanMemory($sKey);
  285. return $mixedResult;
  286. }
  287. /**
  288. * get account info by profile id
  289. */
  290. public function getAccountInfoByProfileId($iId)
  291. {
  292. $sSql = $this->prepare("SELECT `a`.* FROM `sys_accounts` AS `a` INNER JOIN `sys_profiles` AS `p` ON (`p`.`account_id` = `a`.`id`) WHERE `p`.`id` = ? LIMIT 1", $iId);
  293. return $this->getRow($sSql);
  294. }
  295. /**
  296. * get account email by profile id
  297. */
  298. public function getEmailById($iId)
  299. {
  300. $a = $this->getAccountInfoByProfileId($iId);
  301. if (!$a || empty($a['email']))
  302. return false;
  303. return $a['email'];
  304. }
  305. /**
  306. * Get profile info by id
  307. * @param int $iID profile id
  308. * @return array with profile info
  309. */
  310. public function getInfoById( $iID )
  311. {
  312. return $this->_getDataByField('id', (int)$iID);
  313. }
  314. /**
  315. * Is profile online by id
  316. * @param int $iId profile id
  317. * @return profile online status
  318. */
  319. public function isOnline($iId)
  320. {
  321. $sSql = $this->prepare("SELECT
  322. `tp`.`id`
  323. FROM `sys_profiles` AS `tp`
  324. INNER JOIN `sys_accounts` AS `ta` ON `tp`.`account_id`=`ta`.`id`
  325. INNER JOIN `sys_sessions` AS `ts` ON `tp`.`account_id`=`ts`.`user_id`
  326. WHERE
  327. `tp`.`id` = ? AND
  328. `ta`.`profile_id`=`tp`.`id` AND
  329. `ts`.`date` > (UNIX_TIMESTAMP() - 60 * ?)
  330. LIMIT 1", $iId, (int)getParam('sys_account_online_time'));
  331. return (int)$this->getOne($sSql) > 0;
  332. }
  333. /**
  334. * Get online profiles count
  335. * @return online profiles count
  336. */
  337. public function getOnlineCount()
  338. {
  339. $sSql = $this->prepare("SELECT
  340. COUNT(`tp`.`id`)
  341. FROM `sys_profiles` AS `tp`
  342. INNER JOIN `sys_accounts` AS `ta` ON `tp`.`account_id`=`ta`.`id`
  343. INNER JOIN `sys_sessions` AS `ts` ON `tp`.`account_id`=`ts`.`user_id`
  344. WHERE
  345. `ta`.`profile_id`=`tp`.`id` AND
  346. `ts`.`date` > (UNIX_TIMESTAMP() - 60 * ?)", (int)getParam('sys_account_online_time'));
  347. return (int)$this->getOne($sSql);
  348. }
  349. public function getProfileQuota($iProfileId)
  350. {
  351. $a = ['current_size' => 0, 'current_number' => 0, 'quota_size' => 0, 'quota_number' => 0, 'max_file_size' => 0];
  352. if ($iProfileId) {
  353. $sQuery = $this->prepare("SELECT `current_size`, `current_number`, 0 as `quota_size`, 0 as `quota_number`, 0 as `max_file_size` FROM `sys_storage_user_quotas` WHERE `profile_id` = ?", $iProfileId);
  354. $a = $this->getRow($sQuery);
  355. if (!is_array($a) || !$a)
  356. $a = ['current_size' => 0, 'current_number' => 0, 'quota_size' => 0, 'quota_number' => 0, 'max_file_size' => 0];
  357. }
  358. // get quota_number and quota_size from user's acl/membership
  359. $aMembershipInfo = BxDolAcl::getInstance()->getMemberMembershipInfo($iProfileId);
  360. if ($aMembershipInfo) {
  361. if (isset($aMembershipInfo['quota_size']))
  362. $a['quota_size'] = $aMembershipInfo['quota_size'];
  363. if (isset($aMembershipInfo['quota_number']))
  364. $a['quota_number'] = $aMembershipInfo['quota_number'];
  365. if (isset($aMembershipInfo['quota_max_file_size']))
  366. $a['max_file_size'] = $aMembershipInfo['quota_max_file_size'];
  367. }
  368. return $a;
  369. }
  370. public function updateProfileQuota($iProfileId, $iSize, $iNumber = 1)
  371. {
  372. if (!$iProfileId) // for guests and storages without owner don't update per-user quota
  373. return true;
  374. $iTime = time();
  375. $sQuery = $this->prepare("
  376. INSERT INTO `sys_storage_user_quotas`
  377. SET `profile_id` = ?, `current_size` = `current_size` + ?, `current_number` = `current_number` + ?, `ts` = ?
  378. ON DUPLICATE KEY UPDATE `current_size` = `current_size` + ?, `current_number` = `current_number` + ?, `ts` = ?",
  379. $iProfileId, $iSize, $iNumber, $iTime, $iSize, $iNumber, $iTime
  380. );
  381. if ($this->query($sQuery))
  382. return true;
  383. else
  384. return false;
  385. }
  386. /**
  387. * Get profile field by specified field name and value.
  388. * In most cases it is for internal usage only.
  389. * Use other funtions to get profile info, like getIdByEmail, etc.
  390. * @param string $sFieldRequested database field name to return
  391. * @param string $sFieldSearch database field name to search for
  392. * @param mixed $sValue database field value
  393. * @return specified profile field value
  394. */
  395. protected function _getFieldByField ($sFieldRequested, $sFieldSearch, $sValue)
  396. {
  397. $sSql = $this->prepare("SELECT `$sFieldRequested` FROM `sys_profiles` WHERE `$sFieldSearch` = ? LIMIT 1", $sValue);
  398. return $this->getOne($sSql);
  399. }
  400. /**
  401. * Update some field by profile id
  402. * In most cases it is for internal usage only.
  403. * Use other funtions to get profile info, like updateLogged, etc.
  404. * @param string $sFieldRequested database field name to return
  405. * @param string $sFieldSearch database field name to search for
  406. * @param mixed $sValue database field value
  407. * @return specified profile field value
  408. */
  409. protected function _updateField ($iId, $sFieldForUpdate, $sValue)
  410. {
  411. $sSql = $this->prepare("UPDATE `sys_profiles` SET `$sFieldForUpdate` = ? WHERE `id` = ? LIMIT 1", $sValue, $iId);
  412. return $this->query($sSql);
  413. }
  414. /**
  415. * Delete profile info by id
  416. * @param int $iID profile id
  417. * @return affected rows
  418. */
  419. public function delete($iID)
  420. {
  421. $aInfo = $this->getInfoById($iID);
  422. $sSql = $this->prepare("DELETE FROM `sys_profiles` WHERE `id` = ? LIMIT 1", $iID);
  423. if ($res = $this->query($sSql)) {
  424. $this->getProfileByContentAndType($aInfo['content_id'], $aInfo['type'], true);
  425. $this->getCurrentProfileByAccount($aInfo['account_id'], true);
  426. $this->getIdById($iID, true);
  427. }
  428. return $res;
  429. }
  430. /**
  431. * Reset deleted profile ids and assign system profile ids.
  432. * Should be called after profiles module deletion.
  433. * It can be called automatically if
  434. * @code
  435. * 'process_deleted_profiles' => 1
  436. * @endcode
  437. * is specified in module config.php file in 'uninstall' section.
  438. */
  439. public function processDeletedProfiles ()
  440. {
  441. $bResult = true;
  442. // reset deleted profiles
  443. $bResult &= $this->query("UPDATE `sys_accounts` AS `a` LEFT OUTER JOIN `sys_profiles` AS `p` ON `a`.`profile_id`=`p`.`id` SET `a`.`profile_id`='0' WHERE `p`.`id` IS NULL") !== false;
  444. // try to assign another non-system profile to reset accounts
  445. $bResult &= $this->query("UPDATE `sys_accounts` AS `a` INNER JOIN `sys_profiles` AS `p` ON `a`.`id`=`p`.`account_id` AND `p`.`type`<>'system' AND `a`.`profile_id`='0' SET `a`.`profile_id`=`p`.`id`") !== false;
  446. // assign system profile to reset accounts
  447. $bResult &= $this->query("UPDATE `sys_accounts` AS `a` INNER JOIN `sys_profiles` AS `p` ON `a`.`id`=`p`.`account_id` AND `p`.`type`='system' AND `a`.`profile_id`='0' SET `a`.`profile_id`=`p`.`id`") !== false;
  448. return $bResult;
  449. }
  450. public function updateProfileTrack($iProfileId, $sAction)
  451. {
  452. return $this->query("INSERT INTO `sys_profiles_track` SET `profile_id`=:profile_id, `action`=:action, `date`=:now ON DUPLICATE KEY UPDATE `date`=:now", [
  453. 'profile_id' => $iProfileId,
  454. 'action' => $sAction,
  455. 'now' => time()
  456. ]);
  457. }
  458. public function getProfileTrack($iProfileId, $sAction)
  459. {
  460. return (int)$this->getOne("SELECT `date` FROM `sys_profiles_track` WHERE `profile_id`=:profile_id AND `action`=:action LIMIT 1", [
  461. 'profile_id' => $iProfileId,
  462. 'action' => $sAction
  463. ]);
  464. }
  465. }
  466. /** @} */