BxDolProfileQuery.php 17 KB

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