BxDolAcl.php 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707
  1. <?php defined('BX_DOL') or die('hack attempt');
  2. /**
  3. * Copyright (c) BoonEx Pty Limited - http://www.boonex.com/
  4. * CC-BY License - http://creativecommons.org/licenses/by/3.0/
  5. *
  6. * @defgroup DolphinCore Dolphin Core
  7. * @{
  8. */
  9. bx_import('BxDol');
  10. bx_import('BxDolAclQuery');
  11. /**
  12. * Message constants passed to _t_ext() function by checkAction()
  13. *
  14. * NOTE: checkAction() returns language dependent messages
  15. */
  16. define('CHECK_ACTION_MESSAGE_NOT_ALLOWED', "_sys_acl_action_not_allowed");
  17. define('CHECK_ACTION_MESSAGE_LIMIT_REACHED', "_sys_acl_action_limit_reached");
  18. define('CHECK_ACTION_MESSAGE_MESSAGE_EVERY_PERIOD', "_sys_acl_action_every_period");
  19. define('CHECK_ACTION_MESSAGE_NOT_ALLOWED_BEFORE', "_sys_acl_action_not_allowed_before");
  20. define('CHECK_ACTION_MESSAGE_NOT_ALLOWED_AFTER', "_sys_acl_action_not_allowed_after");
  21. define('CHECK_ACTION_MESSAGE_UNAUTHENTICATED', "_sys_acl_action_unauthenticated");
  22. define('CHECK_ACTION_MESSAGE_UNCONFIRMED', "_sys_acl_action_unconfirmed");
  23. define('CHECK_ACTION_MESSAGE_PENDING', "_sys_acl_action_pending");
  24. define('CHECK_ACTION_MESSAGE_SUSPENDED', "_sys_acl_action_suspended");
  25. /**
  26. * Nodes of $args array that are passed to _t_ext() function by checkAction()
  27. */
  28. define('CHECK_ACTION_LANG_FILE_ACTION', 1);
  29. define('CHECK_ACTION_LANG_FILE_MEMBERSHIP', 2);
  30. define('CHECK_ACTION_LANG_FILE_LIMIT', 3);
  31. define('CHECK_ACTION_LANG_FILE_PERIOD', 4);
  32. define('CHECK_ACTION_LANG_FILE_AFTER', 5);
  33. define('CHECK_ACTION_LANG_FILE_BEFORE', 6);
  34. define('CHECK_ACTION_LANG_FILE_SITE_EMAIL', 7);
  35. /**
  36. * Standard membership ID's
  37. */
  38. define('MEMBERSHIP_ID_NON_MEMBER', 1);
  39. define('MEMBERSHIP_ID_STANDARD', 2);
  40. define('MEMBERSHIP_ID_UNCONFIRMED', 3);
  41. define('MEMBERSHIP_ID_PENDING', 4);
  42. define('MEMBERSHIP_ID_SUSPENDED', 5);
  43. define('MEMBERSHIP_ID_MODERATOR', 6);
  44. define('MEMBERSHIP_ID_ADMINISTRATOR', 7);
  45. /**
  46. * Indices for checkAction() result array
  47. */
  48. define('CHECK_ACTION_RESULT', 0);
  49. define('CHECK_ACTION_MESSAGE', 1);
  50. define('CHECK_ACTION_PARAMETER', 3);
  51. /**
  52. * CHECK_ACTION_RESULT node values
  53. */
  54. define('CHECK_ACTION_RESULT_ALLOWED', 0);
  55. define('CHECK_ACTION_RESULT_NOT_ALLOWED', 1);
  56. define('CHECK_ACTION_RESULT_NOT_ACTIVE', 2);
  57. define('CHECK_ACTION_RESULT_LIMIT_REACHED', 3);
  58. define('CHECK_ACTION_RESULT_NOT_ALLOWED_BEFORE', 4);
  59. define('CHECK_ACTION_RESULT_NOT_ALLOWED_AFTER', 5);
  60. class BxDolAcl extends BxDol implements iBxDolSingleton
  61. {
  62. protected $oDb;
  63. protected $_aStandardMemberships = array(
  64. MEMBERSHIP_ID_NON_MEMBER => 1,
  65. MEMBERSHIP_ID_UNCONFIRMED => 1,
  66. MEMBERSHIP_ID_PENDING => 1,
  67. MEMBERSHIP_ID_SUSPENDED => 1,
  68. MEMBERSHIP_ID_STANDARD => 1,
  69. );
  70. protected $_aProfileStatus2LevelMap = array (
  71. BX_PROFILE_STATUS_SUSPENDED => MEMBERSHIP_ID_SUSPENDED,
  72. BX_PROFILE_STATUS_PENDING => MEMBERSHIP_ID_PENDING,
  73. );
  74. protected $_aLevel2MessageMap = array (
  75. MEMBERSHIP_ID_NON_MEMBER => '_sys_acl_action_unauthenticated',
  76. MEMBERSHIP_ID_UNCONFIRMED => '_sys_acl_action_unconfirmed',
  77. MEMBERSHIP_ID_PENDING => '_sys_acl_action_pending',
  78. MEMBERSHIP_ID_SUSPENDED => '_sys_acl_action_suspended',
  79. );
  80. protected function __construct()
  81. {
  82. if (isset($GLOBALS['bxDolClasses'][get_class($this)]))
  83. trigger_error ('Multiple instances are not allowed for the class: ' . get_class($this), E_USER_ERROR);
  84. parent::__construct();
  85. $this->oDb = new BxDolAclQuery();
  86. }
  87. /**
  88. * Prevent cloning the instance
  89. */
  90. public function __clone()
  91. {
  92. if (isset($GLOBALS['bxDolClasses'][get_class($this)]))
  93. trigger_error('Clone is not allowed for the class: ' . get_class($this), E_USER_ERROR);
  94. }
  95. /**
  96. * Get singleton instance of the class
  97. */
  98. public static function getInstance()
  99. {
  100. if(!isset($GLOBALS['bxDolClasses'][__CLASS__])) {
  101. bx_import('BxTemplAcl');
  102. $GLOBALS['bxDolClasses'][__CLASS__] = new BxTemplAcl();
  103. }
  104. return $GLOBALS['bxDolClasses'][__CLASS__];
  105. }
  106. /**
  107. * Check if member has one of the provided membership levels
  108. * @param $iPermissions - integer value to check permissions for, every bit is matched with some membership id
  109. * @param $iProfileId - profile to check, if it isn't provided or is false then currently logged in profile is used.
  110. * @return true if member has privided membership levels, or false if member hasn't.
  111. */
  112. public function isMemberLevelInSet($iPermissions, $iProfileId = false)
  113. {
  114. if (!$iPermissions)
  115. return false;
  116. if (false === $iProfileId && ($iPermissions&(pow(2, MEMBERSHIP_ID_ADMINISTRATOR - 1))) && isAdmin())
  117. return true;
  118. if (false === $iProfileId) {
  119. bx_import('BxDolProfile');
  120. $oProfile = BxDolProfile::getInstance();
  121. $iProfileId = $oProfile ? $oProfile->id() : 0;
  122. }
  123. $aACL = $this->getMemberMembershipInfo($iProfileId);
  124. return ($iPermissions & pow(2, $aACL['id'] - 1));
  125. }
  126. /**
  127. * Checks if a given action is allowed for a given profile and updates action information if the
  128. * action is performed.
  129. *
  130. * @param int $iProfileId ID of a profile that is going to perform an action
  131. * @param int $iActionId ID of the action itself
  132. * @param boolean $bPerformAction if true, then action information is updated, i.e. action is 'performed'
  133. * @return array(
  134. * CHECK_ACTION_RESULT => CHECK_ACTION_RESULT_ constant,
  135. * CHECK_ACTION_MESSAGE => CHECK_ACTION_MESSAGE_ constant,
  136. * CHECK_ACTION_PARAMETER => additional action parameter (string)
  137. * )
  138. *
  139. * NOTES:
  140. *
  141. * $aResult[CHECK_ACTION_MESSAGE] contains a message with detailed information about the result,
  142. * already processed by the language file
  143. *
  144. * if $aResult[CHECK_ACTION_RESULT] === CHECK_ACTION_RESULT_ALLOWED then this node contains
  145. * an empty string
  146. *
  147. * The error messages themselves are stored in the language file. Additional variables are
  148. * passed to the languages.inc.php function _t_ext() as an array and can be used there in the form of
  149. * {0}, {1}, {2} ...
  150. *
  151. * Additional variables passed to the lang. file on errors (can be used in error messages):
  152. *
  153. * For all errors:
  154. *
  155. * $arg0[CHECK_ACTION_LANG_FILE_ACTION] = name of the action
  156. * $arg0[CHECK_ACTION_LANG_FILE_MEMBERSHIP]= name of the current membership
  157. *
  158. * CHECK_ACTION_RESULT_LIMIT_REACHED:
  159. *
  160. * $arg0[CHECK_ACTION_LANG_FILE_LIMIT] = limit on number of actions allowed for the profile
  161. * $arg0[CHECK_ACTION_LANG_FILE_PERIOD] = period that the limit is set for (in hours, 0 if unlimited)
  162. *
  163. * CHECK_ACTION_RESULT_NOT_ALLOWED_BEFORE:
  164. *
  165. * $arg0[CHECK_ACTION_LANG_FILE_BEFORE] = date/time since when the action is allowed
  166. *
  167. * CHECK_ACTION_RESULT_NOT_ALLOWED_AFTER:
  168. *
  169. * $arg0[CHECK_ACTION_LANG_FILE_AFTER] = date/time since when the action is not allowed
  170. *
  171. * $aResult[CHECK_ACTION_PARAMETER] contains an additional parameter that can be considered
  172. * when performing the action (like the number of profiles to show in search result)
  173. */
  174. function checkAction($iProfileId, $iActionId, $bPerformAction = false)
  175. {
  176. $aResult = array();
  177. $aLangFileParams = array();
  178. $iProfileId = (int)$iProfileId;
  179. $iActionId = (int)$iActionId;
  180. $bPerformAction = $bPerformAction ? true : false;
  181. $aMembership = $this->getMemberMembershipInfo($iProfileId); // get current profile's membership information
  182. $aLangFileParams[CHECK_ACTION_LANG_FILE_MEMBERSHIP] = _t($aMembership['name']);
  183. $aLangFileParams[CHECK_ACTION_LANG_FILE_SITE_EMAIL] = getParam('site_email');
  184. $aAction = $this->oDb->getAction($aMembership['id'], $iActionId);
  185. if (!$aAction)
  186. bx_trigger_error('Unknown action ID: ' . $iActionId, 2);
  187. $aResult[CHECK_ACTION_PARAMETER] = $aAction['additional_param_value'];
  188. $aLangFileParams[CHECK_ACTION_LANG_FILE_ACTION] = !empty($aAction['title']) ? _t($aAction['title']) : $aAction['name'];
  189. /**
  190. * Action is not allowed for the current membership
  191. */
  192. if (is_null($aAction['id'])) {
  193. $sLangKey = CHECK_ACTION_MESSAGE_NOT_ALLOWED;
  194. if (isset($this->_aLevel2MessageMap[$aMembership['id']]))
  195. $sLangKey = $this->_aLevel2MessageMap[$aMembership['id']];
  196. $aResult[CHECK_ACTION_RESULT] = CHECK_ACTION_RESULT_NOT_ALLOWED;
  197. $aResult[CHECK_ACTION_MESSAGE] = _t_ext($sLangKey, $aLangFileParams);
  198. return $aResult;
  199. }
  200. /**
  201. * Check fixed period limitations if present (also for non-members)
  202. */
  203. if($aAction['allowed_period_start'] && time() < $aAction['allowed_period_start']) {
  204. $aLangFileParams[CHECK_ACTION_LANG_FILE_BEFORE] = bx_time_js($aAction['allowed_period_start'], BX_FORMAT_DATE_TIME);
  205. $aResult[CHECK_ACTION_RESULT] = CHECK_ACTION_RESULT_NOT_ALLOWED_BEFORE;
  206. $aResult[CHECK_ACTION_MESSAGE] = _t_ext(CHECK_ACTION_MESSAGE_NOT_ALLOWED_BEFORE, $aLangFileParams);
  207. return $aResult;
  208. }
  209. if($aAction['allowed_period_end'] && time() > $aAction['allowed_period_end']) {
  210. $aLangFileParams[CHECK_ACTION_LANG_FILE_AFTER] = bx_time_js($aAction['allowed_period_end'], BX_FORMAT_DATE_TIME);
  211. $aResult[CHECK_ACTION_RESULT] = CHECK_ACTION_RESULT_NOT_ALLOWED_AFTER;
  212. $aResult[CHECK_ACTION_MESSAGE] = _t_ext(CHECK_ACTION_MESSAGE_NOT_ALLOWED_AFTER, $aLangFileParams);
  213. return $aResult;
  214. }
  215. /**
  216. * if non-member, allow action without performing further checks
  217. */
  218. if ($aMembership['id'] == MEMBERSHIP_ID_NON_MEMBER) {
  219. $aResult[CHECK_ACTION_RESULT] = CHECK_ACTION_RESULT_ALLOWED;
  220. return $aResult;
  221. }
  222. /**
  223. * Check other limitations (for members only)
  224. */
  225. $iAllowedCnt = (int)$aAction['allowed_count']; ///< Number of allowed actions. Unlimited if not specified or 0
  226. $iPeriodLen = (int)$aAction['allowed_period_len']; ///< Period for AllowedCount in hours. If not specified, AllowedCount is treated as total number of actions permitted.
  227. if($iAllowedCnt > 0) {
  228. $aActionTrack = $this->oDb->getActionTrack($iActionId, $iProfileId);
  229. $iActionsLeft = $bPerformAction ? $iAllowedCnt - 1 : $iAllowedCnt;
  230. $iValidSince = time();
  231. /**
  232. * Member is requesting/performing this action for the first time,
  233. * and there is no corresponding record in sys_acl_actions_track table.
  234. */
  235. if(!$aActionTrack) {
  236. $this->oDb->insertActionTarck($iActionId, $iProfileId, $iActionsLeft, $iValidSince);
  237. $aResult[CHECK_ACTION_RESULT] = CHECK_ACTION_RESULT_ALLOWED;
  238. return $aResult;
  239. }
  240. /**
  241. * Action has been requested/performed at least once at this point and there is a corresponding record in sys_acl_actions_track table
  242. *
  243. * Action record in sys_acl_actions_track table is out of date.
  244. */
  245. $iPeriodEnd = (int)$aActionTrack['valid_since'] + $iPeriodLen * 3600; //ValidSince is in seconds, PeriodLen is in hours
  246. if($iPeriodLen > 0 && $iPeriodEnd < time()) {
  247. $this->oDb->updateActionTrack($iActionId, $iProfileId, $iActionsLeft, $iValidSince);
  248. $aResult[CHECK_ACTION_RESULT] = CHECK_ACTION_RESULT_ALLOWED;
  249. return $aResult;
  250. }
  251. $iActionsLeft = (int)$aActionTrack['actions_left']; ///< Action record is up to date
  252. /**
  253. * Action limit reached for now
  254. */
  255. if($iActionsLeft <= 0){
  256. $aLangFileParams[CHECK_ACTION_LANG_FILE_LIMIT] = $iAllowedCnt;
  257. $aLangFileParams[CHECK_ACTION_LANG_FILE_PERIOD] = $iPeriodLen;
  258. $aResult[CHECK_ACTION_RESULT] = CHECK_ACTION_RESULT_LIMIT_REACHED;
  259. $aResult[CHECK_ACTION_MESSAGE] = '<div style="width: 80%">' . _t_ext(CHECK_ACTION_MESSAGE_LIMIT_REACHED, $aLangFileParams) . ($iPeriodLen > 0 ? _t_ext(CHECK_ACTION_MESSAGE_MESSAGE_EVERY_PERIOD, $aLangFileParams) : '') . '.</div>';
  260. return $aResult;
  261. }
  262. if($bPerformAction) {
  263. $iActionsLeft--;
  264. $this->oDb->updateActionTrack($iActionId, $iProfileId, $iActionsLeft);
  265. }
  266. }
  267. $aResult[CHECK_ACTION_RESULT] = CHECK_ACTION_RESULT_ALLOWED;
  268. return $aResult;
  269. }
  270. /**
  271. * Get the list of existing memberships
  272. *
  273. * @param bool $bPurchasableOnly if true, fetches only purchasable memberships; 'purchasable' here means that:
  274. * - MemLevels.Purchasable = 'yes'
  275. * - MemLevels.Active = 'yes'
  276. * - there is at least one pricing option for the membership
  277. * @return array( membershipID_1 => membershipName_1, membershipID_2 => membershipName_2, ...) if no such memberships, then just array()
  278. */
  279. function getMemberships($bPurchasableOnly = false, $bActiveOnly = false, $isTranslate = true)
  280. {
  281. $sType = 'all_pair';
  282. if($bPurchasableOnly)
  283. $sType = 'all_active_purchasble_pair';
  284. else if($bActiveOnly)
  285. $sType = 'all_active_pair';
  286. $aLevels = array();
  287. $this->oDb->getLevels(array('type' => $sType), $aLevels, false);
  288. if ($isTranslate)
  289. foreach ($aLevels as $k => $s)
  290. $aLevels[$k] = _t($s);
  291. return $aLevels;
  292. }
  293. /**
  294. * Get info about a given membership
  295. *
  296. * @param int $iLevelId membership to get info about
  297. * @return array(
  298. * 'id' => ID,
  299. * 'name' => name,
  300. * 'icon' => icon,
  301. * 'description' => description,
  302. * 'active' => active,
  303. * 'purchasable' => purchasable,
  304. * 'removable' => removable
  305. * 'quota_size' => quota size,
  306. * 'quota_number' => quota number,
  307. * 'quota_max_file_size' => quota max file size
  308. * )
  309. */
  310. function getMembershipInfo($iLevelId)
  311. {
  312. $aLevel = array();
  313. $this->oDb->getLevels(array('type' => 'by_id', 'value' => $iLevelId), $aLevel, false);
  314. return $aLevel;
  315. }
  316. /**
  317. * Get pricing options for the given membership
  318. *
  319. * @param int $iLevelId membership to get prices for
  320. * @return array( days1 => price1, days2 => price2, ...) if no prices set, then just array()
  321. */
  322. function getMembershipPrices($iLevelId)
  323. {
  324. $aPrice = array();
  325. $this->oDb->getPrices(array('type' => 'by_level_id_pair', 'value' => $iLevelId), $aPrice, false);
  326. return $aPrice;
  327. }
  328. /**
  329. * Retrieves information about membership for a given profile at a given moment.
  330. *
  331. * If there are no memberships purchased/assigned to the
  332. * given profile or all of them have expired at the given point,
  333. * the profile is assumed to be a standard profile, and the function
  334. * returns information about the Standard membership. This will
  335. * also happen if a profile wasnt actually registered in the database
  336. * at that point - the function will still return info about Standard
  337. * membership, not the Non-member one.
  338. *
  339. * If there is no profile with the given $iProfileId,
  340. * the function returns information about the Non-member or Authenticated
  341. * predefined membership.
  342. *
  343. * The Standard, Authenticated and Non-member memberships have their
  344. * DateStarts and DateExpires attributes set to NULL.
  345. *
  346. * @param int $iProfileId ID of a profile to get info about
  347. * @param int $time specifies the time to use when determining membership; if not specified, the function takes the current time
  348. * @return array(
  349. * 'id' => membership id,
  350. * 'name' => membership name,
  351. * 'date_starts' => (UNIX timestamp) date/time purchased,
  352. * 'date_expires' => (UNIX timestamp) date/time expires
  353. * )
  354. */
  355. function getMemberMembershipInfo($iProfileId, $iTime = 0)
  356. {
  357. $aMembershipCurrent = $this->getMemberMembershipInfoCurrent($iProfileId, $iTime);
  358. if (isset($this->_aStandardMemberships[$aMembershipCurrent['id']]))
  359. return $aMembershipCurrent;
  360. $aMembership = $aMembershipCurrent;
  361. do {
  362. $iDateStarts = $aMembership['date_starts'];
  363. $aMembership = $this->getMemberMembershipInfoCurrent($iProfileId, ((int)$iDateStarts < 1 ? 0 : $iDateStarts - 1));
  364. }
  365. while($aMembership['id'] == $aMembershipCurrent['id'] && (int)$aMembership['date_starts']);
  366. $aMembership = $aMembershipCurrent;
  367. do {
  368. $iDateExpires = $aMembership['date_expires'];
  369. $aMembership = $this->getMemberMembershipInfoCurrent($iProfileId, $iDateExpires);
  370. } while($aMembership['id'] == $aMembershipCurrent['id'] && (int)$aMembership['date_expires']);
  371. $aMembershipCurrent['date_starts'] = $iDateStarts;
  372. $aMembershipCurrent['date_expires'] = $iDateExpires;
  373. return $aMembershipCurrent;
  374. }
  375. /**
  376. * Buy a membership for a profile
  377. *
  378. * @param int $iProfileId profile that is going to get the membership
  379. * @param int $iMembershipId bought membership
  380. * @param int $sTransactionId internal key of the transaction (ID from Transactions table)
  381. * @param boolean $bStartsNow if true, the membership will start immediately; if false, the membership will start after the current membership expires
  382. * @return boolean true in case of success, false in case of failure
  383. */
  384. function buyMembership($iProfileId, $iPriceId, $sTransactionId, $bStartsNow = false)
  385. {
  386. $aPrice = array();
  387. $this->oDb->getPrices(array('type' => 'by_id', 'value' => (int)$iPriceId), $aPrice, false);
  388. if(!is_array($aPrice) || empty($aPrice))
  389. return false;
  390. $aLevel = array();
  391. $this->oDb->getLevels(array('type' => 'by_id', 'value' => $aPrice['level_id']), $aLevel, false);
  392. if(!is_array($aLevel) || empty($aLevel))
  393. return false;
  394. $iLevelId = (int)$aLevel['id'];
  395. if (isset($this->_aStandardMemberships[$iLevelId])) // check for predefined non-purchasable memberships
  396. return false;
  397. if($aLevel['active'] != 'yes' || $aLevel['purchasable'] != 'yes') // check if membership is active and purchasable
  398. return false;
  399. return $this->setMembership((int)$iProfileId, $iLevelId, $aPrice['days'], $bStartsNow, $sTransactionId);
  400. }
  401. /**
  402. * Set a membership for a profile
  403. *
  404. * @param int $iProfileId profile that is going to get the membership
  405. * @param int $iLevelId membership that is going to be assigned to the profile
  406. * if $iLevelId == MEMBERSHIP_ID_STANDARD then $days and $bStartsNow parameters are not used,
  407. * so Standard membership is always set immediately and `forever`
  408. * @param int $iDays number of days to set membership for if 0, then the membership is set forever
  409. * @param boolean $bStartsNow if true, the membership will start immediately if false, the membership will start after the current membership expires
  410. * @return boolean true in case of success, false in case of failure
  411. */
  412. function setMembership($iProfileId, $iLevelId, $iDays = 0, $bStartsNow = false, $sTransactionId = '')
  413. {
  414. $iProfileId = (int)$iProfileId;
  415. $iLevelId = (int)$iLevelId;
  416. $iDays = (int)$iDays;
  417. $bStartsNow = $bStartsNow ? true : false;
  418. $iSecInDay = 86400;
  419. if (!$iProfileId)
  420. $iProfileId = -1;
  421. if (empty($sTransactionId))
  422. $sTransactionId = 'NULL';
  423. // check if profile exists
  424. bx_import('BxDolProfileQuery');
  425. if(($sProfileEmail = BxDolProfileQuery::getInstance()->getEmailById($iProfileId)) === false)
  426. return false;
  427. // check if membership exists
  428. $aLevel = array();
  429. $this->oDb->getLevels(array('type' => 'by_id', 'value' => $iLevelId), $aLevel, false);
  430. if(empty($aLevel) || !is_array($aLevel))
  431. return false;
  432. if($iLevelId == MEMBERSHIP_ID_NON_MEMBER)
  433. return false;
  434. $aMembershipCurrent = $this->getMemberMembershipInfo($iProfileId);
  435. $aMembershipLatest = $this->getMemberMembershipInfoLatest($iProfileId);
  436. // setting Standard membership level
  437. if ($iLevelId == MEMBERSHIP_ID_STANDARD) {
  438. if ($aMembershipCurrent['id'] == MEMBERSHIP_ID_STANDARD)
  439. return true;
  440. // delete present and future memberships
  441. return $this->oDb->deleteLevelByProfileId($iProfileId);
  442. }
  443. if ($iDays < 0)
  444. return false;
  445. $iDateStarts = time();
  446. if (!$bStartsNow) {
  447. // make the membership starts after the latest membership expires or return false if latest membership isn't Standard and is lifetime membership.
  448. if(!is_null($aMembershipLatest['date_expires']))
  449. $iDateStarts = $aMembershipLatest['date_expires'];
  450. else if(is_null($aMembershipLatest['date_expires']) && $aMembershipLatest['id'] != MEMBERSHIP_ID_STANDARD)
  451. return false;
  452. } else
  453. $this->oDb->deleteLevelByProfileId($iProfileId, true); ///< Delete any profile's membership level
  454. // set lifetime membership if 0 days is used.
  455. $iDateExpires = $iDays != 0 ? (int)$iDateStarts + $iDays * $iSecInDay : null;
  456. if(!$this->oDb->insertLevelByProfileId($iProfileId, $iLevelId, $iDateStarts, $iDateExpires, $sTransactionId))
  457. return false;
  458. // raise membership alert
  459. bx_import('BxDolAlerts');
  460. $oZ = new BxDolAlerts('profile', 'set_membership', '', $iProfileId, array('mlevel'=> $iLevelId, 'days' => $iDays, 'starts_now' => $bStartsNow, 'txn_id' => $sTransactionId));
  461. $oZ->alert();
  462. // Send notification
  463. bx_import('BxDolEmailTemplates');
  464. $aTemplate = BxDolEmailTemplates::getInstance()->parseTemplate('t_MemChanged', array('membership_level' => _t($aLevel['name'])), 0, $iProfileId);
  465. if ($aTemplate)
  466. sendMail($sProfileEmail, $aTemplate['Subject'], $aTemplate['Body']);
  467. return true;
  468. }
  469. /**
  470. * Define action, defining all names are translated the following way:
  471. * my action => BX_MY_ACTION
  472. *
  473. * @param $aActions array of actions from sys_acl_actions table, with default array keys (starting from 0) and text values
  474. */
  475. function defineMembershipActions($mixedActions, $sPrefix = 'BX_')
  476. {
  477. if (is_array($mixedActions))
  478. $aActions = $mixedActions;
  479. else
  480. $aActions = array($mixedActions);
  481. $aNames = array();
  482. foreach ($aActions as $sName)
  483. if(!defined($sPrefix . strtoupper(str_replace(' ', '_', $sName))))
  484. $aNames[] = $sName;
  485. if(!$aNames)
  486. return;
  487. $aActions = array();
  488. $this->oDb->getActions(array('type' => 'by_names', 'value' => $aNames), $aActions, false);
  489. foreach($aActions as $aAction)
  490. define($sPrefix . strtoupper(str_replace(' ', '_', $aAction['name'])), $aAction['id']);
  491. }
  492. /**
  493. * get action id by module and name
  494. * @param $sAction action name
  495. * @param $sModule module name
  496. * @param $aActions array of actions from sys_acl_actions table, with default array keys (starting from 0) and text values
  497. */
  498. function getMembershipActionId($sAction, $sModule)
  499. {
  500. $this->oDb->getActions(array('type' => 'by_names_and_module', 'value' => $sAction, 'module' => $sModule), $aActions, false);
  501. if (count($aActions) > 1)
  502. trigger_error('Duplicate action - name:' . $sAction . ', module:' . $sModule, E_USER_ERROR);
  503. $aAction = array_pop($aActions);
  504. return $aAction['id'];
  505. }
  506. function getExpirationLetter($iProfileId, $sLevelName, $iLevelExpireDays )
  507. {
  508. $iProfileId = (int)$iProfileId;
  509. if(!$iProfileId)
  510. return false;
  511. bx_import('BxDolProfileQuery');
  512. $oProfileQuery = BxDolProfileQuery::getInstance();
  513. $sProfileEmail = $oProfileQuery->getEmailById($iProfileId);
  514. $aPlus = array(
  515. 'membership_name' => $sLevelName,
  516. 'expire_days' => $iLevelExpireDays
  517. );
  518. bx_import('BxDolEmailTemplates');
  519. $aTemplate = BxDolEmailTemplates::getInstance()->parseTemplate('t_MemExpiration', $aPlus, 0, $iProfileId);
  520. $iResult = $aTemplate && sendMail($sProfileEmail, $aTemplate['Subject'], $aTemplate['Body'], $iProfileId, $aPlus);
  521. return !empty($iResult);
  522. }
  523. /**
  524. * clear expired membership levels
  525. */
  526. public function maintenance ()
  527. {
  528. $iDaysToCleanMemLevels = (int) getParam("db_clean_mem_levels");
  529. return $this->oDb->maintenance ($iDaysToCleanMemLevels);
  530. }
  531. protected function getMemberMembershipInfoCurrent($iProfileId, $iTime = 0)
  532. {
  533. $aMemLevel = false;
  534. // get profile status
  535. bx_import('BxDolProfile');
  536. $oProfile = BxDolProfile::getInstance($iProfileId);
  537. $aProfileInfo = $oProfile ? $oProfile->getInfo() : false;
  538. $sProfileStatus = $aProfileInfo ? $aProfileInfo['status'] : false;
  539. // profile is not active, so return standard memberships according to profile status
  540. if (BX_PROFILE_STATUS_ACTIVE != $sProfileStatus) {
  541. bx_import('BxDolAccount');
  542. $oAccount = $aProfileInfo ? BxDolAccount::getInstance($aProfileInfo['account_id']) : false;
  543. if ($oAccount && !$oAccount->isConfirmed())
  544. $iLevelId = MEMBERSHIP_ID_UNCONFIRMED; // every account's profile is unconfirmed if account is unconfirmed
  545. elseif (!isset($this->_aProfileStatus2LevelMap[$sProfileStatus]))
  546. $iLevelId = MEMBERSHIP_ID_NON_MEMBER; // if there is no profile status - then it isn't member
  547. else
  548. $iLevelId = $this->_aProfileStatus2LevelMap[$sProfileStatus]; // get member level id which associated with every non-active status
  549. $aMemLevel = $this->oDb->getLevelByIdCached($iLevelId);
  550. if (!$aMemLevel)
  551. trigger_error ('Standard member level is missing: ' . $iLevelId, E_USER_ERROR);
  552. return $aMemLevel;
  553. }
  554. // profile is active get memebr level from profile
  555. $aMemLevel = $this->oDb->getLevelCurrent((int)$iProfileId, $iTime);
  556. // There are no purchased/assigned memberships for the profile or all of them have expired.
  557. // In this case the profile is assumed to have Standard membership.
  558. if (!$aMemLevel || is_null($aMemLevel['id'])) {
  559. $aMemLevel = $this->oDb->getLevelByIdCached(MEMBERSHIP_ID_STANDARD);
  560. if (!$aMemLevel)
  561. trigger_error ('Standard member level is missing: ' . MEMBERSHIP_ID_NON_MEMBER, E_USER_ERROR);
  562. }
  563. return $aMemLevel;
  564. }
  565. protected function getMemberMembershipInfoLatest($iProfileId, $iTime = 0)
  566. {
  567. $aMembershipCurrent = $this->getMemberMembershipInfoCurrent($iProfileId, $iTime);
  568. if (isset($this->_aStandardMemberships[$aMembershipCurrent['id']]))
  569. return $aMembershipCurrent;
  570. $aMembership = $aMembershipCurrent;
  571. while ($aMembership['id'] != MEMBERSHIP_ID_STANDARD) {
  572. $aMembershipLast = $aMembership;
  573. if(!isset($aMembership['DateExpires']) || (int)$aMembership['DateExpires'] == 0)
  574. break;
  575. $aMembership = $this->getMemberMembershipInfoCurrent($iProfileId, $aMembership['date_expires']);
  576. }
  577. return $aMembershipLast;
  578. }
  579. public function onProfileDelete ($iProfileId)
  580. {
  581. return $this->oDb->deleteLevelByProfileId($iProfileId, true);
  582. }
  583. }
  584. function checkAction($iProfileId, $iActionId, $bPerformAction = false)
  585. {
  586. return BxDolAcl::getInstance()->checkAction($iProfileId, $iActionId, $bPerformAction);
  587. }
  588. function checkActionModule($iProfileId, $sActionName, $sModuleName, $bPerformAction = false)
  589. {
  590. $oACL = BxDolAcl::getInstance();
  591. $iActionId = $oACL->getMembershipActionId($sActionName, $sModuleName);
  592. return BxDolAcl::getInstance()->checkAction($iProfileId, $iActionId, $bPerformAction);
  593. }
  594. /** @} */