/**
  * 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();
 }
 /**
  * Draws the user profile tab "Subscriptions" (if enabled, user is the profile owner, and something to display.
  * 
  * @param  string  $htmlSubscriptionsAndUpgrades
  * @param  string  $htmlInvoicesLink
  * @param  string  $tabTitleText
  * @param  string  $htmlTabDescription
  * @return string
  */
 public function drawTab($htmlSubscriptionsAndUpgrades, $htmlInvoicesLink, $tabTitleText, $htmlTabDescription)
 {
     global $ueConfig;
     $this->htmlSubscriptionsAndUpgrades = $htmlSubscriptionsAndUpgrades;
     $this->htmlInvoicesLink = $htmlInvoicesLink;
     $this->htmlTabDescription = $htmlTabDescription;
     $user = $this->_model;
     $title = cbReplaceVars(CBPTXT::Th(cbUnHtmlspecialchars($tabTitleText)), $user);
     if ($title) {
         $name = getNameFormat($user->name, $user->username, $ueConfig['name_format']);
         $title = sprintf($title, $name);
     }
     $this->htmlTabTitle = $title;
     return $this->display();
 }
 /**
  * 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();
 }
 /**
  * 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 ? ' - ' : ' - ') . 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 ? ' - ' : ' - ') . 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;
 }
 /**
  * Saves invoicing address, and if error, sets error to baseClass and
  * Renders the edit form for the invoicing address for that basket again.
  *
  * @return string|null                             NULL if no error, otherwise HTML for edit.
  */
 protected function saveRecordPaymentForm()
 {
     if ($this->authoriseAction('cbsubs.recordpayments')) {
         $return = $this->bindFromFormPost('recordpayment', 'recordpayment');
         if ($return === null) {
             $this->store();
         }
     } else {
         $return = CBPTXT::Th("Not authorized");
     }
     return $return;
 }
Пример #6
0
	/**
	 * Returns HTML or TEXT rendering the validity period and pricing for that given plan.
	 * (public because can be used as call-back in onCPayAfterDisplayProductPeriodPrice event handlers)
	 *
	 * @param  float        $price                 price of plan
	 * @param  float|null   $firstPeriodFullPrice  regular price of plan in first period
	 * @param  float|null   $firstPeriodPrice      real price of plan in first period (with discount)
	 * @param  boolean      $prorateDiscount       is a discount applied to first price ?
	 * @param  int          $expiryTime            expiry time of plan
	 * @param  int          $startTime             starting time of plan
	 * @param  boolean      $autorecurring         is plan autorecurring ?
	 * @param  int          $recurring_max_times   if autorecurring, maximum total number of occurrences
	 * @param  string       $reason                payment reason: 'N'=new subscription (default), 'R'=renewal, 'U'=update
	 * @param  int          $occurrence            Occurence of the payment for that item
	 * @param  boolean      $html                  TRUE for HTML, FALSE for TEXT
	 * @param  boolean      $roundings             TRUE: do round, FALSE: do not round display
	 * @param  boolean      $displayPeriod         TRUE: display price and period, FALSE: display price only (ONLY for single prices)
	 * @param  boolean       $displaySecondaryCurrency   TRUE: display secondary currencies, FALSE: only display in $this->currency()
	 * @return string                              HTML or TEXT
	 */
	public function renderPeriodPrice( $price, $firstPeriodFullPrice, $firstPeriodPrice, $prorateDiscount, $expiryTime, $startTime,
									   $autorecurring, $recurring_max_times, $reason, $occurrence, $html, $roundings = true, $displayPeriod = true, $displaySecondaryCurrency = true ) {
		global $_CB_framework;

		$params							=&	cbpaidApp::settingsParams();
		$return							=	'';

		$priceDisplay					=	$this->getPriceDisplay();	// This is used in this class if available (it's actually only available in derived class cbpaidProduct and in all its derived classes)
		if ( $priceDisplay == null ) {
			$priceDisplay				=	'[automatic]';
		} else {
			$priceDisplay				=	( $html ? CBPTXT::Th( $priceDisplay ) : CBPTXT::T( $priceDisplay ) );
		}
		$period_for_price_text			=	$params->get('period_for_price_text', '%1s%2s%3s' );
		$textFor						=	' ' . ( $html ? CBPTXT::Th($params->get('regtextFor')) : CBPTXT::T($params->get('regtextFor')) ) . ' ';

		$priceText						=	$this->renderPricesWithConversion( $price, $html, $roundings, $displaySecondaryCurrency );

		if ( $firstPeriodFullPrice !== null ) {
			$firstPeriodFullPriceText	=	$this->renderPricesWithConversion( $firstPeriodFullPrice, $html, $roundings, $displaySecondaryCurrency );
		} else {
			$firstPeriodFullPriceText	=	null;
		}
		if ( $firstPeriodPrice !== null ) {
			$discountedPriceText		=	$this->renderPricesWithConversion( $firstPeriodPrice, $html, $roundings, $displaySecondaryCurrency );
		} else {
			$discountedPriceText		=	null;
		}

		if ( $firstPeriodFullPrice !== null ) {
			$effectiveFirstPeriodFullPrice		=	$firstPeriodFullPrice;
			$effectiveFirstPeriodFullPriceText	=	$firstPeriodFullPriceText;
		} else {
			$effectiveFirstPeriodFullPrice		=	$price;
			$effectiveFirstPeriodFullPriceText	=	$priceText;
		}
		$firstPeriodRendered = null;
		if ( ( $this->bonustime!='0000-00-00 00:00:00' && $reason!='R') || ( ( $firstPeriodPrice || $prorateDiscount ) && ( $effectiveFirstPeriodFullPrice != $firstPeriodPrice ) ) ) {
			if ( ( $firstPeriodPrice || $prorateDiscount ) && ( $effectiveFirstPeriodFullPrice != $firstPeriodPrice ) ) {
				if ( $autorecurring ) {
					if ( $reason == 'U' ) {
						if ( $prorateDiscount ) {
							$subTxt				=	CBPTXT::T( $params->get( 'subscription_name', 'subscription' ) );
							$t	= sprintf( CBPTXT::T("The first payment of the upgrade for %s, taking in account your current %s, is %s instead of %s."), '%s', $subTxt, '%s', '%s' );
						} else {
							$t	= CBPTXT::T("The first payment of the upgrade for %s is %s instead of %s.");
						}
					} elseif ( $reason == 'R' ) {
						if ( $prorateDiscount ) {
							$t	= CBPTXT::T("The first payment of the renewal for %s, pro-rata temporis, is %s instead of %s.");
						} else {
							$t	= CBPTXT::T("The first payment of the renewal for %s is %s instead of %s.");
						}
					} else {
						if ( $prorateDiscount ) {
							$t	= CBPTXT::T("The first payment for %s, pro-rata temporis, is %s instead of %s.");
						} else {
							$t	= CBPTXT::T("The first payment for %s is %s instead of %s.");
						}
					}
				} else {
					if ( $reason == 'U' ) {
						if ( $prorateDiscount ) {
							$subTxt				=	CBPTXT::T( $params->get( 'subscription_name', 'subscription' ) );
							$t	= sprintf( CBPTXT::T("The price of the upgrade for %s, taking in account your current %s, is %s instead of %s."), '%s', $subTxt, '%s', '%s' );
						} else {
							$t	= CBPTXT::T("The price of the upgrade for %s is %s instead of %s.");
						}
					} elseif ( $reason == 'R' ) {
						if ( $prorateDiscount ) {
							$t	= CBPTXT::T("The price of the renewal for %s, pro-rata temporis, is %s instead of %s.");
						} else {
							$t	= CBPTXT::T("The price of the renewal for %s is %s instead of %s.");
						}
					} else {
						if ( $prorateDiscount ) {
							$t	= CBPTXT::T("The price for %s, pro-rata temporis, is %s instead of %s.");
						} else {
							$t	= CBPTXT::T("The price for %s is %s instead of %s.");
						}
					}
				}
				$varName				=	$this->getPlanVarName( $reason, $occurrence, 'validity' );
				$firstPeriodRendered	=	sprintf( $t, $this->getFormattedValidity( $expiryTime, $startTime, $varName, $reason, 1, true, $html ),
					$discountedPriceText, $effectiveFirstPeriodFullPriceText );
			} else {
				if ( $autorecurring ) {
					if ( $reason == 'U' ) {
						$t	= CBPTXT::T("The first period for the upgrade will be %s.");
					} elseif ( $reason == 'R' ) {
						$t	= CBPTXT::T("The first period for the renewal will be %s.");
					} else {
						$t	= CBPTXT::T("The first period will be %s.");
					}
					$varName				=	$this->getPlanVarName( $reason, $occurrence, 'validity' );
					$firstPeriodRendered	=	sprintf( $t, $this->getFormattedValidity( $expiryTime, $startTime, $varName, $reason, 1, true, $html ) );
				}
			}
		}

		cbimport( 'cb.tabs' );		//needed for CBuser and replacements

		if ( ( $firstPeriodFullPrice === null ) && ! $autorecurring ) {
			$validityText	=	$this->getFormattedValidity( $expiryTime, $startTime, 'validity', $reason, 1, true, $html );
			if ( ( $validityText != '' ) && $displayPeriod ) {
				$period		=	$this->_span( $validityText,	$html, 'cbregTimeframe', false );
				$for		=	$this->_span( $textFor					,	$html, 'cbregFor', false );
			} else {
				$period		=	'';					// in case 'lifetime' text is ''
				$for		=	'';
			}
			if ( $priceText != '' ) {
				$money		=	$this->_span( $priceText				,	$html, 'cbregRate', false );
			} else {
				$for		=	'';					// in case 'Free' text is ''
				$money		=	'';
			}
			$automatic		=	sprintf( $period_for_price_text, $period, $for, $money );
			if ( strtolower( $priceDisplay ) == '[automatic]' ) {
				$return		.=	$automatic;
			} else {
				$per		=	$this->_span(  ' ' . ( $html ? CBPTXT::Th("per") : CBPTXT::T("per") ) . ' '		,	$html, 'cbregFor', false );
				$cbUser		=	CBuser::getInstance( $_CB_framework->myId() );
				$return		=	$cbUser->replaceUserVars( $priceDisplay, true, false );
				$return		=	str_ireplace( array( '[price]', '[for]', '[period]', '[per]', '[automatic]' ), array( $money, $for, $period, $per, $automatic ), $return );
			}
		} else {
			if ( $firstPeriodFullPrice !== null ) {
				$moneyFirst	=	$this->_span( $firstPeriodFullPriceText	,	$html, 'cbregRate', false );
				$forFirst	=	$this->_span( $textFor						,	$html, 'cbregFor', false );
				$varName	=	$this->getPlanVarName( $reason, $occurrence, 'validity' );
				$periodFirst =	$this->_span( $this->_renderPeriodOfValiditiy( $varName, 1 )	,	$html, 'cbregTimeframe' );
				$then		=	$this->_span( ( $html ? CBPTXT::Th(", then ")	: CBPTXT::T(", then ")	)			,	$html, 'cbregFor', false );
				// $automatic .=	$this->_timedObject->getFormattedValidity( $expiryTime, $startTime, false );
				$automatic	=	sprintf( $period_for_price_text, $periodFirst, $forFirst, $moneyFirst )
					.	$then;
			} else {
				$moneyFirst	=	null;
				$forFirst	=	null;
				$periodFirst =	null;
				$then		=	null;
				$automatic	=	'';
			}
			$money			=	$this->_span( $priceText						,	$html, 'cbregRate', false );
			if ( $price ) {
				$per		=	$this->_span(  ' ' . ( $html ? CBPTXT::Th("per") : CBPTXT::T("per") ) . ' '		,	$html, 'cbregFor', false );
				$period		=	$this->_span( $this->_renderPeriodOfValiditiy( 'validity', 1, false )	,	$html, 'cbregTimeframe' );
				$automatic	.=	sprintf( '%3$s%2$s%1$s', $period, $per, $money );
			} else {
				$per		=	null;
				$period		=	null;
				$automatic	.=	$money;
			}
			if ( $recurring_max_times ) {
				$during		=	$this->_span( ', ' . ( $html ? CBPTXT::Th("during") : CBPTXT::T("during") ) . ' ',	$html, 'cbregFor', false );
				$periodTot	=	$this->_span( $this->_renderPeriodOfValiditiy( 'validity', $recurring_max_times, true, false )	,	$html, 'cbregTimeframe' );
				$automatic	.=	$during . $periodTot;
			} else {
				$during		=	null;
				$periodTot	=	null;
			}

			if ( strtolower( $priceDisplay ) == '[automatic]' ) {
				$return		.=	$automatic;
			} else {
				$cbUser		=	CBuser::getInstance( $_CB_framework->myId() );
				$return		=	$cbUser->replaceUserVars( $priceDisplay, true, false );
				$return		=	str_ireplace( array( '[price]', '[per]', '[period]', '[for]', '[firstperiod]', '[firstfor]', '[firstprice]', '[then]', '[during]', '[totalperiod]', '[automatic]' ),
					array( $money, $per, $period, $textFor, $periodFirst, $forFirst, $moneyFirst, $then, $during, $periodTot, $automatic ), $return );
			}
		}
		if ( $firstPeriodRendered ) {
			$return			.=	' ' . $this->_span( $firstPeriodRendered											,	$html, 'cbregDiscountRate', false );
		}
		return $return;
	}
Пример #7
0
?>
	<button type="submit" class="button" name="addcouponcode" value="1" style="position:absolute;left:-9999px;top:-9999px;height:0;width:0;">Add</button>
	<div class="cbregCouponsInputed">
		<ul class="cbregListOfCouponsInputed">
<?php 	foreach ( $this->couponsUsed as $coupon ) { ?>
			<li>
				<span class="cbregCouponCode"><?php echo $coupon->coupon_code; ?></span><span class="cbregCouponCodeSAeparator">:</span>
				<span class="cbregCouponName"><?php echo $coupon->name; ?></span>
				<span class="cb_button_wrapper_small cpay_button_couponcode_wrapper cbregCouponDelete"><button type="submit" class="button" name="deletecouponcode[<?php echo $coupon->id;?>]" value="1"><?php echo CBPTXT::Th( $this->couponRemoveButtonText ); ?></button></span>
			</li>
<?php	} ?>
		</ul>
	</div>
<?php } ?>
	<div class="cbregCouponInput">
		<label for="cbsubscouponcode"><span><?php echo CBPTXT::Th( $this->couponLabelText ); ?></span></label>
		<input name="couponcode" id="cbsubscouponcode" type="text" />
		<span class="cb_button_wrapper_small cpay_button_couponcode_wrapper"><button type="submit" class="button" name="addcouponcode" value="1"><?php echo CBPTXT::Th( $this->couponAddButtonText ); ?></button></span>
		<span class="cbsubscouponInstructions"><?php echo CBPTXT::Th( $this->couponDescription ); ?></span>
		<?php if ( count( $this->couponDescriptionHints ) > 0 ) { ?>
		<div class="cbsubscouponsHints">
			<?php foreach ( $this->couponDescriptionHints as $htmlDescription ) { ?>
			<div class="cbsubsCouponsHint">
				<?php echo $htmlDescription; ?>
			</div>
			<?php } ?>
		</div>
		<?php } ?>
	</div>
</div>
	/**
	 * Gives links for maintenance of an invoice/basket in the list of invoices in frontend
	 *
	 * @return array   of HTML links
	 */
	public function renderMaintenanceButtonsHtml( ) {
		$html				=	array();
		if ( $this->authoriseAction( 'cbsubs.recordpayments' ) ) {
			if ( $this->payment_status == 'Pending') {
				$html[]		=	'<a href="' . cbpaidApp::getBaseClass()->getRecordPaymentUrl( $this ) . '" class="cbregLinkRecordPayment">'
					.	CBPTXT::Th("Record offline payment")
					.	'</a>';
			}
		}
		return $html;
	}
<?php

/**
* @version $Id: $
* @package CBSubs (TM) Community Builder Plugin for Paid Subscriptions (TM)
* @subpackage Template for Paid Subscriptions
* @copyright (C) 2007-2015 and Trademark of Lightning MultiCom SA, Switzerland - www.joomlapolis.com - and its licensors, all rights reserved
* @license http://www.gnu.org/licenses/old-licenses/gpl-2.0.html GNU/GPL version 2
*/
/** ensure this file is being included by a parent file */
if (!(defined('_VALID_CB') || defined('_JEXEC') || defined('_VALID_MOS'))) {
    die('Direct Access to this location is not allowed.');
}
$tmplVersion = 1;
// This is the template version that needs to match
?>
	<div class="contentheading" id="cbregInvoicesTitle"><?php 
echo $this->plansTitle;
?>
</div>
	<div class="cbregLinkToInvoices">
		<a href="<?php 
echo $this->invoicesListUrl;
?>
">
			<?php 
echo CBPTXT::Th("Click here to view the list of invoices");
?>
		</a>
	</div>
 /**
  * Returns an array for the 'radios' array of $redirectNow type:
  * return array( account_id, submethod, paymentMethod:'single'|'subscribe', array(cardtypes), 'label for radio', 'description for radio' )
  * 
  * @param  cbpaidPaymentBasket  $paymentBasket  paymentBasket object
  * @param  string               $subMethod
  * @param  string               $paymentType
  * @param  string               $defaultLabel
  * @return array
  */
 private function getPayRadioRecepie($paymentBasket, $subMethod, $paymentType, $defaultLabel)
 {
     if ($paymentType == 'psp') {
         $cardtypesString = $this->getAccountParam($paymentType . '_radio_cardtypes');
         $cardtypes = $cardtypesString ? explode('|*|', $cardtypesString) : array();
     } else {
         $cardtypes = array($paymentType);
     }
     $brandLabelHtml = $this->getAccountParam($paymentType . '_radio_name', $defaultLabel);
     // CBPTXT::T("Credit Card")
     $brandDescriptionHtml = CBPTXT::Th($this->getAccountParam($paymentType . '_radio_description'));
     if ($brandLabelHtml === null) {
         $brandLabelHtml = CBPTXT::Th($this->getAccountParam('psp_human_name'));
     } else {
         $brandLabelHtml = CBPTXT::Th($brandLabelHtml);
     }
     if ($this->getAccountParam('payment_methods_selection') == 'onsite') {
         $currencies = $this->getAccountParam($paymentType . '_currencies');
     } else {
         $currencies = $this->getAccountParam('currencies_accepted');
     }
     $payNameForCssClass = $this->getPayName();
     if ($currencies == '' || in_array($paymentBasket->mc_currency, explode('|*|', $currencies))) {
         $paySafelyWith = CBPTXT::T($this->getAccountParam('button_title_text'));
         $altText = strip_tags(sprintf($paySafelyWith, $brandLabelHtml));
     } else {
         if ($this->getAccountParam('payment_methods_selection') == 'onsite') {
             $altText = CBPTXT::T($this->getAccountParam($paymentType . '_currencies_description'));
         } else {
             $altText = CBPTXT::T($this->getAccountParam('currency_acceptance_text'));
         }
         $payNameForCssClass .= ' ' . 'cbregconfirmtitleonclick';
     }
     return cbpaidGatewaySelectorRadio::getPaymentRadio($this->getAccountParam('id'), $subMethod, $paymentType, $cardtypes, $brandLabelHtml, $brandDescriptionHtml, $altText, $payNameForCssClass);
 }
Пример #11
0
	/**
	 * Checks the VAT number using EU VIES checkVatApprox SOAP call
	 *
	 * @param  array                $params
	 * @param  cbpaidPaymentBasket  $paymentBasket
	 * @param  string               $vat_verification  OUTPUT: raw log of the verification for storage
	 * @return int                  1: Verification Passed, 0: not passed
	 */
	public function checkVatApprox( $params, $paymentBasket, &$vat_verification )
	{
		try {
			$client						=	new SoapClient("http://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl", array( 'exceptions' => true ) );
			/** @noinspection PhpUndefinedMethodInspection */
			$result						=	$client->checkVatApprox($params);
			$checked					=	true;
		}
		catch ( \SoapFault $e ) {
			$result						=	$e->getMessage();
			$checked					=	false;
		}

		/** @var StdClass $result */

		// log result
		// echo 'Params: '; var_export( $params ); echo "<br />\nResult: "; var_export( $result );

		if ( ( ! $checked ) || is_soap_fault( $result ) ) {
			// FaultString can take the following specific values:
			// - INVALID_INPUT: The provided Country Code is invalid or the VAT number is empty;  This is the only final error state.
			// - SERVICE_UNAVAILABLE: The EU VIES SOAP service is unavailable, try again later;
			// - MS_UNAVAILABLE: The Member State service is unavailable at this time, try again later: http://ec.europa.eu/taxation_customs/vies/viesspec.do
			// - TIMEOUT: The Member State service could not be reached in time, try again later;
			// - SERVER_BUSY: The service can't process your request. Try again latter.
			if ( ! $checked ) {
				$vat_verification		=	$this->encodeVatVerification( 'SOAPSERVERFAULT', null, $params, $result );
				$userMessage			=	CBPTXT::Th("EU VIES VAT number verification server unreachable. VAT number could not be checked. Proceed with VAT or try again later.");
			} elseif ( isset( $result->faultstring ) ) {
				$vat_verification		=	$this->encodeVatVerification( $result->faultstring, $result->faultcode, $params, $result );
				$userMessage			=	( $result->faultstring == 'INVALID_INPUT' ? CBPTXT::T("Invalid EU VAT Number. EU VAT numbers start with country code and must be valid.") : null );
			} else {
				$vat_verification		=	$this->encodeVatVerification( 'SOAPFAULT', null, $params, $result );
				$userMessage			=	null;
			}
			cbpaidApp::getBaseClass()->setLogErrorMSG( 5, $paymentBasket, sprintf( CBPTXT::T('EU VAT VIES error condition: "%s" for request on VAT: "%s%s", faultcode: "%"'), $result->faultstring, $params['countryCode'], $params['vatNumber'], $result->faultcode ), $userMessage );
			return 0;
		}

		if ( ! $result->valid ) {
			$vat_verification			=	$this->encodeVatVerification( 'INVALID', $params['countryCode'] . $params['vatNumber'], $params, $result );
			$userMessage				=	CBPTXT::T("Invalid EU VAT Number. EU VAT numbers start with country code and must be valid.");
			cbpaidApp::getBaseClass()->_setErrorMSG( $userMessage );
			return 0;
		} else {
			$matchesToCheck					=	array( 'traderNameMatch', /* 'traderCompanyTypeMatch', */ 'traderStreetMatch', 'traderPostcodeMatch', 'traderCityMatch' );
			foreach ( $matchesToCheck as $match ) {
				// 1=VALID, 2=INVALID:
				if ( isset( $result->$match ) && ( $result->$match == 2 ) ) {
					$vat_verification	=	$this->encodeVatVerification( 'MISMATCH', strtoupper( substr( $match, 6, -5 ) ), $params, $result );
					return 0;
				}
			}
			// requestIdentifier, requestDate, valid
			// countryCode vatNumber
			// traderName traderCompanyType traderAddress traderStreet traderPostcode traderCity

			$vat_verification			=	$this->encodeVatVerification( 'VALID', ( $result->requestIdentifier ? $result->requestIdentifier : '-' ) . ' / ' . $result->requestDate, $params, $result );
			return 1;
		}
	}
Пример #12
0
?>
	<div class="cbregInvoicePaymentType">
		<span class="cbregInvTitle"><?php
			echo CBPTXT::Th("Payment method:");
		?>&nbsp;</span>
		<span class="cbregInvField"><?php
			echo $this->paymentType;
		?></span>
	</div>
<?php
		// Conditions:
		if ( $this->invoiceConditions ) {
?>
	<div class="cbregInvoiceConditions">
		<span class="cbregInvTitle"><?php
			echo CBPTXT::Th("Terms and conditions:");
		?>&nbsp;</span>
		<span class="cbregInvField"><?php
			echo $this->invoiceConditions;
		?></span>
	</div>
<?php
		}
		// Buttons:
		if ( $this->displayButtons ) {
?>
	<div id="cbpaidPrint"><p><a href="javascript:void(window.print())"><?php echo CBPTXT::T("PRINT"); ?></a></p></div>
	<div id="cbpaidClose"><p><a href="javascript:void(window.close())"><?php echo CBPTXT::T("CLOSE"); ?></a></p></div>
<?php
		}
?>
Пример #13
0
			echo ' (' . sprintf( CBPTXT::Th("waiting for %s"), ( $i->pending_reason ? $i->pending_reason : CBPTXT::T("Payment") ) ) . ')';
		}
		$maintenanceButtonsHtml		=	$i->renderMaintenanceButtonsHtml();
		if ( $maintenanceButtonsHtml ) {
			echo '<div class="cbregMaintenanceButtons">' . implode( ' | ', $maintenanceButtonsHtml ) . '</div>';
		}
						?>
					</td>
					<td class="cbregInvoicePaymentType">
						<?php echo CBPTXT::Th( htmlspecialchars( $i->payment_type ) ); ?>
					</td>
				</tr>
<?php
		}
?>
			</tbody>
		</table>
	</div>
<?php
		global $_CB_framework;
		if ( $_CB_framework->getUi() == 1 ) {
?>
	<div class="cbControlButtonsLine">
		<a href="<?php echo $_CB_framework->userProfileUrl( $this->user->id, true, 'getcbpaidsubscriptionsTab' ); ?>">
			<?php echo CBPTXT::Th("Click here to go back to your user profile"); ?>
		</a>
	</div>
<?php
		}
?>
Пример #14
0
	/**
	 * Draws the invoice
	 *
	 * @param  UserTable  $user
	 * @param  array      $extraStrings
	 * @param  boolean    $displayButtons   Displays the PRINT and CLOSE buttons
	 * @return string                       HTML
	 */
	public function drawInvoice( $user, $extraStrings, $displayButtons = true ) {
		/** @var $invoice cbpaidPaymentBasket */
		$invoice					=	$this->_model;
		$this->user					=	$user;
		$this->extraStrings			=	$extraStrings;
		$this->displayButtons		=	$displayButtons;

		$params						=	cbpaidApp::settingsParams();

		$invoiceHeader				=	cbReplaceVars( CBPTXT::T( trim( $params->get( 'invoice_header', '' ) ) ), $user, true, false, $extraStrings, false );
		$invoiceHeaderAltText		=	cbReplaceVars( CBPTXT::T( trim( $params->get( 'invoice_header_alt_text' ) ) ), $user, false, false, $extraStrings, false );
		$this->invoiceHeaderAlign	=	trim( $params->get( 'invoice_header_align', '' ) );
		$invoiceFooter				=	cbReplaceVars( CBPTXT::T( trim( $params->get( 'invoice_footer', '' ) ) ), $user, true, false, $extraStrings, false );
		$invoiceFooterAltText		=	cbReplaceVars( CBPTXT::T( trim( $params->get( 'invoice_footer_alt_text' ) ) ), $user, false, false, $extraStrings, false );
		$this->invoiceFooterAlign	=	trim( $params->get( 'invoice_footer_align', '' ) );
		$this->invoicerAddress		=	cbReplaceVars( CBPTXT::T( trim( $params->get( 'invoicer_address', '' ) ) ), $user, true, false, $extraStrings, false );
		$this->invoiceConditions	=	cbReplaceVars( CBPTXT::T( trim( $params->get( 'invoice_conditions', '' ) ) ), $user, true, false, $extraStrings, false );

		if ( $invoiceHeader ) {
			if ( preg_match( "/(\\.jpg|\\.png|\\.gif)$/i", $invoiceHeader ) ) {
				$this->header		=	'<img src="' . htmlspecialchars( $invoiceHeader ) . '" alt="' . htmlspecialchars( CBPTXT::T( $invoiceHeaderAltText ) ) . "\" />\n";
			} else {
				$this->header		=	$invoiceHeader;
			}
		} else {
			$this->header			=	null;
		}
		if ( $invoiceFooter ) {
			if ( preg_match( "/(\\.jpg|\\.png|\\.gif)$/i", $invoiceFooter ) ) {
				$this->footer		=	'<img src="' . htmlspecialchars( $invoiceFooter ) . '" alt="' . htmlspecialchars( CBPTXT::T( $invoiceFooterAltText ) ) . "\" />\n";
			} else {
				$this->footer		=	$invoiceFooter;
			}
		} else {
			$this->footer			=	null;
		}

		$this->invoiceDate			=	cbFormatDate( $invoice->time_initiated, 1, false );
		$this->invoiceNumberTitle	=	CBPTXT::Th( $invoice->getInvoiceTitleFormat() );
		$this->invoiceNumber		=	$invoice->invoice;
		$this->invoiceNumberHtml	=	'<span class="cbregInvTitle">'
									.	str_replace( ' ', '&nbsp;', str_replace( '[INVOICENUMBER]', '<span class="cbregInvField">' . $invoice->invoice . '</span>', $this->invoiceNumberTitle ) )
									.	'</span>';
		
		$this->paymentType			=	CBPTXT::T( $invoice->payment_type );
/*
		$this->address				=	$invoice->payer_business_name
									.	"\n"
									.	$invoice->first_name . ' ' . $invoice->last_name
									.	"\n"
									.	$invoice->address_street
									.	"\n"
									.	$invoice->address_city . ( $invoice->address_state ? ', ' . $invoice->address_state : '' )
									.	"\n"
									.	$invoice->address_zip
									.	"\n"
									.	$invoice->address_country
									;
*/
		$this->address				=	cbReplaceVars( CBPTXT::T( trim( $params->get( 'invoice_address_format' ) ) ), $user, false, false, $extraStrings, false );
		if ( $this->address == strip_tags( $this->address ) ) {
			$this->address			=	nl2br( $this->address );
		}
		$this->basketHtml			=	$invoice->displayBasket( "Invoice details", '', 'invoice' );		// it's translated, this is for translations grabber: CBPTxt::Th("Invoice details");

		return $this->display();
	}
Пример #15
0
	/**
	 * Function for the backend XML
	 *
	 * @param  string  $name          Name of the control
	 * @param  string  $value         Current value
	 * @param  string  $control_name  Name of the controlling array (if any)
	 * @return string                 HTML for the control data part or FALSE in case of error
	 */
	public function loadGJParentGroupsList( $name, $value, $control_name ) {
 		global $_CB_framework;

		$api							=	$_CB_framework->getCfg( 'absolute_path' ) . '/components/com_comprofiler/plugin/user/plug_cbgroupjive/cbgroupjive.class.php';

		if ( ! file_exists( $api ) ) {
			return CBPTXT::Th( 'GroupJive 2.x is not installed!' );
		}

		/** @noinspection PhpIncludeInspection */
		require_once( $api );

		$list_gj_groups					=	cbgjClass::getGroupOptions( null );

		if ( $list_gj_groups ) {
			array_unshift( $list_gj_groups, moscomprofilerHTML::makeOption( '0', CBTxt::T( 'No Parent' ) ) );

			if ( isset( $value ) ) {
				$valAsObj				=	array_map( create_function( '$v', '$o=new stdClass(); $o->value=$v; return $o;' ), explode( '|*|', $value ) );
			} else {
				$valAsObj				=	null;
			}

			$groups						=	moscomprofilerHTML::selectList( $list_gj_groups, $control_name ? $control_name .'['. $name .'][]' : $name, null, 'value', 'text', $valAsObj, 0, false, false );
		} else {
			$groups						=	CBPTXT::T( 'No groups exist!' );;
		}

		return $groups;
	}
 /**
  * Called just before showing the form to send email to users, allowing to add lines to the form
  *
  * param  array      $rows
  * param  cbPageNav  $pageNav
  * param  string     $search
  * param  array      $lists
  * param  array      $cid
  * param  string     $emailSubject
  * param  string     $emailBody
  * param  string     $inputTextExtras
  * param  string     $select_tag_attribs
  * param  boolean    $simulationMode
  * param  string     $option
  * @return array      of 'title' => 'row' html code for lines to display in form
  */
 public function onBeforeBackendUsersEmailForm()
 {
     $lines = array();
     if (cbpaidApp::authoriseAction('cbsubs.usersubscriptionview')) {
         if ($this->filter_cbpaidplan > 0) {
             $plansMgr = cbpaidPlansMgr::getInstance();
             $plan = $plansMgr->loadPlan((int) $this->filter_cbpaidplan);
             $lines[CBPTXT::Th('Selected plan')] = CBPTXT::Th($plan->name);
             $lines[CBPTXT::Th('More substitutions with the selected plan')] = '[subscription_start_date], ' . ($plan->isProductWithExpiration() ? '[subscription_end_date], ' : '') . '[subscription_lastrenew_date]';
         }
     }
     return $lines;
 }
 /**
  * Renders the rate of $this payment item
  *
  * @param  string       $variable
  * @param  boolean      $output   'html', ...
  * @param  boolean      $rounded
  * @return string|null
  */
 private function renderTotalRate($variable, $output, $rounded = false)
 {
     $renderedBasketPrice = null;
     $params = cbpaidApp::settingsParams();
     if ($params->get('totalizer_description_' . 'grandtotal') == '[AUTOMATIC]') {
         list($recurring, , $period, $occurrences) = $this->_itemsProps($this->_paymentBasket->loadPaymentItems());
         $renderedBasketPrice = $this->_paymentBasket->renderPrice(null, null, null, true);
         if ($recurring && ($this->_paymentBasket->period1 && $this->_paymentBasket->mc_amount1 != $this->_paymentBasket->mc_amount3)) {
             $then = $this->_paymentBasket->renderPrice($this->_paymentBasket->mc_amount3, $period, $occurrences, true);
             $renderedBasketPrice = sprintf(CBPTXT::Th("%s, then %s"), $renderedBasketPrice, $then);
         }
     } else {
         parent::renderColumn($variable, $output, $rounded);
     }
     return $renderedBasketPrice;
 }
	/**
	 * Creates a new (or loads an existing) subscription, and if it's non-free:
	 * Creates a payment basket if there is not already one
	 * ---- and then displays payment processing mask, button, or redirects
	 * If it's free: activates account and does not return anything.
	 *
	 * @param  UserTable           $user
	 * @param  cbpaidProduct[]     $chosenPlans              array of cbpaidProduct : Chosen plans to pay
	 * @param  array               $postdata                 $_POST array for the parameters of the subscription plans
	 * @param  array|null          $replacesSubscriptionIds  In fact: the existing one in all cases, except if new to be created.
	 * @param  array|null          $existingSubscriptionIds  In fact: the new one in case of upgrade !
	 * @param  string              $status 					 subscription status: 'R'=registered (default) , 'I'=illegal, 'A'=active, etc.
	 * @param  string              $prefixText 				 text to prefix the payment items (default: null)
	 * @param  string              $reason 					 payment reason: 'N'=new subscription (default), 'R'=renewal, 'U'=update
	 * @param  string              $payment                  'now' (default), 'free'
	 * @return cbpaidPaymentBasket|string                    object if something to pay, otherwise HTML text for message.
	 */
	public static function createSubscriptionsAndPayment( &$user, $chosenPlans, $postdata, $replacesSubscriptionIds = null, $existingSubscriptionIds = null, $status = 'R', $prefixText = null, $reason='N', $payment = 'now' ) {
		global $_CB_framework, $_CB_database;

		$subscriptionTime				=	$_CB_framework->now();

		/** @var cbpaidSomething[] $subscriptions */
		$subscriptions					=	array();
		$needToPay						=	false;

		//TBD LATER: Handle fully payment baskets as baskets, adding/replacing the content with the new items:
		$paymentBasket					=&	cbpaidPaymentBasket::getInstanceBasketOfUser( $user->id, false );			//TBD could be true to avoid old baskets ?
		if ( $paymentBasket->id ) {
			// otherwise show existing basket:
			return $paymentBasket;
		}

		if ( ! ( $chosenPlans && ( count( $chosenPlans ) > 0 ) ) ) {
			trigger_error( 'createSubscriptionsAndPayment:: called without plans chosen !', E_USER_ERROR );
		}
		// 1. add subscription records if not existing: pass 1: parents, pass 2: children:
		$pass							=	0;
		while ( ++$pass <= 2 ) {
			foreach ( $chosenPlans as $plan ) {
				$parentPlan							=	$plan->get( 'parent' );
				if ( ( ( $pass == 1 ) && ( $parentPlan == 0 ) ) || ( ( $pass == 2 ) && ( $parentPlan != 0 ) ) ) {
					$planId							=	$plan->get( 'id' );

					/* $reasonInCaseExpired			=	$reason; */
					// find replaced subscription id:
					$replacesSubId					=	null;
					if ( $replacesSubscriptionIds && isset( $replacesSubscriptionIds[$planId] ) ) {
						$replacesSubId				=	$replacesSubscriptionIds[$planId];
						/*		//TBD later: need to check if we really want to renew an existing subscription when there is an interruption.
						if ( $reason == 'R' ) {
							$paidSomethinMgr		=&	cbpaidSomethingMgr::getInstance();
							$replacesSub			=&	$paidSomethinMgr->loadSomething( $replacesSubId[0], $replacesSubId[1] );
							if ( $replacesSub ) {
								if ( ! $replacesSub->checkIfValid( $subscriptionTime ) ) {

								}
							}
						}
						*/
					} else {
						if ( $reason == 'R' ) {
							trigger_error( 'createSubscriptionsAndPayment::no existing subscription for renewal !', E_USER_ERROR );
							exit;
						}
					}

					// find existing plan+subscription id:
					$existingSubId					=	null;
					if ( $reason != 'R' ) {
						// new or upgrade: create or load $subscription:
						if ( $existingSubscriptionIds && isset( $existingSubscriptionIds[$planId] ) ) {
							$existingSubId			=	$existingSubscriptionIds[$planId];
						}
					}

					// check that subscription is renewable if getting renewed:
					if ( ( $reason == 'R' ) && $replacesSubId ) {
						$paidSomethingMgr						=&	cbpaidSomethingMgr::getInstance();
						$subscription							=	$paidSomethingMgr->loadSomething( $replacesSubId[0], $replacesSubId[1] );
						if ( ! $subscription->checkIfRenewable() ) {
							trigger_error( sprintf( 'createSubscriptionsAndPayment::Renewal not allowed !' ), E_USER_WARNING );
							return 'Unexpected condition: Renewal not allowed !';
						}
					}
					// find parent subscription id if exists:
					$parentSubId									=	null;
					if ( $parentPlan ) {
						switch ( $reason ) {
							case 'R':
								// renew: don't change anything in the existing subscription (no update on NULL):
								// $parentSubId						=	null;
								break;
							case 'U':
								// upgrade: check if parent subscription is upgraded same time:
								if ( isset( $subscriptions[$parentPlan] ) ) {
									$parentSubId					=	array( (int) $subscriptions[$parentPlan]->plan_id, (int) $subscriptions[$parentPlan]->id );
								} else {
									// if not: try to find the existing subscription in database:
									if ( $existingSubId ) {
										$paidSomethinMgr			=&	cbpaidSomethingMgr::getInstance();
										$thisSub					=	$paidSomethinMgr->loadSomething( $existingSubId[0], $existingSubId[1] );
										if ( $thisSub ) {
											// then try to find parent subscription of the existing subscription:
											if ( $thisSub->parent_plan && $thisSub->parent_subscription ) {
												$thisSubParent		=	$paidSomethinMgr->loadSomething( $thisSub->parent_plan, $thisSub->parent_subscription );
												if ( $thisSubParent ) {
													$parentSubId	=	array( $thisSubParent->parent_plan, $thisSubParent->parent_subscription );
												}
											}
										} else {
											trigger_error( sprintf( 'createSubscriptionsAndPayment::no existing subscription id %d found in database for upgraded plan id %d !', $existingSubId[1], $existingSubId[0] ), E_USER_WARNING );
										}
									} else {
										// try finding subscription of parent plan by this user:
										$plansMgr					=&	cbpaidPlansMgr::getInstance();
										$parPlan					=	$plansMgr->loadPlan( $parentPlan );
										if ( $parPlan ) {
											$something				=	$parPlan->newSubscription();
											$foundParent			=	$something->loadLatestSomethingOfUser( $user->id );
											if ( $foundParent ) {
												$parentSubId		=	array( $something->plan_id, $something->id );
											}
										}
									}
								}
								break;

							case 'N':
							default:
								// new: find parent subscription:
								if ( isset( $subscriptions[$parentPlan] ) ) {
									$parentSubId		=	array( (int) $subscriptions[$parentPlan]->plan_id, (int) $subscriptions[$parentPlan]->id );
								} else {
									trigger_error( sprintf( 'createSubscriptionsAndPayment::no existing subscription for parent plan id %d of plan %d in new subscription !', $parentPlan, $planId ), E_USER_WARNING );
								}
								break;
						}
					}

					// creates the subscription of the correct type:
					$price						=	false;		// returned values from next line:
					$recurringPrice				=	false;		// returned values from next line:
					$subscriptions[$planId]		=	$plan->createProductThing( $user, $postdata, $reason, $status, $replacesSubId, $existingSubId, $subscriptionTime, $price, $recurringPrice, $parentSubId );
					if ( ( $price === false ) && ( $recurringPrice === false ) ) {
						unset( $subscriptions[$planId] );		// can't be subscribed/purchased
						unset( $chosenPlans[$planId] );
					} elseif ( ( $price > 0 ) || ( $recurringPrice > 0 ) ) {
						// $lastSubscriptionId	=	$subscriptions[$planId]->id;
						// $lastPlanId			=	$planId;
						$needToPay				=	true;
					}
				}
			}
		}

		// Sort subscriptions, so they are presented in basket in same order as on the plans selection:
		$sortedSubscriptions					=	array();
		foreach ( array_keys( $chosenPlans ) as $id ) {
			$sortedSubscriptions[$id]			=	$subscriptions[$id];
		}

		if ( ( $payment == 'free' ) || ( ! $needToPay ) ) {						//TBD: Should we activate already what can be activated (check for hierarchy) !???
			// Free plan: no payment ! : activate $subscription now:
			$thankYouText						=	array();
			$cbUser								=	CBuser::getInstance( $user->id );
			foreach ( array_keys( $subscriptions ) as $k ) {
				if ( ( $reason != 'R' ) || $subscriptions[$k]->checkIfRenewable() ) {
					$occurrences				=	1;
					$autorecurring_type			=	0;
					$autorenew_type				=	0;
					// bug #1184 fix: this was certainly wrong in backend at least, but in frontend too most likely too, as it would block from renewing imho:
					// $autorecurring_type			=	( ( $chosenPlans[$k]->autorecurring > 0 ) ? 2 : 0 );
					// $autorenew_type				=	( ( $chosenPlans[$k]->autorecurring > 0 ) ? 2 : 0 );
					$subscriptions[$k]->activate( $user, $subscriptionTime, true, $reason, $occurrences, $autorecurring_type, $autorenew_type );
					$extraStrings				=	$subscriptions[$k]->substitutionStrings( true );
					$thankYouText[]				=	trim( $cbUser->replaceUserVars( CBPTXT::Th( $subscriptions[$k]->getText( 'thankyoutextcompleted' ) ), true, true, $extraStrings, false ) );
				}
			}
			if ( count( $thankYouText ) > 0 ) {
				return implode( '<br />', $thankYouText );
			} else {
				return CBPTXT::Th("Chosen plan(s) can not be subscribed") . '.';
			}
		} else {
			// non-free plan:
			// 2. add payment_item and payment_basket records:

			// get the most recent payment basket for $subscription
			$paymentBasket						=	new cbpaidPaymentBasket( $_CB_database );
			/*
						$basketLoaded						=	$paymentBasket->loadLatestBasketOfUserPlanSubscription( $user->id );
						if ( $basketLoaded ) {
							$paymentBasket->delete();
							$paymentBasket					=	new cbpaidPaymentBasket( $_CB_database );
							//TBD LATER: Handle fully payment baskets as baskets, adding/replacing the content with the new items.
						}
			*/
			$hasAmountToPay						=	$paymentBasket->createAndFillCreteSubscriptionsItems( $user, $sortedSubscriptions, $prefixText, $reason, $subscriptionTime );
			if ( ! $hasAmountToPay ) {
				$thankYouText					=	array();
				$cbUser							=	CBuser::getInstance( $user->id );
				foreach ( array_keys( $subscriptions ) as $k ) {
					$subscriptions[$k]->activate( $user, $subscriptionTime, true, $reason );
					$extraStrings				=	$subscriptions[$k]->substitutionStrings( true );
					$thankYouText[]				=	trim( $cbUser->replaceUserVars( CBPTXT::Th( $subscriptions[$k]->getText( 'thankyoutextcompleted' ) ), true, true, $extraStrings, false ) );
				}
				return implode( '<br />', $thankYouText );
			}

			if ( ( $paymentBasket->payment_status === null ) || ( $paymentBasket->payment_status == 'NotInitiated' ) ) {
				return $paymentBasket;
			}
		}
		trigger_error( '_createSubscriptionsAndPayment: Unexpected condition: no payment and no free plan', E_USER_NOTICE );
		return 'Unexpected condition.';
	}
 /**
  * Computes text for the title of the invoices list
  *
  * @param  int        $invoicesNumber  array of cbpaidPaymentBasket  of Completed and Pending baskets
  * @param  UserTable  $user            reflecting the user being displayed (here null)
  * @param  boolean    $itsmyself       user is logged in user
  * @param  string     $periodText      if non-empty, text of the period showing invoices
  * @return string
  */
 protected function _invoicesTitle($invoicesNumber, $user, $itsmyself, $periodText)
 {
     global $ueConfig;
     if ($itsmyself) {
         if ($periodText) {
             $plansTitle = sprintf(CBPTXT::Th("Your invoices of last %s"), htmlspecialchars($periodText));
         } else {
             if ($invoicesNumber == 1) {
                 $plansTitle = CBPTXT::Th("Your invoice");
             } else {
                 $plansTitle = CBPTXT::Th("Your invoices");
             }
         }
     } else {
         if ($periodText) {
             $plansTitle = sprintf(CBPTXT::Th("%s's invoices of last %s"), getNameFormat($user->name, $user->username, $ueConfig['name_format']), htmlspecialchars($periodText));
         } else {
             $plansTitle = sprintf(CBPTXT::Th("%s's invoices"), getNameFormat($user->name, $user->username, $ueConfig['name_format']));
         }
     }
     return $plansTitle;
 }
	/**
	 * Displays the "Content Access Denied View
	 * 
	 * @param  UserTable                   $user
	 * @param  CBplug_cbpaidsubscriptions  $baseClass
	 * @return string
	 */
	public function display( & $user, /** @noinspection PhpUnusedParameterInspection */ &$baseClass ) {
		global $_CB_framework;

		if ( ! is_callable( array( 'cbpaidBot', 'getInstance' ) ) ) {
			return CBPTXT::T("CBSubs CbpaidSubsBot is not installed, enabled and running or CBSubs Content integration plugin is not up to date. Please ask site administrator to do so.");
		}

		$cbpaidBot				=	cbpaidBot::getInstance();

		$userId						=	$_CB_framework->myId();
		$accesstype					=	cbGetParam( $_GET, 'accesstype' );
		$accessvalue				=	cbGetParam( $_GET, 'accessvalue' );
		$accessurl					=	cbGetParam( $_GET, 'accessurl' );
		switch ( $accesstype ) {
			case 'components':
				$option				=	$accessvalue;
				$accessPlans		=	$cbpaidBot->checkAccess( $userId, $option, 'cpaycontent_components', null, true );
				if ( is_array( $accessPlans ) ) {
					$result			=	array( 'can', CBPTXT::T("component") );	// CBPTXT::T("You can access to this component with following plans: ");													// . implode( ', ', $accessPlans );
					$access			=	false;
				} elseif ( $accessPlans === true ) {
					$result			=	array( 'have', CBPTXT::T("component") );	// CBPTXT::T("You have access now to this component !");
					$access			=	true;
				} else {
					$result			=	array( 'unknown', CBPTXT::T("component"), $accessPlans );	// 'Unknown component access result: ' . var_export( $accessPlans, true );
					$access			=	false;
				}
				break;

			case 'menus':
				$itemid				=	(int) $accessvalue;
				$accessPlans		=	$cbpaidBot->checkAccess( $userId, $itemid, 'cpaycontent_menus' , null, true );
				if ( is_array( $accessPlans ) ) {
					$result			=	array( 'can', CBPTXT::T("menu") );	// CBPTXT::T("You can access to this menu with following plans: ");														// . implode( ', ', $accessPlans );
					$access			=	false;
				} elseif ( $accessPlans === true ) {
					$result			=	array( 'have', CBPTXT::T("menu") );	// CBPTXT::T("You have access now to this menu !");
					$access			=	true;
				} else {
					$result			=	array( 'unknown', CBPTXT::T("menu"), $accessPlans );	// 'Unknown menu access result: ' . var_export( $accessPlans, true );
					$access			=	false;
				}
				break;

			case 'urls':
				$getPostArray		=	$this->_decodeArrayUrl( $accessurl );
				$postsMissingInGetToFindPlans	=	array();
				$accessPlans		=	$cbpaidBot->checkAccessUrl( $userId, $getPostArray, $getPostArray, $postsMissingInGetToFindPlans, 'cpaycontent_urls', true );
				if ( is_array( $accessPlans ) ) {
					$result			=	array( 'can', CBPTXT::T("location") );	// CBPTXT::T("You can access to this location with following plans: ");													// . implode( ', ', $accessPlans );
					$access			=	false;
				} elseif ( $accessPlans === true ) {
					$result			=	array( 'have', CBPTXT::T("location") );	// CBPTXT::T("You have access now to this location !");
					$access			=	true;
				} else {
					$result			=	array( 'unknown', CBPTXT::T("location"), $accessPlans );	// 'Unknown location access result: ' . var_export( $accessPlans, true );
					$access			=	false;
				}
				break;

			case 'sections':					// section list:
				$sectionId			=	(int) $accessvalue;
				$accessPlans		=	$cbpaidBot->checkAccess( $userId, $sectionId, 'cpaycontent_sections', 'cpaycontent_sections_list', true );
				if ( is_array( $accessPlans ) ) {
					$result			=	array( 'can', CBPTXT::T("content section") );	// CBPTXT::T("You can access to this content section with following plans: ");												// . implode( ', ', $accessPlans );
					$access			=	false;
				} elseif ( $accessPlans === true ) {
					$result			=	array( 'have', CBPTXT::T("content section") );	// CBPTXT::T("You have access now to this content section !");
					$access			=	true;
				} else {
					$result			=	array( 'unknown', CBPTXT::T("content section"), $accessPlans );	// 'Unknown content section access result: ' . var_export( $accessPlans, true );
					$access			=	false;
				}
				break;

			case 'categories':
				$categoryId			=	(int) $accessvalue;
				$accessPlans		=	$cbpaidBot->checkAccess( $userId, $categoryId, 'cpaycontent_categories', 'cpaycontent_categories_list', true );

				$sectionId			=	$cbpaidBot->getSectionOfCategory( $categoryId );
				if ( $sectionId ) {
					$accessPlansSection	=	$cbpaidBot->checkAccess( $userId, $sectionId, 'cpaycontent_sections', 'cpaycontent_sections_list', true );
				} else {
					$accessPlansSection	=	array();
				}

				if ( is_array( $accessPlans ) ) {
					if ( is_array( $accessPlansSection ) ) {
						$result		=	array( 'can', CBPTXT::T("content category") . ' ' . CBPTXT::T("or"). ' ' . CBPTXT::T("content section in which this content category is located") );	// CBPTXT::T("You can access to this content category with following plans: ")												// . implode( ', ', $accessPlans )
																			//.	CBPTXT::T("You can access to the whole content section enclosing this content category with following plans: ");			// . implode( ', ', $accessPlansSection );
						$access		=	false;
					} elseif ( $accessPlansSection === null ) {
						$result		=	array( 'can', CBPTXT::T("content category") );	// CBPTXT::T("You can access to this content category with following plans: ");											// . implode( ', ', $accessPlans );
						$access		=	false;
					} elseif ( $accessPlansSection === true ) {
						$result		=	array( 'have', CBPTXT::T("content section in which this content category is located") );	// CBPTXT::T("You have access now to the whole content section in which this content category is located !");
						$access		=	true;
					} else {
						$result		=	array( 'unknown', CBPTXT::T("content section"), $accessPlansSection );	// 'Unknown content section access result: ' . var_export( $accessPlans, true );
						$access		=	false;
					}
				} elseif ( $accessPlans === null ) {
					if ( is_array( $accessPlansSection ) ) {
						$result		=	array( 'can', CBPTXT::T("content section in which this content category is located") );	//CBPTXT::T("You can access to the whole content section enclosing this content category with following plans: ");			// . implode( ', ', $accessPlansSection );
						$access		=	false;
					} elseif ( $accessPlansSection === null ) {
						$result		=	CBPTXT::T("These content categories are not under category or section access control");
						$access		=	true;
					} elseif ( $accessPlansSection === true ) {
						$result		=	array( 'have', CBPTXT::T("content section in which this content category is located") );	//CBPTXT::T("You have access now to the whole content section in which this content category is located !");
						$access		=	true;
					} else {
						$result		=	array( 'unknown', CBPTXT::T("content section"), $accessPlansSection );	// 'Unknown content section access result: ' . var_export( $accessPlans, true );
						$access		=	false;
					}
				} elseif ( $accessPlans === true ) {
					$result			=	array( 'have', CBPTXT::T("content category") );	// CBPTXT::T("You have access now to this content categories !");
					$access			=	true;
				} else {
					$result			=	array( 'unknown', CBPTXT::T("content category"), $accessPlans );	// 'Unknown content categories access result: ' . var_export( $accessPlans, true );
					$access			=	false;
				}
				break;

			case 'contentdisplay':
				$contentId			=	(int) $accessvalue;

				global $_CB_database;

				$row				=	null;
				$sql				=	'SELECT * FROM #__content WHERE id = ' . (int) $contentId;
				$_CB_database->setQuery( $sql );
				$contentExists		=	$_CB_database->loadObject( $row );
				if ( $contentExists ) {
					/** @var StdClass $row */
					$_cbACL			=&	cbpaidBotAclApi::getInstance();
					$accessPlans	=	$_cbACL->_cb_checkMultiAcl_Ok_or_Plans( $_CB_framework->myId(), $row->id, isset( $row->catid ) ? $row->catid : null, isset( $row->sectionid ) ? $row->sectionid : null, -1 );
					if ( is_array( $accessPlans ) ) {
						$accessPlansWrite	=	$_cbACL->_cb_checkMultiAcl( $_CB_framework->myId(), $row->id, isset( $row->catid ) ? $row->catid : null, isset( $row->sectionid ) ? $row->sectionid : null, count( $_cbACL->cbContentAclRights ) -1 );
						if ( $accessPlansWrite === true ) {
							$result	=	CBPTXT::T("You have access to this content item");
							$access	=	true;
						} elseif ( is_array( $accessPlansWrite ) && ( count( $accessPlansWrite ) > 0 ) ) {
							$result	=	array( 'can', CBPTXT::T("content item") );	// CBPTXT::T("You can access to this article with following plans: ")														// . implode( ', ', $accessPlans ) 
																		//.	CBPTXT::T("You can access with write access to this article with following plans: ");									// . implode( ', ', $accessPlansWrite );
							$access	=	false;
						} else {
							$result	=	array( 'can', CBPTXT::T("content item") );	// CBPTXT::T("You can access to this article with following plans: ");														// . implode( ', ', $accessPlans );
							$access	=	false;
						}
					} elseif ( $accessPlans === true ) {
						$result		=	array( 'have', CBPTXT::T("content item") );	// CBPTXT::T("You have access now to this article !");
						$access		=	true;
					} else {
						$result		=	array( 'unknown', CBPTXT::T("content item"), $accessPlans );	// 'Unknown access result: ' . var_export( $accessPlans, true );
						$access		=	false;
					}
				} else {
					$result			=	CBPTXT::T("This content item does not exist");
					$access			=	true;
					$accessPlans	=	array();
				}
				break;

			default:
				// Hacking or PCI-DSS intrusion trial:
				$result			=	CBPTXT::T("This redirection URL is invalid.");
				$access			=	true;
				$accessPlans	=	array();
				break;
		}
		if ( $access ) {
			if ( is_array( $result ) ) {
				switch ( $result[0] ) {
					case 'have':
						$return		=	sprintf( CBPTXT::Th("You have now access to this %s"), $result[1] );
						//TBD later in a safe way (FS#259): or with $_SESSION
						// $realUrl	=	base64_decode( $accessurl );
						// $return		.=	'<a href="' . $_CB_framework->getCfg( 'live_site' ) . '/index.php?' . htmlspecialchars( $realUrl ) . '">Click here to access</a>';
						break;

					default:
						$return		=	"Unknown access allowed result: " . var_export( $result, true );
						break;
				}
			} else {
				$return				=	$result;
			}
		} else {
			if ( is_array( $result ) ) {
				switch ( $result[0] ) {
					case 'can':
						if ( count( $accessPlans ) > 0 ) {
							$params	=&	cbpaidApp::settingsParams();
							$subTxt	=	CBPTXT::T( $params->get( 'subscription_name', 'subscription' ) );
							$result	=	sprintf( CBPTXT::Th("You can access this %s with following %s plans:"), $result[1], $subTxt );

							// CB login return-to after login URL:
							if ( $accessurl ) {
								global $cbSpecialReturnAfterLogin;
								$url =	base64_decode( $accessurl );
								if ( ! preg_match( '#https?://#i', $url ) ) {
									$cbSpecialReturnAfterLogin	=	'******' . $url;
								}
							}

							// We need to also display child plans of the $accessPlans as some might be needed (mandatory):
							$plans	=	cbpaidSubscriptionsMgr::getInstance()->getUpgradablePlansWithChildrensForPlans( $accessPlans, $user );
							$return	=	cbpaidControllerOffer::displaySpecificPlans( $plans, null, $user, $result );
						} else {
							$return	=	sprintf( CBPTXT::Th("You can not access this %s") . '.', $result[1] );
						}
						break;

					case 'unknown':
						$return		=	sprintf( CBPTXT::Th("Unknown %s access result: %s") . '.', $result[1], var_export( $result[2], true ) );
						break;

					default:
						$return		=	"Unknown access allowed result" . ': ' . var_export( $result, true );
						break;
				}
			} else {
				$return				=	$result;
			}
		}
		return $return;
	}
Пример #21
0
	/**
	* Generates the HTML to display the plans and upgrade possibilities for subscription tab/area
	* (frontend and backend)
	*
	* @param  UserTable  $user        Reflecting the user being displayed (here null)
	* @param  int        $subsAccess  0 has only read access, 1 has user access, 2 reserved for future Super-admin access
	* @return mixed                   either string HTML for tab content, or false if ErrorMSG generated
	*/
	public function getShowSubscriptionUpgrades( $user, $subsAccess ) {
		global $_CB_framework;

		$ui						=	$_CB_framework->getUi();
		$return 				=	'';
		$now					=	$_CB_framework->now();
		
		
		$params				 	=&	$this->params;
		$plansTitle			 	=	$params->get('regTitle');
		$upgradePlansEnabled 	=	( $ui == 2 ) || ( $subsAccess && ( $params->get( 'upgradePlansEnabled', 1 ) == '1' ) );
		$showRenewButtons		=	( $ui == 2 ) || ( $subsAccess && ( $params->get( 'showRenewButtons', '1' ) == '1' ) );
		$showUnsubscribeButtons =	( $ui == 2 ) || ( $subsAccess && ( $params->get( 'showUnsubscribeButtons', '0' ) == '1' ) );
		$plansToShowOnly		=	$this->setShowOnlyPlans( false );

		$subscriptions			=	array();
		if ( ( $ui == 2 ) && ( $user->id == 0 ) ) {
			// creating a new user in backend: propose registration plans:
			$plansMgr			=&	cbpaidPlansMgr::getInstance();
			$plans				=&	$plansMgr->loadPublishedPlans( null, true, 'registration', null );
		} else {
			$paidsubsManager	=&	cbpaidSubscriptionsMgr::getInstance();
			$plans				=	$paidsubsManager->getUpgradeAndRenewalPossibilities( $ui, $user->id, $now, $subscriptions, $plansToShowOnly, $subsAccess );

			$this->_unsetNonReactivableSubscriptions( $subscriptions, $now );
			$this->_unsetIrrelevantSubscriptions( $subscriptions, $plans );
		}
		if ( $this->_unsetIrrelevantPlans( $plans ) ) {
			$chosenPlans		=	$this->_chooseMaxPlans( $plans );
		} else {
			$chosenPlans		=	$this->_planGetAndCheckReqParamArray( $user, 'plan', $plans, false, null );
		}
		if ( ! is_array( $chosenPlans ) ) {
			$chosenPlans		=	array();		// no need to display errors here.
		}
		// display subscriptions and upgrade possibilities:
		if ( ( count( $subscriptions ) > 0 ) || ( $upgradePlansEnabled && ( count( $plans ) > 0 ) ) ) {
			$this->_outputRegTemplate();
			if  ( count( $subscriptions ) > 0 ) {

				// Render subscriptions for renewal/cancellations:

				$htmlSubscribed	=	$this->_getSubscribedPlans( $now, $user, $subscriptions, $plansTitle, $showRenewButtons, $showUnsubscribeButtons );
				$viewer			=	cbpaidTemplateHandler::getViewer( null, 'usersubscriptions' );
				/** @var $viewer cbpaidusersubscriptionsView */
				$viewer->setModel( $subscriptions );
				$return			.=	$viewer->drawUserSomethings( $user, $subsAccess, $htmlSubscribed );
			}
			if ( $upgradePlansEnabled && ( count( $plans ) > 0 ) ) {
				if ( ( $ui == 1 ) && $subsAccess ) {
					$plansDisplayed	=	0;
					$buttonTexts	=	array();
					foreach ( array_keys( $plans ) as $id ) {
						if ( ! ( isset( $plans[$id]->_drawOnlyAsContainer ) && $plans[$id]->_drawOnlyAsContainer ) ) {
							++$plansDisplayed;
							$button	=	$plans[$id]->buttonText( 'upgrade' );		// CBPTXT::T("Upgrade")
							$buttonTexts[$button]	=	$button;
						}
					}
					if ( $plansDisplayed > 0 ) {

						// Render plans for upgrades:

						$htmlUpgrades	=	$this->_getFormattedPlans( $user, $plans, $plansTitle, $chosenPlans, 'U' );
						if ( $htmlUpgrades ) {
							$htmlspecialcharedBaseUrl	=	$this->getHttpsAbsURLwithParam( array( 'Itemid' => 0, 'user' => $user->id ), 'pluginclass' );
							$hiddenFlds	=	'<input type="hidden" name="user" value="' . $user->id . '" />';
		//					$hiddenFlds	.=	'<input type="hidden" name="' . $this->_getPagingParamName("subscription") . '" value="' . $plans[0]->_subscriptionToUpdate . '" />';		//TBD: select which if more than 1...
							$hiddenFlds	.=	'<input type="hidden" name="' . $this->_getPagingParamName("act") . '" value="upgrade" />';
							$hiddenFlds	.=	cbGetSpoofInputTag( 'plugin' );
							$buttonName	=	$this->_getPagingParamName("cbregUpgrade");

							/** @var $viewer cbpaiduserupgradeplansView */
							$viewer		=	cbpaidTemplateHandler::getViewer( null, 'userupgradeplans' );
							$viewer->setModel( $plans );
							$return		.=	$viewer->drawUserUpgradePlans( $user, $plansDisplayed, $htmlUpgrades, $htmlspecialcharedBaseUrl, $hiddenFlds, $buttonTexts, $buttonName );

							$this->_addJsCodeIfNeeded( $plans, 'U' );
						}
					} else {
						// no upgrade possibility
					}
				} elseif ( $ui == 2 ) {
					$subTxt		=	CBPTXT::T( $params->get( 'subscription_name', 'subscription' ) );
//					$return		.=	'<input type="hidden" name="' . $this->_getPagingParamName("subscription") . '" value="' . $plans[0]->_subscriptionToUpdate . '" />';		//TBD: select which if more than 1...
					$return		.=	'<input type="hidden" name="' . $this->_getPagingParamName("act") . '" value="upgrade" />';
					
					$return		.=	'<div class="contentheading" id="cbregUpgradePossibilities">';
					if ( count( $plans ) == 1 ) {
						$return	.=	sprintf( CBPTXT::Th("Current %s upgrade possibility:"), $subTxt );
					} else {
						$return	.=	sprintf( CBPTXT::Th("Current %s upgrade possibilities:"), $subTxt );
					}
					$return		.=	"</div>\n";

					$return		.=	$this->_getFormattedPlans( $user, $plans, $plansTitle, $chosenPlans, 'U', true );
					$this->_addJsCodeIfNeeded( $plans, 'U' );
				}
			}
		}
		return  $return;
	}
 /**
  * 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  null       $tab
  * @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 getCBpluginComponent($tab, &$user, $ui, &$postdata)
 {
     global $_CB_framework, $ueConfig, $_GET;
     cbpaidErrorHandler::on();
     $result = null;
     $do = cbGetParam($_GET, 'do');
     switch ($do) {
         case null:
             $return = $this->getTabComponent($tab, $user, $ui, $postdata);
             cbpaidErrorHandler::keepTurnedOn();
             break;
         case 'display_subscriptions':
             if ($user && $user->id && $_CB_framework->myId()) {
                 $regTitle = strip_tags(CBPTXT::T($this->params->get('regTitle', "Subscriptions")));
                 outputCbTemplate();
                 $_CB_framework->setPageTitle($regTitle);
                 $_CB_framework->appendPathWay($regTitle);
                 $pre = '<div class="cbPageOuter"><div class="cbPageInner">';
                 $post = '</div></div><div class="cbClr"> </div>';
                 $return = $pre . $this->displayUserTab($user) . $post;
             } else {
                 if ($_CB_framework->getCfg('allowUserRegistration') == '0' && (!isset($ueConfig['reg_admin_allowcbregistration']) || $ueConfig['reg_admin_allowcbregistration'] != '1')) {
                     $return = _UE_NOT_AUTHORIZED . '<br />' . _UE_DO_LOGIN;
                 } else {
                     /*
                     $registrationUrl	=	cbSef( 'index.php?option=com_comprofiler&task=registers' );
                     $registrationLink	=	'<a href="' . $registrationUrl . '">' . _UE_REGISTER . '</a>';
                     $loginRegisterText	=	sprintf( CBPTXT::Th("Please login or %s"), $registrationLink );
                     $return				=	_UE_NOT_AUTHORIZED . '<br /><br />' . $loginRegisterText;
                     */
                     $accessPlans = null;
                     $return = cbpaidControllerOffer::displaySpecificPlans($accessPlans, null, $user, '');
                 }
             }
             break;
         case 'accessdenied':
             $params = cbpaidApp::settingsParams();
             $accessRedirectLink = $params->get('subscriptionNeededRedirectLink');
             if ($accessRedirectLink) {
                 $textMessage = $params->get('subscriptionNeededText', "A membership is needed for access.");
                 $return = null;
                 cbRedirect(cbSef($accessRedirectLink, false), CBPTXT::T($textMessage), 'warning');
             } else {
                 /** @noinspection PhpIncludeInspection */
                 include_once cbpaidApp::getAbsoluteFilePath('plugin/cbsubscontent/cbsubs.content_deniedview.php');
                 $accessDeniedView = new cbpaidContentAccessDeniedView();
                 $return = $accessDeniedView->display($user, $this);
             }
             break;
         case 'displayplans':
             $plansParam = cbGetParam($_GET, 'plans');
             $plans = null;
             $preselect = null;
             if ($plansParam) {
                 $plansParam = explode('-', $plansParam);
                 foreach ($plansParam as $p) {
                     $pN = (int) $p;
                     if ($pN) {
                         $plans[] = $pN;
                         if (substr($p, -1) == 's') {
                             $preselect[] = $pN;
                         }
                     }
                 }
             }
             if ($user === null || $user->id == $_CB_framework->myId()) {
                 $introText = CBPTXT::Th($this->params->get('plansDisplayIntroText', "We suggest subscribing to following subscriptions:"));
                 $return = cbpaidControllerOffer::displaySpecificPlans($plans, $preselect, $user, $introText);
             } else {
                 $return = _UE_NOT_AUTHORIZED;
             }
             break;
         case 'massexpire':
             // cron
             $params = cbpaidApp::settingsParams();
             $key = cbGetParam($_GET, 'key');
             if ($key && $key == md5($params->get('license_number')) && $params->get('massexpirymethod', 0) >= 2) {
                 $limit = $params->get('massexpirynumber', 100);
                 // mass-expire 100 subscriptions at a time on the way if not exipring a particular user:
                 $plansMgr = cbpaidPlansMgr::getInstance();
                 $plansMgr->checkAllSubscriptions((int) $limit);
                 $return = null;
             } else {
                 $return = CBPTXT::Th("Invalid mass-expiry link: link is in global CBSubs settings.");
             }
             break;
         case 'autopayments':
             // cron
             $params = cbpaidApp::settingsParams();
             $key = cbGetParam($_GET, 'key');
             if ($key && $key == md5($params->get('license_number'))) {
                 $limit = $params->get('massautorenewalsnumber', 100);
                 // mass-autorenew 100 subscriptions at a time:
                 $results = cbpaidOrdersMgr::getInstance()->triggerScheduledAutoRecurringPayments((int) $limit);
                 $return = implode("\r\n\r\n", $results);
                 $massrenewalemail = trim($params->get('massrenewalemail', ''));
                 if ($massrenewalemail) {
                     cbimport('cb.notification');
                     $recipients = explode(',', $massrenewalemail);
                     if ($return) {
                         $body = CBPTXT::T("CBSubs has just processed auto-recurring payments as follows:") . "\r\n\r\n" . $return . "\r\n\r\n" . CBPTXT::T("This is an automated email, do not reply.") . "\r\n\r\n";
                         comprofilerMail('', '', $recipients, CBPTXT::T("CBSubs has processed auto-recurring payments"), $body);
                     }
                 }
                 if ($params->get('massrenewaloutputincron', 1) != 1) {
                     // silence output to Cron:
                     $return = null;
                 }
             } else {
                 $return = CBPTXT::Th("Invalid auto-renewals link: link is in global CBSubs settings.");
             }
             break;
         default:
             $return = sprintf(CBPTXT::Th("No valid %s action chosen"), '"do"') . '.';
             break;
     }
     cbpaidErrorHandler::off();
     return $return;
 }
	/**
	 * Returns an array for the 'radios' array of $redirectNow type:
	 * return array( account_id, submethod, paymentMethod:'single'|'subscribe', array(cardtypes), 'label for radio', 'description for radio' )
	 * 
	 * @param  cbpaidPaymentBasket  $paymentBasket  paymentBasket object
	 * @param  string               $subMethod
	 * @param  string               $paymentType
	 * @param  string               $defaultLabel
	 * @return array
	 */
	protected function getPayRadioRecepie( $paymentBasket, $subMethod, $paymentType, $defaultLabel )
	{
		// Settings for Free Trial and Order Now buttons are stored in global CBSubs settings:
		$params					=	cbpaidApp::settingsParams();

		$cardtypes					=	array();

		if ( $this->_button == 'freetrial' ) {
			$brandLabelHtml				=	CBPTXT::Th( $params->get( 'freetrial_radio_name', "Free Trial" ) );		// CBPTXT::T("Free Trial")
			$altText					=	CBPTXT::T( $params->get( 'freetrial_radio_alt', "Subscribe to free trial period only") );	// CBPTXT::T("Subscribe to free trial period only")
			$brandDescriptionHtml		=	CBPTXT::Th( $params->get( 'freetrial_radio_description' ) );
		} else {
			$brandLabelHtml				=	CBPTXT::Th("Confirm Order");
			$altText					=	CBPTXT::T("Confirm Order");
			$brandDescriptionHtml		=	null;
		}
		return cbpaidGatewaySelectorRadio::getPaymentRadio( $this->_button, $subMethod, $paymentType, $cardtypes, $brandLabelHtml, $brandDescriptionHtml, $altText );
		
	}
Пример #24
0
	/**
	 * Generates the HTML to display the user edit tab
	 *
	 * @param  TabTable   $tab       the tab database entry
	 * @param  UserTable  $user      the user being displayed
	 * @param  int        $ui        1 for front-end, 2 for back-end
	 * @return mixed                 either string HTML for tab content, or false if ErrorMSG generated
	 */
	public function getEditTab( $tab, $user, $ui ) {
		global $ueConfig, $_CB_framework;

		$return		=	'';
		if ( ( $ui != 2 ) /* || ( $_CB_framework->myId() == $user->id ) */ ) {
			return $return;
		}

		cbpaidErrorHandler::on();

		if ( cbpaidApp::authoriseAction( 'cbsubs.usersubscriptionview' ) ) {


			$params					=	$this->params;
			
			$paidsubsManager		=&	cbpaidSubscriptionsMgr::getInstance();
			$paidsubsManager->checkExpireMe( __FUNCTION__ );
	
			if ( $user->id ) {
				$basketsMgr			=&	cbpaidOrdersMgr::getInstance();
				$basketsMgr->timeoutUnusedBaskets( $user->id );
			}
	
			$title					=	CBPTXT::Th( $params->get( 'profileTitle', "Your subscriptions" ));
			if ( $title ) {
				$name				=	getNameFormat( $user->name, $user->username, $ueConfig['name_format'] );
				$return				.=	'<div class="contentheading" id="cbregProfileTitle">' . sprintf( $title, $name ) . "</div>\n";
			}
	
			$return					.=	$this->_writeTabDescription( $tab, $user );
	
			$itsmyself				=	( $_CB_framework->myId() == $user->id );

			$subscriptionsGUI		=	new cbpaidControllerUI();
			$return					.=	$subscriptionsGUI->getShowSubscriptionUpgrades( $user, $itsmyself );

		}

		cbpaidErrorHandler::off();
		return $return;

/*
		global $_CB_framework;
		
		$params = $this->params;
		$exampleText		= $params->get('exampletext', 'Text Parameter not set!');

		$xmlfile = $_CB_framework->getCfg( 'absolute_path' ) . '/components/com_comprofiler/plugin/user/plug_cbpaidsubscriptions/cbpaidsubscriptions.xml';
		$this->userParams = new Registry( $user->cb_subs_params, $xmlfile, $maintagname='cbinstall', $attrname='type', $attrvalue='plugin', $paramsnode='params' );

		$ret = $this->userParams->render( $pluginId=null, $tabId=null, $tag_name='userparams',$attr='class',$attrvalue='getcbpaidsubscriptionsTab', $control_name='subscriptionparams', $paramstextarea=false );
		
		return $ret;
*/
	}
 /**
  * View for <param  type="private" class="cbpaidParamsExt" method="checkifexecutable">...
  *
  * @param  string              $value                  Stored Data of Model Value associated with the element
  * @param  ParamsInterface     $pluginParams           Main settigns parameters of the plugin
  * @param  string              $name                   Name attribute
  * @param  CBSimpleXMLElement  $param                  This XML node
  * @param  string              $control_name           Name of the control
  * @param  string              $control_name_name      css id-encode of the names of the controls surrounding this node
  * @param  boolean             $view                   TRUE: view, FALSE: edit
  * @param  cbpaidTable         $modelOfData            Data of the Model corresponding to this View
  * @param  cbpaidTable[]       $modelOfDataRows        Displayed Rows if it is a table
  * @param  int                 $modelOfDataRowsNumber  Total Number of rows
  * @return null|string
  */
 public function checkifexecutable($value, &$pluginParams, $name, &$param, $control_name, $control_name_name, $view, &$modelOfData, &$modelOfDataRows, &$modelOfDataRowsNumber)
 {
     $default = $param->attributes('default');
     $return = '';
     $filePath = isset($modelOfData->{$default}) ? $modelOfData->{$default} : null;
     //->get( 'default' );
     if ($filePath) {
         if (function_exists('is_executable')) {
             $executable = @is_executable($filePath);
             $return .= $this->_outputGreenRed($filePath, $executable, "is executable", "is not found or not executable");
         } else {
             $return .= $this->_outputGreenRed($filePath, false, '', "can not be checked because of SafeMode enabled or is_executable function disabled.");
         }
     } else {
         $return .= $this->_outputGreenRed('', false, '', "No path defined yet. Please define then apply setting to get result of check.");
     }
     // $openSSLloaded	=	extension_loaded( 'openssl' );
     // $return			.=	$this->_outputGreenRed( "openSSL library", $openSSLloaded );
     if (!cbStartOfStringMatch($return, '<div class="cbEnabled">')) {
         if ($default == 'openssl_exec_path') {
             $resultOpenssl = $this->opensslstatus($value, $pluginParams, $name, $param, $control_name, $control_name_name, $view, $modelOfData, $modelOfDataRows, $modelOfDataRowsNumber);
             if (cbStartOfStringMatch($resultOpenssl, '<div class="cbEnabled">')) {
                 $return = '<div class="cbEnabled">' . CBPTXT::Th("Not needed, as OpenSSL PHP module is loaded") . '</div>';
                 return $return;
             }
         }
     }
     return $return;
 }
 /**
  * Returns html text on current status and next steps of payment, depending on payment basket status
  *
  * @param  cbpaidPaymentBasket  $paymentBasket  Payment basket being paid
  * @return string    HTML
  */
 public function getTxtNextStep($paymentBasket)
 {
     switch ($paymentBasket->payment_status) {
         case 'Completed':
             if ($paymentBasket->txn_id && $paymentBasket->subscr_id) {
                 $newMsg = sprintf(CBPTXT::Th("Your payment has been completed with transaction id %s and with subscription id %s."), htmlspecialchars($paymentBasket->txn_id), htmlspecialchars($paymentBasket->subscr_id));
             } elseif ($paymentBasket->txn_id) {
                 $newMsg = sprintf(CBPTXT::Th("Your payment has been completed with transaction id %s."), htmlspecialchars($paymentBasket->txn_id));
             } elseif ($paymentBasket->subscr_id) {
                 $newMsg = sprintf(CBPTXT::Th("Your payment has been completed with subscription id %s."), htmlspecialchars($paymentBasket->subscr_id));
             } else {
                 $newMsg = CBPTXT::Th("Your payment has been completed.");
             }
             break;
         case 'Pending':
             $newMsg = CBPTXT::Th("Your payment is currently being processed.");
             break;
         case 'FreeTrial':
             $newMsg = '';
             break;
         case 'RegistrationCancelled':
             $newMsg = CBPTXT::Th("Payment operation cancelled.") . ' ' . CBPTXT::Th("Please choose another payment method.");
             break;
         case 'Denied':
             $newMsg = CBPTXT::Th("The payment has been denied and therefore not executed.") . ' ' . CBPTXT::Th("Please choose another payment method.");
             break;
         case 'Processed':
         case 'Reversed':
         case 'Refunded':
         case 'Partially-Refunded':
         default:
             $newMsg = CBPTXT::Th("Your transaction is not cleared and has currently following status:") . ' <strong>' . CBPTXT::Th(htmlspecialchars($paymentBasket->payment_status)) . '</strong>.';
             break;
     }
     return $newMsg;
 }
 /**
  * Displays specific plans
  *
  * @param  int[]|null   $plans
  * @param  int[]|null   $plansToPreselect
  * @param  UserTable    $user
  * @param  string       $introText
  * @return null|string
  */
 public static function displaySpecificPlans($plans, $plansToPreselect, $user, $introText)
 {
     global $_CB_framework, $_PLUGINS, $ueConfig;
     $return = '';
     $subscriptionsGUI = new cbpaidControllerUI();
     if (is_array($plans) && count($plans) == 0) {
         $return .= '<div class="message">' . _UE_NOT_AUTHORIZED . ($user === null ? ' ' . _UE_DO_LOGIN : '') . '</div>';
     } else {
         $subscriptionsGUI->setShowOnlyPlans($plans);
         $subscriptionsGUI->setSelectedPlans($plansToPreselect);
         if ($user === null) {
             // Show registration form:
             if ($_CB_framework->getCfg('allowUserRegistration') == '0' && (!isset($ueConfig['reg_admin_allowcbregistration']) || $ueConfig['reg_admin_allowcbregistration'] != '1')) {
                 cbNotAuth();
                 return null;
             }
             if ($_CB_framework->myId()) {
                 $return .= '<div class="error">' . _UE_ALREADY_LOGGED_IN . '</div>';
                 return self::displayWithTemplate($return);
             }
             $fieldsQuery = null;
             $_PLUGINS->loadPluginGroup('user');
             $_PLUGINS->loadPluginGroup('user/plug_cbpaidsubscriptions/plugin');
             $regErrorMSG = null;
             $results = $_PLUGINS->trigger('onBeforeRegisterForm', array('com_comprofiler', isset($ueConfig['emailpass']) ? $ueConfig['emailpass'] : '******', &$regErrorMSG, $fieldsQuery));
             if ($_PLUGINS->is_errors()) {
                 $return .= "<script type=\"text/javascript\">alert('" . addslashes($_PLUGINS->getErrorMSG(" ; ")) . "'); </script>\n";
                 $return .= $_PLUGINS->getErrorMSG("<br />");
                 return self::displayWithTemplate($return);
             }
             if (implode('', $results) != "") {
                 $allResults = implode("</div><div>", $results);
                 $return .= "<div>" . $allResults . "</div>";
                 return self::displayWithTemplate($return);
             }
             $loginOrRegister = CBPTXT::Th(cbpaidApp::settingsParams()->get('plansLoginOrRegisterText', "If you already have an account, please login first. Otherwise you need to register using this form."));
             $userComplete = new UserTable();
             $option = 'com_comprofiler';
             $emailpass = isset($ueConfig['emailpass']) ? $ueConfig['emailpass'] : '******';
             $regErrorMSG = $loginOrRegister . ' ' . $introText;
             ob_start();
             $null = null;
             HTML_comprofiler::registerForm($option, $emailpass, $userComplete, $null, $regErrorMSG, true);
             $return .= ob_get_contents();
             ob_end_clean();
         } else {
             // User logged in: Show upgrade form:
             $itsmyself = true;
             $params = cbpaidApp::settingsParams();
             $subTxt = CBPTXT::T($params->get('subscriptions_name', 'subscriptions'));
             $title = ucfirst($subTxt);
             if ($title) {
                 $return .= '<div class="contentheading" id="cbregProfileTitle">' . $title . "</div>\n";
             }
             if ($introText) {
                 $return .= '<div class="contentpane">' . $introText . '</div>';
             }
             $return .= $subscriptionsGUI->getShowSubscriptionUpgrades($user, $itsmyself);
         }
         $subscriptionsGUI->setShowOnlyPlans(null);
     }
     return self::displayWithTemplate($return);
 }
	/**
	 * 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;
	}
Пример #29
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' => '&euro;', 'USD' => '$', 'GBP' => '&pound;', 'JPY' => '&yen;', 'CHF' => 'Fr.', 'CAD' => 'C$', 'AUD' => '$', 'BRL' => 'R$', 'CNY' => '&yen;', '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;
	}
	/**
	 * 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;
	}