BxDolAcl.php 29 KB

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