1
0

BxDolProfileQuery.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  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. return $this->_updateField ($iProfileId, 'account_id', $iAccountId);
  183. }
  184. /**
  185. * Update profile's status
  186. * @param $iProfileId profile id
  187. * @param $sStatus profile status
  188. * @return true on success or false otherwise
  189. */
  190. public function changeStatus ($iProfileId, $sStatus)
  191. {
  192. return $this->_updateField ($iProfileId, 'status', $sStatus);
  193. }
  194. /**
  195. * Update profile's content filter value (watch)
  196. * @param $iProfileId profile id
  197. * @param $iValue bitmask of selected items
  198. * @return true on success or false otherwise
  199. */
  200. public function changeCfwValue ($iProfileId, $iValue)
  201. {
  202. return $this->_updateField ($iProfileId, 'cfw_value', $iValue);
  203. }
  204. /**
  205. * Update profile's content filter items (watch)
  206. * @param $iProfileId profile id
  207. * @param $iValue bitmask of available items
  208. * @return true on success or false otherwise
  209. */
  210. public function changeCfwItems ($iProfileId, $iValue)
  211. {
  212. return $this->_updateField ($iProfileId, 'cfw_items', $iValue);
  213. }
  214. /**
  215. * Update profile's content filter items (use)
  216. * @param $iProfileId profile id
  217. * @param $iValue bitmask of available items
  218. * @return true on success or false otherwise
  219. */
  220. public function changeCfuItems ($iProfileId, $iValue)
  221. {
  222. return $this->_updateField ($iProfileId, 'cfu_items', $iValue);
  223. }
  224. /**
  225. * Get current account profile.
  226. * @param string $iAccountId account id
  227. * @return current account's profile id
  228. */
  229. public function getCurrentProfileByAccount ($iAccountId, $bClearCache = false)
  230. {
  231. if (!$iAccountId)
  232. return false;
  233. $sKey = 'BxDolProfileQuery::getCurrentProfileByAccount' . $iAccountId;
  234. if ($bClearCache)
  235. $this->cleanMemory($sKey);
  236. $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);
  237. $iProfileId = $this->fromMemory($sKey, 'getOne', $sSql);
  238. if (!$iProfileId) {
  239. $this->cleanMemory($sKey);
  240. $sSql = $this->prepare("SELECT `id` FROM `sys_profiles` WHERE `account_id` = ? ORDER BY FIELD(`type`, 'system', 'bx_organizations', 'bx_persons') DESC LIMIT 1", $iAccountId);
  241. $iProfileId = $this->getOne($sSql);
  242. if (!$iProfileId)
  243. return false;
  244. if (!BxDolAccountQuery::getInstance()->updateCurrentProfile($iAccountId, $iProfileId))
  245. return false;
  246. }
  247. return $iProfileId;
  248. }
  249. /**
  250. * Get profile by specified field name and value.
  251. * It is for internal usage only.
  252. * Use other funtions to get profile info, like getInfoById, etc.
  253. * @param string $sField database field name
  254. * @param mixed $sValue database field value
  255. * @return array with porfile info
  256. */
  257. protected function _getDataByField ($sField, $sValue)
  258. {
  259. $sSql = $this->prepare("SELECT * FROM `sys_profiles` WHERE `$sField` = ? LIMIT 1", $sValue);
  260. return $this->fromMemory('sys_profiles_' . $sField . '_' . $sValue, 'getRow', $sSql);
  261. }
  262. /**
  263. * get profile id by id
  264. */
  265. public function getIdById($iId, $bClearCache = false)
  266. {
  267. if (!$iId)
  268. return false;
  269. $sKey = 'BxDolProfileQuery::getIdById' . $iId;
  270. if ($bClearCache)
  271. $this->cleanMemory($sKey);
  272. $sSql = $this->prepare("SELECT `id` FROM `sys_profiles` WHERE `id` = ? LIMIT 1", $iId);
  273. $mixedResult = $this->fromMemory($sKey, 'getOne', $sSql);
  274. if (!$mixedResult)
  275. $this->cleanMemory($sKey);
  276. return $mixedResult;
  277. }
  278. /**
  279. * get account info by profile id
  280. */
  281. public function getAccountInfoByProfileId($iId)
  282. {
  283. $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);
  284. return $this->getRow($sSql);
  285. }
  286. /**
  287. * get account email by profile id
  288. */
  289. public function getEmailById($iId)
  290. {
  291. $a = $this->getAccountInfoByProfileId($iId);
  292. if (!$a || empty($a['email']))
  293. return false;
  294. return $a['email'];
  295. }
  296. /**
  297. * Get profile info by id
  298. * @param int $iID profile id
  299. * @return array with profile info
  300. */
  301. public function getInfoById( $iID )
  302. {
  303. return $this->_getDataByField('id', (int)$iID);
  304. }
  305. /**
  306. * Is profile online by id
  307. * @param int $iId profile id
  308. * @return profile online status
  309. */
  310. public function isOnline($iId)
  311. {
  312. $sSql = $this->prepare("SELECT
  313. `tp`.`id`
  314. FROM `sys_profiles` AS `tp`
  315. INNER JOIN `sys_accounts` AS `ta` ON `tp`.`account_id`=`ta`.`id`
  316. INNER JOIN `sys_sessions` AS `ts` ON `tp`.`account_id`=`ts`.`user_id`
  317. WHERE
  318. `tp`.`id` = ? AND
  319. `ta`.`profile_id`=`tp`.`id` AND
  320. `ts`.`date` > (UNIX_TIMESTAMP() - 60 * ?)
  321. LIMIT 1", $iId, (int)getParam('sys_account_online_time'));
  322. return (int)$this->getOne($sSql) > 0;
  323. }
  324. /**
  325. * Get online profiles count
  326. * @return online profiles count
  327. */
  328. public function getOnlineCount()
  329. {
  330. $sSql = $this->prepare("SELECT
  331. COUNT(`tp`.`id`)
  332. FROM `sys_profiles` AS `tp`
  333. INNER JOIN `sys_accounts` AS `ta` ON `tp`.`account_id`=`ta`.`id`
  334. INNER JOIN `sys_sessions` AS `ts` ON `tp`.`account_id`=`ts`.`user_id`
  335. WHERE
  336. `ta`.`profile_id`=`tp`.`id` AND
  337. `ts`.`date` > (UNIX_TIMESTAMP() - 60 * ?)", (int)getParam('sys_account_online_time'));
  338. return (int)$this->getOne($sSql);
  339. }
  340. public function getProfileQuota($iProfileId)
  341. {
  342. $a = ['current_size' => 0, 'current_number' => 0, 'quota_size' => 0, 'quota_number' => 0, 'max_file_size' => 0];
  343. if ($iProfileId) {
  344. $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);
  345. $a = $this->getRow($sQuery);
  346. if (!is_array($a) || !$a)
  347. $a = ['current_size' => 0, 'current_number' => 0, 'quota_size' => 0, 'quota_number' => 0, 'max_file_size' => 0];
  348. }
  349. // get quota_number and quota_size from user's acl/membership
  350. $aMembershipInfo = BxDolAcl::getInstance()->getMemberMembershipInfo($iProfileId);
  351. if ($aMembershipInfo) {
  352. if (isset($aMembershipInfo['quota_size']))
  353. $a['quota_size'] = $aMembershipInfo['quota_size'];
  354. if (isset($aMembershipInfo['quota_number']))
  355. $a['quota_number'] = $aMembershipInfo['quota_number'];
  356. if (isset($aMembershipInfo['quota_max_file_size']))
  357. $a['max_file_size'] = $aMembershipInfo['quota_max_file_size'];
  358. }
  359. return $a;
  360. }
  361. public function updateProfileQuota($iProfileId, $iSize, $iNumber = 1)
  362. {
  363. if (!$iProfileId) // for guests and storages without owner don't update per-user quota
  364. return true;
  365. $iTime = time();
  366. $sQuery = $this->prepare("
  367. INSERT INTO `sys_storage_user_quotas`
  368. SET `profile_id` = ?, `current_size` = `current_size` + ?, `current_number` = `current_number` + ?, `ts` = ?
  369. ON DUPLICATE KEY UPDATE `current_size` = `current_size` + ?, `current_number` = `current_number` + ?, `ts` = ?",
  370. $iProfileId, $iSize, $iNumber, $iTime, $iSize, $iNumber, $iTime
  371. );
  372. if ($this->query($sQuery))
  373. return true;
  374. else
  375. return false;
  376. }
  377. /**
  378. * Get profile field by specified field name and value.
  379. * In most cases it is for internal usage only.
  380. * Use other funtions to get profile info, like getIdByEmail, etc.
  381. * @param string $sFieldRequested database field name to return
  382. * @param string $sFieldSearch database field name to search for
  383. * @param mixed $sValue database field value
  384. * @return specified profile field value
  385. */
  386. protected function _getFieldByField ($sFieldRequested, $sFieldSearch, $sValue)
  387. {
  388. $sSql = $this->prepare("SELECT `$sFieldRequested` FROM `sys_profiles` WHERE `$sFieldSearch` = ? LIMIT 1", $sValue);
  389. return $this->getOne($sSql);
  390. }
  391. /**
  392. * Update some field by profile id
  393. * In most cases it is for internal usage only.
  394. * Use other funtions to get profile info, like updateLogged, etc.
  395. * @param string $sFieldRequested database field name to return
  396. * @param string $sFieldSearch database field name to search for
  397. * @param mixed $sValue database field value
  398. * @return specified profile field value
  399. */
  400. protected function _updateField ($iId, $sFieldForUpdate, $sValue)
  401. {
  402. $sSql = $this->prepare("UPDATE `sys_profiles` SET `$sFieldForUpdate` = ? WHERE `id` = ? LIMIT 1", $sValue, $iId);
  403. return $this->query($sSql);
  404. }
  405. /**
  406. * Delete profile info by id
  407. * @param int $iID profile id
  408. * @return affected rows
  409. */
  410. public function delete($iID)
  411. {
  412. $aInfo = $this->getInfoById($iID);
  413. $sSql = $this->prepare("DELETE FROM `sys_profiles` WHERE `id` = ? LIMIT 1", $iID);
  414. if ($res = $this->query($sSql)) {
  415. $this->getProfileByContentAndType($aInfo['content_id'], $aInfo['type'], true);
  416. $this->getCurrentProfileByAccount($aInfo['account_id'], true);
  417. $this->getIdById($iID, true);
  418. }
  419. return $res;
  420. }
  421. /**
  422. * Reset deleted profile ids and assign system profile ids.
  423. * Should be called after profiles module deletion.
  424. * It can be called automatically if
  425. * @code
  426. * 'process_deleted_profiles' => 1
  427. * @endcode
  428. * is specified in module config.php file in 'uninstall' section.
  429. */
  430. public function processDeletedProfiles ()
  431. {
  432. $bResult = true;
  433. // reset deleted profiles
  434. $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;
  435. // try to assign another non-system profile to reset accounts
  436. $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;
  437. // assign system profile to reset accounts
  438. $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;
  439. return $bResult;
  440. }
  441. public function updateProfileTrack($iProfileId, $sAction)
  442. {
  443. return $this->query("INSERT INTO `sys_profiles_track` SET `profile_id`=:profile_id, `action`=:action, `date`=:now ON DUPLICATE KEY UPDATE `date`=:now", [
  444. 'profile_id' => $iProfileId,
  445. 'action' => $sAction,
  446. 'now' => time()
  447. ]);
  448. }
  449. public function getProfileTrack($iProfileId, $sAction)
  450. {
  451. return (int)$this->getOne("SELECT `date` FROM `sys_profiles_track` WHERE `profile_id`=:profile_id AND `action`=:action LIMIT 1", [
  452. 'profile_id' => $iProfileId,
  453. 'action' => $sAction
  454. ]);
  455. }
  456. }
  457. /** @} */