/**
  * Draws the user profile tab "Subscriptions" (if enabled, user is the profile owner, and something to display.
  * 
  * @param  UserTable  $user
  * @param  boolean    $itsmyself
  * @param  string     $htmlSubscribed
  * @return string
  */
 public function drawUserSomethings($user, $itsmyself, $htmlSubscribed)
 {
     global $_CB_framework, $ueConfig;
     $this->htmlSubscribed = $htmlSubscribed;
     $subscriptions = $this->_model;
     if (count($subscriptions) == 1) {
         $subTxt = CBPTXT::T(cbpaidApp::settingsParams()->get('subscription_name', 'subscription'));
     } else {
         $subTxt = CBPTXT::T(cbpaidApp::settingsParams()->get('subscriptions_name', 'subscriptions'));
     }
     if ($itsmyself) {
         $userName = null;
     } else {
         $userName = getNameFormat($user->name, $user->username, $ueConfig['name_format']);
     }
     if ($_CB_framework->getUi() == 1) {
         if ($itsmyself) {
             $this->htmlTabTitle = sprintf(CBPTXT::Th("Your current %s"), $subTxt);
         } else {
             $this->htmlTabTitle = sprintf(CBPTXT::Th("%s's current %s"), $userName, $subTxt);
         }
     } else {
         if ($itsmyself) {
             $this->htmlTabTitle = sprintf(CBPTXT::Th("Your current and past %s"), $subTxt);
         } else {
             $this->htmlTabTitle = sprintf(CBPTXT::Th("%s's current and past %s"), $userName, $subTxt);
         }
     }
     return $this->display();
 }
	/**
	 * Returns text for button for upgrade, renewals, etc.
	 *
	 * @param  string  $type  'upgrade', 'pay', 'renew', 'reactivate', 'resubscribe', 'unsubscribe', 'delete', default is Apply
	 * @return string         translated button text (without htmlspecialchars, it will be applied on the returned text.
	 */
	public function buttonText( $type ) {
		switch ( $type ) {
			case 'upgrade':
				return CBPTXT::T("Buy");
			case 'pay':
				return CBPTXT::T("Buy Now");
			default:
				return parent::buttonText( $type );
		}
	}
 /**
  * Draws the plans upgrade proposals
  * 
  * @param  UserTable  $user
  * @param  int        $plansDisplayed
  * @param  string     $htmlUpgrades
  * @param  string     $htmlspecialcharedBaseUrl
  * @param  array      $hiddenFlds
  * @param  array      $buttonTexts
  * @param  string     $buttonName
  * @return string
  */
 public function drawUserUpgradePlans($user, $plansDisplayed, $htmlUpgrades, $htmlspecialcharedBaseUrl, $hiddenFlds, $buttonTexts, $buttonName)
 {
     $this->htmlUpgrades = $htmlUpgrades;
     $this->htmlspecialcharedBaseUrl = $htmlspecialcharedBaseUrl;
     $this->hiddenFlds = $hiddenFlds;
     $this->buttonName = $buttonName;
     $this->buttonText = implode(' / ', $buttonTexts);
     $subTxt = CBPTXT::T(cbpaidApp::settingsParams()->get('subscription_name', 'subscription'));
     if ($plansDisplayed == 1) {
         $this->htmlTitle = sprintf(CBPTXT::Th("Your current %s upgrade possibility:"), $subTxt);
     } else {
         $this->htmlTitle = sprintf(CBPTXT::Th("Your current %s upgrade possibilities:"), $subTxt);
     }
     return $this->display();
 }
Exemplo n.º 4
0
	/**
	 * Builds and sends e-mail
	 *
	 * @param UserTable  $user
	 * @param string     $mailFrom_email
	 * @param string     $mailFrom_name
	 * @param string     $mailTo
	 * @param string     $mailSubject
	 * @param string     $mailBody
	 * @param string     $mailHtml
	 * @param string     $mailCC
	 * @param string     $mailBCC
	 * @param string     $mailAttachments
	 * @param string[]   $extraStrings
	 * @return void
	 */
	protected function sendMail( $user, $mailFrom_email, $mailFrom_name, $mailTo, $mailSubject, $mailBody, $mailHtml, $mailCC, $mailBCC, $mailAttachments, $extraStrings ) {
		global $_CB_framework;

		cbimport( 'cb.tabs' );

		$cbUser					=	CBuser::getInstance( $user->id );

		if ( ! $cbUser ) {
			return;
		}

		$mailFrom_email			=	trim( $cbUser->replaceUserVars( $mailFrom_email, false, false, array(), false ) );
		$mailFrom_name			=	trim( $cbUser->replaceUserVars( $mailFrom_name, false, false, array(), false ) );
		$mailTo					=	trim( $cbUser->replaceUserVars( $mailTo, false, false, array(), false ) );
		$mailCC					=	trim( $cbUser->replaceUserVars( $mailCC, false, false, array(), false ) );
		$mailBCC				=	trim( $cbUser->replaceUserVars( $mailBCC, false, false, array(), false ) );
		$mailSubject			=	trim( $cbUser->replaceUserVars( CBPTXT::T( $mailSubject ), false, false, $extraStrings, false ) );
		$mailBody				=	trim( $cbUser->replaceUserVars( CBPTXT::T( $mailBody ), false, false, $extraStrings, false ) );
		$mailAttachments		=	trim( $mailAttachments );

		if ( $mailTo != '' ) {
			$mailTo				=	preg_split( '/ *, */', $mailTo );
		} else {
			return;
		}

		if ( $mailCC != '' ) {
			$mailCC				=	preg_split( '/ *, */', $mailCC );
		} else {
			$mailCC				=	null;
		}

		if ( $mailBCC != '' ) {
			$mailBCC			=	preg_split( '/ *, */', $mailBCC );
		} else {
			$mailBCC			=	null;
		}

		if ( $mailAttachments != '' ) {
			$mailAttachments	=	preg_split( '/ *, */', $mailAttachments );
		} else {
			$mailAttachments	=	null;
		}

		if ( $mailTo && ( $mailSubject || $mailBody ) ) {
			comprofilerMail( $mailFrom_email, $mailFrom_name, $mailTo, $_CB_framework->getCfg( 'sitename' ).' - '.$mailSubject, $mailBody, $mailHtml, $mailCC, $mailBCC, $mailAttachments );
		}
	}
 /**
  *	Check for whether dependancies exist for this object in the db schema
  *
  *	@param  int      $oid   Optional key index
  *	@return boolean         TRUE: OK to delete, FALSE: not OK to delete, error in $this->_error
  */
 public function canDelete($oid = null)
 {
     $k = $this->_tbl_key;
     if ($oid) {
         $this->{$k} = $oid;
     }
     $query = "SELECT COUNT(*)" . "\n FROM `#__cbsubs_subscriptions`" . "\n WHERE `plan_id` = " . (int) $this->{$k};
     $this->_db->setQuery($query);
     $obj = null;
     $count = $this->_db->loadResult($obj);
     if ($count > 0) {
         $this->setError(CBPTXT::T("Subscriptions exist for this plan"));
         return false;
     }
     return parent::canDelete($oid);
 }
Exemplo n.º 6
0
	/**
	 * Renders the currency symbol according to global settings
	 *
	 * @param  string|null  $currency
	 * @param  boolean      $html
	 * @return string
	 */
	public function renderCurrencySymbol( $currency, $html ) {
		$params						=	$this->params;
		if ( $currency === null ) {
			$currency				=	$params->get( 'currency_code', 'USD' );
		}
		$priceCurrencyFormat		=	$params->get('price_currency_format', '%2$s %1$s' );
		if ( $html ) {
			if ( strpos( $priceCurrencyFormat, '%3' ) !== false ) {
				$currencySymbols	=	array ( 'EUR' => '€', 'USD' => '$', 'GBP' => '£', 'JPY' => '¥', 'CHF' => 'Fr.', 'CAD' => 'C$', 'AUD' => '$', 'BRL' => 'R$', 'CNY' => '¥', 'DKK' => 'KR', 'ZAR' => 'R', 'SEK' => 'KR' );		//TBD: move to currency table
				$textHtmlSymbol		=	isset( $currencySymbols[$currency] ) ? $currencySymbols[$currency] : CBPTXT::Th( $currency );
			} else {
				$textHtmlSymbol		=	CBPTXT::Th( $currency );
			}
			$textHtmlSymbol			=	'<span class="cbregPcur">' . $textHtmlSymbol . '</span>';
		} else {
			$textHtmlSymbol			=	CBPTXT::T( $currency );
		}
		return $textHtmlSymbol;
	}
 /**
  * Renders a $variable for an $output
  *
  * @param  string   $variable
  * @param  string   $output
  * @param  boolean  $rounded
  * @return string|null
  */
 public function renderColumn($variable, $output = 'html', $rounded = false)
 {
     $html = $output == 'html';
     switch ($variable) {
         case 'rate':
             $ret = $this->renderItemRate($html);
             break;
         case 'discount_amount':
         case 'tax_amount':
             $ret = $this->renderJustItemRates($variable, $html, $rounded);
             break;
         case 'first_rate':
         case 'first_discount_amount':
         case 'first_tax_amount':
             $ret = cbpaidMoney::getInstance()->renderPrice($this->{$variable}, $this->currency, $html, $rounded);
             break;
         case 'quantity':
             // removes insignifiant zeros after ., as well as the . itself if no decimals:
             $matches = null;
             $matched = preg_match("/^(.+?)[.]?[0]*\$/", $this->get($variable), $matches);
             $ret = $matched ? $matches[1] : null;
             break;
         case 'validity_period':
             if ($this->start_date && $this->stop_date && $this->start_date != '0000-00-00 00:00:00' && $this->stop_date != '0000-00-00 00:00:00') {
                 $showTime = false;
                 $startDate = cbFormatDate($this->start_date, 1, $showTime);
                 $stopDate = cbFormatDate($this->stop_date, 1, $showTime);
                 $ret = htmlspecialchars($startDate);
                 if ($stopDate && $startDate != $stopDate) {
                     $ret .= ($html ? '&nbsp;-&nbsp;' : ' - ') . htmlspecialchars($stopDate);
                 }
                 if ($this->second_stop_date && $this->second_stop_date != '0000-00-00 00:00:00') {
                     $secondStartDate = cbFormatDate($this->_db->getUtcDateTime(cbpaidTimes::getInstance()->strToTime($this->stop_date) + 1), 1, $showTime);
                     $secondStopDate = cbFormatDate($this->second_stop_date, 1, $showTime);
                     $retsecond = htmlspecialchars($secondStartDate) . ($html ? '&nbsp;-&nbsp;' : ' - ') . htmlspecialchars($secondStopDate);
                     $ret = sprintf($html ? CBPTXT::Th("%s, then %s") : CBPTXT::T("%s, then %s"), $ret, $retsecond);
                 }
             } else {
                 $ret = null;
             }
             break;
         case 'tax_rule_id':
             if ($this->tax_rule_id && is_callable(array('cbpaidTaxRule', 'getInstance'))) {
                 $ret = cbpaidTaxRule::getInstance((int) $this->tax_rule_id)->getShortCode();
             } else {
                 $ret = null;
             }
             break;
         case 'original_rate':
         case 'first_original_rate':
             $ret = null;
             break;
         case 'ordering':
         case 'artnum':
         case 'description':
         case 'discount_text':
         default:
             $value = $this->get($variable);
             if ($value !== null) {
                 $ret = htmlspecialchars($this->get($variable));
             } else {
                 $ret = null;
             }
             break;
     }
     return $ret;
 }
 /**
  * Displays $text inside a standard CB div, and sets page title and pathway too
  *
  * @param  string  $text
  * @return string
  */
 public static function displayWithTemplate($text)
 {
     global $_CB_framework;
     $regTitle = strip_tags(CBPTXT::T(cbpaidApp::settingsParams()->get('regTitle', "Subscriptions")));
     outputCbTemplate();
     $_CB_framework->setPageTitle($regTitle);
     $_CB_framework->appendPathWay($regTitle);
     $pre = '<div class="cbPageOuter"><div class="cbPageInner" id="cbregField">';
     $post = '</div></div><div class="cbClr"> </div>';
     return $pre . $text . $post;
 }
 /**
  * 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.º 10
0
	/**
	 * Returns formatted time period ( xxx weeks , or xxx years xxx months xxx days xxx hours xxx minutes xxx seconds
	 *
	 * @param  string        $varName                    'validity' or 'fist_validity'
	 * @param  int           $occurrences                [default: 1] multiply period by the occurrences before displaying
	 * @param  boolean       $displayOne                 [default: true] displays also if only 1 unit of something
	 * @param  boolean       $displayCalendarYearStart   [default: true] displays start of calendar year if not January 1st
	 * @return string
	 */
	private function _renderPeriodOfValiditiy( $varName, $occurrences = 1, $displayOne = true, $displayCalendarYearStart = true ) {
		// $ycdhmsArray	=	$this->_timedObject->getValidity( $varName );
		// $prefix			=	( $this->_timedObject->isCalendarValidity( $varName ) ? CBPTXT::T("calendar ") : '' );
		// return $this->_timedObject->renderPeriod( $ycdhmsArray, $occurrences, $displayOne, $prefix );
		$ycdhmsArray	=	$this->getValidity( $varName );
		$prefix			=	( $this->isCalendarValidity( $varName ) ? CBPTXT::T("calendar ") : '' );
		$text			=	$this->renderPeriod( $ycdhmsArray, $occurrences, $displayOne, $prefix );
		$calStart		=	$this->calendarYearStart( $varName );
		if ( $prefix && ( $calStart != '01-01' ) && $displayCalendarYearStart ) {
			list( $m, $d )	=	explode( '-', $calStart );
			$text		.=	' ' . CBPTXT::T("starting") . ' ' . date( 'F j', mktime( 0, 0, 0, $m, $d, 2004 ) );
		}
		return $text;
	}
Exemplo n.º 11
0
	/**
	* gets the chosen plans from the form, and checks if they are allowed for that user
	* also gets the options of the plans
	* In detail:
	* gets an array of array of int as an array of int (removing first level), verifying that if index is not 0 the parent exists
	* In each plan object there is a ->_options variable with a Registry object with the option values of the plan
	*
	* @param  UserTable        $user            Reflecting the user being registered or saved
	* @param  string           $name            name of parameter in REQUEST URL
	* @param  cbpaidProduct[]  $allowedPlans    array of cbpaidProduct  which are allowed
	* @param  boolean          $isRegistration  TRUE: Registration process (guest), or FALSE: upgrade-process (logged-in user)
	* @param  string           $reason          Subscription reason: 'N'=new subscription (default), 'R'=renewal, 'U'=update
	* @param  boolean          $returnPlans     TRUE: returns plan objects or FALSE: returns plan ids only.
	* @param  string           $postfix         postfix for identifying multiple plans spaces (optional)
	* @return int[]|cbpaidProduct[]|string     ARRAY of int|of cbpaidProducts : Plans which are selected within hierarchy (according to the post, to be rechecked !) or STRING: error message.
	*/
	protected function & _planGetAndCheckReqParamArray( &$user, $name, &$allowedPlans, $isRegistration, $reason, $returnPlans = false, $postfix = '' ) {
		global $_CB_framework, $_POST;

		$params							=&	cbpaidApp::settingsParams();
		$enableFreeRegisteredUser		=	$params->get( 'enableFreeRegisteredUser', 1 );
		$createAlsoFreeSubscriptions	=	$params->get( 'createAlsoFreeSubscriptions', 0 );

		$ui								=	$_CB_framework->getUi();
		if ( ! $isRegistration ) {
			if ( $ui == 1 ) {
				$userId					=	(int) cbGetParam( $_POST, 'user', 0 );
			} else {
				$userId					=	(int) cbGetParam( $_POST, 'id', 0 );
			}
		} else {
			$userId						=	null;
		}

		$selectedPlanIds							=	$this->_plangetReqParamArray( $name, $postfix );
		/// $validSub									=	array();
		// 1. checks that selected plans hierarchy is respected:
		$ok											=	true;
		$plansMgr									=	null;
		foreach ( $selectedPlanIds as $id ) {
			if ( $id != 0 ) {						// ignore "None" plan in backend edit profile
				$ok									=	false;
	
				// foreach ( $allowedPlans as $planid => $p ) {
				if ( isset( $allowedPlans[(int) $id] ) ) {
					$p								=	$allowedPlans[(int) $id];
	
					if ( $id == $p->id ) {
						$parentOk					=	true;
						$parentId					=	$p->get( 'parent' );
						if ( $parentId != 0 ) {
							// the selected plan has a parent plan: check if parent plan is also chosen or already subscribed and active:
							$parentOk				=	false;
							foreach ($selectedPlanIds as $selPlanId ) {
								if ( $parentId == $selPlanId ) {
									$parentOk		=	true;
									break;
								}
							}
							if ( ( ! $isRegistration ) && ( ! $parentOk ) ) {
								// try to see if user is subscribed already to the parent plan:
								if ( $userId ) {
									if ( $plansMgr === null ) {
										$plansMgr	=&	cbpaidPlansMgr::getInstance();
									}
									$plan			=	$plansMgr->loadPlan( $parentId );
									/** @var $plan cbpaidProduct */
									if ( $plan ) {
										// Check if allow free lifetime users without need to create such subscriptions:
										if ( $enableFreeRegisteredUser && ( ! $createAlsoFreeSubscriptions ) && $plan->isLifetimeValidity() && $plan->isFree() ) {
											$parentOk		=	true;
										} else {
											$sub			=	$plan->newSubscription();
											/** @var $sub cbpaidSomething */
											if ( $sub->loadValidUserSubscription( $userId ) ) {
												$parentOk	=	true;
												/// $validSub[$parentId]		=	$sub->id;
											}
										}
									}
								}
							}
						}
						if ( $parentOk ) {
							$ok						=	true;
						}
						break;
					}
				}
				if ( ! $ok ) {
					break;
				}
			}
		}

		if ( ! $ok ) {
			$selectedPlanIds								=	CBPTXT::T("Chosen plans combination is not allowed (you must choose coherent plans selection, e.g. parent subscriptions to a plan must be active).");
		} else {
			// 2. Check that all exclusivities are respected:
			$plansMgr										=&	cbpaidPlansMgr::getInstance();
			// 2.a. build array of exclusive [parent][plan]:
			$exclusiveChildren								=	array();
			// 2.a.1. add the plans just selected now:
			foreach ($allowedPlans as $id => $p ) {
				if ( $p->get( 'exclusive' ) ) {
					$exclusiveChildren[$p->get( 'parent' )][$p->get( 'id' )]	=	( in_array( $id, $selectedPlanIds ) ? 1 : 0 );
				}
			}
			// 2.a.2. add the plans already subscribed with active subscription (if we are not just upgrading that level):
			$ValidUserPlans									=	array();
			$validSubExists									=	array();
			if ( ( ! $isRegistration ) && $userId ) {
				foreach ( $exclusiveChildren as $parentId => $exclPlansArray ) {
					if ( $parentId != 0 ) {
						$plan								=	$plansMgr->loadPlan( $parentId );
						if ( $plan ) {
							$sub							=	$plan->newSubscription();
							$ValidUserPlans[$parentId]		=	( $sub->loadValidUserSubscription( $userId ) );
						} else {
							$selectedPlanIds				=	CBPTXT::T("Chosen plan has a parent plan configured that doesn't exist anymore.");
						}
					}
					$numberOfSelected						=	array_sum( $exclPlansArray );
					if ( $numberOfSelected == 0 ) {
						$firstFreeLifeTime					=	array();
						// foreach ( $exclPlansArray as $childId => $selected )
						foreach ( array_keys( $exclPlansArray ) as $childId ) {
							$plan							=	$plansMgr->loadPlan( $childId );
							if ( ( ! isset( $firstFreeLifeTime[$parentId] ) ) && ( $enableFreeRegisteredUser && ( ! $createAlsoFreeSubscriptions ) && $plan->isLifetimeValidity() && $plan->isFree() ) ) {
								$firstFreeLifeTime[$parentId]	=	$plan->get( 'id' );
							}
							if ( ! isset( $ValidUserPlans[$childId] ) ) {
								$sub						=	$plan->newSubscription();
								$ValidUserPlans[$childId]	=	( $sub->loadValidUserSubscription( $userId ) );
							}
							if ( $ValidUserPlans[$childId] ) {
								$exclusiveChildren[$parentId][$childId]		=	1;
								$validSubExists[$parentId]						=	1;
							}
						}
					}
				}
			}
			// 2.b. check that exactly 1 exclusive plan is selected at each level (including still valid subscribed plans) which matters:
			if ( ! ( ( $ui == 2 ) && ( $selectedPlanIds == array( '0' ) ) ) ) {		// ignore "None" plan in backend edit profile
				foreach ( $exclusiveChildren as $parentId => $exclPlansArray ) {
					$numberOfSelected						=	array_sum( $exclPlansArray );
					if ( $numberOfSelected > 1 ) {
						$selectedPlanIds					=	CBPTXT::T("Chosen plans combination is not allowed (you can't choose more than one mandatory plan).") . $numberOfSelected;
						break;
					}
					elseif ( ( $numberOfSelected == 0 ) && ( ! isset( $validSubExists[$parentId] ) ) && ( ! isset( $firstFreeLifeTime[$parentId] ) ) ) {
						if ( ( $parentId == 0 ) || in_array( $parentId, $selectedPlanIds ) || ( isset( $ValidUserPlans[$parentId] ) && ( $ValidUserPlans[$parentId] == true ) ) )
						{
							$selectedPlanIds				=	CBPTXT::T("Chosen plans combination is not allowed (you must choose coherent plans selection, e.g. mandatory subscription(s) must be active or mandatory plan(s) must be chosen).");
							$names							=	array();
							foreach ( array_keys( $exclPlansArray ) as $childId ) {
								$exclPlan					=&	$plansMgr->loadPlan( $childId );
								/** @var $exclPlan cbpaidProduct */
								$names[]					=	$exclPlan->get( 'name' );
							}
							if ( $parentId ) {
								$parentPlan					=&	$plansMgr->loadPlan( $parentId );
								/** @var $parentPlan cbpaidProduct */
								$parentName					=	$parentPlan->get( 'name' );
								$selectedPlanIds			.=	' ' . CBPTXT::T( sprintf( "'%s' has mandatory options '%s' and none is selected." , $parentName, implode( "', '", $names ) ) );
							}
							break;
						}
					}
				}
			}
			// 3. Checks that all selected plans' conditions are met:
			if ( is_array( $selectedPlanIds ) ) {
				foreach ( $selectedPlanIds as $id ) {
					if ( $id ) {
						$plan								=&	$plansMgr->loadPlan( $id );
						if ( $plan ) {
							if ( ! $plan->checkActivateConditions( $user, $reason, $selectedPlanIds ) ) {
								// Error text will be in selectedPlanIds in case of error returning false:
								break;
							}
						}
					}
				}
			}
			// 4. Checks done:
			if ( $returnPlans && is_array( $selectedPlanIds ) && ( count( $selectedPlanIds ) > 0 ) ) {
				// if returning selected plans, sort them in same order and with same keys as corresponding allowed plans:
				global $_PLUGINS;
				$_PLUGINS->loadPluginGroup( 'user', 'cbsubs.' );
				$_PLUGINS->loadPluginGroup('user/plug_cbpaidsubscriptions/plugin');

				$selectedPlans								=	array();
				foreach ($allowedPlans as $id => $p ) {
					if ( in_array( $id, $selectedPlanIds ) ) {
						/** @var cbpaidProduct[] $selectedPlans */
						$selectedPlans[(int) $id]			=	$allowedPlans[$id];
						$selectionId						=	'plan' . $id;
						$selectionName						=	'plan' . ( $selectedPlans[$id]->get( 'exclusive' ) ? 'E' : 'N' ) . '[' . (int) $selectedPlans[$id]->parent . ']';
						$selectionValue						=	$id;
						$view								=	$selectedPlans[$id]->getViewer();

						$paramsOrString						=	$view->getOptions( $selectionId, $selectionName, $selectionValue, $reason );
						if ( is_string( $paramsOrString ) ) {
							$selectedPlans					=	$paramsOrString;		// error message
							break;
						}
						$selectedPlans[(int) $id]->_options		=	$paramsOrString;
						$selectedPlans[(int) $id]->_integrations	=	new Registry( '' );
						$_PLUGINS->trigger( 'onCPayAfterPlanSelected', array( &$selectedPlans[(int) $id], &$selectedPlans[(int) $id]->_integrations , $reason ) );
						if ( $_PLUGINS->is_errors() ) {
							$selectedPlans							=	$_PLUGINS->getErrorMSG();
							break;
						}
					}
				}
				return $selectedPlans;
			}
		}
		return $selectedPlanIds;
	}
	/**
	 * display basket and payment buttons or redirect for payment depending if multiple payment choices or intro text present:
	 *
	 * @param  UserTable            $user
	 * @param  cbpaidPaymentBasket  $paymentBasket
	 * @param  string               $introText
	 * @param  boolean              $ajax           TRUE if AJAX refresh inside #cbregPayMethodsChoice, FALSE: wraps in <div id="cbregPayMethodsChoice">
	 * @return string                               HTML  (or DOES REDIRECT if $redirectNow = ! ( ( $nbClasses != 1 ) || $introText ) == TRUE)
	 */
	public function getPaymentBasketPaymentForm( &$user, &$paymentBasket, $introText, $ajax = false ) {
		global $_PLUGINS;

		$result								=	null;

		$params								=	cbpaidApp::settingsParams();
		$invoicingAddressQuery				=	$params->get( 'invoicing_address_query' );
		$basket_requiredterms				=	$params->get( 'basket_requiredterms' );
		$basket_requiredtermserror			=	$params->get( 'basket_requiredtermserror' );
		$payment_method_selection_type		=	$params->get( 'payment_method_selection_type', 'buttons' );
		$allow_select_currency				=	$params->get( 'allow_select_currency', '0' );

		$redirectNow						=	null;
		$payChoicesArray					=	$this->getPaymentMethodsParams( $user, $paymentBasket, $introText, $redirectNow );

		$chosenPaymentMethod				=	$paymentBasket->gateway_account ? $paymentBasket->gateway_account . '-' . $paymentBasket->payment_type : '';		// cbGetParam( $_POST, 'payment_method' );

		$payChoicesHtmlRadiosArray			=	array();
		$chosenPaymentSelector				=	null;
		$payChoicesHtmlBottomArray			=	$this->_renderPayChoicesArray( $payChoicesArray, $paymentBasket, $redirectNow, $chosenPaymentMethod, $payChoicesHtmlRadiosArray, $chosenPaymentSelector );
		if ( $redirectNow == 'redirect' && is_string( $payChoicesHtmlBottomArray ) ) {
			cbRedirect( $payChoicesHtmlBottomArray );
		}

		$subscriptionsGUI					=	new cbpaidControllerUI();
		$subscriptionsGUI->addcbpaidjsplugin();

		if ( ( $payment_method_selection_type == 'radios') && ( $chosenPaymentMethod != '' ) && $chosenPaymentSelector ) {
			// Select button to draw:
			$payChoicePayButton				=	$this->getPayMethodButton( $user, $paymentBasket, $paymentBasket->gateway_account, $paymentBasket->payment_type, $chosenPaymentSelector );
			/** @var $chosenPaymentSelector cbpaidGatewaySelector */
			$this->modifyAspectPayMethodButton( $payChoicePayButton, $chosenPaymentSelector->paymentType );
			$dummy							=	null;
			$payChoicePayButtonHtmlArray	=	$this->_renderPayChoicesArray( array( $payChoicePayButton ), $paymentBasket, 'buttons', $chosenPaymentMethod, $payChoicesHtmlRadiosArray, $dummy );
			$payChoicesHtmlBottomArray		=	array_merge( $payChoicesHtmlBottomArray, $payChoicePayButtonHtmlArray );
		}

		if ( true )  {
			// always add cancel link
			cbpaidApp::import( 'processors.cancelpay.cancelpay' );
			$cancelmethod					=	new cbpaidGatewayAccountcancelpay();
			$payClass						=	$cancelmethod->getPayMean();
			$payChoicesHtmlBottomArray[]	=	$payClass->getPaymentBasketProcess( $user, $paymentBasket, 'buttons' );	// never redirectNow a cancel link :D !
		}

		$basketHtml							=	$paymentBasket->displayBasket();

		if ( $allow_select_currency == 2 ) {
			$currencySelector				=	$this->displayCurrencySelector( $paymentBasket );
		} else {
			$currencySelector				=	null;
		}
		$txtConclusion						=	$params->get('conclusion_text');
		$txtFinal							=	$params->get('final_text');

		$txtTerms						=	null;
		if ( $basket_requiredterms == 1 ) {
			global $_CB_database, $_CB_framework;

			$query							=	'SELECT ' . $_CB_database->NameQuote( 'params' )
											.	"\n FROM " .  $_CB_database->NameQuote( '#__comprofiler_fields' )
											.	"\n WHERE " . $_CB_database->NameQuote( 'name' ) . " = " . $_CB_database->Quote( 'acceptedterms' );
			$_CB_database->setQuery( $query );
			$tcParams						=	new Registry( $_CB_database->loadResult() );

			$termsOutput					=	$tcParams->get( 'terms_output', 'url' );
			$termsDisplay					=	$tcParams->get( 'terms_display', 'modal' );
			$termsURL						=	$tcParams->get( 'terms_url', null );
			$termsText						=	$tcParams->get( 'terms_text', null );
			$termsWidth						=	(int) $tcParams->get( 'terms_width', 400 );
			$termsHeight					=	(int) $tcParams->get( 'terms_height', 200 );

			if ( ! $termsHeight ) {
				$termsHeight				=	200;
			}

			if ( ( ( $termsOutput == 'url' ) && $termsURL ) || ( ( $termsOutput == 'text' ) && $termsText ) ) {
				if ( $termsDisplay == 'iframe' ) {
					if ( $termsOutput == 'url' ) {
						$txtTerms			.=				'<iframe class="cbTermsFrameURL" height="' . $termsHeight . '" width="' . ( $termsWidth ? $termsWidth : '100%' ) . '" src="' . htmlspecialchars( $termsURL ) . '"></iframe>';
					} else {
						$txtTerms			.=				'<div class="cbTermsFrameText" style="height:' . $termsHeight . 'px;width:' . ( $termsWidth ? $termsWidth . 'px' : '100%' ) . ';overflow:auto;">' . CBPTXT::T( $termsText ) . '</div>';
					}
				}

				if ( $termsDisplay != 'iframe' ) {
					$attributes				=	' class="cbTermsLink"';

					if ( ( $termsOutput == 'text' ) && ( $termsDisplay == 'window' ) ) {
						$termsDisplay		=	'modal';
					}

					if ( $termsDisplay == 'modal' ) {
						if ( ! $termsWidth ) {
							$termsWidth		=	400;
						}

						if ( $termsOutput == 'url' ) {
							$tooltip		=	'<iframe class="cbTermsModalURL" height="' . $termsHeight . '" width="' . $termsWidth . '" src="' . htmlspecialchars( $termsURL ) . '"></iframe>';
						} else {
							$tooltip		=	'<div class="cbTermsModalText" style="height:' . $termsHeight . 'px;width:' . $termsWidth . 'px;overflow:auto;">' . CBPTXT::T( $termsText ) . '</div>';
						}

						$url				=	'javascript:void(0);';
						$attributes			.=	' ' . cbTooltip( $_CB_framework->getUi(), $tooltip, CBPTXT::T( 'Terms and Conditions' ), 'auto', null, null, null, 'data-cbtooltip="true" data-modal="true"' );
					} else {
						$url				=	htmlspecialchars( $termsURL );
						$attributes			.=	' target="_blank"';
					}

					$txtTerms				.=				CBPTXT::P( 'I have read and approve the <a href="[url]"[attributes]>Terms and Conditions</a>', array( '[url]' => $url, '[attributes]' => $attributes ) );
				} else {
					$txtTerms				.=				CBPTXT::T( 'I have read and approve the above Terms and Conditions.' );
				}
			}
		} elseif ( $basket_requiredterms == 2 ) {
			$txtTerms					=	$params->get( 'basket_termsandconditions' );
		}

		if ($introText) {
			$result						.=	'<div class="cbregIntro">' . CBPTXT::Th( $introText ) . "</div>\n";
		}
		$result							.=	$basketHtml;

		if ( $allow_select_currency == 2 ) {
			$result						.=	$currencySelector;
		}

		if ( $invoicingAddressQuery > 0 ) {
			$errorMsg					=	$paymentBasket->checkAddressComplete();
			if ( $errorMsg && ( $invoicingAddressQuery == 2 ) ) {
				$result					=	'';
				$introAddrNeeded		=	$params->get('invoicing_address_required_into_text');
				if ($introAddrNeeded) {
					$result				.=	'<div class="cbregIntro">' . CBPTXT::Th( $introAddrNeeded ) . "</div>\n";
				}
				$result					.=	$paymentBasket->renderInvoicingAddressForm( $user );	// $xmlController->handleAction( 'action', 'editinvoiceaddress' );
				return $result;
			} else {
				if ( $errorMsg ) {
					cbpaidApp::getBaseClass()->_setErrorMSG( $errorMsg );
				}
				$result					.=	'<div class="cbregInvoicingAddress">'
					.	$paymentBasket->renderInvoicingAddressFieldset()
					.	'</div>';
			}
			// display current invoicing address with a link to change/edit it with a back link to the payment basket id
			// if the address is not mandatory.
			// If it is mandatory, check that it is complete (and later also screened),
			// if not display instead of this the invoicing address edit page !
		}
		$integrationsResults			=	$_PLUGINS->trigger( 'onCbSubsAfterPaymentBasket', array( $paymentBasket, &$result, &$txtTerms ) );
		foreach ( $integrationsResults as $intRes ) {
			if ( is_string( $intRes ) ) {
				$result					.=	$intRes;
			}
		}
		if ( $txtConclusion ) {
			$result						.=	'<div class="cbregConcl">' . CBPTXT::Th( $txtConclusion ) . "</div>\n";
		}

		if ( count( $payChoicesHtmlRadiosArray ) > 0 ) {

			$radios_intro_html			=	CBPTXT::Th( $params->get( 'radios_intro_html' ) );
			$radios_conclusion_html		=	CBPTXT::Th( $params->get( ( $chosenPaymentMethod != null ) ? 'radios_selected_conclusion_html' : 'radios_unselected_conclusion_html' ) );

			$htmlList					=	'<ul class="cbregPaymentMethodChoiceList">' . "\n";
			foreach ( $payChoicesHtmlRadiosArray as $selHtmlArr ) {
				if ( $selHtmlArr[0] ) {
					$htmlList			.=	'<li class="cbregCCradioLi cbregCCradioSelected">';
				} else {
					$htmlList			.=	'<li class="cbregCCradioLi">';				//LATER:  class="cbpaidCCradio cbpaidRadio_<?php echo htmlspecialchars( $this->payNameForCssClass ); " id="<?php echo htmlspecialchars( $this->butId );
				}
				$htmlList				.=	'<div class="cbregCCradioLiBg"></div>'		// This allows to use the CSS trick for highlighting as explained here: http://www.commentcamarche.net/forum/affich-3898635-transparance-du-fond-uniquement
					.	$selHtmlArr[1]
					.	"</li>\n";
			}
			$htmlList					.=	"</ul>\n";

			$methodsHTML				=	'<div class="cbregPaymentMethodChoice ' . ( ( $chosenPaymentMethod != null ) ? 'cbregPMselected' : 'cbregPMunselected' ) . '">'
				.	( $radios_intro_html ? '<h2 class="contentheading cbregPaymenMethodChoiceIntro">' . $radios_intro_html . '</h2>' : '' )
				.	$htmlList
				.	'<span class="cb_button_wrapper">'
				.	'<button type="submit" id="cbregSelectPayment">' . CBPTXT::Th("Change Payment Method") . '</button>'
				.	'</span>'
				.	( $radios_conclusion_html ? '<div class="cbregPaymenMethodChoiceConclusion">' . $radios_conclusion_html . '</div>' : '' )
				.	"</div>\n"
			;
			$getParams					=	$paymentBasket->getSetBasketPaymentMethodUrl( $user );
			$ajaxGetParams				=	cbUnHtmlspecialchars( $paymentBasket->getSetBasketPaymentMethodUrl( $user, 'raw' ) );
			$formHiddens				=	array(	cbpaidApp::getBaseClass()->_getPagingParamName('act') => 'setbsktpmtmeth',
				'ajaxurl' => bin2hex( $ajaxGetParams ) );
			$result						.=	'<div class="cbregPaymentMethodsSelect">' . $subscriptionsGUI->drawForm( $methodsHTML, null, $formHiddens, $getParams ) . "</div>\n";
			$termsCanBeDisplayed		=	( $payment_method_selection_type != 'radios' ) || ( $chosenPaymentMethod != null );
		} else {
			$termsCanBeDisplayed		=	true;
		}

		if ( $txtTerms ) {
			if ( $termsCanBeDisplayed ) {
				$accepted				=	( cbGetParam( $_POST, 'terms_accepted', 0 ) == 1 );
				$settings				=	'<div class="cbregTermsAccept"><input type="checkbox" class="required" name="terms_accepted" id="terms_accepted" value="1"'
					.	( $accepted ? ' checked="checked" disabled="disabled" ' : '' )
					.	'/> '
					.	'<label for="terms_accepted">'
					.	$txtTerms
					.	'</label></div>'
				;
				if ( ! $accepted ) {
					$settings			.=	'<span class="cb_button_wrapper">'
						.	'<button type="submit" id="cbTermsAccept" title="' . htmlspecialchars( CBPTXT::T( $basket_requiredtermserror ) ) . '">' . CBPTXT::Th("Accept Terms") . '</button>'
						.	'</span>'
					;
				}
				$getParams				=	$accepted ? '#' : $paymentBasket->getShowBasketUrl( false );
				$formHiddens			=	$accepted ? array( 'terms_accepted' => 1 ) : array();
				$result					.=	'<div class="cbregTerms">' . $subscriptionsGUI->drawForm( $settings, null, $formHiddens, $getParams ) . "</div>\n";
			} else {
				$accepted				=	false;
			}
		} else {
			$accepted					=	true;
		}

		$result							.=	'<div class="cbpayChoices cbclearboth"'
			.	( $termsCanBeDisplayed && $txtTerms && ! $accepted ? ' style="display:none;"' : '' )
			.	">\n "
			.	implode ( "\n  ", $payChoicesHtmlBottomArray )
			.	"\n</div>\n";
		if ( $txtFinal ) {
			$result						.=	'<div class="cbregFinalText">' . CBPTXT::Th( $txtFinal ) . "</div>\n";
		}

		$result							=	'<div class="cbpayBasketView">' . $result . '</div>';
		if ( ! $ajax ) {
			$result						=	'<div id="cbpayOrderContainer">'	// Needed for Javascript delegated binding
				.	$result
				.	'</div>';
		}
		return $result;
	}
 /**
  * Evaluates $postdata which is the $_POST array of the form submission of the cbpaidProductView::draw() form,
  * and returns the filtered unescaped options.
  *
  * @param  string           $selectionId     html input tag attribute id=''    field for the input
  * @param  string           $selectionName   html input tag attribute name=''  field for the input
  * @param  string           $selectionValue  html input tag attribute value='' field for the input
  * @param  string           $reason          Payment reason: 'N'=new subscription (default), 'R'=renewal, 'U'=update
  * @return ParamsInterface                   Product's selected options
  */
 public function getOptions($selectionId, $selectionName, $selectionValue, $reason)
 {
     $optionParams = new Registry('');
     $this->_setOptionNames($selectionId, $selectionName, false);
     $selectedvalue = (double) $this->_getReqParam($this->_donselName);
     $donval = abs((double) $this->_getReqParam($this->_donvalName));
     $this->fixedchoices = $this->_model->getParam('fixedchoices', 1);
     $this->defaultchoice = $this->_model->getParam('defaultchoice', '');
     $minimumDonation = (double) $this->_model->getParam('minimumdonation', '');
     $maximumDonation = (double) $this->_model->getParam('maximumdonation', '');
     $this->donateamounts = explode(',', $this->_model->getParam('donateamount', ''));
     $this->_trimArray($this->donateamounts);
     $amount = 0;
     if ($this->fixedchoices > 1 && in_array($selectedvalue, $this->donateamounts)) {
         $amount = $selectedvalue;
     } elseif ($selectedvalue == '' && $this->fixedchoices != 2) {
         if ($donval < $minimumDonation) {
             return CBPTXT::T("Amount too small") . '.';
         } elseif ($maximumDonation != 0 && $donval > $maximumDonation) {
             return CBPTXT::T("Amount too large") . '.';
         }
         $amount = $donval;
     }
     if ($amount == 0) {
         return CBPTXT::T("Amount not allowed") . '.';
     }
     $optionParams->set('amount', $amount);
     return $optionParams;
 }
	/**
	 * 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;
	}
Exemplo n.º 15
0
	/**
	 * Get a correct display of the formatted validity of a plan: override if needed
	 *
	 * @return string                     Formatted text giving validity of this subscription
	 */
	public function getFormattedExpirationDateText() {
		if ( $this->status == 'A' ) {
			$params				=&	cbpaidApp::settingsParams();
			return CBPTXT::T( $params->get( 'regtextLifetime', 'Lifetime Subscription' ) );
		} else {
			return CBPTXT::T('Not active');
		}
	}
Exemplo n.º 16
0
	/**
	 * Renders payments cycles with rate and validity for $this basket
	 *
	 * @param  boolean       $html
	 * @param  boolean       $roundings  TRUE: use settings roundings, FALSE: round to cents
	 * @return string                 HTML text
	 */
	public function renderRatesValidtiy( $html, $roundings = true ) {
		if ( $this->period1 ) {
			if ( $this->recur_times ) {
				$tmpltext	=	CBPTXT::T("%s for the first %s, then %s for each %s, in %s installments");
			} else {
				$tmpltext	=	CBPTXT::T("%s for the first %s, then %s each %s");		//TBD: alternate text: "&s, then, after %s, %s each %s"
			}
		} else {
			if ( $this->recur_times ) {
				$tmpltext	=	CBPTXT::T("%3\$s for each %4\$s, in %5\$s installments");
			} else {
				$tmpltext	=	CBPTXT::T("%3\$s for each %4\$s");
			}
		}
		$cbpaidMoney			=&	cbpaidMoney::getInstance();
		$cbpaidTimes			=&	cbpaidTimes::getInstance();

		if ( $this->period1 ) {
			$validity			 =	$this->ymwdPeriodToTimePeriod( $this->period1 );
			$first_validity_text =	$cbpaidTimes->renderPeriod( $validity, 1 , false );
			$first_rate_text	 =	$cbpaidMoney->renderPrice( $this->mc_amount1, $this->mc_currency, $html, $roundings );
		} else {
			$first_validity_text =	null;
			$first_rate_text	 =	null;
		}

		$validity				=	$this->ymwdPeriodToTimePeriod( $this->period3 );
		$validity_text			=	$cbpaidTimes->renderPeriod( $validity, 1 , false );
		$rate_text				=	$cbpaidMoney->renderPrice( $this->mc_amount3, $this->mc_currency, $html, $roundings );

		$text					=	sprintf( $tmpltext, $first_rate_text, $first_validity_text, $rate_text, $validity_text, $this->recur_times );
		return $text;
	}
Exemplo n.º 17
0
	/**
	 * This is the handler for current version
	 *
	 * @return string
	 */
	public static function currentVersion( ){
		$licenseMgr				=&	self::getInstance();
		return CBPTXT::T("Version") . ' ' . $licenseMgr->version . ' ' . $licenseMgr->versionminor . '.';
	}
 /**
  * Renders an HTML table with the differences in $diffArry
  *
  * @param  array  $diffArry
  * @return string
  */
 protected function _diffTableHtml($diffArry)
 {
     $tr = '<table summary="' . CBPTXT::T("Changes") . '" class="cbregChangeDiffs">' . "\n";
     $tr .= " <thead>\n";
     $tr .= "  <tr>\n";
     $tr .= '    <th scope="col" class="cbregDiffHF">';
     $tr .= CBPTXT::T("Field");
     $tr .= "</th>\n";
     $tr .= '    <th scope="col" class="cbregDiffHO">';
     $tr .= CBPTXT::T("Old value");
     $tr .= "</th>\n";
     $tr .= '    <th scope="col" class="cbregDiffHN">';
     $tr .= CBPTXT::T("New value");
     $tr .= "</th>\n";
     $tr .= "  </tr>\n";
     $tr .= " </thead>\n";
     $tr .= " <tbody>\n";
     foreach ($diffArry as $k => $v) {
         $tr .= "  <tr>\n";
         $tr .= '    <th scope="row">';
         $tr .= htmlspecialchars($k);
         $tr .= "</th>\n";
         $tr .= '    <td class="cbregDiffold">';
         $tr .= isset($v['o']) ? htmlspecialchars($v['o']) : '';
         $tr .= "</td>\n";
         $tr .= '    <td class="cbregDiffnew">';
         $tr .= isset($v['n']) ? htmlspecialchars($v['n']) : '';
         $tr .= "</td>\n";
         $tr .= "  </tr>\n";
     }
     $tr .= " </tbody>\n";
     $tr .= "</table>\n";
     return $tr;
 }
	/**
	 * Returns a cbpaidGatewaySelectorButton object parameters for rendering an HTML form with a visible button and hidden fields for the gateway
	 * Or a string with HTML content instead (not recommended)
	 * 
	 * @param  cbpaidPaymentBasket  $paymentBasket  paymentBasket object
	 * @param  string               $subMethod      'single', 'subscribe' or gateway-specific string (e.g. credit-card brand)
	 * @param  string               $paymentType    'single' or 'subscribe' or for subscriptions 'cancel'
	 * @return cbpaidGatewaySelectorButton                  or string with HTML
	 */
	protected function getPayButtonRecepie( $paymentBasket, $subMethod, $paymentType )
	{
		// Settings for Free Trial and Order Now buttons are stored in global CBSubs settings:
		$params					=	cbpaidApp::settingsParams();

		// Generate URLs for payment:
		$pspUrl					=	$this->pspUrl( $paymentBasket, ( $paymentType == 'subscribe' ) );
		$requestParams			=	$this->getSinglePaymentRequstParams( $paymentBasket );
		$customImage			=	$params->get( $this->_button . '_custom_image' );
		$titleText				=	( $this->_button == 'freetrial' ? CBPTXT::T("Subscribe to free trial period only") : CBPTXT::T("Confirm Order") );
		$altText				=	( $this->_button == 'freetrial' ? CBPTXT::T("Free Trial") :  CBPTXT::T("Confirm Order") );
		$butId					=	'cbpaidButt' . strtolower( $this->_button );

		if ( $customImage == '' ) {
			$customImage		=	$params->get( $this->_button . '_image', 'components/com_comprofiler/plugin/user/plug_cbpaidsubscriptions/icons/cards/'
								.	( $this->_button == 'freetrial' ? 'cc_big_orange_free_trial.gif' : 'cc_big_orange_confirm_order.gif' ) );
		}
		$payNameForCssClass		=	$this->_button;
		
		return cbpaidGatewaySelectorButton::getPaymentButton( $this->getAccountParam( 'id' ), $subMethod, $paymentType, $pspUrl, $requestParams, $customImage, $altText, $titleText, $payNameForCssClass, $butId );
	}
	/**
	 * Prepares and signs payflow payment $requestParams
	 *
	 * @param cbpaidPaymentBasket $paymentBasket
	 * @param bool $subscription
	 * @return array $requestParams
	 */
	private function _payflowPayment( $paymentBasket, $subscription = false )
	{
		$requestParams									=	array();

		if ( $this->hasPaypalPayflow() ) {
			$countries									=	new cbpaidCountries();

			if ( $paymentBasket->period3 ) {
				if ( $paymentBasket->period1 ) {
					$amount								=	sprintf( '%.2f', $paymentBasket->mc_amount1 );
				} else {
					$amount								=	sprintf( '%.2f', $paymentBasket->mc_amount3 );
				}
			} else {
				$amount									=	sprintf( '%.2f', $paymentBasket->mc_gross );
			}

			if ( $this->getAccountParam( 'normal_gateway' ) == '0' ) {
				$requestParams['MODE']					=	'TEST';
			}

			$request									=	array(	'PARTNER' => 'PayPal',
																	'VENDOR' => $this->getAccountParam( 'paypal_payflow_vendor' ),
																	'USER' => $this->getAccountParam( 'paypal_payflow_user' ),
																	'PWD' => $this->getAccountParam( 'paypal_payflow_password' ),
																	'TRXTYPE' => 'S',
																	'AMT' => $amount,
																	'CREATESECURETOKEN' => 'Y',
																	'SECURETOKENID' => uniqid(),
																	'TEMPLATE' => $this->getAccountParam( 'template_layout', 'MINLAYOUT' ),
																	'ORDERDESC' => $paymentBasket->item_name,
																	'INVNUM' => $paymentBasket->invoice,
																	'CURRENCY' => $paymentBasket->mc_currency,
																	'USER1' => $paymentBasket->id,
																	'USER2' => $paymentBasket->user_id,
																	'USER3' => $paymentBasket->item_number,
																	'USER4' => ( $subscription ? 'R' : 'S' )
																);

			if ( $subscription ) {
				$request['RECURRING']					=	'Y';
			}

			if ( $this->getAccountParam( 'givehiddenbillemail' ) && ( strlen( $paymentBasket->payer_email ) <= 127 ) ) {
				$request['EMAIL']						=	$paymentBasket->payer_email;
			}

			if ( $this->getAccountParam( 'givehiddenbilladdress' ) ) {
				cbimport( 'cb.tabs' );

				$addressFields							=	array(	'BILLTOFIRSTNAME' => array( $paymentBasket->first_name, 30 ),
																	'BILLTOLASTNAME' => array( $paymentBasket->last_name, 30 ),
																	'BILLTOSTREET' => array( $paymentBasket->address_street, 150 ),
																	'BILLTOZIP' => array( $paymentBasket->address_zip, 9 ),
																	'BILLTOCITY' => array( $paymentBasket->address_city, 45 ),
																	'BILLTOCOUNTRY' => array( $countries->countryToTwoLetters( $paymentBasket->address_country ), 2 )
																);

				if ( $paymentBasket->address_state != 'other' ) {
					$addressFields['BILLTOSTATE']		=	array( substr( $paymentBasket->address_state, -2 ), 2 );
				}

				foreach ( $addressFields as $k => $valueMaxlength ) {
					$adrField							=	cbIsoUtf_substr( $valueMaxlength[0], 0, $valueMaxlength[1] );

					if ( $adrField ) {
						$request[$k]					=	$adrField;
					}
				}
			}

			if ( $this->getAccountParam( 'givehiddenbilltelno' ) && ( strlen( $paymentBasket->contact_phone ) <= 50 ) ) {
				$request['BILLTOPHONENUM']				=	$paymentBasket->contact_phone;
			}

			if ( $this->getAccountParam( 'givehiddenshipemail' ) && ( strlen( $paymentBasket->payer_email ) <= 127 ) ) {
				$request['SHIPTOEMAIL']					=	$paymentBasket->payer_email;
			}

			if ( $this->getAccountParam( 'givehiddenshipaddress' ) ) {
				cbimport( 'cb.tabs' );

				$addressFields							=	array(	'SHIPTOFIRSTNAME' => array( $paymentBasket->first_name, 30 ),
																	'SHIPTOLASTNAME' => array( $paymentBasket->last_name, 30 ),
																	'SHIPTOSTREET' => array( $paymentBasket->address_street, 150 ),
																	'SHIPTOZIP' => array( $paymentBasket->address_zip, 9 ),
																	'SHIPTOCITY' => array( $paymentBasket->address_city, 45 ),
																	'SHIPTOCOUNTRY' => array( $countries->countryToThreeLetters( $paymentBasket->address_country ), 3 )
																);

				if ( $paymentBasket->address_state != 'other' ) {
					$addressFields['SHIPTOSTATE']		=	array( substr( $paymentBasket->address_state, -2 ), 2 );
				}

				foreach ( $addressFields as $k => $valueMaxlength ) {
					$adrField							=	cbIsoUtf_substr( $valueMaxlength[0], 0, $valueMaxlength[1] );

					if ( $adrField ) {
						$request[$k]					=	$adrField;
					}
				}
			}

			if ( $this->getAccountParam( 'givehiddenshiptelno' ) && ( strlen( $paymentBasket->contact_phone ) <= 50 ) ) {
				$request['SHIPTOPHONENUM']				=	$paymentBasket->contact_phone;
			}

			$formUrl									=	array();

			foreach ( $request as $k => $v ) {
				$formUrl[$k]							=	$k . '=' . $v;
			}

			$formUrl									=	implode( '&', $formUrl );

			$results									=	array();
			$response									=	null;
			$status										=	null;
			$error										=	$this->_httpsRequest( $this->gatewayUrl( 'psp' ), $formUrl, 105, $response, $status, 'post', 'normal' );

			if ( $response ) {
				parse_str( $response, $results );
			}

			if ( $error || ( $status != 200 ) || ( ! $response ) ) {
				$this->_setLogErrorMSG( 3, null, $this->getPayName() . ' HTTPS POST request to payment gateway server failed.', CBPTXT::T( "Submitted subscription payment didn't return an error but didn't complete." ) . ' ' . CBPTXT::T( 'Please contact site administrator to check error log.' ) );
			} else {
				if ( cbGetParam( $results, 'RESULT' ) == '0' ) {
					$requestParams['SECURETOKEN']		=	cbGetParam( $results, 'SECURETOKEN' );
					$requestParams['SECURETOKENID']		=	cbGetParam( $results, 'SECURETOKENID' );
				} else{
					$this->_setLogErrorMSG( 3, null, $this->getPayName() . ' Paypal Payflow error returned. ERROR: ' . cbGetParam( $results, 'RESPMSG' ), CBPTXT::T( 'Please contact site administrator to check error log.' ) );
				}
			}
		}

		return $requestParams;
	}
 /**
  * Utility function to return title with description as hover
  *
  * @param  CBSimpleXMLElement  $node
  * @return null|string
  */
 function _title(&$node)
 {
     $description = $node->attributes('description');
     if ($description) {
         $description = CBPTXT::T($description);
         $name = $node->attributes('name');
         return ' title="' . htmlspecialchars($name . '|' . $description) . '"';
     }
     return null;
 }
 /**
  * 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;
 }
 /**
  * Saves record payment view
  *
  * @param  int          $paymentBasketId
  * @return null|string
  */
 public static function saveRecordPayment($paymentBasketId)
 {
     cbpaidApp::loadLang('admin');
     $paymentRecorder = new self();
     $exists = $paymentBasketId && $paymentRecorder->load((int) $paymentBasketId);
     if ($exists) {
         if ($paymentRecorder->authoriseAction('cbsubs.recordpayments')) {
             $return = $paymentRecorder->saveRecordPaymentForm();
         } else {
             $return = CBPTXT::T("You are not authorized to record payments.");
         }
     } else {
         $return = CBPTXT::T("No unpaid payment basket found.");
     }
     return $return;
 }
	/**
	 * Finds file and returns absolute file path
	 *
	 * @param  string      $layout       one word name
	 * @param  string      $extension    '.php' or '.css'
	 * @return string|null
	 */
	protected function _file_path( $layout, $extension ) {
		global $_CB_framework;

		$saneLayout						=	( $layout ? preg_replace( '/\W/', '', strtolower( $layout ) ) : 'default' ) . $extension;
		if ( $extension === '.php' ) {
			$absPrefix					=	$_CB_framework->getCfg( 'absolute_path' );
			$chkPrefix					=	'';
			$saneLayout					=	$this->viewName . '/' . $saneLayout;
		} else {
			$absPrefix					=	'';
			$chkPrefix					=	$_CB_framework->getCfg( 'absolute_path' );
		}
		$cmsTemplate					=	$this->_cmsCurrentTemplate();
		$overrideFilePath				=	'/templates/' . $cmsTemplate . '/html/com_comprofiler/' . $this->_overrideSubFolder . '/';
		if ( $cmsTemplate && file_exists( $chkPrefix . $absPrefix . $overrideFilePath . $saneLayout ) ) {
			$this->_tmplUsedPath		=	$overrideFilePath;
			return $absPrefix . $overrideFilePath . $saneLayout;
		} else {
			$internalFilePath			=	'/components/com_comprofiler/' . $this->_defaultTemplatePath . '/' . $this->templateToUse() . '/';
			if ( file_exists( $chkPrefix . $absPrefix . $internalFilePath . $saneLayout ) ) {
				$this->_tmplUsedPath	=	$internalFilePath;
				return $absPrefix . $internalFilePath . $saneLayout;
			} else {
				$defaultInternalFilePath =	'/components/com_comprofiler/' . $this->_defaultTemplatePath . '/' . 'default' . '/';
				if ( ( $this->templateToUse() != 'default' ) && file_exists( $chkPrefix . $absPrefix . $defaultInternalFilePath . $saneLayout ) ) {
					$this->_tmplUsedPath =	$defaultInternalFilePath;
					return $absPrefix . $defaultInternalFilePath . $saneLayout;
				} else {
					// $method					=	'_render' . $layout;
					// if ( is_callable( array( $this, $method ) ) ) {
					//	$this->$method();
					// } else {
					trigger_error( sprintf( CBPTXT::T("CB View %s Layout %s has no rendering file %s."), $this->viewName, $saneLayout, $absPrefix . $internalFilePath . $saneLayout ), E_USER_NOTICE );
					// }
				}
			}
		}
		return null;
	}
	/**
	 * 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;
	}
 /**
  * Renders the rate of $this payment item
  *
  * @param  string       $variable
  * @param  boolean      $html       TRUE: HTML rendering, FALSE: TEXT rendering
  * @param  boolean      $rounded
  * @return string|null
  */
 public function renderItemRate($variable, $html, $rounded = false)
 {
     $first_var = 'first_' . $variable;
     $cbpaidMoney = cbpaidMoney::getInstance();
     if (!$this->_paymentBasket->isAnyAutoRecurring()) {
         return $cbpaidMoney->renderPrice($this->{$variable}, $this->currency, $html, $rounded, false);
     } else {
         if ($this->{$first_var} || $this->{$variable}) {
             $first = $cbpaidMoney->renderPrice($this->{$first_var}, $this->currency, $html, $rounded, false);
             $then = $cbpaidMoney->renderPrice($this->{$variable}, $this->currency, $html, $rounded, false);
             if ($this->{$first_var} && $this->{$variable} === null) {
                 // $ret	=	$first;		// replacing this line by next one fixes bug #3624 at display time
                 $ret = sprintf($html ? CBPTXT::Th("%s, then %s") : CBPTXT::T("%s, then %s"), $first, $then);
             } elseif ($this->{$variable} && $this->{$first_var} === null) {
                 $ret = $then;
             } elseif ($this->{$first_var} === $this->{$variable} && $this->_paymentBasket->period1 == null) {
                 $ret = $first;
             } else {
                 $ret = sprintf($html ? CBPTXT::Th("%s, then %s") : CBPTXT::T("%s, then %s"), $first, $then);
             }
         } else {
             if ($variable == 'rate' && $this->rate !== null) {
                 $ret = $cbpaidMoney->renderPrice($this->{$variable}, $this->currency, $html, $rounded, false);
             } else {
                 $ret = null;
             }
         }
     }
     return $ret;
 }
	/**
	 * Get a correct display of the formatted validity of a plan
	 *
	 * @return string                     Formatted text giving validity of this subscription
	 */
	public function getFormattedValidityRemaining() {
		if ( ( $this->status == 'A' ) && ( $this->expiry_date == '0000-00-00 00:00:00' ) ) {
			$params				=&	cbpaidApp::settingsParams();
			return CBPTXT::T( $params->get( 'regtextLifetime', 'Lifetime Subscription' ) );
		} else {
			$occurrence			=	$this->regular_recurrings_used;
			if ( $occurrence > 0 ) {
				$reason			=	'R';
			} elseif ( $this->replaces_plan && $this->replaces_subscription ) {
				$reason			=	'U';
			} else {
				$reason			=	'N';
			}
			$varName			=	$this->getPlan()->getPlanVarName( $reason, $occurrence, 'validity' );
			return $this->getPlan()->getFormattedValidity( $this->getPlan()->strToTime( $this->expiry_date ), $this->getPlan()->strToTime( $this->subscription_date ), $varName );
		}
	}
	/**
	 * Prepares ARB request (check outside of this that amount is in USD !!!!
	 *
	 * @param  string				 $arbRequestType : 'CreateSubscription', 'UpdateSubscription', 'CancelSubscription'
	 * @param  array|null			 $card : $card['type'], $card['number'], $card['firstname'], $card['lastname'], $card['expmonth'], $card['expyear'], and optionally: $card['address'], $card['zip'], $card['country']
	 * @param  cbpaidPaymentBasket	 $paymentBasket		WARNING: Using mc_amount3 as price as it's a subscription, instead of mc_gross.
	 * @param  string				 $subscriptionId
	 * @return mixed				 string of XML request 
	 */
	private function _encodeArbXmlRequest( $arbRequestType, $card, &$paymentBasket, $subscriptionId = null )
	{
		$authorize_login_id			= $this->ISOtoUtf8( $this->getAccountParam( 'authorize_login_id' ) );
		$authorize_transaction_key	= $this->ISOtoUtf8( $this->getAccountParam( 'authorize_transaction_key' ) );
		$refId						= $this->ISOtoUtf8( $paymentBasket->id );

		if ( $arbRequestType != 'CancelSubscription' ) {

			// CreateSubscription or UpdateSubscription:

			$cardNumber					= substr( preg_replace ( '/[^0-9]+/', '', strval( $card['number'] ) ), 0, 16 );
			$cardExpirationDate			= substr( strval( intval( $card['expyear'] ) ), 0, 4 ) . '-' . substr( sprintf( '%02d', intval( $card['expmonth'] ) ), 0, 2 );
			$firstName					= $this->_cbp_utf8_substr( $this->ISOtoUtf8( $card['firstname'] ), 0, 50 );
			$lastName					= $this->_cbp_utf8_substr( $this->ISOtoUtf8( $card['lastname'] ), 0, 50 );
			$email						= $this->_cbp_utf8_substr( $this->ISOtoUtf8( $paymentBasket->payer_email ), 0, 255 );
			$country					= ( isset( $card['country'] ) ? $this->_cbp_utf8_substr( $this->ISOtoUtf8( $card['country'] ), 0, 60 ) : null );
			$zip						= ( isset( $card['zip'] ) ? $this->_cbp_utf8_substr( $this->ISOtoUtf8( $card['zip'] ), 0, 20 ) : null );
			$address					= ( isset( $card['address'] ) ? $this->_cbp_utf8_substr( $this->ISOtoUtf8( $card['address'] ), 0, 60 ) : null );

			if ( $arbRequestType == 'CreateSubscription' ) {

				$subscriptionName			= $this->_cbp_utf8_substr( $this->ISOtoUtf8( $paymentBasket->item_name ), 0, 20 );
				$subscriptionDescription	= $this->_cbp_utf8_substr( $this->ISOtoUtf8( $paymentBasket->item_name ), 0, 255 );

				$subscriptionTiming			= $this->_computeSubscriptionTiming( $paymentBasket, 'noUpfrontFirstCharge', $card );
				if ( $subscriptionTiming['totalOccurrences'] == 0 ) {
					return array( CBPTXT::T("Credit card expiry too short for subscribing to any automatically re-occurrings payments at this time.") . ' ' . CBPTXT::T("Please renew from your subscriptions in time.") );
				}
				$amount						= sprintf( '%.2f', $paymentBasket->mc_amount3 );
				$trialAmount				= null;
				if ( $paymentBasket->mc_currency != 'USD' ) {
					trigger_error('Authorize.net ARB API handles only USD, not ' . $paymentBasket->mc_currency, E_USER_ERROR );
				}

				//Build XML to post
				$content =	  "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
					. "<ARBCreateSubscriptionRequest xmlns=\"AnetApi/xml/v1/schema/AnetApiSchema.xsd\">\n"
					. "  <merchantAuthentication>\n"
					. "    <name>"				. htmlspecialchars( $authorize_login_id )			. "</name>\n"
					. "    <transactionKey>"	. htmlspecialchars( $authorize_transaction_key )	. "</transactionKey>\n"
					. "  </merchantAuthentication>\n"
					. "  <refId>"				. htmlspecialchars( $refId )						. "</refId>\n"
					. "  <subscription>\n"
					. "    <name>"				. htmlspecialchars( $subscriptionName )			. "</name>\n"
					. "    <paymentSchedule>\n"
					. "      <interval>\n"
					. "        <length>"		. htmlspecialchars( $subscriptionTiming['intervalLength'] )	. "</length>\n"
					. "        <unit>"			. htmlspecialchars( $subscriptionTiming['intervalUnit'] )		. "</unit>\n"
					. "      </interval>\n"
					. "      <startDate>"		. htmlspecialchars( $subscriptionTiming['startDate'] )			. "</startDate>\n"
					. "      <totalOccurrences>". htmlspecialchars( $subscriptionTiming['totalOccurrences'] )	. "</totalOccurrences>\n";
				if ( $trialAmount ) {
					$content .= "      <trialOccurrences>". '1'							. "</trialOccurrences>\n";
				}
				$content .=   "    </paymentSchedule>\n"
					. "    <amount>"			. htmlspecialchars( $amount )						. "</amount>\n";
				if ( $trialAmount ) {
					$content .= "    <trialAmount>"		. htmlspecialchars( $trialAmount )				. "</trialAmount>\n";
				}
				$content .=   "    <payment>\n"
					. "      <creditCard>\n"
					. "        <cardNumber>"	. htmlspecialchars( $cardNumber )					. "</cardNumber>\n"
					. "        <expirationDate>". htmlspecialchars( $cardExpirationDate )		. "</expirationDate>\n"
					. "      </creditCard>\n"
					. "    </payment>\n"
					. "    <order>\n"
					. "      <invoiceNumber>"	. htmlspecialchars( $paymentBasket->invoice ? $paymentBasket->invoice : $paymentBasket->id )			. "</invoiceNumber>\n"
					. "      <description>"		. htmlspecialchars( $subscriptionDescription )	. "</description>\n"
					. "    </order>\n"
					. "    <customer>\n"
					. "      <id>"				. htmlspecialchars( $paymentBasket->user_id )		. "</id>\n"
					. "      <email>"			. htmlspecialchars( $email )						. "</email>\n"
					. "    </customer>\n"
					. "    <billTo>\n"
					. "      <firstName>"		. htmlspecialchars( $firstName )					. "</firstName>\n"
					. "      <lastName>"		. htmlspecialchars( $lastName )						. "</lastName>\n"
					. ( $address !== null ?
						"      <address>"			. htmlspecialchars( $address )						. "</address>\n"
						: ''
					)
					. ( $zip !== null ?
						"      <zip>"				. htmlspecialchars( $zip )							. "</zip>\n"
						: ''
					)
					. ( $country !== null ?
						"      <country>"			. htmlspecialchars( $country )						. "</country>\n"
						: ''
					)
					. "    </billTo>\n"
					. "  </subscription>\n"
					. "</ARBCreateSubscriptionRequest>\n";

			} elseif ( $arbRequestType == 'UpdateSubscription' ) {

				//Build XML to post
				$content =	  "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
					. "<ARBUpdateSubscriptionRequest xmlns=\"AnetApi/xml/v1/schema/AnetApiSchema.xsd\">\n"
					. "  <merchantAuthentication>\n"
					. "    <name>"				. htmlspecialchars( $authorize_login_id )			. "</name>\n"
					. "    <transactionKey>"	. htmlspecialchars( $authorize_transaction_key )	. "</transactionKey>\n"
					. "  </merchantAuthentication>\n"
					. "  <refId>"				. htmlspecialchars( $refId )						. "</refId>\n"
					. "  <subscriptionId>"		. htmlspecialchars( $subscriptionId )				. "</subscriptionId>\n"
					. "  <subscription>\n"
					. "    <payment>\n"
					. "      <creditCard>\n"
					. "        <cardNumber>"	. htmlspecialchars( $cardNumber )					. "</cardNumber>\n"
					. "        <expirationDate>". htmlspecialchars( $cardExpirationDate )		. "</expirationDate>\n"
					. "      </creditCard>\n"
					. "    </payment>\n"
					. "    <customer>\n"
					. "      <id>"				. htmlspecialchars( $paymentBasket->user_id )		. "</id>\n"
					. "      <email>"			. htmlspecialchars( $email )						. "</email>\n"
					. "    </customer>\n"
					. "    <billTo>\n"
					. "      <firstName>"		. htmlspecialchars( $firstName )					. "</firstName>\n"
					. "      <lastName>"		. htmlspecialchars( $lastName )					. "</lastName>\n"
					. ( $address !== null ?
						"      <address>"			. htmlspecialchars( $address )						. "</address>\n"
						: ''
					)
					. ( $zip !== null ?
						"      <zip>"				. htmlspecialchars( $zip )							. "</zip>\n"
						: ''
					)
					. ( $country !== null ?
						"      <country>"			. htmlspecialchars( $country )						. "</country>\n"
						: ''
					)
					. "    </billTo>\n"
					. "  </subscription>\n"
					. "</ARBUpdateSubscriptionRequest>\n";

			} else {
				$content	=	null;
			}
		} else {	// 'CancelSubscription':

			//Build XML to post
			$content =	  "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
				. "<ARBCancelSubscriptionRequest xmlns=\"AnetApi/xml/v1/schema/AnetApiSchema.xsd\">\n"
				. "  <merchantAuthentication>\n"
				. "    <name>"				. htmlspecialchars( $authorize_login_id )			. "</name>\n"
				. "    <transactionKey>"	. htmlspecialchars( $authorize_transaction_key )	. "</transactionKey>\n"
				. "  </merchantAuthentication>\n"
				. "  <refId>"				. htmlspecialchars( $refId )						. "</refId>\n"
				. "  <subscriptionId>"		. htmlspecialchars( $subscriptionId )				. "</subscriptionId>\n"
				. "</ARBCancelSubscriptionRequest>\n";

		}
		return $content;
	}
 /**
  * Redirects expired user to the re-subscription screen.
  * @access private
  * @param  int  $userId
  */
 protected function _redirectExpiredMembership($userId)
 {
     global $_CB_framework;
     $params = cbpaidApp::settingsParams();
     $paidUserExtension = cbpaidUserExtension::getInstance($userId);
     $expiredSubscriptions = $paidUserExtension->getUserSubscriptions('X');
     // check if there is any expired extensions for the text
     if (count($expiredSubscriptions) > 0) {
         $textMessage = $params->get('subscriptionExpiredText', "Your membership has expired.");
         $expiredRedirectLink = $params->get('subscriptionExpiredRedirectLink');
     } else {
         $textMessage = $params->get('subscriptionNeededText', "A membership is needed for access.");
         $expiredRedirectLink = $params->get('subscriptionNeededRedirectLink');
     }
     if (!$expiredRedirectLink) {
         $baseClass = cbpaidApp::getBaseClass();
         if ($baseClass) {
             $expiredRedirectLink = $baseClass->_getAbsURLwithParam(array('Itemid' => 0, 'account' => 'expired', 'user' => (int) $userId), 'pluginclass', false);
         } else {
             // without baseClass, as baseClass is not loaded in case of cbpaidsubsbot:
             $cbpPrefix = 'cbp';
             $expiredRedirectLink = 'index.php?option=com_comprofiler&task=pluginclass&plugin=cbpaidsubscriptions&' . $cbpPrefix . 'account=expired&user='******'index.php?option=com_comprofiler&task=pluginclass&plugin=cbpaidsubscriptions&do=display_subscriptions';		// &Itemid= ???
         }
         if ($userId) {
             $_SESSION['cbsubs']['expireduser'] = $userId;
         }
     }
     if ($_CB_framework->getRequestVar('option') != 'com_comprofiler' || $_CB_framework->getRequestVar('task') != 'pluginclass' || $_CB_framework->getRequestVar('plugin') != 'cbpaidsubscriptions') {
         cbRedirect(cbSef($expiredRedirectLink, false), CBPTXT::T($textMessage), 'warning');
     }
 }
Exemplo n.º 30
0
	/**
	 * Auxiliary function for replacing texts when extending XML
	 * <replaces translate="yes"><replace attribute="label OR [DATA]" from="{source}" to="target" />
	 *
	 * @param  CBSimpleXMLElement|string|array $sourceData
	 * @param  CBSimpleXMLElement              $sourceNode
	 * @param  CBSimpleXMLElement              $destinationParentNode
	 * @param  CBObject                        $paramsView
	 */
	static function _substituteChildTexts( $sourceData, $sourceNode = null, $destinationParentNode = null, $paramsView = null ) {
		static $substitutions	=	array();
		if ( is_array( $sourceData ) ) {
			// that is $source->attributes():
			$return				=	array();
			foreach ($sourceData as $k => $v ) {
				if ( isset( $substitutions[$k] ) ) {
					$v			=	str_replace( $substitutions[$k]['from'], $substitutions[$k]['to'], $v );
					if ( $substitutions[$k]['translate'] ) {
						$v		=	CBPTXT::T( $v );
					}
				}
				$return[$k]		=	$v;
			}
		} elseif ( is_string( $sourceData ) ) {
			// that is $source->data():
			if ( isset( $substitutions['[DATA]'] ) ) {
				$k				=	'[DATA]';
				$return			=	str_replace( $substitutions[$k]['from'], $substitutions[$k]['to'], $sourceData );
				if ( $substitutions[$k]['translate'] ) {
					$return		=	CBPTXT::T( $return );
				}
			} else {
				$return			=	$sourceData;
			}
		} elseif ( is_object( $sourceData ) ) {
			// initialize replacements:
			$substitutions		=	array();
			foreach ($sourceData->children() as $replaceRule ) {
				$substitutions[$replaceRule->attributes( 'attribute' )]['from'][]			=	$replaceRule->attributes( 'from' );
				$substitutions[$replaceRule->attributes( 'attribute' )]['to'][]				=	( $replaceRule->attributes( 'type' ) == 'datavalue:string' ? $paramsView->get( $replaceRule->attributes( 'to' ) ) : $replaceRule->attributes( 'to' ) );
				$substitutions[$replaceRule->attributes( 'attribute' )]['translate']		=	$replaceRule->attributes( 'translate' ) === 'yes';
			}
			$return				=	null;
		}
		return $return;
	}