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();
}
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_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_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();
}
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();
}
/**
 * Commented CBT calls for language parser pickup: Moved to cb.core.php so they get picked-up in front-end language file and not in backend one.
 */
function loadSampleData()
{
    global $_CB_Backend_Title;
    @set_time_limit(240);
    $_CB_Backend_Title = array(0 => array('fa fa-wrench', CBTxt::T('TOOLS_SAMPLE_DATA_TITLE', 'CB Tools: Sample Data: Results')));
    $return = null;
    $affected = false;
    $tab = new TabTable();
    $tab->load(array('title' => '_UE_ADDITIONAL_INFO_HEADER'));
    if (!$tab->tabid) {
        $affected = true;
        $tab->set('title', '_UE_ADDITIONAL_INFO_HEADER');
        $tab->set('displaytype', 'menunested');
        $tab->set('position', 'canvas_main_middle');
        $tab->set('viewaccesslevel', 1);
        $tab->set('enabled', 1);
        $tab->set('ordering', 1);
        if ($tab->getError() || !$tab->store()) {
            $return .= '<div class="form-group cb_form_line clearfix text-danger">' . CBTxt::T('TOOLS_SAMPLE_DATA_TAB_NOT_OK', 'Tab [title] failed to add. Error: [error]', array('[title]' => $tab->get('title'), '[error]' => $tab->getError())) . '</div>';
        }
    }
    if ($affected) {
        $return .= '<div class="form-group cb_form_line clearfix text-success">' . CBTxt::T('TOOLS_SAMPLE_DATA_TAB_OK', 'Tab Added Successfully!') . '</div>';
    }
    $affected = false;
    $fields = array('cb_website' => array('title' => '_UE_Website', 'type' => 'webaddress', 'registration' => 0, 'ordering' => 1), 'cb_location' => array('title' => '_UE_Location', 'type' => 'text', 'maxlength' => 50, 'size' => 25, 'registration' => 0, 'ordering' => 2), 'cb_occupation' => array('title' => '_UE_Occupation', 'type' => 'text', 'registration' => 0, 'ordering' => 3), 'cb_interests' => array('title' => '_UE_Interests', 'type' => 'text', 'registration' => 0, 'ordering' => 4), 'cb_company' => array('title' => '_UE_Company', 'type' => 'text', 'ordering' => 5), 'cb_city' => array('title' => '_UE_City', 'type' => 'text', 'ordering' => 6), 'cb_state' => array('title' => '_UE_State', 'type' => 'text', 'maxlength' => 10, 'size' => 4, 'ordering' => 7), 'cb_zipcode' => array('title' => '_UE_ZipCode', 'type' => 'text', 'ordering' => 8), 'cb_country' => array('title' => '_UE_Country', 'type' => 'text', 'ordering' => 9), 'cb_address' => array('title' => '_UE_Address', 'type' => 'text', 'ordering' => 10), 'cb_phone' => array('title' => '_UE_PHONE', 'type' => 'text', 'ordering' => 11), 'cb_fax' => array('title' => '_UE_FAX', 'type' => 'text', 'ordering' => 12));
    foreach ($fields as $fieldName => $fieldSettings) {
        $field = new FieldTable();
        $field->load(array('name' => $fieldName));
        if (!$field->fieldid) {
            $affected = true;
            $field->set('name', $fieldName);
            $field->set('registration', 1);
            $field->set('profile', 1);
            $field->set('edit', 1);
            $field->set('published', 1);
            foreach ($fieldSettings as $column => $value) {
                $field->set($column, $value);
            }
            $field->set('tabid', $tab->tabid);
            $field->set('pluginid', 1);
            if ($field->getError() || !$field->store()) {
                $return .= '<div class="form-group cb_form_line clearfix text-danger">' . CBTxt::T('TOOLS_SAMPLE_DATA_FIELD_NOT_OK', 'Field [name] failed to add. Error: [error]', array('[name]' => $field->get('name'), '[error]' => $field->getError())) . '</div>';
            }
        }
    }
    if ($affected) {
        $return .= '<div class="form-group cb_form_line clearfix text-success">' . CBTxt::T('TOOLS_SAMPLE_DATA_FIELD_OK', 'Fields Added Successfully!') . '</div>';
    }
    $affected = false;
    $list = new ListTable();
    $list->load(array('title' => 'Members List'));
    if (!$list->listid) {
        $affected = true;
        $list->set('title', 'Members List');
        $list->set('viewaccesslevel', 1);
        $list->set('usergroupids', '1|*|6|*|7|*|2|*|3|*|4|*|5|*|8');
        $list->set('default', 1);
        $list->set('published', 1);
        $list->set('ordering', 1);
        $listParams = new Registry();
        $listParams->set('sort_mode', '0');
        $listParams->set('basic_sort', array(array('column' => 'username', 'direction' => 'ASC')));
        $listParams->set('columns', array(array('title' => 'User', 'size' => '3', 'fields' => array(array('field' => '17', 'display' => '4'), array('field' => '29', 'display' => '4'), array('field' => '42', 'display' => '4'), array('field' => '26', 'display' => '4'))), array('title' => 'Info', 'size' => '9', 'fields' => array(array('field' => '27', 'display' => '1'), array('field' => '49', 'display' => '1'), array('field' => '28', 'display' => '1')))));
        $listParams->set('list_grid_layout', '1');
        $list->set('params', $listParams->asJson());
        if ($list->getError() || !$list->store()) {
            $return .= '<div class="form-group cb_form_line clearfix text-danger">' . CBTxt::T('TOOLS_SAMPLE_DATA_LIST_NOT_OK', 'List [title] failed to add. Error: [error]', array('[title]' => $list->get('title'), '[error]' => $tab->getError())) . '</div>';
        }
    }
    if ($affected) {
        $return .= '<div class="form-group cb_form_line clearfix text-success">' . CBTxt::T('TOOLS_SAMPLE_DATA_LIST_OK', 'List Added Successfully!') . '</div>';
    }
    if (!$return) {
        $return .= '<div class="form-group cb_form_line clearfix">' . CBTxt::T('TOOLS_SAMPLE_DATA_ALREADY_CONFIGURED', 'Sample Data is already loaded!') . '</div>';
    }
    echo $return;
}
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();
				}
			}
		}
	}
}
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' );
	}
}
function plug_cbgallery_install()
{
	global $_CB_framework, $_CB_database;

	$plugin								=	new PluginTable();

	if ( $plugin->load( array( 'element' => 'cb.profilegallery' ) ) ) {
		$path							=	$_CB_framework->getCfg( 'absolute_path' );
		$indexPath						=	$path . '/components/com_comprofiler/plugin/user/plug_cbgallery/index.html';
		$oldFilesPath					=	$path . '/images/comprofiler/plug_profilegallery';
		$newFilesPath					=	$path . '/images/comprofiler/plug_cbgallery';

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

		/** @var $rows Table[] */
		foreach ( $rows as $row ) {
			$oldFilePath				=	$oldFilesPath . '/' . (int) $row->get( 'userid' );

			if ( in_array( $row->get( 'pgitemtype' ), array( 'jpg', 'jpeg', 'gif', 'png' ) ) ) {
				$type					=	'photos';
			} else {
				$type					=	'files';
			}

			$newFilePath				=	$newFilesPath . '/' . (int) $row->get( 'userid' ) . '/' . $type;

			if ( ( ! file_exists( $oldFilePath . '/' . $row->get( 'pgitemfilename' ) ) ) || ( ( $type == 'photos' ) && ( ! file_exists( $oldFilePath . '/tn' . $row->get( 'pgitemfilename' ) ) ) ) ) {
				continue;
			}

			$cleanFileName				=	str_replace( 'pg_', '', pathinfo( $row->get( 'pgitemfilename' ), PATHINFO_FILENAME ) );
			$newFileName				=	uniqid( $cleanFileName . '_' ) . '.' . strtolower( pathinfo( $row->get( 'pgitemfilename' ), PATHINFO_EXTENSION ) );

			if ( cbReadDirectory( $newFilePath, '^' . preg_quote( $cleanFileName ) ) ) {
				$query					=	'SELECT COUNT(*)'
										.	"\n FROM " . $_CB_database->NameQuote( '#__comprofiler_plugin_gallery_items' )
										.	"\n WHERE " . $_CB_database->NameQuote( 'user_id' ) . " = " . (int) $row->get( 'userid' )
										.	"\n AND " . $_CB_database->NameQuote( 'value' ) . " LIKE " . $_CB_database->Quote( '%' . $_CB_database->getEscaped( $cleanFileName, true ) . '%', false );
				$_CB_database->setQuery( $query );
				if ( $_CB_database->loadResult() ) {
					continue;
				}
			}

			if ( ! is_dir( $newFilesPath ) ) {
				$oldMask				=	@umask( 0 );

				if ( @mkdir( $newFilesPath, 0755, true ) ) {
					@umask( $oldMask );
					@chmod( $newFilesPath, 0755 );

					if ( ! file_exists( $newFilesPath . '/index.html' ) ) {
						@copy( $indexPath, $newFilesPath . '/index.html' );
						@chmod( $newFilesPath . '/index.html', 0755 );
					}
				} else {
					@umask( $oldMask );
				}
			}

			if ( ! file_exists( $newFilesPath . '/.htaccess' ) ) {
				file_put_contents( $newFilesPath . '/.htaccess', 'deny from all' );
			}

			if ( ! is_dir( $newFilePath ) ) {
				$oldMask				=	@umask( 0 );

				if ( @mkdir( $newFilePath, 0755, true ) ) {
					@umask( $oldMask );
					@chmod( $newFilePath, 0755 );

					if ( ! file_exists( $newFilePath . '/index.html' ) ) {
						@copy( $indexPath, $newFilePath . '/index.html' );
						@chmod( $newFilePath . '/index.html', 0755 );
					}
				} else {
					@umask( $oldMask );
				}
			}

			if ( ! @copy( $oldFilePath . '/' . $row->get( 'pgitemfilename' ), $newFilePath . '/' . $newFileName ) ) {
				continue;
			} else {
				@chmod( $newFilePath . '/' . $newFileName, 0755 );
			}

			if ( $type == 'photos' ) {
				if ( ! @copy( $oldFilePath . '/tn' . $row->get( 'pgitemfilename' ), $newFilePath . '/tn' . $newFileName ) ) {
					continue;
				} else {
					@chmod( $newFilePath . '/tn' . $newFileName, 0755 );
				}
			}

			$item						=	new Table( null, '#__comprofiler_plugin_gallery_items', 'id' );

			$item->set( 'user_id', (int) $row->get( 'userid' ) );
			$item->set( 'type', $type );
			$item->set( 'value', $newFileName );
			$item->set( 'folder', 0 );
			$item->set( 'title', $row->get( 'pgitemtitle' ) );
			$item->set( 'description', $row->get( 'pgitemdescription' ) );
			$item->set( 'date', $row->get( 'pgitemdate' ) );
			$item->set( 'published', ( $row->get( 'pgitemapproved', 0 ) ? (int) $row->get( 'pgitempublished', 0 ) : -1 ) );

			if ( ! $item->store() ) {
				@unlink( $newFilePath . '/' . $newFileName );

				if ( $type == 'photos' ) {
					@unlink( $newFilePath . '/tn' . $newFileName );
				}
			}
		}

		$field							=	new FieldTable();

		if ( $field->load( array( 'name' => 'cb_pgtotalquotaitems' ) ) ) {
			$field->set( 'type', 'integer' );
			$field->set( 'tabid', 11 );
			$field->set( 'pluginid', 1 );
			$field->set( 'readonly', 1 );
			$field->set( 'calculated', 0 );
			$field->set( 'sys', 0 );

			$field->store();
		}

		$gallery						=	new PluginTable();

		if ( $gallery->load( array( 'element' => 'cbgallery' ) ) ) {
			$galleryParams				=	new Registry( $gallery->params );

			$galleryParams->set( 'photos_item_limit', 'cb_pgtotalquotaitems' );
			$galleryParams->set( 'files_item_limit', 'cb_pgtotalquotaitems' );

			$gallery->set( 'params', $galleryParams->asJson() );

			$gallery->store();
		}

		ob_start();
		$plgInstaller					=	new cbInstallerPlugin();

		$plgInstaller->uninstall( $plugin->id, 'com_comprofiler' );
		ob_end_clean();
	}
}
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;
}