}
global $_PLUGINS;
$_PLUGINS->registerFunction('onBeforeBackendUsersListBuildQuery', 'onBeforeBackendUsersListBuildQuery', 'cbpaidAdminEvents');
$_PLUGINS->registerFunction('onAfterBackendUsersList', 'onAfterBackendUsersList', 'cbpaidAdminEvents');
$_PLUGINS->registerFunction('onBeforeBackendUsersEmailForm', 'onBeforeBackendUsersEmailForm', 'cbpaidAdminEvents');
// $_PLUGINS->registerFunction( 'onBeforeBackendUsersEmailStart',		'onBeforeBackendUsersEmailStart',		'cbpaidAdminEvents' );
$_PLUGINS->registerFunction('onBeforeBackendUserEmail', 'onBeforeBackendUserEmail', 'cbpaidAdminEvents');
global $_CB_framework;
if ($_CB_framework->getCfg('debug')) {
    ini_set('display_errors', true);
    error_reporting(E_ALL);
}
/** @noinspection PhpIncludeInspection */
include_once $_CB_framework->getCfg('absolute_path') . '/components/com_comprofiler/plugin/user/plug_cbpaidsubscriptions/cbpaidsubscriptions.class.php';
cbpaidErrorHandler::install();
cbpaidErrorHandler::on();
/**
 * Controller class for the admin interface
 */
class cbpaidAdminEvents extends cbpaidApp
{
    // getcbpaidsubscriptionsTab {
    protected $filter_cbpaidplan;
    protected $filter_cbpaidsubstate;
    protected $filter_cbpaidsubexpdate;
    /**
     * Intercepts CB User Manager list controller to add filters evaluation
     *
     * @param  array   $tablesSQL
     * @param  array   $joinsSQL
     * @param  array   $tablesWhereSQL
 /**
  * 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;
 }
	/**
	 * 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   $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 string|boolean        Either string HTML for tab content, or false if ErrorMSG generated
	 */
	public function getTabComponent( $tab, $user, $ui, $postdata ) {
		global $_POST;

		cbpaidErrorHandler::on();

		$tabComponent		=	new cbpaidControllerCBTab();
		$return				=	$tabComponent->getTabComponent( $tab, $user, $ui, $postdata );

		cbpaidErrorHandler::off();
		return $return;
	}
/**
 * Trigger for onBeforeDisplayContent
 * @param  object     $row
 * @param  JRegistry  $articleParams
 * @param  int        $page
 * @return void
 */
function cbpaidsubsbot_onBeforeDisplayContent( &$row, &$articleParams, /** @noinspection PhpUnusedParameterInspection */ $page ) {
	global $_CB_framework;

	$cbpaidBot					=	cbpaidBot::getInstance();

	if ( $cbpaidBot->paidsubsManager === null ) {
			return;
	}
	cbpaidErrorHandler::on();

	if ( isset( $row->id ) ) {
		$myId					=	$_CB_framework->myId();
		$_cbACL					=&	cbpaidBotAclApi::getInstance();
		$access					=	$_cbACL->_cb_checkMultiAcl( $myId, $row->id, isset( $row->catid ) ? $row->catid : null, isset( $row->sectionid ) ? $row->sectionid : null, -1 );

		if ( $access === false ) {

			if ( $_cbACL->_cb_checkMultiAcl( $myId, $row->id, isset( $row->catid ) ? $row->catid : null, isset( $row->sectionid ) ? $row->sectionid : null, count( $_cbACL->cbContentAclRights ) -1 ) !== true ) {

				// allow usage of <!-- !CBPAIDaccessCheck --> to NOT control the item
				if( ! ( isset( $row->text ) && strstr( $row->text, " !CBPAIDaccessCheck " ) ) ) {

					$params							=&	cbpaidApp::settingsParams();

					// allow access to someone who is unrestricted:
					if ( ! $cbpaidBot->hasAccessAnyway( $myId ) ) {

						// var_dump($row);
							// show/hides the intro text
						//	if ( $params->get( 'introtext'  ) ) {
						//		$row->text = $row->introtext. ( $params->get( 'intro_only' ) ? '' : chr(13) . chr(13) . $row->fulltext);
						//	} else {
						//		$row->text = $row->fulltext;
						//	}
						$redirectVars				=	array( 'accesstype' => 'contentdisplay', 'accessvalue' => (int) $row->id );
						$redirectVars['accessurl']	=	cbpaidsubsbot_encodeArrayUrl( $_GET );
			
						$redirectUrl				=	'index.php?option=com_comprofiler&task=pluginclass&plugin=cbpaidsubscriptions&do=accessdenied' . getCBprofileItemid( false);		// &Itemid= ???
						foreach ( $redirectVars as $k => $v ) {
							$redirectUrl			.=	'&' . urlencode( $k ) . '=' . urlencode( $v );
						}
			
						// translate message:
						cbpaidApp::loadLang();
						$subTxt						=	CBPTXT::T( $params->get( 'subscription_name', 'subscription' ) );

						$allowAccessToIntro			=	$params->get( 'integration_cpaycontent_allowIntro', '1' );
						// If access to intro is NO (0), or DEPENDS (2) but there is no main full text, then we do not allow to see anything:
						$disallowAccessToAnyText	=	( $allowAccessToIntro == 0 ) || ( ( $allowAccessToIntro == 2 ) && ! ( isset( $row->readmore ) ? $row->readmore != 0 : trim( strip_tags( $row->fulltext ) ) != '' ) );

						if ( $disallowAccessToAnyText ) {
							$messageTxt				=	'<span class="cbpaidContentAccessDenied">' . sprintf( CBPTXT::Th( 'To read this article, a %s is needed: Click here to subscribe' ), $subTxt ) . '</span>';
						} else {
							$messageTxt				=	'<span class="cbpaidContentAccessDenied">' . sprintf( CBPTXT::Th( 'To read more, a %s is needed: Click here to subscribe' ), $subTxt ) . '</span>';
						}

						if ( ( ($cbpaidBot->option == 'com_content' || $cbpaidBot->option == 'content') && ( ( $cbpaidBot->task == 'view' ) || ( $cbpaidBot->task == '' ) ) && ( $cbpaidBot->view != 'frontpage' ) && ( $cbpaidBot->view != 'featured' ) ) )  {
							// article view:
							if ( $disallowAccessToAnyText ) {
								// option=com_content&task=view
								cbRedirect( cbSef( $redirectUrl, false ), sprintf( CBPTXT::T("Access to this content is not allowed without %s"), $subTxt ) );
								return;
							}
							// 1.5: needed for title links:
							$row->readmore_link		=	cbSef( $redirectUrl );
							if ( ( $cbpaidBot->cbCmsVersion == 1 ) && ( in_array( $cbpaidBot->view, array( 'frontpage', 'section', 'category' ) ) ) ) {
								// 1.5: (section and category are for layout=blog (section blog), but as section layout just displays categories, it is ok to not check for that)
								$row->readmore_register	=	false;
								$articleParams->set( 'readmore', $messageTxt );
							} else {
								$row->text			=	$row->introtext;

								if ( trim( strip_tags( $row->fulltext ) ) ) {
									$row->text			.=	'<a href="' . cbSef( $redirectUrl ) . '">' . $messageTxt . '</a>';
								}
							}
						} else {
							//	$row->text			=	$row->text . $message;
							// 1.0:
							$row->link_text			=	$messageTxt;
							$row->link_on			=	cbSef( $redirectUrl );
							$articleParams->set( 'intro_only', 1 );
							if ( $cbpaidBot->cbCmsVersion == 1 ) {
								$articleParams->set( 'readmore', $messageTxt );
							} else {
								$articleParams->set( 'readmore', 1 );
							}
							// 1.5: needed for title links:
							$row->readmore_link		=	cbSef( $redirectUrl );
							if ( $disallowAccessToAnyText ) {
								$row->introtext		=	'';
								$row->text			=	'';
								$row->readmore		=	1;
							}
							if ( class_exists( 'JDatabaseQuery' ) ) {
								// 1.6:
								$row->alternative_readmore	=	'</a>' . '<a class="cbregPayToViewRedirectLink" href="' . cbSef( $redirectUrl ) . '">' . $messageTxt . ' ';		// Space is for case of article title in readmore link following. Ideally should be ': ' in that case only.
							}
						}
					}
				}
			}
		}

		// run cbsubs plan substitutions after access readmore access checks
		if ( isset( $row->title ) ) {
			$row->title			=	preg_replace_callback( '/\{cbsubs:plan:(\d+):(.*?)\}/s', array( $cbpaidBot, 'replacePlanSubstitutions' ), $row->title );
		}

		if ( isset( $row->introtext ) ) {
			$row->introtext		=	preg_replace_callback( '/\{cbsubs:plan:(\d+):(.*?)\}/s', array( $cbpaidBot, 'replacePlanSubstitutions' ), $row->introtext );
		}

		if ( isset( $row->fulltext ) ) {
			$row->fulltext		=	preg_replace_callback( '/\{cbsubs:plan:(\d+):(.*?)\}/s', array( $cbpaidBot, 'replacePlanSubstitutions' ), $row->fulltext );
		}

		if ( isset( $row->text ) ) {
			$row->text			=	preg_replace_callback( '/\{cbsubs:plan:(\d+):(.*?)\}/s', array( $cbpaidBot, 'replacePlanSubstitutions' ), $row->text );
		}
	}
	cbpaidErrorHandler::off();

}