function plug_cbgroupjiveabout_install()
{
	// Grab GJ params to migrate the legacy params:
	$plugin				=	new PluginTable();

	$plugin->load( array( 'element' => 'cbgroupjive' ) );

	$pluginParams		=	new Registry( $plugin->get( 'params' ) );

	if ( ( ! $pluginParams->has( 'about_content' ) ) || ( $pluginParams->get( 'about_content' ) == null ) ) {
		return;
	}

	// Migrate about integration parameters:
	$about				=	new PluginTable();

	$about->load( array( 'element' => 'cbgroupjiveabout' ) );

	$aboutParams		=	new Registry( $about->get( 'params' ) );

	if ( $aboutParams->get( 'migrated' ) ) {
		return;
	}

	$aboutParams->set( 'groups_about_content_plugins', $pluginParams->get( 'about_content' ) );
	$aboutParams->set( 'migrated', true );

	$about->set( 'params', $aboutParams->asJson() );

	$about->store();
}
function plug_cbgroupjivevideo_install()
{
	// Grab GJ params to migrate the legacy params:
	$plugin				=	new PluginTable();

	$plugin->load( array( 'element' => 'cbgroupjive' ) );

	$pluginParams		=	new Registry( $plugin->get( 'params' ) );

	if ( ( ! $pluginParams->has( 'video_captcha' ) ) || ( $pluginParams->get( 'video_captcha' ) == null ) ) {
		return;
	}

	// Migrate video integration parameters:
	$video				=	new PluginTable();

	$video->load( array( 'element' => 'cbgroupjivevideo' ) );

	$videoParams		=	new Registry( $video->get( 'params' ) );

	if ( $videoParams->get( 'migrated' ) ) {
		return;
	}

	$videoParams->set( 'groups_video_captcha', $pluginParams->get( 'video_captcha' ) );
	$videoParams->set( 'groups_video_paging', $pluginParams->get( 'video_paging' ) );
	$videoParams->set( 'groups_video_limit', $pluginParams->get( 'video_limit' ) );
	$videoParams->set( 'groups_video_search', $pluginParams->get( 'video_search' ) );
	$videoParams->set( 'migrated', true );

	$video->set( 'params', $videoParams->asJson() );

	$video->store();
}
function plug_cbgroupjiveforums_install()
{
	// Grab GJ params to migrate the legacy params:
	$plugin				=	new PluginTable();

	$plugin->load( array( 'element' => 'cbgroupjive' ) );

	$pluginParams		=	new Registry( $plugin->get( 'params' ) );

	if ( ( ! $pluginParams->has( 'forum_id' ) ) || ( $pluginParams->get( 'forum_id' ) == null ) ) {
		return;
	}

	// Migrate forums integration parameters:
	$forums				=	new PluginTable();

	$forums->load( array( 'element' => 'cbgroupjiveforums' ) );

	$forumsParams		=	new Registry( $forums->get( 'params' ) );

	if ( $forumsParams->get( 'migrated' ) ) {
		return;
	}

	$forumsParams->set( 'groups_forums_category', $pluginParams->get( 'forum_id' ) );
	$forumsParams->set( 'groups_forums_paging', $pluginParams->get( 'forum_paging' ) );
	$forumsParams->set( 'groups_forums_limit', $pluginParams->get( 'forum_limit' ) );
	$forumsParams->set( 'groups_forums_search', $pluginParams->get( 'forum_search' ) );
	$forumsParams->set( 'migrated', true );

	$forums->set( 'params', $forumsParams->asJson() );

	$forums->store();
}
	/**
	 * @param  TabTable   $tab       Current tab
	 * @param  UserTable  $user      Current user
	 * @param  int        $ui        1 front, 2 admin UI
	 * @param  array      $postdata  Raw unfiltred POST data
	 * @return string                HTML
	 */
	public function getCBpluginComponent( $tab, $user, $ui, $postdata )
	{
		$format				=	$this->input( 'format', null, GetterInterface::STRING );

		if ( $format != 'raw' ) {
			outputCbJs();
			outputCbTemplate();
		}

		$action				=	$this->input( 'action', null, GetterInterface::STRING );
		$function			=	$this->input( 'func', null, GetterInterface::STRING );
		$id					=	(int) $this->input( 'id', null, GetterInterface::INT );
		$user				=	CBuser::getMyUserDataInstance();

		if ( $format != 'raw' ) {
			ob_start();
		}

		switch ( $action ) {
			case 'wall':
				switch ( $function ) {
					case 'publish':
						$this->stateWall( 1, $id, $user );
						break;
					case 'unpublish':
						$this->stateWall( 0, $id, $user );
						break;
					case 'delete':
						$this->deleteWall( $id, $user );
						break;
					case 'new':
						$this->showWallEdit( null, $user );
						break;
					case 'edit':
						$this->showWallEdit( $id, $user );
						break;
					case 'save':
						cbSpoofCheck( 'plugin' );
						$this->saveWallEdit( $id, $user );
						break;
				}
				break;
		}

		if ( $format != 'raw' ) {
			$html			=	ob_get_contents();
			ob_end_clean();

			$class			=	$this->_gjParams->get( 'general_class', null );

			$return			=	'<div class="cbGroupJive' . ( $class ? ' ' . htmlspecialchars( $class ) : null ) . '">'
							.		'<div class="cbGroupJiveInner">'
							.			$html
							.		'</div>'
							.	'</div>';

			echo $return;
		}
	}
 /**
  * Gets a param value
  *
  * @param  string|string[]        $key      Name of index or array of names of indexes, each with name or input-name-encoded array selection, e.g. a.b.c
  * @param  mixed|GetterInterface  $default  [optional] Default value, or, if instanceof GetterInterface, parent GetterInterface for the default value
  * @param  string|array           $type     [optional] default: null: raw. Or const int GetterInterface::COMMAND|GetterInterface::INT|... or array( const ) or array( $key => const )
  * @return string|array
  *
  * @throws \InvalidArgumentException        If namespace doesn't exist
  */
 public function get($key, $default = null, $type = null)
 {
     if (substr($key, 0, 11) == 'permission:') {
         $parts = explode(':', substr($key, 11));
         if (count($parts) < 2) {
             return cbpaidApp::authoriseAction($parts[0]) ? 1 : 0;
         } else {
             return cbpaidApp::authoriseAction($parts[1], $parts[0]) ? 1 : 0;
         }
     }
     return parent::get($key, $default);
 }
function plug_cb_profilebook_uninstall()
{
	global $_CB_database;

	$html_return			=	'';
	
	// if needed get cb profilebook plugin parameters
	$plugparms_query		=	"SELECT params"
							.	"\n FROM #__comprofiler_plugin"
							.	"\n WHERE element='cb.profilebook'";
	$_CB_database->setQuery( $plugparms_query );
	$cbpbplugparms			=	$_CB_database->loadResult();

	$params					=	new Registry( $cbpbplugparms );

	if ( $params->get( 'pbUnistallMode' ) ) {			// if full unistall mode parameter selected then purge everything
		$drop_table_query	=	'DROP TABLE `#__comprofiler_plug_profilebook`';
		$_CB_database->setQuery( $drop_table_query );
		$ret				=	$_CB_database->query();
		if( ! $ret ) {
			$html_return	.=	'<div style="font-size:14px;color:red;margin-bottom:10px;">Failed to drop table #__comprofiler_plug_profilebook</div>';
		} else {
			$html_return	.=	'<div style="font-size:14px;color:green;margin-bottom:10px;">Table #__comprofiler_plug_profilebook deleted (all items lost)</div>';
		}
		$drop_fields_query	=	"ALTER TABLE `#__comprofiler` DROP COLUMN `cb_pb_enable`,"
							.	"\n DROP COLUMN `cb_pb_autopublish`,"
							.	"\n DROP COLUMN `cb_pb_notifyme`";	
		$_CB_database->setQuery( $drop_fields_query );
		$ret				=	$_CB_database->query();
		if( ! $ret ) {
			$html_return	.=	'<div style="font-size:14px;color:red;margin-bottom:10px;">Failed to delete Plugin fields from #__comprofiler table</div>';
		} else {
			$html_return	.=	'<div style="font-size:14px;color:green;margin-bottom:10px;">Plugin fields deleted from #__comprofiler table (all personalization lost)</div>';
		}
	} else {
		// just unistall plugin code - keep all data
		$html_return		.=	'<div style="font-size:14px;color:green;margin-bottom:10px;">The profilebook plugin has been deleted but data remains so upgrade is possible</div>';
	}
	# Show installation result to user
	echo 'Plugin successfully uninstalled. See bellow for extra status messages';
	return $html_return;
}
function plug_cbgroupjivephoto_install()
{
	// Grab GJ params to migrate the legacy params:
	$plugin				=	new PluginTable();

	$plugin->load( array( 'element' => 'cbgroupjive' ) );

	$pluginParams		=	new Registry( $plugin->get( 'params' ) );

	if ( ( ! $pluginParams->has( 'photo_captcha' ) ) || ( $pluginParams->get( 'photo_captcha' ) == null ) ) {
		return;
	}

	// Migrate photo integration parameters:
	$photo				=	new PluginTable();

	$photo->load( array( 'element' => 'cbgroupjivephoto' ) );

	$photoParams		=	new Registry( $photo->get( 'params' ) );

	if ( $photoParams->get( 'migrated' ) ) {
		return;
	}

	$photoParams->set( 'groups_photo_captcha', $pluginParams->get( 'photo_captcha' ) );
	$photoParams->set( 'groups_photo_image_height', $pluginParams->get( 'photo_maxheight' ) );
	$photoParams->set( 'groups_photo_image_width', $pluginParams->get( 'photo_maxwidth' ) );
	$photoParams->set( 'groups_photo_thumbnail_height', $pluginParams->get( 'photo_thumbheight' ) );
	$photoParams->set( 'groups_photo_thumbnail_width', $pluginParams->get( 'photo_thumbwidth' ) );
	$photoParams->set( 'groups_photo_max_size', $pluginParams->get( 'photo_maxsize' ) );
	$photoParams->set( 'groups_photo_paging', $pluginParams->get( 'photo_paging' ) );
	$photoParams->set( 'groups_photo_limit', $pluginParams->get( 'photo_limit' ) );
	$photoParams->set( 'groups_photo_search', $pluginParams->get( 'photo_search' ) );
	$photoParams->set( 'migrated', true );

	$photo->set( 'params', $photoParams->asJson() );

	$photo->store();
}
function plug_cbgroupjivewall_install()
{
	// Grab GJ params to migrate the legacy params:
	$plugin				=	new PluginTable();

	$plugin->load( array( 'element' => 'cbgroupjive' ) );

	$pluginParams		=	new Registry( $plugin->get( 'params' ) );

	if ( ( ! $pluginParams->has( 'wall_inputlimit' ) ) || ( $pluginParams->get( 'wall_inputlimit' ) == null ) ) {
		return;
	}

	// Migrate wall integration parameters:
	$wall				=	new PluginTable();

	$wall->load( array( 'element' => 'cbgroupjivewall' ) );

	$wallParams			=	new Registry( $wall->get( 'params' ) );

	if ( $wallParams->get( 'migrated' ) ) {
		return;
	}

	$wallParams->set( 'groups_wall_character_limit', $pluginParams->get( 'wall_inputlimit' ) );
	$wallParams->set( 'groups_wall_replies', $pluginParams->get( 'wall_reply' ) );
	$wallParams->set( 'groups_wall_replies_paging', $pluginParams->get( 'wall_replypaging' ) );
	$wallParams->set( 'groups_wall_replies_limit', $pluginParams->get( 'wall_replylimit' ) );
	$wallParams->set( 'groups_wall_paging', $pluginParams->get( 'wall_paging' ) );
	$wallParams->set( 'groups_wall_limit', $pluginParams->get( 'wall_limit' ) );
	$wallParams->set( 'migrated', true );

	$wall->set( 'params', $wallParams->asJson() );

	$wall->store();
}
function plug_cbgroupjivefile_install()
{
	// Grab GJ params to migrate the legacy params:
	$plugin				=	new PluginTable();

	$plugin->load( array( 'element' => 'cbgroupjive' ) );

	$pluginParams		=	new Registry( $plugin->get( 'params' ) );

	if ( ( ! $pluginParams->has( 'file_captcha' ) ) || ( $pluginParams->get( 'file_captcha' ) == null ) ) {
		return;
	}

	// Migrate file integration parameters:
	$file				=	new PluginTable();

	$file->load( array( 'element' => 'cbgroupjivefile' ) );

	$fileParams			=	new Registry( $file->get( 'params' ) );

	if ( $fileParams->get( 'migrated' ) ) {
		return;
	}

	$fileParams->set( 'groups_file_captcha', $pluginParams->get( 'file_captcha' ) );
	$fileParams->set( 'groups_file_max_size', $pluginParams->get( 'file_maxsize' ) );
	$fileParams->set( 'groups_file_extensions', $pluginParams->get( 'file_types' ) );
	$fileParams->set( 'groups_file_paging', $pluginParams->get( 'file_paging' ) );
	$fileParams->set( 'groups_file_limit', $pluginParams->get( 'file_limit' ) );
	$fileParams->set( 'groups_file_search', $pluginParams->get( 'file_search' ) );
	$fileParams->set( 'migrated', true );

	$file->set( 'params', $fileParams->asJson() );

	$file->store();
}
	/**
	 * Internal method to get all menu types
	 *
	 * @return string[]
	 */
	function _form_mos_menu__menutypes() {
		global $_CB_database;

		$query		=	"SELECT params"
			.	"\n FROM #__modules"
			.	"\n WHERE module = 'mod_mainmenu'"
			//.	"\n ORDER BY title"
		;
		$_CB_database->setQuery( $query	);
		$modMenus	=	$_CB_database->loadObjectList();

		$query		=	"SELECT menutype"
			.	"\n FROM #__menu"
			.	"\n GROUP BY menutype"
			//.	"\n ORDER BY menutype"
		;
		$_CB_database->setQuery( $query	);
		$menuMenus	=	$_CB_database->loadResultArray();

		$menuTypes	=	array();

		foreach ( $modMenus as $modMenu ) {
			$modParams 		=	new Registry( $modMenu->params );
			$menuType 		=	$modParams->get( 'menutype' );
			if ( ! $menuType ) {
				$menuType	=	'mainmenu';
			}
			if ( ! in_array( $menuType, $menuTypes ) ) {
				$menuTypes[] =	$menuType;
			}
		}

		foreach ( $menuMenus as $menuType ) {
			if ( ! in_array( $menuType, $menuTypes ) ) {
				$menuTypes[] =	$menuType;
			}
		}

		asort( $menuTypes );
		return $menuTypes;				//FIXME: this seems quite broken! (but as unused it's ok for now)
	}
Example #11
0
/**
 * Checks if a page is executed https, and if not, if it should be according to login module HTTPS posts specifications
 * 
 * @param  boolean  $return  [default: false] : True: returns if https switchover is needed for the POST form (if not already on HTTPS and login module asks for it). False: errors 403 if not in https and it's configured in login module.
 * @return boolean           True: switchover needed (returned only if $return = true)
 */
function checkCBPostIsHTTPS($return = false)
{
    global $_CB_framework, $_CB_database, $_SERVER;
    $isHttps = isset($_SERVER['HTTPS']) && !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off';
    if (!$isHttps && file_exists($_CB_framework->getCfg('absolute_path') . '/modules/' . (checkJversion() > 0 ? 'mod_cblogin/' : null) . 'mod_cblogin.php')) {
        $language = CBuser::getMyUserDataInstance()->getUserLanguage();
        if (!$language) {
            $language = Application::Cms()->getLanguageTag();
        }
        $query = 'SELECT ' . $_CB_database->NameQuote('params') . "\n FROM " . $_CB_database->NameQuote('#__modules') . "\n WHERE " . $_CB_database->NameQuote('module') . " = " . $_CB_database->Quote('mod_cblogin') . "\n AND " . $_CB_database->NameQuote('published') . " = 1" . "\n AND " . $_CB_database->NameQuote('access') . " IN " . $_CB_database->safeArrayOfIntegers(Application::MyUser()->getAuthorisedViewLevels()) . "\n AND " . $_CB_database->NameQuote('language') . " IN ( " . $_CB_database->Quote($language) . ", " . $_CB_database->Quote('*') . ", " . $_CB_database->Quote('') . " )" . "\n ORDER BY " . $_CB_database->NameQuote('position') . ", " . $_CB_database->NameQuote('ordering');
        $_CB_database->setQuery($query, 0, 1);
        $module = $_CB_database->loadResult();
        if ($module) {
            $params = new Registry($module);
            $https_post = $params->get('https_post', 0) != 0;
        } else {
            $https_post = false;
        }
    } else {
        $https_post = false;
    }
    if ($return) {
        return $https_post;
    } else {
        if ($https_post && !$isHttps) {
            header('HTTP/1.0 403 Forbidden');
            exit(CBTxt::T('UE_NOT_AUTHORIZED', 'You are not authorized to view this page!'));
        }
    }
    return null;
}
	/**
	 * 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;
	}
Example #13
0
	/**
	 * @param UserTable  $user
	 * @param GroupTable $group
	 * @param array      $counters
	 * @return array|null
	 */
	public function getTopics( $user, &$group, &$counters )
	{
		global $_CB_framework, $_CB_database;

		$categoryId					=	(int) $group->params()->get( 'forum_id' );

		if ( ( ! $categoryId ) || ( ! $group->params()->get( 'forums', 1 ) ) || ( $group->category()->get( 'id' ) && ( ! $group->category()->params()->get( 'forums', 1 ) ) ) ) {
			return null;
		}

		CBGroupJive::getTemplate( 'forums', true, true, $this->plugin->element );

		$limit						=	(int) $this->params->get( 'groups_forums_limit', 15 );
		$limitstart					=	$_CB_framework->getUserStateFromRequest( 'gj_group_forums_limitstart{com_comprofiler}', 'gj_group_forums_limitstart' );
		$search						=	$_CB_framework->getUserStateFromRequest( 'gj_group_forums_search{com_comprofiler}', 'gj_group_forums_search' );
		$where						=	null;

		if ( $search && $this->params->get( 'groups_forums_search', 1 ) ) {
			$where					.=	'( m.' . $_CB_database->NameQuote( 'subject' ) . ' LIKE ' . $_CB_database->Quote( '%' . $_CB_database->getEscaped( $search, true ) . '%', false )
									.	' OR t.' . $_CB_database->NameQuote( 'message' ) . ' LIKE ' . $_CB_database->Quote( '%' . $_CB_database->getEscaped( $search, true ) . '%', false ) . ' )';
		}

		$searching					=	( $where ? true : false );

		$params						=	array(	'starttime' => -1,
												'where' => $where
											);

		$posts						=	\KunenaForumMessageHelper::getLatestMessages( $categoryId, 0, 0, $params );
		$total						=	array_shift( $posts );

		if ( ( ! $total ) && ( ! $searching ) && ( ! CBGroupJive::canCreateGroupContent( $user, $group, 'forums' ) ) ) {
			return null;
		}

		$pageNav					=	new \cbPageNav( $total, $limitstart, $limit );

		$pageNav->setInputNamePrefix( 'gj_group_forums_' );

		switch( (int) $this->params->get( 'groups_forums_orderby', 2 ) ) {
			case 1:
				$params['orderby']	=	'm.' . $_CB_database->NameQuote( 'time' ) . ' ASC';
				break;
		}

		if ( $this->params->get( 'groups_forums_paging', 1 ) ) {
			$posts					=	\KunenaForumMessageHelper::getLatestMessages( $categoryId, (int) $pageNav->limitstart, (int) $pageNav->limit, $params );
			$posts					=	array_pop( $posts );
		} else {
			$posts					=	array_pop( $posts );
		}

		$rows						=	array();

		/** @var \KunenaForumMessage[] $posts */
		foreach ( $posts as $post ) {
			$row					=	new PostTable();

			$row->post( $post );

			$rows[]					=	$row;
		}

		$input						=	array();

		$input['search']			=	'<input type="text" name="gj_group_forums_search" value="' . htmlspecialchars( $search ) . '" onchange="document.gjGroupForumsForm.submit();" placeholder="' . htmlspecialchars( CBTxt::T( 'Search Posts...' ) ) . '" class="form-control" />';

		CBGroupJive::preFetchUsers( $rows );

		$group->set( '_forums', $pageNav->total );

		return array(	'id'		=>	'forums',
						'title'		=>	CBTxt::T( 'Forums' ),
						'content'	=>	\HTML_groupjiveForums::showForums( $rows, $pageNav, $searching, $input, $counters, $group, $user, $this )
					);
	}
function plug_cbautoactions_install()
{
	global $_CB_framework, $_CB_database;

	$table									=	'#__comprofiler_plugin_autoactions';
	$fields									=	$_CB_database->getTableFields( $table );

	if ( isset( $fields[$table]['field'] ) ) {
		$translateExists					=	isset( $fields[$table]['translate'] );
		$excludeExists						=	isset( $fields[$table]['exclude'] );
		$debugExists						=	isset( $fields[$table]['debug'] );

		$query								=	'SELECT *'
											.	"\n FROM " . $_CB_database->NameQuote( '#__comprofiler_plugin_autoactions' );
		$_CB_database->setQuery( $query );
		$rows								=	$_CB_database->loadObjectList( null, '\CBLib\Database\Table\Table', array( $_CB_database, '#__comprofiler_plugin_autoactions', 'id' ) );

		/** @var $rows Table[] */
		foreach ( $rows as $row ) {
			$row->set( 'trigger', str_replace( ',', '|*|', $row->get( 'trigger' ) ) );
			$row->set( 'params', new Registry( $row->get( 'params' ) ) );

			$newParams						=	new Registry();

			if ( $row->get( 'field' ) ) {
				$fields						=	new Registry( $row->get( 'field' ) );
				$operators					=	new Registry( $row->get( 'operator' ) );
				$values						=	new Registry( $row->get( 'value' ) );

				if ( $translateExists ) {
					$translates				=	new Registry( $row->get( 'translate' ) );
				} else {
					$translates				=	null;
				}

				$conditionals				=	count( $fields );

				if ( $conditionals ) {
					$conditions				=	array();

					for ( $i = 0, $n = $conditionals; $i < $n; $i++ ) {
						$field				=	$fields->get( "field$i" );
						$operator			=	$operators->get( "operator$i" );
						$value				=	$values->get( "value$i" );

						if ( $translateExists ) {
							$translate		=	$translates->get( "translate$i" );
						} else {
							$translate		=	0;
						}

						if ( $operator ) {
							$conditions[]	=	array( 'field' => $field, 'operator' => $operator, 'value' => $value, 'translate' => $translate );
						}
					}

					if ( $conditions ) {
						$newConditionals	=	new Registry( $conditions );

						$row->set( 'conditions', $newConditionals->asJson() );
					}
				}

				$row->set( 'field', null );
				$row->set( 'operator', null );
				$row->set( 'value', null );

				if ( $translateExists ) {
					$row->set( 'translate', null );
				}
			}

			if ( $excludeExists ) {
				$exclude					=	$row->get( 'exclude' );

				if ( $exclude ) {
					$newParams->set( 'exclude', $exclude );
					$row->set( 'exclude', null );
				}
			}

			if ( $debugExists ) {
				$debug						=	$row->get( 'debug' );

				if ( $debug ) {
					$newParams->set( 'debug', $debug );
					$row->set( 'debug', null );
				}
			}

			if ( method_exists( 'cbautoactionsMigrate', $row->get( 'type' ) ) ) {
				call_user_func_array( array( 'cbautoactionsMigrate', $row->get( 'type' ) ), array( &$row, &$newParams ) );
			}

			$row->set( 'params', $newParams->asJson() );

			$row->store( true );
		}

		$_CB_database->dropColumn( $table, 'field' );
		$_CB_database->dropColumn( $table, 'operator' );
		$_CB_database->dropColumn( $table, 'value' );

		if ( $translateExists ) {
			$_CB_database->dropColumn( $table, 'translate' );
		}

		if ( $excludeExists ) {
			$_CB_database->dropColumn( $table, 'exclude' );
		}

		if ( $debugExists ) {
			$_CB_database->dropColumn( $table, 'debug' );
		}
	} else {
		// Convert old |*| delimitered triggers to comma separated:
		$query								=	'UPDATE ' . $_CB_database->NameQuote( '#__comprofiler_plugin_autoactions' )
											.	"\n SET " . $_CB_database->NameQuote( 'trigger' ) . " = REPLACE( " . $_CB_database->NameQuote( 'trigger' ) . ", " . $_CB_database->Quote( ',' ) . ", " . $_CB_database->Quote( '|*|' ) . " )";
		$_CB_database->setQuery( $query );
		$_CB_database->query();
	}

	// Delete system actions that no longer exist:
	if ( isset( $fields[$table]['system'] ) ) {
		$xmlFile							=	$_CB_framework->getCfg( 'absolute_path' ) . '/components/com_comprofiler/plugin/user/plug_cbautoactions/cbautoactions.xml';

		if ( file_exists( $xmlFile ) ) {
			$xml							=	new SimpleXMLElement( trim( file_get_contents( $xmlFile ) ) );

			$systemRows						=	$xml->xpath( '//database/table[@name="#__comprofiler_plugin_autoactions"]/rows/row[@index="system"]/@value' );

			if ( $systemRows !== false ) {
				$systemIds					=	array();

				foreach ( $systemRows as $systemRow ) {
					$systemIds[]			=	(string) $systemRow;
				}

				if ( $systemIds ) {
					$query					=	'DELETE'
											.	"\n FROM " . $_CB_database->NameQuote( '#__comprofiler_plugin_autoactions' )
											.	"\n WHERE " . $_CB_database->NameQuote( 'system' ) . " NOT IN " . $_CB_database->safeArrayOfIntegers( $systemIds )
											.	"\n AND " . $_CB_database->NameQuote( 'system' ) . " != 0";
					$_CB_database->setQuery( $query );
					$_CB_database->query();
				}
			}
		}
	}
}
function plug_cbgroupjiveevents_install()
{
	global $_CB_database;

	// Grab GJ params to migrate the legacy params:
	$plugin						=	new PluginTable();

	$plugin->load( array( 'element' => 'cbgroupjive' ) );

	$pluginParams				=	new Registry( $plugin->get( 'params' ) );

	if ( $pluginParams->has( 'events_event_content' ) || ( $pluginParams->get( 'events_event_content' ) != null ) ) {
		// Migrate events integration parameters:
		$events					=	new PluginTable();

		$events->load( array( 'element' => 'cbgroupjiveevents' ) );

		$eventsParams			=	new Registry( $events->get( 'params' ) );

		if ( ! $eventsParams->get( 'migrated' ) ) {
			$eventsParams->set( 'groups_events_content_plugins', $pluginParams->get( 'events_event_content' ) );
			$eventsParams->set( 'groups_events_address', $pluginParams->get( 'events_plotting' ) );
			$eventsParams->set( 'groups_events_captcha', $pluginParams->get( 'events_captcha' ) );
			$eventsParams->set( 'groups_events_paging', $pluginParams->get( 'group_tab_paging' ) );
			$eventsParams->set( 'groups_events_limit', $pluginParams->get( 'group_tab_limit' ) );
			$eventsParams->set( 'groups_events_search', $pluginParams->get( 'group_tab_search' ) );
			$eventsParams->set( 'migrated', true );

			$events->set( 'params', $eventsParams->asJson() );

			$events->store();
		}
	}

	$table						=	'#__groupjive_plugin_events';
	$fields						=	$_CB_database->getTableFields( $table );

	if ( isset( $fields[$table]['date'] ) ) {
		$now					=	Application::Database()->getUtcDateTime();

		// Move attending to attendance table:
		$query					=	'SELECT ' . $_CB_database->NameQuote( 'id' )
								.	', ' . $_CB_database->NameQuote( 'attending' )
								.	"\n FROM " . $_CB_database->NameQuote( '#__groupjive_plugin_events' );
		$_CB_database->setQuery( $query );
		$rows					=	$_CB_database->loadAssocList( 'id', 'attending' );

		$attend					=	array();

		foreach ( $rows as $id => $attending ) {
			foreach ( explode( '|*|', $attending ) as $attendee ) {
				$attendee		=	explode( ':', $attendee );
				$userId			=	( isset( $attendee[0] ) ? (int) $attendee[0] : null );
				$attendance		=	( isset( $attendee[1] ) ? (int) $attendee[1] : null );

				if ( $userId && ( $attendance == 1 ) ) {
					$attend[]	=	'( ' . (int) $userId . ', ' . (int) $id . ', ' . $_CB_database->Quote( $now ) . ' )';
				}
			}
		}

		if ( $attend ) {
			$query				=	'INSERT IGNORE INTO '. $_CB_database->NameQuote( '#__groupjive_plugin_events_attendance' )
								.	' ( '
								.		$_CB_database->NameQuote( 'user_id' )
								.		', ' . $_CB_database->NameQuote( 'event' )
								.		', ' . $_CB_database->NameQuote( 'date' )
								.	' ) VALUES ' . implode( ', ', $attend );
			$_CB_database->setQuery( $query );
			$_CB_database->query();
		}

		// Mode date to start:
		$query					=	'UPDATE '. $_CB_database->NameQuote( '#__groupjive_plugin_events' )
								.	"\n SET " . $_CB_database->NameQuote( 'start' ) . " = " . $_CB_database->NameQuote( 'date' );
		$_CB_database->setQuery( $query );
		$_CB_database->query();

		// Remove the old columns:
		$_CB_database->dropColumn( $table, 'latitude' );
		$_CB_database->dropColumn( $table, 'longitude' );
		$_CB_database->dropColumn( $table, 'attending' );
		$_CB_database->dropColumn( $table, 'date' );
	}
}
Example #16
0
/**
 * Checks if a page is executed https, and if not, if it should be according to login module HTTPS posts specifications
 * 
 * @param  boolean  $return  [default: false] : True: returns if https switchover is needed for the POST form (if not already on HTTPS and login module asks for it). False: errors 403 if not in https and it's configured in login module.
 * @return boolean           True: switchover needed (returned only if $return = true)
 */
function checkCBPostIsHTTPS($return = false)
{
    global $_CB_framework, $_CB_database, $_SERVER;
    $isHttps = isset($_SERVER['HTTPS']) && !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off';
    if (!$isHttps && file_exists($_CB_framework->getCfg('absolute_path') . '/modules/' . (checkJversion() > 0 ? 'mod_cblogin/' : null) . 'mod_cblogin.php')) {
        $query = 'SELECT ' . $_CB_database->NameQuote('params') . "\n FROM " . $_CB_database->NameQuote('#__modules') . "\n WHERE " . $_CB_database->NameQuote('module') . " = " . $_CB_database->Quote('mod_cblogin') . "\n ORDER BY " . $_CB_database->NameQuote('ordering');
        $_CB_database->setQuery($query, 0, 1);
        $module = $_CB_database->loadResult();
        if ($module) {
            $params = new Registry($module);
            $https_post = $params->get('https_post', 0) != 0;
        } else {
            $https_post = false;
        }
    } else {
        $https_post = false;
    }
    if ($return) {
        return $https_post;
    } else {
        if ($https_post && !$isHttps) {
            header('HTTP/1.0 403 Forbidden');
            exit(CBTxt::T('UE_NOT_AUTHORIZED', 'You are not authorized to view this page!'));
        }
    }
    return null;
}
Example #17
0
	/**
	 * @param cbinvitesInviteTable[] $rows
	 * @param cbPageNav              $pageNav
	 * @param bool                   $searching
	 * @param array                  $input
	 * @param UserTable              $viewer
	 * @param UserTable              $user
	 * @param TabTable               $tab
	 * @param cbTabHandler           $plugin
	 * @return string
	 */
	static function showTab( $rows, $pageNav, $searching, $input, $viewer, $user, $tab, $plugin )
	{
		global $_CB_framework, $_CB_database;

		$params						=	new Registry( $tab->params );
		$profileOwner				=	( $viewer->get( 'id' ) == $user->get( 'id' ) );
		$cbModerator				=	Application::User( (int) $viewer->get( 'id' ) )->isGlobalModerator();

		$tabPaging					=	$params->get( 'tab_paging', 1 );
		$canSearch					=	( $params->get( 'tab_search', 1 ) && ( $searching || $pageNav->total ) );

		$inviteLimit				=	(int) $plugin->params->get( 'invite_limit', null );
		$canCreate					=	false;

		if ( $profileOwner ) {
			if ( $cbModerator ) {
				$canCreate			=	true;
			} elseif ( $user->get( 'id' ) && Application::MyUser()->canViewAccessLevel( $plugin->params->get( 'invite_create_access', 2 ) ) ) {
				if ( $inviteLimit ) {
					$query			=	'SELECT COUNT(*)'
									.	"\n FROM " . $_CB_database->NameQuote( '#__comprofiler_plugin_invites' )
									.	"\n WHERE " . $_CB_database->NameQuote( 'user_id' ) . " = " . (int) $user->get( 'id' )
									.	"\n AND ( " . $_CB_database->NameQuote( 'user' ) . " IS NULL OR " . $_CB_database->NameQuote( 'user' ) . " = " . $_CB_database->Quote( '' ) . " )";
					$_CB_database->setQuery( $query );
					$inviteCount	=	(int) $_CB_database->loadResult();

					if ( $inviteCount < $inviteLimit ) {
						$canCreate	=	true;
					}
				} else {
					$canCreate		=	true;
				}
			}
		}

		$return						=	'<div class="invitesTab">'
									.		'<form action="' . $_CB_framework->userProfileUrl( $user->get( 'id' ), true, $tab->tabid ) . '" method="post" name="inviteForm" id="inviteForm" class="inviteForm">';

		if ( $canCreate || $canSearch ) {
			$return					.=			'<div class="invitesHeader row" style="margin-bottom: 10px;">';

			if ( $canCreate ) {
				$return				.=				'<div class="' . ( ! $canSearch ? 'col-sm-12' : 'col-sm-8' ) . ' text-left">'
									.					'<button type="button" onclick="location.href=\'' . $_CB_framework->pluginClassUrl( $plugin->element, false, array( 'action' => 'invites', 'func' => 'new' ) ) . '\';" class="invitesButton invitesButtonNew btn btn-success"><span class="fa fa-plus-circle"></span> ' . CBTxt::T( 'New Invite' ) . '</button>'
									.				'</div>';
			}

			if ( $canSearch ) {
				$return				.=				'<div class="' . ( ! $canCreate ? 'col-sm-offset-8 ' : null ) . 'col-sm-4 text-right">'
									.					'<div class="input-group">'
									.						'<span class="input-group-addon"><span class="fa fa-search"></span></span>'
									.						$input['search']
									.					'</div>'
									.				'</div>';
			}

			$return					.=			'</div>';
		}

		$menuAccess					=	( $cbModerator || $profileOwner );

		if ( $menuAccess ) {
			if ( $rows ) foreach ( $rows as $row ) {
				if ( $row->canResend() || ( ! $row->isAccepted() ) ) {
					$menuAccess		=	true;
					break;
				}
			}
		}

		$return						.=			'<table class="invitesContainer table table-hover table-responsive">'
									.				'<thead>'
									.					'<tr>'
									.						'<th class="text-left">' . CBTxt::T( 'To' ) . '</th>'
									.						'<th style="width: 25%;" class="text-left hidden-xs">' . CBTxt::T( 'Date' ) . '</th>'
									.						'<th style="width: 5%;" class="text-center hidden-xs">' . CBTxt::T( 'Status' ) . '</th>'
									.						( $menuAccess ? '<th style="width: 1%;" class="text-right">&nbsp;</th>' : null )
									.					'</tr>'
									.				'</thead>'
									.				'<tbody>';

		if ( $rows ) foreach ( $rows as $row ) {
			if ( $row->get( 'user' ) ) {
				$toUser				=	CBuser::getInstance( (int) $row->get( 'user' ), false )->getField( 'formatname', null, 'html', 'none', 'list', 0, true );
			} else {
				$toUser				=	'******' . htmlspecialchars( $row->get( 'to' ) ) . '">' . $row->get( 'to' ) . '</a>';
			}

			$return					.=					'<tr>'
									.						'<td class="text-left">' . $toUser . '</td>'
									.						'<td style="width: 25%;" class="text-left hidden-xs">'
									.							( $row->isSent() ? '<div class="text-info" title="' . htmlspecialchars( CBTxt::T( 'Sent' ) ) . '">' . cbFormatDate( $row->get( 'sent' ) ) . '</div>' : '<div class="text-warning">' . CBTxt::T( 'Please Resend' ) . '</div>' )
									.							( $row->isAccepted() ? '<div class="text-success" title="' . htmlspecialchars( CBTxt::T( 'Accepted' ) ) . '">' . cbFormatDate( $row->get( 'accepted' ) ) . '</div>' : null )
									.						'</td>'
									.						'<td style="width: 5%;" class="text-center hidden-xs">';

			if ( $row->isAccepted() ) {
				$return				.=							'<span class="fa fa-check text-success" title="' . htmlspecialchars( CBTxt::T( 'Accepted' ) ) . '"></span>';
			} elseif ( $row->isSent() ) {
				$return				.=							'<span class="fa fa-clock-o text-warning" title="' . htmlspecialchars( CBTxt::T( 'Pending' ) ) . '"></span>';
			} else {
				$return				.=							'<span class="fa fa-warning text-danger" title="' . htmlspecialchars( CBTxt::T( 'Resend' ) ) . '"></span>';
			}

			$return					.=						'</td>';

			if ( ( $cbModerator || $profileOwner ) && ( $row->canResend() || ( ! $row->isAccepted() ) ) ) {
				$menuItems			=	'<ul class="invitesMenuItems dropdown-menu" style="display: block; position: relative; margin: 0;">';

				if ( $row->canResend() ) {
					$menuItems		.=		'<li class="invitesMenuItem"><a href="' . $_CB_framework->pluginClassUrl( $plugin->element, true, array( 'action' => 'invites', 'func' => 'send', 'id' => (int) $row->get( 'id' ) ) ) . '"><span class="fa fa-share-square-o"></span> ' . CBTxt::T( 'Resend' ) . '</a></li>';
				}

				if ( ! $row->isAccepted() ) {
					$menuItems		.=		'<li class="invitesMenuItem"><a href="' . $_CB_framework->pluginClassUrl( $plugin->element, true, array( 'action' => 'invites', 'func' => 'edit', 'id' => (int) $row->get( 'id' ) ) ) . '"><span class="fa fa-edit"></span> ' . CBTxt::T( 'Edit' ) . '</a></li>'
									.		'<li class="invitesMenuItem"><a href="javascript: void(0);" onclick="if ( confirm( \'' . addslashes( CBTxt::T( 'Are you sure you want to delete this Invite?' ) ) . '\' ) ) { location.href = \'' . $_CB_framework->pluginClassUrl( $plugin->element, false, array( 'action' => 'invites', 'func' => 'delete', 'id' => (int) $row->get( 'id' ) ) ) . '\'; }"><span class="fa fa-trash-o"></span> ' . CBTxt::T( 'Delete' ) . '</a></li>';
				}

				$menuItems			.=	'</ul>';

				$menuAttr			=	cbTooltip( 1, $menuItems, null, 'auto', null, null, null, 'class="btn btn-default btn-xs" data-cbtooltip-menu="true" data-cbtooltip-classes="qtip-nostyle"' );

				$return				.=						'<td style="width: 1%;" class="text-right">'
									.							'<div class="invitesMenu btn-group">'
									.								'<button type="button"' . $menuAttr . '><span class="fa fa-cog"></span> <span class="fa fa-caret-down"></span></button>'
									.							'</div>'
									.						'</td>';
			} elseif ( $menuAccess ) {
				$return				.=						'<td style="width: 1%;" class="text-right"></td>';
			}

			$return					.=					'</tr>';
		} else {
			$return					.=					'<tr>'
									.						'<td colspan="' . ( $menuAccess ? 4 : 3 ) . '" class="text-left">';

			if ( $searching ) {
				$return				.=							CBTxt::T( 'No invite search results found.' );
			} else {
				if ( $viewer->id == $user->id ) {
					$return			.=							CBTxt::T( 'You have no invites.' );
				} else {
					$return			.=							CBTxt::T( 'This user has no invites.' );
				}
			}

			$return					.=						'</td>'
									.					'</tr>';
		}

		$return						.=				'</tbody>';

		if ( $tabPaging && ( $pageNav->total > $pageNav->limit ) ) {
			$return					.=				'<tfoot>'
									.					'<tr>'
									.						'<td colspan="' . ( $menuAccess ? 4 : 3 ) . '" class="text-center">'
									.							$pageNav->getListLinks()
									.						'</td>'
									.					'</tr>'
									.				'</tfoot>';
		}

		$return						.=			'</table>'
									.			$pageNav->getLimitBox( false )
									.		'</form>'
									.	'</div>';

		return $return;
	}
Example #18
0
	/**
	 * @param cbinvitesInviteTable[] $rows
	 * @param cbPageNav              $pageNav
	 * @param bool                   $searching
	 * @param array                  $input
	 * @param UserTable              $viewer
	 * @param UserTable              $user
	 * @param TabTable               $tab
	 * @param cbTabHandler           $plugin
	 * @return string
	 */
	static function showTab( $rows, $pageNav, $searching, $input, $viewer, $user, $tab, $plugin )
	{
		global $_CB_framework, $_CB_database;

		$params						=	new Registry( $tab->params );
		$profileOwner				=	( $viewer->get( 'id' ) == $user->get( 'id' ) );
		$cbModerator				=	Application::User( (int) $viewer->get( 'id' ) )->isGlobalModerator();

		$tabPaging					=	$params->get( 'tab_paging', 1 );
		$canSearch					=	( $params->get( 'tab_search', 1 ) && ( $searching || $pageNav->total ) );

		$inviteLimit				=	(int) $plugin->params->get( 'invite_limit', null );
		$canCreate					=	false;
                
                $user_groups_can_create = array(12,16); //proizvoditeli, komercheskie organizacii
                $gids = $user->get('gids');

		if ( $profileOwner ) {
			if ( $cbModerator ) {
				$canCreate			=	true;
			} elseif ( $user->get( 'id' )   ) {
				if ( $inviteLimit ) {
					$query			=	'SELECT COUNT(*)'
									.	"\n FROM " . $_CB_database->NameQuote( '#__comprofiler_plugin_invites' )
									.	"\n WHERE " . $_CB_database->NameQuote( 'user_id' ) . " = " . (int) $user->get( 'id' )
									.	"\n AND ( " . $_CB_database->NameQuote( 'user' ) . " IS NULL OR " . $_CB_database->NameQuote( 'user' ) . " = " . $_CB_database->Quote( '' ) . " )";
					$_CB_database->setQuery( $query );
					$inviteCount	=	(int) $_CB_database->loadResult();

					if ( $inviteCount < $inviteLimit ) {
						$canCreate	=	true;
					}
				} else {
					$canCreate		=	true;
				}
			}
		}
                $groupcancreate = false;
                if($gids){
                    foreach($gids as $gid){
                        if(in_array($gid, $user_groups_can_create)){
                            $groupcancreate = true;
                        }
                    }
                    
                }
                
                if(!$groupcancreate){
                    $canCreate = false;
                }

		$return						=	'<div class="medizdTab">'
									.		'<form action="' . $_CB_framework->userProfileUrl( $user->get( 'id' ), true, $tab->tabid ) . '" method="post" name="medizdForm" id="inviteForm" class="medizdForm">';

		if ( $canCreate || $canSearch ) {
			$return					.=			'<div class="medizdHeader row" style="margin-bottom: 10px;">';

			if ( $canCreate ) {
				$return				.=				'<div class="' . ( ! $canSearch ? 'col-sm-12' : 'col-sm-8' ) . ' text-left">'
									.					'<button type="button" onclick="location.href=\'' . $_CB_framework->pluginClassUrl( $plugin->element, false, array( 'action' => 'medizd', 'func' => 'new' ) ) . '\';" class="invitesButton invitesButtonNew btn btn-success"><span class="fa fa-plus-circle"></span> ' . CBTxt::T( 'MEDPR_NEW_PRODUCT' ) . '</button>'
									.				'</div>';
			}

			if ( $canSearch ) {
				$return				.=				'<div class="' . ( ! $canCreate ? 'col-sm-offset-8 ' : null ) . 'col-sm-4 text-right">'
									.					'<div class="input-group">'
									.						'<span class="input-group-addon"><span class="fa fa-search"></span></span>'
									.						$input['search']
									.					'</div>'
									.				'</div>';
			}

			$return					.=			'</div>';
		}

		$menuAccess					=	( $cbModerator || $profileOwner );

		

		$return						.=			'<table class="invitesContainer table table-hover table-responsive">'
									.				'<thead>'
									.					'<tr>'
									.						'<th class="text-left">' . CBTxt::T( 'MEDPR_CODE' ) . '</th>'
									.						'<th style="width: 25%;" class="text-left hidden-xs">' . CBTxt::T( 'Name' ) . '</th>'
									.						'<th style="width: 5%;" class="text-center hidden-xs">' . CBTxt::T( 'Date' ) . '</th>'
                                                                        .                                               '<th style="width: 1%;" class="text-left hidden-xs"></th>'
									.					'</tr>'
									.				'</thead>'
									.				'<tbody>';

		if ( $rows ) foreach ( $rows as $row ) {
			

			$return					.=					'<tr>'
									.						'<td class="text-left"><a href="'.JRoute::_(JUri::base().'index.php?option=com_medicineproducts&view=item&id='.$row->id).'">' . $row->code . '</td>'
									.						'<td style="width: 50%;" class="text-left hidden-xs">'
									.							$row->name
									.						'</td>'
									.						'<td style="width: 25%;" class="text-center hidden-xs">'
                                                                        .                                               $row->created;

			

			$return					.=						'</td>';

			if ( ( $cbModerator || $profileOwner )    ) {
				$menuItems			=	'<ul class="invitesMenuItems dropdown-menu" style="display: block; position: relative; margin: 0;">';

                                    $link = $_CB_framework->pluginClassUrl( $plugin->element, false, array( 'action' => 'medizd', 'func' => 'edit', 'id' => (int) $row->get( 'id' )));
				
					$menuItems		.=		'<li class="invitesMenuItem"><a href="' . $link . '"><span class="fa fa-edit"></span> ' . CBTxt::T( 'Edit' ) . '</a></li>'
									.		'<li class="invitesMenuItem"><a href="javascript: void(0);" onclick="if ( confirm( \'' . addslashes( CBTxt::T( 'MEDPR_CONFIRM_DEL' ) ) . '\' ) ) { location.href = \'' . $_CB_framework->pluginClassUrl( $plugin->element, false, array( 'action' => 'medizd', 'func' => 'delete', 'id' => (int) $row->get( 'id' ) ) ) . '\'; }"><span class="fa fa-trash-o"></span> ' . CBTxt::T( 'Delete' ) . '</a></li>';
				

				$menuItems			.=	'</ul>';

				$menuAttr			=	cbTooltip( 1, $menuItems, null, 'auto', null, null, null, 'class="btn btn-default btn-xs" data-cbtooltip-menu="true" data-cbtooltip-classes="qtip-nostyle"' );

				$return				.=						'<td style="width: 1%;" class="text-right">'
									.							'<div class="invitesMenu btn-group">'
									.								'<button type="button"' . $menuAttr . '><span class="fa fa-cog"></span> <span class="fa fa-caret-down"></span></button>'
									.							'</div>'
									.						'</td>';
			} else{
				$return				.=						'<td style="width: 1%;" class="text-right"></td>';
			}

			$return					.=					'</tr>';
		} else {
			$return					.=					'<tr>'
									.						'<td colspan="3" class="text-left">';

			if ( $searching ) {
				$return				.=							CBTxt::T( 'MEDPR_PRODUCT_SEARCH_NULL' );
			} else {
				if ( $viewer->id == $user->id ) {
					$return			.=							CBTxt::T( 'MEDPR_NO_PRODUCT' );
				} else {
					$return			.=							CBTxt::T( 'MEDPR_USER_NO_PRODUCT' );
				}
			}

			$return					.=						'</td>'
									.					'</tr>';
		}

		$return						.=				'</tbody>';

		if ( $tabPaging && ( $pageNav->total > $pageNav->limit ) ) {
			$return					.=				'<tfoot>'
									.					'<tr>'
									.						'<td colspan="3" class="text-center">'
									.							$pageNav->getListLinks()
									.						'</td>'
									.					'</tr>'
									.				'</tfoot>';
		}

		$return						.=			'</table>'
									.			$pageNav->getLimitBox( false )
									.		'</form>'
									.	'</div>';

		return $return;
	}
Example #19
0
	/**
	 * Valiadtes a captcha code
	 *
	 * @param null|string $code
	 * @param bool        $reset
	 * @return bool
	 */
	public function validateCaptcha( $code = null, $reset = true )
	{
		global $_CB_framework, $_CB_database;

		if ( ! $code ) {
			$code									=	$this->getCaptchaInputValue();
		}

		$valid										=	false;
		$ipAddresses								=	cbGetIParray();
		$ipAddress									=	trim( array_shift( $ipAddresses ) );

		if ( $code ) switch( $this->mode ) {
			case 'recaptcha':
				$client								=	new GuzzleHttp\Client();

				try {
					$body							=	array(	'secret' => $this->params->get( 'captcha_recaptcha_secret_key', null ),
																'remoteip' => $ipAddress,
																'response' => $code
															);

					$result							=	$client->get( 'https://www.google.com/recaptcha/api/siteverify', array( 'query' => $body ) );

					if ( $result->getStatusCode() == 200 ) {
						$response					=	$result->json();

						if ( isset( $response['success'] ) && ( $response['success'] == true ) ) {
							$valid					=	true;
						}
					}
				} catch ( Exception $e ) {}
				break;
			case 'question':
				$captchaQuestions					=	"What is 2 plus 2?=4\n"
													.	"What is 1 times 6?=6\n"
													.	"What is 9 divide 3?=3\n"
													.	"Are you a Human?=Yes\n"
													.	"Are you a Bot?=No\n"
													.	"How many words is this?=5\n"
													.	"How many fingers on a hand?=5\n"
													.	"How many toes on a foot?=5\n"
													.	"What is 10 add 10?=20\n"
													.	"What is 0 multiply 100?=0\n"
													.	"What is 5 minus 1?=4\n"
													.	"What is 2 add 2?=4\n"
													.	"4th letter of Test is?=t\n"
													.	"20, 81, 3; which is smallest?=3\n"
													.	"12, 31, 9; which is greatest?=31\n"
													.	"Purple, car, dog; which is a color?=Purple\n"
													.	"Cat, plane, rock; which is an animal?=Cat\n"
													.	"If tomorrow is Monday; what day is today?=Sunday\n"
													.	"Tim, cat, dog; which is human?=Tim";

				$questions							=	$this->params->get( 'captcha_internal_questions', $captchaQuestions );

				if ( ! $questions ) {
					$questions						=	$captchaQuestions;
				}

				$questions							=	explode( "\n", $questions );
				$codes								=	array();

				foreach ( $questions as $question ) {
					$question						=	explode( '=', $question );
					$key							=	( isset( $question[0] ) ? trim( CBTxt::T( $question[0] ) ) : null );
					$value							=	( isset( $question[1] ) ? trim( CBTxt::T( $question[1] ) ) : null );

					if ( $key && $value ) {
						$codes[$key]				=	$value;
					}
				}

				$captchaCode						=	$this->getCaptchaCode();

				if ( $captchaCode && isset( $codes[$captchaCode] ) && ( strtolower( $codes[$captchaCode] ) == strtolower( $code ) ) ) {
					$valid							=	true;
				}
				break;
			case 'internal':
			default:
				$captchaCode						=	$this->getCaptchaCode();

				if ( $captchaCode && ( $captchaCode == $code ) ) {
					$valid							=	true;
				}
				break;
		}

		if ( $valid && $reset ) {
			$this->setSession( null );
		}

		if ( $this->params->get( 'captcha_honeypot', 1 ) ) {
			$honeyPot								=	$this->params->get( 'captcha_honeypot_name', 'full_address' );

			if ( ! $honeyPot ) {
				$honeyPot							=	'full_address';
			}

			if ( Get::get( $_REQUEST, $honeyPot, null, GetterInterface::STRING ) ) {
				$valid								=	false;
			}
		}

		if ( $reset ) {
			$blocked								=	cbantispamClass::getUserBlock( null, $ipAddress );
			$message								=	$this->params->get( 'captcha_autoblock_msg', 'Your captcha attempt has been blocked. Reason: [reason]' );

			if ( $blocked ) {
				if ( $message ) {
					$extras							=	array(	'[duration]' => ucwords( strtolower( str_replace( array( '+', '-' ), '', $blocked->get( 'duration' ) ) ) ),
																'[date]' => $blocked->get( 'date' ) . ' UTC',
																'[expire]' => $blocked->getExpire() . ( $blocked->get( 'duration' ) ? ' UTC' : null )
															);

					$extras							=	array_merge( $extras, array( '[reason]' => CBTxt::T( 'CAPTCHA_BLOCK_REASON', ( $blocked->get( 'reason' ) ? $blocked->get( 'reason' ) : 'Spam.' ), $extras ) ) );

					$this->error					=	CBTxt::T( 'CAPTCHA_BLOCK_MESSAGE', $message, $extras );
				}

				$valid								=	false;
			} elseif ( $this->params->get( 'general_attempts', 1 ) ) {
				if ( ! $valid ) {
					$timeframe						=	$this->params->get( 'captcha_autoblock_timeframe', '-1 DAY' );

					$query							=	'SELECT *'
													.	"\n FROM " . $_CB_database->NameQuote( '#__comprofiler_plugin_antispam_attempts' )
													.	"\n WHERE " . $_CB_database->NameQuote( 'ip_address' ) . " = " . $_CB_database->Quote( $ipAddress )
													.	"\n AND " . $_CB_database->NameQuote( 'type' ) . " = " . $_CB_database->Quote( 'captcha' )
													.	"\n ORDER BY " . $_CB_database->NameQuote( 'date' ) . " DESC";
					$_CB_database->setQuery( $query, 0, 1 );
					$attempt						=	new cbantispamAttemptsTable();
					$_CB_database->loadObject( $attempt );

					if ( ! $attempt->get( 'id' ) ) {
						$attempt->set( 'ip_address', $ipAddress );
						$attempt->set( 'type', 'captcha' );
						$attempt->set( 'count', 1 );
					} elseif ( ( ! $timeframe ) || ( $_CB_framework->getUTCTimestamp( $attempt->get( 'date' ) ) >= $_CB_framework->getUTCTimestamp( strtolower( $timeframe ) ) ) ) {
						$attempt->set( 'count', ( (int) $attempt->get( 'count' ) + 1 ) );
					}

					$attempt->set( 'date', $_CB_framework->getUTCDate() );

					$attempt->store();

					if ( $this->params->get( 'captcha_autoblock', 1 ) && cbantispamClass::isUserBlockable( null, $ipAddress ) ) {
						$count						=	(int) $this->params->get( 'captcha_autoblock_count', 20 );

						if ( ! $count ) {
							$count					=	20;
						}

						if ( (int) $attempt->get( 'count' ) >= $count ) {
							$reason					=	$this->params->get( 'captcha_autoblock_reason', 'Too many failed captcha attempts.' );

							if ( $this->params->get( 'captcha_autoblock_method', 0 ) ) {
								$row				=	new cbantispamBlockTable();

								$row->set( 'type', 'ip' );
								$row->set( 'value', $ipAddress );
								$row->set( 'date', $_CB_framework->getUTCDate() );
								$row->set( 'duration', $this->params->get( 'captcha_autoblock_dur', '+1 HOUR' ) );
								$row->set( 'reason', $reason );

								$row->store();

								if ( $message ) {
									$extras			=	array(	'[duration]' => ucwords( strtolower( str_replace( array( '+', '-' ), '', $row->get( 'duration' ) ) ) ),
																'[date]' => $row->get( 'date' ) . ' UTC',
																'[expire]' => $row->getExpire() . ( $row->get( 'duration' ) ? ' UTC' : null )
															);

									$extras			=	array_merge( $extras, array( '[reason]' => CBTxt::T( 'CAPTCHA_BLOCK_REASON', ( $row->get( 'reason' ) ? $row->get( 'reason' ) : 'Spam.' ), $extras ) ) );

									$this->error	=	CBTxt::T( 'CAPTCHA_BLOCK_MESSAGE', $message, $extras );
								}
							} elseif ( $message ) {
								$extras				=	array(	'[duration]' => null,
																'[date]' => null,
																'[expire]' => null
															);

								$extras				=	array_merge( $extras, array( '[reason]' => CBTxt::T( 'CAPTCHA_BLOCK_REASON', ( $reason ? $reason : 'Spam.' ), $extras ) ) );

								$this->error		=	CBTxt::T( 'CAPTCHA_BLOCK_MESSAGE', $message, $extras );
							}
						}
					}
				} else {
					$query							=	'SELECT *'
													.	"\n FROM " . $_CB_database->NameQuote( '#__comprofiler_plugin_antispam_attempts' )
													.	"\n WHERE " . $_CB_database->NameQuote( 'ip_address' ) . " = " . $_CB_database->Quote( $ipAddress )
													.	"\n AND " . $_CB_database->NameQuote( 'type' ) . " = " . $_CB_database->Quote( 'captcha' )
													.	"\n ORDER BY " . $_CB_database->NameQuote( 'date' ) . " DESC";
					$_CB_database->setQuery( $query );
					$attempts						=	$_CB_database->loadObjectList( null, 'cbantispamAttemptsTable', array( $_CB_database ) );

					/** @var cbantispamAttemptsTable[] $attempts */
					foreach ( $attempts as $attempt ) {
						$attempt->delete();
					}
				}
			}
		}

		return $valid;
	}
function cbInstaller_install_plugins(&$return)
{
    global $_CB_framework, $_CB_adminpath, $ueConfig;
    cbimport('cb.adminfilesystem');
    cbimport('cb.installer');
    $cbDatabase = \CBLib\Application\Application::Database();
    // List of core plugins that are no longer core, but we just want to disable core status and not remove as they don't conflict:
    $deprecated = array('bootstrap', 'winclassic', 'webfx', 'osx', 'luna', 'dark', 'yanc', 'cb.mamblogtab', 'cb.simpleboardtab', 'cb.authortab');
    foreach ($deprecated as $pluginElement) {
        $plugin = new PluginTable();
        if ($plugin->load(array('element' => $pluginElement))) {
            $query = "UPDATE " . $cbDatabase->NameQuote('#__comprofiler_plugin') . "\n SET " . $cbDatabase->NameQuote('iscore') . " = 0" . "\n WHERE " . $cbDatabase->NameQuote('id') . " = " . (int) $plugin->id;
            $cbDatabase->setQuery($query);
            if (!$cbDatabase->query()) {
                $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::P('Plugin [element] failed to deprecate. Please run Tools > Check Community Builder Database to reattempt.', array('[element]' => $pluginElement)) . '</div>';
            }
            $query = "UPDATE " . $cbDatabase->NameQuote('#__comprofiler_tabs') . "\n SET " . $cbDatabase->NameQuote('sys') . " = 0" . "\n WHERE " . $cbDatabase->NameQuote('pluginid') . " = " . (int) $plugin->id;
            $cbDatabase->setQuery($query);
            if (!$cbDatabase->query()) {
                $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::P('Plugin [element] tabs failed to deprecate. Please run Tools > Check Community Builder Database to reattempt.', array('[element]' => $pluginElement)) . '</div>';
            }
            $query = "UPDATE " . $cbDatabase->NameQuote('#__comprofiler_fields') . "\n SET " . $cbDatabase->NameQuote('sys') . " = 0" . "\n WHERE " . $cbDatabase->NameQuote('pluginid') . " = " . (int) $plugin->id;
            $cbDatabase->setQuery($query);
            if (!$cbDatabase->query()) {
                $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::P('Plugin [element] fields failed to deprecate. Please run Tools > Check Community Builder Database to reattempt.', array('[element]' => $pluginElement)) . '</div>';
            }
        }
    }
    // List of plugins that conflict with the core that need to be removed (normally due to being merged into core):
    $conflicted = array('bootstrap', 'winclassic', 'webfx', 'osx', 'luna', 'dark', 'yanc', 'cb.mamblogtab', 'cb.authortab', 'cbvideofield', 'cb.filefield');
    foreach ($conflicted as $pluginElement) {
        $plugin = new PluginTable();
        if ($plugin->load(array('element' => $pluginElement))) {
            if (!cbInstaller_uninstall_plugin($plugin, $return)) {
                return false;
            }
        }
    }
    // Ensure Default template, CB Core, and language plugins are published as they are not allowed to be unpublished:
    $query = "UPDATE " . $cbDatabase->NameQuote('#__comprofiler_plugin') . "\n SET " . $cbDatabase->NameQuote('published') . " = 1" . "\n WHERE ( " . $cbDatabase->NameQuote('id') . " IN " . $cbDatabase->safeArrayOfIntegers(array(1, 7)) . ' OR ' . $cbDatabase->NameQuote('type') . ' = ' . $cbDatabase->quote('language') . ' )';
    $cbDatabase->setQuery($query);
    $cbDatabase->query();
    $pluginsFile = $_CB_adminpath . 'pluginsfiles.tgz';
    // We need to ensure the core plugins archive actually exists before doing anything with it:
    if (!file_exists($pluginsFile)) {
        $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::P('Core plugins archive [path] missing.', array('[path]' => $pluginsFile)) . '</div>';
        return false;
    }
    // We need zlib to unzip packages so lets check that it exists:
    if (!extension_loaded('zlib')) {
        $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::T('Core plugins can not be installed as zlib is not installed.') . '</div>';
        return false;
    }
    $installer = new cbInstallerPlugin();
    // Uncompress the core plugins so we can install them:
    if (!$installer->upload($pluginsFile, true, false)) {
        $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::P('Core plugins can not be installed as uncompressing [path] failed.', array('[path]' => $pluginsFile)) . '</div>';
        return false;
    }
    $adminFS = cbAdminFileSystem::getInstance();
    $baseDir = $_CB_framework->getCfg('absolute_path') . '/components/com_comprofiler';
    // Create the base plugin directory:
    if (!$adminFS->is_dir($baseDir . '/plugin')) {
        if (!$adminFS->mkdir($baseDir . '/plugin')) {
            $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::P('Failed to create directory [path].', array('[path]' => $baseDir . '/plugin')) . '</div>';
            return false;
        }
        if (!$adminFS->copy($baseDir . '/index.html', $baseDir . '/plugin/index.html')) {
            $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::P('Failed to create index [path].', array('[path]' => $baseDir . '/plugin/index.html')) . '</div>';
            return false;
        }
    }
    // Create the language template directory:
    if (!$adminFS->is_dir($baseDir . '/plugin/language')) {
        if (!$adminFS->mkdir($baseDir . '/plugin/language')) {
            $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::P('Failed to create directory [path].', array('[path]' => $baseDir . '/plugin/language')) . '</div>';
            return false;
        }
        if (!$adminFS->copy($baseDir . '/index.html', $baseDir . '/plugin/language/index.html')) {
            $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::P('Failed to create index [path].', array('[path]' => $baseDir . '/plugin/language/index.html')) . '</div>';
            return false;
        }
    }
    // Create the template plugin directory:
    if (!$adminFS->is_dir($baseDir . '/plugin/templates')) {
        if (!$adminFS->mkdir($baseDir . '/plugin/templates')) {
            $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::P('Failed to create directory [path].', array('[path]' => $baseDir . '/plugin/templates')) . '</div>';
            return false;
        }
        if (!$adminFS->copy($baseDir . '/index.html', $baseDir . '/plugin/templates/index.html')) {
            $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::P('Failed to create index [path].', array('[path]' => $baseDir . '/plugin/templates/index.html')) . '</div>';
            return false;
        }
    }
    // Create the user plugin directory:
    if (!$adminFS->is_dir($baseDir . '/plugin/user')) {
        if (!$adminFS->mkdir($baseDir . '/plugin/user')) {
            $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::P('Failed to create directory [path].', array('[path]' => $baseDir . '/plugin/user')) . '</div>';
            return false;
        }
        if (!$adminFS->copy($baseDir . '/index.html', $baseDir . '/plugin/user/index.html')) {
            $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::P('Failed to create index [path].', array('[path]' => $baseDir . '/plugin/user/index.html')) . '</div>';
            return false;
        }
    }
    // Install core plugins 1 by 1 silently:
    $installFrom = $installer->installDir();
    $filesList = cbReadDirectory($installFrom, '.', true);
    foreach ($filesList as $file) {
        if (preg_match('/^.+\\.xml$/i', $file)) {
            $plgPath = $installFrom . (substr($installFrom, -1, 1) == '/' ? '' : '/') . $file;
            $plgXml = new SimpleXMLElement(trim(file_get_contents($plgPath)));
            if ($plgXml->getName() == 'cbinstall') {
                $plgDir = dirname($plgPath) . '/';
                ob_start();
                $plgInstaller = new cbInstallerPlugin();
                $installed = $plgInstaller->install($plgDir);
                ob_end_clean();
                if (!$installed) {
                    $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::P('Installing core plugin [plugin] failed with error [error].', array('[plugin]' => $plgInstaller->i_elementname ? $plgInstaller->i_elementname : $file, '[error]' => $plgInstaller->getError())) . '</div>';
                    return false;
                }
            }
        }
    }
    // Delete the expanded core plugins archive:
    $result = $adminFS->deldir(_cbPathName($installFrom . '/'));
    if ($result === false) {
        $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::T('Deleting expanded core plugins archive failed.') . '</div>';
    }
    // Delete the core plugins archive:
    $result = $adminFS->unlink(_cbPathName($pluginsFile, false));
    if ($result === false) {
        $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::P('Deleting core plugins archive [path] failed.', array('[path]' => $pluginsFile)) . '</div>';
    }
    // Sets the as ready so config can actually load this time:
    \CB\Application\CBConfig::setCbConfigReadyToLoad(true);
    // Load the config now that the tables exist encase they didn't during install:
    \CB\Application\CBConfig::loadLegacyCBueConfig();
    // Migrate old file based configuration to database based configuration:
    $newConfig = null;
    if ($adminFS->file_exists($_CB_adminpath . 'ue_config.php')) {
        /** @noinspection PhpIncludeInspection */
        include_once $_CB_adminpath . 'ue_config.php';
        // Reset the template back to default if upgrading from a 1.x install:
        $ueConfig['templatedir'] = 'default';
        $newConfig = json_encode($ueConfig);
    }
    // Convert CB 1.x nesttabs into new nested tab display mode if needed:
    if (isset($ueConfig['nesttabs'])) {
        // Update all the tabs that would have normally auto-nested and make them nested displays
        $query = 'UPDATE ' . $cbDatabase->NameQuote('#__comprofiler_tabs') . "\n SET " . $cbDatabase->NameQuote('displaytype') . " = " . $cbDatabase->Quote('nested') . "\n WHERE " . $cbDatabase->NameQuote('displaytype') . " = " . $cbDatabase->Quote('tab') . "\n AND " . $cbDatabase->NameQuote('fields') . " = 1" . "\n AND ( ( " . $cbDatabase->NameQuote('pluginclass') . " IS NULL )" . ' OR ( ' . $cbDatabase->NameQuote('sys') . ' = 2 ) )';
        $cbDatabase->setQuery($query);
        $cbDatabase->query();
        unset($ueConfig['nesttabs']);
        $newConfig = json_encode($ueConfig);
    }
    // Migrate global avatar params to field params:
    if (isset($ueConfig['allowAvatar']) || isset($ueConfig['defaultAvatar']) || isset($ueConfig['defaultPendingAvatar']) || isset($ueConfig['allowAvatarGallery'])) {
        $field = new FieldTable();
        if ($field->load(array('name' => 'avatar'))) {
            $fieldParams = new Registry($field->params);
            if (isset($ueConfig['allowAvatar'])) {
                $fieldParams->set('image_allow_uploads', (int) $ueConfig['allowAvatar']);
                unset($ueConfig['allowAvatar']);
            }
            if (isset($ueConfig['defaultAvatar'])) {
                $fieldParams->set('defaultAvatar', $ueConfig['defaultAvatar']);
                unset($ueConfig['defaultAvatar']);
            }
            if (isset($ueConfig['defaultPendingAvatar'])) {
                $fieldParams->set('defaultPendingAvatar', $ueConfig['defaultPendingAvatar']);
                unset($ueConfig['defaultPendingAvatar']);
            }
            if (isset($ueConfig['allowAvatarGallery'])) {
                $fieldParams->set('image_allow_gallery', (int) $ueConfig['allowAvatarGallery']);
                unset($ueConfig['allowAvatarGallery']);
            }
            $field->set('params', $fieldParams->asJson());
            if (!$field->store()) {
                $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::P('Field [name] failed to migrate. Error: [error]', array('[name]' => $field->name, '[error]' => $field->getError())) . '</div>';
            }
        }
        $newConfig = json_encode($ueConfig);
    }
    // Migrate global email ajax checker to field specific param:
    if (isset($ueConfig['reg_email_checker'])) {
        $field = new FieldTable();
        if ($field->load(array('name' => 'email'))) {
            $fieldParams = new Registry($field->params);
            $fieldParams->set('field_check_email', (string) $ueConfig['reg_email_checker']);
            $field->set('params', $fieldParams->asJson());
            if (!$field->store()) {
                $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::P('Field [name] failed to migrate. Error: [error]', array('[name]' => $field->name, '[error]' => $field->getError())) . '</div>';
            }
        }
        unset($ueConfig['reg_email_checker']);
        $newConfig = json_encode($ueConfig);
    }
    // Migrate global image params to field params:
    if (isset($ueConfig['allowAvatarUpload'])) {
        $query = 'SELECT *' . "\n FROM " . $cbDatabase->NameQuote('#__comprofiler_fields') . "\n WHERE " . $cbDatabase->NameQuote('name') . " != " . $cbDatabase->Quote('avatar') . "\n AND " . $cbDatabase->NameQuote('type') . " = " . $cbDatabase->Quote('image');
        $cbDatabase->setQuery($query);
        $fields = $cbDatabase->loadObjectList(null, '\\CB\\Database\\Table\\FieldTable', array($cbDatabase));
        /** @var $fields FieldTable[] */
        foreach ($fields as $field) {
            $fieldParams = new Registry($field->params);
            $fieldParams->set('image_allow_uploads', (int) $ueConfig['allowAvatarUpload']);
            $field->set('params', $fieldParams->asJson());
            if (!$field->store()) {
                $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::P('Field [name] failed to migrate. Error: [error]', array('[name]' => $field->name, '[error]' => $field->getError())) . '</div>';
            }
        }
        unset($ueConfig['allowAvatarUpload']);
        $newConfig = json_encode($ueConfig);
    }
    // Convert CB 1.x allow_profileviewbyGID into new profile_viewaccesslevel if needed:
    if (isset($ueConfig['allow_profileviewbyGID']) && !isset($ueConfig['profile_viewaccesslevel'])) {
        $ueConfig['profile_viewaccesslevel'] = \CBLib\Application\Application::CmsPermissions()->convertOldGroupToViewAccessLevel($ueConfig['allow_profileviewbyGID'], 'CB Profiles access');
        unset($ueConfig['allow_profileviewbyGID']);
        $newConfig = json_encode($ueConfig);
    }
    // Convert CB 1.x allow_profileviewbyGID into new profile_viewaccesslevel if needed:
    if (isset($ueConfig['imageApproverGid']) && !isset($ueConfig['moderator_viewaccesslevel'])) {
        $ueConfig['moderator_viewaccesslevel'] = \CBLib\Application\Application::CmsPermissions()->convertOldGroupToViewAccessLevel($ueConfig['imageApproverGid'], 'CB Moderators access');
        unset($ueConfig['imageApproverGid']);
        $newConfig = json_encode($ueConfig);
    }
    // If old configuration for terms and conditions exists we need to pass it to the terms and conditions field:
    if (isset($ueConfig['reg_enable_toc']) && isset($ueConfig['reg_toc_url'])) {
        if ($ueConfig['reg_enable_toc'] == 1 && $ueConfig['reg_toc_url'] != '') {
            $field = new FieldTable();
            if ($field->load(array('name' => 'acceptedterms'))) {
                $fieldParams = new Registry($field->params);
                if ($fieldParams->get('terms_url') == '') {
                    $fieldParams->set('terms_url', $ueConfig['reg_toc_url']);
                    $field->set('required', 1);
                    $field->set('registration', 1);
                    $field->set('edit', 1);
                    $field->set('params', $fieldParams->asJson());
                    if (!$field->store()) {
                        $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::P('Field [name] failed to migrate. Error: [error]', array('[name]' => $field->name, '[error]' => $field->getError())) . '</div>';
                    }
                }
            }
        }
        unset($ueConfig['reg_enable_toc']);
        unset($ueConfig['reg_toc_url']);
        $newConfig = json_encode($ueConfig);
    }
    // If old configuration for userlists exists we need to pass it to the userlist it self:
    if (isset($ueConfig['num_per_page']) && isset($ueConfig['allow_profilelink'])) {
        if ($ueConfig['num_per_page'] != '' || $ueConfig['allow_profilelink'] != 1) {
            $query = 'SELECT *' . "\n FROM " . $cbDatabase->NameQuote('#__comprofiler_lists');
            $cbDatabase->setQuery($query);
            $lists = $cbDatabase->loadObjectList(null, '\\CB\\Database\\Table\\ListTable', array($cbDatabase));
            /** @var $lists ListTable[] */
            foreach ($lists as $list) {
                $listParams = new Registry($list->params);
                $changed = false;
                if ($ueConfig['num_per_page'] != '' && $listParams->get('list_limit') == '') {
                    $listParams->set('list_limit', $ueConfig['num_per_page']);
                    $changed = true;
                }
                if ($ueConfig['allow_profilelink'] != 1 && $listParams->get('allow_profilelink') == '') {
                    $listParams->set('allow_profilelink', $ueConfig['allow_profilelink']);
                    $changed = true;
                }
                if ($changed) {
                    $list->set('params', $listParams->asJson());
                    if (!$list->store()) {
                        $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::P('Userlist [title] failed to migrate. Error: [error]', array('[name]' => $list->title, '[error]' => $list->getError())) . '</div>';
                    }
                }
            }
        }
        unset($ueConfig['num_per_page']);
        unset($ueConfig['allow_profilelink']);
        $newConfig = json_encode($ueConfig);
    }
    // Establish default for any missing config params:
    $configXml = new SimpleXMLElement(trim(file_get_contents($_CB_adminpath . 'xmlcb/views/view.com_comprofiler.editconfig.xml')));
    if ($configXml) {
        $configXmlParams = $configXml->xpath('//param');
        if ($configXmlParams) {
            $configXmlSet = false;
            foreach ($configXmlParams as $configXmlParam) {
                $k = (string) $configXmlParam->attributes('name');
                if (!isset($ueConfig[$k])) {
                    $v = (string) $configXmlParam->attributes('default');
                    if ($k) {
                        $ueConfig[$k] = $v;
                        $configXmlSet = true;
                    }
                }
            }
            if ($configXmlSet) {
                $newConfig = json_encode($ueConfig);
            }
        }
    }
    // Update cb.core with the new cb config:
    if ($newConfig) {
        $query = "UPDATE " . $cbDatabase->NameQuote('#__comprofiler_plugin') . "\n SET " . $cbDatabase->NameQuote('params') . " = " . $cbDatabase->Quote($newConfig) . "\n WHERE " . $cbDatabase->NameQuote('id') . " = 1";
        $cbDatabase->setQuery($query);
        if (!$cbDatabase->query()) {
            $_CB_framework->enqueueMessage(CBTxt::P('Failed to update configuration params in database. Error: [error]', array('[error]' => $cbDatabase->getErrorMsg())), 'error');
            return false;
        }
    }
    // Remove the old config file if it exists as we migrated above already:
    if ($adminFS->file_exists($_CB_adminpath . 'ue_config.php')) {
        $adminFS->unlink($_CB_adminpath . 'ue_config.php');
    }
    // Migrate old userlist columns to new usage:
    $tableFields = $cbDatabase->getTableFields('#__comprofiler_lists');
    if (isset($tableFields['#__comprofiler_lists'])) {
        $userListFields = array_keys($tableFields['#__comprofiler_lists']);
        $userListOldFields = array('useraccessgroupid', 'sortfields', 'filterfields', 'col1title', 'col1enabled', 'col1fields', 'col1captions', 'col2title', 'col2enabled', 'col2fields', 'col2captions', 'col3title', 'col3enabled', 'col3fields', 'col3captions', 'col4title', 'col4enabled', 'col4fields', 'col4captions');
        // At least 1 legacy column still exists so lets begin migration of userlists:
        if (array_intersect($userListOldFields, $userListFields)) {
            $query = 'SELECT *' . "\n FROM " . $cbDatabase->NameQuote('#__comprofiler_lists');
            $cbDatabase->setQuery($query);
            $lists = $cbDatabase->loadObjectList(null, '\\CB\\Database\\Table\\ListTable', array($cbDatabase));
            /** @var $lists ListTable[] */
            foreach ($lists as $list) {
                $listParams = new Registry($list->params);
                $listSorting = array();
                $listSortFields = $list->get('sortfields') ? explode(', ', str_replace('`', '', $list->get('sortfields'))) : array();
                $paramsChanged = false;
                foreach ($listSortFields as $listSortField) {
                    $sortParts = explode(' ', $listSortField);
                    $sortField = isset($sortParts[0]) ? trim($sortParts[0]) : null;
                    if ($sortField) {
                        $sortDirection = isset($sortParts[1]) ? trim($sortParts[1]) : 'ASC';
                        $listSorting[] = array('column' => $sortField, 'direction' => $sortDirection);
                    }
                }
                if ($listSorting) {
                    $paramsChanged = true;
                    $listParams->set('sort_mode', '0');
                    $listParams->set('basic_sort', $listSorting);
                }
                $listFilterFields = $list->get('filterfields');
                if ($listFilterFields) {
                    $filterType = substr($listFilterFields, 0, 1);
                    $listFilterFields = rawurldecode(substr($listFilterFields, 2, -1));
                    if ($filterType == 'a') {
                        $paramsChanged = true;
                        $listParams->set('filter_mode', '1');
                        $listParams->set('filter_advanced', $listFilterFields);
                    } else {
                        $listFilters = array();
                        $basicFilters = explode(' AND ', $listFilterFields);
                        foreach ($basicFilters as $basicFilter) {
                            if (preg_match('/`(.+)`\\s*(.+)\\s*\'(.*)\'|`(.+)`\\s*(.+)/i', $basicFilter, $matches)) {
                                $filterField = isset($filterParts[1]) ? $filterParts[1] : (isset($filterParts[4]) ? $filterParts[4] : null);
                                $filterOperator = isset($filterParts[2]) ? $filterParts[2] : (isset($filterParts[5]) ? $filterParts[5] : null);
                                $filterVal = isset($filterParts[3]) ? $filterParts[3] : '';
                                switch ($filterOperator) {
                                    case '!=':
                                        $filterOperator = '<>||ISNULL';
                                        break;
                                    case 'IS NULL':
                                    case "= ''":
                                        $filterOperator = '=';
                                        $filterVal = '';
                                        break;
                                    case 'IS NOT NULL':
                                    case "!= ''":
                                        $filterOperator = '!=';
                                        $filterVal = '';
                                        break;
                                }
                                if ($filterField && $filterOperator) {
                                    $listFilters[] = array('column' => $filterField, 'operator' => $filterOperator, 'value' => $filterVal);
                                }
                            }
                        }
                        if ($listFilters) {
                            $paramsChanged = true;
                            $listParams->set('filter_mode', '0');
                            $listParams->set('filter_basic', $listFilters);
                        }
                    }
                }
                $listColumns = array();
                for ($i = 1, $n = 4; $i <= $n; $i++) {
                    if ($list->get('col' . $i . 'enabled')) {
                        $columnTitle = $list->get('col' . $i . 'title', '');
                        $columnCaptions = (int) $list->get('col' . $i . 'captions', 0);
                        $columnFields = $list->get('col' . $i . 'fields') ? explode('|*|', $list->get('col' . $i . 'fields')) : array();
                        $listFields = array();
                        foreach ($columnFields as $columnField) {
                            $listFields[] = array('field' => (string) $columnField, 'display' => $columnCaptions ? '1' : '4');
                        }
                        if ($listFields) {
                            $listColumns[] = array('title' => $columnTitle, 'size' => '3', 'cssclass' => '', 'fields' => $listFields);
                        }
                    }
                }
                if ($listColumns) {
                    $paramsChanged = true;
                    $listParams->set('columns', $listColumns);
                }
                if ($paramsChanged || $list->get('usergroupids')) {
                    $list->set('usergroupids', implode('|*|', explode(', ', $list->get('usergroupids'))));
                    $list->set('params', $listParams->asJson());
                    if (!$list->store()) {
                        $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::P('Userlist [title] failed to migrate. Error: [error]', array('[name]' => $list->title, '[error]' => $list->getError())) . '</div>';
                    }
                }
            }
            $userListDrop = array();
            foreach ($userListOldFields as $userListOldField) {
                if (in_array($userListOldField, $userListFields)) {
                    $userListDrop[] = $cbDatabase->NameQuote($userListOldField);
                }
            }
            if ($userListDrop) {
                $query = 'ALTER TABLE ' . $cbDatabase->NameQuote('#__comprofiler_lists') . "\n DROP " . implode(', DROP ', $userListDrop);
                $cbDatabase->setQuery($query);
                $cbDatabase->query();
            }
        }
    }
    // Migrates password strength parameters:
    $plugin = new PluginTable();
    if ($plugin->load(array('element' => 'cbpasswordstrength'))) {
        $query = "SELECT *" . "\n FROM " . $cbDatabase->NameQuote('#__comprofiler_fields') . "\n WHERE " . $cbDatabase->NameQuote('type') . " = " . $cbDatabase->Quote('password');
        $cbDatabase->setQuery($query);
        $fields = $cbDatabase->loadObjectList(null, '\\CB\\Database\\Table\\FieldTable', array($cbDatabase));
        /** @var $fields FieldTable[] */
        foreach ($fields as $field) {
            $fieldParams = new Registry($field->params);
            $fieldParams->set('passTestSrength', (string) $fieldParams->get('pswstr_display', 1));
            $field->set('params', $fieldParams->asJson());
            if (!$field->store()) {
                $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::P('Field [name] failed to migrate. Error: [error]', array('[name]' => $field->name, '[error]' => $field->getError())) . '</div>';
            }
        }
        if (!cbInstaller_uninstall_plugin($plugin, $return)) {
            return false;
        }
    }
    // Migrates ajax points field parameters:
    $plugin = new PluginTable();
    if ($plugin->load(array('element' => 'cbajaxpointsfield'))) {
        $query = "SELECT *" . "\n FROM " . $cbDatabase->NameQuote('#__comprofiler_fields') . "\n WHERE " . $cbDatabase->NameQuote('type') . " = " . $cbDatabase->Quote('ajaxpoints');
        $cbDatabase->setQuery($query);
        $fields = $cbDatabase->loadObjectList(null, '\\CB\\Database\\Table\\FieldTable', array($cbDatabase));
        /** @var $fields FieldTable[] */
        foreach ($fields as $field) {
            $fieldParams = new Registry($field->params);
            switch ((int) $fieldParams->get('ajax_layout', 1)) {
                case 1:
                    $fieldParams->set('points_layout', '[minus] [value] [plus]');
                    break;
                case 2:
                    $fieldParams->set('points_layout', '[plus] [value] [minus]');
                    break;
                case 3:
                    $fieldParams->set('points_layout', '[value] [minus][plus]');
                    break;
                case 4:
                    $fieldParams->set('points_layout', '[value] [plus][minus]');
                    break;
                case 5:
                    $fieldParams->set('points_layout', '[minus][plus] [value]');
                    break;
                case 6:
                    $fieldParams->set('points_layout', '[plus][minus] [value]');
                    break;
            }
            $fieldParams->set('points_inc_plus', (string) $fieldParams->get('ajax_increment_up', 1));
            $fieldParams->set('points_inc_minus', (string) $fieldParams->get('ajax_increment_down', 1));
            $fieldParams->set('points_access', '8');
            $fieldParams->set('points_access_custom', (string) $fieldParams->get('ajax_access', 0));
            $field->set('type', 'points');
            $field->set('pluginid', 1);
            $field->set('params', $fieldParams->asJson());
            if (!$field->store()) {
                $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::P('Field [name] failed to migrate. Error: [error]', array('[name]' => $field->name, '[error]' => $field->getError())) . '</div>';
            }
        }
        if (!cbInstaller_uninstall_plugin($plugin, $return)) {
            return false;
        }
    }
    // Migrates rating field parameters:
    $plugin = new PluginTable();
    if ($plugin->load(array('element' => 'ratingfield'))) {
        $query = "SELECT *" . "\n FROM " . $cbDatabase->NameQuote('#__comprofiler_fields') . "\n WHERE " . $cbDatabase->NameQuote('type') . " IN " . $cbDatabase->safeArrayOfStrings(array('myrating', 'yourrating'));
        $cbDatabase->setQuery($query);
        $fields = $cbDatabase->loadObjectList(null, '\\CB\\Database\\Table\\FieldTable', array($cbDatabase));
        /** @var $fields FieldTable[] */
        foreach ($fields as $field) {
            $fieldParams = new Registry($field->params);
            if ($field->type == 'myrating') {
                $fieldParams->set('rating_access', '2');
            } else {
                if ($fieldParams->get('AllowAnnonymous', 1)) {
                    $fieldParams->set('rating_access', '3');
                } else {
                    $fieldParams->set('rating_access', '4');
                    $fieldParams->set('rating_access_exclude', '1');
                }
            }
            $fieldParams->set('rating_number', (string) $fieldParams->get('NumStars', 5));
            switch ((int) $fieldParams->get('RatingFraction', 1)) {
                case 1:
                    $fieldParams->set('rating_step', '1');
                    break;
                case 2:
                    $fieldParams->set('rating_step', '0.5');
                    break;
                case 3:
                    $fieldParams->set('rating_step', '0.33');
                    break;
                case 4:
                    $fieldParams->set('rating_step', '0.25');
                    break;
            }
            $field->set('type', 'rating');
            $field->set('pluginid', 1);
            $field->set('params', $fieldParams->asJson());
            if (!$field->store()) {
                $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::P('Field [name] failed to migrate. Error: [error]', array('[name]' => $field->name, '[error]' => $field->getError())) . '</div>';
            }
        }
        if (!cbInstaller_uninstall_plugin($plugin, $return)) {
            return false;
        }
    }
    // Migrates verify email field parameters:
    $plugin = new PluginTable();
    if ($plugin->load(array('element' => 'cbverifyemail'))) {
        $query = "SELECT *" . "\n FROM " . $cbDatabase->NameQuote('#__comprofiler_fields') . "\n WHERE " . $cbDatabase->NameQuote('type') . " IN " . $cbDatabase->safeArrayOfStrings(array('emailaddress', 'primaryemailaddress'));
        $cbDatabase->setQuery($query);
        $fields = $cbDatabase->loadObjectList(null, '\\CB\\Database\\Table\\FieldTable', array($cbDatabase));
        /** @var $fields FieldTable[] */
        foreach ($fields as $field) {
            $fieldParams = new Registry($field->params);
            $fieldParams->set('fieldVerifyInput', $fieldParams->get('verifyemail_display_reg', 1) || $fieldParams->get('verifyemail_display_edit', 0) ? '1' : '0');
            $fieldParams->set('verifyEmailTitle', $fieldParams->get('verifyemail_title', '_UE_VERIFY_SOMETHING'));
            $field->set('params', $fieldParams->asJson());
            if (!$field->store()) {
                $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::P('Field [name] failed to migrate. Error: [error]', array('[name]' => $field->name, '[error]' => $field->getError())) . '</div>';
            }
        }
        if (!cbInstaller_uninstall_plugin($plugin, $return)) {
            return false;
        }
    }
    // Migrates forum integration parameters:
    $plugin = new PluginTable();
    if ($plugin->load(array('element' => 'cb.simpleboardtab'))) {
        $pluginParams = new Registry($plugin->params);
        $cbForums = new PluginTable();
        if ($cbForums->load(array('element' => 'cbforums'))) {
            $cbForumsParams = new Registry($cbForums->params);
            if ((int) $pluginParams->get('forumType', 0) == 4) {
                $cbForumsParams->set('forum_model', '6');
            } else {
                $cbForumsParams->set('forum_model', '1');
            }
            switch ((int) $pluginParams->get('sidebarMode', 0)) {
                case 1:
                    $cbForumsParams->set('k20_personaltext', $pluginParams->get('sidebarBeginner1'));
                    $cbForumsParams->set('k20_gender', $pluginParams->get('sidebarBeginner4'));
                    $cbForumsParams->set('k20_birthdate', $pluginParams->get('sidebarBeginner2'));
                    $cbForumsParams->set('k20_location', $pluginParams->get('sidebarBeginner3'));
                    $cbForumsParams->set('k20_icq', $pluginParams->get('sidebarBeginner5'));
                    $cbForumsParams->set('k20_aim', $pluginParams->get('sidebarBeginner6'));
                    $cbForumsParams->set('k20_yim', $pluginParams->get('sidebarBeginner7'));
                    $cbForumsParams->set('k20_msn', $pluginParams->get('sidebarBeginner8'));
                    $cbForumsParams->set('k20_skype', $pluginParams->get('sidebarBeginner9'));
                    $cbForumsParams->set('k20_twitter', $pluginParams->get('sidebarBeginner12'));
                    $cbForumsParams->set('k20_facebook', $pluginParams->get('sidebarBeginner13'));
                    $cbForumsParams->set('k20_gtalk', $pluginParams->get('sidebarBeginner10'));
                    $cbForumsParams->set('k20_myspace', $pluginParams->get('sidebarBeginner14'));
                    $cbForumsParams->set('k20_linkedin', $pluginParams->get('sidebarBeginner15'));
                    $cbForumsParams->set('k20_delicious', $pluginParams->get('sidebarBeginner16'));
                    $cbForumsParams->set('k20_digg', $pluginParams->get('sidebarBeginner18'));
                    $cbForumsParams->set('k20_blogspot', $pluginParams->get('sidebarBeginner19'));
                    $cbForumsParams->set('k20_flickr', $pluginParams->get('sidebarBeginner20'));
                    $cbForumsParams->set('k20_bebo', $pluginParams->get('sidebarBeginner21'));
                    $cbForumsParams->set('k20_website', $pluginParams->get('sidebarBeginner11'));
                    break;
                case 2:
                    $cbForumsParams->set('k20_sidebar_reg', $pluginParams->get('sidebarAdvancedExists'));
                    $cbForumsParams->set('k20_sidebar_anon', $pluginParams->get('sidebarAdvancedPublic'));
                    $cbForumsParams->set('k20_sidebar_del', $pluginParams->get('sidebarAdvancedDeleted'));
                    break;
            }
            $cbForums->set('params', $cbForumsParams->asJson());
            if (!$cbForums->store()) {
                $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::P('Plugin [element] failed to migrate. Error: [error]', array('[element]' => $plugin->element, '[error]' => $cbForums->getError())) . '</div>';
            }
        }
        // Migrate the forum fields to ensure their display mode is set:
        $query = "SELECT *" . "\n FROM " . $cbDatabase->NameQuote('#__comprofiler_fields') . "\n WHERE " . $cbDatabase->NameQuote('name') . " IN " . $cbDatabase->safeArrayOfStrings(array('forumrank', 'forumposts', 'forumkarma'));
        $cbDatabase->setQuery($query);
        $fields = $cbDatabase->loadObjectList(null, '\\CB\\Database\\Table\\FieldTable', array($cbDatabase));
        /** @var $fields FieldTable[] */
        foreach ($fields as $field) {
            $fieldParams = new Registry($field->params);
            switch ($field->name) {
                case 'forumposts':
                    $fieldParams->set('forumStatus', 'posts');
                    break;
                case 'forumkarma':
                    $fieldParams->set('forumStatus', 'karma');
                    break;
                case 'forumrank':
                    $fieldParams->set('forumStatus', 'rank');
                    break;
            }
            $field->set('params', $fieldParams->asJson());
            if (!$field->store()) {
                $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::P('Field [name] failed to migrate. Error: [error]', array('[name]' => $field->name, '[error]' => $field->getError())) . '</div>';
            }
        }
        if (!cbInstaller_uninstall_plugin($plugin, $return)) {
            return false;
        }
    }
    // Removes legacy about cb menu items from CB Menu tab params
    $tab = new TabTable();
    if ($tab->load(17)) {
        $tabParams = new Registry($tab->params);
        if ($tabParams->get('firstSubMenuName') == '_UE_MENU_ABOUT_CB') {
            $tabParams->set('firstSubMenuName', '');
            $tabParams->set('firstSubMenuHref', '');
            if ($tabParams->get('firstMenuName') == '_UE_MENU_CB' && !$tabParams->get('secondSubMenuName')) {
                $tabParams->set('firstMenuName', '');
            }
            $tab->set('params', $tabParams->asJson());
            if (!$tab->store()) {
                $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::P('Tab [title] failed to migrate. Error: [error]', array('[title]' => $tab->title, '[error]' => $tab->getError())) . '</div>';
            }
        }
    }
    // We need to fix the name fields publish state:
    switch ($ueConfig['name_style']) {
        case 2:
            $nameArray = array('name' => 0, 'firstname' => 1, 'middlename' => 0, 'lastname' => 1);
            break;
        case 3:
            $nameArray = array('name' => 0, 'firstname' => 1, 'middlename' => 1, 'lastname' => 1);
            break;
        case 1:
        default:
            $nameArray = array('name' => 1, 'firstname' => 0, 'middlename' => 0, 'lastname' => 0);
            break;
    }
    foreach ($nameArray as $name => $published) {
        $query = 'UPDATE ' . $cbDatabase->NameQuote('#__comprofiler_fields') . "\n SET " . $cbDatabase->NameQuote('published') . " = " . (int) $published . "\n WHERE " . $cbDatabase->NameQuote('name') . " = " . $cbDatabase->Quote($name);
        $cbDatabase->setQuery($query);
        $cbDatabase->query();
    }
    return true;
}
	/**
	 * @param  TabTable   $tab       Current tab
	 * @param  UserTable  $user      Current user
	 * @param  int        $ui        1 front, 2 admin UI
	 * @param  array      $postdata  Raw unfiltred POST data
	 * @return string                HTML
	 */
	public function getCBpluginComponent( $tab, $user, $ui, $postdata )
	{
		global $_CB_framework;

		$format						=	$this->input( 'format', null, GetterInterface::STRING );
		$raw						=	( $format == 'raw' );

		if ( ! $raw ) {
			outputCbJs();
			outputCbTemplate();
		}

		$action						=	null;
		$function					=	null;
		$id							=	null;
		$viewer						=	CBuser::getMyUserDataInstance();
		$user						=	$viewer;
		$stream						=	null;
		$inline						=	false;
		$data						=	true;

		if ( isset( $postdata['stream'] ) && ( $postdata['stream'] instanceof StreamInterface ) ) {
			$stream					=	$postdata['stream'];

			if ( $stream instanceof ActivityInterface ) {
				$action				=	'activity';
				$function			=	'show';
			} elseif ( $stream instanceof CommentsInterface ) {
				$action				=	'comments';
				$function			=	'show';
			} elseif ( $stream instanceof TagsInterface ) {
				$action				=	'tags';
				$function			=	'show';
			}

			if ( isset( $postdata['inline'] ) ) {
				$inline				=	$postdata['inline'];
			}

			if ( isset( $postdata['data'] ) ) {
				$data				=	$postdata['data'];
			}

			$user					=	$stream->user();
		} else {
			$action					=	$this->input( 'action', null, GetterInterface::STRING );
			$function				=	$this->input( 'func', null, GetterInterface::STRING );

			if ( $action == 'recentactivity' ) {
				$action				=	'activity';
				$function			=	'recent';
			} elseif ( $action == 'myactivity' ) {
				$action				=	'activity';
				$function			=	'my';
			} elseif ( $action == 'hiddenactivity' ) {
				$action				=	'hidden';
				$function			=	'activity';
			} elseif ( $action == 'hiddencomments' ) {
				$action				=	'hidden';
				$function			=	'comments';
			}

			if ( ( $action == 'activity' ) || ( $function == 'activity' ) ) {
				$stream				=	new Activity();
			} elseif ( ( $action == 'comments' ) || ( $function == 'comments' ) ) {
				$stream				=	new Comments();
			} elseif ( ( $action == 'tags' ) || ( $function == 'tags' ) ) {
				$stream				=	new Tags();
			}

			if ( $stream && $raw ) {
				$token				=	$this->input( 'token', null, GetterInterface::STRING );

				$post				=	new Registry( base64_decode( $this->input( 'stream', null, GetterInterface::BASE64 ) ) );

				$source				=	$post->get( 'source', null, GetterInterface::STRING );
				$userId				=	$post->get( 'user', null, GetterInterface::INT );
				$direction			=	$post->get( 'direction', null, GetterInterface::INT );

				if ( $source !== null ) {
					$stream->source( $source );
				}

				if ( $userId !== null ) {
					$user			=	CBuser::getUserDataInstance( (int) $userId );

					$stream->user( $user );
				}

				if ( ! ( $stream instanceof TagsInterface ) ) {
					if ( $direction !== null ) {
						$stream->direction( $direction );
					}
				}

				$stream->load( $post );

				if ( ( $stream->token() != $token ) || ( ! $token ) ) {
					header( 'HTTP/1.0 401 Unauthorized' );
					exit();
				}

				$id					=	$stream->get( 'id', null, GetterInterface::INT );
			}
		}

		if ( $stream && ( ! ( ( $stream instanceof CommentsInterface ) || ( $stream instanceof TagsInterface ) ) ) ) {
			$hashtag				=	$this->input( 'hashtag', null, GetterInterface::STRING );

			if ( $hashtag !== null ) {
				$stream->set( 'filter', '#' . $hashtag );
			}
		}

		if ( ! $raw ) {
			ob_start();
		}

		switch ( $action ) {
			case 'comments':
				if ( ! $stream ) {
					if ( $raw ) {
						header( 'HTTP/1.0 401 Unauthorized' );
						exit();
					} else {
						cbRedirect( 'index.php', CBTxt::T( 'Not authorized.' ), 'error' );
					}
				}

				switch ( $function ) {
					case 'new':
						if ( ! $raw ) {
							cbRedirect( 'index.php', CBTxt::T( 'Not authorized.' ), 'error' );
						}

						$this->saveComment( null, $stream, $user, $viewer );
						break;
					case 'save':
						if ( ! $raw ) {
							cbRedirect( 'index.php', CBTxt::T( 'Not authorized.' ), 'error' );
						}

						$this->saveComment( $id, $stream, $user, $viewer );
						break;
					case 'delete':
						if ( ! $raw ) {
							cbRedirect( 'index.php', CBTxt::T( 'Not authorized.' ), 'error' );
						}

						$this->deleteComment( $id, $stream, $user, $viewer );
						break;
					case 'hide':
						if ( ! $raw ) {
							cbRedirect( 'index.php', CBTxt::T( 'Not authorized.' ), 'error' );
						}

						$this->hideComment( $id, $stream, $user, $viewer );
						break;
					case 'unhide':
						if ( ! $raw ) {
							cbRedirect( 'index.php', CBTxt::T( 'Not authorized.' ), 'error' );
						}

						$this->unhideComment( $id, $stream, $user, $viewer );
						break;
					case 'load':
						if ( ! $raw ) {
							cbRedirect( 'index.php', CBTxt::T( 'Not authorized.' ), 'error' );
						}

						$this->showComments( $id, $stream, 3, true, $user, $viewer );
						break;
					case 'show':
					default:
						if ( isset( $postdata['stream'] ) && ( $postdata['stream'] instanceof CommentsInterface ) ) {
							$this->showComments( $id, $stream, ( $inline ? 2 : 0 ), $data, $user, $viewer );
						} else {
							$this->showComments( $id, $stream, ( $inline ? 2 : ( $raw ? 1 : 0 ) ), true, $user, $viewer );
						}
						break;
				}
				break;
			case 'activity':
				if ( ! $stream ) {
					if ( $raw ) {
						header( 'HTTP/1.0 401 Unauthorized' );
						exit();
					} else {
						cbRedirect( 'index.php', CBTxt::T( 'Not authorized.' ), 'error' );
					}
				}

				switch ( $function ) {
					case 'new':
						if ( ! $raw ) {
							cbRedirect( 'index.php', CBTxt::T( 'Not authorized.' ), 'error' );
						}

						$this->saveActivity( null, $stream, $user, $viewer );
						break;
					case 'save':
						if ( ! $raw ) {
							cbRedirect( 'index.php', CBTxt::T( 'Not authorized.' ), 'error' );
						}

						$this->saveActivity( $id, $stream, $user, $viewer );
						break;
					case 'delete':
						if ( ! $raw ) {
							cbRedirect( 'index.php', CBTxt::T( 'Not authorized.' ), 'error' );
						}

						$this->deleteActivity( $id, $stream, $user, $viewer );
						break;
					case 'hide':
						if ( ! $raw ) {
							cbRedirect( 'index.php', CBTxt::T( 'Not authorized.' ), 'error' );
						}

						$this->hideActivity( $id, $stream, $user, $viewer );
						break;
					case 'unhide':
						if ( ! $raw ) {
							cbRedirect( 'index.php', CBTxt::T( 'Not authorized.' ), 'error' );
						}

						$this->unhideActivity( $id, $stream, $user, $viewer );
						break;
					case 'load':
						if ( ! $raw ) {
							cbRedirect( 'index.php', CBTxt::T( 'Not authorized.' ), 'error' );
						}

						$this->showActivity( $id, $stream, 3, true, $user, $viewer );
						break;
					case 'recent':
						$stream->source( 'recent' );

						$menu				=	JFactory::getApplication()->getMenu()->getActive();

						if ( $menu && isset( $menu->id ) ) {
							CBActivity::loadStreamDefaults( $stream, $menu->params, 'activity_' );
						}

						$this->showActivity( $id, $stream, ( $raw ? 1 : 0 ), true, $user, $viewer );

						$_CB_framework->setMenuMeta();
						break;
					case 'my':
						$tab				=	new TabTable();

						$tab->load( array( 'pluginclass' => 'cbactivityTab' ) );

						if ( ! ( $tab->get( 'enabled' ) && CBActivity::canAccess( (int) $tab->get( 'viewaccesslevel' ), (int) $viewer->get( 'id' ) ) ) ) {
							if ( $raw ) {
								header( 'HTTP/1.0 401 Unauthorized' );
								exit();
							} else {
								cbRedirect( $_CB_framework->userProfileUrl( (int) $user->get( 'id' ), false, 'cbactivityTab' ), CBTxt::T( 'Not authorized.' ), 'error' );
							}
						}

						if ( ! ( $tab->params instanceof ParamsInterface ) ) {
							$tab->params	=	new Registry( $tab->params );
						}

						$stream->source( 'profile' );

						CBActivity::loadStreamDefaults( $activity, $tab->params, 'tab_activity_' );

						$this->showActivity( $id, $stream, ( $raw ? 1 : 0 ), true, $user, $viewer );

						$_CB_framework->setMenuMeta();
						break;
					case 'show':
					default:
						if ( isset( $postdata['stream'] ) && ( $postdata['stream'] instanceof ActivityInterface ) ) {
							$this->showActivity( $id, $stream, ( $inline ? 2 : 0 ), $data, $user, $viewer );
						} else {
							$this->showActivity( $id, $stream, ( $inline ? 2 : ( $raw ? 1 : 0 ) ), true, $user, $viewer );
						}
						break;
				}
				break;
			case 'hidden':
				if ( ! $stream ) {
					if ( $raw ) {
						header( 'HTTP/1.0 401 Unauthorized' );
						exit();
					} else {
						cbRedirect( 'index.php', CBTxt::T( 'Not authorized.' ), 'error' );
					}
				}

				switch ( $function ) {
					case 'users':
						break;
					case 'types':
						break;
					case 'comments':
						$stream->source( 'hidden' );

						$stream->set( 'create_access', -1 );
						$stream->set( 'replies', 0 );

						$this->showComments( $id, $stream, ( $raw ? 1 : 0 ), true, $user, $viewer );
						break;
					case 'activity':
						$stream->source( 'hidden' );

						$stream->set( 'create_access', -1 );
						$stream->set( 'comments', 0 );

						$this->showActivity( $id, $stream, ( $raw ? 1 : 0 ), true, $user, $viewer );
						break;
				}

				$_CB_framework->setMenuMeta();
				break;
			case 'tags':
				if ( ! $stream ) {
					if ( $raw ) {
						header( 'HTTP/1.0 401 Unauthorized' );
						exit();
					} else {
						cbRedirect( 'index.php', CBTxt::T( 'Not authorized.' ), 'error' );
					}
				}

				switch ( $function ) {
					case 'show':
					default:
						if ( isset( $postdata['stream'] ) && ( $postdata['stream'] instanceof TagsInterface ) ) {
							$this->showTags( $id, $stream, ( $inline ? 2 : 0 ), $data, $user, $viewer );
						} else {
							$this->showTags( $id, $stream, ( $inline ? 2 : ( $raw ? 1 : 0 ) ), true, $user, $viewer );
						}
						break;
				}
				break;
			case 'cleanup':
				if ( ( ! $raw ) || ( $this->input( 'token', null, GetterInterface::STRING ) != md5( $_CB_framework->getCfg( 'secret' ) ) ) ) {
					header( 'HTTP/1.0 401 Unauthorized' );
					exit();
				}

				$this->cleanUp();
				break;
		}

		if ( ! $raw ) {
			$html						=	ob_get_contents();
			ob_end_clean();

			if ( ! $inline ) {
				$class					=	$this->params->get( 'general_class', null );

				$html					=	'<div id="cbActivity" class="cbActivity' . ( $class ? ' ' . htmlspecialchars( $class ) : null ) . '">'
										.		'<div id="cbActivityInner" class="cbActivityInner">'
										.			$html
										.		'</div>'
										.	'</div>';
			}

			echo $html;
		}
	}
function plug_cbgroupjive_install()
{
	global $_CB_database, $_PLUGINS;

	// Uninstall the old integrations to avoid conflicts:
	$integrations									=	array(	'cbgroupjiveabout', 'cbgroupjiveevents', 'cbgroupjivefile',
																'cbgroupjiveforums', 'cbgroupjivephoto', 'cbgroupjivevideo',
																'cbgroupjivewall', 'cbgroupjiveauto'
															);

	foreach ( $integrations as $integration ) {
		$plugin										=	new PluginTable();

		$plugin->load( array( 'element' => $integration ) );

		if ( $plugin->get( 'id' ) && ( ! is_dir( $_PLUGINS->getPluginPath( $plugin ) . '/xml' ) ) ) {
			$plugin->delete();
		}
	}

	// Migrate categories:
	$table											=	'#__groupjive_categories';
	$fields											=	$_CB_database->getTableFields( $table );
	$migrate										=	false;

	if ( isset( $fields[$table]['parent'] ) ) {
		$migrate									=	true;

		$query										=	'SELECT *'
													.	"\n FROM " . $_CB_database->NameQuote( '#__groupjive_categories' );
		$_CB_database->setQuery( $query );
		$categories									=	$_CB_database->loadObjectList( null, '\CBLib\Database\Table\Table', array( $_CB_database, '#__groupjive_categories', 'id' ) );

		/** @var $categories Table[] */
		foreach ( $categories as $category ) {
			$category->set( 'access', ( $category->get( 'access' ) == -2 ? 1 : ( $category->get( 'access' ) == -1 ? 2 : Application::CmsPermissions()->convertOldGroupToViewAccessLevel( $category->get( 'access' ), 'CB GroupJive: Category Access - ' . (int) $category->get( 'id' ) ) ) ) );
			$category->set( 'create_access', ( ! $category->get( 'create' ) ? -1 : ( $category->get( 'create_access' ) == -1 ? 2 : Application::CmsPermissions()->convertOldGroupToViewAccessLevel( $category->get( 'create_access' ), 'CB GroupJive: Category Create Access - ' . (int) $category->get( 'id' ) ) ) ) );

			$categoryParams							=	new Registry( $category->get( 'params' ) );

			// CB GroupJive Forums:
			$categoryParams->set( 'forums', $categoryParams->get( 'forum_show' ) );

			$category->set( 'params', $categoryParams->asJson() );

			$category->store();
		}

		// Remove the old columns:
		$_CB_database->dropColumn( $table, 'parent' );
		$_CB_database->dropColumn( $table, 'create' );
		$_CB_database->dropColumn( $table, 'nested' );
		$_CB_database->dropColumn( $table, 'nested_access' );
	}

	// Migrate groups:
	$table											=	'#__groupjive_groups';
	$fields											=	$_CB_database->getTableFields( $table );

	if ( isset( $fields[$table]['parent'] ) ) {
		$migrate									=	true;

		$query										=	'SELECT *'
													.	"\n FROM " . $_CB_database->NameQuote( '#__groupjive_groups' );
		$_CB_database->setQuery( $query );
		$groups										=	$_CB_database->loadObjectList( null, '\CBLib\Database\Table\Table', array( $_CB_database, '#__groupjive_groups', 'id' ) );

		/** @var $groups Table[] */
		foreach ( $groups as $group ) {
			$groupParams							=	new Registry( $group->get( 'params' ) );

			// Core:
			$groupParams->set( 'invites', ( $group->get( 'invite' ) > 0 ? 0 : 1 ) );

			// CB GroupJive Events:
			$groupParams->set( 'events', ( $groupParams->get( 'events_approve' ) ? 2 : $groupParams->get( 'events_show' ) ) );

			// CB GroupJive File:
			$groupParams->set( 'file', ( $groupParams->get( 'file_approve' ) ? 2 : $groupParams->get( 'file_show' ) ) );

			// CB GroupJive Forums:
			$groupParams->set( 'forums', $groupParams->get( 'forum_show' ) );

			// CB GroupJive Photo:
			$groupParams->set( 'photo', ( $groupParams->get( 'photo_approve' ) ? 2 : $groupParams->get( 'photo_show' ) ) );

			// CB GroupJive Video:
			$groupParams->set( 'video', ( $groupParams->get( 'video_approve' ) ? 2 : $groupParams->get( 'video_show' ) ) );

			// CB GroupJive Wall:
			$groupParams->set( 'wall', ( $groupParams->get( 'wall_approve' ) ? 2 : $groupParams->get( 'wall_show' ) ) );

			$group->set( 'params', $groupParams->asJson() );

			$group->store();
		}

		// Remove the old columns:
		$_CB_database->dropColumn( $table, 'parent' );
		$_CB_database->dropColumn( $table, 'access' );
		$_CB_database->dropColumn( $table, 'invite' );
		$_CB_database->dropColumn( $table, 'users' );
		$_CB_database->dropColumn( $table, 'nested' );
		$_CB_database->dropColumn( $table, 'nested_access' );
	}

	// Migrate notifications:
	$table											=	'#__groupjive_notifications';
	$fields											=	$_CB_database->getTableFields( $table );

	if ( isset( $fields[$table]['type'] ) ) {
		$migrate									=	true;

		// Delete notification types no longer supported:
		$query										=	'DELETE'
													.	"\n FROM " . $_CB_database->NameQuote( '#__groupjive_notifications' )
													.	"\n WHERE " . $_CB_database->NameQuote( 'type' ) . " != " . $_CB_database->Quote( 'group' );
		$_CB_database->setQuery( $query );
		$_CB_database->query();

		// Migration notification parameters:
		$query										=	'SELECT *'
													.	"\n FROM " . $_CB_database->NameQuote( '#__groupjive_notifications' );
		$_CB_database->setQuery( $query );
		$notifications								=	$_CB_database->loadObjectList( null, '\CBLib\Database\Table\Table', array( $_CB_database, '#__groupjive_notifications', 'id' ) );

		/** @var $notifications Table[] */
		foreach ( $notifications as $notification ) {
			if ( ( $notification->get( 'type' ) == 'group' ) && $notification->get( 'item' ) ) {
				$notification->set( 'group', (int) $notification->get( 'item' ) );

				$notificationParams					=	new Registry( $notification->get( 'params' ) );

				// Core:
				$notificationParams->set( 'user_join', $notificationParams->get( 'group_userjoin' ) );
				$notificationParams->set( 'user_leave', $notificationParams->get( 'group_userleave' ) );
				$notificationParams->set( 'user_approve', $notificationParams->get( 'group_userapprove' ) );
				$notificationParams->set( 'invite_accept', $notificationParams->get( 'group_inviteaccept' ) );

				// CB GroupJive Events:
				$notificationParams->set( 'event_new', $notificationParams->get( 'group_eventnew' ) );
				$notificationParams->set( 'event_approve', $notificationParams->get( 'group_eventapprove' ) );
				$notificationParams->set( 'event_attend', $notificationParams->get( 'group_eventyes' ) );
				$notificationParams->set( 'event_unattend', $notificationParams->get( 'group_eventno' ) );

				// CB GroupJive File:
				$notificationParams->set( 'file_new', $notificationParams->get( 'group_filenew' ) );
				$notificationParams->set( 'file_approve', $notificationParams->get( 'group_fileapprove' ) );

				// CB GroupJive Photo:
				$notificationParams->set( 'photo_new', $notificationParams->get( 'group_photonew' ) );
				$notificationParams->set( 'photo_approve', $notificationParams->get( 'group_photoapprove' ) );

				// CB GroupJive Video:
				$notificationParams->set( 'video_new', $notificationParams->get( 'group_videonew' ) );
				$notificationParams->set( 'video_approve', $notificationParams->get( 'group_videoapprove' ) );

				// CB GroupJive Wall:
				$notificationParams->set( 'wall_new', $notificationParams->get( 'group_wallnew' ) );
				$notificationParams->set( 'wall_approve', $notificationParams->get( 'group_wallapprove' ) );
				$notificationParams->set( 'wall_reply', $notificationParams->get( 'group_wallreply' ) );

				$notification->set( 'params', $notificationParams->asJson() );

				$notification->store();
			}
		}

		// Remove the old columns:
		$_CB_database->dropColumn( $table, 'type' );
		$_CB_database->dropColumn( $table, 'item' );
	}

	if ( $migrate ) {
		// Migrate global parameters:
		$plugin										=	new PluginTable();

		$plugin->load( array( 'element' => 'cbgroupjive' ) );

		$pluginParams								=	new Registry( $plugin->get( 'params' ) );

		// Logos:
		$pluginParams->set( 'logo_max_size', $pluginParams->get( 'logo_size' ) );
		$pluginParams->set( 'logo_image_width', $pluginParams->get( 'logo_width' ) );
		$pluginParams->set( 'logo_image_height', $pluginParams->get( 'logo_height' ) );
		$pluginParams->set( 'logo_thumbnail_width', $pluginParams->get( 'logo_thumbwidth' ) );
		$pluginParams->set( 'logo_thumbnail_height', $pluginParams->get( 'logo_thumbheight' ) );

		// Notifications:
		$pluginParams->set( 'notifications', $pluginParams->get( 'general_notifications' ) );
		$pluginParams->set( 'notifications_notifyby', ( $pluginParams->get( 'general_notifyby' ) < 4 ? 2 : 1 ) );
		$pluginParams->set( 'notifications_default_user_join', $pluginParams->get( 'notifications_group_userjoin' ) );
		$pluginParams->set( 'notifications_default_user_leave', $pluginParams->get( 'notifications_group_userleave' ) );
		$pluginParams->set( 'notifications_default_user_approve', $pluginParams->get( 'notifications_group_userapprove' ) );
		$pluginParams->set( 'notifications_default_invite_accept', $pluginParams->get( 'notifications_group_inviteaccept' ) );

		// Categories:
		$pluginParams->set( 'categories_paging', $pluginParams->get( 'overview_paging' ) );
		$pluginParams->set( 'categories_limit', $pluginParams->get( 'overview_limit' ) );
		$pluginParams->set( 'categories_search', $pluginParams->get( 'overview_search' ) );

		switch( (int) $pluginParams->get( 'overview_orderby' ) ) {
			case 7:
				$orderBy							=	5;
				break;
			case 8:
				$orderBy							=	6;
				break;
			case 5:
				$orderBy							=	3;
				break;
			case 6:
				$orderBy							=	4;
				break;
			case 1:
			case 2:
				$orderBy							=	(int) $pluginParams->get( 'overview_orderby' );
				break;
			case 3:
			case 4:
			case 9:
			case 10:
			default:
				$orderBy							=	1;
				break;
		}

		$pluginParams->set( 'categories_orderby', $orderBy );
		$pluginParams->set( 'categories_groups_paging', $pluginParams->get( 'category_groups_paging' ) );
		$pluginParams->set( 'categories_groups_limit', $pluginParams->get( 'category_groups_limit' ) );
		$pluginParams->set( 'categories_groups_search', $pluginParams->get( 'category_groups_search' ) );
		$pluginParams->set( 'categories_groups_orderby', ( $pluginParams->get( 'category_groups_orderby' ) > 8 ? 4 : $pluginParams->get( 'category_groups_orderby' ) ) );

		// Groups:
		$pluginParams->set( 'groups_create_access', ( ! $pluginParams->get( 'group_create' ) ? -1 : ( $pluginParams->get( 'group_create_access' ) == -1 ? 2 : Application::CmsPermissions()->convertOldGroupToViewAccessLevel( $pluginParams->get( 'group_create_access' ), 'CB GroupJive: Groups Create Access' ) ) ) );
		$pluginParams->set( 'groups_create_limit', $pluginParams->get( 'group_limit' ) );
		$pluginParams->set( 'groups_create_approval', $pluginParams->get( 'group_approve' ) );
		$pluginParams->set( 'groups_create_captcha', $pluginParams->get( 'group_captcha' ) );
		$pluginParams->set( 'groups_message', $pluginParams->get( 'group_message' ) );
		$pluginParams->set( 'groups_message_captcha', $pluginParams->get( 'group_message_captcha' ) );
		$pluginParams->set( 'groups_users_paging', $pluginParams->get( 'group_users_paging' ) );
		$pluginParams->set( 'groups_users_limit', $pluginParams->get( 'group_users_limit' ) );
		$pluginParams->set( 'groups_users_search', $pluginParams->get( 'group_users_search' ) );
		$pluginParams->set( 'groups_invites_display', $pluginParams->get( 'group_invites_display' ) );
		$pluginParams->set( 'groups_invites_by', $pluginParams->get( 'group_invites_by' ) );
		$pluginParams->set( 'groups_invites_list', $pluginParams->get( 'group_invites_list' ) );
		$pluginParams->set( 'groups_invites_accept', $pluginParams->get( 'group_invites_accept' ) );
		$pluginParams->set( 'groups_invites_captcha', $pluginParams->get( 'group_invites_captcha' ) );
		$pluginParams->set( 'groups_invites_paging', $pluginParams->get( 'group_invites_paging' ) );
		$pluginParams->set( 'groups_invites_limit', $pluginParams->get( 'group_invites_limit' ) );
		$pluginParams->set( 'groups_invites_search', $pluginParams->get( 'group_invites_search' ) );
		$pluginParams->set( 'groups_paging', $pluginParams->get( 'group_all_paging' ) );
		$pluginParams->set( 'groups_limit', $pluginParams->get( 'group_all_limit' ) );
		$pluginParams->set( 'groups_search', $pluginParams->get( 'group_all_search' ) );
		$pluginParams->set( 'groups_orderby', ( $pluginParams->get( 'group_all_orderby' ) > 8 ? 4 : $pluginParams->get( 'group_all_orderby' ) ) );

		$plugin->set( 'params', $pluginParams->asJson() );

		$plugin->store();

		// Migrate the old auto fields to core GJ:
		$query										=	'UPDATE '. $_CB_database->NameQuote( '#__comprofiler_fields' )
													.	"\n SET " . $_CB_database->NameQuote( 'type' ) . " = " . $_CB_database->Quote( 'groupautojoin' )
													.	', ' . $_CB_database->NameQuote( 'pluginid' ) . ' = ' . (int) $plugin->get( 'id' )
													.	"\n WHERE " . $_CB_database->NameQuote( 'type' ) . " = " . $_CB_database->Quote( 'cbgjautojoin' );
		$_CB_database->setQuery( $query );
		$_CB_database->query();

		// Migrate tab parameters:
		$tab										=	new TabTable();

		$tab->load( array( 'pluginclass' => 'cbgjTab' ) );

		$tabParams									=	new Registry( $tab->get( 'params' ) );

		$tabParams->set( 'tab_paging', $pluginParams->get( 'group_tab_paging' ) );
		$tabParams->set( 'tab_limit', $pluginParams->get( 'group_tab_limit' ) );
		$tabParams->set( 'tab_search', $pluginParams->get( 'group_tab_search' ) );
		$tabParams->set( 'tab_orderby', ( $pluginParams->get( 'group_tab_orderby' ) > 8 ? 4 : $pluginParams->get( 'group_tab_orderby' ) ) );

		$tab->set( 'params', $tabParams->asJson() );

		$tab->store();
	}

	// Migrate gj auto to cb auto actions if possible:
	$table											=	'#__groupjive_plugin_auto';

	if ( $_CB_database->getTableStatus( $table ) ) {
		$fields										=	$_CB_database->getTableFields( $table );

		if ( isset( $fields[$table]['trigger'] ) ) {
			$autoActions							=	new PluginTable();

			$autoActions->load( array( 'element' => 'cbautoactions' ) );

			if ( $autoActions->get( 'id' ) ) {
				$table								=	'#__comprofiler_plugin_autoactions';
				$fields								=	$_CB_database->getTableFields( $table );

				if ( ! isset( $fields[$table]['conditions'] ) ) {
					return;
				}

				$query								=	'SELECT *'
													.	"\n FROM " . $_CB_database->NameQuote( '#__groupjive_plugin_auto' );
				$_CB_database->setQuery( $query );
				$autos								=	$_CB_database->loadObjectList( null, '\CBLib\Database\Table\Table', array( $_CB_database, '#__groupjive_plugin_auto', 'id' ) );

				/** @var $autos Table[] */
				foreach ( $autos as $auto ) {
					$oldParams						=	new Registry( $auto->get( 'params' ) );

					if ( $oldParams->get( 'migrated' ) ) {
						continue;
					}

					$newParams						=	new Registry();
					$newConditions					=	null;

					if ( $auto->get( 'field' ) ) {
						$fields						=	new Registry( $auto->get( 'field' ) );
						$operators					=	new Registry( $auto->get( 'operator' ) );
						$values						=	new Registry( $auto->get( 'value' ) );

						$conditionals				=	count( $fields );

						if ( $conditionals ) {
							$conditions				=	array();

							for ( $i = 0, $n = $conditionals; $i < $n; $i++ ) {
								$field				=	$fields->get( "field$i" );
								$operator			=	$operators->get( "operator$i" );
								$value				=	$values->get( "value$i" );

								if ( $operator ) {
									$conditions[]	=	array( 'field' => $field, 'operator' => $operator, 'value' => $value, 'translate' => 0 );
								}
							}

							if ( $conditions ) {
								$newConditionals	=	new Registry( $conditions );
								$newConditions		=	$newConditionals->asJson();
							}
						}
					}

					$mode							=	$oldParams->get( 'auto' );

					$join							=	array(	'mode'					=>	$mode,
																'groups'				=>	$oldParams->get( 'groups' ),
																'status'				=>	$oldParams->get( 'status' ),
																'name'					=>	( $mode == 2 ? $oldParams->get( 'grp_name' ) : $oldParams->get( 'cat_name' ) ),
																'category'				=>	$oldParams->get( 'category' ),
																'category_name'			=>	$oldParams->get( 'cat_name' ),
																'category_parent'		=>	$oldParams->get( 'cat_parent' ),
																'category_types'		=>	$oldParams->get( 'types' ),
																'category_description'	=>	$oldParams->get( 'cat_description' ),
																'category_unique'		=>	$oldParams->get( 'cat_unique' ),
																'group_parent'			=>	$oldParams->get( 'grp_parent' ),
																'type'					=>	$oldParams->get( 'type' ),
																'parent'				=>	$oldParams->get( 'cat_parent' ),
																'types'					=>	$oldParams->get( 'types' ),
																'description'			=>	( $mode == 2 ? $oldParams->get( 'grp_description' ) : $oldParams->get( 'cat_description' ) ),
																'owner'					=>	( $mode == 2 ? $oldParams->get( 'grp_owner' ) : $oldParams->get( 'cat_owner' ) ),
																'unique'				=>	( $mode == 2 ? $oldParams->get( 'grp_unique' ) : $oldParams->get( 'cat_unique' ) ),
																'autojoin'				=>	$oldParams->get( 'grp_autojoin' ),
																'group_status'			=>	$oldParams->get( 'status' )
															);

					$newParams->set( 'groupjive', array( $join ) );
					$newParams->set( 'exclude', $auto->get( 'exclude' ) );

					$query							=	'INSERT IGNORE INTO '. $_CB_database->NameQuote( '#__comprofiler_plugin_autoactions' )
													.	' ( '
													.		$_CB_database->NameQuote( 'published' )
													.		', ' . $_CB_database->NameQuote( 'title' )
													.		', ' . $_CB_database->NameQuote( 'description' )
													.		', ' . $_CB_database->NameQuote( 'type' )
													.		', ' . $_CB_database->NameQuote( 'trigger' )
													.		', ' . $_CB_database->NameQuote( 'object' )
													.		', ' . $_CB_database->NameQuote( 'variable' )
													.		', ' . $_CB_database->NameQuote( 'access' )
													.		', ' . $_CB_database->NameQuote( 'conditions' )
													.		', ' . $_CB_database->NameQuote( 'params' )
													.	' ) VALUES ( '
													.		(int) $auto->get( 'published' )
													.		', ' . $_CB_database->Quote( $auto->get( 'title' ) )
													.		', ' . $_CB_database->Quote( $auto->get( 'description' ) )
													.		', ' . $_CB_database->Quote( 'groupjive' )
													.		', ' . $_CB_database->Quote( str_replace( ',', '|*|', $auto->get( 'trigger' ) ) )
													.		', ' . $_CB_database->Quote( $auto->get( 'object' ) )
													.		', ' . $_CB_database->Quote( $auto->get( 'variable' ) )
													.		', ' . $_CB_database->Quote( $auto->get( 'access' ) )
													.		', ' . $_CB_database->Quote( $newConditions )
													.		', ' . $_CB_database->Quote( $newParams->asJson() )
													.	' )';
					$_CB_database->setQuery( $query );
					$_CB_database->query();

					$oldParams->set( 'migrated', true );

					$auto->set( 'params', $oldParams->asJson() );

					$auto->store();
				}
			}
		}
	}
}
Example #23
0
	/**
	 * Returns a provider button
	 *
	 * @param string $provider
	 * @param int    $horizontal
	 * @return null|string
	 */
	public function getButton( $provider, $horizontal = 1 )
	{
		global $_CB_framework;

		if ( ! ( $provider && isset( $this->providers[$provider] ) ) ) {
			return null;
		}

		$fieldName					=	$this->providers[$provider]['field'];
		$siteName					=	$this->providers[$provider]['name'];
		$iconClass					=	$this->providers[$provider]['icon'];
		$buttonClass				=	$this->providers[$provider]['button'];
		$user						=	CBuser::getMyUserDataInstance();
		$style						=	(int) $this->params->get( $provider . '_button_style', 2, GetterInterface::INT );

		if ( $style == 1 ) {
			$horizontal				=	1;
		}

		static $returnUrl			=	null;

		if ( ! isset( $returnUrl ) ) {
			$returnUrl				=	$this->input->get( 'return', null, GetterInterface::BASE64 );

			if ( $returnUrl ) {
				$returnUrl			=	base64_decode( $returnUrl );
			} else {
				$isHttps			=	( isset( $_SERVER['HTTPS'] ) && ( ! empty( $_SERVER['HTTPS'] ) ) && ( $_SERVER['HTTPS'] != 'off' ) );
				$returnUrl			=	'http' . ( $isHttps ? 's' : '' ) . '://' . $_SERVER['HTTP_HOST'];

				if ( ( ! empty( $_SERVER['PHP_SELF'] ) ) && ( ! empty( $_SERVER['REQUEST_URI'] ) ) ) {
					$returnUrl		.=	$_SERVER['REQUEST_URI'];
				} else {
					$returnUrl		.=	$_SERVER['SCRIPT_NAME'];

					if ( isset( $_SERVER['QUERY_STRING'] ) && ( ! empty( $_SERVER['QUERY_STRING'] ) ) ) {
						$returnUrl	.=	'?' . $_SERVER['QUERY_STRING'];
					}
				}
			}

			$returnUrl				=	cbUnHtmlspecialchars( preg_replace( '/[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']/', '""', preg_replace( '/eval\((.*)\)/', '', htmlspecialchars( urldecode( $returnUrl ) ) ) ) );

			if ( preg_match( '/index\.php\?option=com_comprofiler&view=login|index\.php\?option=com_comprofiler&view=pluginclass&plugin=cbconnect/', $returnUrl ) ) {
				$returnUrl			=	'index.php';
			}

			$returnUrl				=	base64_encode( $returnUrl );
		}

		$return						=	null;

		if ( $this->params->get( $provider . '_enabled', false, GetterInterface::BOOLEAN ) ) {
			if ( $user->get( 'id' ) ) {
				if ( $this->params->get( $provider . '_link', true, GetterInterface::BOOLEAN ) && ( ! $user->get( $fieldName ) ) ) {
					$link			=	$this->params->get( $provider . '_button_link', null, GetterInterface::STRING );

					$return			=	'<button class="cbConnectButton cbConnectButton' . ucfirst( $provider ) . ' btn btn-' . $buttonClass . ' btn-sm' . ( ! $horizontal ? ' btn-block' : null ) . '" onclick="window.location=\'' . $_CB_framework->pluginClassUrl( $this->plugin->element, false, array( 'provider' => $provider, 'action' => 'authenticate', 'return' => $returnUrl ) ) . '\'; return false;" title="' . htmlspecialchars( CBTxt::T( 'LINK_YOUR_SITENAME_ACCOUNT', 'Link your [sitename] account', array( '[sitename]' => $siteName ) ) ) . '">'
									.		( in_array( $style, array( 1, 2 ) ) ? '<span class="fa fa-' . $iconClass . ' fa-lg' . ( $style != 1 ? ' cbConnectButtonPrefix' : null ) . '"></span>' : null )
									.		( in_array( $style, array( 2, 3 ) ) ? ( $link ? $link : CBTxt::T( 'LINK_WITH_SITENAME', 'Link with [sitename]', array( '[sitename]' => $siteName ) ) ) : null )
									.	'</button>'
									.	( $horizontal ? ' ' : null );
				}
			} else {
				$signin				=	$this->params->get( $provider . '_button_signin', null, GetterInterface::STRING );

				$return				=	'<button class="cbConnectButton cbConnectButton' . ucfirst( $provider ) . ' btn btn-' . $buttonClass . ' btn-sm' . ( ! $horizontal ? ' btn-block' : null ) . '" onclick="window.location=\'' . $_CB_framework->pluginClassUrl( $this->plugin->element, false, array( 'provider' => $provider, 'action' => 'authenticate', 'return' => $returnUrl ) ) . '\'; return false;" title="' . htmlspecialchars( CBTxt::T( 'LOGIN_WITH_YOUR_SITENAME_ACCOUNT', 'Login with your [sitename] account', array( '[sitename]' => $siteName ) ) ) . '">'
									.		( in_array( $style, array( 1, 2 ) ) ? '<span class="fa fa-' . $iconClass . ' fa-lg' . ( $style != 1 ? ' cbConnectButtonPrefix' : null ) . '"></span>' : null )
									.		( in_array( $style, array( 2, 3 ) ) ? ( $signin ? $signin : CBTxt::T( 'SIGN_IN_WITH_SITENAME', 'Sign in with [sitename]', array( '[sitename]' => $siteName ) ) ) : null )
									.	'</button>'
									.	( $horizontal ? ' ' : null );
			}
		}

		return $return;
	}
Example #24
0
	/**
	 * Parses a string for PHP functions
	 *
	 * @param string $input
	 * @param array  $vars
	 * @return string
	 */
	static public function formatCondition( $input, $vars = array() )
	{
																// \[cb:parse(?: +function="([^"/\[\] ]+)")( +(?: ?[a-zA-Z-_]+="(?:[^"]|\\")+")+)?(?:(?:\s*/])|(?:]((?:[^\[]|\[(?!/?cb:parse[^\]]*])|(?R))+)?\[/cb:parse]))
		$regex												=	'%\[cb:parse(?: +function="([^"/\[\] ]+)")( +(?: ?[a-zA-Z-_]+="(?:[^"]|\\\\")+")+)?(?:(?:\s*/])|(?:]((?:[^\[]|\[(?!/?cb:parse[^\]]*])|(?R))+)?\[/cb:parse]))%i';

		if ( preg_match_all( $regex, $input, $results, PREG_SET_ORDER ) ) {
			foreach( $results as $matches ) {
				$function									=	( isset( $matches[1] ) ? $matches[1] : null );

				if ( $function ) {
					$value									=	( isset( $matches[3] ) ? self::formatCondition( $matches[3], $vars ) : null );
					$options								=	new Registry();

					if ( isset( $matches[2] ) ) {
						if ( preg_match_all( '/(?:([a-zA-Z-_]+)="((?:[^"]|\\\\\\\\")+)")+/i', $matches[2], $optionResults, PREG_SET_ORDER ) ) {
							foreach( $optionResults as $option ) {
								$k							=	( isset( $option[1] ) ? $option[1] : null );
								$v							=	( isset( $option[2] ) ? $option[2] : null );

								if ( $k ) {
									$options->set( $k, $v );
								}
							}
						}
					}

					$method									=	$options->get( 'method' );

					$options->unsetEntry( 'method' );

					switch ( $function ) {
						case 'clean':
							switch( $method ) {
								case 'cmd':
									$input					=	str_replace( $matches[0], Get::clean( $value, GetterInterface::COMMAND ), $input );
									break;
								case 'numeric':
									$input					=	str_replace( $matches[0], Get::clean( $value, GetterInterface::NUMERIC ), $input );
									break;
								case 'unit':
									$input					=	str_replace( $matches[0], Get::clean( $value, GetterInterface::UINT ), $input );
									break;
								case 'int':
								case 'integer':
									$input					=	str_replace( $matches[0], Get::clean( $value, GetterInterface::INT ), $input );
									break;
								case 'bool':
								case 'boolean':
									$input					=	str_replace( $matches[0], Get::clean( $value, GetterInterface::BOOLEAN ), $input );
									break;
								case 'str':
								case 'string':
									$input					=	str_replace( $matches[0], Get::clean( $value, GetterInterface::STRING ), $input );
									break;
								case 'html':
									$input					=	str_replace( $matches[0], Get::clean( $value, GetterInterface::HTML ), $input );
									break;
								case 'float':
									$input					=	str_replace( $matches[0], Get::clean( $value, GetterInterface::FLOAT ), $input );
									break;
								case 'base64':
									$input					=	str_replace( $matches[0], Get::clean( $value, GetterInterface::BASE64 ), $input );
									break;
								case 'tags':
									$input					=	str_replace( $matches[0], strip_tags( $value ), $input );
									break;
							}
							break;
						case 'convert':
							switch( $method ) {
								case 'uppercase':
									$input					=	str_replace( $matches[0], strtoupper( $value ), $input );
									break;
								case 'uppercasewords':
									$input					=	str_replace( $matches[0], ucwords( $value ), $input );
									break;
								case 'uppercasefirst':
									$input					=	str_replace( $matches[0], ucfirst( $value ), $input );
									break;
								case 'lowercase':
									$input					=	str_replace( $matches[0], strtolower( $value ), $input );
									break;
								case 'lowercasefirst':
									$input					=	str_replace( $matches[0], lcfirst( $value ), $input );
									break;
							}
							break;
						case 'math':
							$input							=	str_replace( $matches[0], self::formatMath( $value ), $input );
							break;
						case 'time':
							$input							=	str_replace( $matches[0], ( $options->has( 'time' ) ? strtotime( $options->get( 'time', null, GetterInterface::STRING ), ( is_numeric( $value ) ? (int) $value : strtotime( $value ) ) ) : strtotime( $value ) ), $input );
							break;
						case 'date':
							$offset							=	$options->get( 'offset' );
							$input							=	str_replace( $matches[0], cbFormatDate( ( is_numeric( $value ) ? (int) $value : strtotime( $value ) ), ( $offset ? true : false ), true, $options->get( 'date-format' ), $options->get( 'time-format' ), ( $offset != 'true' ? $offset : null ) ), $input );
							break;
						case 'length':
							$input							=	str_replace( $matches[0], strlen( $value ), $input );
							break;
						case 'replace':
							$input							=	str_replace( $matches[0], ( $options->has( 'count' ) ? str_replace( $options->get( 'search' ), $options->get( 'replace' ), $value, $options->get( 'count', 0, GetterInterface::INT ) ) : str_replace( $options->get( 'search' ), $options->get( 'replace' ), $value ) ), $input );
							break;
						case 'position':
							switch( $options->get( 'occurrence' ) ) {
								case 'last':
									$input					=	str_replace( $matches[0], strrpos( $value, $options->get( 'search' ) ), $input );
									break;
								case 'first':
								default:
									$input					=	str_replace( $matches[0], strpos( $value, $options->get( 'search' ) ), $input );
									break;
							}
							break;
						case 'occurrence':
							$input							=	str_replace( $matches[0], strstr( $value, $options->get( 'search' ) ), $input );
							break;
						case 'repeat':
							$input							=	str_replace( $matches[0], str_repeat( $value, $options->get( 'count', 0, GetterInterface::INT ) ), $input );
							break;
						case 'extract':
							$input							=	str_replace( $matches[0], ( $options->has( 'length' ) ? substr( $value, $options->get( 'start', 0, GetterInterface::INT ), $options->get( 'length', 0, GetterInterface::INT ) ) : substr( $value, $options->get( 'start', 0, GetterInterface::INT ) ) ), $input );
							break;
						case 'trim':
							switch( $options->get( 'direction' ) ) {
								case 'left':
									$input					=	str_replace( $matches[0], ( $options->has( 'characters' ) ? ltrim( $value, $options->get( 'characters', null, GetterInterface::STRING ) ) : ltrim( $value ) ), $input );
									break;
								case 'right':
									$input					=	str_replace( $matches[0], ( $options->has( 'characters' ) ? rtrim( $value, $options->get( 'characters', null, GetterInterface::STRING ) ) : rtrim( $value ) ), $input );
									break;
								default:
									$input					=	str_replace( $matches[0], ( $options->has( 'characters' ) ? trim( $value, $options->get( 'characters', null, GetterInterface::STRING ) ) : trim( $value ) ), $input );
									break;
							}
							break;
						case 'encode':
							switch( $method ) {
								case 'cslashes':
									$input					=	str_replace( $matches[0], addcslashes( $value, $options->get( 'characters', null, GetterInterface::STRING ) ), $input );
									break;
								case 'slashes':
									$input					=	str_replace( $matches[0], addslashes( $value ), $input );
									break;
								case 'entity':
									$input					=	str_replace( $matches[0], htmlentities( $value ), $input );
									break;
								case 'html':
									$input					=	str_replace( $matches[0], htmlspecialchars( $value ), $input );
									break;
								case 'url':
									$input					=	str_replace( $matches[0], urlencode( $value ), $input );
									break;
								case 'base64':
									$input					=	str_replace( $matches[0], base64_encode( $value ), $input );
									break;
								case 'md5':
									$input					=	str_replace( $matches[0], md5( $value ), $input );
									break;
								case 'sha1':
									$input					=	str_replace( $matches[0], sha1( $value ), $input );
									break;
								case 'password':
									$user					=	new UserTable();

									$input					=	str_replace( $matches[0], $user->hashAndSaltPassword( $value ), $input );
									break;
							}
							break;
						case 'decode':
							switch( $method ) {
								case 'cslashes':
									$input					=	str_replace( $matches[0], stripcslashes( $value ), $input );
									break;
								case 'slashes':
									$input					=	str_replace( $matches[0], stripslashes( $value ), $input );
									break;
								case 'entity':
									$input					=	str_replace( $matches[0], html_entity_decode( $value ), $input );
									break;
								case 'html':
									$input					=	str_replace( $matches[0], htmlspecialchars_decode( $value ), $input );
									break;
								case 'url':
									$input					=	str_replace( $matches[0], urldecode( $value ), $input );
									break;
								case 'base64':
									$input					=	str_replace( $matches[0], base64_encode( $value ), $input );
									break;
							}
							break;
						default:
							if ( ! $function ) {
								continue;
							}

							$class							=	$options->get( 'class', null, GetterInterface::STRING );
							$subFunction					=	null;
							$static							=	false;
							$result							=	null;

							if ( strpos( $function, '::' ) !== false ) {
								list( $class, $function )	=	explode( '::', $function, 2 );

								$static						=	true;
							} elseif ( strpos( $class, '::' ) !== false ) {
								$subFunction				=	$function;

								list( $class, $function )	=	explode( '::', $class, 2 );

								$static						=	true;
							}

							if ( $class ) {
								$object						=	null;

								$options->unsetEntry( 'class' );

								if ( isset( $vars[$class] ) && is_object( $vars[$class] ) ) {
									$object					=	$vars[$class];
									$class					=	get_class( $object );
								}

								if ( $static ) {
									if ( $subFunction ) {
										if ( is_callable( array( $class, $function ) ) ) {
											$object			=	call_user_func_array( array( $class, $function ), array() );

											if ( method_exists( $object, $subFunction ) ) {
												$result		=	call_user_func_array( array( $object, $subFunction ), $options->asArray() );
											}
										}
									} else {
										if ( is_callable( array( $class, $function ) ) ) {
											$result			=	call_user_func_array( array( $class, $function ), $options->asArray() );
										}
									}
								} else {
									if ( $object || class_exists( $class ) ) {
										if ( ! $object ) {
											$object			=	new $class();

											if ( $value && method_exists( $object, 'load' ) ) {
												$object->load( $value );
											}
										}

										if ( method_exists( $object, $function ) ) {
											$result			=	call_user_func_array( array( $object, $function ), $options->asArray() );
										}
									}
								}
							} else {
								if ( function_exists( $function ) ) {
									$result					=	call_user_func_array( $function, $options->asArray() );
								}
							}

							if ( $method && is_object( $result ) && method_exists( $result, $method ) ) {
								$result						=	call_user_func_array( array( $result, $method ), $options->asArray() );
							}

							if ( ( ! is_array( $result ) ) && ( ! is_object( $result ) ) ) {
								$input						=	str_replace( $matches[0], $result, $input );
							}
							break;
					}

					// If no replacement is done above then the string still exists; lets just replace the substitution with the found value:
					$input									=	str_replace( $matches[0], $value, $input );
				}
			}

			$input											=	self::formatCondition( $input, $vars );
		}

		return $input;
	}
Example #25
0
	/**
	 * @param string $text
	 * @param string $phrase
	 * @param string $ordering
	 * @param null   $areas
	 * @return array|null
	 */
	public function onContentSearch( $text, $phrase = '', $ordering = '', $areas = null )
	{
		global $_CB_database, $_CB_framework;

		if ( ( ( ! $this->getCategorySearching() ) && ( ! $this->getGroupSearching() ) ) || ( ! $text ) || ( ! $this->_gjPlugin ) ) {
			return array();
		}

		$user							=	CBuser::getMyUserDataInstance();
		$isModerator					=	CBGroupJive::isModerator( $user->get( 'id' ) );
		$results						=	array();

		$excludeCategories				=	$this->params->get( 'search_category_exclude', null );

		if ( $excludeCategories ) {
			$excludeCategories			=	explode( '|*|', $excludeCategories );
		}

		$excludeGroups					=	$this->params->get( 'search_group_exclude', null );

		if ( $excludeGroups ) {
			$excludeGroups				=	explode( '|*|', $excludeGroups );
		}

		if ( $this->getCategorySearching() ) {
			$resultTitle				=	$this->params->get( 'results_category_title', '[name]' );
			$resultText					=	$this->params->get( 'results_category_text', '[description]' );
			$resultsLimit				=	(int) $this->params->get( 'results_category_limit', 50 );
			$resultsLinks				=	(int) $this->params->get( 'results_category_link', 0 );

			switch( $phrase ) {
				case 'exact':
					$where				=	"\n WHERE ( c." . $_CB_database->NameQuote( 'name' ) . " = " . $_CB_database->Quote( $text )
										.	" OR c." . $_CB_database->NameQuote( 'description' ) . " = " . $_CB_database->Quote( $text ) . " )";
					break;
				case 'any':
				case 'all':
				default:
					$words				=	explode( ' ', $text );
					$search				=	array();

					foreach ( $words as $word ) {
						$search[]		=	"( c." . $_CB_database->NameQuote( 'name' ) . " LIKE " . $_CB_database->Quote( '%' . $_CB_database->getEscaped( $word, true ) . '%', false )
										.	" OR c." . $_CB_database->NameQuote( 'description' ) . " LIKE " . $_CB_database->Quote( '%' . $_CB_database->getEscaped( $word, true ) . '%', false ) . " )";
					}

					$where				=	"\n WHERE ( " . implode( ( $phrase == 'any' ? " OR " : " AND " ), $search ) . " )";
					break;
			}

			switch( $ordering ) {
				case 'oldest':
					$orderBy			=	'c.' . $_CB_database->NameQuote( 'ordering' ) . ' ASC';
					break;
				case 'popular':
					$orderBy			=	$_CB_database->NameQuote( '_groups' ) . ' DESC';
					break;
				case 'alpha':
					$orderBy			=	'c.' . $_CB_database->NameQuote( 'name' ) . ' ASC';
					break;
				case 'newest':
				case 'category':
				default:
					$orderBy			=	'c.' . $_CB_database->NameQuote( 'ordering' ) . ' DESC';
					break;
			}

			$groups						=	null;

			if ( $ordering == 'popular' ) {
				$groups					=	'SELECT COUNT(*)'
										.	"\n FROM " . $_CB_database->NameQuote( '#__groupjive_groups' ) . " AS g"
										.	"\n LEFT JOIN " . $_CB_database->NameQuote( '#__comprofiler' ) . " AS cb"
										.	' ON cb.' . $_CB_database->NameQuote( 'id' ) . ' = g.' . $_CB_database->NameQuote( 'user_id' )
										.	"\n LEFT JOIN " . $_CB_database->NameQuote( '#__users' ) . " AS j"
										.	' ON j.' . $_CB_database->NameQuote( 'id' ) . ' = cb.' . $_CB_database->NameQuote( 'id' );

				if ( ! $isModerator ) {
					$groups				.=	"\n LEFT JOIN " . $_CB_database->NameQuote( '#__groupjive_users' ) . " AS u"
										.	' ON u.' . $_CB_database->NameQuote( 'user_id' ) . ' = ' . (int) $user->get( 'id' )
										.	' AND u.' . $_CB_database->NameQuote( 'group' ) . ' = g.' . $_CB_database->NameQuote( 'id' )
										.	"\n LEFT JOIN " . $_CB_database->NameQuote( '#__groupjive_invites' ) . " AS i"
										.	' ON i.' . $_CB_database->NameQuote( 'group' ) . ' = g.' . $_CB_database->NameQuote( 'id' )
										.	' AND i.' . $_CB_database->NameQuote( 'accepted' ) . ' = ' . $_CB_database->Quote( '0000-00-00 00:00:00' )
										.	' AND ( ( i.' . $_CB_database->NameQuote( 'email' ) . ' = ' . $_CB_database->Quote( $user->get( 'email' ) )
										.	' AND i.' . $_CB_database->NameQuote( 'email' ) . ' != "" )'
										.	' OR ( i.' . $_CB_database->NameQuote( 'user' ) . ' = ' . (int) $user->get( 'id' )
										.	' AND i.' . $_CB_database->NameQuote( 'user' ) . ' > 0 ) )';
				}

				$groups					.=	"\n WHERE g." . $_CB_database->NameQuote( 'category' ) . " = c." . $_CB_database->NameQuote( 'id' )
										.	"\n AND cb." . $_CB_database->NameQuote( 'approved' ) . " = 1"
										.	"\n AND cb." . $_CB_database->NameQuote( 'confirmed' ) . " = 1"
										.	"\n AND j." . $_CB_database->NameQuote( 'block' ) . " = 0";

				if ( ! $isModerator ) {
					$groups				.=	"\n AND ( g." . $_CB_database->NameQuote( 'user_id' ) . " = " . (int) $user->get( 'id' )
										.		' OR ( g.' . $_CB_database->NameQuote( 'published' ) . ' = 1'
										.		' AND ( g.' . $_CB_database->NameQuote( 'type' ) . ' IN ( 1, 2 )'
										.		' OR u.' . $_CB_database->NameQuote( 'status' ) . ' IN ( 0, 1, 2, 3 )'
										.		' OR i.' . $_CB_database->NameQuote( 'id' ) . ' IS NOT NULL ) ) )';
				}
			}

			$query						=	'SELECT c.*'
										.	( $ordering == 'popular' ? ', ( ' . $groups . ' ) AS _groups' : null )
										.	"\n FROM " . $_CB_database->NameQuote( '#__groupjive_categories' ) . " AS c"
										.	$where;

			if ( ! $isModerator ) {
				$query					.=	"\n AND c." . $_CB_database->NameQuote( 'published' ) . " = 1"
										.	"\n AND c." . $_CB_database->NameQuote( 'access' ) . " IN " . $_CB_database->safeArrayOfIntegers( CBGroupJive::getAccess( $user->get( 'id' ) ) );
			}

			$query						.=	( $excludeCategories ? "\n AND c." . $_CB_database->NameQuote( 'id' ) . " NOT IN " . $_CB_database->safeArrayOfIntegers( $excludeCategories ) : null )
										.	"\n ORDER BY " . $orderBy;
			if ( $resultsLimit ) {
				$_CB_database->setQuery( $query, 0, $resultsLimit );
			} else {
				$_CB_database->setQuery( $query );
			}
			$rows						=	$_CB_database->loadObjectList( null, '\CB\Plugin\GroupJive\Table\CategoryTable', array( $_CB_database ) );

			/** @var CategoryTable[] $rows */
			foreach ( $rows as $row ) {
				$url					=	$_CB_framework->pluginClassUrl( $this->_gjPlugin->element, true, array( 'action' => 'categories', 'func' => 'show', 'id' => (int) $row->get( 'id' ) ) );
				$extras					=	array(	'[id]'			=>	$row->get( 'id' ),
													'[name]'		=>	CBTxt::T( $row->get( 'name' ) ),
													'[description]'	=>	CBTxt::T( $row->get( 'description' ) ),
													'[logo]'		=>	$row->logo( true, false, true ),
													'[canvas]'		=>	$row->canvas( true ),
													'[url]'			=>	$url
											);

				$result					=	new stdClass();
				$result->href			=	$url;
				$result->title			=	CBTxt::T( 'CATEGORY_SEARCH_TITLE', $resultTitle, $extras );
				$result->text			=	CBTxt::T( 'CATEGORY_SEARCH_TEXT', $resultText, $extras );
				$result->created		=	null;
				$result->browsernav		=	$resultsLinks;
				$result->section		=	0;

				$results[]				=	$result;
			}
		}

		if ( $this->getGroupSearching() ) {
			$resultTitle				=	$this->params->get( 'results_group_title', '[name]' );
			$resultText					=	$this->params->get( 'results_group_text', '[description]' );
			$resultsLimit				=	(int) $this->params->get( 'results_group_limit', 50 );
			$resultsLinks				=	(int) $this->params->get( 'results_group_link', 0 );

			switch( $phrase ) {
				case 'exact':
					$where				=	"\n AND ( g." . $_CB_database->NameQuote( 'name' ) . " = " . $_CB_database->Quote( $text )
										.	" OR g." . $_CB_database->NameQuote( 'description' ) . " = " . $_CB_database->Quote( $text ) . " )";
					break;
				case 'any':
				case 'all':
				default:
					$words				=	explode( ' ', $text );
					$search				=	array();

					foreach ( $words as $word ) {
						$search[]		=	"( g." . $_CB_database->NameQuote( 'name' ) . " LIKE " . $_CB_database->Quote( '%' . $_CB_database->getEscaped( $word, true ) . '%', false )
										.	" OR g." . $_CB_database->NameQuote( 'description' ) . " LIKE " . $_CB_database->Quote( '%' . $_CB_database->getEscaped( $word, true ) . '%', false ) . " )";
					}

					$where				=	"\n AND ( " . implode( ( $phrase == 'any' ? " OR " : " AND " ), $search ) . " )";
					break;
			}

			switch( $ordering ) {
				case 'oldest':
					$orderBy			=	'g.' . $_CB_database->NameQuote( 'date' ) . ' ASC';
					break;
				case 'popular':
					$orderBy			=	$_CB_database->NameQuote( '_users' ) . ' DESC';
					break;
				case 'alpha':
					$orderBy			=	'g.' . $_CB_database->NameQuote( 'name' ) . ' ASC';
					break;
				case 'category':
					$orderBy			=	'c.' . $_CB_database->NameQuote( 'ordering' ) . ' ASC';
					break;
				case 'newest':
				default:
					$orderBy			=	'g.' . $_CB_database->NameQuote( 'date' ) . ' DESC';
					break;
			}

			$users						=	null;

			if ( $ordering == 'popular' ) {
				$users					=	'SELECT COUNT(*)'
										.	"\n FROM " . $_CB_database->NameQuote( '#__groupjive_users' ) . " AS uc"
										.	"\n LEFT JOIN " . $_CB_database->NameQuote( '#__comprofiler' ) . " AS uccb"
										.	' ON uccb.' . $_CB_database->NameQuote( 'id' ) . ' = uc.' . $_CB_database->NameQuote( 'user_id' )
										.	"\n LEFT JOIN " . $_CB_database->NameQuote( '#__users' ) . " AS ucj"
										.	' ON ucj.' . $_CB_database->NameQuote( 'id' ) . ' = uccb.' . $_CB_database->NameQuote( 'id' )
										.	"\n WHERE uc." . $_CB_database->NameQuote( 'group' ) . " = g." . $_CB_database->NameQuote( 'id' )
										.	"\n AND uccb." . $_CB_database->NameQuote( 'approved' ) . " = 1"
										.	"\n AND uccb." . $_CB_database->NameQuote( 'confirmed' ) . " = 1"
										.	"\n AND ucj." . $_CB_database->NameQuote( 'block' ) . " = 0";

				if ( ! $isModerator ) {
					$users				.=	"\n AND ( g." . $_CB_database->NameQuote( 'user_id' ) . " = " . (int) $user->get( 'id' )
										.		' OR u.' . $_CB_database->NameQuote( 'status' ) . ' >= 2'
										.		' OR uc.' . $_CB_database->NameQuote( 'status' ) . ' >= 1 )';
				}

				if ( ! $this->_gjParams->get( 'groups_users_owner', 1 ) ) {
					$users				.=	"\n AND uc." . $_CB_database->NameQuote( 'status' ) . " != 4";
				}
			}

			$query						=	'SELECT g.*'
										.	', c.' . $_CB_database->NameQuote( 'name' ) . ' AS _category_name'
										.	( $ordering == 'popular' ? ', ( ' . $users . ' ) AS _users' : null )
										.	"\n FROM " . $_CB_database->NameQuote( '#__groupjive_groups' ) . " AS g"
										.	"\n LEFT JOIN " . $_CB_database->NameQuote( '#__comprofiler' ) . " AS cb"
										.	' ON cb.' . $_CB_database->NameQuote( 'id' ) . ' = g.' . $_CB_database->NameQuote( 'user_id' )
										.	"\n LEFT JOIN " . $_CB_database->NameQuote( '#__users' ) . " AS j"
										.	' ON j.' . $_CB_database->NameQuote( 'id' ) . ' = cb.' . $_CB_database->NameQuote( 'id' )
										.	"\n LEFT JOIN " . $_CB_database->NameQuote( '#__groupjive_categories' ) . " AS c"
										.	' ON c.' . $_CB_database->NameQuote( 'id' ) . ' = g.' . $_CB_database->NameQuote( 'category' )
										.	"\n LEFT JOIN " . $_CB_database->NameQuote( '#__groupjive_users' ) . " AS u"
										.	' ON u.' . $_CB_database->NameQuote( 'user_id' ) . ' = ' . (int) $user->get( 'id' )
										.	' AND u.' . $_CB_database->NameQuote( 'group' ) . ' = g.' . $_CB_database->NameQuote( 'id' )
										.	"\n LEFT JOIN " . $_CB_database->NameQuote( '#__groupjive_invites' ) . " AS i"
										.	' ON i.' . $_CB_database->NameQuote( 'group' ) . ' = g.' . $_CB_database->NameQuote( 'id' )
										.	' AND i.' . $_CB_database->NameQuote( 'accepted' ) . ' = ' . $_CB_database->Quote( '0000-00-00 00:00:00' )
										.	' AND ( ( i.' . $_CB_database->NameQuote( 'email' ) . ' = ' . $_CB_database->Quote( $user->get( 'email' ) )
										.	' AND i.' . $_CB_database->NameQuote( 'email' ) . ' != "" )'
										.	' OR ( i.' . $_CB_database->NameQuote( 'user' ) . ' = ' . (int) $user->get( 'id' )
										.	' AND i.' . $_CB_database->NameQuote( 'user' ) . ' > 0 ) )'
										.	"\n WHERE cb." . $_CB_database->NameQuote( 'approved' ) . " = 1"
										.	"\n AND cb." . $_CB_database->NameQuote( 'confirmed' ) . " = 1"
										.	"\n AND j." . $_CB_database->NameQuote( 'block' ) . " = 0";

			if ( ! $isModerator ) {
				$query				.=	"\n AND ( g." . $_CB_database->NameQuote( 'user_id' ) . " = " . (int) $user->get( 'id' )
									.		' OR ( g.' . $_CB_database->NameQuote( 'published' ) . ' = 1'
									.		' AND ( g.' . $_CB_database->NameQuote( 'type' ) . ' IN ( 1, 2 )'
									.		' OR u.' . $_CB_database->NameQuote( 'status' ) . ' IN ( 0, 1, 2, 3 )'
									.		' OR i.' . $_CB_database->NameQuote( 'id' ) . ' IS NOT NULL ) ) )'
									.	"\n AND ( ( c." . $_CB_database->NameQuote( 'published' ) . " = 1"
									.		' AND c.' . $_CB_database->NameQuote( 'access' ) . ' IN ' . $_CB_database->safeArrayOfIntegers( CBGroupJive::getAccess( (int) $user->get( 'id' ) ) ) . ' )'
									.		( $this->_gjParams->get( 'groups_uncategorized', 1 ) ? ' OR g.' . $_CB_database->NameQuote( 'category' ) . ' = 0 )' : ' )' );
			}

			$query					.=	$where
									.	( $excludeCategories ? "\n AND c." . $_CB_database->NameQuote( 'id' ) . " NOT IN " . $_CB_database->safeArrayOfIntegers( $excludeCategories ) : null )
									.	( $excludeGroups ? "\n AND g." . $_CB_database->NameQuote( 'id' ) . " NOT IN " . $_CB_database->safeArrayOfIntegers( $excludeGroups ) : null )
									.	"\n ORDER BY " . $orderBy;
			if ( $resultsLimit ) {
				$_CB_database->setQuery( $query, 0, $resultsLimit );
			} else {
				$_CB_database->setQuery( $query );
			}
			$rows					=	$_CB_database->loadObjectList( null, '\CB\Plugin\GroupJive\Table\GroupTable', array( $_CB_database ) );

			/** @var GroupTable[] $rows */
			foreach ( $rows as $row ) {
				$url					=	$_CB_framework->pluginClassUrl( $this->_gjPlugin->element, true, array( 'action' => 'groups', 'func' => 'show', 'id' => (int) $row->get( 'id' ) ) );
				$extras					=	array(	'[id]'			=>	$row->get( 'id' ),
													'[name]'		=>	CBTxt::T( $row->get( 'name' ) ),
													'[description]'	=>	CBTxt::T( $row->get( 'description' ) ),
													'[logo]'		=>	$row->logo( true, false, true ),
													'[canvas]'		=>	$row->canvas( true ),
													'[url]'			=>	$url,
													'[date]'		=>	cbFormatDate( $row->get( 'date' ) )
											);

				$result					=	new stdClass();
				$result->href			=	$url;
				$result->title			=	CBTxt::T( 'GROUP_SEARCH_TITLE', $resultTitle, $extras );
				$result->text			=	CBTxt::T( 'GROUP_SEARCH_TEXT', $resultText, $extras );
				$result->created		=	$row->get( 'date' );
				$result->browsernav		=	$resultsLinks;
				$result->section		=	0;

				$results[]				=	$result;
			}
		}

		return $results;
	}
 /**
  * Sends a PM notification
  *
  * @param cbmypmsproTable $pm
  * @param null|string     $message
  */
 private function sendNotification($pm, $message = null)
 {
     if (!$pm->get('id')) {
         return;
     }
     $itemId = uddeIMgetItemid($this->uddeIMConfigRAW);
     if (!uddeIMexistsEMN($pm->get('toid'))) {
         uddeIMinsertEMNdefaults($pm->get('toid'), $this->uddeIMConfigRAW);
     }
     $emailNotify = $this->uddeIMConfig->get('allowemailnotify', 0);
     $isModerated = uddeIMgetEMNmoderated($pm->get('fromid'));
     $isReply = stristr($pm->get('message'), $this->uddeIMConfig->get('quotedivider'), '__________');
     $isOnline = uddeIMisOnline($pm->get('toid'));
     // Strip the html and bbcode as uddeim supports neither in its notification:
     $message = strip_tags(uddeIMbbcode_strip($message ? $message : $pm->get('message'), $this->uddeIMConfigRAW));
     if (!$isModerated) {
         if ($emailNotify == 1 || $emailNotify == 2 && Application::User($pm->get('toid'))->isSuperAdmin()) {
             $status = uddeIMgetEMNstatus($pm->get('toid'));
             if ($status == 1 || $status == 2 && !$isOnline || $status == 10 && !$isReply || $status == 20 && !$isOnline && !$isReply) {
                 uddeIMdispatchEMN($pm->get('id'), $itemId, 0, $pm->get('fromid'), $pm->get('toid'), $message, 0, $this->uddeIMConfigRAW);
             }
         }
     }
 }
 /**
  * @param ListTable     $row
  * @param UserTable[]   $users
  * @param array         $columns
  * @param FieldTable[]  $fields
  * @param array         $input
  * @param string|null   $search
  * @param int           $searchmode
  * @param cbPageNav     $pageNav
  * @param UserTable     $myUser
  * @param FieldTable[]  $searchableFields
  * @param stdClass      $searchValues
  * @param cbTabs        $tabs
  * @param string|null   $errorMsg
  * @param bool          $listAll
  * @param int           $random
  */
 static function usersList(&$row, &$users, &$columns, &$fields, &$input, $search, $searchmode, $pageNav, &$myUser, &$searchableFields, &$searchValues, &$tabs, $errorMsg, $listAll = true, $random = 0)
 {
     global $_CB_framework, $_PLUGINS, $_POST, $_GET, $_REQUEST;
     $params = new Registry($row->params);
     // The Itemid for this userlist; kept for trigger B/C:
     $Itemid = getCBprofileItemid(null, 'userslist', '&listid=' . (int) $row->listid);
     $results = $_PLUGINS->trigger('onBeforeDisplayUsersList', array(&$row, &$users, &$columns, &$fields, &$input, $row->listid, &$search, &$Itemid, 1));
     // $uid = 1
     // Plugin content divided by location:
     $pluginAdditions = array('search', 'header', 'footer');
     $pluginAdditions['search'] = array();
     $pluginAdditions['header'] = array();
     $pluginAdditions['footer'] = array();
     if (is_array($results) && count($results) > 0) {
         foreach ($results as $res) {
             if (is_array($res)) {
                 foreach ($res as $k => $v) {
                     $pluginAdditions[$k][] = $v;
                 }
             }
         }
     }
     outputCbTemplate(1);
     outputCbJs();
     cbValidator::loadValidation();
     $cbTemplate = HTML_comprofiler::_cbTemplateLoad();
     if ($errorMsg) {
         $_CB_framework->enqueueMessage($errorMsg, 'error');
     }
     // Page title and pathway:
     $listTitleHtml = cbReplaceVars($row->title, $myUser);
     $listTitleNoHtml = strip_tags(cbReplaceVars($row->title, $myUser, false, false));
     $listDescription = cbReplaceVars($row->description, $myUser);
     $_CB_framework->setPageTitle($listTitleNoHtml);
     $_CB_framework->appendPathWay($listTitleHtml);
     // Add row click JS:
     if ($params->get('allow_profilelink', 1)) {
         $allowProfileLink = true;
     } else {
         $allowProfileLink = false;
     }
     $js = "var cbUserURLs = [];";
     if (is_array($users) && $allowProfileLink) {
         // Ensures the jQuery array index matches the same as HTML ID index (e.g. cbU0, cbU1):
         $index = 0;
         foreach ($users as $user) {
             $js .= "cbUserURLs[{$index}] = '" . addslashes($_CB_framework->userProfileUrl((int) $user->id, false)) . "';";
             $index++;
         }
     }
     $js .= "\$( '.cbUserListRow' ).click( function( e ) {" . "if ( ! ( \$( e.target ).is( 'a' ) || ( \$( e.target ).is( 'img' ) && \$( e.target ).parent().is( 'a' ) ) || \$( e.target ).hasClass( 'cbClicksInside' ) || ( \$( e.target ).parents( '.cbClicksInside' ).length > 0 ) || ( \$( this ).attr( 'id' ) == '' ) ) ) {" . "var index = \$( this ).prop( 'id' ).substr( 3 );";
     if ($allowProfileLink) {
         $js .= "window.location = cbUserURLs[index];";
     }
     $js .= "return false;" . "}" . "});";
     $_CB_framework->outputCbJQuery($js);
     // Search JS:
     $isSearching = $search !== null;
     if ($isSearching && $params->get('list_search_collapse', 0) && !in_array($searchmode, array(1, 2))) {
         $isCollapsed = true;
     } else {
         $isCollapsed = false;
     }
     if (count($searchableFields) > 0) {
         cbUsersList::outputAdvancedSearchJs($isCollapsed ? null : $search);
     }
     // Base form URL:
     $baseUrl = $_CB_framework->rawViewUrl('userslist', true, array('listid' => (int) $row->listid, 'searchmode' => 0), 'html', 0, '&listid=' . (int) $row->listid);
     // Searching attributes:
     $showAll = $search === null;
     $criteriaTitle = cbReplaceVars(CBTxt::Th('UE_SEARCH_CRITERIA', 'Search criteria'), $myUser);
     if ($searchmode == 0 || $searchmode == 1 && count(get_object_vars($searchValues)) || $searchmode == 2) {
         $resultsTitle = cbReplaceVars(CBTxt::Th('UE_SEARCH_RESULTS', 'Search results'), $myUser);
     } else {
         $resultsTitle = null;
     }
     // Search content:
     $searchTabContent = $tabs->getSearchableContents($searchableFields, $myUser, $searchValues, $params->get('list_compare_types', 0));
     if (count($pluginAdditions['search'])) {
         $searchTabContent .= '<div class="cbUserListSearchPlugins">' . '<div>' . implode('</div><div>', $pluginAdditions['search']) . '</div>' . '</div>';
     }
     // User row content:
     $tableContent =& HTML_comprofiler::_getListTableContent($users, $columns, $fields);
     if ($params->get('list_grid_layout', 0)) {
         $layout = 'grid';
     } else {
         $layout = 'list';
     }
     $gridHeight = (int) $params->get('list_grid_height', 200);
     $gridWidth = (int) $params->get('list_grid_width', 200);
     if ($params->get('list_show_selector', 1)) {
         $listSelector = true;
     } else {
         $listSelector = false;
     }
     $pageClass = $_CB_framework->getMenuPageClass();
     $return = '<div class="cbUsersList cb_template cb_template_' . selectTemplate('dir') . ($pageClass ? ' ' . htmlspecialchars($pageClass) : null) . '">' . '<form action="' . $_CB_framework->rawViewUrl('userslist', true, array('listid' => (int) $row->listid), 'html', 0, '&listid=' . (int) $row->listid) . '" method="get" id="adminForm" name="adminForm" class="cb_form form-auto cbValidation">' . '<input type="hidden" name="option" value="com_comprofiler" />' . '<input type="hidden" name="view" value="userslist" />' . (!$listSelector ? '<input type="hidden" name="listid" value="' . (int) $row->listid . '" />' : null) . '<input type="hidden" name="Itemid" value="' . (int) $Itemid . '" />' . '<input type="hidden" name="limitstart" value="0" />' . '<input type="hidden" name="searchmode" value="' . (int) $searchmode . '" />' . '<input type="hidden" name="search" value="" />' . ($random ? '<input type="hidden" name="rand" value="' . (int) $random . '" />' : null) . cbGetSpoofInputTag('userslist') . $_PLUGINS->callTemplate($cbTemplate, 'List', 'drawListHead', array(&$input, $row->listid, $pageNav->total, $showAll, $searchTabContent, $isSearching, $baseUrl, $listTitleHtml, $listDescription, $criteriaTitle, $resultsTitle, $listAll, $listSelector, $isCollapsed, $searchmode), 'html');
     if ($searchmode == 0 || $searchmode == 1 && count(get_object_vars($searchValues)) || $searchmode == 2) {
         $canPage = $params->get('list_paging', 1) && ($pageNav->limitstart != 0 || $pageNav->limit <= $pageNav->total);
         if (count($pluginAdditions['header'])) {
             $return .= '<div class="cbUserListHeader">' . '<div>' . implode('</div><div>', $pluginAdditions['header']) . '</div>' . '</div>';
         }
         $return .= $_PLUGINS->callTemplate($cbTemplate, 'List', 'drawListBody', array(&$users, &$columns, &$tableContent, $row->listid, $allowProfileLink, $layout, $gridHeight, $gridWidth, $searchmode), 'html');
         if ($canPage) {
             $return .= '<div class="cbUserListPagination cbUserListPaginationBottom text-center">' . $pageNav->getListLinks() . '</div>';
         }
         if (count($pluginAdditions['footer'])) {
             $return .= '<div class="cbUserListFooter">' . '<div>' . implode('</div><div>', $pluginAdditions['footer']) . '</div>' . '</div>';
         }
     }
     $return .= '</form>' . '</div>' . cbPoweredBy();
     echo $return;
     $_CB_framework->setMenuMeta();
 }
Example #28
-1
 /**
  * Draws Users list (ECHO)
  *
  * @param  int      $userId
  * @param  int      $listId
  * @param  array    $postData
  * @return void
  */
 public function drawUsersList($userId, $listId, $postData)
 {
     global $_CB_database, $_PLUGINS;
     $_PLUGINS->loadPluginGroup('user');
     $searchData = cbGetParam($postData, 'search');
     $limitstart = (int) cbGetParam($postData, 'limitstart');
     $searchMode = (int) cbGetParam($postData, 'searchmode', 0);
     $random = (int) cbGetParam($postData, 'rand', 0);
     $cbUser = CBuser::getInstance((int) $userId, false);
     $user = $cbUser->getUserData();
     $search = null;
     $input = array();
     $publishedLists = array();
     $query = 'SELECT *' . "\n FROM " . $_CB_database->NameQuote('#__comprofiler_lists') . "\n WHERE " . $_CB_database->NameQuote('published') . " = 1" . "\n AND " . $_CB_database->NameQuote('viewaccesslevel') . " IN " . $_CB_database->safeArrayOfIntegers(Application::MyUser()->getAuthorisedViewLevels()) . "\n ORDER BY " . $_CB_database->NameQuote('ordering');
     $_CB_database->setQuery($query);
     /** @var ListTable[] $userLists */
     $userLists = $_CB_database->loadObjectList(null, '\\CB\\Database\\Table\\ListTable', array($_CB_database));
     if ($userLists) {
         foreach ($userLists as $userList) {
             $publishedLists[] = moscomprofilerHTML::makeOption((int) $userList->listid, strip_tags($cbUser->replaceUserVars($userList->title, false, false)));
             if (!$listId && $userList->default) {
                 $listId = (int) $userList->listid;
             }
         }
         if (!$listId) {
             $listId = (int) $userLists[0]->listid;
         }
     }
     if (!$listId) {
         echo CBTxt::Th('UE_NOLISTFOUND', 'There are no published user lists!');
         return;
     }
     if ($userLists) {
         $input['plists'] = moscomprofilerHTML::selectList($publishedLists, 'listid', 'class="form-control input-block" onchange="this.form.submit();"', 'value', 'text', (int) $listId, 1);
     }
     $row = self::getInstance((int) $listId);
     if (!$row) {
         echo CBTxt::Th('UE_LIST_DOES_NOT_EXIST', 'This list does not exist');
         return;
     }
     if (!$cbUser->authoriseView('userslist', $row->listid)) {
         echo CBTxt::Th('UE_NOT_AUTHORIZED', 'You are not authorized to view this page!');
         return;
     }
     $params = new Registry($row->params);
     if ($params->get('hotlink_protection', 0) == 1) {
         if ($searchData !== null || $limitstart) {
             cbSpoofCheck('userslist', 'GET');
         }
     }
     $limit = (int) $params->get('list_limit', 30);
     if (!$limit) {
         $limit = 30;
     }
     if ($params->get('list_paging', 1) != 1) {
         $limitstart = 0;
     }
     $isModerator = Application::MyUser()->isGlobalModerator();
     $_PLUGINS->trigger('onStartUsersList', array(&$listId, &$row, &$search, &$limitstart, &$limit));
     // Prepare query variables:
     $userGroupIds = explode('|*|', $row->usergroupids);
     $orderBy = self::getSorting($listId, $userId, $random);
     $filterBy = self::getFiltering($listId, $userId);
     $columns = self::getColumns($listId, $userId);
     // Grab all the fields the $user can access:
     $tabs = new cbTabs(0, 1);
     $fields = $tabs->_getTabFieldsDb(null, $user, 'list');
     // Build the field SQL:
     $tableReferences = array('#__comprofiler' => 'ue', '#__users' => 'u');
     $searchableFields = array();
     $fieldsSQL = cbUsersList::getFieldsSQL($columns, $fields, $tableReferences, $searchableFields, $params);
     $_PLUGINS->trigger('onAfterUsersListFieldsSql', array(&$columns, &$fields, &$tableReferences));
     // Build the internal joins and where statements best off list parameters:
     $tablesSQL = array();
     $joinsSQL = array();
     $tablesWhereSQL = array();
     if ($isModerator) {
         if (!$params->get('list_show_blocked', 0)) {
             $tablesWhereSQL['block'] = 'u.block = 0';
         }
         if (!$params->get('list_show_banned', 1)) {
             $tablesWhereSQL['banned'] = 'ue.banned = 0';
         }
         if (!$params->get('list_show_unapproved', 0)) {
             $tablesWhereSQL['approved'] = 'ue.approved = 1';
         }
         if (!$params->get('list_show_unconfirmed', 0)) {
             $tablesWhereSQL['confirmed'] = 'ue.confirmed = 1';
         }
     } else {
         $tablesWhereSQL = array('block' => 'u.block = 0', 'approved' => 'ue.approved = 1', 'confirmed' => 'ue.confirmed = 1', 'banned' => 'ue.banned = 0');
     }
     $joinsSQL[] = 'JOIN #__user_usergroup_map g ON g.`user_id` = u.`id`';
     if ($userGroupIds) {
         $tablesWhereSQL['gid'] = 'g.group_id IN ' . $_CB_database->safeArrayOfIntegers($userGroupIds);
     }
     foreach ($tableReferences as $table => $name) {
         if ($name == 'u') {
             $tablesSQL[] = $table . ' ' . $name;
         } else {
             $joinsSQL[] = 'JOIN ' . $table . ' ' . $name . ' ON ' . $name . '.`id` = u.`id`';
         }
     }
     // Build the search criteria:
     $searchValues = new stdClass();
     $searchesFromFields = $tabs->applySearchableContents($searchableFields, $searchValues, $postData, $params->get('list_compare_types', 0));
     $whereFields = $searchesFromFields->reduceSqlFormula($tableReferences, $joinsSQL, true);
     if ($whereFields) {
         $tablesWhereSQL[] = '(' . $whereFields . ')';
     }
     $_PLUGINS->trigger('onBeforeUsersListBuildQuery', array(&$tablesSQL, &$joinsSQL, &$tablesWhereSQL));
     // Construct the FROM and WHERE for the userlist query:
     $queryFrom = "FROM " . implode(', ', $tablesSQL) . (count($joinsSQL) ? "\n " . implode("\n ", $joinsSQL) : '') . "\n WHERE " . implode("\n AND ", $tablesWhereSQL) . " " . $filterBy;
     $_PLUGINS->trigger('onBeforeUsersListQuery', array(&$queryFrom, 1, $listId));
     // $ui = 1 (frontend)
     $errorMsg = null;
     // Checks if the list is being actively searched and it allows searching; otherwise reset back to normal:
     $searchCount = count(get_object_vars($searchValues));
     if ($params->get('list_search', 1) > 0 && $params->get('list_search_empty', 0) && !$searchCount) {
         $searchMode = 1;
         $listAll = false;
     } else {
         $listAll = $searchCount ? true : false;
     }
     if ($searchMode == 0 || $searchMode == 1 && $searchCount || $searchMode == 2) {
         // Prepare the userlist count query for pagination:
         $_CB_database->setQuery("SELECT COUNT( DISTINCT u.id ) " . $queryFrom);
         $total = $_CB_database->loadResult();
         if ($limit > $total || $limitstart >= $total) {
             $limitstart = 0;
         }
         // Prepare the actual userlist query to build a list of users:
         $query = "SELECT DISTINCT ue.*, u.*, '' AS 'NA' " . ($fieldsSQL ? ", " . $fieldsSQL . " " : '') . $queryFrom . " " . $orderBy;
         $_CB_database->setQuery($query, (int) $limitstart, (int) $limit);
         /** @var UserTable[] $users */
         $users = $_CB_database->loadObjectList(null, '\\CB\\Database\\Table\\UserTable', array($_CB_database));
         if (!$_CB_database->getErrorNum()) {
             $profileLink = $params->get('allow_profilelink', 1);
             // If users exist lets cache them and disable profile linking if necessary:
             if ($users) {
                 foreach (array_keys($users) as $k) {
                     // Add this user to cache:
                     CBuser::setUserGetCBUserInstance($users[$k]);
                     if (!$profileLink) {
                         $users[$k]->set('_allowProfileLink', 0);
                     }
                 }
             }
         } else {
             $errorMsg = CBTxt::T('UE_ERROR_IN_QUERY_TURN_SITE_DEBUG_ON_TO_VIEW', 'There is an error in the database query. Site admin can turn site debug to on to view and fix the query.');
         }
         if ($searchCount) {
             $search = '';
         } else {
             $search = null;
         }
         if ($search === null && ($searchMode == 1 && $searchCount || $searchMode == 2)) {
             $search = '';
         }
     } else {
         $total = 0;
         $users = array();
         if ($search === null) {
             $search = '';
         }
     }
     $pageNav = new cbPageNav($total, $limitstart, $limit);
     HTML_comprofiler::usersList($row, $users, $columns, $fields, $input, $search, $searchMode, $pageNav, $user, $searchableFields, $searchValues, $tabs, $errorMsg, $listAll, $random);
 }