BxDolProfileQuery.php 18 KB

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