BxDolAcl.php 29 KB

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