/**
  * View for <param  type="private" class="cbpaidParamsExt" method="checkAllSubscriptions">...
  *
  * @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 checkAllSubscriptions($value, &$pluginParams, $name, &$param, $control_name, $control_name_name, $view, &$modelOfData, &$modelOfDataRows, &$modelOfDataRowsNumber)
 {
     $size = $param->attributes('size');
     if ($size == '') {
         $size = 100;
     }
     $cbsubsParams = cbpaidApp::settingsParams();
     if ($cbsubsParams->get('massexpirymethod') < 3) {
         $plansMgr = cbpaidPlansMgr::getInstance();
         $total = $plansMgr->checkAllSubscriptions((int) $size);
         if ($total == $size) {
             $total .= ' (' . CBPTXT::T("reload page for more mass expiries") . ')';
         }
     } else {
         $total = '0 (' . CBPTXT::T("no mass expiry from admin area, Settings-Global-Massexpiry is only by cron tasks") . ')';
     }
     $basketsMgr = cbpaidOrdersMgr::getInstance();
     $expBaskets = $basketsMgr->timeoutUnusedBaskets(null, (int) $size);
     return $total . ' / ' . $expBaskets;
 }
	/**
	* CB user activation interception
	* 
	* @param  UserTable  $user       + moscomprofile the user being displayed
	* @param  int        $ui         1 for front-end, 2 for back-end
	* @param  string     $returnURL  URL to redirect to (using cbRedirect) (can be changed here !)
	* @return array                  with keys (or null if not intercepting/changing behavior):
	* 		string  ['messagesToUser']	html text to display to user (within a div-tag)
	* 		string	['alertMessage']	false if should not display any JS popup, true otherwise
	* 		boolean ['showSysMessage']	false if should not show the CB standard result error messages to user, true otherwise
	* 		boolean ['stopLogin']		true if should not login, false otherwise
	*/
	public function onDuringLogin( &$user, $ui, &$returnURL ) {
		global $_CB_framework, $_POST;

		cbpaidErrorHandler::on();

		$params							=	$this->params;
		$registrationPlansEnabled		=	$params->get( 'registrationPlansEnabled', 0 );
		$enableFreeRegisteredUser		=	$params->get( 'enableFreeRegisteredUser', 1 );

		$result							=	null;			// no interception or change by default

		$paidsubsManager				=&	cbpaidSubscriptionsMgr::getInstance();
		$paidsubsManager->checkExpireMe( __FUNCTION__, $user->id );

		if ( $registrationPlansEnabled ) {
			// any unpaid basket pending ?
			$basketsMgr					=&	cbpaidOrdersMgr::getInstance();
			$paymentBasket				=	$basketsMgr->loadCurrentUnpaidBasket( $user->id );
//			$paymentBasket				=	new cbpaidPaymentBasket( $_CB_database );
//			if ( $paymentBasket->loadLatestBasketFromUser( $user->id, true ) ) {
			if ( $paymentBasket ) {
				// if there is an unpaid basket, show it to the user, and keep user logged-in or not, depending of $user->block status:
				$introText				=	$params->get('intro_text', null);
				$paymentFormHtml		=	cbpaidControllerOrder::showBasketForPayment( $user, $paymentBasket, $introText );
				$result = array(	'messagesToUser' =>	$paymentFormHtml,
									'alertMessage'	 =>	null,
									'showSysMessage' =>	false,
									'stopLogin'		 =>	false			// $user->block will be tested by CB later		// ( ! $enableFreeRegisteredUser )
								);
				$_POST['loginfrom']		=	'noLoginFormDisplay';
				$this->outputRegTemplate();
				$returnURL				=	null;
			} else {
				// this is now user-subciptions-plans specific stuff:
				$paidUserExtension		=&	cbpaidUserExtension::getInstance( $user->id );
				$subscriptions			=	$paidUserExtension->getUserSubscriptions();
				// user blocked in frontend while not enabling free registered users ?
				if ( ( $ui == 1 ) && $user->block /* && ! $enableFreeRegisteredUser */ ) {
					$subsToPay			=	null;
					$couldPayNow		=	false;
					if ( $user->confirmed && ( $user->approved == 1 ) ) {
						// all fine to login on joomla and CB side
						$couldPayNow	=	true;
					} else {
						foreach ( $subscriptions as $sub ) {
							if ( in_array( $sub->status, array( 'R', 'X') ) && ( ! $sub->checkifValid() ) ) {
								if ( $sub->status == 'R' ) {
									$reason = 'N';
								} else {
									$reason = 'R';
								}
								$now	=	$_CB_framework->now();
								$price	= $sub->getPriceOfNextPayment( null, $now, 1, $reason );
								if ( $price > 0 ) {
					 				if (	( ( ! $user->confirmed ) && ( $sub->getPlanAttribute( 'confirmed' ) != 3 ) )	// unconfirmed but payment not after confirmation
										||	( $user->confirmed && ( $user->approved != 1 )  && ( $sub->getPlanAttribute( 'approved' ) != 3 ) )
										)															// or confirmed but unapproved & payment not after approval
									{
										$couldPayNow	=	true;
										$subsToPay[]	=	array( $sub->plan_id, $sub->id );
									}
								}
							}
						}
					}
					if ( $couldPayNow ) {
						// any unpaid payment basket ?
						$introText		=	$params->get('intro_text', null);
						$paymentStatus	=	null;
						$paymentFormHtml =	cbpaidControllerOrder::showPaymentForm( $user, null, $introText, $subsToPay, $paymentStatus );
						if ($paymentFormHtml ) {
							if ( ( ( $paymentStatus == null ) || ( $paymentStatus == 'NotInitiated' ) )
								// if unpaid: display basket and payment buttons or redirect for payment depending if multiple payment choices or intro text present:
							|| ( $paymentStatus != 'Completed' ) )
								// if payment not completed: display payment basket current status:
							{
								$result = array(	'messagesToUser' =>	$paymentFormHtml,
													'alertMessage'	 =>	null,
													'showSysMessage' =>	false,
													'stopLogin'		 =>	( ! $enableFreeRegisteredUser )
												);
								$_POST['loginfrom']		=	'noLoginFormDisplay';
								$this->outputRegTemplate();
								$returnURL	=	null;
							}
						}
					}
				} else {
					if ( ( strpos( $returnURL, 'getTabComponent' ) || strpos( $returnURL, 'tabclass' ) || strpos( $returnURL, 'pluginclass' ) ) && strpos( $returnURL, 'cbpaidsubscriptions' ) ) {
						// avoid displaying the thank you page again (specially that the registration basket will not be found:
						$returnURL		=	null;
					}
					if ( $user->lastvisitDate == '0000-00-00 00:00:00' ) {
						// user has a paid subscription plan, and it's his first login:
						$firstLoginUrl		=	null;
						$paidUserExtension	=&	cbpaidUserExtension::getInstance( $user->id );
						$subscriptions		=	$paidUserExtension->getUserSubscriptions( 'A' );
						foreach ( $subscriptions as $sub ) {
							if ( $sub->checkifValid() && $sub->getPlanAttribute( 'firstloginurl' ) ) {
								$firstLoginUrl	=	$sub->getPlanAttribute( 'firstloginurl' );
							}
						}
						if ( $firstLoginUrl ) {
							$returnURL		=	cbSef( $firstLoginUrl );
						}
					} else {
						// it's a paid subscription user and see if we need to redirect him to his login-home page URL:
						$eachLoginUrl		=	null;
						$paidUserExtension	=&	cbpaidUserExtension::getInstance( $user->id );
						$subscriptions		=	$paidUserExtension->getUserSubscriptions( 'A' );
						foreach ( $subscriptions as $sub ) {
							if ( $sub->checkifValid() && $sub->getPlanAttribute( 'eachloginurl' ) ) {
								$eachLoginUrl =	$sub->getPlanAttribute( 'eachloginurl' );
							}
						}
						if ( $eachLoginUrl ) {
							$returnURL		=	cbSef( $eachLoginUrl );
						}
					}
				}
			}
				
/*			
			// any paid subscription plan on the way ?
			$chosenPlans				=	$this->_getChosenUserPlans( $user );
			if ( count( $chosenPlans ) > 0 ) {
				// user blocked in frontend while not enabling free registered users ?
				if ( ( $ui == 1 ) && $user->block /* && ! $enableFreeRegisteredUser * / ) {
					$couldPayNow		=	false;
					if ( $user->confirmed && ( $user->approved == 1 ) ) {
						// all fine to login on joomla and CB side
						$couldPayNow	=	true;
					} else {
						foreach ( $chosenPlans as $plan ) {
							if ( $plan->get( 'rate' ) != 0 ) {
				 				if (	( ( ! $user->confirmed ) && ( $plan->get( 'confirmed' ) != 3 ) )	// unconfirmed but payment not after confirmation
									||	( $user->confirmed && ( $user->approved != 1 )  && ( $plan->get( 'approved' ) != 3 ) )
									)															// or confirmed but unapproved & payment not after approval
								{
									$couldPayNow	=	true;
								}
							}
						}
					}
					if ( $couldPayNow ) {
						// any unpaid payment basket ?
						$introText		=	$params->get('intro_text', null);
						$paymentStatus	=	null;
						$paymentFormHtml =	cbpaidControllerOrder::showPaymentForm( $user, $chosenPlans, $introText, null, $paymentStatus );
						if ( ( ( $paymentStatus == null ) || ( $paymentStatus == 'NotInitiated' ) )
							// if unpaid: display basket and payment buttons or redirect for payment depending if multiple payment choices or intro text present:
						|| ( $paymentStatus != 'Completed' ) )
							// if payment not completed: display payment basket current status:
						{
							$result = array(	'messagesToUser' =>	$paymentFormHtml,
												'alertMessage'	 =>	null,
												'showSysMessage' =>	false,
												'stopLogin'		 =>	( ! $enableFreeRegisteredUser )
											);
							$this->_outputRegTemplate();
							$returnURL	=	null;
						}
					}
				} elseif ( $user->lastvisitDate == '0000-00-00 00:00:00' ) {
					// user has a paid subscription plan, and it's his first login:
					if ( strpos( $returnURL, 'getTabComponent' ) && strpos( $returnURL, 'cbpaidsubscriptions' ) ) {
						// avoid displaying the thank you page again (specially that the registration basket will not be found:
						$returnURL		=	null;
					}
					$firstLoginUrl		=	null;
					foreach ( $chosenPlans as $plan ) {
						if ( $plan->get( 'firstloginurl' ) ) {
							$firstLoginUrl	=	$plan->get( 'firstloginurl' );
						}
					}
					if ( $firstLoginUrl ) {
						$returnURL		=	cbSef( $firstLoginUrl );
					}
				} else {
					// it's a paid subscription user and see if we need to redirect him to his login-home page URL:
					$eachLoginUrl		=	null;
					foreach ( $chosenPlans as $plan ) {
						if ( $plan->get( 'firstloginurl' ) ) {
							$eachLoginUrl =	$plan->get( 'eachloginurl' );
						}
					}
					if ( $eachLoginUrl ) {
						$returnURL		=	cbSef( $eachLoginUrl );
					}
				}
			}
*/
		}
		cbpaidErrorHandler::off();
		return $result;
	}
	/**
	 * Displays user subscription and link to invoice HTML (if allowed)
	 *
	 * @param  UserTable  $user
	 * @param  string     $htmlTabDescription
	 * @return string
	 */
	public function displaySubscriptionsAndInvoicesLink( $user, $htmlTabDescription = null ) {
		global $_CB_framework;

		$return					=	'';
		$params					=	$this->params;

		$itsmyself				=	( $_CB_framework->myId() == $user->id );
		$displayToMe			=	$itsmyself;
		if ( ! $itsmyself ) {
			$displayToMe		=	cbpaidApp::authoriseAction( 'cbsubs.usersubscriptionview' );
			if ( $displayToMe ) {
				$itsmyself		=	cbpaidApp::authoriseAction( 'cbsubs.usersubscriptionmanage' );
			}
		}
		if ( $user->id && $displayToMe ) {

			$basketsMgr				=&	cbpaidOrdersMgr::getInstance();
			$basketsMgr->timeoutUnusedBaskets( $user->id );

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

			$htmlInvoicesLink		=	null;
			$showInvoices			=	$params->get( 'show_invoices', 1 );
			$invoicesShowPeriod		=	$params->get( 'invoices_show_period', '0000-06-00 00:00:00' );
			if ( $showInvoices ) {
				$invoicesNumber		=	$this->_getInvoices( $user, $invoicesShowPeriod, true );
				if ( $invoicesNumber > 0 ) {
					$invoicesListUrl =	$this->getInvoicesListUrl( $user );
					if ( $invoicesShowPeriod && ( $invoicesShowPeriod != '0000-00-00 00:00:00' ) ) {
						$cbpaidTimes	=&	cbpaidTimes::getInstance();
						$periodText		=	$cbpaidTimes->renderPeriod( $invoicesShowPeriod, 1, false );
					} else {
						$periodText		=	'';
					}
					$htmlInvoicesLink	=	$subscriptionsGUI->showInvoicesListLink( $invoicesNumber, $invoicesListUrl, $user, $itsmyself, $periodText );
				}
			}

			$tabTitleText			=	$params->get( 'profileTitle', "Your subscriptions" );

			/** @var $viewer cbpaiduserprofilesubstabView */
			$viewer					=	cbpaidTemplateHandler::getViewer( null, 'userprofilesubstab' );
			$viewer->setModel( $user );
			$return					.=	$viewer->drawTab( $htmlSubscriptionsAndUpgrades, $htmlInvoicesLink, $tabTitleText, $htmlTabDescription );
		}
		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;
 }