BxDolProfileQuery.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  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 'all':
  91. break;
  92. }
  93. $sGroupClause = $sGroupClause ? "GROUP BY " . $sGroupClause : "";
  94. $sOrderClause = $sOrderClause ? "ORDER BY " . $sOrderClause : "";
  95. $aMethod['params'][0] = "SELECT
  96. " . $sFieldsClause . "
  97. FROM `sys_profiles` AS `tp`" . $sJoinClause . "
  98. WHERE 1" . $sWhereClause . " " . $sGroupClause . " " . $sOrderClause;
  99. return call_user_func_array([$this, $aMethod['name']], $aMethod['params']);
  100. }
  101. /**
  102. * Get profile by content id, type and account.
  103. * @param string $iAccountId account id
  104. * @return array if aprofile ids, key is profile id
  105. */
  106. public function getProfileByContentTypeAccount ($iContentId, $sType, $iAccountId)
  107. {
  108. $sSql = $this->prepare("SELECT * FROM `sys_profiles` WHERE `account_id` = ? AND `type` = ? AND `content_id` = ?", $iAccountId, $sType, $iContentId);
  109. return $this->getRow($sSql);
  110. }
  111. /**
  112. * Get profile by content id and type.
  113. * @param string $iAccountId account id
  114. * @return array if aprofile ids, key is profile id
  115. */
  116. public function getProfileByContentAndType ($iContentId, $sType, $bClearCache = false)
  117. {
  118. if (!$iContentId)
  119. return false;
  120. $sKey = 'BxDolProfileQuery::getProfileByContentAndType' . $iContentId . $sType;
  121. if ($bClearCache)
  122. $this->cleanMemory($sKey);
  123. $sSql = $this->prepare("SELECT * FROM `sys_profiles` WHERE `content_id` = ? AND `type` = ?", $iContentId, $sType);
  124. $mixedResult = $this->fromMemory($sKey, 'getRow', $sSql);
  125. if (!$mixedResult)
  126. $this->cleanMemory($sKey);
  127. return $mixedResult;
  128. }
  129. public function getConnectedProfilesByType ($aSqlParts, $sType, $iStart, $iLimit)
  130. {
  131. if(empty($aSqlParts['join']))
  132. return array();
  133. $aBindings = array();
  134. $sSelectClause = '';
  135. if(!empty($aSqlParts['fields']))
  136. foreach($aSqlParts['fields'] as $sName => $sField)
  137. $sSelectClause .= ', ' . $sField;
  138. $sWhereClause = '';
  139. if(!empty($sType)) {
  140. $sWhereClause = ' AND `sys_profiles`.`type`=:type';
  141. $aBindings['type'] = $sType;
  142. }
  143. $sOrderClause = '';
  144. if(!empty($aSqlParts['fields']['added']))
  145. $sOrderClause = ' ORDER BY ' . $aSqlParts['fields']['added'] . ' DESC';
  146. $sLimitClause = '';
  147. if(!empty($iLimit))
  148. $sLimitClause = $this->prepareAsString(' LIMIT ?, ?', $iStart, $iLimit);
  149. return $this->getAllWithKey("SELECT `sys_profiles`.*" . $sSelectClause . " FROM `sys_profiles` " . $aSqlParts['join'] . " WHERE 1" . $sWhereClause . $sOrderClause . $sLimitClause, 'id', $aBindings);
  150. }
  151. /**
  152. * Insert account and content id association. Also if currect profile id is not defined - it updates current profile id in account.
  153. * @param $iAccountId account id
  154. * @param $iContentId content id
  155. * @param $sStatus profile status
  156. * @param $sType profile content type
  157. * @return inserted profile's id
  158. */
  159. public function insertProfile ($iAccountId, $iContentId, $sStatus, $sType = 'system')
  160. {
  161. $sSql = $this->prepare("INSERT INTO `sys_profiles` SET `account_id` = ?, `type` = ?, `content_id` = ?, `status` = ?", $iAccountId, $sType, $iContentId, $sStatus);
  162. if (!$this->query($sSql))
  163. return false;
  164. $iProfileId = $this->lastId();
  165. $this->getCurrentProfileByAccount($iAccountId); // it updates current profile id automatically if it is not defined
  166. return $iProfileId;
  167. }
  168. /**
  169. * Update profile's status
  170. * @param $iProfileId profile id
  171. * @param $sStatus profile status
  172. * @return true on success or false otherwise
  173. */
  174. public function changeStatus ($iProfileId, $sStatus)
  175. {
  176. return $this->_updateField ($iProfileId, 'status', $sStatus);
  177. }
  178. /**
  179. * Update profile's content filter value (watch)
  180. * @param $iProfileId profile id
  181. * @param $iValue bitmask of selected items
  182. * @return true on success or false otherwise
  183. */
  184. public function changeCfwValue ($iProfileId, $iValue)
  185. {
  186. return $this->_updateField ($iProfileId, 'cfw_value', $iValue);
  187. }
  188. /**
  189. * Update profile's content filter items (watch)
  190. * @param $iProfileId profile id
  191. * @param $iValue bitmask of available items
  192. * @return true on success or false otherwise
  193. */
  194. public function changeCfwItems ($iProfileId, $iValue)
  195. {
  196. return $this->_updateField ($iProfileId, 'cfw_items', $iValue);
  197. }
  198. /**
  199. * Update profile's content filter items (use)
  200. * @param $iProfileId profile id
  201. * @param $iValue bitmask of available items
  202. * @return true on success or false otherwise
  203. */
  204. public function changeCfuItems ($iProfileId, $iValue)
  205. {
  206. return $this->_updateField ($iProfileId, 'cfu_items', $iValue);
  207. }
  208. /**
  209. * Get current account profile.
  210. * @param string $iAccountId account id
  211. * @return current account's profile id
  212. */
  213. public function getCurrentProfileByAccount ($iAccountId, $bClearCache = false)
  214. {
  215. if (!$iAccountId)
  216. return false;
  217. $sKey = 'BxDolProfileQuery::getCurrentProfileByAccount' . $iAccountId;
  218. if ($bClearCache)
  219. $this->cleanMemory($sKey);
  220. $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);
  221. $iProfileId = $this->fromMemory($sKey, 'getOne', $sSql);
  222. if (!$iProfileId) {
  223. $this->cleanMemory($sKey);
  224. $sSql = $this->prepare("SELECT `id` FROM `sys_profiles` WHERE `account_id` = ? ORDER BY FIELD(`type`, 'system', 'bx_organizations', 'bx_persons') DESC LIMIT 1", $iAccountId);
  225. $iProfileId = $this->getOne($sSql);
  226. if (!$iProfileId)
  227. return false;
  228. if (!BxDolAccountQuery::getInstance()->updateCurrentProfile($iAccountId, $iProfileId))
  229. return false;
  230. }
  231. return $iProfileId;
  232. }
  233. /**
  234. * Get profile by specified field name and value.
  235. * It is for internal usage only.
  236. * Use other funtions to get profile info, like getInfoById, etc.
  237. * @param string $sField database field name
  238. * @param mixed $sValue database field value
  239. * @return array with porfile info
  240. */
  241. protected function _getDataByField ($sField, $sValue)
  242. {
  243. $sSql = $this->prepare("SELECT * FROM `sys_profiles` WHERE `$sField` = ? LIMIT 1", $sValue);
  244. return $this->fromMemory('sys_profiles_' . $sField . '_' . $sValue, 'getRow', $sSql);
  245. }
  246. /**
  247. * get profile id by id
  248. */
  249. public function getIdById($iId, $bClearCache = false)
  250. {
  251. if (!$iId)
  252. return false;
  253. $sKey = 'BxDolProfileQuery::getIdById' . $iId;
  254. if ($bClearCache)
  255. $this->cleanMemory($sKey);
  256. $sSql = $this->prepare("SELECT `id` FROM `sys_profiles` WHERE `id` = ? LIMIT 1", $iId);
  257. $mixedResult = $this->fromMemory($sKey, 'getOne', $sSql);
  258. if (!$mixedResult)
  259. $this->cleanMemory($sKey);
  260. return $mixedResult;
  261. }
  262. /**
  263. * get account info by profile id
  264. */
  265. public function getAccountInfoByProfileId($iId)
  266. {
  267. $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);
  268. return $this->getRow($sSql);
  269. }
  270. /**
  271. * get account email by profile id
  272. */
  273. public function getEmailById($iId)
  274. {
  275. $a = $this->getAccountInfoByProfileId($iId);
  276. if (!$a || empty($a['email']))
  277. return false;
  278. return $a['email'];
  279. }
  280. /**
  281. * Get profile info by id
  282. * @param int $iID profile id
  283. * @return array with profile info
  284. */
  285. public function getInfoById( $iID )
  286. {
  287. return $this->_getDataByField('id', (int)$iID);
  288. }
  289. /**
  290. * Is profile online by id
  291. * @param int $iId profile id
  292. * @return profile online status
  293. */
  294. public function isOnline($iId)
  295. {
  296. $sSql = $this->prepare("SELECT
  297. `tp`.`id`
  298. FROM `sys_profiles` AS `tp`
  299. INNER JOIN `sys_accounts` AS `ta` ON `tp`.`account_id`=`ta`.`id`
  300. INNER JOIN `sys_sessions` AS `ts` ON `tp`.`account_id`=`ts`.`user_id`
  301. WHERE
  302. `tp`.`id` = ? AND
  303. `ta`.`profile_id`=`tp`.`id` AND
  304. `ts`.`date` > (UNIX_TIMESTAMP() - 60 * ?)
  305. LIMIT 1", $iId, (int)getParam('sys_account_online_time'));
  306. return (int)$this->getOne($sSql) > 0;
  307. }
  308. /**
  309. * Get online profiles count
  310. * @return online profiles count
  311. */
  312. public function getOnlineCount()
  313. {
  314. $sSql = $this->prepare("SELECT
  315. COUNT(`tp`.`id`)
  316. FROM `sys_profiles` AS `tp`
  317. INNER JOIN `sys_accounts` AS `ta` ON `tp`.`account_id`=`ta`.`id`
  318. INNER JOIN `sys_sessions` AS `ts` ON `tp`.`account_id`=`ts`.`user_id`
  319. WHERE
  320. `ta`.`profile_id`=`tp`.`id` AND
  321. `ts`.`date` > (UNIX_TIMESTAMP() - 60 * ?)", (int)getParam('sys_account_online_time'));
  322. return (int)$this->getOne($sSql);
  323. }
  324. public function getProfileQuota($iProfileId)
  325. {
  326. $a = ['current_size' => 0, 'current_number' => 0, 'quota_size' => 0, 'quota_number' => 0, 'max_file_size' => 0];
  327. if ($iProfileId) {
  328. $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);
  329. $a = $this->getRow($sQuery);
  330. if (!is_array($a) || !$a)
  331. $a = ['current_size' => 0, 'current_number' => 0, 'quota_size' => 0, 'quota_number' => 0, 'max_file_size' => 0];
  332. }
  333. // get quota_number and quota_size from user's acl/membership
  334. $aMembershipInfo = BxDolAcl::getInstance()->getMemberMembershipInfo($iProfileId);
  335. if ($aMembershipInfo) {
  336. if (isset($aMembershipInfo['quota_size']))
  337. $a['quota_size'] = $aMembershipInfo['quota_size'];
  338. if (isset($aMembershipInfo['quota_number']))
  339. $a['quota_number'] = $aMembershipInfo['quota_number'];
  340. if (isset($aMembershipInfo['quota_max_file_size']))
  341. $a['max_file_size'] = $aMembershipInfo['quota_max_file_size'];
  342. }
  343. return $a;
  344. }
  345. public function updateProfileQuota($iProfileId, $iSize, $iNumber = 1)
  346. {
  347. if (!$iProfileId) // for guests and storages without owner don't update per-user quota
  348. return true;
  349. $iTime = time();
  350. $sQuery = $this->prepare("
  351. INSERT INTO `sys_storage_user_quotas`
  352. SET `profile_id` = ?, `current_size` = `current_size` + ?, `current_number` = `current_number` + ?, `ts` = ?
  353. ON DUPLICATE KEY UPDATE `current_size` = `current_size` + ?, `current_number` = `current_number` + ?, `ts` = ?",
  354. $iProfileId, $iSize, $iNumber, $iTime, $iSize, $iNumber, $iTime
  355. );
  356. if ($this->query($sQuery))
  357. return true;
  358. else
  359. return false;
  360. }
  361. /**
  362. * Get profile field by specified field name and value.
  363. * In most cases it is for internal usage only.
  364. * Use other funtions to get profile info, like getIdByEmail, etc.
  365. * @param string $sFieldRequested database field name to return
  366. * @param string $sFieldSearch database field name to search for
  367. * @param mixed $sValue database field value
  368. * @return specified profile field value
  369. */
  370. protected function _getFieldByField ($sFieldRequested, $sFieldSearch, $sValue)
  371. {
  372. $sSql = $this->prepare("SELECT `$sFieldRequested` FROM `sys_profiles` WHERE `$sFieldSearch` = ? LIMIT 1", $sValue);
  373. return $this->getOne($sSql);
  374. }
  375. /**
  376. * Update some field by profile id
  377. * In most cases it is for internal usage only.
  378. * Use other funtions to get profile info, like updateLogged, etc.
  379. * @param string $sFieldRequested database field name to return
  380. * @param string $sFieldSearch database field name to search for
  381. * @param mixed $sValue database field value
  382. * @return specified profile field value
  383. */
  384. protected function _updateField ($iId, $sFieldForUpdate, $sValue)
  385. {
  386. $sSql = $this->prepare("UPDATE `sys_profiles` SET `$sFieldForUpdate` = ? WHERE `id` = ? LIMIT 1", $sValue, $iId);
  387. return $this->query($sSql);
  388. }
  389. /**
  390. * Delete profile info by id
  391. * @param int $iID profile id
  392. * @return affected rows
  393. */
  394. public function delete($iID)
  395. {
  396. $aInfo = $this->getInfoById($iID);
  397. $sSql = $this->prepare("DELETE FROM `sys_profiles` WHERE `id` = ? LIMIT 1", $iID);
  398. if ($res = $this->query($sSql)) {
  399. $this->getProfileByContentAndType($aInfo['content_id'], $aInfo['type'], true);
  400. $this->getCurrentProfileByAccount($aInfo['account_id'], true);
  401. $this->getIdById($iID, true);
  402. }
  403. return $res;
  404. }
  405. /**
  406. * Reset deleted profile ids and assign system profile ids.
  407. * Should be called after profiles module deletion.
  408. * It can be called automatically if
  409. * @code
  410. * 'process_deleted_profiles' => 1
  411. * @endcode
  412. * is specified in module config.php file in 'uninstall' section.
  413. */
  414. public function processDeletedProfiles ()
  415. {
  416. $bResult = true;
  417. // reset deleted profiles
  418. $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;
  419. // try to assign another non-system profile to reset accounts
  420. $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;
  421. // assign system profile to reset accounts
  422. $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;
  423. return $bResult;
  424. }
  425. }
  426. /** @} */