Exemplo n.º 1
0
 /**
  * @param  TabTable   $tab       Current tab
  * @param  UserTable  $user      Current user
  * @param  int        $ui        1 front, 2 admin UI
  * @param  array      $postdata  Raw unfiltred POST data
  * @return string                HTML
  */
 public function getCBpluginComponent($tab, $user, $ui, $postdata)
 {
     global $_CB_framework;
     outputCbJs(1);
     outputCbTemplate(1);
     $plugin = cbblogsClass::getPlugin();
     $model = cbblogsClass::getModel();
     $action = $this->input('action', null, GetterInterface::STRING);
     $function = $this->input('func', null, GetterInterface::STRING);
     $id = $this->input('id', null, GetterInterface::INT);
     $user = CBuser::getUserDataInstance($_CB_framework->myId());
     $tab = new TabTable();
     $tab->load(array('pluginid' => (int) $plugin->id));
     $profileUrl = $_CB_framework->userProfileUrl($user->get('id'), false, 'cbblogsTab');
     if (!($tab->enabled && Application::MyUser()->canViewAccessLevel($tab->viewaccesslevel))) {
         cbRedirect($profileUrl, CBTxt::T('Not authorized.'), 'error');
     }
     ob_start();
     switch ($action) {
         case 'blogs':
             switch ($function) {
                 case 'new':
                     $this->showBlogEdit(null, $user, $model, $plugin);
                     break;
                 case 'edit':
                     $this->showBlogEdit($id, $user, $model, $plugin);
                     break;
                 case 'save':
                     cbSpoofCheck('plugin');
                     $this->saveBlogEdit($id, $user, $model, $plugin);
                     break;
                 case 'publish':
                     $this->stateBlog(1, $id, $user, $model, $plugin);
                     break;
                 case 'unpublish':
                     $this->stateBlog(0, $id, $user, $model, $plugin);
                     break;
                 case 'delete':
                     $this->deleteBlog($id, $user, $model, $plugin);
                     break;
                 case 'show':
                 default:
                     if ($model->type != 2) {
                         cbRedirect(cbblogsModel::getUrl((int) $id, false));
                     } else {
                         $this->showBlog($id, $user, $model, $plugin);
                     }
                     break;
             }
             break;
         default:
             cbRedirect($profileUrl, CBTxt::T('Not authorized.'), 'error');
             break;
     }
     $html = ob_get_contents();
     ob_end_clean();
     $class = $plugin->params->get('general_class', null);
     $return = '<div id="cbBlogs" class="cbBlogs' . ($class ? ' ' . htmlspecialchars($class) : null) . '">' . '<div id="cbBlogsInner" class="cbBlogsInner">' . $html . '</div>' . '</div>';
     echo $return;
 }
Exemplo n.º 2
0
 public function check()
 {
     if ($this->get('title') == '') {
         $this->setError(CBTxt::T('Title not specified!'));
         return false;
     } elseif (!$this->get('user')) {
         $this->setError(CBTxt::T('User not specified!'));
         return false;
     } elseif ($this->get('user') && !CBuser::getUserDataInstance((int) $this->get('user'))->id) {
         $this->setError(CBTxt::T('User specified does not exist!'));
         return false;
     } elseif ($this->get('access') === '') {
         $this->setError(CBTxt::T('Access not specified!'));
         return false;
     } elseif ($this->get('category') === '') {
         $this->setError(CBTxt::T('Category not specified!'));
         return false;
     } elseif (!in_array($this->get('category'), cbblogsModel::getCategoriesList(true))) {
         $this->setError(CBTxt::T('Category not allowed!'));
         return false;
     }
     return true;
 }
Exemplo n.º 3
0
	/**
	 * Gets all subscriptions of $user for $plans having $statuses
	 * $plans and $statuses can be null or empty array() meaning that condition is ignored
	 * 
	 * @param  int                   $userId
	 * @param  int[]|null     $plans
	 * @param  string[]|null  $statuses
	 * @return cbpaidSomething[]
	 */
	private function _getUsersSubscriptions( $userId, $plans, $statuses ) {
		$subsOfPlansStatus						=	array();
		if ( $userId ) {
			// get list of plan_id of all active and inactive subscriptions:
			$user								=	CBuser::getUserDataInstance( $userId );
			$subsByPlanType						=	cbpaidSomethingMgr::getAllSomethingOfUser( $user, null );
			foreach ( $subsByPlanType as $subs ) {
				foreach ( $subs as $subscription ) {
					// $subscription = NEW cbpaidSomething();
					if ( ( ( $plans == null )    || in_array( $subscription->plan_id, $plans ) )
					&&   ( ( $statuses == null ) || in_array( $subscription->status, $statuses ) ) ) {
						$subsOfPlansStatus[]	=	$subscription;
					}
				}
			}
		}
		return $subsOfPlansStatus;
	}
Exemplo n.º 4
0
 /**
  * Saves legacy user edit display
  *
  * @param string $option
  * @param string $task
  */
 public function saveUser($option, $task = 'save')
 {
     global $_CB_framework, $_CB_Backend_task, $_POST, $_PLUGINS;
     cbimport('language.all');
     cbimport('cb.tabs');
     cbimport('cb.params');
     cbimport('cb.adminfilesystem');
     cbimport('cb.imgtoolbox');
     $userIdPosted = (int) cbGetParam($_POST, 'id', 0);
     if ($userIdPosted == 0) {
         $_POST['id'] = null;
     }
     $msg = $this->_authorizedEdit($userIdPosted);
     if (!$msg) {
         if ($userIdPosted != 0) {
             $msg = checkCBpermissions(array($userIdPosted), 'save', true);
         } else {
             $msg = checkCBpermissions(null, 'save', true);
         }
     }
     if ($userIdPosted != 0) {
         $_PLUGINS->trigger('onBeforeUserProfileSaveRequest', array($userIdPosted, &$msg, 2));
     }
     if ($msg) {
         cbRedirect($_CB_framework->backendViewUrl('showusers', false), $msg, 'error');
     }
     $_PLUGINS->loadPluginGroup('user');
     // Get current user state:
     if ($userIdPosted != 0) {
         $userComplete = CBuser::getUserDataInstance($userIdPosted);
         if (!($userComplete && $userComplete->id)) {
             cbRedirect($_CB_framework->backendViewUrl('showusers', false), CBTxt::T('Your profile could not be updated.'), 'error');
         }
     } else {
         $userComplete = new UserTable();
     }
     // Store new user state:
     $saveResult = $userComplete->saveSafely($_POST, $_CB_framework->getUi(), 'edit');
     if (!$saveResult) {
         $regErrorMSG = $userComplete->getError();
         $msg = checkCBpermissions(array((int) $userComplete->id), 'edit', true);
         if ($userIdPosted != 0) {
             $_PLUGINS->trigger('onBeforeUserProfileEditRequest', array((int) $userComplete->id, &$msg, 2));
         }
         if ($msg) {
             cbRedirect($_CB_framework->backendViewUrl('showusers', false), $msg, 'error');
         }
         if ($userIdPosted != 0) {
             $_PLUGINS->trigger('onAfterUserProfileSaveFailed', array(&$userComplete, &$regErrorMSG, 2));
         } else {
             $_PLUGINS->trigger('onAfterUserRegistrationSaveFailed', array(&$userComplete, &$regErrorMSG, 2));
         }
         $_CB_framework->enqueueMessage($regErrorMSG, 'error');
         $_CB_Backend_task = 'edit';
         // so the toolbar comes up...
         $_PLUGINS->loadPluginGroup('user');
         // resets plugin errors
         $userView = _CBloadView('user');
         /** @var CBController_user $userView */
         $userView->edituser($userComplete, $option, $userComplete->user_id != null ? 0 : 1, $_POST);
         return;
     }
     // Checks-in the row:
     $userComplete->checkin();
     if ($userIdPosted != 0) {
         $_PLUGINS->trigger('onAfterUserProfileSaved', array(&$userComplete, 2));
     } else {
         $messagesToUser = array();
         $_PLUGINS->trigger('onAfterSaveUserRegistration', array(&$userComplete, &$messagesToUser, 2));
     }
     if ($task == 'apply') {
         cbRedirect($_CB_framework->backendViewUrl('edit', false, array('cid' => (int) $userComplete->user_id)), CBTxt::T('SUCCESSFULLY_SAVED_USER_USERNAME', 'Successfully Saved User: [username]', array('[username]' => $userComplete->username)));
     } else {
         cbRedirect($_CB_framework->backendViewUrl('showusers', false), CBTxt::T('SUCCESSFULLY_SAVED_USER_USERNAME', 'Successfully Saved User: [username]', array('[username]' => $userComplete->username)));
     }
 }
 /**
  * Checks for upgrade or renewal possibilities
  *
  * @param  int                   $ui                     1=frontend, 2=backend
  * @param  int                   $user_id
  * @param  int                   $now                    system unix time
  * @param  cbpaidUsersubscriptionRecord[]  $subscriptionsReturned  RETURNED: current subscriptions
  *                                                               with ->status = 'A' for active ones and 'X' for expired ones. 'R' unpaid, 'C' cancelled.
  * @param  array|null            $plansToShowOnly        array of specific plan numbers to show (so we add these plans if allowed and not spontaneous in frontend
  * @param  int                   $subsAccess             0 has only read access, 1 has user access, 2 reserved for future Super-admin access
  * @param  boolean               $plansToShowOnlyDoIncludeChildren  Include children with plansToShowOnly
  * @return cbPaidProduct[]                               upgrade possibilities including _renewalDiscount in plan's currency
  */
 public function getUpgradeAndRenewalPossibilities($ui, $user_id, $now, &$subscriptionsReturned, $plansToShowOnly = null, $subsAccess = 1, $plansToShowOnlyDoIncludeChildren = false)
 {
     global $_CB_database, $_CB_framework;
     if (!isset($this->_upgradesCache[$user_id])) {
         $quantity = 1;
         //TBD later !
         $paidUserExtension = cbpaidUserExtension::getInstance($user_id);
         $subscriptions = $paidUserExtension->getUserSubscriptions(null, true);
         $user = CBuser::getUserDataInstance((int) $user_id);
         $plansMgr = cbpaidPlansMgr::getInstance();
         $plans = $plansMgr->loadPublishedPlans($user, true, 'any', null);
         //TBD LATER: upgrades limiting owners
         $params = cbpaidApp::settingsParams();
         $enableFreeRegisteredUser = $params->get('enableFreeRegisteredUser', 1);
         $createAlsoFreeSubscriptions = $params->get('createAlsoFreeSubscriptions', 0);
         $noValidSubscriptionFound = true;
         $subscriptionsUpgradePlansIdsDiscount = array();
         // array: [$k][$upgrade_plan->id]=discountedPrice  where $l is index in $subscriptions
         $activeExclusiveSubChild = array();
         // array: [$parentPlanId] = true
         $notProposedParents = array();
         foreach (array_keys($subscriptions) as $k) {
             // for each user subscription:
             // 1. check if it's plan can be shown as an extra subscription possibility and/or upgrade,
             $subscriptions[$k]->checkRenewalUpgrade($ui, $user, $quantity, $now, $subsAccess);
             // 2. don't propose subscription which can not be shown to the user
             if ($subscriptions[$k]->_hideItsPlan && isset($plans[$subscriptions[$k]->plan_id])) {
                 $plans[$subscriptions[$k]->plan_id]->_drawOnlyAsContainer = true;
                 // $notProposedParents[$subscriptions[$k]->plan_id]				=	true;
             }
             if (($subscriptions[$k]->_hideThisSubscription || !$subscriptions[$k]->checkIfValid($now)) && (isset($plans[$subscriptions[$k]->plan_id]) && $plans[$subscriptions[$k]->plan_id]->get('multiple') == 0)) {
                 foreach (array_keys($plans) as $pk) {
                     // hidden or inactive subscription: do not display any of its children plans as upgrade possibility:
                     if ($plans[$pk]->get('parent') == $subscriptions[$k]->plan_id) {
                         $plans[$pk]->_drawOnlyAsContainer = true;
                         $notProposedParents[$pk] = true;
                     }
                 }
             }
             if ($subscriptions[$k]->_hideThisSubscription) {
                 unset($subscriptions[$k]);
             } elseif ($subscriptions[$k]->checkIfValid($now)) {
                 // 3. all upgrade possibilities of this subscription
                 $noValidSubscriptionFound = false;
                 $subscriptionsUpgradePlansIdsDiscount[$k] = $subscriptions[$k]->_upgradePlansIdsDiscount;
                 if ($subscriptions[$k]->getPlanAttribute('exclusive') == 1) {
                     $activeExclusiveSubChild[$subscriptions[$k]->getPlanAttribute('parent')] = true;
                 }
             } else {
             }
         }
         // add to each plan the subscriptions which can be upgraded: plan, subscription and price:
         foreach (array_keys($plans) as $pk) {
             foreach ($subscriptionsUpgradePlansIdsDiscount as $k => $upgradePlansDiscount) {
                 foreach ($upgradePlansDiscount as $planId => $discountedPrice) {
                     if ($plans[$pk]->get('id') == $planId) {
                         $plans[$pk]->_subscriptionToUpdate = array($subscriptions[$k]->plan_id, $subscriptions[$k]->id);
                         $plans[$pk]->_renewalDiscount = $discountedPrice;
                     }
                 }
             }
         }
         // finally remove all plans not allowed for upgrade and
         // also all exclusive plans which can't be upgraded to by no subscription
         // (already subscribed plans have already been removed by plan's _hideItsPlan instructions):
         // also memorize them as removed parent, so that children are not proposed either:
         foreach (array_keys($plans) as $pk) {
             $exclPlan = $plans[$pk]->get('exclusive');
             $resultTexts = array();
             // remove plans not listed by default and not specifically selected:
             if (!$plans[$pk]->isPlanAllowingUpgradesToThis($user_id, $resultTexts) || $plans[$pk]->get('propose_upgrade') != 1 && $ui != 2 && !($plansToShowOnly && (in_array($pk, $plansToShowOnly) || $plansToShowOnlyDoIncludeChildren && in_array($plans[$pk]->get('parent'), $plansToShowOnly))) || $exclPlan == 1 && $plans[$pk]->get('multiple') == 0 && isset($activeExclusiveSubChild[$plans[$pk]->get('parent')]) && $plans[$pk]->_subscriptionToUpdate === null) {
                 // if ( $ui == 1 ) {	// when we are in frontend:
                 if (!(isset($plans[$pk]->_drawOnlyAsContainer) && $plans[$pk]->_drawOnlyAsContainer)) {
                     $plans[$pk]->_drawOnlyAsContainer = true;
                     $notProposedParents[$pk] = true;
                 }
             }
         }
         // very finally remove also children of non-authorized parent plans:
         // second case is that parent plan isn't published:
         foreach (array_keys($plans) as $pk) {
             $parentPlanId = $plans[$pk]->get('parent');
             if ($parentPlanId && (isset($notProposedParents[$parentPlanId]) || !isset($plans[$parentPlanId]))) {
                 $plans[$pk]->_drawOnlyAsContainer = true;
             }
         }
         // If no sbscriptions at all or no active/registered ones, and the corresponding setting allows it:
         // Find the first free lifetime one with Registered level:
         if ((count($subscriptions) == 0 || $noValidSubscriptionFound) && $enableFreeRegisteredUser && !$createAlsoFreeSubscriptions) {
             $firstFreePlanId = null;
             $registeredUserGroup = $_CB_framework->getCfg('new_usertype');
             foreach ($plans as $v) {
                 if ($v->isLifetimeValidity() && $v->isFree() && in_array($v->get('usergroup'), array($registeredUserGroup, 0))) {
                     if ($firstFreePlanId === null) {
                         $firstFreePlanId = $v->get('id');
                     }
                     break;
                 }
             }
             if ($firstFreePlanId) {
                 $freeSub = new cbpaidUsersubscriptionRecord($_CB_database);
                 $freeSub->createSubscription($user_id, $plans[$firstFreePlanId], null, null, 'A', false);
                 array_unshift($subscriptions, $freeSub);
                 $plans[$firstFreePlanId]->_drawOnlyAsContainer = true;
             }
         }
         $this->_upgradesCache[$user_id] = array('subscriptions' => &$subscriptions, 'plans' => &$plans);
     }
     $subscriptionsReturned = $this->_upgradesCache[$user_id]['subscriptions'];
     return $this->_upgradesCache[$user_id]['plans'];
 }
	/**
	 * Returns substitution strings
	 *
	 * @see cbpaidSomething::substitutionStringsForItemDetailed()
	 *
	 * @param  boolean  $html           HTML or TEXT return
	 * @param  string   $reason         'N' new subscription, 'R' renewal, 'U'=update )
	 * @param  boolean  $autorecurring  TRUE: is autorecurring, no real expiration date, FALSE: is not autorecurring
	 * @return array
	 */
	public function substitutionStringsForItemDetailed( /** @noinspection PhpUnusedParameterInspection */ $html, $reason, $autorecurring ) {
		global $_CB_framework;

		$user						=	CBuser::getUserDataInstance( $this->user_id );

		$prefixText					=	'';

		$params						=&	cbpaidApp::settingsParams();

		$extraStrings				=	array(	'ITEM_NAME'				=>	$this->getPlan()->getPersonalized( 'name', $this->user_id, false ),		//	CBPTXT::T( $this->getText( 'name' ) ),
			'ITEM_ALIAS'			=>	CBPTXT::T( $this->getText( 'alias' ) ),
			'ITEM_DESCRIPTION'		=>	$this->getPlan()->getPersonalized( 'description', $this->user_id, false ),	//strip_tags( CBPTXT::T( $this->getText( 'description' ) ) ),
			'SITENAME'				=>	$_CB_framework->getCfg( 'sitename' ),
			'SITEURL'				=>	$_CB_framework->getCfg( 'live_site' ),
			'PLANS_TITLE'			=>	strip_tags( CBPTXT::T( $params->get( 'regTitle' ) ) ),
			'EMAILADDRESS'			=>	$user->email,
			'PREFIX_TEXT'			=>	$prefixText
		);
		return $extraStrings;
	}
 /**
  * store() function override, instead of storing it imports.
  *
  * @param  boolean  $updateNulls
  * @return boolean
  */
 public function store($updateNulls = false)
 {
     $return = '';
     // Check if file uploads are enabled
     if (!(bool) ini_get('file_uploads')) {
         $this->_error = CBPTXT::T("Importer") . ' - ' . CBPTXT::T("error:") . ' ' . CBPTXT::T("The importer can't continue before file uploads are enabled in PHP settings.");
         return false;
     }
     if (!$this->import_type) {
         $this->_error = CBPTXT::T("Importer") . ' - ' . CBPTXT::T("error:") . ' ' . CBPTXT::T("No import type selected");
         return false;
     }
     $fromFile = cbStartOfStringMatch($this->import_type, 'file_');
     if ($fromFile) {
         $userfile = $_FILES['userfile'];
         if (!$userfile || $userfile == null) {
             $this->_error = CBPTXT::T("Importer") . ' - ' . CBPTXT::T("error:") . ' ' . CBPTXT::T("No file selected");
             return false;
         }
         if (isset($userfile['error']) && $userfile['error']) {
             $errors_array = array(1 => CBPTXT::T("The uploaded file exceeds the upload_max_filesize directive in php.ini."), 2 => CBPTXT::T("The uploaded file exceeds the maximum size allowed by this form."), 3 => CBPTXT::T("The uploaded file was only partially uploaded."), 4 => CBPTXT::T("No file was selected and uploaded."), 6 => CBPTXT::T("Missing a temporary folder in php.ini."), 7 => CBPTXT::T("Failed to write file to disk."), 8 => CBPTXT::T("File upload stopped by extension."));
             if (in_array($userfile['error'], $errors_array)) {
                 $fileErrorTxt = $errors_array[$userfile['error']];
             } else {
                 $fileErrorTxt = CBPTXT::T("File upload error number ") . htmlspecialchars($userfile['error']);
             }
             $this->_error = CBPTXT::T("Importer") . ' - ' . CBPTXT::T("error:") . ' ' . $fileErrorTxt;
             return false;
         }
         if (!$userfile['tmp_name'] || !is_uploaded_file($userfile['tmp_name'])) {
             $this->_error = CBPTXT::T("Importer") . ' - ' . CBPTXT::T("error:") . ' ' . CBPTXT::T("No temporary file name");
             return false;
         }
         if ($userfile['size'] == 0) {
             $this->_error = CBPTXT::T("Importer") . ' - ' . CBPTXT::T("error:") . ' ' . CBPTXT::T("Empty file");
             return false;
         }
     } else {
         $userfile = null;
     }
     if ($this->import_type == 'cms_acl') {
         if (!$this->usergroup) {
             $this->_error = CBPTXT::T("Importer") . ' - ' . CBPTXT::T("error:") . ' ' . CBPTXT::T("No usergroup selected");
             return false;
         }
     }
     if ($this->import_type == 'subscription') {
         if (!$this->from_plan) {
             $this->_error = CBPTXT::T("Importer") . ' - ' . CBPTXT::T("error:") . ' ' . CBPTXT::T("No subscription plan selected");
             return false;
         }
         if (!$this->from_sub_status) {
             $this->_error = CBPTXT::T("Importer") . ' - ' . CBPTXT::T("error:") . ' ' . CBPTXT::T("No subscription status selected");
             return false;
         }
     }
     if ($this->import_type != 'file_uid_plan_exp') {
         if (!$this->plan) {
             $this->_error = CBPTXT::T("Importer") . ' - ' . CBPTXT::T("error:") . ' ' . CBPTXT::T("No plan selected");
             return false;
         }
         if (!$this->state) {
             $this->_error = CBPTXT::T("Importer") . ' - ' . CBPTXT::T("error:") . ' ' . CBPTXT::T("No subscription state selected");
             return false;
         }
         if (!$this->date) {
             $this->_error = CBPTXT::T("Importer") . ' - ' . CBPTXT::T("error:") . ' ' . CBPTXT::T("No subscription date selected");
             return false;
         }
     }
     if ($fromFile) {
         $tmpName = $userfile['tmp_name'];
         $fileSize = (int) $userfile['size'];
         // $fileType = $userfile['type'];
     } else {
         $tmpName = null;
         $fileSize = null;
     }
     $planStateDate = array();
     switch ($this->import_type) {
         case 'file_uid':
             $fp = fopen($tmpName, 'r');
             $content = fread($fp, $fileSize);
             fclose($fp);
             unlink($tmpName);
             $userIdList = explode(',', trim($content));
             break;
         case 'file_uid_plan_exp':
             $userIdList = array();
             $fp = fopen($tmpName, 'r');
             if ($fp) {
                 $n = 0;
                 while (!feof($fp)) {
                     $line = trim(str_replace('"', '', fgets($fp, 256)));
                     $n += 1;
                     if (strlen($line) > 0) {
                         $matches = null;
                         if (preg_match('/([1-9][0-9]*),([1-9][0-9]*),([AXC]),([0-9]{4}-[0-9]{2}-[0-9]{2} [0-9][0-9]:[0-9][0-9]:[0-9][0-9])/', $line, $matches)) {
                             if (!in_array((int) $matches[1], $userIdList)) {
                                 $userIdList[] = (int) $matches[1];
                             }
                             $planStateDate[(int) $matches[1]][] = array('plan' => (int) $matches[2], 'status' => $matches[3], 'date' => $matches[4]);
                         } else {
                             $this->_error = CBPTXT::T("Importer") . ' - ' . CBPTXT::T("error:") . ' ' . sprintf(CBPTXT::T("Line %s does not match the format userid,planid,status,date, e.g. 63,1,A,2009-01-01 00:00:00, and is instead: %s ."), $n, htmlspecialchars($line));
                             fclose($fp);
                             unlink($tmpName);
                             return false;
                         }
                     }
                 }
             }
             fclose($fp);
             unlink($tmpName);
             break;
         case 'cms_acl':
             if (checkJversion() >= 2) {
                 $sql = 'SELECT id FROM #__users u' . ' JOIN #__user_usergroup_map m ON ( u.id = m.user_id )' . ' WHERE m.group_id = ' . (int) $this->usergroup;
             } else {
                 $sql = 'SELECT id FROM #__users' . ' WHERE gid = ' . (int) $this->usergroup;
             }
             $this->_db->setQuery($sql);
             $userIdList = $this->_db->loadResultArray();
             break;
         case 'subscription':
             $statuses = $this->from_sub_status;
             foreach (array_keys($statuses) as $k) {
                 $statuses[$k] = $this->_db->Quote($statuses[$k][0]);
             }
             $sql = 'SELECT s.user_id FROM #__cbsubs_subscriptions s' . ' JOIN #__users u ON ( u.id = s.user_id AND u.block = 0 )' . ' JOIN #__comprofiler c ON ( c.id = s.user_id AND c.confirmed = 1 AND c.approved = 1 )' . ' WHERE s.plan_id = ' . (int) $this->from_plan . ' AND s.status IN (' . implode(',', $statuses) . ')';
             $this->_db->setQuery($sql);
             $userIdList = $this->_db->loadResultArray();
             break;
         default:
             $this->_error = CBPTXT::T("Importer") . ' - ' . CBPTXT::T("error:") . ' ' . CBPTXT::T("Import type not implemented!");
             return false;
             break;
     }
     if (count($userIdList) == 0) {
         $this->_error = CBPTXT::T("Importer") . ' - ' . CBPTXT::T("error:") . ' ' . CBPTXT::T("No user to import");
         return false;
     }
     $plansMgr = cbpaidPlansMgr::getInstance();
     if ($this->import_type != 'file_uid_plan_exp') {
         $plan = $plansMgr->loadPlan((int) $this->plan);
         $subscriptionTime = (int) $plan->strToTime($this->date);
         foreach ($userIdList as $key => $value) {
             if (!is_numeric($value)) {
                 $this->_error = CBPTXT::T("Importer") . ' - ' . CBPTXT::T("error:") . ' ' . CBPTXT::T("non-numeric userid value: ") . str_replace("\n", ' ', htmlspecialchars($value));
                 return false;
             }
             $userIdList[$key] = (int) $value;
         }
     } else {
         $plan = null;
         $subscriptionTime = null;
     }
     $this->_db->setQuery("SELECT u.id, u.username FROM #__comprofiler c, #__users u WHERE c.id=u.id AND u.block = 0 AND c.approved = 1 AND c.confirmed = 1 AND c.id IN (" . implode(',', $userIdList) . ")");
     $users = $this->_db->loadObjectList('id');
     if (count($userIdList) != count($users)) {
         if (is_array($users)) {
             foreach ($users as $u) {
                 $keys = array_keys($userIdList, $u->id);
                 unset($userIdList[$keys[0]]);
                 unset($planStateDate[(int) $u->id]);
             }
         }
         $idList = implode(', ', $userIdList);
         $this->_error = CBPTXT::T("Importer") . ' - ' . CBPTXT::T("error:") . ' ' . CBPTXT::T("Not all userId exist, are active (confirmed, approved and enabled) ! innexistant or inactive ids: ") . $idList;
         return false;
     }
     $this->_db->setQuery("SELECT DISTINCT user_id FROM #__cbsubs_subscriptions WHERE user_id IN (" . implode(',', $userIdList) . ")" . " ORDER BY user_id");
     $usersSubscribed = $this->_db->loadResultArray();
     $incompatibleUsersSubs = array();
     if ($this->import_type != 'file_uid_plan_exp') {
         foreach ($users as $user) {
             @set_time_limit(60);
             $incompatible = false;
             if (in_array($user->id, $usersSubscribed)) {
                 if ($plan->get('exclusive') && $plan->get('item_type') == 'usersubscription') {
                     $paidUserExtension = cbpaidUserExtension::getInstance($user->id);
                     $subscriptions = $paidUserExtension->getUserSubscriptions(null, false);
                     foreach ($subscriptions as $s) {
                         if ($s->parent_plan == $plan->get('parent') && $s->checkIfValid()) {
                             $sPlan = $s->getPlan();
                             if ($sPlan->get('exclusive') && $sPlan->get('item_type') == 'usersubscription') {
                                 // check if any other exclusive subscription with same parent plan is active:
                                 $incompatible = true;
                                 break;
                             }
                         }
                     }
                 }
             }
             if (!$incompatible) {
                 if ($plan->get('parent')) {
                     $plansMgr = cbpaidPlansMgr::getInstance();
                     $parentPlan = $plansMgr->loadPlan($plan->get('parent'));
                     $parentSub = $parentPlan->loadLatestSomethingOfUser($user->id, null);
                     if (!$parentSub) {
                         $incompatible = true;
                     }
                 }
             }
             if ($incompatible) {
                 if (!in_array($user->id, $incompatibleUsersSubs)) {
                     $incompatibleUsersSubs[] = $user->id;
                 }
                 continue;
             }
             if (!$this->dryrun) {
                 $userFull = CBuser::getUserDataInstance($user->id);
                 $this->createSomething($plan, $userFull, $this->state, $subscriptionTime);
                 CBuser::unsetUsersNotNeeded(array((int) $user->id));
             }
         }
     } else {
         $cbpaidTimes = cbpaidTimes::getInstance();
         $systemTimeZone = new DateTimeZone($cbpaidTimes->systemTimeZone());
         foreach ($users as $user) {
             @set_time_limit(60);
             foreach ($planStateDate[(int) $user->id] as $psd) {
                 $plan = $plansMgr->loadPlan((int) $psd['plan']);
                 $status = $psd['status'];
                 if ($psd['date']) {
                     $date = DateTime::createFromFormat('Y-m-d H:i:s', $psd['date'], $systemTimeZone);
                     $subscriptionTime = $date->getTimestamp();
                 } else {
                     $subscriptionTime = $cbpaidTimes->startTime();
                 }
                 $incompatible = false;
                 if (in_array($user->id, $usersSubscribed)) {
                     if ($plan->get('exclusive') && $plan->get('item_type') == 'usersubscription') {
                         $paidUserExtension = cbpaidUserExtension::getInstance($user->id);
                         $subscriptions = $paidUserExtension->getUserSubscriptions(null, false);
                         foreach ($subscriptions as $s) {
                             if ($s->parent_plan == $plan->get('parent') && $s->checkIfValid()) {
                                 $sPlan = $s->getPlan();
                                 if ($sPlan->get('exclusive') && $sPlan->get('item_type') == 'usersubscription') {
                                     // check if any other exclusive subscription with same parent plan is active:
                                     $incompatible = true;
                                     break;
                                 }
                             }
                         }
                     }
                 }
                 if (!$incompatible) {
                     if ($plan->get('parent')) {
                         $plansMgr = cbpaidPlansMgr::getInstance();
                         $parentPlan = $plansMgr->loadPlan($plan->get('parent'));
                         $parentSub = $parentPlan->loadLatestSomethingOfUser($user->id, null);
                         if (!$parentSub) {
                             $incompatible = true;
                         }
                     }
                 }
                 if ($incompatible) {
                     if (!in_array($user->id, $incompatibleUsersSubs)) {
                         $incompatibleUsersSubs[] = $user->id;
                     }
                     continue;
                 }
                 if (!$this->dryrun) {
                     $userFull = CBuser::getUserDataInstance($user->id);
                     $this->createSomething($plan, $userFull, $status, $subscriptionTime);
                     CBuser::unsetUsersNotNeeded(array((int) $user->id));
                 }
             }
         }
     }
     if (count($userIdList) > 0 && count($incompatibleUsersSubs) == 0) {
         $resultText = CBPTXT::T("Success");
     } elseif (count($userIdList) > count($incompatibleUsersSubs)) {
         $resultText = CBPTXT::T("Partial Success");
     } elseif (count($userIdList) == count($incompatibleUsersSubs)) {
         $resultText = CBPTXT::T("Import failed");
     } else {
         $resultText = CBPTXT::T("Unknown Result");
     }
     $return .= '<h1>' . $resultText . ($this->dryrun ? ' [' . CBPTXT::T("DRY-RUN - NO REAL SUBSCRIPTION") . ']' : '') . ':</h1>';
     if (count($incompatibleUsersSubs) > 0) {
         $idList = implode(', ', $incompatibleUsersSubs);
         $return .= '<p>' . CBPTXT::T("Some users have already subscriptions: user ids: ") . $idList . '</p>';
         // $this->_error		=	CBPTXT::T("Importer") . ' - ' . CBPTXT::T("error:") . ' ' . CBPTXT::T("Some users have already subscriptions: user ids: ") . $idList;
         // return false;
     }
     if ($this->import_type != 'file_uid_plan_exp') {
         $return .= '<p>' . sprintf(CBPTXT::T("%d users subscribed to plan: %s , with state: %s"), count($userIdList) - count($incompatibleUsersSubs), $plan->get('name'), CBPTXT::T($this->_states[$this->state])) . '</p>';
         if (count($userIdList) - count($incompatibleUsersSubs) > 0) {
             $return .= '<p>' . CBPTXT::T("Users subscribed (usernames):") . '</p>';
             $return .= '<p>';
             foreach ($users as $user) {
                 if (!in_array($user->id, $incompatibleUsersSubs)) {
                     $return .= $user->username . ' ';
                 }
             }
             $return .= '</p>';
         }
     } else {
         $return .= '<p>' . sprintf(CBPTXT::T("%d users subscribed"), count($userIdList) - count($incompatibleUsersSubs)) . '</p>';
         if (count($userIdList) - count($incompatibleUsersSubs) > 0) {
             $return .= '<p>' . CBPTXT::T("Users subscribed (usernames):") . '</p>';
             foreach ($users as $user) {
                 if (!in_array($user->id, $incompatibleUsersSubs)) {
                     $return .= '<p>' . $user->username . ' ' . CBPTXT::T("to") . ' ';
                     foreach ($planStateDate[(int) $user->id] as $psd) {
                         $plan = $plansMgr->loadPlan((int) $psd['plan']);
                         $status = $psd['status'];
                         $return .= sprintf(CBPTXT::T("plan: %s , with state: %s") . ' ', $plan->get('name'), CBPTXT::T($this->_states[$status]));
                     }
                 }
             }
             $return .= '</p>';
         }
     }
     if (count($incompatibleUsersSubs) > 0) {
         $return .= '<p>' . CBPTXT::T("Following Users could not be subscribed (usernames) because either: (A) an exclusive active subscription exists that would conflict with the imported user subscription, or: (B) it is a children plan but the parent plan subscription does not exist:") . '</p>';
         $return .= '<p>';
         foreach ($incompatibleUsersSubs as $uid) {
             if (isset($users[$uid])) {
                 $return .= $users[$uid]->username . ' ';
             }
         }
         $return .= '</p>';
     }
     $this->_resultOfStore = $return;
     return true;
 }
Exemplo n.º 8
0
	public function setParams( $params, $html = true ) {
		global $_CB_framework, $_PLUGINS;

		$plugin	=	cbgjClass::getPlugin();
		$user	=&	CBuser::getUserDataInstance( $_CB_framework->myId() );
		$params	=	cbgjClass::parseParams( $params, $html, $this->getParams( $html ) );

		$_PLUGINS->trigger( 'gjint_onBeforeSetAutoParams', array( &$params, &$this, $user, $plugin ) );

		$this->set( 'params', trim( $params->toIniString() ) );

		$_PLUGINS->trigger( 'gjint_onAfterSetAutoParams', array( $params, $this, $user, $plugin ) );
	}
Exemplo n.º 9
0
	/**
	 * Parses for users set to receive a notification and sends it to them
	 *
	 * @param string             $notification The notification to send
	 * @param string             $subject
	 * @param string             $body
	 * @param GroupTable         $group        Group for this notification
	 * @param UserTable|int|null $from         UserTable|int: Specific user to notify from (used for substitutions), Null: Notify from self
	 * @param UserTable|int|null $to           UserTable|int: Specific user to notify, Null: Notify everyone elegible
	 * @param array              $skip         Array of user ids to skip
	 * @param int                $status       Group status restriction for notifications (e.g. 2: Group Moderators and above)
	 * @param array              $extra
	 * @return bool
	 */
	static public function sendNotifications( $notification, $subject, $body, $group, $from = null, $to = null, $skip = array(), $status = 1, $extra = array() )
	{
		global $_CB_database, $_PLUGINS;

		if ( is_int( $from ) ) {
			$from					=	\CBuser::getUserDataInstance( $from );
		}

		if ( is_int( $to ) ) {
			$to						=	\CBuser::getUserDataInstance( $to );
		}

		$myId						=	Application::MyUser()->getUserId();

		if ( ( ! $notification ) || ( ! $subject ) || ( ! $body ) ) {
			return false;
		} elseif ( $to && ( $to->get( 'id' ) == $myId ) ) {
			return false;
		} elseif ( $from && $to && ( $from->get( 'id' ) == $to->get( 'id' ) ) ) {
			return false;
		} elseif ( ( ! $group->get( 'id' ) ) || ( $group->get( 'published' ) != 1 ) ) {
			return false;
		} elseif ( $group->category()->get( 'id' ) && ( ! $group->category()->get( 'published' ) ) ) {
			return false;
		}

		static $params				=	null;

		if ( ! $params ) {
			$plugin					=	$_PLUGINS->getLoadedPlugin( 'user', 'cbgroupjive' );
			$params					=	$_PLUGINS->getPluginParams( $plugin );
		}

		if ( ( ! $group->category()->get( 'id' ) ) && ( ! $params->get( 'groups_uncategorized', 1 ) ) ) {
			return false;
		} elseif ( ! $params->get( 'notifications', 1 ) ) {
			return false;
		}

		if ( ! $status ) {
			$status					=	1;
		}

		if ( ! is_array( $skip ) ) {
			$skip					=	array( $skip );
		}

		if ( $from ) {
			$skip[]					=	$from->get( 'id' );
		}

		$moderators					=	Application::CmsPermissions()->getGroupsOfViewAccessLevel( Application::Config()->get( 'moderator_viewaccesslevel', 3, GetterInterface::INT ), true );

		$query						=	'SELECT DISTINCT n.*'
									.	', u.' . $_CB_database->NameQuote( 'status' )
									.	"\n FROM " . $_CB_database->NameQuote( '#__groupjive_notifications' ) . " AS n"
									.	"\n LEFT JOIN " . $_CB_database->NameQuote( '#__groupjive_users' ) . " AS u"
									.	' ON u.' . $_CB_database->NameQuote( 'user_id' ) . ' = n.' . $_CB_database->NameQuote( 'user_id' )
									.	' AND u.' . $_CB_database->NameQuote( 'group' ) . ' = n.' . $_CB_database->NameQuote( 'group' )
									.	"\n LEFT JOIN " . $_CB_database->NameQuote( '#__comprofiler' ) . " AS cb"
									.	' ON cb.' . $_CB_database->NameQuote( 'id' ) . ' = u.' . $_CB_database->NameQuote( 'user_id' )
									.	"\n LEFT JOIN " . $_CB_database->NameQuote( '#__users' ) . " AS j"
									.	' ON j.' . $_CB_database->NameQuote( 'id' ) . ' = cb.' . $_CB_database->NameQuote( 'id' )
									.	"\n LEFT JOIN " . $_CB_database->NameQuote( '#__user_usergroup_map' ) . " AS g"
									.	' ON g.' . $_CB_database->NameQuote( 'user_id' ) . ' = j.' . $_CB_database->NameQuote( 'id' )
									.	"\n WHERE n." . $_CB_database->NameQuote( 'group' ) . " = " . (int) $group->get( 'id' );

		if ( $to ) {
			$query					.=	"\n AND n." . $_CB_database->NameQuote( 'user_id' ) . " = " . (int) $to->get( 'id' );
		} else {
			$query					.=	"\n AND n." . $_CB_database->NameQuote( 'user_id' ) . " != " . (int) $myId;
		}

		if ( $skip ) {
			$query					.=	"\n AND n." . $_CB_database->NameQuote( 'user_id' ) . " NOT IN " . $_CB_database->safeArrayOfIntegers( $skip );
		}

		$query						.=	"\n AND cb." . $_CB_database->NameQuote( 'approved' ) . " = 1"
									.	"\n AND cb." . $_CB_database->NameQuote( 'confirmed' ) . " = 1"
									.	"\n AND j." . $_CB_database->NameQuote( 'block' ) . " = 0"
									.	"\n AND ( n." . $_CB_database->NameQuote( 'user_id' ) . " = " . (int) $group->get( 'user_id' )
									.		' OR u.' . $_CB_database->NameQuote( 'status' ) . " >= " . (int) $status
									.		' OR g.' . $_CB_database->NameQuote( 'group_id' ) . " IN " . $_CB_database->safeArrayOfIntegers( $moderators ) . ' )';
		$_CB_database->setQuery( $query );
		$rows						=	$_CB_database->loadObjectList( null, '\CB\Plugin\GroupJive\Table\NotificationTable', array( $_CB_database ) );

		self::preFetchUsers( $rows );

		/** @var NotificationTable[] $rows */
		foreach ( $rows as $row ) {
			if ( ! $row->params()->get( $notification, 0 ) ) {
				continue;
			}

			if ( $to ) {
				$notifyUser			=	$to;
			} else {
				$notifyUser			=	\CBuser::getUserDataInstance( (int) $row->get( 'user_id' ) );
			}

			$group->set( '_user_status', $row->get( 'status' ) );

			if ( ! self::canAccessGroup( $group, $notifyUser ) ) {
				continue;
			}

			self::sendNotification( 4, $from, $notifyUser, $subject, $body, $group, $extra );
		}

		return true;
	}
 function sendFromSystem($toid, $sub, $message, $replaceVariables = true, $mode = 0, $cc = null, $bcc = null, $attachment = null, $extraStrings = null, $footer = true)
 {
     global $_CB_framework, $_CB_database, $ueConfig;
     if (!$sub && !$message) {
         return true;
     }
     if ($extraStrings === null) {
         $extraStrings = array();
     }
     $rowFrom = new stdClass();
     $rowFrom->email = $ueConfig['reg_email_from'];
     $rowFrom->name = stripslashes($ueConfig['reg_email_name']);
     $rowFrom->replytoEmail = $ueConfig['reg_email_replyto'];
     $rowFrom->replytoName = stripslashes($ueConfig['reg_email_name']);
     if (!is_object($toid)) {
         $rowTo = CBuser::getUserDataInstance($toid);
     } else {
         $rowTo = $toid;
     }
     if ($replaceVariables) {
         $sub = $this->_replaceVariables($sub, $rowTo, $mode, $extraStrings);
         $message = $this->_replaceVariables($message, $rowTo, $mode, $extraStrings);
     }
     if ($footer) {
         $message .= ($mode ? "\n<br />\n<br />" : "\n\n") . sprintf(_UE_EMAILFOOTER, cb_html_entity_decode_all($_CB_framework->getCfg('sitename')), $_CB_framework->getCfg('live_site'));
     }
     // $message = str_replace(array("\\","\"","\$"), array("\\\\","\\\"","\\\$"), $message);
     // eval ("\$message = \"$message\";");
     $message = str_replace(array('\\n'), array("\n"), $message);
     // compensate for wrong language definitions (using '\n' instaed of "\n")
     return $this->_sendEmailMSG($rowTo, $rowFrom, cb_html_entity_decode_all($_CB_framework->getCfg('sitename')) . ' - ' . $sub, $message, false, $mode, $cc, $bcc, $attachment);
 }
function sendNewPass($option)
{
    global $_CB_framework, $_CB_database, $ueConfig, $_PLUGINS, $_POST;
    // simple spoof check security
    checkCBPostIsHTTPS();
    cbSpoofCheck('lostPassForm');
    cbRegAntiSpamCheck();
    $usernameExists = isset($ueConfig['login_type']) && $ueConfig['login_type'] != 2;
    // ensure no malicous sql gets past
    $checkusername = trim(cbGetParam($_POST, 'checkusername', ''));
    $confirmEmail = trim(cbGetParam($_POST, 'checkemail', ''));
    $Itemid = $_CB_framework->itemid();
    $_PLUGINS->loadPluginGroup('user');
    $_PLUGINS->trigger('onStartNewPassword', array(&$checkusername, &$confirmEmail));
    if ($_PLUGINS->is_errors()) {
        cbRedirect(cbSef("index.php?option={$option}&amp;task=lostPassword" . ($Itemid ? "&amp;Itemid=" . (int) $Itemid : ""), false), $_PLUGINS->getErrorMSG(), 'error');
        return;
    }
    $checkusername = stripslashes($checkusername);
    $confirmEmail = stripslashes($confirmEmail);
    // these two are used by _NEWPASS_SUB message below:
    $_live_site = $_CB_framework->getCfg('live_site');
    $_sitename = "";
    // NEEDED BY _NEWPASS_SUB for  sitename already added in subject by cbNotification class. was = $_CB_framework->getCfg( 'sitename' );
    if ($usernameExists && $confirmEmail != '' && !$checkusername) {
        $_CB_database->setQuery("SELECT id, username FROM #__users" . "\n WHERE email = " . $_CB_database->Quote($confirmEmail));
        $userIdUsername = null;
        $result = $_CB_database->loadObjectList($userIdUsername);
        if ($_CB_database->getErrorNum() || count($result) == 0) {
            cbRedirect(cbSef('index.php?option=' . $option . '&amp;task=lostPassword' . ($Itemid ? '&amp;Itemid=' . (int) $Itemid : ''), false), sprintf(_UE_EMAIL_DOES_NOT_EXISTS_ON_SITE, htmlspecialchars($confirmEmail)), 'error');
        }
        foreach ($result as $userIdUsername) {
            $message = str_replace('\\n', "\n", sprintf(_UE_USERNAMEREMINDER_MSG, $_CB_framework->getCfg('sitename'), $userIdUsername->username, $_live_site));
            $subject = sprintf(_UE_USERNAMEREMINDER_SUB, $userIdUsername->username);
            $_PLUGINS->trigger('onBeforeUsernameReminder', array($userIdUsername->id, &$subject, &$message));
            if ($_PLUGINS->is_errors()) {
                cbRedirect(cbSef("index.php?option={$option}&amp;task=lostPassword" . ($Itemid ? "&amp;Itemid=" . (int) $Itemid : ""), false), $_PLUGINS->getErrorMSG(), 'error');
                return;
            }
            $cbNotification = new cbNotification();
            $res = $cbNotification->sendFromSystem($userIdUsername->id, $subject, $message);
            if (!$res) {
                break;
            }
        }
        $_PLUGINS->trigger('onAfterUsernameReminder', array(&$result, &$res));
        if ($res) {
            cbRedirect(cbSef("index.php?option={$option}&amp;task=done" . ($Itemid ? "&amp;Itemid=" . (int) $Itemid : ""), false), sprintf(_UE_USERNAME_REMINDER_SENT, htmlspecialchars($confirmEmail)));
        } else {
            cbRedirect(cbSef("index.php?option={$option}&amp;task=done" . ($Itemid ? "&amp;Itemid=" . (int) $Itemid : ""), false), _UE_EMAIL_SENDING_ERROR);
        }
    } elseif ($confirmEmail != '') {
        if ($usernameExists) {
            $_CB_database->setQuery("SELECT id FROM #__users" . "\n WHERE username = "******" AND email = " . $_CB_database->Quote($confirmEmail));
        } else {
            $_CB_database->setQuery("SELECT id FROM #__users" . "\n WHERE email = " . $_CB_database->Quote($confirmEmail));
        }
        $user_id = $_CB_database->loadResult();
        if (!$user_id) {
            cbRedirect(cbSef('index.php?option=' . $option . '&amp;task=lostPassword' . ($Itemid ? '&amp;Itemid=' . (int) $Itemid : ''), false), _ERROR_PASS);
        }
        $newpass = cbMakeRandomString(8, true);
        // should be $user->setRandomPassword() but as this whole function needs to be redone to require clicking link for new password change, let's leave it for now.
        $message = str_replace('\\n', "\n", sprintf(_UE_NEWPASS_MSG, $checkusername, $_live_site, $newpass));
        $subject = sprintf(_UE_NEWPASS_SUB, $checkusername);
        $_PLUGINS->trigger('onBeforeNewPassword', array($user_id, &$newpass, &$subject, &$message));
        if ($_PLUGINS->is_errors()) {
            cbRedirect(cbSef("index.php?option={$option}&amp;task=lostPassword" . ($Itemid ? "&amp;Itemid=" . (int) $Itemid : ""), false), $_PLUGINS->getErrorMSG(), 'error');
            return;
        }
        $_PLUGINS->trigger('onNewPassword', array($user_id, $newpass));
        $user = CBuser::getUserDataInstance((int) $user_id);
        $user->password = $newpass;
        if (!$user->storePassword()) {
            cbRedirect(cbSef("index.php?option={$option}&amp;task=lostPassword" . ($Itemid ? "&amp;Itemid=" . (int) $Itemid : ""), false), $user->getError(), 'error');
            return;
        } else {
            $cbNotification = new cbNotification();
            $res = $cbNotification->sendFromSystem($user_id, $subject, $message);
            if (!$res) {
                cbRedirect(cbSef("index.php?option={$option}&amp;task=done" . ($Itemid ? "&amp;Itemid=" . (int) $Itemid : ""), false), _UE_NEWPASS_FAILED);
                return;
            }
        }
        cbRedirect(cbSef("index.php?option={$option}&amp;task=done" . ($Itemid ? "&amp;Itemid=" . (int) $Itemid : ""), false), sprintf(_UE_NEWPASS_SENT, htmlspecialchars($confirmEmail)));
    } else {
        cbRedirect(cbSef("index.php?option={$option}&amp;task=done" . ($Itemid ? "&amp;Itemid=" . (int) $Itemid : ""), false), _UE_NEWPASS_FAILED);
    }
}
 /**
  * Attempts to authorize and capture a credit card for a single payment of a payment basket using PSP DirectLink
  *
  * @ param  array                $card                : $card['type'], $card['number'], $card['firstname'], $card['lastname'], $card['expmonth'], $card['expyear'], and optionally: $card['address'], $card['zip'], $card['country']
  * @param  cbpaidPaymentBasket  $paymentBasket
  * @param  string               $returnText                  RETURN param
  * @param  boolean              $transientErrorDoReschedule  RETURN param
  * @return boolean|null                                      TRUE: succes, FALSE: failed or unknown result, NULL: not implemented
  */
 public function processAutoRecurringPayment($paymentBasket, &$returnText, &$transientErrorDoReschedule)
 {
     // form XML request:
     $formvars = $this->_fillinAutoRecuringDirectLinkRequstParams($paymentBasket);
     $error = null;
     $status = null;
     $response = $this->_directLinkOperation($paymentBasket, 'orderdirect', $formvars, 'Autorecurring', $error, $status);
     if ($response === false) {
         $user = CBuser::getUserDataInstance($paymentBasket->user_id);
         $username = $user ? $user->username : '******';
         $returnText = sprintf(CBPTXT::T("FAILED Auto-recurring payment of %s for basket %s Order_id %s of %s (username %s - user id %s) using %s due to error %s."), $paymentBasket->renderPrice(null, null, null, false), $paymentBasket->id, $paymentBasket->sale_id, $paymentBasket->first_name . ' ' . $paymentBasket->last_name, $username, $paymentBasket->user_id, $this->getPayName(), 'HTTP error ' . ': ' . $error . ' ' . 'Status' . ': ' . $status);
         $transientErrorDoReschedule = true;
         $return = false;
     } else {
         // clean logs for PCI compliance:
         $formvarsCleaned = $formvars;
         if (isset($formvars['CC'])) {
             $formvarsCleaned['CC'] = preg_replace('/^.+(.{4})$/', 'XXXX XXXX XXXX \\1', $formvars['CC']);
         }
         unset($formvarsCleaned['CVC']);
         unset($formvarsCleaned['Ecom_Payment_Card_Verification']);
         if (isset($formvars['PSWD'])) {
             $formvars['PSWD'] = '********';
         }
         // Parse the response XML results:
         $paymentResult = $this->handleDirectLinkPaymentResult($paymentBasket, $response, 'A', array('formvars' => $formvarsCleaned, 'xmlreply' => $response));
         $user = CBuser::getUserDataInstance($paymentBasket->user_id);
         $username = $user ? $user->username : '******';
         if ($paymentResult !== false) {
             if ($paymentResult === true && in_array($paymentBasket->payment_status, array('Completed', 'Pending'))) {
                 if ($paymentBasket->payment_status == 'Completed') {
                     $returnText = sprintf(CBPTXT::T("Completed Auto-recurring payment of %s for basket %s Order_id %s of %s (username %s - user id %s) using %s with txn_id %s and auth_id %s."), $paymentBasket->renderPrice(null, null, null, false), $paymentBasket->id, $paymentBasket->sale_id, $paymentBasket->first_name . ' ' . $paymentBasket->last_name, $username, $paymentBasket->user_id, $this->getPayName(), $paymentBasket->txn_id, $paymentBasket->auth_id);
                 } else {
                     $returnText = sprintf(CBPTXT::T("Pending Auto-recurring payment of %s for basket %s Order_id %s of %s (username %s - user id %s) using %s with txn_id %s and auth_id %s for reason: %s."), $paymentBasket->renderPrice(null, null, null, false), $paymentBasket->id, $paymentBasket->sale_id, $paymentBasket->first_name . ' ' . $paymentBasket->last_name, $username, $paymentBasket->user_id, $this->getPayName(), $paymentBasket->txn_id, $paymentBasket->auth_id, $paymentBasket->reason_code);
                 }
                 $transientErrorDoReschedule = false;
                 $return = true;
             } else {
                 $returnText = sprintf(CBPTXT::T("FAILED (%s) Auto-recurring payment of %s for basket %s Order_id %s of %s (username %s - user id %s) using %s due to error %s."), $paymentBasket->payment_status, $paymentBasket->renderPrice(null, null, null, false), $paymentBasket->id, $paymentBasket->sale_id, $paymentBasket->first_name . ' ' . $paymentBasket->last_name, $username, $paymentBasket->user_id, $this->getPayName(), $paymentBasket->reason_code);
                 $transientErrorDoReschedule = true;
                 $return = false;
             }
         } else {
             $returnText = sprintf(CBPTXT::T("FAILED (Error) Auto-recurring payment of %s for basket %s Order_id %s of %s (username %s - user id %s) using %s due to error %s."), $paymentBasket->renderPrice(null, null, null, false), $paymentBasket->id, $paymentBasket->sale_id, $paymentBasket->first_name . ' ' . $paymentBasket->last_name, $username, $paymentBasket->user_id, $this->getPayName(), $paymentBasket->reason_code);
             $transientErrorDoReschedule = true;
             $return = false;
         }
     }
     return $return;
 }
Exemplo n.º 13
0
	/**
	 * @param  TabTable   $tab       Current tab
	 * @param  UserTable  $user      Current user
	 * @param  int        $ui        1 front, 2 admin UI
	 * @param  array      $postdata  Raw unfiltred POST data
	 * @return string                HTML
	 */
	public function getCBpluginComponent( $tab, $user, $ui, $postdata )
	{
		global $_CB_framework;

		$format							=	$this->input( 'format', null, GetterInterface::STRING );

		if ( $format != 'raw' ) {
			outputCbJs( 1 );
			outputCbTemplate( 1 );
		}

		$action							=	$this->input( 'action', null, GetterInterface::STRING );
		$function						=	$this->input( 'func', null, GetterInterface::STRING );
		$type							=	$this->input( 'type', null, GetterInterface::STRING );
		$id								=	(int) $this->input( 'id', null, GetterInterface::INT );
		$userId							=	(int) $this->input( 'user', null, GetterInterface::INT );
		$tabId							=	(int) $this->input( 'tab', null, GetterInterface::INT );

		if ( ! $tabId ) {
			switch( $type ) {
				case 'photos':
					$tabId				=	'cbgalleryTabPhotos';
					break;
				case 'files':
					$tabId				=	'cbgalleryTabFiles';
					break;
				case 'videos':
					$tabId				=	'cbgalleryTabVideos';
					break;
				case 'music':
					$tabId				=	'cbgalleryTabMusic';
					break;
			}
		}

		$viewer							=	CBuser::getMyUserDataInstance();

		if ( $userId ) {
			$user						=	CBuser::getUserDataInstance( (int) $userId );
		} else {
			$user						=	CBuser::getMyUserDataInstance();
		}

		$profileUrl						=	$_CB_framework->userProfileUrl( (int) $user->get( 'id' ), false, $tabId );

		if ( ! in_array( $type, array( 'photos', 'files', 'videos', 'music' ) ) ) {
			if ( ( $action == 'items' ) && in_array( $function, array( 'download', 'preview', 'show' ) ) ) {
				header( 'HTTP/1.0 401 Unauthorized' );
				exit();
			} else {
				cbRedirect( $profileUrl, CBTxt::T( 'Not authorized.' ), 'error' );
			}
		}

		$tab							=	new TabTable();

		$tab->load( ( is_integer( $tabId ) ? $tabId : array( 'pluginclass' => $tabId ) ) );

		if ( ! ( $tab->get( 'enabled' ) && Application::User( (int) $viewer->get( 'id' ) )->canViewAccessLevel( $tab->get( 'viewaccesslevel' ) ) ) ) {
			if ( ( $action == 'items' ) && in_array( $function, array( 'download', 'preview', 'show' ) ) ) {
				header( 'HTTP/1.0 401 Unauthorized' );
				exit();
			} else {
				cbRedirect( $profileUrl, CBTxt::T( 'Not authorized.' ), 'error' );
			}
		}

		if ( ! ( $tab->params instanceof ParamsInterface ) ) {
			$tab->params				=	new Registry( $tab->params );
		}

		if ( $format != 'raw' ) {
			ob_start();
		}

		switch ( $action ) {
			case 'items':
				switch ( $function ) {
					case 'download':
						$this->outputItem( false, false, $id, $type, $tab, $user, $viewer );
						break;
					case 'edit':
						$this->showItemEdit( $id, $type, $tab, $user, $viewer );
						break;
					case 'new':
						$this->showItemEdit( null, $type, $tab, $user, $viewer );
						break;
					case 'save':
						cbSpoofCheck( 'plugin' );
						$this->saveItemEdit( $id, $type, $tab, $user, $viewer );
						break;
					case 'publish':
						$this->stateItem( 1, $id, $type, $tab, $user, $viewer );
						break;
					case 'unpublish':
						$this->stateItem( 0, $id, $type, $tab, $user, $viewer );
						break;
					case 'delete':
						$this->deleteItem( $id, $type, $tab, $user, $viewer );
						break;
					case 'preview':
						$this->outputItem( true, true, $id, $type, $tab, $user, $viewer );
						break;
					case 'show':
					default:
						$this->outputItem( true, false, $id, $type, $tab, $user, $viewer );
						break;
				}
				break;
			case 'folders':
				if ( ! $tab->params->get( 'tab_' . $type . '_folders', 1 ) ) {
					cbRedirect( $profileUrl, CBTxt::T( 'Not authorized.' ), 'error' );
				}

				switch ( $function ) {
					case 'edit':
						$this->showFolderEdit( $id, $type, $tab, $user, $viewer );
						break;
					case 'new':
						$this->showFolderEdit( null, $type, $tab, $user, $viewer );
						break;
					case 'save':
						cbSpoofCheck( 'plugin' );
						$this->saveFolderEdit( $id, $type, $tab, $user, $viewer );
						break;
					case 'publish':
						$this->stateFolder( 1, $id, $type, $tab, $user, $viewer );
						break;
					case 'unpublish':
						$this->stateFolder( 0, $id, $type, $tab, $user, $viewer );
						break;
					case 'delete':
						$this->deleteFolder( $id, $type, $tab, $user, $viewer );
						break;
					case 'show':
					default:
						$this->showFolder( $id, $type, $tab, $user, $viewer );
						break;
				}
				break;
			default:
				cbRedirect( 'index.php', CBTxt::T( 'Not authorized.' ), 'error' );
				break;
		}

		if ( $format != 'raw' ) {
			$html						=	ob_get_contents();
			ob_end_clean();

			$class						=	$this->params->get( 'general_class', null );

			$return						=	'<div id="cbGallery" class="cbGallery' . ( $class ? ' ' . htmlspecialchars( $class ) : null ) . '">'
										.		'<div id="cbGalleryInner" class="cbGalleryInner">'
										.			$html
										.		'</div>'
										.	'</div>';

			echo $return;
		}
	}
Exemplo n.º 14
0
	/**
	 * Trys to load a user object from a variable
	 *
	 * @param object|int $userVar
	 * @param boolean $fallback
	 * @return UserTable
	 */
	private function prepareUser( $userVar, $fallback = true )
	{
		if ( is_object( $userVar ) ) {
			if ( $userVar instanceof UserTable ) {
				$user		=	$userVar;
			} elseif ( isset( $userVar->user_id ) ) {
				$userId		=	(int) $userVar->user_id;
			} elseif ( isset( $userVar->user ) ) {
				$userId		=	(int) $userVar->user;
			} elseif ( isset( $userVar->id ) ) {
				$userId		=	(int) $userVar->id;
			}
		} elseif ( is_integer( $userVar ) ) {
			$userId			=	$userVar;
		}

		if ( isset( $userId ) && is_integer( $userId ) ) {
			$user			=	CBuser::getUserDataInstance( (int) $userId );

			if ( ( ! $user->get( 'id' ) ) && ( ! $fallback ) ) {
				$user		=	null;
			}
		}

		if ( ! isset( $user ) ) {
			if ( $fallback ) {
				$user		=	CBuser::getUserDataInstance( null );
			} else {
				$user		=	null;
			}
		}

		return $user;
	}
Exemplo n.º 15
0
	/**
	 * prepare notification owner CB user
	 *
	 * @return moscomprofilerUser
	 */
	public function getOwner() {
		static $cache	=	array();

		$id				=	$this->get( 'user_id' );

		if ( ! isset( $cache[$id] ) ) {
			$cache[$id]	=&	CBuser::getUserDataInstance( (int) $id );
		}

		return $cache[$id];
	}
Exemplo n.º 16
0
	/**
	 * Authorizes the provider, registers or links, then logs in as needed
	 */
	private function authenticate()
	{
		global $_CB_database;

		try {
			/** @var Hybrid_Provider_Adapter $adapter */
			$adapter				=	$this->_hybridAuth->authenticate( $this->_providerId );
		} catch ( Exception $e ) {
			cbRedirect( $this->_returnUrl, CBTxt::T( 'AUTH_TO_PROVIDER_FAILED', 'Authentication to [provider] failed. Error: [error]', array( '[provider]' => $this->_providerName, '[error]' => $e->getMessage() ) ), 'error' );
			return;
		}

		if ( $adapter ) {
			if ( ! $this->_hybridAuth->isConnectedWith( $this->_providerId ) ) {
				cbRedirect( $this->_returnUrl, CBTxt::T( 'CONNECTION_TO_PROVIDER_NOT_ESTABLISHED', 'Connection to [provider] not established.', array( '[provider]' => $this->_providerName ) ), 'error' );
				return;
			}

			try {
				/** @var Hybrid_User_Profile $profile */
				/** @noinspection PhpUndefinedMethodInspection */
				$profile			=	$adapter->getUserProfile();

				$this->profile( $profile );

				$myUser				=	CBuser::getMyUserDataInstance();

				$query				=	'SELECT ' . $_CB_database->NameQuote( 'id' )
									.	"\n FROM " . $_CB_database->NameQuote( '#__comprofiler' )
									.	"\n WHERE " . $_CB_database->NameQuote( $this->_providerField ) . " = " . $_CB_database->Quote( $profile->identifier );
				$_CB_database->setQuery( $query );
				$userId				=	(int) $_CB_database->loadResult();

				$user				=	CBuser::getUserDataInstance( $userId );

				if ( $myUser->get( 'id' ) ) {
					if ( ( ! $this->params->get( $this->_provider . '_link', true, GetterInterface::BOOLEAN ) ) && ( ! $myUser->get( $this->_providerField ) ) ) {
						cbRedirect( $this->_returnUrl, CBTxt::T( 'LINKING_FOR_PROVIDER_NOT_PERMITTED', 'Linking for [provider] is not permitted.', array( '[provider]' => $this->_providerName ) ), 'error' );
						return;
					}

					if ( ! $myUser->get( $this->_providerField ) ) {
						if ( $user->get( 'id' ) && ( $myUser->get( 'id' ) != $user->get( 'id' ) ) ) {
							cbRedirect( $this->_returnUrl, CBTxt::T( 'PROVIDER_ALREADY_LINKED', '[provider] account already linked to another user.', array( '[provider]' => $this->_providerName ) ), 'error' );
							return;
						}

						if ( ! $myUser->storeDatabaseValue( $this->_providerField, $profile->identifier ) ) {
							cbRedirect( $this->_returnUrl, CBTxt::T( 'PROVIDER_FAILED_TO_LINK', '[provider] account failed to link. Error: [error]', array( '[provider]' => $this->_providerName, '[error]' => $myUser->getError() ) ), 'error' );
							return;
						}

						cbRedirect( $this->_returnUrl, CBTxt::T( 'PROVIDER_LINKED_SUCCESSFULLY', '[provider] account linked successfully!', array( '[provider]' => $this->_providerName ) ) );
						return;
					}

					cbRedirect( $this->_returnUrl, CBTxt::T( 'ALREADY_LINKED_TO_PROVIDER', 'You are already linked to a [provider] account.', array( '[provider]' => $this->_providerName ) ), 'error' );
					return;
				} else {
					if ( ( ! $this->params->get( $this->_provider . '_register', true, GetterInterface::BOOLEAN ) ) && ( ! $user->get( 'id' ) ) ) {
						cbRedirect( $this->_returnUrl, CBTxt::T( 'SIGN_UP_WITH_PROVIDER_NOT_PERMITTED', 'Sign up with [provider] is not permitted.', array( '[provider]' => $this->_providerName ) ), 'error' );
						return;
					}

					$login			=	true;

					if ( ! $user->get( 'id' ) ) {
						$login		=	$this->register( $user, $profile );
					}

					if ( $login ) {
						$this->login( $user );
					}
				}
			} catch( Exception $e ) {
				cbRedirect( $this->_returnUrl, CBTxt::T( 'FAILED_TO_RETRIEVE_PROVIDER_PROFILE', 'Failed to retrieve [provider] profile. Error: [error]', array( '[provider]' => $this->_providerName, '[error]' => $e->getMessage() ) ), 'error' );
				return;
			}
		}
	}
Exemplo n.º 17
0
	/**
	 * @param null|int  $id
	 * @param UserTable $user
	 */
	private function saveInviteEdit( $id, $user )
	{
		global $_CB_framework, $_CB_database, $_PLUGINS;

		$inviteLimit						=	(int) $this->params->get( 'invite_limit', null );
		$cbModerator						=	Application::User( (int) $user->get( 'id' ) )->isGlobalModerator();

		$row								=	new cbinvitesInviteTable();

		$row->load( (int) $id );

		$canAccess							=	false;
		$inviteCount						=	0;

		if ( ! $row->get( 'id' ) ) {
			if ( $cbModerator ) {
				$canAccess					=	true;
			} elseif ( $user->get( 'id' ) && Application::MyUser()->canViewAccessLevel( $this->params->get( 'invite_create_access', 2 ) ) ) {
				if ( $inviteLimit ) {
					$query					=	'SELECT COUNT(*)'
											.	"\n FROM " . $_CB_database->NameQuote( '#__comprofiler_plugin_invites' )
											.	"\n WHERE " . $_CB_database->NameQuote( 'user_id' ) . " = " . (int) $user->get( 'id' )
											.	"\n AND ( " . $_CB_database->NameQuote( 'user' ) . " IS NULL OR " . $_CB_database->NameQuote( 'user' ) . " = " . $_CB_database->Quote( '' ) . " )";
					$_CB_database->setQuery( $query );
					$inviteCount			=	(int) $_CB_database->loadResult();

					if ( $inviteCount < $inviteLimit ) {
						$canAccess			=	true;
					}
				} else {
					$canAccess				=	true;
				}
			}
		} elseif ( $cbModerator || ( $row->get( 'user_id' ) == $user->get( 'id' ) ) ) {
			$canAccess						=	true;
		}

		$profileUrl							=	$_CB_framework->userProfileUrl( $row->get( 'user_id', $user->get( 'id' ) ), false, 'cbinvitesTab' );

		if ( $canAccess && ( ! $row->isAccepted() ) ) {
			$toArray						=	explode( ',', $this->input( 'post/to', null, GetterInterface::STRING ) );

			if ( ( ! $this->params->get( 'invite_multiple', 1 ) ) && ( ! $cbModerator ) && ( count( $toArray ) > 1 ) ) {
				$this->showInviteEdit( $row->get( 'id' ), $user, CBTxt::T( 'Comma seperated lists are not supported! Please use a single To address.' ) ); return;
			}

			$sent							=	false;

			if ( ! empty( $toArray ) ) {
				foreach ( $toArray as $k => $to ) {
					if ( $k != 0 ) {
						$row->set( 'id', null );
						$row->set( 'code', null );
					}

					$orgTo					=	$row->get( 'to' );

					$row->set( 'to', $to );
					$row->set( 'subject', $this->input( 'post/subject', $row->get( 'subject' ), GetterInterface::STRING ) );

					if ( $this->params->get( 'invite_editor', 2 ) >= 2 ) {
						$row->set( 'body', $this->input( 'post/body', $row->get( 'body' ), GetterInterface::HTML ) );
					} else {
						$row->set( 'body', $this->input( 'post/body', $row->get( 'body' ), GetterInterface::STRING ) );
					}

					$row->set( 'user_id', (int) $this->input( 'post/user_id', $row->get( 'user_id', $user->get( 'id' ) ), GetterInterface::INT ) );

					if ( $cbModerator ) {
						$row->set( 'user', (int) $this->input( 'post/user', $row->get( 'user' ), GetterInterface::INT ) );
					}

					if ( ! $row->get( 'code' ) ) {
						$row->set( 'code', md5( uniqid() ) );
					}

					$new					=	( $row->get( 'id' ) ? false : true );

					if ( $new && $inviteLimit ) {
						$inviteCount++;

						if ( $inviteCount > $inviteLimit ) {
							cbRedirect( $profileUrl, CBTxt::T( 'Invite limit reached!' ), 'error' );
						}
					}

					if ( ! $row->get( 'user' ) ) {
						$toUser				=	new UserTable();

						$toUser->loadByEmail( $row->get( 'to' ) );
					} else {
						$toUser				=	CBuser::getUserDataInstance( (int) $row->get( 'user' ) );
					}

					if ( ! $row->get( 'to' ) ) {
						$row->setError( CBTxt::T( 'To address not specified.' ) );
					} elseif ( ! cbIsValidEmail( $row->get( 'to' ) ) ) {
						$row->setError( CBTxt::T( 'INVITE_TO_ADDRESS_INVALID', 'To address not valid: [to_address]', array( '[to_address]' => $row->get( 'to' ) ) ) );
					} elseif ( $toUser->id == $row->get( 'user_id' ) ) {
						$row->setError( CBTxt::T( 'You can not invite your self.' ) );
					} elseif ( $toUser->id && ( $row->get( 'to' ) != $orgTo ) ) {
						$row->setError( CBTxt::T( 'To address is already a user.' ) );
					} elseif ( ( ! $this->params->get( 'invite_duplicate', 0 ) ) && ( ! $cbModerator ) && $row->isDuplicate() ) {
						$row->setError( CBTxt::T( 'To address is already invited.' ) );
					} elseif ( $this->params->get( 'invite_captcha', 0 ) && ( ! $row->get( 'id' ) ) && ( $k == 0 ) && ( ! $cbModerator ) ) {
						$_PLUGINS->loadPluginGroup( 'user' );

						$_PLUGINS->trigger( 'onCheckCaptchaHtmlElements', array() );

						if ( $_PLUGINS->is_errors() ) {
							$row->setError( CBTxt::T( $_PLUGINS->getErrorMSG() ) );
						}
					}

					$_PLUGINS->trigger( 'invites_onBeforeInvite', array( &$row, $user ) );

					if ( $row->getError() || ( ! $row->store() ) ) {
						$this->showInviteEdit( $row->get( 'id' ), $user, CBTxt::T( 'INVITE_FAILED_SAVE_ERROR', 'Invite failed to save! Error: [error]', array( '[error]' => $row->getError() ) ) ); return;
					}

					if ( ( $new || ( ! $row->isSent() ) ) && ( ! $toUser->id ) ) {
						if ( ! $row->send() ) {
							$this->showInviteEdit( $row->get( 'id' ), $user, CBTxt::T( 'INVITE_FAILED_SEND_ERROR', 'Invite failed to send! Error: [error]', array( '[error]' => $row->getError() ) ) ); return;
						} else {
							$sent			=	true;
						}
					}

					$_PLUGINS->trigger( 'invites_onAfterInvite', array( $row, $sent, $user ) );
				}

				cbRedirect( $profileUrl, ( $sent ? CBTxt::T( 'Invite sent successfully!' ) : CBTxt::T( 'Invite saved successfully!' ) ) );
			} else {
				$this->showInviteEdit( $row->get( 'id' ), $user, CBTxt::T( 'To address not specified.' ) ); return;
			}
		} else {
			cbRedirect( $profileUrl, CBTxt::T( 'Not authorized.' ), 'error' );
		}
	}
Exemplo n.º 18
0
	/**
	 * @param cbautoactionsActionTable $trigger
	 * @param UserTable $user
	 */
	public function execute( $trigger, $user )
	{
		global $_CB_database;

		if ( ! $this->installed() ) {
			if ( $trigger->getParams()->get( 'debug', false, GetterInterface::BOOLEAN ) ) {
				var_dump( CBTxt::T( 'AUTO_ACTION_INVITE_NOT_INSTALLED', ':: Action [action] :: CB Invites is not installed', array( '[action]' => (int) $trigger->get( 'id' ) ) ) );
			}

			return;
		}

		foreach ( $trigger->getParams()->subTree( 'invite' ) as $row ) {
			/** @var ParamsInterface $row */
			$owner					=	$row->get( 'owner', null, GetterInterface::STRING );

			if ( ! $owner ) {
				$owner				=	(int) $user->get( 'id' );
			} else {
				$owner				=	(int) $trigger->getSubstituteString( $owner );
			}

			if ( ! $owner ) {
				if ( $trigger->getParams()->get( 'debug', false, GetterInterface::BOOLEAN ) ) {
					var_dump( CBTxt::T( 'AUTO_ACTION_INVITE_NO_OWNER', ':: Action [action] :: CB Invites skipped due to missing owner', array( '[action]' => (int) $trigger->get( 'id' ) ) ) );
				}

				continue;
			}

			if ( $user->get( 'id' ) != $owner ) {
				$user				=	CBuser::getUserDataInstance( $owner );
			}

			switch ( (int) cbGetParam( $params, 'invite_mode', 1 ) ) {
				case 1:
					$invite			=	new cbinvitesInviteTable();

					$toArray		=	explode( ',', $trigger->getSubstituteString( $row->get( 'to', null, GetterInterface::STRING ) ) );

					foreach ( $toArray as $to ) {
						$invite->set( 'id', null );
						$invite->set( 'to', $to );
						$invite->set( 'subject', $trigger->getSubstituteString( $row->get( 'subject', null, GetterInterface::STRING ) ) );
						$invite->set( 'body', $trigger->getSubstituteString( $row->get( 'body', null, GetterInterface::RAW ) ) );
						$invite->set( 'user_id', $owner );
						$invite->set( 'code', md5( uniqid() ) );

						if ( ! $invite->store() ) {
							if ( $trigger->getParams()->get( 'debug', false, GetterInterface::BOOLEAN ) ) {
								var_dump( CBTxt::T( 'AUTO_ACTION_INVITE_FAILED', ':: Action [action] :: CB Invites failed to save. Error: [error]', array( '[action]' => (int) $trigger->get( 'id' ), '[error]' => $invite->getError() ) ) );
							}

							continue;
						}

						if ( ! $invite->send() ) {
							if ( $trigger->getParams()->get( 'debug', false, GetterInterface::BOOLEAN ) ) {
								var_dump( CBTxt::T( 'AUTO_ACTION_INVITE_SEND_FAILED', ':: Action [action] :: CB Invites failed to send. Error: [error]', array( '[action]' => (int) $trigger->get( 'id' ), '[error]' => $invite->getError() ) ) );
							}

							continue;
						}
					}
					break;
				case 2:
					$query			=	'SELECT *'
									.	"\n FROM " . $_CB_database->NameQuote( '#__comprofiler_plugin_invites' )
									.	"\n WHERE " . $_CB_database->NameQuote( 'to' ) . " = " . $_CB_database->Quote( $user->get( 'email' ) );
					$_CB_database->setQuery( $query );
					$invites		=	$_CB_database->loadObjectList( null, 'cbinvitesInviteTable', array( $_CB_database ) );

					/** @var cbinvitesInviteTable[] $invites */
					foreach ( $invites as $invite ) {
						$invite->accept( $user );
					}
					break;
				case 3:
					$query			=	'SELECT *'
									.	"\n FROM " . $_CB_database->NameQuote( '#__comprofiler_plugin_invites' )
									.	"\n WHERE ( " . $_CB_database->NameQuote( 'user_id' ) . " = " . (int) $user->get( 'id' )
									.	' OR ' . $_CB_database->NameQuote( 'user' ) . ' = ' . (int) $user->get( 'id' ) . ' )';
					$_CB_database->setQuery( $query );
					$invites		=	$_CB_database->loadObjectList( null, 'cbinvitesInviteTable', array( $_CB_database ) );

					/** @var cbinvitesInviteTable[] $invites */
					foreach ( $invites as $invite ) {
						$invite->delete();
					}
					break;
			}
		}
	}
Exemplo n.º 19
0
	/**
	 * USED by XML interface ONLY !!! Renders invoice
	 *
	 * @param  string           $value
	 * @param  ParamsInterface  $params
	 * @return string                    HTML to display
	 */
	public function renderInvoice( $value, &$params ) {
		global $_CB_framework;

		if ( ( $_CB_framework->getUi() == 2 ) && ( $_CB_framework->myId() != 0 ) ) {

			if ( cbpaidApp::getBaseClass() === null ) {
				//TODO: check if this is even needed:
				$pseudoPlugin				=	new getcbpaidsubscriptionsTab();
				$pseudoPlugin->params		=&	$params;
				cbpaidApp::getBaseClass( $pseudoPlugin );
			}
			$baseClass						=&	cbpaidApp::getBaseClass();

			$itsmyself					=	true;			// simulate user's view of invoice.

			$baseClass->outputRegTemplate();

			if ( strpos( cbGetParam( $_GET, 'invoice' ), ',') === false ) {
				if ( $this->load( (int) $value ) ) {
					$user					=	CBuser::getUserDataInstance( (int) $this->user_id );
				}
				return $this->displayInvoice( $user, $itsmyself, true );
			} else {
				$html					=	'<div class="cbregmultipage">';
				foreach ( explode( ',', cbGetParam( $_GET, 'invoice' ) ) as $basketId ) {
					$paymentBasket		=	new self();
					if ( $paymentBasket->load( (int) $basketId ) ) {
						$user			=	CBuser::getUserDataInstance( (int) $paymentBasket->user_id );
					}
					$html				.=	$paymentBasket->displayInvoice( $user, $itsmyself, false )
						.	'<hr class="cbregpagebreak" />';
					if ( is_callable( array( 'CBuser', 'unsetUsersNotNeeded' ) ) ) {
						// CB 1.8+:
						CBuser::unsetUsersNotNeeded( array( (int) $paymentBasket->user_id ) );
					}
					unset( $paymentBasket, $user );
				}
				$html					.=	'</div>';
			}
			return $html;
		}
		return null;
	}
 /**
  * Checks for upgrade or renewal possibilities
  *
  * @param  boolean                       $newSubsActivation   called to activate new subscriptions
  * @param  cbpaidUsersubscriptionRecord|null       $deactivatedSub      just deactivated subscription before (and reason for) calling this method (or NULL)
  * @param  string                        $reason              checking reason: 'N'=new subscription (default), 'R'=renewal, 'U'=update
  * @param  boolean                       $forceCheck
  * @return boolean|null                                       TRUE: any valid subscription found, FALSE: no valid subscription, NULL: no $forceCheck and no changes
  */
 public function checkUserSubscriptions($newSubsActivation, &$deactivatedSub, $reason, $forceCheck = false)
 {
     global $_CB_framework;
     $params = cbpaidApp::settingsParams();
     // as this method beeing called e.g. whenever a subscription is deactivated, it's calling itself through expireIfExpired:
     static $recurringStopper = 0;
     static $justExpiredSubs = array();
     $user_id = $this->id;
     if (!$user_id) {
         return null;
     }
     $user = CBuser::getUserDataInstance($user_id);
     if (!$user) {
         return null;
     }
     if ($deactivatedSub !== null) {
         $justExpiredSubs[$deactivatedSub->id] = $deactivatedSub;
     }
     while ($recurringStopper++ == 0) {
         // get all subscriptions with status 'A' Active:
         $subscriptions = $this->getUserSubscriptions('A');
         // check for just expired subscriptions within status 'A' Active and expires them now:
         foreach (array_keys($subscriptions) as $k) {
             if (!isset($justExpiredSubs[$k])) {
                 $exp = $subscriptions[$k]->expireIfExpired();
                 if ($exp) {
                     $justExpiredSubs[$k] = $subscriptions[$k];
                 }
             }
         }
         // check if no recurring occured:
         if ($recurringStopper == 1) {
             // no recurrings, can stop at next while:
             $recurringStopper = -1;
         } else {
             // recurring occured, need to recheck everything:
             $recurringStopper = 0;
         }
     }
     if ($recurringStopper == 0) {
         if ($newSubsActivation || count($justExpiredSubs) > 0) {
             // some subscription(s) just expired, we now need to adapt user's ACL:
             $remainingSubscriptions = $this->getUserSubscriptions('A');
             if (count($justExpiredSubs) > 0) {
                 // Just expired Gids: collect Gids to remove:
                 list(, $removeGids, $oldChldGids) = $this->_computeMaxBlockGid($user, $justExpiredSubs);
             } else {
                 $removeGids = array();
                 $oldChldGids = array();
             }
             // Collect current Gids (and their children Gids):
             list($block, $gids, $curChldGids) = $this->_computeMaxBlockGid($user, $remainingSubscriptions);
             // Add old children gids and current children Gids to make sure we're allowed to change gid in j 1.5- through multiple plans and usergroups:
             $oldChldGids = array_merge($oldChldGids, $curChldGids);
             // Now adjust the blocking and gids:
             $this->_adjustUserAclBlock($user, 'PaidSubscription', $block, $gids, $removeGids, $oldChldGids, $reason);
             return $block == 0;
         } else {
             if ($forceCheck) {
                 $enableFreeRegisteredUser = $params->get('enableFreeRegisteredUser', 1);
                 $remainingSubscriptions = $this->getUserSubscriptions('A');
                 $block = count($remainingSubscriptions) == 0 && !$enableFreeRegisteredUser ? 1 : 0;
                 if ($block == 1) {
                     list($block, $gids, ) = $this->_computeMaxBlockGid($user, $remainingSubscriptions);
                     // Get all gids of all plans that are available to $user_id: This will allow to not change any GID of a user which is not included in those GIDS (e.g. super-admin) in j 1.5-:
                     $oldPotentialPlansGids = $this->_allPlansGid($user);
                     $removeGids = array();
                     $this->_adjustUserAclBlock($user, 'PaidSubscription', $block, $gids, $removeGids, $oldPotentialPlansGids, $reason);
                     if (!self::_allValuesOfArrayInArray((array) $user->gids, $oldPotentialPlansGids) || in_array($_CB_framework->acl->mapGroupNamesToValues('Superadministrator'), (array) $user->gids)) {
                         // Do not block a user that has a gid in his gids that is not controlled by a plan that was accessible to him after downgrade:
                         // This avoids blocking e.g. super admins if there is no super-admin plan.
                         // But also if there is a Super-admin plan by configuration error, it still should not get blocked:
                         $block = 0;
                     }
                 }
                 return $block == 0;
             }
         }
     }
     return null;
 }
Exemplo n.º 21
0
	function _cbadmin_emailUsers( &$rows, $emailSubject, $emailBody, $limitstart, $limit, $total, $simulationMode ) {
		global $_PLUGINS;
		// simple spoof check security
		cbSpoofCheck( 'cbadmingui' );
		cbRegAntiSpamCheck();
	
		$cbNotification				=	new cbNotification();
		$mode						=	1;		// html
		
		$usernames					=	'';
		foreach ( $rows as $row ) {
			$user					=	CBuser::getUserDataInstance( (int) $row->id );
			$usernames				.=	( $usernames ? ', ' : '' ) . htmlspecialchars( $user->username );
			if ( $simulationMode ) {
				$usernames			.=	' (' . htmlspecialchars( CBTxt::T('email not send: simulation mode') ) . ')';
			} else {
				$extraStrings		=	array();
				$_PLUGINS->trigger( 'onBeforeBackendUserEmail', array( &$user, &$emailSubject, &$emailBody, $mode, &$extraStrings, $simulationMode ) );
				if ( ! $cbNotification->sendFromSystem( $user, $emailSubject, $this->_cbadmin_makeLinksAbsolute( $emailBody ), true, $mode, null, null, null, $extraStrings, false ) ) {
					$usernames		.=	': <span class="cb_result_error">' . htmlspecialchars( CBTxt::T('Error sending email!') ) . '</span>';
				}
			}
		}
	
		if ( $total < $limit ) {
			$limit					=	$total;
		}
		ob_start();
		$usersView					=	_CBloadView( 'users' );
		$usersView->ajaxResults( $usernames, $emailSubject, $this->_cbadmin_makeLinksAbsolute( $emailBody ), $limitstart, $limit, $total );
		$html						=	ob_get_contents();
		ob_end_clean();
	
		$reply						=	array(	'result'		=>	1,
												'htmlcontent'	=>	$html );
		if ( ! ( $total - ( $limitstart + $limit ) > 0 ) ) {
			$reply['result']		=	2;
		}
		echo json_encode( $reply );
		sleep(3);
	}
Exemplo n.º 22
0
	/**
	 * prepare frontend tab render
	 *
	 * @param  object             $tab
	 * @param  moscomprofilerUser $user
	 * @param  int                $ui
	 * @return mixed
	 */
	public function getDisplayTab( $tab, $user, $ui ) {
		global $_CB_framework;

		outputCbJs( 1 );
		outputCbTemplate( 1 );

		cbgjClass::getTemplate( 'tab' );

		$plugin		=	cbgjClass::getPlugin();
		$viewer		=&	CBuser::getUserDataInstance( $_CB_framework->myId() );
		$categories	=	$this->getCategories( $user, $viewer, $plugin );
		$groups		=	$this->getGroups( $user, $viewer, $plugin );
		$joined		=	$this->getJoined( $user, $viewer, $plugin );
		$invites	=	$this->getInvites( $user, $viewer, $plugin );
		$invited	=	$this->getInvited( $user, $viewer, $plugin );

		ob_start();
		HTML_groupjiveTab::showTab( $categories, $groups, $joined, $invites, $invited, $user, $viewer, $plugin );

		$html		=	ob_get_contents();
		ob_end_clean();

		$return		=	'<div id="cbGj" class="cbGroupJive' . htmlspecialchars( $plugin->params->get( 'general_class', null ) ) . '">'
					.		'<div id="cbGjInner" class="cbGroupJiveInner">'
					.			$html
					.		'</div>'
					.	'</div>';

		return $return;
	}
Exemplo n.º 23
0
$plugin						=	cbactivityClass::getPlugin();

if ( ! $plugin ) {
	return;
}

$exclude					=	$plugin->params->get( 'general_exclude', null );
$display					=	(int) $params->get( 'activity_display', 1 );
$avatar						=	(int) $params->get( 'activity_avatar', 0 );
$cutOff						=	(int) $params->get( 'activity_cut_off', 5 );
$limit						=	(int) $params->get( 'activity_limit', 10 );
$titleLimit					=	(int) $params->get( 'activity_title_length', 100 );
$descLimit					=	(int) $params->get( 'activity_desc_length', 100 );
$imgThumbnails				=	(int) $params->get( 'activity_img_thumbnails', 1 );
$user						=	CBuser::getUserDataInstance( $_CB_framework->myId() );
$now						=	$_CB_framework->getUTCNow();

outputCbJs( 1 );
outputCbTemplate( 1 );

cbactivityClass::getTemplate( array( 'module', 'jquery', 'activity' ) );
HTML_cbactivityJquery::loadJquery( 'module', $user, $plugin );

switch( $display ) {
	case 2: // Connections Only
		$where				=	array( 'b.referenceid', '=', (int) $user->get( 'id' ), 'b.accepted', '=', 1, 'b.pending', '=', 0 );
		break;
	case 3: // Self Only
		$where				=	array( 'user_id', '=', (int) $user->get( 'id' ) );
		break;
 /**
  * Updates payment status of basket and of corresponding subscriptions if there is a change in status
  *
  * @param  cbpaidPaymentBasket        $paymentBasket         Basket
  * @param  string                     $eventType             type of event (paypal type): 'web_accept', 'subscr_payment', 'subscr_signup', 'subscr_modify', 'subscr_eot', 'subscr_cancel', 'subscr_failed'
  * @param  string                     $paymentStatus         new status (Completed, RegistrationCancelled)
  * @param  cbpaidPaymentNotification  $notification          notification object of the payment
  * @param  int                        $occurrences           renewal occurrences
  * @param  int                        $autorecurring_type    0: not auto-recurring, 1: auto-recurring without payment processor notifications, 2: auto-renewing with processor notifications updating $expiry_date
  * @param  int                        $autorenew_type        0: not auto-renewing (manual renewals), 1: asked for by user, 2: mandatory by configuration
  * @param  boolean|string             $txnIdMultiplePaymentDates  FALSE: unique txn_id for each payment, TRUE: same txn_id can have multiple payment dates, additionally: 'SINGLEPAYMENT' will not look at txn_id at all
  * @param  boolean                    $storePaymentRecord   TRUE: normal case, create payment record if needed. FALSE: offline case where pending payment should not create a payment record.
  * @return void
  */
 public function updatePaymentStatus($paymentBasket, $eventType, $paymentStatus, &$notification, $occurrences, $autorecurring_type, $autorenew_type, $txnIdMultiplePaymentDates, $storePaymentRecord = true)
 {
     global $_CB_framework, $_PLUGINS;
     $pluginsLoaded = false;
     $basketUpdateNulls = false;
     $previousUnifiedStatus = $this->mapPaymentStatus($paymentBasket->payment_status);
     $unifiedStatus = $this->mapPaymentStatus($paymentStatus);
     // get all related subscriptions being paid by this basket:
     $subscriptions = $paymentBasket->getSubscriptions();
     $thisIsReferencePayment = false;
     $user = CBuser::getUserDataInstance((int) $paymentBasket->user_id);
     if ($paymentBasket->payment_status != $paymentStatus || $unifiedStatus == 'Partially-Refunded' || $autorecurring_type) {
         if ($paymentStatus && (in_array($eventType, array('web_accept', 'subscr_payment', 'subscr_signup')) || in_array($unifiedStatus, array('Reversed', 'Refunded', 'Partially-Refunded')))) {
             $paymentBasket->payment_status = $paymentStatus;
         }
         if (in_array($eventType, array('subscr_payment', 'subscr_signup'))) {
             $paymentBasket->recurring = 1;
         }
         if ($autorecurring_type == 0 && in_array($unifiedStatus, array('Completed', 'Processed', 'FreeTrial'))) {
             $paymentBasket->mc_amount1 = null;
             $paymentBasket->mc_amount3 = null;
             $paymentBasket->period1 = null;
             $paymentBasket->period3 = null;
             $basketUpdateNulls = true;
         }
         // if (count($subscriptions) >= 1) {
         $now = $_CB_framework->now();
         $completed = false;
         $thisIsReferencePayment = false;
         $reason = null;
         switch ($unifiedStatus) {
             case 'FreeTrial':
             case 'Completed':
             case 'Processed':
                 // this includes Canceled_Reversal !!! :
                 if ($unifiedStatus == 'FreeTrial') {
                     $paymentBasket->payment_status = 'Completed';
                 }
                 if ($unifiedStatus == 'FreeTrial' || $unifiedStatus == 'Completed') {
                     if ($notification->payment_date) {
                         $time_completed = cbpaidTimes::getInstance()->gmStrToTime($notification->payment_date);
                     } else {
                         $time_completed = $now;
                     }
                     $paymentBasket->time_completed = Application::Database()->getUtcDateTime($time_completed);
                     $completed = true;
                 }
                 if ($paymentStatus == 'Canceled_Reversal') {
                     $paymentBasket->payment_status = 'Completed';
                 }
                 if (is_object($notification) && isset($notification->txn_id)) {
                     // real payment with transaction id: store as reference payment if not already stored:
                     $thisIsReferencePayment = $this->_storePaymentOnce($paymentBasket, $notification, $now, $txnIdMultiplePaymentDates, 'Updating payment record because of new status of payment basket: ' . $unifiedStatus . ($paymentStatus != $unifiedStatus ? ' (new gateway-status: ' . $paymentStatus . ')' : '') . ' because of event received: ' . $eventType . '. Previous status was: ' . $previousUnifiedStatus);
                 } else {
                     // Free trials don't have a notification:
                     $thisIsReferencePayment = true;
                 }
                 if ($thisIsReferencePayment) {
                     // payment not yet processed:
                     $autorenewed = $paymentBasket->recurring == 1 && $unifiedStatus == 'Completed' && $previousUnifiedStatus == 'Completed';
                     for ($i = 0, $n = count($subscriptions); $i < $n; $i++) {
                         $reason = $autorenewed ? 'R' : $subscriptions[$i]->_reason;
                         $subscriptions[$i]->activate($user, $now, $completed, $reason, $occurrences, $autorecurring_type, $autorenew_type, $autorenewed ? 1 : 0);
                     }
                 }
                 break;
             case 'RegistrationCancelled':
             case 'Reversed':
             case 'Refunded':
             case 'Unsubscribed':
                 if ($unifiedStatus == 'RegistrationCancelled') {
                     if (!($previousUnifiedStatus == 'NotInitiated' || $previousUnifiedStatus === 'Pending' && $paymentBasket->payment_method === 'offline')) {
                         return;
                     }
                 }
                 for ($i = 0, $n = count($subscriptions); $i < $n; $i++) {
                     $reason = $subscriptions[$i]->_reason;
                     if ($reason != 'R' || in_array($unifiedStatus, array('Reversed', 'Refunded'))) {
                         // Expired and Cancelled as well as Partially-Refunded are not reverted !		//TBD: really revert on refund everything ? a plan param would be nice here
                         if (!in_array($previousUnifiedStatus, array('Pending', 'In-Progress', 'Denied', 'Reversed', 'Refunded')) && in_array($subscriptions[$i]->status, array('A', 'R', 'I')) && !$subscriptions[$i]->hasPendingPayment($paymentBasket->id)) {
                             // not a cancelled or denied renewal:
                             $subscriptions[$i]->revert($user, $unifiedStatus);
                         }
                     }
                 }
                 if ($unifiedStatus == 'RegistrationCancelled') {
                     $paymentBasket->historySetMessage('Payment basket deleted because the subscriptions and payment got cancelled');
                     $paymentBasket->delete();
                     // deletes also payment_Items
                 }
                 $paidUserExtension = cbpaidUserExtension::getInstance($paymentBasket->user_id);
                 $subscriptionsAnyAtAll = $paidUserExtension->getUserSubscriptions('');
                 $params = cbpaidApp::settingsParams();
                 $createAlsoFreeSubscriptions = $params->get('createAlsoFreeSubscriptions', 0);
                 if (count($subscriptionsAnyAtAll) == 0 && !$createAlsoFreeSubscriptions) {
                     $user = new UserTable();
                     $id = (int) cbGetParam($_GET, 'user');
                     $user->load((int) $id);
                     if ($user->id && $user->block == 1) {
                         $user->delete(null);
                     }
                 }
                 break;
             case 'Denied':
             case 'Pending':
                 if ($unifiedStatus == 'Denied') {
                     // In fact when denied, it's the case as if the user attempted payment but failed it: He should be able to re-try: So just store the payment as denied for the records.
                     if ($eventType == 'subscr_failed' || $eventType == 'subscr_cancel' && $autorecurring_type != 2) {
                         // special case of a failed attempt:
                         // or this is the final failed attempt of a basket with notifications:
                         break;
                     }
                 }
                 if ($previousUnifiedStatus == 'Completed') {
                     return;
                     // do not change a Completed payment as it cannot become Pending again. If we get "Pending" after "Completed", it is a messages chronological order mistake.
                 }
                 break;
             case 'In-Progress':
             case 'Partially-Refunded':
             default:
                 break;
         }
         if ($eventType == 'subscr_cancel') {
             if (!in_array($unifiedStatus, array('Denied', 'Reversed', 'Refunded', 'Unsubscribed'))) {
                 for ($i = 0, $n = count($subscriptions); $i < $n; $i++) {
                     $subscriptions[$i]->autorecurring_cancelled($user, $unifiedStatus, $eventType);
                 }
             }
         }
         for ($i = 0, $n = count($subscriptions); $i < $n; $i++) {
             $subscriptions[$i]->notifyPaymentStatus($unifiedStatus, $previousUnifiedStatus, $paymentBasket, $notification, $now, $user, $eventType, $paymentStatus, $occurrences, $autorecurring_type, $autorenew_type);
         }
         if (in_array($unifiedStatus, array('Denied', 'Reversed', 'Refunded', 'Partially-Refunded', 'Pending', 'In-Progress'))) {
             $thisIsReferencePayment = $this->_storePaymentOnce($paymentBasket, $notification, $now, $txnIdMultiplePaymentDates, 'Updating payment record because of new status of payment basket: ' . $unifiedStatus . ($paymentStatus != $unifiedStatus ? ' (new gateway-status: ' . $paymentStatus . ')' : '') . ' because of event received: ' . $eventType . '. Previous status was: ' . $previousUnifiedStatus);
         }
         // }
         foreach ($paymentBasket->loadPaymentTotalizers() as $totalizer) {
             $totalizer->notifyPaymentStatus($thisIsReferencePayment, $unifiedStatus, $previousUnifiedStatus, $paymentBasket, $notification, $now, $user, $eventType, $paymentStatus, $occurrences, $autorecurring_type, $autorenew_type, $txnIdMultiplePaymentDates);
         }
         if (!in_array($unifiedStatus, array('RegistrationCancelled'))) {
             if ($thisIsReferencePayment && in_array($unifiedStatus, array('Completed', 'Processed'))) {
                 $paymentBasket->setPaidInvoiceNumber($reason);
             }
             $paymentBasket->historySetMessage('Updating payment basket ' . ($paymentStatus !== null ? 'status: ' . $unifiedStatus . ($paymentStatus != $unifiedStatus ? ' (new gateway-status: ' . $paymentStatus . ')' : '') : '') . ' because of event received: ' . $eventType . ($paymentStatus !== null ? '. Previous status was: ' . $previousUnifiedStatus : ''));
             $paymentBasket->store($basketUpdateNulls);
         } else {
             //TDB ? : $paymentBasket->delete(); in case of RegistrationCancelled done above, but should be done in case of FreeTrial ? (could be a param in future)
         }
         if (!in_array($unifiedStatus, array('Completed', 'Processed')) || $thisIsReferencePayment) {
             $_PLUGINS->loadPluginGroup('user', 'cbsubs.');
             $_PLUGINS->loadPluginGroup('user/plug_cbpaidsubscriptions/plugin');
             $pluginsLoaded = true;
             $_PLUGINS->trigger('onCPayAfterPaymentStatusChange', array(&$user, &$paymentBasket, &$subscriptions, $unifiedStatus, $previousUnifiedStatus, $occurrences, $autorecurring_type, $autorenew_type));
         }
     }
     if (!in_array($unifiedStatus, array('Completed', 'Processed')) || $thisIsReferencePayment) {
         if (!$pluginsLoaded) {
             $_PLUGINS->loadPluginGroup('user', 'cbsubs.');
             $_PLUGINS->loadPluginGroup('user/plug_cbpaidsubscriptions/plugin');
         }
         $_PLUGINS->trigger('onCPayAfterPaymentStatusUpdateEvent', array(&$user, &$paymentBasket, &$subscriptions, $unifiedStatus, $previousUnifiedStatus, $eventType, &$notification));
     }
 }
	/**
	 * Returns substitution strings
	 *
	 * @see cbpaidSomething::substitutionStringsForItemDetailed()
	 *
	 * @param  boolean  $html           HTML or TEXT return
	 * @param  string   $reason         'N' new subscription, 'R' renewal, 'U'=update )
	 * @param  boolean  $autorecurring  TRUE: is autorecurring, no real expiration date, FALSE: is not autorecurring
	 * @return array
	 */
	public function substitutionStringsForItemDetailed( $html, $reason, $autorecurring ) {
		global $_CB_framework;

		$params						=	cbpaidApp::settingsParams();
		$user						=	CBuser::getUserDataInstance( $this->user_id );

		$prefixText					=	'';
		if ( $reason == 'R' ) {
			$prefixText				=	CBPTXT::T("Renew");
		} elseif ( ( $reason == 'U' ) && $this->replaces_subscription ) {
			$prefixText				=	CBPTXT::T("Upgrade");
		}

		$validityText				=	$this->getFormattedValidityIfRenewed( $reason );
		$showtime					=	( $params->get( 'showtime', '1' ) == '1' );
		if ( $this->expiry_date && ( $this->expiry_date != '0000-00-00 00:00:00' ) ) {
			$expiryText				=	cbFormatDate( $this->expiry_date, 1, $showtime );
		} elseif ( $this->isLifetimeValidity() ) {
			$expiryText				=	CBPTXT::T( $params->get( 'regtextLifetime', 'Lifetime Subscription' ) );
		} else {
			$expiryText				=	'';
		}
		$validityIfNotAutoRec		=	'';
		$expiryTextIfNotAutoRec		=	'';
		if ( ! $autorecurring ) {
			$validityIfNotAutoRec	=	': ' . $validityText;
			if ( $expiryText ) {
				$expiryTextIfNotAutoRec	=	' ' . sprintf( CBPTXT::T("expiring on %s"), $expiryText );
			} else {
				$expiryTextIfNotAutoRec	=	'';
			}
		}

		$extraStrings				=	array(
			'ITEM_NAME'				=>	$this->getPlan()->getPersonalized( 'name', $this->user_id, false ),		//	CBPTXT::T( $this->getText( 'name' ) ),
			'ITEM_ALIAS'			=>	CBPTXT::T( $this->getText( 'alias' ) ),
			'ITEM_DESCRIPTION'		=>	$this->getPlan()->getPersonalized( 'description', $this->user_id, false ),		//	strip_tags( CBPTXT::T( $this->getText( 'description' ) ) ),
			'SITENAME'				=>	$_CB_framework->getCfg( 'sitename' ),
			'SITEURL'				=>	$_CB_framework->getCfg( 'live_site' ),
			'PLANS_TITLE'			=>	strip_tags( CBPTXT::T( $params->get( 'regTitle' ) ) ),
			'EMAILADDRESS'			=>	$user->email,
			'PREFIX_TEXT'			=>	$prefixText,
			'VALIDITY'				=>	$validityText,
			'SUBSCRIPTION_VALIDITY_PERIOD_IF_RENEWED'	=>	$validityText,	// alias of VALIDITY
			'SUBSCRIPTION_EXPIRY_DATE_IF_RENEWED'		=>	$this->getFormattedExpiryDateIfRenewed( $reason ),
			'SUBSCRIPTION_VALIDITY_PERIOD_REMAINING'	=>	$this->getFormattedValidityRemaining(),
			'VALIDITY_IF_NOT_AUTORECURRING'				=>	$validityIfNotAutoRec,
			'EXPIRY'				=>	$expiryText,
			'EXPIRING_IF_NOT_AUTORECURRING'	=>	$expiryTextIfNotAutoRec,
			'SUBSCRIPTION_EXPIRY_DATE'					=>	$expiryText,		// alias of EXPIRY
			'SUBSCRIPTION_SIGNUP_DATE'					=>	( $this->subscription_date ? cbFormatDate( $this->subscription_date, 1, $showtime ) : '' ),
			'SUBSCRIPTION_LAST_RENEWAL_DATE'			=>	( $this->last_renewed_date ? cbFormatDate( $this->last_renewed_date, 1, $showtime ) : '' ),
			'SUBSCRIPTION_RENEWAL_PRICE'				=>	$this->displayPeriodPrice( 'R', $html ),
		);
		return $extraStrings;
	}
	/**
	 * WARNING: UNCHECKED ACCESS! On purpose unchecked access for M2M operations
	 * Generates the HTML to display for a specific component-like page for the tab. WARNING: unchecked access !
	 * @param  TabTable|null  $tab       the tab database entry
	 * @param  UserTable      $user      the user being displayed
	 * @param  int            $ui        1 for front-end, 2 for back-end
	 * @param  array          $postdata  _POST data for saving edited tab content as generated with getEditTab
	 * @return mixed                     either string HTML for tab content, or false if ErrorMSG generated
	 */
	public function getTabComponent( /** @noinspection PhpUnusedParameterInspection */ $tab, $user, $ui, $postdata ) {
		global $_CB_database, $_CB_framework, $_POST;

		$return								=	'';
		$paid								=	false;

		$oldignoreuserabort = ignore_user_abort(true);

		$allowHumanHtmlOutput				=	true;			// this will be reverted in case of M2M server-to-server notifications

		$act								=	$this->base->_getReqParam( 'act' );
		$actPosted							=	isset($_POST[$this->base->_getPagingParamName('act')]);

		if ( $act === null ) {
			$act							=	$this->base->input( 'act', null, GetterInterface::COMMAND );
			$actPosted						=	$this->base->input( 'post/act', null, GetterInterface::COMMAND ) !== null;
		}

		$post_user_id						=	(int) cbGetParam( $_GET, 'user', 0 );

		if ( $actPosted && ( $post_user_id > 0 ) ) {
			$access							=	false;
			$myId							=	$_CB_framework->myId();
			if ( is_object( $user ) ) {
				if ( $myId == 0 ) {
					if ( in_array( $act, array( 'saveeditinvoiceaddress', 'saveeditbasketintegration', 'showbskt' ) ) ) {
						$access				=	true;
					} else {
						$paidsubsManager	=&	cbpaidSubscriptionsMgr::getInstance();
						if ( ! $paidsubsManager->checkExpireMe( __FUNCTION__, $user->id, false ) ) {
							// expired subscriptions: we will allow limited access to:
							if ( in_array( $act, array( 'upgrade', 'pay', 'reactivate', 'resubscribe', 'display_subscriptions' ) ) ) {
								$access		=	true;
							}
						}
					}
				} else {
					if ( ( $ui == 1 && ( $user->id == $myId ) )
						||	 ( cbpaidApp::authoriseAction( 'cbsubs.usersubscriptionmanage' ) ) ) {
						$access				=	true;
					}
				}
			} else {
				$return						=	CBPTXT::T("User does not exist") . '.';
			}
			if ( ! $access ) {
				$return						.=	'<br />' . CBPTXT::T("Not authorized action") . '.';
				return $return;
			}

			cbSpoofCheck( 'plugin' );		// anti-spoofing check


			// renew or upgrade subscription payment form:
			$params							=	$this->params;
			$now							=	$_CB_framework->now();
			$subscriptionsGUI				=	new cbpaidControllerUI();
			$subscriptionIds				=	$subscriptionsGUI->getEditPostedBoxes( 'id' );

			if ( $subscriptionIds == array( 0 ) ) {
				$subscriptionIds			=	array();
			}
			if ( $post_user_id && ( $user->id == $post_user_id ) ) {
				outputCbTemplate();
				$this->base->outputRegTemplate();
				outputCbJs();
				switch ( $act ) {
					case 'upgrade':		// upgrade an existing subscription
						// display basket and payment buttons or redirect for payment depending if multiple payment choices or intro text present:
						$chosenPlans		=	$subscriptionsGUI->getAndCheckChosenUpgradePlans( $postdata, $user, $now );
						if ( ( ! is_array( $chosenPlans ) ) || ( count( $chosenPlans ) == 0 ) ) {
							$subTxt			=	CBPTXT::T( $params->get( 'subscription_name', 'subscription' ) );
							$return			.=	( is_string( $chosenPlans ) ? $chosenPlans . '<br />' : '' )
								.	sprintf( CBPTXT::Th("Please press back button and select the %s plan to which you would like to upgrade."), $subTxt );
							break;
						}
						$introText			=	CBPTXT::Th( $params->get( 'intro_text_upgrade', null ) );
						//TBD: check if already exists (reload protection):
						$paymentBasket		=	cbpaidControllerOrder::createSubscriptionsAndPayment( $user, $chosenPlans, $postdata, $subscriptionIds, null, 'R', CBPTXT::T("Upgrade"), 'U' );
						if ( is_object( $paymentBasket ) ) {
							$return			=	cbpaidControllerOrder::showBasketForPayment( $user, $paymentBasket, $introText );
						} else {
							$return			=	$paymentBasket;		// show messages as nothing to pay.
						}
						break;
					case 'pay':			// pay for an unpaid subscription
						// display basket and payment buttons or redirect for payment depending if multiple payment choices or intro text present:
						$plan				=	$this->base->_getReqParam( 'plan' );
						if ( ( ! $plan ) || ( ! isset( $subscriptionIds[$plan] ) ) || ( ! $subscriptionIds[$plan] ) ) {
							$subTxt			=	CBPTXT::T( $params->get( 'subscription_name', 'subscription' ) );
							$return			.=	sprintf( CBPTXT::Th("Please press back button and select a %s plan."), $subTxt );
							break;
						}
						$plansMgr			=&	cbpaidPlansMgr::getInstance();
						$chosenPlans		=	array();
						$chosenPlans[(int) $plan]		=	$plansMgr->loadPlan( (int) $plan );
						$introText			=	CBPTXT::Th( $params->get( 'intro_text', null ) );
						$paymentStatus		=	null;
						$return				=	cbpaidControllerOrder::showPaymentForm( $user, $chosenPlans, $introText, $subscriptionIds, $paymentStatus );
						break;
					case 'renew':		// renew a still valid subscription
					case 'reactivate':	// reactivate an expired subscription
					case 'resubscribe':	// resubscribe a cancelled subscription
						// display basket and payment buttons or redirect for payment depending if multiple payment choices or intro text present:
						$plan				=	$this->base->_getReqParam( 'plan' );
						if ( ( ! $plan ) || ( ! isset( $subscriptionIds[$plan] ) ) || ( ! $subscriptionIds[$plan] ) ) {
							$subTxt			=	CBPTXT::T( $params->get( 'subscription_name', 'subscription' ) );
							$return			.=	sprintf( CBPTXT::Th("Please press back button and select a %s plan."), $subTxt );
							break;
						}
						$plansMgr			=&	cbpaidPlansMgr::getInstance();
						$chosenPlans		=	array();
						$chosenPlans[(int) $plan]		=	$plansMgr->loadPlan( (int) $plan );

						$paidSomethingMgr	=&	cbpaidSomethingMgr::getInstance();
						$subscription		=	$paidSomethingMgr->loadSomething( $subscriptionIds[$plan][0], $subscriptionIds[$plan][1] );
						global $_PLUGINS;
						$_PLUGINS->loadPluginGroup( 'user', 'cbsubs.' );
						$_PLUGINS->loadPluginGroup('user/plug_cbpaidsubscriptions/plugin');
						$_PLUGINS->trigger( 'onCPayAfterPlanRenewalSelected', array( &$chosenPlans[(int) $plan], &$subscription, $act ) );
						if ( $_PLUGINS->is_errors() ) {
							$return			.=	$_PLUGINS->getErrorMSG();
							break;
						}

						$introText			=	CBPTXT::Th( $params->get( 'intro_text_renew', null ) );
						//TBD: check if already exists (reload protection):
						$paymentBasket		=	cbpaidControllerOrder::createSubscriptionsAndPayment( $user, $chosenPlans, $postdata, $subscriptionIds, null, null, CBPTXT::T("Renew"), 'R' );
						if ( is_object( $paymentBasket ) ) {
							$return			=	cbpaidControllerOrder::showBasketForPayment( $user, $paymentBasket, $introText );
						} else {
							$return			=	$paymentBasket;		// show messages as nothing to pay.
						}
						break;
					case 'unsubscribe':	// request to unsubscribe an active subscription
						// display unsubscribe confirmation form:
						$plan				=	$this->base->_getReqParam( 'plan' );
						if ( ( ! $plan ) || ( ! isset( $subscriptionIds[$plan] ) ) || ( ! $subscriptionIds[$plan] ) ) {
							$subTxt			=	CBPTXT::T( $params->get( 'subscription_name', 'subscription' ) );
							$return			.=	sprintf( CBPTXT::Th("Please press back button and select a %s plan."), $subTxt );
							break;
						}
						$introText			=	CBPTXT::Th( $params->get( 'unsubscribe_intro_text' , null ) );
						$return				=	$subscriptionsGUI->showUnsubscribeForm( $user, $introText, (int) $plan, (int) $subscriptionIds[$plan][1] );

						break;
					case 'confirm_unsubscribe':	// confirm previous request to unsubscribe an active subscription
						// unsubscribe confirmed:
						$plan				=	$this->base->_getReqParam( 'plan' );
						if ( ( ! $plan ) || ( ! isset( $subscriptionIds[$plan] ) ) || ( ! $subscriptionIds[$plan] ) ) {
							$subTxt			=	CBPTXT::T( $params->get( 'subscription_name', 'subscription' ) );
							$return			.=	sprintf( CBPTXT::Th("Please press back button and select a %s plan."), $subTxt );
							break;
						}
						if ( ( $plan ) && ( count( $subscriptionIds ) == 1 ) ) {
							$unsubscribeConfText =	CBPTXT::Th( $params->get( 'unsubscribe_confirmation_text', null ) );
							$return			=	cbpaidControllerOrder::doUnsubscribeConfirm( $user, $unsubscribeConfText, (int) $plan, (int) $subscriptionIds[$plan][1] );
						}
						break;
					case 'display_subscriptions':
						// unsubscribe cancelled: display subscriptions:
						$return				=	$this->base->displayUserTab( $user );
						break;
					case 'showinvoice':
						// shows a particular user invoice:
						if ( $params->get( 'show_invoices', 1 ) ) {
							$invoiceNo		=	$this->base->_getReqParam( 'invoice' );
							$return			=	$this->showInvoice( $invoiceNo, $user );
						}
						break;
					case 'saveeditinvoiceaddress':
					case 'editinvoiceaddress':		// this is the case of reload of invoicing address
						$invoicingAddressQuery		=	$params->get( 'invoicing_address_query' );
						if ( $invoicingAddressQuery > 0 ) {
							$basketId				=	$this->base->_getReqParam( 'basket', 0 );
							$hashToCheck			=	$this->base->_getReqParam( 'bck' );
							$paymentBasket			=	new cbpaidPaymentBasket( $_CB_database );
							if ( $basketId && $paymentBasket->load( (int) $basketId ) && ( $paymentBasket->payment_status == 'NotInitiated' ) && ( $hashToCheck == $paymentBasket->checkHashUser( $hashToCheck ) ) ) {
								if ( ( $act == 'saveeditinvoiceaddress' ) && $this->base->input( 'actbutton', null, GetterInterface::COMMAND ) ) {				// IE7-8 will return text instead of value and IE6 will return button all the time http://www.dev-archive.net/articles/forms/multiple-submit-buttons.html
									$return			=	$paymentBasket->saveInvoicingAddressForm( $user );
									if ( $return === null ) {
										$paymentBasket->storeInvoicingDefaultAddress();
										$introText	=	CBPTXT::Th( $params->get( 'intro_text', null ) );
										$return		.=	cbpaidControllerOrder::showBasketForPayment( $user, $paymentBasket, $introText );
									}
								} else {
									// invoice has reloaded itself (e.g. for country change):
									$return			=	$paymentBasket->renderInvoicingAddressForm( $user );
								}
							} else {
								$this->base->_setErrorMSG( CBPTXT::T("No unpaid payment basket found.") );
							}
						} else {
							$this->base->_setErrorMSG( CBPTXT::T("Not authorized action") );
						}

						break;
					case 'saverecordpayment':
					case 'editrecordpayment':		// this is the case of reload of the form
						$basketId				=	$this->base->_getReqParam( 'basket', 0 );
						$hashToCheck			=	$this->base->_getReqParam( 'bck' );
						$paymentBasket			=	new cbpaidPaymentBasket( $_CB_database );
						if ( $basketId && $paymentBasket->load( (int) $basketId ) && ( $paymentBasket->payment_status != 'Completed' ) && ( $hashToCheck == $paymentBasket->checkHashUser( $hashToCheck ) ) ) {
							if ( $paymentBasket->authoriseAction( 'cbsubs.recordpayments' ) ) {
								if ( ( $act == 'saverecordpayment' ) && $this->base->input( 'actbutton', null, GetterInterface::COMMAND ) ) {				// IE7-8 will return text instead of value and IE6 will return button all the time http://www.dev-archive.net/articles/forms/multiple-submit-buttons.html
									$return			=	cbpaidRecordBasketPayment::saveRecordPayment( $paymentBasket->id );
									if ( $return === null ) {
										$return		.=	CBPTXT::T("Payment recorded.")
											.	' <a href="' . $_CB_framework->userProfileUrl( $paymentBasket->user_id, true ) . '">'
											.	CBPTXT::Th("View user profile")
											.	'</a>';
									}
								} else {
									// invoice has reloaded itself (e.g. for country change):
									$return			=	cbpaidRecordBasketPayment::displayRecordPaymentForm( $paymentBasket->id );
								}
							} else {
								$this->base->_setErrorMSG( CBPTXT::T("Not authorized action") );
							}
						} else {
							$this->base->_setErrorMSG( CBPTXT::T("No unpaid payment basket found.") );
						}

						break;

					default:
						cbNotAuth();
						return '';
						break;
				}
			}

		} elseif ( $this->base->_getReqParam( 'account' ) && ( ( (int) cbGetParam( $_GET, 'user', 0 ) ) > 0 ) ) {

			$account					=	$this->base->_getReqParam( 'account' );
			$post_user_id				=	(int) cbGetParam( $_GET, 'user', 0 );
			$user						=	CBuser::getUserDataInstance( (int) $post_user_id );
			if ( $user->id ) {
				if ( isset( $_SESSION['cbsubs']['expireduser'] ) && ( $_SESSION['cbsubs']['expireduser'] == $user->id ) ) {
					// expired subscriptions of membership: show possibilities:
					$subscriptionsGUI		=	new cbpaidControllerUI();

					outputCbTemplate();
					$this->base->outputRegTemplate();
					outputCbJs();

					switch ( $account ) {
						case 'expired':
							$paidsubsManager		=&	cbpaidSubscriptionsMgr::getInstance();
							if ( ! $paidsubsManager->checkExpireMe( __FUNCTION__, $user->id, false ) ) {
								// no valid membership:
								$return				=	$subscriptionsGUI->getShowSubscriptionUpgrades( $user, true );
							}

							break;
						default:
							break;
					}
				} else {
					$return					=	CBPTXT::Th("Browser cookies must be enabled.");
				}
			}

		} elseif ( in_array( $act, array( 'setbsktpmtmeth', 'setbsktcurrency' ) ) ) {

			cbSpoofCheck( 'plugin' );		// anti-spoofing check
			$params							=	$this->params;
			outputCbTemplate();
			$this->base->outputRegTemplate();
			outputCbJs();

			$basketId				=	$this->base->_getReqParam( 'bskt', 0 );
			$hashToCheck			=	$this->base->_getReqParam( 'bck' );

			$paymentBasket			=	new cbpaidPaymentBasket( $_CB_database );
			if ( $basketId && $paymentBasket->load( (int) $basketId ) && ( $paymentBasket->payment_status == 'NotInitiated' ) && ( $hashToCheck == $paymentBasket->checkHashUser( $hashToCheck ) ) ) {

				switch ( $act ) {
					case 'setbsktpmtmeth':
						if ( $params->get( 'payment_method_selection_type' ) == 'radios' ) {
							$chosenPaymentMethod	=	cbGetParam( $_POST, 'payment_method' );
							$introText				=	CBPTXT::Th( $params->get( 'intro_text', null ) );
							$return					=	$paymentBasket->saveBasketPaymentMethodForm( $user, $introText, $chosenPaymentMethod );
							if ( $return === null ) {
								$return				.=	cbpaidControllerOrder::showBasketForPayment( $user, $paymentBasket, $introText );
							}
						} else {
							$this->base->_setErrorMSG( CBPTXT::T("Not authorized action") );
						}
						break;

					case 'setbsktcurrency':
						if ( $params->get( 'allow_select_currency', '0' ) ) {
							$newCurrency			=	cbGetParam( $_POST, 'currency' );
							if ( $newCurrency ) {
								if ( in_array( $newCurrency, cbpaidControllerPaychoices::getInstance()->getAllCurrencies() ) ) {
									$paymentBasket->changeCurrency( $newCurrency );
								} else {
									$this->base->_setErrorMSG( CBPTXT::T("This currency is not allowed") );
								}
								$introText			=	CBPTXT::Th( $params->get( 'intro_text', null ) );
								$return				.=	cbpaidControllerOrder::showBasketForPayment( $user, $paymentBasket, $introText );
							} else {
								$this->base->_setErrorMSG( CBPTXT::T("Not authorized action") );
							}
						} else {
							$this->base->_setErrorMSG( CBPTXT::T("Changes of currency of orders are not authorized") );
						}
						break;

					default:
						cbNotAuth();
						return '';
						break;
				}

			} else {
				$this->base->_setErrorMSG( CBPTXT::T("No unpaid payment basket found.") );
			}

		} elseif ( $act == 'cbsubsclass' ) {

			$pluginName						=	$this->base->_getReqParam( 'class' );
			if ( preg_match( '/^[a-z]+$/', $pluginName ) ) {
				$element					=	'cbsubs.' . $pluginName;
				global $_PLUGINS;
				$_PLUGINS->loadPluginGroup('user/plug_cbpaidsubscriptions/plugin', $element );
				$loadedPlugins				=&	$_PLUGINS->getLoadedPluginGroup( 'user/plug_cbpaidsubscriptions/plugin' );
				$params						=	$this->params;
				foreach ($loadedPlugins as $p ) {
					if ( $p->element == $element ) {
						$pluginId			=	$p->id;
						$args				=	array( &$user, &$params, &$postdata );
						/** @noinspection PhpUndefinedCallbackInspection */
						$return				=	$_PLUGINS->call( $pluginId, 'executeTask', 'getcbsubs' . $pluginName . 'Tab', $args, null );
						break;
					}
				}
			}

		} elseif ( $act && ( ! in_array( $act, array( 'showbskt', 'setbsktpmtmeth' ) ) ) && ( ( (int) cbGetParam( $_GET, 'user', 0 ) ) > 0 ) ) {

			if ( ! is_object( $user ) ) {
				return CBPTXT::T("User does not exist.");
			}

			$params								=	$this->params;

			$post_user_id						=	(int) cbGetParam( $_GET, 'user', 0 );
			if ( $post_user_id && ( ( $user->id == $post_user_id ) || ( cbpaidApp::authoriseAction( 'cbsubs.usersubscriptionmanage' ) ) ) ) {

				outputCbTemplate();
				$this->base->outputRegTemplate();
				outputCbJs();

				switch ( $act ) {
					case 'showinvoice':
						if ( $params->get( 'show_invoices', 1 ) ) {
							$invoiceNo			=	$this->base->_getReqParam( 'invoice', 0 );
							// This also checks for cbpaidApp::authoriseAction on cbsubs.sales or cbsubs.financial access permissions:
							$return				=	$this->showInvoice( $invoiceNo, $user );
						} else {
							$this->base->_setErrorMSG( CBPTXT::T("Not authorized action") );
						}
						break;
					case 'showinvoiceslist':
						$showInvoices			=	$params->get( 'show_invoices', 1 );
						$invoicesShowPeriod		=	$params->get( 'invoices_show_period', '0000-06-00 00:00:00' );
						$itsmyself				=	( $_CB_framework->myId() == $user->id );
						if ( $showInvoices && ( $itsmyself || ( cbpaidApp::authoriseAction( 'cbsubs.sales' ) || cbpaidApp::authoriseAction( 'cbsubs.financial' ) ) ) ) {
							$subscriptionsGUI	=	new cbpaidControllerUI();
							$invoices			=	$this->_getInvoices( $user, $invoicesShowPeriod, false );

							if ( $invoicesShowPeriod && ( $invoicesShowPeriod != '0000-00-00 00:00:00' ) ) {
								$cbpaidTimes	=&	cbpaidTimes::getInstance();
								$periodText		=	$cbpaidTimes->renderPeriod( $invoicesShowPeriod, 1, false );
							} else {
								$periodText		=	'';
							}
							$return				.=	$subscriptionsGUI->showInvoicesList( $invoices, $user, $itsmyself, $periodText );
						} else {
							$this->base->_setErrorMSG( CBPTXT::T("Not authorized action") );
						}
						break;
					case 'editinvoiceaddress':			// this is the case of the initial edit address link
						if ( $params->get( 'invoicing_address_query' ) > 0 ) {
							$basketId			=	$this->base->_getReqParam( 'basket', 0 );
							$hashToCheck		=	$this->base->_getReqParam( 'bck' );
							$paymentBasket		=	new cbpaidPaymentBasket( $_CB_database );
							if ( $basketId && $paymentBasket->load( (int) $basketId ) && ( $paymentBasket->payment_status == 'NotInitiated' ) && ( $hashToCheck == $paymentBasket->checkHashUser( $hashToCheck ) ) ) {
								$return			=	$paymentBasket->renderInvoicingAddressForm( $user );
							} else {
								$this->base->_setErrorMSG( CBPTXT::T("No unpaid payment basket found.") );
							}
						} else {
							$this->base->_setErrorMSG( CBPTXT::T("Not authorized action") );
						}
						break;
					case 'showrecordpayment':
						$paymentBasketId		=	$this->base->_getReqParam( 'recordpayment', 0 );
						if ( $paymentBasketId ) {
							$paymentBasket		=	new cbpaidPaymentBasket();
							if ( $paymentBasket->load( (int) $paymentBasketId ) && $paymentBasket->authoriseAction( 'cbsubs.recordpayments' ) ) {
								// Auto-loads class: and authorization is checked inside:
								$return				=	cbpaidRecordBasketPayment::displayRecordPaymentForm( $paymentBasketId );
							} else {
								$this->base->_setErrorMSG( CBPTXT::T("Not authorized action") );
							}
						} else {
							$this->base->_setErrorMSG( CBPTXT::T("Not authorized action") );
						}
						break;
					default:
						$this->base->_setErrorMSG( CBPTXT::T("Not authorized action") );
						break;
				}
			}

		} elseif ( $act == 'showbskt' && ( ( ( (int) cbGetParam( $_GET, 'user', 0 ) ) > 0 ) ) || ( $this->base->_getReqParam( 'bskt', 0 ) && $this->base->_getReqParam( 'bck' ) ) ) {

			$basketId			=	$this->base->_getReqParam( 'bskt', 0 );
			$hashToCheck		=	$this->base->_getReqParam( 'bck' );

			// Basket integrations saving/editing url:
			if ( in_array($act, array( 'saveeditbasketintegration', 'editbasketintegration' ) ) ) {		// edit is the case of edit or reload of integration form
				$integration			=	$this->base->_getReqParam( 'integration' );
				$paymentBasket			=	new cbpaidPaymentBasket( $_CB_database );
				if ( preg_match( '/^[a-z]+$/', $integration ) && $basketId && $paymentBasket->load( (int) $basketId ) && ( $paymentBasket->payment_status == 'NotInitiated' ) && ( $hashToCheck == $paymentBasket->checkHashUser( $hashToCheck ) ) ) {
					global $_PLUGINS;
					$element			=	'cbsubs.' . $integration;
					$_PLUGINS->loadPluginGroup('user/plug_cbpaidsubscriptions/plugin', $element );
					$results		=	$_PLUGINS->trigger( 'onCPayEditBasketIntegration', array( $integration, $act, &$paymentBasket ) );
					$return			=	null;
					foreach ( $results as $r ) {
						if ( $r ) {
							$return	.=	$r;
						}
					}
					if ( $act == 'editbasketintegration' ) {
						if ( $return !== null ) {
							return $return;
						}
					}
				} else {
					$this->base->_setErrorMSG( CBPTXT::T("No unpaid payment basket found.") );
				}
			}


			$post_user_id							=	(int) cbGetParam( $_GET, 'user', 0 );
			if ( $post_user_id && ! ( ( is_object( $user ) && ( $user->id == $post_user_id ) ) ) ) {
				return CBPTXT::T("User does not exist.");
			}

			outputCbTemplate();
			$this->base->outputRegTemplate();
			outputCbJs();
			$params				=	$this->params;

			$paymentBasket		=	new cbpaidPaymentBasket( $_CB_database );
			if ( $basketId && $paymentBasket->load( (int) $basketId ) && ( $paymentBasket->payment_status == 'NotInitiated' ) ) {
				if ( ! $post_user_id ) {
					$cbUser		=&	CBuser::getInstance( (int) $paymentBasket->user_id );
					$user		=&	$cbUser->getUserData();
					if ( ( ! is_object( $user ) ) || ! $user->id ) {
						return CBPTXT::T("User does not exist.");
					}
				}
				if ( ( $hashToCheck && $hashToCheck == $paymentBasket->checkHashUser( $hashToCheck ) )
					|| ( ( ! $hashToCheck ) && $paymentBasket->user_id && ( $paymentBasket->user_id == $_CB_framework->myId() ) ) )
				{
					$introText	=	CBPTXT::Th( $params->get( 'intro_text', null ) );
					$return		.=	cbpaidControllerOrder::showBasketForPayment( $user, $paymentBasket, $introText );
				} else {
					$this->base->_setErrorMSG( CBPTXT::T("Not authorized action") );
				}
			} else {
				$this->base->_setErrorMSG( CBPTXT::T("No unpaid payment basket found.") );
			}

			//	} elseif ( isset($_REQUEST['result']) && isset( $_REQUEST['user'] ) && ( $_REQUEST['user'] > 0 ) ) {
		} elseif ( isset($_REQUEST['result']) && ( $this->base->_getReqParam('method') || $this->base->_getReqParam('gacctno') ) ) {

			// don't check license here so initiated payments can complete !

			$params				=	$this->params;

			$method				=	$this->base->_getReqParam('method');

			if ( ( $method == 'freetrial' ) || ( $method == 'cancelpay' ) ) {
				cbpaidApp::import( 'processors.freetrial.freetrial' );
				cbpaidApp::import( 'processors.cancelpay.cancelpay' );
				$className		=	'cbpaidGatewayAccount' . $method;
				$payAccount		=	new $className( $_CB_database );
			} else {
				$gateAccount	=	$this->base->_getReqParam('gacctno');

				$payAccount		=	cbpaidControllerPaychoices::getInstance()->getPayAccount( $gateAccount );
				if ( ! $payAccount ) {
					return '';
				}
			}
			$payClass			=	$payAccount->getPayMean();
			$paymentBasket		=	new cbpaidPaymentBasket($_CB_database);

			if ( $payClass && ( ( $this->base->_getReqParam('method') == $payClass->getPayName() ) || ( $this->base->_getReqParam('method') == null ) ) && $payClass->hashPdtBackCheck( $this->base->_getReqParam('pdtback') ) ) {
				// output for resultNotification: $return and $allowHumanHtmlOutput
				$return			=	$payClass->resultNotification( $paymentBasket, $postdata, $allowHumanHtmlOutput );
			}

			if ( ! $paymentBasket->id ) {
				$this->base->_setErrorMSG(CBPTXT::T("No suitable basket found."));
			} else {
				$user			=&	CBuser::getUserDataInstance( (int) $paymentBasket->user_id );

				if ( $paymentBasket->payment_status == 'RegistrationCancelled' ) {
					// registration cancelled: delete payment basket and delete user after checking that he is not yet active:
					if ( $paymentBasket->load( (int) $paymentBasket->id ) ) {
						if ( $payClass->hashPdtBackCheck( $this->base->_getReqParam('pdtback') ) && ( ( $paymentBasket->payment_status == 'NotInitiated' ) || ( ( $paymentBasket->payment_status === 'Pending' ) && ( $paymentBasket->payment_method === 'offline' ) ) ) ) {

							$notification						=	new cbpaidPaymentNotification();
							$notification->initNotification( $payClass, 0, 'P', $paymentBasket->payment_status, $paymentBasket->payment_type, null, $_CB_framework->now(), $paymentBasket->charset );

							$payClass->updatePaymentStatus( $paymentBasket, 'web_accept', 'RegistrationCancelled', $notification, 0, 0, 0, true );

							// This is a notification or a return to site after payment, we want to log any error happening in third-party stuff in case:
							cbpaidErrorHandler::keepTurnedOn();
						}
					}
				}
				if ( $allowHumanHtmlOutput ) {
					// If frontend, we display result, otherwise, If Server-to-server notification: do not display any additional text here !
					switch ( $paymentBasket->payment_status ) {
						case 'Completed':
							// PayPal recommends including the following information with the confirmation:
							// - Item name
							// - Amount paid
							// - Payer email
							// - Shipping address
							$newMsg = sprintf( CBPTXT::Th("Thank you for your payment of %s for the %s %s."), $paymentBasket->renderPrice(),
								$paymentBasket->item_name,
								htmlspecialchars( $payClass->getTxtUsingAccount( $paymentBasket ) ) )		// ' using your paypal account ' . $paymentBasket->payer_email
								. ' ' . $payClass->getTxtNextStep( $paymentBasket );
							// . "Your transaction has been completed, and a receipt for your purchase has been emailed to you by PayPal. "
							// . "You may log into your account at www.paypal.com to view details of this transaction.</p>\n";
							if ( $params->get( 'show_invoices' ) ) {
								$itsmyself			=	( $_CB_framework->myId() == $user->id );
								$subscriptionsGUI	=	new cbpaidControllerUI();
								$newMsg				.=	'<p id="cbregviewinvoicelink">'
									.	$subscriptionsGUI->getInvoiceShowAhtml( $paymentBasket, $user, $itsmyself, CBPTXT::Th("View printable invoice") )
									.	'</p>'
								;
							}
							$paid = true;
							break;
						case 'Pending':
							$newMsg = sprintf( CBPTXT::Th("Thank you for initiating the payment of %s for the %s %s."), $paymentBasket->renderPrice(),
								$paymentBasket->item_name,
								htmlspecialchars( $payClass->getTxtUsingAccount( $paymentBasket ) ) )		// ' using your paypal account ' . $paymentBasket->payer_email
								. ' ' . $payClass->getTxtNextStep( $paymentBasket );
							// . "Your payment is currently being processed. "
							// . "A receipt for your purchase will be emailed to you by PayPal once processing is complete. "
							// . "You may log into your account at www.paypal.com to view status details of this transaction.</p>\n";
							break;
						case 'RegistrationCancelled':
							$newMsg		=	$payClass->getTxtNextStep( $paymentBasket );
							break;
						case 'FreeTrial':
							$newMsg = CBPTXT::Th("Thank you for subscribing to") . ' ' . $paymentBasket->item_name . '.'
								. ' ' . $payClass->getTxtNextStep( $paymentBasket );
							break;
						case null:
							$newMsg	= CBPTXT::T("Payment basket does not exist.");
							break;
						case 'NotInitiated':
							$newMsg	=	'';
							break;
						case 'RedisplayOriginalBasket':
							if ( $paymentBasket->load( (int) $paymentBasket->id ) && ( $paymentBasket->payment_status == 'NotInitiated' ) ) {
								$introText		=	CBPTXT::Th( $params->get( 'intro_text', null ) );
								$return			.=	cbpaidControllerOrder::showBasketForPayment( $user, $paymentBasket, $introText );
							}
							$newMsg				=	'';
							break;
						case 'Processed':
						case 'Denied':
						case 'Reversed':
						case 'Refunded':
						case 'Partially-Refunded':
						default:
							$newMsg = $payClass->getTxtNextStep( $paymentBasket );
							// "<p>Your transaction is not cleared and has currently following status: <strong>" . $paymentBasket->payment_status . ".</strong></p>"
							// . "<p>You may log into your account at www.paypal.com to view status details of this transaction.</p>";
							break;
					}

					if ( in_array( $paymentBasket->payment_status, array( 'Completed', 'Pending' ) ) ) {
						$subscriptions = $paymentBasket->getSubscriptions();
						$texts		=	array();			// avoid repeating several times identical texts:
						if ( is_array( $subscriptions ) ) {
							foreach ( $subscriptions as $sub ) {
								/** @var $sub cbpaidSomething */
								$thankYouParam		=	( $paymentBasket->payment_status == 'Completed') ? 'thankyoutextcompleted' : 'thankyoutextpending';
								$thankYouText		=	$sub->getPersonalized( $thankYouParam, true );
								if ( $thankYouText && ! in_array( $thankYouText, $texts ) ) {
									$texts[]		=	$thankYouText;
									if ( strpos( $thankYouText, '<' ) === false ) {
										$msgTag		=	'p';
									} else {
										$msgTag		=	'div';
									}
									$newMsg			.=	'<' . $msgTag . ' class="cbregThanks" id="cbregThanks' . $sub->plan_id . '">' . $thankYouText . '</' . $msgTag . ">\n";
								}
							}
						}
					}
					if ( $newMsg ) {
						$return .= '<div>' . $newMsg . '</div>';
					}

					if ( $paid && ( $_CB_framework->myId() < 1 ) && ( cbGetParam( $_REQUEST, 'user', 0 ) == $paymentBasket->user_id ) ) {
						$_CB_database->setQuery( "SELECT * FROM #__comprofiler c, #__users u WHERE c.id=u.id AND c.id=".(int) $paymentBasket->user_id );
						if ( $_CB_database->loadObject( $user ) && ( $user->lastvisitDate == '0000-00-00 00:00:00' ) ) {
							$return = '<p>' . implode( '', getActivationMessage( $user, 'UserRegistration' ) ) . '</p>' . $return;
						}
					}
				}
			}

		} else {
			cbNotAuth();
			return ' ' . CBPTXT::T("No result.");
		}

		if ( $allowHumanHtmlOutput ) {
			$allErrorMsgs	=	$this->base->getErrorMSG( '</div><div class="error">' );
			if ( $allErrorMsgs ) {
				$errorMsg	=	'<div class="error">' . $allErrorMsgs . '</div>';
			} else {
				$errorMsg	=	null;
			}

			/** @var string $return */
			if ( ( $return == '' ) && ( $errorMsg ) ) {
				$this->base->outputRegTemplate();
				$return		=	$errorMsg . '<br /><br />' . $return;
				$return		.=	cbpaidControllerOrder::showBasketForPayment( $user, $paymentBasket, '' );
			} else {
				$return		=	$errorMsg . $return;
			}
		}

		if ( ! is_null( $oldignoreuserabort ) ) {
			ignore_user_abort($oldignoreuserabort);
		}

		return $return;
	}
 /**
  * CB messaging anti-spam protection for maximum messages per time-frame
  *
  * @param  int          $userId       User id
  * @param  boolean      $count        Should it increment the number of messages or just check ?
  * @param  boolean      $allowPublic  Should public messaging also be allowed ?
  * @return null|string
  */
 function cbSpamProtect($userId, $count, $allowPublic = false)
 {
     global $_CB_framework, $_CB_database, $ueConfig;
     $maxEmailsPerHr = isset($ueConfig['maxEmailsPerHr']) ? (int) $ueConfig['maxEmailsPerHr'] : 10;
     // mails per
     $maxInterval = 24 * 3600;
     // hours (expressed in seconds) limit
     $time = time();
     if (!$userId && $allowPublic) {
         $messageNumberSent = (int) $_CB_framework->getUserState('cb_message_number_sent', 0);
         $messageLastSent = $_CB_framework->getUserState('cb_message_last_sent', '0000-00-00 00:00:00');
         $canSendMessage = true;
     } else {
         $user = CBuser::getUserDataInstance((int) $userId);
         if ($user) {
             $messageNumberSent = (int) $user->message_number_sent;
             $messageLastSent = $user->message_last_sent;
             $canSendMessage = true;
         } else {
             $messageNumberSent = 0;
             $messageLastSent = '0000-00-00 00:00:00';
             $canSendMessage = false;
         }
     }
     if ($canSendMessage) {
         if ($messageLastSent != '0000-00-00 00:00:00') {
             list($y, $c, $d, $h, $m, $s) = sscanf($messageLastSent, "%4d-%2d-%2d\t%2d:%2d:%2d");
             $expiryTime = gmmktime($h, $m, $s, $c, $d, $y) + $maxInterval;
             if ($time < $expiryTime) {
                 if ($messageNumberSent >= $maxEmailsPerHr) {
                     return CBTxt::Th('UE_MAXEMAILSLIMIT', 'You exceeded the maximum limit of ||one email|%%NUMBERMAILSPERHOUR%% emails|| per hour| every %%NUMBERHOURS%% hours||. Please try again later.', array('%%NUMBERMAILSPERHOUR%%' => $maxEmailsPerHr, '%%NUMBERHOURS%%' => round($maxInterval / 3600)));
                 } else {
                     if ($count) {
                         if ($userId) {
                             $query = 'UPDATE ' . $_CB_database->NameQuote('#__comprofiler') . "\n SET " . $_CB_database->NameQuote('message_number_sent') . " = " . (int) ($messageNumberSent + 1) . "\n WHERE " . $_CB_database->NameQuote('id') . " = " . (int) $userId;
                             $_CB_database->setQuery($query);
                             $_CB_database->query();
                         } else {
                             $_CB_framework->setUserState('cb_message_number_sent', $messageNumberSent + 1);
                         }
                     }
                 }
             } else {
                 if ($count) {
                     if ($userId) {
                         $query = 'UPDATE ' . $_CB_database->NameQuote('#__comprofiler') . "\n SET " . $_CB_database->NameQuote('message_number_sent') . " = 1" . ', ' . $_CB_database->NameQuote('message_last_sent') . ' = ' . $_CB_database->Quote($_CB_framework->getUTCDate()) . "\n WHERE " . $_CB_database->NameQuote('id') . " = " . (int) $userId;
                         $_CB_database->setQuery($query);
                         $_CB_database->query();
                     } else {
                         $_CB_framework->setUserState('cb_message_number_sent', 1);
                         $_CB_framework->setUserState('cb_message_last_sent', $_CB_framework->getUTCDate());
                     }
                 }
             }
         } else {
             if ($count) {
                 if ($userId) {
                     $query = 'UPDATE ' . $_CB_database->NameQuote('#__comprofiler') . "\n SET " . $_CB_database->NameQuote('message_number_sent') . " = 1" . ', ' . $_CB_database->NameQuote('message_last_sent') . ' = ' . $_CB_database->Quote($_CB_framework->getUTCDate()) . "\n WHERE " . $_CB_database->NameQuote('id') . " = " . (int) $userId;
                     $_CB_database->setQuery($query);
                     $_CB_database->query();
                 } else {
                     $_CB_framework->setUserState('cb_message_number_sent', 1);
                     $_CB_framework->setUserState('cb_message_last_sent', $_CB_framework->getUTCDate());
                 }
             }
         }
         return null;
     } else {
         return 'Not Authorized';
     }
 }
Exemplo n.º 28
0
 /**
  * Generates the HTML to display the user profile tab
  *
  * @param  TabTable        $tab   The tab database entry
  * @param  UserTable       $user  The user being displayed
  * @param  int             $ui    1 for front-end, 2 for back-end
  * @return string|boolean         Either string HTML for tab content, or false if ErrorMSG generated
  */
 public function getDisplayTab($tab, $user, $ui)
 {
     global $_CB_framework;
     $model = cbforumsClass::getModel();
     if (!$model->file) {
         return CBTxt::T('No supported forum model found!');
     }
     outputCbJs(1);
     outputCbTemplate(1);
     $plugin = cbforumsClass::getPlugin();
     $viewer =& CBuser::getUserDataInstance($_CB_framework->myId());
     $message = null;
     cbforumsClass::getTemplate('tab');
     if ($user->get('id') == $_CB_framework->myId()) {
         $profileUrl = cbSef('index.php?option=com_comprofiler&tab=' . (int) $tab->tabid, false);
         if ($this->params->get('tab_favs_display', 1)) {
             $unfavorite = cbGetParam($_REQUEST, 'forums_unfav', null);
             if ($unfavorite) {
                 if (cbforumsModel::unFavorite($unfavorite, $user, $plugin)) {
                     cbRedirect($profileUrl, CBTxt::T('Favorite deleted successfully!'));
                 } else {
                     cbRedirect($profileUrl, CBTxt::T('Favorite failed to delete.'), 'error');
                 }
             }
         }
         if ($this->params->get('tab_subs_display', 1)) {
             $unsubscribePost = cbGetParam($_REQUEST, 'forums_unsub', null);
             if ($unsubscribePost) {
                 if (cbforumsModel::unSubscribe($unsubscribePost, $user, $plugin)) {
                     cbRedirect($profileUrl, CBTxt::T('Subscription deleted successfully!'));
                 } else {
                     cbRedirect($profileUrl, CBTxt::T('Subscription failed to delete.'), 'error');
                 }
             }
             $unsubscribeCat = cbGetParam($_REQUEST, 'forums_unsubcat', null);
             if ($unsubscribeCat) {
                 if (cbforumsModel::unSubscribeCategory($unsubscribeCat, $user, $plugin)) {
                     cbRedirect($profileUrl, CBTxt::T('Category subscription deleted successfully!'));
                 } else {
                     cbRedirect($profileUrl, CBTxt::T('Category subscription failed to delete.'), 'error');
                 }
             }
         }
     }
     $tab->params = $this->params;
     $class = $plugin->params->get('general_class', null);
     $return = '<div id="cbForums" class="cbForums' . ($class ? ' ' . htmlspecialchars($class) : null) . '">' . '<div id="cbForumsInner" class="cbForumsInner">' . HTML_cbforumsTab::showTab($viewer, $user, $tab, $plugin) . '</div>' . '</div>';
     return $return;
 }
Exemplo n.º 29
0
 /**
  * Send email from system to a user
  * Replaces optionally variables
  *
  * @param  int|UserTable  $toUserOrUserId    Receiver
  * @param  string         $subject           Subject
  * @param  string         $message           HTML message for PMS
  * @param  boolean|int    $replaceVariables  Should we replace variables ?
  * @param  int            $mode              false = plain text, true = HTML
  * @param  null|string    $cc                Email CC address
  * @param  null|string    $bcc               Email BCC address
  * @param  null|string    $attachment        Email attachment files
  * @param  array          $extraStrings      Extra replacement strings to use if $replaceVariables = true
  * @param  boolean        $footer            Add footer "Automated message sent from" ?
  * @param  null|string    $fromName          [optional] From name
  * @param  null|string    $fromEmail         [optional] From email address
  * @param  null|string    $replyToName       [optional] Reply-To name
  * @param  null|string    $replyToEmail      [optional] Reply-To email address
  * @return boolean                           Result
  */
 public function sendFromSystem($toUserOrUserId, $subject, $message, $replaceVariables = true, $mode = 0, $cc = null, $bcc = null, $attachment = null, $extraStrings = array(), $footer = true, $fromName = null, $fromEmail = null, $replyToName = null, $replyToEmail = null)
 {
     global $_CB_framework, $ueConfig;
     if (!$subject && !$message) {
         return true;
     }
     $rowFrom = new UserTable();
     $rowFrom->email = $fromEmail ? $fromEmail : $ueConfig['reg_email_from'];
     $rowFrom->name = $fromName ? $fromName : $this->defaultFromName();
     if (!$replyToEmail) {
         $replyToEmail = $ueConfig['reg_email_replyto'];
     }
     if (!$replyToName) {
         $replyToName = $this->defaultFromName();
     }
     if (!is_object($toUserOrUserId)) {
         $rowTo = CBuser::getUserDataInstance((int) $toUserOrUserId);
     } else {
         if (!$toUserOrUserId instanceof UserTable) {
             $rowTo = CBuser::getUserDataInstance((int) $toUserOrUserId->id);
         } else {
             $rowTo = $toUserOrUserId;
         }
     }
     if ($replaceVariables) {
         $subject = $this->_replaceVariables($subject, $rowTo, $mode, $extraStrings);
         $message = $this->_replaceVariables($message, $rowTo, $mode, $extraStrings);
     }
     if ($footer) {
         $toUserLanguage = CBuser::getInstance((int) $rowTo->id)->getUserData()->getUserLanguage();
         $savedLanguage = CBTxt::setLanguage($toUserLanguage);
         $message .= "\n\n" . $this->_replaceVariables(CBTxt::T('EMAIL_NOTE_AUTOMATIC_GENERATION', 'NOTE: This email was automatically generated from [sitename] ([siteurl]).'), $rowTo, $mode, $extraStrings);
         CBTxt::setLanguage($savedLanguage);
     }
     $subject = $_CB_framework->getCfg('sitename') . ' - ' . $subject;
     // Lets fix linebreaks encase the message was sent as a plain string:
     $message = str_replace(array('\\r\\n', '\\n'), array("\r\n", "\n"), $message);
     return $this->_sendEmailMSG($rowTo, $rowFrom, $replyToName, $replyToEmail, $subject, $message, false, $mode, $cc, $bcc, $attachment);
 }
 /**
  * If table key (id) is NULL : inserts a new row
  * otherwise updates existing row in the database table
  *
  * Can be overridden or overloaded by the child class
  *
  * @param  boolean  $updateNulls  TRUE: null object variables are also updated, FALSE: not.
  * @return boolean                TRUE if successful otherwise FALSE
  */
 public function store($updateNulls = false)
 {
     if (!cbpaidApp::authoriseAction('cbsubs.refunds')) {
         $this->setError(CBPTXT::T("Not authorized"));
         return false;
     }
     // 1) check:
     if (!in_array($this->payment_status, array('Completed', 'Pending', 'Partially-Refunded'))) {
         $this->setError(CBPTXT::T("This payment is not completed, pending or partially refunded."));
         return false;
     }
     if ($this->txn_id == '') {
         $this->txn_id = 'None';
         // needed for updatePayment to generate payment record.
     }
     $payment = new cbpaidPayment();
     if (!$payment->load((int) $this->id)) {
         $this->setError(CBPTXT::T("This payment does not exist."));
         return false;
     }
     $paymentBasket = new cbpaidPaymentBasket();
     if (!$paymentBasket->load($this->payment_basket_id)) {
         $this->setError(CBPTXT::T("This payment has no associated payment basket and cannot be refunded from here. Maybe from your PSP online terminal ?"));
         return false;
     }
     if (!$this->gateway_account) {
         $this->setError(CBPTXT::T("This payment has no gateway associated so can not be refunded."));
         return false;
     }
     $payAccount = cbpaidControllerPaychoices::getInstance()->getPayAccount($this->gateway_account);
     if (!$payAccount) {
         $this->setError(CBPTXT::T("This payment's payment basket's associated gateway account is not active, so can not be refunded from here."));
         return false;
     }
     $payClass = $payAccount->getPayMean();
     $returnText = null;
     $amount = sprintf('%.2f', (double) $this->refund_gross);
     if (is_callable(array($payClass, 'refundPayment'))) {
         $success = $payClass->refundPayment($paymentBasket, $payment, null, $this->refund_is_last, $amount, $this->refund_reason, $returnText);
     } else {
         $success = false;
     }
     $user = CBuser::getUserDataInstance($paymentBasket->user_id);
     $username = $user ? $user->username : '******';
     $replacements = array('[REFUNDAMOUNT]' => $payment->mc_currency . ' ' . $amount, '[PAYMENTID]' => $payment->id, '[PAYMENTAMOUNT]' => $payment->mc_currency . ' ' . $payment->mc_gross, '[BASKETID]' => $paymentBasket->id, '[ORDERID]' => $paymentBasket->sale_id, '[FULLNAME]' => $paymentBasket->first_name . ' ' . $paymentBasket->last_name, '[USERNAME]' => $username, '[USERID]' => $paymentBasket->user_id, '[PAYMENTMETHOD]' => $payClass->getPayName(), '[TXNID]' => $payment->txn_id, '[AUTHID]' => $payment->auth_id, '[ERRORREASON]' => $paymentBasket->reason_code);
     if ($success) {
         // Success Message ?
         // $returnText	=	CBPTXT::P("Refunded [REFUNDAMOUNT] for payment id [PAYMENTID] of [PAYMENTAMOUNT] for basket id [BASKETID], Order id [ORDERID] of [FULLNAME] (username [USERNAME] - user id [USERID]) using [PAYMENTMETHOD] with txn_id [TXNID] and auth_id [AUTHID].", $replacements );
     } else {
         $this->setError(CBPTXT::T($payClass->getErrorMSG()) . '. ' . CBPTXT::P("Refund request of [REFUNDAMOUNT] for payment id [PAYMENTID] of [PAYMENTAMOUNT] for basket id [BASKETID], Order id [ORDERID] of [FULLNAME] (username [USERNAME] - user id [USERID]) using [PAYMENTMETHOD] with txn_id [TXNID] and auth_id [AUTHID] failed for reason: [ERRORREASON].", $replacements));
         return false;
     }
     return true;
 }