BxDolAcl.php 27 KB

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