/**
  * 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);
 }
	/**
	 * Renders a basket with content
	 *
	 * @param  string  $summaryText     Title         default: CBPTxt("Payment")
	 * @param  string  $captionText     Subtitle      default: CBPTxt("Your membership for payment:")
	 * @param  string  $displayColumnsParamsBaseName  'basket' or 'invoice'
	 * @param  string  $output                        'html' or ?
	 * @return string                                 HTML content with a table for the basket
	 */
	public function displayBasket( $summaryText = "Payment", $captionText = "Your membership for payment:", $displayColumnsParamsBaseName = 'basket', $output = 'html' ) {
		$return							=	null;

		$params							=&	cbpaidApp::settingsParams();

		$this->loadPaymentItems();
		$this->loadPaymentTotalizers();

		$displayColumns					=	 $this->_basketColumns( $displayColumnsParamsBaseName . '_item_line1_columns' );
		$totalizerColumns				=	 $this->_basketColumns( $displayColumnsParamsBaseName . '_totalizer_line1_columns' );

		// Now computes all basket items lines columns content, and removes completely emty columns:

		// this will hold 2-dimensional array of values in basket items view:
		$itemsLinesCols					=	array();
		foreach ( array_keys( $this->_paymentItems ) as $lineIdx ) {
			$itemsLinesCols[$lineIdx]['plan_cssclass']		=		$this->_paymentItems[$lineIdx]->getPlanParam( 'cssclass', '', null );
			foreach ( array_keys( $displayColumns ) as $colName ) {
				$itemsLinesCols[$lineIdx][$colName]		=	$this->renderBasketItem( $lineIdx, $colName, $output );
			}
		}
		if ( $params->get( $displayColumnsParamsBaseName . '_item_display_empty_columns', 0 ) == 0 ) {
			$this->_cleanUpEmptyColumns( $displayColumns, $itemsLinesCols );
		}

		$totalizerLinesCols				=	array();
		foreach ( array_keys( $this->_paymentTotalizers ) as $lineIdx ) {
			$totalizerLinesCols[$lineIdx]['totalizer_type']		=	$this->_paymentTotalizers[$lineIdx]->totalizer_type;
			foreach ( array_keys( $totalizerColumns ) as $colName ) {
				$totalizerLinesCols[$lineIdx][$colName]			=	$this->renderBasketTotalizer( $lineIdx, $colName, $output );
			}
		}
		if ( $params->get( $displayColumnsParamsBaseName . '_totalizer_display_empty_columns', 0 ) == 0 ) {
			$this->_cleanUpEmptyColumns( $totalizerColumns, $totalizerLinesCols );
		}


		if ( count( $this->_paymentTotalizers ) == 0 ) {
			// We have an old basket, that did not have totalizers: we still need to display it properly:
			if ( count ( $totalizerColumns ) == 0 ) {
				$totalizerColumns		=	array( 'description' =>	'Item', 'rate'	=>	'Price' );
			}
			$totalizerLinesCols			=	array();
			if ( ( (float) $this->tax ) != 0.0 ) {
				$renderedTotalNoTax		=	$this->renderTax( $this->mc_gross - $this->tax, true );
				$renderedTaxAmount		=	$this->renderTax( $this->tax, true );

				$totalizerLinesCols[]	=	array( 'totalizer_type' => 'subtotal1', 'description' =>	CBPTXT::Th("Total before tax"), 'rate'	=>	$renderedTotalNoTax );
				$totalizerLinesCols[]	=	array( 'totalizer_type' => 'salestax', 'description' => CBPTXT::Th("Sales tax"), 'rate'	=>	$renderedTaxAmount );
			}
			$renderedBasketPrice		=	$this->renderPrice( null, null, null, true );
			$totalizerLinesCols[]		=	array( 'totalizer_type' => 'grandtotal', 'description' => CBPTXT::Th("Total"), 'rate'	=>	$renderedBasketPrice );
		}

		$subscriptionsGUI				=	new cbpaidControllerUI();
		$return							=	$subscriptionsGUI->showBasket( $this, $summaryText, $captionText, $displayColumns, $totalizerColumns, $itemsLinesCols, $totalizerLinesCols );

		return $return;
	}
	/**
	 * 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;
	}
	/**
	 * 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;
	}
	/**
	 * Checks and binds the plans choosen at registration
	 * 
	 * @param  UserTable     $user        reflecting the user being registered
	 * @return cbpaidProduct[]|string
	 */
	protected function & _getRegistrationChoosenPlans( &$user ) {
		global $_POST;

		static $firstCall							=	true;
		static $chosenPlans							=	null;
		if ( $firstCall ) {
			$firstCall								=	false;
			$params									=	$this->params;
			$registrationPlansEnabled				=	$params->get( 'registrationPlansEnabled', 0 );
			if ( $registrationPlansEnabled ) {
				$subscriptionsGUI					=	new cbpaidControllerUI();
				$chosenPlans						=	$subscriptionsGUI->getAndCheckChosenRegistrationPlans( $_POST, $user );
			}
		}
		return $chosenPlans;
	}
	/**
	 * Cancels an existing recurring subscription
	 *
	 * @param  cbpaidPaymentBasket  $paymentBasket  paymentBasket object
	 * @param  cbpaidPaymentItem[]  $paymentItems   redirect immediately instead of returning HTML for output
	 * @return boolean|string                       TRUE if unsubscription done successfully, STRING if error
	 */
	protected function handleStopPaymentSubscription( $paymentBasket, $paymentItems )
	{
		global $_CB_framework, $_CB_database;

		if ( $paymentBasket->mc_amount3 ) {
			// Recurring amount existing and if first amount existed it got payed OK: subscribe to an ARB:
			if ( $paymentBasket->subscr_id ) {
				
				if ( $this->hasPaypalApi() /* && ( substr( $paymentBasket->subscr_id, 0, 2 ) != 'S-' ) */ ) {			// Only subscription ids starting with I- can be handled through API for unsubscription: S- subscriptions can not.
					// There is an API access, let's try to use it:

					$return						=	$this->getPaypalApi()->ManageRecurringPaymentsProfileStatus( $paymentBasket->subscr_id, 'cancel', null );
					if ( $return ) {
						// Success! : $return is TRUE:
						$ipn					=	new cbpaidPaymentNotification( $_CB_database );
						$ipn->payment_method	=	$this->getPayName();
						$ipn->gateway_account	=	$this->getAccountParam( 'id' );
						$ipn->log_type			=	'5';
						$ipn->time_received		=	date( 'Y-m-d H:i:s', $_CB_framework->now() );
						$ipn->raw_data			=	/* cbGetParam() not needed: we want raw info */ '$_GET=' . var_export( $_GET, true ) . ";\n";
						$ipn->raw_data			.=	/* cbGetParam() not needed: we want raw info */ '$_POST=' . var_export( $_POST, true ) . ";\n";
						$ipn->raw_data			.=	$this->getPaypalApi()->getRawLogData() . ";\n";
						$ipn->ip_addresses		=	cbpaidRequest::getIPlist();
						$ipn->payment_basket_id	=	$paymentBasket->id;
						$ipn->user_id			=	$paymentBasket->user_id;
						$_CB_database->insertObject( $ipn->getTableName(), $ipn, $ipn->getKeyName() );

					} else {
						$this->setLogPaypalApiErrors( $paymentBasket );
						$return					=	'';
					}
				} else {
					$return						=	'';
				}
				if ( ! $return ) {
					// No API, we can only render a button: (which is not displayed in case of upgrades):

					if ( ! is_string( $return ) ) {
						$return					=	'';
					}

					$return						.=	CBPTXT::Th("You are currently using PayPal  Recurring Payments to pay for your subscription. To unsubscribe and stop future payments, you must to do this from Paypal. Click on the button below to login into PayPal and follow the instructions there to unsubscribe. This will automatically stop your subscription on this site.");
	
					$paymentButton				=	$this->getPayButtonRecepie( $paymentBasket, 'subscribe', 'cancel' );
	
					// Needed to post the button:
					$subscriptionsGUI					=	new cbpaidControllerUI();
					$subscriptionsGUI->addcbpaidjsplugin();

					/** @var $renderer cbpaidBasketView */
					$renderer					=	cbpaidTemplateHandler::getViewer( null, 'basket' );
					$renderer->setModel( $paymentBasket );
					$return						.=	$renderer->drawPaymentButton( $paymentButton );
				}
			} else {
				$this->_setLogErrorMSG( 3, null, 'Paypal autorecurring payment subscriptions: stopPaymentSubscription error: missing subscr_id in payment basket', CBPTXT::T("Submitted unsubscription didn't return an error but didn't complete.") );
				$return							=	'';
			}
		} else {
			$return								=	CBPTXT::T("Unsubscription from payment processor is not possible as this payment basket has no autorecurring amount.");
		}
		return $return;
	}