/**
 * Installs CBSubs, final part (ECHOs banners)
 *
 * @return void
 */
function plug_cbpaidsubscriptions_install()
{
    global $_CB_framework, $_CB_database;
    $installedVersion = '4.0.0';
    //CBSUBS_VERSION_AUTOMATICALLY_SET_DO_NOT_EDIT!!!
    ?>
<div style="width:100%;text-align:center">

	<div>
		<img alt="CBSubs Logo" height="300" width="300" src="<?php 
    echo $_CB_framework->getCfg('live_site');
    ?>
/components/com_comprofiler/plugin/user/plug_cbpaidsubscriptions/icons/normal/cbsubs_logo_300.jpg" />
	</div>
	<h1>CBSubs <?php 
    echo $installedVersion;
    ?>
</h1>
    <p><strong>Copyright &copy; 2007-2015 and Trademark of Lightning MultiCom SA, Switzerland - www.joomlapolis.com - and its licensors, all rights reserved</strong></p>
    <p><strong>CBSubs is a Trademark of Lightning MultiCom SA, Switzerland, and its licensors. CB, Community Builder and Joomlapolis are also a trademark of joomlapolis.com and may not be used without permission from the trademark holders.</strong></p>
    <p>The copyright holders have spent massive time on this software and are continuing to improve it. A corresponding membership at Joomlapolis.com is required for ongoing maintenance and support.</p>
    <p>All copyright statements must be kept.</p> 
    <p><em>Official site: <a href="http://www.joomlapolis.com?pk_campaign=in-cb&amp;pk_kwd=installed-cbsubs">www.joomlapolis.com</a></em></p>
		
</div>

<?php 
    // Temporary fix in CBSubs 1.2.2 only for CBSubs 1.2.1 bug:
    if (checkJversion() >= 1 && $installedVersion == '1.2.2') {
        $sql = "UPDATE #__users" . " SET password = concat(md5(concat(password,'12345678901234567890123456789012')),':','12345678901234567890123456789012')" . " WHERE ( LENGTH(password) < 65 )" . " AND ( LENGTH(password) > 3 )" . " AND ( registerDate > '2011-07-13 12:00:00' )";
        $_CB_database->setQuery($sql);
        $_CB_database->query();
    }
    // Temporary fix in CBSubs 1.3.0 for CBSubs 1.2.x bug:
    // Ogone gateway was not transfering address from basket:
    $sql = 'UPDATE #__cbsubs_payments p' . ' LEFT JOIN #__cbsubs_payment_baskets b ON p.payment_basket_id = b.id' . ' SET ' . ' p.`address_street` = b.`address_street`,' . ' p.`address_city` = b.`address_city`,' . ' p.`address_state` = b.`address_state`,' . ' p.`address_zip` = b.`address_zip`,' . ' p.`address_country` = b.`address_country`,' . ' p.`address_country_code` = b.`address_country_code`,' . ' p.`payer_business_name` = b.`payer_business_name`,' . ' p.`payer_email` = b.`payer_email`,' . ' p.`contact_phone` = b.`contact_phone`,' . ' p.`vat_number` = b.`vat_number`' . " WHERE p.payment_method IN ('ogone','swisspostfinance')" . ' AND ISNULL(p.`address_country_code`);';
    $_CB_database->setQuery($sql);
    $_CB_database->query();
    cbimport('cb.adminfilesystem');
    $adminFS = cbAdminFileSystem::getInstance();
    $cbsubsDir = $_CB_framework->getCfg('absolute_path') . '/components/com_comprofiler/plugin/user/plug_cbpaidsubscriptions';
    // Remove old 2Checkout files if there is no 2Checkout gateway configured, as TwoCheckout is not part anymore in CBSubs 1.3:
    $sql = 'SELECT COUNT(*) FROM #__cbsubs_gateway_accounts' . ' WHERE gateway_type = "processors.twocheckout";';
    $_CB_database->setQuery($sql);
    $hasTwoCheckoutInstalled = $_CB_database->loadResult();
    $twocheckoutdir = $cbsubsDir . '/processors/twocheckout';
    if ($hasTwoCheckoutInstalled == 0 && file_exists($twocheckoutdir)) {
        $adminFS->deldir($twocheckoutdir . '/');
    }
    // Remove old 1.x and 2.x files:
    $oldfiles = array('admin.cbpaidsubscriptions.ctrl.php', 'cbpaidsubscriptions.condition.php', 'cbpaidsubscriptions.countries.php', 'cbpaidsubscriptions.crosstotalizer.php', 'cbpaidsubscriptions.ctrl.php', 'cbpaidsubscriptions.currency.php', 'cbpaidsubscriptions.gui.php', 'cbpaidsubscriptions.guisubs.php', 'cbpaidsubscriptions.importer.php', 'cbpaidsubscriptions.scheduler.php', 'cbpaidsubscriptions.sql.php', 'cbpaidsubscriptions.userparams.php');
    foreach ($oldfiles as $file) {
        $pathFile = $cbsubsDir . '/' . $file;
        if ($file && file_exists($pathFile)) {
            $adminFS->unlink($pathFile);
        }
    }
}
function finishInstallation($option)
{
    global $_CB_framework, $ueConfig, $task;
    // Try extending time, as unziping/ftping took already quite some... :
    @set_time_limit(240);
    _CBsecureAboveForm('finishInstallation');
    $tgzFile = $_CB_framework->getCfg('absolute_path') . '/administrator/components/com_comprofiler/pluginsfiles.tgz';
    $installerFile = $_CB_framework->getCfg('absolute_path') . '/administrator/components/com_comprofiler/';
    if (file_exists($installerFile . 'comprofiler.xml')) {
        $installerFile .= 'comprofiler.xml';
    } elseif (file_exists($installerFile . 'comprofilej.xml')) {
        $installerFile .= 'comprofilej.xml';
    } elseif (file_exists($installerFile . 'comprofileg.xml')) {
        $installerFile .= 'comprofileg.xml';
    }
    if (!file_exists($tgzFile)) {
        echo CBTxt::T('UE_NOT_AUTHORIZED', 'You are not authorized to view this page!');
        return;
    }
    $installer = new cbInstallerPlugin();
    $client = 2;
    // Check that the zlib is available
    if (!extension_loaded('zlib')) {
        cbInstaller::renderInstallMessage(CBTxt::T('The installer cannot continue before zlib is installed'), CBTxt::T('Installer - Error'), $installer->returnTo($option, $task, $client));
        return;
    }
    if (!$installer->upload($tgzFile, true, false)) {
        cbInstaller::renderInstallMessage(sprintf(CBTxt::T('Uncompressing %s failed.'), $tgzFile), CBTxt::T('Installer - Error'), $installer->returnTo($option, '', 2));
        return;
    }
    $adminFS = cbAdminFileSystem::getInstance();
    $installFrom = $installer->installDir();
    $filesList = cbReadDirectory($installFrom, '.', true);
    // check if core directories exist as are needed to install plugins:
    $baseDir = $_CB_framework->getCfg('absolute_path') . '/components/com_comprofiler';
    if (!$adminFS->is_dir($baseDir . '/plugin')) {
        if (!$adminFS->mkdir($baseDir . '/plugin')) {
            cbInstaller::renderInstallMessage(sprintf(CBTxt::T('Failed to create directory "%s"'), $baseDir . '/plugin'), CBTxt::T('Installer - Error'), $installer->returnTo($option, '', 2));
            return;
        }
        if (!$adminFS->copy($baseDir . '/index.html', $baseDir . '/plugin/index.html')) {
            cbInstaller::renderInstallMessage(sprintf(CBTxt::T('Failed to create index "%s"'), $baseDir . '/plugin/index.html'), CBTxt::T('Installer - Error'), $installer->returnTo($option, '', 2));
            return;
        }
    }
    if (!$adminFS->is_dir($baseDir . '/plugin/language')) {
        if (!$adminFS->mkdir($baseDir . '/plugin/language')) {
            cbInstaller::renderInstallMessage(sprintf(CBTxt::T('Failed to create directory "%s"'), $baseDir . '/plugin/language'), CBTxt::T('Installer - Error'), $installer->returnTo($option, '', 2));
            return;
        }
        if (!$adminFS->copy($baseDir . '/index.html', $baseDir . '/plugin/language/index.html')) {
            cbInstaller::renderInstallMessage(sprintf(CBTxt::T('Failed to create index "%s"'), $baseDir . '/plugin/language/index.html'), CBTxt::T('Installer - Error'), $installer->returnTo($option, '', 2));
            return;
        }
    }
    if (!$adminFS->is_dir($baseDir . '/plugin/templates')) {
        if (!$adminFS->mkdir($baseDir . '/plugin/templates')) {
            cbInstaller::renderInstallMessage(sprintf(CBTxt::T('Failed to create directory "%s"'), $baseDir . '/plugin/templates'), CBTxt::T('Installer - Error'), $installer->returnTo($option, '', 2));
            return;
        }
        if (!$adminFS->copy($baseDir . '/index.html', $baseDir . '/plugin/templates/index.html')) {
            cbInstaller::renderInstallMessage(sprintf(CBTxt::T('Failed to create index "%s"'), $baseDir . '/plugin/templates/index.html'), CBTxt::T('Installer - Error'), $installer->returnTo($option, '', 2));
            return;
        }
    }
    if (!$adminFS->is_dir($baseDir . '/plugin/user')) {
        if (!$adminFS->mkdir($baseDir . '/plugin/user')) {
            cbInstaller::renderInstallMessage(sprintf(CBTxt::T('Failed to create directory "%s"'), $baseDir . '/plugin/user'), CBTxt::T('Installer - Error'), $installer->returnTo($option, '', 2));
            return;
        }
        if (!$adminFS->copy($baseDir . '/index.html', $baseDir . '/plugin/user/index.html')) {
            cbInstaller::renderInstallMessage(sprintf(CBTxt::T('Failed to create index "%s"'), $baseDir . '/plugin/user/index.html'), CBTxt::T('Installer - Error'), $installer->returnTo($option, '', 2));
            return;
        }
    }
    // install core plugins:
    foreach ($filesList as $file) {
        if (preg_match('/^.+\\.xml$/i', $file)) {
            $plgPath = $installFrom . (substr($installFrom, -1, 1) == '/' ? '' : '/') . $file;
            $plgXml = new \CBLib\Xml\SimpleXMLElement(trim(file_get_contents($plgPath)));
            if ($plgXml->getName() == 'cbinstall') {
                $plgDir = dirname($plgPath) . '/';
                $plgInstaller = new cbInstallerPlugin();
                if (!$plgInstaller->install($plgDir)) {
                    cbInstaller::renderInstallMessage(sprintf(CBTxt::T('Installing plugin failed with error: %s : %s'), $plgInstaller->i_elementname ? $plgInstaller->i_elementname : $file, $plgInstaller->getError()), CBTxt::T('Installer - Error'), $installer->returnTo($option, '', 2));
                    return;
                }
            }
        }
    }
    $result = $adminFS->deldir(_cbPathName($installFrom . '/'));
    if ($result === false) {
        cbInstaller::renderInstallMessage(CBTxt::T('Deleting expanded tgz file directory failed with an error.'), CBTxt::T('Installer - Error'), $installer->returnTo($option, '', 2));
    }
    $tgzFileOS = _cbPathName($tgzFile, false);
    $result = $adminFS->unlink($tgzFileOS);
    if ($result === false) {
        cbInstaller::renderInstallMessage(sprintf(CBTxt::T('Deleting file %s failed with an error.'), $tgzFileOS), CBTxt::T('Installer - Error'), $installer->returnTo($option, '', 2));
    }
    // adapt published fields to global CB config (regarding name type)
    _cbAdaptNameFieldsPublished($ueConfig);
    $htmlToDisplay = $_CB_framework->getUserState('com_comprofiler_install');
    // clears the session buffer memory after installaion done:
    $_CB_framework->setUserState('com_comprofiler_install', '');
    $installerXml = new SimpleXMLElement(file_get_contents($installerFile));
    if (is_object($installerXml)) {
        $description = $installerXml->getElementByPath('description');
        if ($description !== false) {
            echo '<h2>' . $description->data() . '</h2>';
        }
    }
    echo $htmlToDisplay;
    echo '<div style="color:green;font-size:18px;font-weight:bold;margin-top:15px;margin-bottom:15px;">' . CBTxt::Th('Installation done.') . '</div>' . '<div style="color:green;font-size:18px;font-weight:bold;margin-top:15px;margin-bottom:15px;">' . CBTxt::Th('Now is a great time to checkout the <a href="[help_url]" target="_blank">Getting Started</a> resources.', null, array('[help_url]' => 'http://www.joomlapolis.com/documentation/community-builder/getting-started?pk_campaign=in-cb&amp;pk_kwd=installedwelcomescreen')) . '</div>' . '<div style="margin-bottom:10px;">' . '<div style="font-size:12px;"><a href="http://www.joomlapolis.com/cb-solutions?pk_campaign=in-cb&amp;pk_kwd=installedwelcomescreen" target="_blank">' . CBTxt::Th('Click here to see more CB Plugins (Languages, Fields, Tabs, Signup-Connect, Paid Memberships and over 30 more) by CB Team at joomlapolis.com') . '</a></div>' . '<div style="font-size:12px;"><a href="http://extensions.joomla.org/extensions/clients-a-communities/communities/210" target="_blank">' . CBTxt::Th('Click here to see our CB listing on the Joomla! Extensions Directory (JED) and find third-party add-ons for your website.') . '</a></div>' . '<div style="font-size:12px;margin:10px 0 25px;">or &nbsp; <a href="index.php?option=com_comprofiler&view=showconfig" class="btn btn-primary">' . CBTxt::Th('Start to Configure Community Builder') . '</a></div>' . '</div>';
    $_CB_framework->setUserState("com_comprofiler_install", '');
}
 /**
  * Uploads a file from a Url into a file on the filesystem
  *
  * @param  string  $userfileURL    Url
  * @param  string  $userfile_name  INPUT+OUTPUT: Destination filesname
  * @param  string  $msg            OUTPUT: Message for user
  * @return boolean                 Success
  */
 private function uploadFileURL($userfileURL, $userfile_name, &$msg)
 {
     global $_CB_framework;
     cbimport('cb.snoopy');
     cbimport('cb.adminfilesystem');
     $adminFS = cbAdminFileSystem::getInstance();
     if ($adminFS->isUsingStandardPHP()) {
         $baseDir = _cbPathName($_CB_framework->getCfg('tmp_path'));
     } else {
         $baseDir = $_CB_framework->getCfg('absolute_path') . '/tmp';
     }
     if (file_exists($baseDir)) {
         if ($adminFS->is_writable($baseDir) || !$adminFS->isUsingStandardPHP()) {
             $s = new CBSnoopy();
             $fetchResult = @$s->fetch($userfileURL);
             if ($fetchResult && !$s->error && $s->status == 200) {
                 cbimport('cb.adminfilesystem');
                 $adminFS = cbAdminFileSystem::getInstance();
                 if ($adminFS->file_put_contents($baseDir . $userfile_name, $s->results)) {
                     if ($this->_cbAdmin_chmod($baseDir . $userfile_name)) {
                         return true;
                     } else {
                         $msg = sprintf(CBTxt::T('Failed to change the permissions of the uploaded file %s'), $baseDir . $userfile_name);
                     }
                 } else {
                     $msg = sprintf(CBTxt::T('Failed to create and write uploaded file in %s'), $baseDir . $userfile_name);
                 }
             } else {
                 $msg = $s->error ? sprintf(CBTxt::T('Failed to download package file from <code>%s</code> to webserver due to following error: %s'), $userfileURL, $s->error) : sprintf(CBTxt::T('Failed to download package file from <code>%s</code> to webserver due to following status: %s'), $userfileURL, $s->status . ': ' . $s->response_code);
             }
         } else {
             $msg = sprintf(CBTxt::T('Upload failed as %s directory is not writable.'), '<code>' . htmlspecialchars($baseDir) . '</code>');
         }
     } else {
         $msg = sprintf(CBTxt::T('Upload failed as %s directory does not exist.'), '<code>' . htmlspecialchars($baseDir) . '</code>');
     }
     return false;
 }
function com_install()
{
    global $_CB_framework, $_CB_database, $_CB_adminpath, $ueConfig, $mainframe;
    // Ensure PHP version is adaquete for CB:
    if (version_compare(phpversion(), '5.0.0', '<')) {
        echo '<div class="cbError error" style="font-size:120%;color:red;font-weight:bold;margin-bottom:20px;">' . htmlspecialchars(sprintf("As stated in README and prerequisites list, PHP Version %s, which is obsolete since 2008-08-08 and insecure, is not compatible with %s: Please upgrade to PHP %s or greater (CB is also compatible with PHP 5.3.x) as soon as possible.", phpversion(), 'Community Builder', sprintf("at least version %s, recommended version %s", '5.0.0', '5.2.6'))) . '</div>';
        echo '<div class="cbError error" style="font-size:140%;color:red;font-weight:bold;">' . htmlspecialchars(sprintf('Installation failed. In all cases, please require your hoster to upgrade your PHP version as soon as possible.')) . '</div>';
        return;
    }
    // Determine path to CBs backend file structure:
    if (defined('JPATH_ADMINISTRATOR')) {
        $_CB_adminpath = JPATH_ADMINISTRATOR . '/components/com_comprofiler/';
    } else {
        $_CB_adminpath = $mainframe->getCfg('absolute_path') . '/administrator/components/com_comprofiler/';
    }
    // CB Configuration missing; try to copy default:
    if (!file_exists($_CB_adminpath . 'ue_config.php')) {
        include_once $_CB_adminpath . 'library/cb/cb.adminfilesystem.php';
        $adminFS =& cbAdminFileSystem::getInstance();
        if (!$adminFS->copy($_CB_adminpath . 'ue_config_first.php', $_CB_adminpath . 'ue_config.php')) {
            echo sprintf('Error copying initial configuration file in place from %s to %s', $_CB_adminpath . 'ue_config_first.php', $_CB_adminpath . 'ue_config.php') . "<br /><br />\n";
            return;
        }
    }
    include_once $_CB_adminpath . 'plugin.foundation.php';
    // Set location to backend:
    $_CB_framework->cbset('_ui', 2);
    if ($_CB_framework->getCfg('debug')) {
        ini_set('display_errors', true);
        error_reporting(E_ALL);
    }
    // Load in CB API:
    cbimport('cb.tabs');
    cbimport('cb.adminfilesystem');
    cbimport('cb.xml.simplexml');
    cbimport('cb.dbchecker');
    // Define CB backend filesystem API:
    $adminFS =& cbAdminFileSystem::getInstance();
    // If J1.6 or greater ensure XML and backend root component file is present:
    if (checkJversion() >= 2) {
        if (!$adminFS->copy($_CB_adminpath . 'comprofileg.xml', $_CB_adminpath . 'comprofiler.xml')) {
            echo sprintf('Error copying initial xml file in place from %s to %s', $_CB_adminpath . 'comprofileg.xml', $_CB_adminpath . 'comprofiler.xml') . "<br /><br />\n";
            return false;
        }
        if (!$adminFS->copy($_CB_adminpath . 'admin.comprofiler.php', $_CB_adminpath . 'comprofiler.php')) {
            echo sprintf('Error copying admin file in place from %s to %s', $_CB_adminpath . 'admin.comprofiler.php', $_CB_adminpath . 'comprofiler.php') . "<br /><br />\n";
            return false;
        }
    }
    $return = '<div style="text-align:left;margin-bottom:10px;">' . '<table width="100%" border="0">' . '<tr>' . '<td>' . '<img alt="CB Logo" src="../components/com_comprofiler/images/smcblogo.gif" />' . '</td>' . '</tr>' . '<tr>' . '<td>' . '<br />Copyright 2004-2012 MamboJoe/JoomlaJoe, Beat and CB team on joomlapolis.com . This component is released under the GNU/GPL version 2 License. All copyright statements must be kept. Derivate work must prominently duly acknowledge original work and include visible online links. Official site: <a href="http://www.joomlapolis.com">www.joomlapolis.com</a><br />' . '</td>' . '</tr>' . '<tr>' . '<td style="background-color:#F0F0F0;" colspan="2">' . '<code>' . 'Installation Process:<br />';
    // Fix admin menu links:
    if (checkJversion() >= 2) {
        $query = 'SELECT ' . $_CB_database->NameQuote('extension_id') . "\n FROM " . $_CB_database->NameQuote('#__extensions') . "\n WHERE " . $_CB_database->NameQuote('type') . " = " . $_CB_database->Quote('component') . "\n AND " . $_CB_database->NameQuote('element') . " = " . $_CB_database->Quote('com_comprofiler') . "\n ORDER BY " . $_CB_database->NameQuote('extension_id') . " DESC";
        $_CB_database->setQuery($query, 0, 1);
        $componentId = $_CB_database->loadResult();
        if ($componentId) {
            $query = 'UPDATE ' . $_CB_database->NameQuote('#__menu') . "\n SET " . $_CB_database->NameQuote('component_id') . " = " . (int) $componentId . "\n WHERE " . $_CB_database->NameQuote('type') . " = " . $_CB_database->Quote('component') . "\n AND " . $_CB_database->NameQuote('link') . " LIKE " . $_CB_database->Quote('%option=com_comprofiler%');
            $_CB_database->setQuery($query);
            $_CB_database->query();
        }
    } elseif (checkJversion() <= 1) {
        $iconResults = array();
        // Userlist Management icon:
        if (checkJversion() >= 1) {
            $icon = 'js/ThemeOffice/static.png';
        } else {
            $icon = 'js/ThemeOffice/content.png';
        }
        $query = 'UPDATE ' . $_CB_database->NameQuote('#__components') . "\n SET " . $_CB_database->NameQuote('admin_menu_img') . " = " . $_CB_database->Quote($icon) . "\n WHERE " . $_CB_database->NameQuote('admin_menu_link') . " = " . $_CB_database->Quote('option=com_comprofiler&task=showLists');
        $_CB_database->setQuery($query);
        $iconResults[0] = $_CB_database->query();
        // Field Management icon:
        $query = 'UPDATE ' . $_CB_database->NameQuote('#__components') . "\n SET " . $_CB_database->NameQuote('admin_menu_img') . " = " . $_CB_database->Quote('js/ThemeOffice/content.png') . "\n WHERE " . $_CB_database->NameQuote('admin_menu_link') . " = " . $_CB_database->Quote('option=com_comprofiler&task=showField');
        $_CB_database->setQuery($query);
        $iconResults[1] = $_CB_database->query();
        // Tab Management iocn:
        if (checkJversion() >= 1) {
            $icon = 'js/ThemeOffice/article.png';
        } else {
            $icon = 'js/ThemeOffice/content.png';
        }
        $query = 'UPDATE ' . $_CB_database->NameQuote('#__components') . "\n SET " . $_CB_database->NameQuote('admin_menu_img') . " = " . $_CB_database->Quote($icon) . "\n WHERE " . $_CB_database->NameQuote('admin_menu_link') . " = " . $_CB_database->Quote('option=com_comprofiler&task=showTab');
        $_CB_database->setQuery($query);
        $iconResults[2] = $_CB_database->query();
        // Configuration icon:
        $query = 'UPDATE ' . $_CB_database->NameQuote('#__components') . "\n SET " . $_CB_database->NameQuote('admin_menu_img') . " = " . $_CB_database->Quote('js/ThemeOffice/config.png') . "\n WHERE " . $_CB_database->NameQuote('admin_menu_link') . " = " . $_CB_database->Quote('option=com_comprofiler&task=showconfig');
        $_CB_database->setQuery($query);
        $iconResults[3] = $_CB_database->query();
        // User Management icon:
        if (checkJversion() >= 1) {
            $icon = 'js/ThemeOffice/user.png';
        } else {
            $icon = 'js/ThemeOffice/users.png';
        }
        $query = 'UPDATE ' . $_CB_database->NameQuote('#__components') . "\n SET " . $_CB_database->NameQuote('admin_menu_img') . " = " . $_CB_database->Quote($icon) . "\n WHERE " . $_CB_database->NameQuote('admin_menu_link') . " = " . $_CB_database->Quote('option=com_comprofiler&task=showusers');
        $_CB_database->setQuery($query);
        $iconResults[4] = $_CB_database->query();
        // Plugin Management icon:
        if (checkJversion() >= 1) {
            $icon = 'js/ThemeOffice/plugin.png';
        } else {
            $icon = 'js/ThemeOffice/install.png';
        }
        $query = 'UPDATE ' . $_CB_database->NameQuote('#__components') . "\n SET " . $_CB_database->NameQuote('admin_menu_img') . " = " . $_CB_database->Quote($icon) . "\n WHERE " . $_CB_database->NameQuote('admin_menu_link') . " = " . $_CB_database->Quote('option=com_comprofiler&task=showPlugins');
        $_CB_database->setQuery($query);
        $iconResults[5] = $_CB_database->query();
        // Community Builder icon:
        $query = 'UPDATE ' . $_CB_database->NameQuote('#__components') . "\n SET " . $_CB_database->NameQuote('admin_menu_img') . " = " . $_CB_database->Quote('../components/com_comprofiler/plugin/templates/luna/images/header/icon-16-cb.png') . "\n WHERE " . $_CB_database->NameQuote('admin_menu_link') . " = " . $_CB_database->Quote('option=com_comprofiler');
        $_CB_database->setQuery($query);
        $iconResults[6] = $_CB_database->query();
        foreach ($iconResults as $i => $iconResult) {
            if (!$iconResult) {
                $return .= '<span style="color:red;">ERROR:</span> Image of administration menu entry $i could not be corrected.<br />';
            }
        }
        // Delete invalid components:
        $query = 'SELECT COUNT(*)' . "\n FROM " . $_CB_database->NameQuote('#__components') . "\n WHERE " . $_CB_database->NameQuote('link') . " = " . $_CB_database->Quote('option=com_comprofiler');
        $_CB_database->setQuery($query);
        $components = $_CB_database->loadResult();
        if ($components >= 1) {
            $query = 'SELECT ' . $_CB_database->NameQuote('id') . "\n FROM " . $_CB_database->NameQuote('#__components') . "\n WHERE " . $_CB_database->NameQuote('link') . " = " . $_CB_database->Quote('option=com_comprofiler') . "\n ORDER BY " . $_CB_database->NameQuote('id') . " DESC";
            $_CB_database->setQuery($query, 0, 1);
            $componentId = $_CB_database->loadResult();
            if ($componentId) {
                $query = 'DELETE ' . "\n FROM " . $_CB_database->NameQuote('#__components') . "\n WHERE " . $_CB_database->NameQuote('link') . " = " . $_CB_database->Quote('option=com_comprofiler') . "\n AND " . $_CB_database->NameQuote('id') . " != " . (int) $componentId;
                $_CB_database->setQuery($query);
                $_CB_database->query();
                $query = 'DELETE ' . "\n FROM " . $_CB_database->NameQuote('#__components') . "\n WHERE " . $_CB_database->NameQuote('option') . " = " . $_CB_database->Quote('com_comprofiler') . "\n AND " . $_CB_database->NameQuote('id') . " != " . (int) $componentId . "\n AND " . $_CB_database->NameQuote('parent') . " != " . (int) $componentId;
                $_CB_database->setQuery($query);
                $_CB_database->query();
                $query = 'UPDATE ' . $_CB_database->NameQuote('#__menu') . "\n SET " . $_CB_database->NameQuote('componentid') . " = " . (int) $componentId . "\n WHERE " . $_CB_database->NameQuote('type') . " = " . $_CB_database->Quote('component') . "\n AND " . $_CB_database->NameQuote('link') . " LIKE " . $_CB_database->Quote('%option=com_comprofiler%');
                $_CB_database->setQuery($query);
                $_CB_database->query();
            }
            $return .= '<span style="color:green;">Administrator and frontend menus corrected.</span><br />';
        }
    }
    $dbUpgrades = array();
    // Beta 3 upgrades:
    $dbUpgrades[0]['test'] = array('default', '#__comprofiler_lists');
    $dbUpgrades[0]['updates'][0] = "ALTER TABLE `#__comprofiler_lists`" . "\n ADD `default` TINYINT( 1 ) DEFAULT '0' NOT NULL," . "\n ADD `usergroupids` VARCHAR( 255 )," . "\n ADD `sortfields` VARCHAR( 255 )," . "\n ADD `ordering` INT( 11 ) DEFAULT '0' NOT NULL AFTER `published`";
    $dbUpgrades[0]['updates'][1] = "UPDATE #__comprofiler_lists SET `default`=1 WHERE published =1";
    $dbUpgrades[0]['updates'][2] = "UPDATE #__comprofiler_lists SET usergroupids = '29, 18, 19, 20, 21, 30, 23, 24, 25', sortfields = '`username` ASC'";
    $dbUpgrades[0]['updates'][3] = "ALTER TABLE `#__comprofiler` ADD `acceptedterms` TINYINT( 1 ) DEFAULT '0' NOT NULL AFTER `bannedreason`";
    $dbUpgrades[0]['message'] = "1.0 Beta 2 to 1.0 Beta 3";
    // Beta 4 upgrades:
    $dbUpgrades[1]['test'] = array('firstname', '#__comprofiler');
    $dbUpgrades[1]['updates'][0] = "ALTER TABLE #__comprofiler ADD `firstname` VARCHAR( 100 ) AFTER `user_id` ," . "\n ADD `middlename` VARCHAR( 100 ) AFTER `firstname` ," . "\n ADD `lastname` VARCHAR( 100 ) AFTER `middlename` ";
    $dbUpgrades[1]['updates'][1] = "ALTER TABLE `#__comprofiler_fields` ADD `readonly` TINYINT( 1 ) DEFAULT '0' NOT NULL AFTER `profile`";
    $dbUpgrades[1]['updates'][3] = "ALTER TABLE `#__comprofiler_tabs` ADD `width` VARCHAR( 10 ) DEFAULT '.5' NOT NULL AFTER `ordering` ," . "\n ADD `enabled` TINYINT( 1 ) DEFAULT '1' NOT NULL AFTER `width` ," . "\n ADD `plugin` VARCHAR( 255 ) DEFAULT NULL AFTER `enabled`";
    $dbUpgrades[1]['message'] = "1.0 Beta 3 to 1.0 Beta 4";
    // RC 1 upgrades:
    $dbUpgrades[2]['test'] = array('fields', '#__comprofiler_tabs');
    $dbUpgrades[2]['updates'][0] = "ALTER TABLE #__comprofiler_tabs ADD `plugin_include` VARCHAR( 255 ) AFTER `plugin` ," . "\n ADD `fields` TINYINT( 1 ) DEFAULT '1' NOT NULL AFTER `plugin_include` ";
    $dbUpgrades[2]['updates'][1] = "INSERT INTO `#__comprofiler_tabs` ( `title`, `description`, `ordering`, `width`, `enabled`, `plugin`, `plugin_include`, `fields`, `sys`) VALUES " . "\n ( '_UE_CONTACT_INFO_HEADER', '', -4, '1', 1, 'getContactTab', NULL, 1, 1)," . "\n ( '_UE_AUTHORTAB', '', -3, '1', 0, 'getAuthorTab', NULL, 0, 1)," . "\n ( '_UE_FORUMTAB', '', -2, '1', 0, 'getForumTab', NULL, 0, 1)," . "\n ( '_UE_BLOGTAB', '', -1, '1', 0, 'getBlogTab', NULL, 0, 1);";
    $dbUpgrades[2]['updates'][2] = "ALTER TABLE `#__comprofiler_lists` ADD `filterfields` VARCHAR( 255 ) AFTER `sortfields`;";
    $dbUpgrades[2]['message'] = "1.0 Beta 4 to 1.0 RC 1";
    // RC 2 Part 1 upgrades:
    $dbUpgrades[3]['test'] = array('description', '#__comprofiler_fields');
    $dbUpgrades[3]['updates'][0] = "ALTER TABLE `#__comprofiler_fields` ADD `description` MEDIUMTEXT  NOT NULL default '' AFTER `title` ";
    $dbUpgrades[3]['updates'][1] = "ALTER TABLE `#__comprofiler_fields` CHANGE `title` `title` VARCHAR( 255 ) NOT NULL";
    $dbUpgrades[3]['updates'][2] = "INSERT INTO `#__comprofiler_tabs` (`title`, `description`, `ordering`, `width`, `enabled`, `plugin`, `plugin_include`, `fields`, `sys`) VALUES " . "\n ( '_UE_CONNECTION', '',99, '1', 0, 'getConnectionTab', NULL, 0, 1);";
    $dbUpgrades[3]['updates'][3] = "INSERT INTO `#__comprofiler_tabs` (`title`, `description`, `ordering`, `width`, `enabled`, `plugin`, `plugin_include`, `fields`, `sys`) VALUES " . "\n ( '_UE_NEWSLETTER_HEADER', '_UE_NEWSLETTER_INTRODCUTION', 99, '1', 0, 'getNewslettersTab', NULL, 0, 1);";
    $dbUpgrades[3]['updates'][4] = "UPDATE `#__comprofiler_tabs` SET sys=2, enabled=1 WHERE plugin='getContactTab' ";
    $dbUpgrades[3]['updates'][5] = "ALTER TABLE `#__comprofiler_lists` ADD `useraccessgroupid` INT( 9 ) DEFAULT '18' NOT NULL AFTER `usergroupids` ";
    $dbUpgrades[3]['message'] = "1.0 RC 1 to 1.0 RC 2 part 1";
    // RC 2 Part 2 upgrades:
    $dbUpgrades[4]['test'] = array('params', '#__comprofiler_tabs');
    $dbUpgrades[4]['updates'][0] = "ALTER TABLE `#__comprofiler_tabs` CHANGE `plugin` `pluginclass` VARCHAR( 255 ) DEFAULT NULL , " . "\n CHANGE `plugin_include` `pluginid` INT( 11 ) DEFAULT NULL ";
    $dbUpgrades[4]['updates'][1] = "ALTER TABLE `#__comprofiler_tabs` ADD `params` MEDIUMTEXT AFTER `fields` ;";
    $dbUpgrades[4]['updates'][2] = "ALTER TABLE `#__comprofiler_fields` ADD `pluginid` INT( 11 ) , " . "\n ADD `params` MEDIUMTEXT; ";
    $dbUpgrades[4]['updates'][3] = "UPDATE `#__comprofiler_tabs` SET pluginid=1 WHERE pluginclass='getContactTab' ";
    $dbUpgrades[4]['updates'][4] = "UPDATE `#__comprofiler_tabs` SET pluginid=1 WHERE pluginclass='getConnectionTab' ";
    $dbUpgrades[4]['updates'][5] = "UPDATE `#__comprofiler_tabs` SET pluginid=3 WHERE pluginclass='getAuthorTab' ";
    $dbUpgrades[4]['updates'][6] = "UPDATE `#__comprofiler_tabs` SET pluginid=4 WHERE pluginclass='getForumTab' ";
    $dbUpgrades[4]['updates'][7] = "UPDATE `#__comprofiler_tabs` SET pluginid=5 WHERE pluginclass='getBlogTab' ";
    $dbUpgrades[4]['updates'][8] = "UPDATE `#__comprofiler_tabs` SET pluginid=6 WHERE pluginclass='getNewslettersTab' ";
    $dbUpgrades[4]['message'] = "1.0 RC 1 to 1.0 RC 2 part 2";
    // RC 2 Part 3 upgrades:
    $dbUpgrades[5]['test'] = array('position', '#__comprofiler_tabs');
    $dbUpgrades[5]['updates'][1] = "ALTER TABLE `#__comprofiler_tabs`" . "\n ADD `position` VARCHAR( 255 ) DEFAULT '' NOT NULL," . "\n ADD `displaytype` VARCHAR( 255 ) DEFAULT '' NOT NULL AFTER `sys`";
    $dbUpgrades[5]['updates'][2] = "UPDATE `#__comprofiler_tabs` SET position='cb_tabmain', displaytype='tab' ";
    $dbUpgrades[5]['updates'][3] = "INSERT INTO `#__comprofiler_tabs` (`title`, `description`, `ordering`, `width`, `enabled`, `pluginclass`, `pluginid`, `fields`, `sys`, `position`, `displaytype`) VALUES " . "\n ( '_UE_MENU', '', -10, '1', 1, 'getMenuTab', 14, 0, 1, 'cb_head', 'html')," . "\n ( '_UE_CONNECTIONPATHS', '', -9, '1', 1, 'getConnectionPathsTab', 2, 0, 1, 'cb_head', 'html')," . "\n ( '_UE_PROFILE_PAGE_TITLE', '', -8, '1', 1, 'getPageTitleTab', 1, 0, 1, 'cb_head', 'html')," . "\n ( '_UE_PORTRAIT', '', -7, '1', 1, 'getPortraitTab', 1, 0, 1, 'cb_middle', 'html')," . "\n ( '_UE_USER_STATUS', '', -6, '.5', 1, 'getStatusTab', 14, 0, 1, 'cb_right', 'html')," . "\n ( '_UE_PMSTAB', '', -5, '.5', 0, 'getmypmsproTab', 15, 0, 1, 'cb_right', 'html');";
    $dbUpgrades[5]['updates'][5] = "UPDATE `#__comprofiler_tabs` SET pluginid=2 WHERE pluginclass='getConnectionTab' ";
    $dbUpgrades[5]['updates'][6] = "ALTER TABLE `#__comprofiler_members` ADD `reason` MEDIUMTEXT default NULL AFTER `membersince` ";
    $dbUpgrades[5]['updates'][7] = "UPDATE `#__comprofiler_tabs` SET `pluginclass`=NULL, `pluginid`=NULL WHERE `pluginclass` != 'getContactTab' AND `fields` = 1";
    $dbUpgrades[5]['message'] = "1.0 RC 1 to 1.0 RC 2 part 3";
    // 1.0.2 upgrades:
    $dbUpgrades[6]['test'] = array('cbactivation', '#__comprofiler');
    $dbUpgrades[6]['updates'][] = "ALTER TABLE `#__comprofiler_fields` CHANGE `default` `default` MEDIUMTEXT DEFAULT NULL;";
    $dbUpgrades[6]['updates'][] = "ALTER TABLE `#__comprofiler_fields` CHANGE `tabid` `tabid` int(11) DEFAULT NULL;";
    if (checkJversion() < 2) {
        $dbUpgrades[6]['updates'][] = "UPDATE `#__users` SET usertype='Registered' WHERE usertype='';";
    }
    $dbUpgrades[6]['updates'][] = "UPDATE `#__comprofiler_fields` SET `table`='#__users' WHERE name='email';";
    $dbUpgrades[6]['updates'][] = "UPDATE `#__comprofiler_fields` SET `table`='#__users' WHERE name='lastvisitDate';";
    $dbUpgrades[6]['updates'][] = "UPDATE `#__comprofiler_fields` SET `table`='#__users' WHERE name='registerDate';";
    $dbUpgrades[6]['updates'][] = "ALTER TABLE #__comprofiler ADD `registeripaddr` VARCHAR( 50 ) DEFAULT '' NOT NULL AFTER `lastupdatedate`;";
    $dbUpgrades[6]['updates'][] = "ALTER TABLE #__comprofiler ADD `cbactivation` VARCHAR( 50 ) DEFAULT '' NOT NULL AFTER `registeripaddr`;";
    $dbUpgrades[6]['updates'][] = "ALTER TABLE #__comprofiler ADD `message_last_sent` DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00' AFTER `hits`;";
    $dbUpgrades[6]['updates'][] = "ALTER TABLE #__comprofiler ADD `message_number_sent` INT( 11 ) DEFAULT 0 NOT NULL AFTER `message_last_sent`;";
    $dbUpgrades[6]['updates'][] = "ALTER TABLE `#__comprofiler_field_values` ADD INDEX fieldid_ordering (`fieldid`, `ordering` );";
    $dbUpgrades[6]['updates'][] = "ALTER TABLE `#__comprofiler_fields` ADD INDEX `tabid_pub_prof_order` ( `tabid` , `published` , `profile` , `ordering` );";
    $dbUpgrades[6]['updates'][] = "ALTER TABLE `#__comprofiler_fields` ADD INDEX `readonly_published_tabid` ( `readonly` , `published` , `tabid` );";
    $dbUpgrades[6]['updates'][] = "ALTER TABLE `#__comprofiler_fields` ADD INDEX `registration_published_order` ( `registration` , `published` , `ordering` );";
    $dbUpgrades[6]['updates'][] = "ALTER TABLE `#__comprofiler_members` ADD INDEX `pamr` ( `pending` , `accepted` , `memberid` , `referenceid` );";
    $dbUpgrades[6]['updates'][] = "ALTER TABLE `#__comprofiler_members` ADD INDEX `aprm` ( `accepted` , `pending` , `referenceid` , `memberid` );";
    $dbUpgrades[6]['updates'][] = "ALTER TABLE `#__comprofiler_members` ADD INDEX `membrefid` ( `memberid` , `referenceid` );";
    $dbUpgrades[6]['updates'][] = "ALTER TABLE `#__comprofiler_plugin` ADD INDEX `type_pub_order` ( `type` , `published` , `ordering` );";
    $dbUpgrades[6]['updates'][] = "ALTER TABLE `#__comprofiler_tabs` ADD INDEX `enabled_position_ordering` ( `enabled` , `position` , `ordering` );";
    $dbUpgrades[6]['updates'][] = "ALTER TABLE `#__comprofiler_lists` ADD INDEX `pub_ordering` ( `published` , `ordering` );";
    $dbUpgrades[6]['updates'][] = "ALTER TABLE `#__comprofiler_lists` ADD INDEX `default_published` ( `default` , `published` );";
    $dbUpgrades[6]['updates'][] = "ALTER TABLE `#__comprofiler_userreports` ADD INDEX `status_user_date` ( `reportedstatus` , `reporteduser` , `reportedondate` );";
    $dbUpgrades[6]['updates'][] = "ALTER TABLE `#__comprofiler_userreports` ADD INDEX `reportedbyuser_ondate` ( `reportedbyuser` , `reportedondate` );";
    $dbUpgrades[6]['updates'][] = "ALTER TABLE `#__comprofiler_views` ADD INDEX `lastview` ( `lastview` );";
    $dbUpgrades[6]['updates'][] = "ALTER TABLE `#__comprofiler_views` ADD INDEX `profile_id_lastview` (`profile_id`,`lastview`);";
    $dbUpgrades[6]['updates'][] = "UPDATE `#__comprofiler` SET `user_id`=`id` WHERE 1>0;";
    // fix in case something corrupt for unique key
    $dbUpgrades[6]['updates'][] = "ALTER TABLE `#__comprofiler` ADD UNIQUE KEY user_id (`user_id`);";
    $dbUpgrades[6]['updates'][] = "ALTER TABLE `#__comprofiler` ADD INDEX `apprconfbanid` ( `approved` , `confirmed` , `banned` , `id` );";
    $dbUpgrades[6]['updates'][] = "ALTER TABLE `#__comprofiler` ADD INDEX `avatappr_apr_conf_ban_avatar` ( `avatarapproved` , `approved` , `confirmed` , `banned` , `avatar` );";
    $dbUpgrades[6]['updates'][] = "ALTER TABLE `#__comprofiler` ADD INDEX `lastupdatedate` ( `lastupdatedate` );";
    $dbUpgrades[6]['message'] = "1.0 RC 2, 1.0 and 1.0.1 to 1.0.2";
    // 1.1 upgrades:
    $dbUpgrades[7]['test'] = array('ordering_register', '#__comprofiler_tabs');
    $dbUpgrades[7]['updates'][] = "ALTER TABLE `#__comprofiler_plugin` ADD `backend_menu` VARCHAR(255) NOT NULL DEFAULT '' AFTER `folder`;";
    $dbUpgrades[7]['updates'][] = "ALTER TABLE `#__comprofiler_tabs` ADD `ordering_register` int(11) NOT NULL DEFAULT 10 AFTER `ordering`;";
    $dbUpgrades[7]['updates'][] = "ALTER TABLE `#__comprofiler_tabs` ADD `useraccessgroupid` int(9) DEFAULT -2 NOT NULL AFTER `position`;";
    $dbUpgrades[7]['updates'][] = "ALTER TABLE `#__comprofiler_tabs` ADD INDEX `orderreg_enabled_pos_order` ( `enabled` , `ordering_register` , `position` , `ordering` );";
    $dbUpgrades[7]['updates'][] = "ALTER TABLE `#__comprofiler` ADD `unbannedby` int(11) default NULL AFTER `bannedby`;";
    $dbUpgrades[7]['updates'][] = "ALTER TABLE `#__comprofiler` ADD `unbanneddate` datetime default NULL AFTER `banneddate`;";
    $dbUpgrades[7]['updates'][] = "ALTER TABLE `#__comprofiler_field_values` CHANGE `fieldtitle` `fieldtitle` VARCHAR(255) NOT NULL DEFAULT '';";
    $dbUpgrades[7]['message'] = "1.0.2 to 1.1";
    // Perform database upgrades:
    foreach ($dbUpgrades as $dbUpgrade) {
        if (!cbInstaller_field_exists($dbUpgrade['test'][1], $dbUpgrade['test'][0])) {
            foreach ($dbUpgrade['updates'] as $query) {
                $_CB_database->setQuery($query);
                if (!$_CB_database->query()) {
                    $return .= '<span style="color:red;">' . $dbUpgrade['message'] . ' failed! Error: ' . $_CB_database->stderr(true) . '</span><br />';
                }
            }
            $return .= '<span style="color:green;">' . $dbUpgrade['message'] . ' Upgrade Applied Successfully.</span><br />';
        }
    }
    // Correct userlist orders:
    $query = 'SELECT ' . $_CB_database->NameQuote('listid') . "\n FROM " . $_CB_database->NameQuote('#__comprofiler_lists') . "\n ORDER BY " . $_CB_database->NameQuote('ordering') . " ASC, " . $_CB_database->NameQuote('published') . " DESC";
    $_CB_database->setQuery($query);
    $lists = $_CB_database->loadObjectList();
    $order = 0;
    if ($lists) {
        foreach ($lists as $list) {
            $query = 'UPDATE ' . $_CB_database->NameQuote('#__comprofiler_lists') . "\n SET " . $_CB_database->NameQuote('ordering') . " = " . (int) $order . "\n WHERE " . $_CB_database->NameQuote('listid') . " = " . (int) $list->listid;
            $_CB_database->setQuery($query);
            $_CB_database->query();
            $order++;
        }
    }
    // Core database fixes:
    $dbChecker = new CBdbChecker($_CB_database);
    $result = $dbChecker->checkCBMandatoryDb(false);
    if (!$result) {
        $dbChecker = new CBdbChecker($_CB_database);
        $result = $dbChecker->checkCBMandatoryDb(true, false);
        if ($result == true) {
            $return .= '<p><span style="color:green;">Automatic database fixes of old core tabs and fields applied successfully.</span></p>';
        } elseif (is_string($result)) {
            $return .= '<p><span style="color:red;">' . $result . '</span></p>';
        } else {
            $errors = $dbChecker->getErrors(false);
            if ($errors) {
                $return .= '<div style="color:red;">' . '<h3><span style="color:red;">Database fixing errors:</span></h3>';
                foreach ($errors as $error) {
                    $return .= '<div style="font-size:115%">' . $error[0];
                    if ($error[1]) {
                        $return .= '<div style="font-size:90%">' . $error[1] . '</div>';
                    }
                    $return .= '</div>';
                }
                $return .= '</div>';
            }
        }
        if (checkJversion() < 1 || $_CB_framework->getCfg('session_handler') != 'database') {
            $logs = $dbChecker->getLogs(false);
            if (count($logs) > 0) {
                $return .= '<div><a href="#" id="cbdetailsLinkShowOld" onclick="document.getElementById(\'cbdetailsdbcheckOld\').style.display=\'\';return false;">Click to Show details</a></div>' . '<div id="cbdetailsdbcheckOld" style="color:green;display:none;">';
                foreach ($logs as $log) {
                    $return .= '<div>' . $log[0];
                    if ($log[1]) {
                        $return .= '<div style="font-size:90%">' . $log[1] . '</div>';
                    }
                    $return .= '</div>';
                }
                $return .= '</div>';
            }
        }
    }
    $dbChecker = new CBdbChecker($_CB_database);
    $result = $dbChecker->checkDatabase(true, false);
    if ($result == true) {
        $return .= '<p><span style="color:green;">Automatic database upgrade to current version applied successfully.</span></p>';
    } elseif (is_string($result)) {
        $return .= '<p><span style="color:red;">' . $result . '</span></p>';
    } else {
        $errors = $dbChecker->getErrors(false);
        if ($errors) {
            $return .= '<div style="color:red;">' . '<h3><span style="color:red;">Database fixing errors:</span></h3>';
            foreach ($errors as $error) {
                $return .= '<div style="font-size:115%">' . $error[0];
                if ($error[1]) {
                    $return .= '<div style="font-size:90%">' . $error[1] . '</div>';
                }
                $return .= '</div>';
            }
            $return .= '</div>';
        }
    }
    if (checkJversion() < 1 || $_CB_framework->getCfg('session_handler') != 'database') {
        $logs = $dbChecker->getLogs(false);
        if (count($logs) > 0) {
            $return .= '<div><a href="#" id="cbdetailsLinkShow" onclick="document.getElementById(\'cbdetailsdbcheck\').style.display=\'\';return false;">Click to Show details</a></div>' . '<div id="cbdetailsdbcheck" style="color:green;display:none;">';
            foreach ($logs as $log) {
                $return .= '<div>' . $log[0];
                if ($log[1]) {
                    $return .= '<div style="font-size:90%">' . $log[1] . '</div>';
                }
                $return .= '</div>';
            }
            $return .= '</div>';
        }
    }
    $return .= '<p>Core CB database upgrades done. If all lines above are in green, database upgrade completed successfully. Otherwise, please report exact errors and queries to forum, and try checking database again in components : community builder : tools : check database.</p>' . '</code>' . '</td>' . '</tr>' . '<tr>' . '<td>';
    // Fix images:
    $imagesPath = $_CB_framework->getCfg('absolute_path') . '/images';
    $cbImages = $imagesPath . '/comprofiler';
    $cbImagesGallery = $cbImages . '/gallery';
    if ($adminFS->isUsingStandardPHP() && !$adminFS->file_exists($cbImages) && !$adminFS->is_writable($_CB_framework->getCfg('absolute_path') . '/images/')) {
        $return .= '<span style="color:red;">' . $imagesPath . '/ is not writable!</span><br />';
    } else {
        if (!$adminFS->file_exists($cbImages)) {
            if ($adminFS->mkdir($cbImages)) {
                $return .= '<span style="color:green;">' . $cbImages . '/ Successfully added.</span><br />';
            } else {
                $return .= '<span style="color:red;">' . $cbImages . '/ failed to be to be created, please do so manually!</span><br />';
            }
        }
        if (!$adminFS->file_exists($cbImagesGallery)) {
            if ($adminFS->mkdir($cbImagesGallery)) {
                $return .= '<span style="color:green;">' . $cbImagesGallery . '/ Successfully added.</span><br />';
            } else {
                $return .= '<span style="color:red;">' . $cbImagesGallery . '/ failed to be to be created, please do so manually!</span><br />';
            }
        }
        if ($adminFS->file_exists($cbImages)) {
            if (!is_writable($cbImages)) {
                if (!$adminFS->chmod($cbImages, 0775)) {
                    if (!@chmod($cbImages, 0775)) {
                        $return .= '<span style="color:red;">' . $cbImages . '/ failed to chmod to 775 please do so manually!</span><br />';
                    }
                }
            }
            if (!is_writable($cbImages)) {
                $return .= '<span style="color:red;">' . $cbImages . '/ is not writable and failed to chmod to 775 please do so manually!</span><br />';
            }
        }
        if ($adminFS->file_exists($cbImagesGallery)) {
            if (!is_writable($cbImagesGallery)) {
                if (!$adminFS->chmod($cbImagesGallery, 0775)) {
                    if (!@chmod($cbImagesGallery, 0775)) {
                        $return .= '<span style="color:red;">' . $cbImagesGallery . '/ failed to chmod to 775 please do so manually!</span><br />';
                    }
                }
            }
            if (!is_writable($cbImagesGallery)) {
                $return .= '<span style="color:red;">' . $cbImagesGallery . '/ is not writable and failed to chmod to 775 please do so manually!</span><br />';
            }
            $galleryFiles = array('airplane.gif', 'ball.gif', 'butterfly.gif', 'car.gif', 'dog.gif', 'duck.gif', 'fish.gif', 'frog.gif', 'guitar.gif', 'kick.gif', 'pinkflower.gif', 'redflower.gif', 'skater.gif', 'index.html');
            foreach ($galleryFiles as $galleryFile) {
                if (!(file_exists($cbImagesGallery . '/' . $galleryFile) && is_readable($cbImagesGallery . '/' . $galleryFile))) {
                    $result = @copy($_CB_framework->getCfg('absolute_path') . '/components/com_comprofiler/images/gallery/' . $galleryFile, $cbImagesGallery . '/' . $galleryFile);
                    if (!$result) {
                        $result = $adminFS->copy($_CB_framework->getCfg('absolute_path') . '/components/com_comprofiler/images/gallery/' . $galleryFile, $cbImagesGallery . '/' . $galleryFile);
                    }
                    if (!$result) {
                        $return .= '<span style="color:red;">' . $galleryFile . ' failed to be added to the gallery please do so manually!</span><br />';
                    }
                }
            }
        }
    }
    if (!($adminFS->file_exists($cbImages) && is_writable($cbImages) && $adminFS->file_exists($cbImagesGallery))) {
        $return .= '<br /><span style="color:red;">Manually do the following:<br /> 1.) create ' . $cbImages . '/ directory <br /> 2.) chmod it to 755 or if needed to 775 <br /> 3.) create ' . $cbImagesGallery . '/ <br /> 4.) chmod it to 755 or if needed to 775 <br />5.) copy ' . $_CB_framework->getCfg('absolute_path') . '/components/com_comprofiler/images/gallery/ and its contents to ' . $cbImagesGallery . '/</span><br />';
    }
    $return .= '</td>' . '</tr>' . '</table>' . '</div>';
    $_CB_framework->setUserState('com_comprofiler_install', $return);
    if (is_callable(array($_CB_framework, 'backendUrl'))) {
        $stepTwoUrl = $_CB_framework->backendUrl('index.php?option=com_comprofiler&task=finishinstallation', false);
    } else {
        $stepTwoUrl = (checkJversion() < 1 ? 'index2.php' : 'index.php') . '?option=com_comprofiler&task=finishinstallation';
    }
    $return = '<div id="cbInstallNextStep" style="font-weight:bold;font-size:120%;background:#ffffdd;border:2px orange solid;padding:5px;">WAIT PLEASE: DO NOT INTERRUPT INSTALLATION PROCESS: PERFORMING SECOND INSTALLATION STEP: UNCOMPRESSING CORE PLUGINS: THIS CAN TAKE UP TO 2 MINUTES.</div>' . $return;
    echo $return;
    $jsStepTwo = "\$( '#cbInstallNextStep' ).hide().fadeIn( '1500', function() {" . "\$( this ).fadeOut( '1000', function() {" . "\$( this ).fadeIn( '1500', function() {" . "window.location = '" . addslashes($stepTwoUrl) . "';" . "})" . "})" . "});";
    $_CB_framework->document->_outputToHeadCollectionStart();
    if (checkJversion() > 1) {
        $_CB_framework->document->setCmsDoc(null);
    }
    $_CB_framework->outputCbJQuery($jsStepTwo);
    $_CB_framework->getAllJsPageCodes();
    echo $_CB_framework->document->_outputToHead();
    return true;
}
 /**
  * plugin uninstaller with best effort depending on what it finds.
  *
  * @param  int     $id
  * @param  string  $option
  * @param  int     $client
  * @param  string  $action
  * @return boolean
  */
 function uninstall($id, $option, $client = 0)
 {
     global $_CB_database;
     $db = false;
     if ($this->checkPluginGetXml($id, $option, $client)) {
         if ($this->i_xmldocument !== null && count($this->i_xmldocument->children()) > 0) {
             $cbInstallXML =& $this->i_xmldocument;
             // get the element name:
             $e =& $cbInstallXML->getElementByPath('name');
             $this->elementName($e->data());
             // $cleanedElementName = strtolower(str_replace(array(" ","."),array("","_"),$this->elementName()));
             // get the files element
             $files_element =& $cbInstallXML->getElementByPath('files');
             if ($files_element) {
                 if (count($files_element->children())) {
                     foreach ($files_element->children() as $file) {
                         if ($file->attributes("plugin")) {
                             $this->elementSpecial($file->attributes("plugin"));
                             break;
                         }
                     }
                     $cleanedMainFileName = strtolower(str_replace(array(" ", "."), array("", "_"), $this->elementSpecial()));
                 }
                 // Is there an uninstallfile
                 $uninstallfile_elemet =& $cbInstallXML->getElementByPath('uninstallfile');
                 if ($uninstallfile_elemet !== false) {
                     if (is_file($this->i_elementdir . $uninstallfile_elemet->data())) {
                         global $_PLUGINS;
                         // needed for the require_once below !
                         require_once $this->i_elementdir . $uninstallfile_elemet->data();
                         $ret = call_user_func_array("plug_" . $cleanedMainFileName . "_uninstall", array());
                         if ($ret != '') {
                             $this->setError(0, $ret);
                         }
                     }
                 }
                 $adminFS =& cbAdminFileSystem::getInstance();
                 foreach ($files_element->children() as $file) {
                     // delete the files
                     $filename = $file->data();
                     if (file_exists($this->i_elementdir . $filename)) {
                         $parts = pathinfo($filename);
                         $subpath = $parts['dirname'];
                         if ($subpath != '' && $subpath != '.' && $subpath != '..') {
                             //echo '<br />'. 'Deleting'  .': '. $this->i_elementdir . $subpath;
                             $result = $adminFS->deldir(_cbPathName($this->i_elementdir . $subpath . '/'));
                         } else {
                             //echo '<br />'. 'Deleting'  .': '. $this->i_elementdir . $filename;
                             $result = $adminFS->unlink(_cbPathName($this->i_elementdir . $filename, false));
                         }
                         //echo intval( $result );
                     }
                 }
                 // Are there any SQL queries??
                 $query_element =& $cbInstallXML->getElementByPath('uninstall/queries');
                 if ($query_element !== false) {
                     foreach ($query_element->children() as $query) {
                         $_CB_database->setQuery(trim($query->data()));
                         if (!$_CB_database->query()) {
                             $this->setError(1, "SQL Error " . $_CB_database->stderr(true));
                             return false;
                         }
                     }
                 }
                 // Are there any Database statements ??
                 $db =& $cbInstallXML->getElementByPath('database');
                 if ($db !== false && count($db->children()) > 0) {
                     cbimport('cb.sql.upgrader');
                     $sqlUpgrader = new CBSQLupgrader($_CB_database, false);
                     //$sqlUpgrader->setDryRun( true );
                     $success = $sqlUpgrader->checkXmlDatabaseDescription($db, $cleanedMainFileName, 'drop', null);
                     /*
                     var_dump( $success );
                     echo "<br>\nERRORS: " . $sqlUpgrader->getErrors( "<br /><br />\n\n", "<br />\n" );
                     echo "<br>\nLOGS: " . $sqlUpgrader->getLogs( "<br /><br />\n\n", "<br />\n" );
                     exit;
                     */
                     if (!$success) {
                         $this->setError(1, "Plugin database XML SQL Error " . $sqlUpgrader->getErrors());
                         return false;
                     }
                 }
                 // Delete tabs and private fields of plugin:
                 $this->deleteTabAndFieldsOfPlugin($id);
                 // remove XML file from front
                 $xmlRemoveResult = $adminFS->unlink(_cbPathName($this->i_installfilename, false));
                 $filesRemoveResult = true;
                 /*					// define folders that should not be removed
                 					$sysFolders = array(
                 					'content',
                 					'search'
                 					);
                 					if ( ! in_array( $row->folder, $sysFolders ) ) {
                 */
                 // delete the non-system folders if empty
                 if (count(cbReadDirectory($this->i_elementdir)) < 1) {
                     $filesRemoveResult = $adminFS->deldir($this->i_elementdir);
                 }
                 /*					}
                 */
                 if (!$xmlRemoveResult) {
                     HTML_comprofiler::showInstallMessage('Could not delete XML file: ' . _cbPathName($this->i_installfilename, false) . ' due to permission error. Please remove manually.', 'Uninstall -  warning', $this->returnTo($option, 'showPlugins'));
                 }
                 if (!$filesRemoveResult) {
                     HTML_comprofiler::showInstallMessage('Could not delete directory: ' . $this->i_elementdir . ' due to permission error. Please remove manually.', 'Uninstall -  warning', $this->returnTo($option, 'showPlugins'));
                 }
             }
         }
         $_CB_database->setQuery("DELETE FROM #__comprofiler_plugin WHERE id = " . (int) $id);
         if (!$_CB_database->query()) {
             $msg = $_CB_database->stderr;
             HTML_comprofiler::showInstallMessage('Cannot delete plugin database entry due to error: ' . $msg, 'Uninstall -  error', $this->returnTo($option, 'showPlugins'));
             return false;
         }
         if ($this->i_xmldocument !== null && $db !== false && count($db->children()) > 0) {
             HTML_comprofiler::fixcbdbShowResults($sqlUpgrader, true, false, $success, array(), array(), $this->elementName(), 1, false);
         }
         return true;
     }
     return false;
 }
function finishInstallation($option)
{
    global $_CB_framework, $ueConfig, $task;
    // Try extending time, as unziping/ftping took already quite some... :
    @set_time_limit(240);
    HTML_comprofiler::secureAboveForm('finishInstallation');
    $tgzFile = $_CB_framework->getCfg('absolute_path') . '/administrator/components/com_comprofiler/pluginsfiles.tgz';
    $installerFile = $_CB_framework->getCfg('absolute_path') . '/administrator/components/com_comprofiler/';
    if (file_exists($installerFile . 'comprofiler.xml')) {
        $installerFile .= 'comprofiler.xml';
    } elseif (file_exists($installerFile . 'comprofilej.xml')) {
        $installerFile .= 'comprofilej.xml';
    } elseif (file_exists($installerFile . 'comprofileg.xml')) {
        $installerFile .= 'comprofileg.xml';
    }
    if (!file_exists($tgzFile)) {
        echo _UE_NOT_AUTHORIZED;
        return;
    }
    $installer = new cbInstallerPlugin();
    $client = 2;
    // Check that the zlib is available
    if (!extension_loaded('zlib')) {
        HTML_comprofiler::showInstallMessage(CBTxt::T('The installer cannot continue before zlib is installed'), CBTxt::T('Installer - Error'), $installer->returnTo($option, $task, $client));
        exit;
    }
    if (!$installer->upload($tgzFile, true, false)) {
        HTML_comprofiler::showInstallMessage(sprintf(CBTxt::T("Uncompressing %s failed."), $tgzFile), CBTxt::T('Installer - Error'), $installer->returnTo($option, '', 2));
        exit;
    }
    $installFrom = $installer->installDir();
    $installTo = $_CB_framework->getCfg('absolute_path') . '/components/com_comprofiler/plugin';
    $filesList = cbReadDirectory($installFrom, '.', true);
    // create directories and remove them from file list:
    if (!$installer->mosMakePath(dirname($installTo) . '/', 'plugin')) {
        HTML_comprofiler::showInstallMessage(sprintf(CBTxt::T('Failed to create directory "%s"'), $installTo . '/plugin'), CBTxt::T('Installer - Error'), $installer->returnTo($option, '', 2));
        exit;
    }
    foreach ($filesList as $k => $file) {
        if (basename($file) != $file) {
            $newdir = dirname($file);
            if (!$installer->mosMakePath($installTo . '/', $newdir)) {
                HTML_comprofiler::showInstallMessage(sprintf(CBTxt::T('Failed to create directory "%s"'), $installTo . '/' . $newdir), CBTxt::T('Installer - Error'), $installer->returnTo($option, '', 2));
                exit;
            }
        }
        if (!is_file($installFrom . '/' . $file)) {
            unset($filesList[$k]);
        }
    }
    $result = $installer->copyFiles($installFrom, $installTo, $filesList, true);
    if ($result === false) {
        HTML_comprofiler::showInstallMessage(sprintf(CBTxt::T("Copying plugin files failed with error: %s"), $installer->getError()), CBTxt::T('Installer - Error'), $installer->returnTo($option, '', 2));
        exit;
    }
    $adminFS =& cbAdminFileSystem::getInstance();
    $result = $adminFS->deldir(_cbPathName($installFrom . '/'));
    if ($result === false) {
        HTML_comprofiler::showInstallMessage(CBTxt::T('Deleting expanded tgz file directory failed with an error.'), CBTxt::T('Installer - Error'), $installer->returnTo($option, '', 2));
    }
    $tgzFileOS = _cbPathName($tgzFile, false);
    $result = $adminFS->unlink($tgzFileOS);
    if ($result === false) {
        HTML_comprofiler::showInstallMessage(sprintf(CBTxt::T("Deleting file %s failed with an error."), $tgzFileOS), CBTxt::T('Installer - Error'), $installer->returnTo($option, '', 2));
    }
    // adapt published fields to global CB config (regarding name type)
    _cbAdaptNameFieldsPublished($ueConfig);
    $htmlToDisplay = $_CB_framework->getUserState('com_comprofiler_install');
    // clears the session buffer memory after installaion done:
    $_CB_framework->setUserState('com_comprofiler_install', '');
    cbimport('cb.xml.simplexml');
    $installerXml = new CBSimpleXMLElement(file_get_contents($installerFile));
    if (is_object($installerXml)) {
        $description = $installerXml->getElementByPath('description');
        if ($description !== false) {
            echo '<h2>' . $description->data() . '</h2>';
        }
    }
    echo $htmlToDisplay;
    ?>
<div style="font-weight:bold;font-size:110%;background:#ffffe4;border:2px green solid;padding:5px;margin-bottom:20px;"><font color="green"><?php 
    echo CBTxt::T('Second and last installation step of Community Builder Component (comprofiler) done successfully.');
    ?>
</font></div><br />
<div style="font-weight:bold;font-size:125%;background:#ffffe4;border:2px green solid;padding:5px;">
<font color="green"><b><?php 
    echo CBTxt::T('Installation finished. Important: Please read README.TXT and installation manual for further settings.');
    ?>
 <br /><br /><?php 
    echo CBTxt::T('We also have a PDF installation guide as well as a complete documentation available on');
    ?>
 <a href="http://www.joomlapolis.com">www.joomlapolis.com</a> <?php 
    echo CBTxt::T('which will help you making the most out of your Community Builder installation, while supporting this project, as well as plugins and templates.');
    ?>
</b></font>
</div>
<?php 
    $_CB_framework->setUserState("com_comprofiler_install", '');
}
function writableCell( $folder, $useAdminFs = true ) {
	global $_CB_framework;

	$path					=	$_CB_framework->getCfg('absolute_path') . '/' . $folder;

	if ( $useAdminFs ) {
		cbimport( 'cb.adminfilesystem' );
		$adminFS			=&	cbAdminFileSystem::getInstance();
		if ( ! $adminFS->isUsingStandardPHP() ) {
			return;
		}
		// not yet implemented in ftp layer $writable			=	( $adminFS->file_exists( $path ) && $adminFS->is_writable( $path ) );
	}
	$writable				=	is_writable( $path );
	echo '<tr>';
	echo '<td class="item">' . $folder . '/</td>';
	echo '<td align="left">';
	echo $writable ? '<b><font color="green">' . htmlspecialchars( CBTxt::T('Writeable') ) . '</font></b>' : '<b><font color="red">' . htmlspecialchars( CBTxt::T('Unwriteable') ) . '</font></b>' . '</td>';
	echo '</tr>';
}
function com_install() {
  global $_CB_database, $_CB_framework;

	if ( version_compare( phpversion(), '5.0.0', '<' ) ) {
		echo '<div class="cbError error" style="font-size:120%;color:red;font-weight:bold;margin-bottom:20px;">' . htmlspecialchars( sprintf( "As stated in README and prerequisites list, PHP Version %s, which is obsolete since 2008-08-08 and insecure, is not compatible with %s: Please upgrade to PHP %s or greater (CB is also compatible with PHP 5.3.x) as soon as possible.", phpversion(), 'Community Builder', sprintf( "at least version %s, recommended version %s", '5.0.0', '5.2.6' ) ) ) . '</div>';
		echo '<div class="cbError error" style="font-size:140%;color:red;font-weight:bold;">' . htmlspecialchars( sprintf( 'Installation failed. In all cases, please require your hoster to upgrade your PHP version as soon as possible.' ) ) . '</div>';
		return;
	}

	ob_start();

  # Show installation result to user
  ?>
 <div style="text-align:left;">
  <table width="100%" border="0">
    <tr>
      <td>
	<img src="../components/com_comprofiler/images/smcblogo.gif" />
      </td>
    </tr>
    <tr>
      <td>
    	<br />Copyright 2004-2011 MamboJoe/JoomlaJoe, Beat and CB team on joomlapolis.com . This component is released under the GNU/GPL version 2 License. All copyright statements must be kept. Derivate work must prominently duly acknowledge original work and include visible online links. Official site: <a href="http://www.joomlapolis.com">www.joomlapolis.com</a>
    	<br />
      </td>
    </tr>
    <tr>
      <td background="F0F0F0" colspan="2">
        <code>Installation Process:<br />
        <?php

      # Set up new icons for admin menu
      if ( checkJversion() <= 1 ) {
          // echo "Start correcting icons in administration backend.<br />";
          if ( checkJversion() >= 1 ) {
	          $_CB_database->setQuery("UPDATE #__components SET admin_menu_img='js/ThemeOffice/static.png' WHERE admin_menu_link='option=com_comprofiler&task=showLists'");
          } else {
	          $_CB_database->setQuery("UPDATE #__components SET admin_menu_img='js/ThemeOffice/content.png' WHERE admin_menu_link='option=com_comprofiler&task=showLists'");
          }
          $iconresult[0] = $_CB_database->query();
          $_CB_database->setQuery("UPDATE #__components SET admin_menu_img='js/ThemeOffice/content.png' WHERE admin_menu_link='option=com_comprofiler&task=showField'");
          $iconresult[1] = $_CB_database->query();
          if ( checkJversion() >= 1 ) {
	          $_CB_database->setQuery("UPDATE #__components SET admin_menu_img='js/ThemeOffice/article.png' WHERE admin_menu_link='option=com_comprofiler&task=showTab'");
          } else {
	          $_CB_database->setQuery("UPDATE #__components SET admin_menu_img='js/ThemeOffice/content.png' WHERE admin_menu_link='option=com_comprofiler&task=showTab'");
          }
          $iconresult[2] = $_CB_database->query();
          $_CB_database->setQuery("UPDATE #__components SET admin_menu_img='js/ThemeOffice/config.png' WHERE admin_menu_link='option=com_comprofiler&task=showconfig'");
          $iconresult[3] = $_CB_database->query();
          if ( checkJversion() >= 1 ) {
	          $_CB_database->setQuery("UPDATE #__components SET admin_menu_img='js/ThemeOffice/user.png' WHERE admin_menu_link='option=com_comprofiler&task=showusers'");
          } else {
	          $_CB_database->setQuery("UPDATE #__components SET admin_menu_img='js/ThemeOffice/users.png' WHERE admin_menu_link='option=com_comprofiler&task=showusers'");
          }
          $iconresult[4] = $_CB_database->query();
          if ( checkJversion() >= 1 ) {
			  $_CB_database->setQuery("UPDATE #__components SET admin_menu_img='js/ThemeOffice/plugin.png' WHERE admin_menu_link='option=com_comprofiler&task=showPlugins'");
          } else {
			  $_CB_database->setQuery("UPDATE #__components SET admin_menu_img='js/ThemeOffice/install.png' WHERE admin_menu_link='option=com_comprofiler&task=showPlugins'");
          }
          $iconresult[5] = $_CB_database->query();
/* Despite numerous abstractions-level, the name of the component isn't taken from SQL but from xml <name> , same field as used to find comprofiler, so we can't display nicely:
          if ( checkJversion() >= 1 ) {
	          $_CB_database->setQuery("UPDATE #__components SET name='Community Builder' WHERE admin_menu_link='option=com_comprofiler'");
              $iconresult[6] = $_CB_database->query();
          }
*/
         foreach ($iconresult as $i=>$icresult) {
            if ($icresult) {
              // echo "<font color='green'>FINISHED:</font> Image of menu entry $i has been corrected.<br />";
            } else {
              echo "<font color='red'>ERROR:</font> Image of administration menu entry $i could not be corrected.<br />";
            }
          }
		 $_CB_database->setQuery("SELECT COUNT(*) FROM #__components WHERE link = 'option=com_comprofiler'");
	         $components = $_CB_database->loadresult();
		 IF($components >= 1) {
			$_CB_database->setQuery("SELECT id FROM #__components WHERE link = 'option=com_comprofiler' ORDER BY id DESC", 0, 1);
	         	$comid = (int) $_CB_database->loadresult();
			$_CB_database->setQuery("DELETE FROM #__components WHERE link  = 'option=com_comprofiler' AND id != $comid  ");
	         	$_CB_database->query();
			$_CB_database->setQuery("DELETE FROM #__components WHERE #__components.option = 'com_comprofiler' AND parent != $comid AND id != $comid ");
	         	$_CB_database->query();
	        // update front-end menus component id:
	    		$_CB_database->setQuery("UPDATE #__menu SET componentid=" . $comid . " WHERE type = 'component' AND link LIKE '%option=com_comprofiler%'");
	         	$_CB_database->query();
	              	echo "<font color='green'>Administrator and frontend menus corrected.</font><br />";
		}
    }

	//Manage Database Upgrades
	$MCBUpgrades = array();

	//Beta 3 Upgrade
	$MCBUpgrades[0]['test']		=	array( 'default', '#__comprofiler_lists' );
	$MCBUpgrades[0]['updates'][0] = "ALTER TABLE `#__comprofiler_lists`"
					."\n ADD `default` TINYINT( 1 ) DEFAULT '0' NOT NULL,"
					."\n ADD `usergroupids` VARCHAR( 255 ),"
					."\n ADD `sortfields` VARCHAR( 255 ),"
					."\n ADD `ordering` INT( 11 ) DEFAULT '0' NOT NULL AFTER `published`";
	$MCBUpgrades[0]['updates'][1] = "UPDATE #__comprofiler_lists SET `default`=1 WHERE published =1";
	$MCBUpgrades[0]['updates'][2] = "UPDATE #__comprofiler_lists SET usergroupids = '29, 18, 19, 20, 21, 30, 23, 24, 25', sortfields = '`username` ASC'";
	$MCBUpgrades[0]['updates'][3] = "ALTER TABLE `#__comprofiler` ADD `acceptedterms` TINYINT( 1 ) DEFAULT '0' NOT NULL AFTER `bannedreason`";
	$MCBUpgrades[0]['message'] = "1.0 Beta 2 to 1.0 Beta 3";


	//Beta 4 Upgrade
	$MCBUpgrades[1]['test']		=	array( 'firstname', '#__comprofiler' );
	$MCBUpgrades[1]['updates'][0] = "ALTER TABLE #__comprofiler ADD `firstname` VARCHAR( 100 ) AFTER `user_id` ,"
					."\n ADD `middlename` VARCHAR( 100 ) AFTER `firstname` ,"
					."\n ADD `lastname` VARCHAR( 100 ) AFTER `middlename` ";
	$MCBUpgrades[1]['updates'][1] = "ALTER TABLE `#__comprofiler_fields` ADD `readonly` TINYINT( 1 ) DEFAULT '0' NOT NULL AFTER `profile`";
	$MCBUpgrades[1]['updates'][3] = "ALTER TABLE `#__comprofiler_tabs` ADD `width` VARCHAR( 10 ) DEFAULT '.5' NOT NULL AFTER `ordering` ,"
					."\n ADD `enabled` TINYINT( 1 ) DEFAULT '1' NOT NULL AFTER `width` ,"
					."\n ADD `plugin` VARCHAR( 255 ) DEFAULT NULL AFTER `enabled`" ;

	$MCBUpgrades[1]['message'] = "1.0 Beta 3 to 1.0 Beta 4";

	//RC 1 Upgrade
	$MCBUpgrades[2]['test']		=	array( 'fields', '#__comprofiler_tabs' );
	$MCBUpgrades[2]['updates'][0] = "ALTER TABLE #__comprofiler_tabs ADD `plugin_include` VARCHAR( 255 ) AFTER `plugin` ,"
					."\n ADD `fields` TINYINT( 1 ) DEFAULT '1' NOT NULL AFTER `plugin_include` ";
	$MCBUpgrades[2]['updates'][1] = "INSERT INTO `#__comprofiler_tabs` ( `title`, `description`, `ordering`, `width`, `enabled`, `plugin`, `plugin_include`, `fields`, `sys`) VALUES "
					."\n ( '_UE_CONTACT_INFO_HEADER', '', -4, '1', 1, 'getContactTab', NULL, 1, 1),"
					."\n ( '_UE_AUTHORTAB', '', -3, '1', 0, 'getAuthorTab', NULL, 0, 1),"
					."\n ( '_UE_FORUMTAB', '', -2, '1', 0, 'getForumTab', NULL, 0, 1),"
					."\n ( '_UE_BLOGTAB', '', -1, '1', 0, 'getBlogTab', NULL, 0, 1);";
	$MCBUpgrades[2]['updates'][2] = "ALTER TABLE `#__comprofiler_lists` ADD `filterfields` VARCHAR( 255 ) AFTER `sortfields`;";
	$MCBUpgrades[2]['message'] = "1.0 Beta 4 to 1.0 RC 1";

	//RC 2 Upgrade
	$MCBUpgrades[3]['test']		=	array( 'description', '#__comprofiler_fields' );
	$MCBUpgrades[3]['updates'][0] = "ALTER TABLE `#__comprofiler_fields` ADD `description` MEDIUMTEXT  NOT NULL default '' AFTER `title` ";
	$MCBUpgrades[3]['updates'][1] = "ALTER TABLE `#__comprofiler_fields` CHANGE `title` `title` VARCHAR( 255 ) NOT NULL";
	$MCBUpgrades[3]['updates'][2] = "INSERT INTO `#__comprofiler_tabs` (`title`, `description`, `ordering`, `width`, `enabled`, `plugin`, `plugin_include`, `fields`, `sys`) VALUES "
					."\n ( '_UE_CONNECTION', '',99, '1', 0, 'getConnectionTab', NULL, 0, 1);";
	$MCBUpgrades[3]['updates'][3] = "INSERT INTO `#__comprofiler_tabs` (`title`, `description`, `ordering`, `width`, `enabled`, `plugin`, `plugin_include`, `fields`, `sys`) VALUES "
					."\n ( '_UE_NEWSLETTER_HEADER', '_UE_NEWSLETTER_INTRODCUTION', 99, '1', 0, 'getNewslettersTab', NULL, 0, 1);";
	$MCBUpgrades[3]['updates'][4] = "UPDATE `#__comprofiler_tabs` SET sys=2, enabled=1 WHERE plugin='getContactTab' ";
	$MCBUpgrades[3]['updates'][5] = "ALTER TABLE `#__comprofiler_lists` ADD `useraccessgroupid` INT( 9 ) DEFAULT '18' NOT NULL AFTER `usergroupids` ";
	$MCBUpgrades[3]['message'] = "1.0 RC 1 to 1.0 RC 2 part 1";

	$MCBUpgrades[4]['test']		=	array( 'params', '#__comprofiler_tabs' );
	$MCBUpgrades[4]['updates'][0] = "ALTER TABLE `#__comprofiler_tabs` CHANGE `plugin` `pluginclass` VARCHAR( 255 ) DEFAULT NULL , "
					."\n CHANGE `plugin_include` `pluginid` INT( 11 ) DEFAULT NULL ";
	$MCBUpgrades[4]['updates'][1] = "ALTER TABLE `#__comprofiler_tabs` ADD `params` MEDIUMTEXT AFTER `fields` ;";
	$MCBUpgrades[4]['updates'][2] = "ALTER TABLE `#__comprofiler_fields` ADD `pluginid` INT( 11 ) , "
					."\n ADD `params` MEDIUMTEXT; ";
	$MCBUpgrades[4]['updates'][3] = "UPDATE `#__comprofiler_tabs` SET pluginid=1 WHERE pluginclass='getContactTab' ";
	$MCBUpgrades[4]['updates'][4] = "UPDATE `#__comprofiler_tabs` SET pluginid=1 WHERE pluginclass='getConnectionTab' ";
	$MCBUpgrades[4]['updates'][5] = "UPDATE `#__comprofiler_tabs` SET pluginid=3 WHERE pluginclass='getAuthorTab' ";
	$MCBUpgrades[4]['updates'][6] = "UPDATE `#__comprofiler_tabs` SET pluginid=4 WHERE pluginclass='getForumTab' ";
	$MCBUpgrades[4]['updates'][7] = "UPDATE `#__comprofiler_tabs` SET pluginid=5 WHERE pluginclass='getBlogTab' ";
	$MCBUpgrades[4]['updates'][8] = "UPDATE `#__comprofiler_tabs` SET pluginid=6 WHERE pluginclass='getNewslettersTab' ";
	$MCBUpgrades[4]['message'] = "1.0 RC 1 to 1.0 RC 2 part 2";

	$MCBUpgrades[5]['test']		=	array( 'position', '#__comprofiler_tabs' );
	$MCBUpgrades[5]['updates'][1] = "ALTER TABLE `#__comprofiler_tabs`"
					."\n ADD `position` VARCHAR( 255 ) DEFAULT '' NOT NULL,"
					."\n ADD `displaytype` VARCHAR( 255 ) DEFAULT '' NOT NULL AFTER `sys`";
	$MCBUpgrades[5]['updates'][2] = "UPDATE `#__comprofiler_tabs` SET position='cb_tabmain', displaytype='tab' ";
	$MCBUpgrades[5]['updates'][3] = "INSERT INTO `#__comprofiler_tabs` (`title`, `description`, `ordering`, `width`, `enabled`, `pluginclass`, `pluginid`, `fields`, `sys`, `position`, `displaytype`) VALUES "
					."\n ( '_UE_MENU', '', -10, '1', 1, 'getMenuTab', 14, 0, 1, 'cb_head', 'html'),"
					."\n ( '_UE_CONNECTIONPATHS', '', -9, '1', 1, 'getConnectionPathsTab', 2, 0, 1, 'cb_head', 'html'),"
					."\n ( '_UE_PROFILE_PAGE_TITLE', '', -8, '1', 1, 'getPageTitleTab', 1, 0, 1, 'cb_head', 'html'),"
					."\n ( '_UE_PORTRAIT', '', -7, '1', 1, 'getPortraitTab', 1, 0, 1, 'cb_middle', 'html'),"
					."\n ( '_UE_USER_STATUS', '', -6, '.5', 1, 'getStatusTab', 14, 0, 1, 'cb_right', 'html'),"
					."\n ( '_UE_PMSTAB', '', -5, '.5', 0, 'getmypmsproTab', 15, 0, 1, 'cb_right', 'html');";
	$MCBUpgrades[5]['updates'][5] = "UPDATE `#__comprofiler_tabs` SET pluginid=2 WHERE pluginclass='getConnectionTab' ";
	$MCBUpgrades[5]['updates'][6] = "ALTER TABLE `#__comprofiler_members` ADD `reason` MEDIUMTEXT default NULL AFTER `membersince` ";
	$MCBUpgrades[5]['updates'][7] = "UPDATE `#__comprofiler_tabs` SET `pluginclass`=NULL, `pluginid`=NULL WHERE `pluginclass` != 'getContactTab' AND `fields` = 1";
	// this is from build 10 to 11:
	// changed back sys=3 -> 1 for _UE_MENU and _UE_USER_STATUS
	// $MCBUpgrades[5]['updates'][8] = "ALTER TABLE `#__comprofiler_fields` CHANGE `default` `default` MEDIUMTEXT DEFAULT NULL";
	// this last one is only for upgrades from build 8 to 9.
	$MCBUpgrades[5]['message'] = "1.0 RC 1 to 1.0 RC 2 part 3";

	// from 1.0.1 to 1.0.2: (includes RC2 to 1.0):
	$MCBUpgrades[6]['test']		=	array( 'cbactivation', '#__comprofiler' );
	// from RC2 to 1.0 stable:	in fact did it always up to now, since we can alter tables indefinitely.
	$MCBUpgrades[6]['updates'][] = "ALTER TABLE `#__comprofiler_fields` CHANGE `default` `default` MEDIUMTEXT DEFAULT NULL;";
	$MCBUpgrades[6]['updates'][] = "ALTER TABLE `#__comprofiler_fields` CHANGE `tabid` `tabid` int(11) DEFAULT NULL;";
	$MCBUpgrades[6]['updates'][] = "UPDATE `#__users` SET usertype='Registered' WHERE usertype='';";	// fix effect of previous bug in CB registration
	// $MCBUpgrades[6]['message'] = "1.0 RC 2 to 1.0 stable";
	// from 1.0.1 to 1.0.2: (includes RC2 to 1.0):
	$MCBUpgrades[6]['updates'][] = "UPDATE `#__comprofiler_fields` SET `table`='#__users' WHERE name='email';";
	$MCBUpgrades[6]['updates'][] = "UPDATE `#__comprofiler_fields` SET `table`='#__users' WHERE name='lastvisitDate';";
	$MCBUpgrades[6]['updates'][] = "UPDATE `#__comprofiler_fields` SET `table`='#__users' WHERE name='registerDate';";
	$MCBUpgrades[6]['updates'][] = "ALTER TABLE #__comprofiler ADD `registeripaddr` VARCHAR( 50 ) DEFAULT '' NOT NULL AFTER `lastupdatedate`;";
	$MCBUpgrades[6]['updates'][] = "ALTER TABLE #__comprofiler ADD `cbactivation` VARCHAR( 50 ) DEFAULT '' NOT NULL AFTER `registeripaddr`;";
	$MCBUpgrades[6]['updates'][] = "ALTER TABLE #__comprofiler ADD `message_last_sent` DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00' AFTER `hits`;";
	$MCBUpgrades[6]['updates'][] = "ALTER TABLE #__comprofiler ADD `message_number_sent` INT( 11 ) DEFAULT 0 NOT NULL AFTER `message_last_sent`;";
	$MCBUpgrades[6]['updates'][] = "ALTER TABLE `#__comprofiler_field_values` ADD INDEX fieldid_ordering (`fieldid`, `ordering` );";
	$MCBUpgrades[6]['updates'][] = "ALTER TABLE `#__comprofiler_fields` ADD INDEX `tabid_pub_prof_order` ( `tabid` , `published` , `profile` , `ordering` );";
	$MCBUpgrades[6]['updates'][] = "ALTER TABLE `#__comprofiler_fields` ADD INDEX `readonly_published_tabid` ( `readonly` , `published` , `tabid` );";
	$MCBUpgrades[6]['updates'][] = "ALTER TABLE `#__comprofiler_fields` ADD INDEX `registration_published_order` ( `registration` , `published` , `ordering` );";
	$MCBUpgrades[6]['updates'][] = "ALTER TABLE `#__comprofiler_members` ADD INDEX `pamr` ( `pending` , `accepted` , `memberid` , `referenceid` );";
	$MCBUpgrades[6]['updates'][] = "ALTER TABLE `#__comprofiler_members` ADD INDEX `aprm` ( `accepted` , `pending` , `referenceid` , `memberid` );";
	$MCBUpgrades[6]['updates'][] = "ALTER TABLE `#__comprofiler_members` ADD INDEX `membrefid` ( `memberid` , `referenceid` );";
	$MCBUpgrades[6]['updates'][] = "ALTER TABLE `#__comprofiler_plugin` ADD INDEX `type_pub_order` ( `type` , `published` , `ordering` );";
	$MCBUpgrades[6]['updates'][] = "ALTER TABLE `#__comprofiler_tabs` ADD INDEX `enabled_position_ordering` ( `enabled` , `position` , `ordering` );";
	$MCBUpgrades[6]['updates'][] = "ALTER TABLE `#__comprofiler_lists` ADD INDEX `pub_ordering` ( `published` , `ordering` );";
	$MCBUpgrades[6]['updates'][] = "ALTER TABLE `#__comprofiler_lists` ADD INDEX `default_published` ( `default` , `published` );";
	$MCBUpgrades[6]['updates'][] = "ALTER TABLE `#__comprofiler_userreports` ADD INDEX `status_user_date` ( `reportedstatus` , `reporteduser` , `reportedondate` );";
	$MCBUpgrades[6]['updates'][] = "ALTER TABLE `#__comprofiler_userreports` ADD INDEX `reportedbyuser_ondate` ( `reportedbyuser` , `reportedondate` );";
	$MCBUpgrades[6]['updates'][] = "ALTER TABLE `#__comprofiler_views` ADD INDEX `lastview` ( `lastview` );";
	$MCBUpgrades[6]['updates'][] = "ALTER TABLE `#__comprofiler_views` ADD INDEX `profile_id_lastview` (`profile_id`,`lastview`);";
	$MCBUpgrades[6]['updates'][] = "UPDATE `#__comprofiler` SET `user_id`=`id` WHERE 1>0;";	// fix in case something corrupt for unique key
	$MCBUpgrades[6]['updates'][] = "ALTER TABLE `#__comprofiler` ADD UNIQUE KEY user_id (`user_id`);";
	$MCBUpgrades[6]['updates'][] = "ALTER TABLE `#__comprofiler` ADD INDEX `apprconfbanid` ( `approved` , `confirmed` , `banned` , `id` );";
	$MCBUpgrades[6]['updates'][] = "ALTER TABLE `#__comprofiler` ADD INDEX `avatappr_apr_conf_ban_avatar` ( `avatarapproved` , `approved` , `confirmed` , `banned` , `avatar` );";
	$MCBUpgrades[6]['updates'][] = "ALTER TABLE `#__comprofiler` ADD INDEX `lastupdatedate` ( `lastupdatedate` );";
	$MCBUpgrades[6]['message'] = "1.0 RC 2, 1.0 and 1.0.1 to 1.0.2";

	// from 1.0.2 to 1.1:
	$MCBUpgrades[7]['test']		=	array( 'ordering_register', '#__comprofiler_tabs' );
	$MCBUpgrades[7]['updates'][] = "ALTER TABLE `#__comprofiler_plugin` ADD `backend_menu` VARCHAR(255) NOT NULL DEFAULT '' AFTER `folder`;";
	$MCBUpgrades[7]['updates'][] = "ALTER TABLE `#__comprofiler_tabs` ADD `ordering_register` int(11) NOT NULL DEFAULT 10 AFTER `ordering`;";
	$MCBUpgrades[7]['updates'][] = "ALTER TABLE `#__comprofiler_tabs` ADD `useraccessgroupid` int(9) DEFAULT -2 NOT NULL AFTER `position`;";
	$MCBUpgrades[7]['updates'][] = "ALTER TABLE `#__comprofiler_tabs` ADD INDEX `orderreg_enabled_pos_order` ( `enabled` , `ordering_register` , `position` , `ordering` );";
	$MCBUpgrades[7]['updates'][] = "ALTER TABLE `#__comprofiler` ADD `unbannedby` int(11) default NULL AFTER `bannedby`;";
	$MCBUpgrades[7]['updates'][] = "ALTER TABLE `#__comprofiler` ADD `unbanneddate` datetime default NULL AFTER `banneddate`;";
	$MCBUpgrades[7]['updates'][] = "ALTER TABLE `#__comprofiler_field_values` CHANGE `fieldtitle` `fieldtitle` VARCHAR(255) NOT NULL DEFAULT '';";
	$MCBUpgrades[7]['message'] = "1.0.2 to 1.1";

	// from 1.1 to 1.2: uses new method...

	//Apply Upgrades
	foreach ($MCBUpgrades AS $MCBUpgrade) {
		//if it fails test then apply upgrade
		if ( ! cbInstaller_field_exists( $MCBUpgrade['test'][1], $MCBUpgrade['test'][0] ) ) {
			foreach( $MCBUpgrade['updates'] as $MCBScript ) {
				$_CB_database->setQuery( $MCBScript );
				if( ! $_CB_database->query() ) {
					//Upgrade failed
					print("<font color=red>".$MCBUpgrade['message']." failed! SQL error:" . $_CB_database->stderr(true)."</font><br />");
					// return;
				}
			}
			//Upgrade was successful
			print "<font color=green>".$MCBUpgrade['message']." Upgrade Applied Successfully.</font><br />";
		}
	}

	$sql="SELECT listid FROM #__comprofiler_lists ORDER BY ordering asc, published desc";
	$_CB_database->setQuery($sql);
	$lists = $_CB_database->loadObjectList();
	$order=0;
	if ( ! $_CB_database->getErrorNum() ) {
		foreach($lists AS $list) {
			$_CB_database->setQuery("UPDATE #__comprofiler_lists SET ordering = $order WHERE listid='".$list->listid."'");
			$_CB_database->query();
			$order++;
		}
	}

	// fixing the tabid of installs before CB 1.0 RC 2:

	$dbChecker		=	new CBdbChecker( $_CB_database );
	$result			=	$dbChecker->checkCBMandatoryDb( false );
	if ( ! $result ) {
		$dbChecker		=	new CBdbChecker( $_CB_database );
		$result			=	$dbChecker->checkCBMandatoryDb( true, false );

		if ( $result == true ) {
			echo "<p><font color=green>Automatic database fixes of old core tabs and fields applied successfully.</font></p>";
		} elseif ( is_string( $result ) ) {
			echo "<p><font color=red>" . $result . "</font></p>";
		} else {
			echo "<div style='color:red;'>";
			echo "<h3><font color=red>Database fixing errors:</font></h3>";
			$errors		=	$dbChecker->getErrors( false );
			foreach ( $errors as $err ) {
				echo '<div style="font-size:115%">' . $err[0];
				if ( $err[1] ) {
					echo '<div style="font-size:90%">' . $err[1] . '</div>';
				}
				echo '</div>';
			}
			echo "</div>";
		}
		if ( ( checkJversion() < 1 ) || ( $_CB_framework->getCfg( 'session_handler' ) != 'database' ) ) {
			// joomla 1.5 and 1.6 database session storage limited to 20kb, so do not display details in that case:
			$logs			=	$dbChecker->getLogs( false );
			if ( count( $logs ) > 0 ) {
				echo "<div><a href='#' id='cbdetailsLinkShowOld' onclick=\"document.getElementById('cbdetailsdbcheckOld').style.display='';return false;\">Click to Show details</a></div>";
				echo "<div id='cbdetailsdbcheckOld' style='color:green;display:none;'>";
				foreach ( $logs as $err ) {
					echo '<div>' . $err[0];
					if ( $err[1] ) {
						echo '<div style="font-size:90%">' . $err[1] . '</div>';
					}
					echo '</div>';
				}
				echo '</div>';
			}
		}
	}
	// now missing core tabs will be inserted in the new 1.2 upgrader in next step:
	// from CB 1.2 upwards:

	$dbChecker		=	new CBdbChecker( $_CB_database );
	$result			=	$dbChecker->checkDatabase( true, false );
	if ( $result == true ) {
		echo "<p><font color=green>Automatic database upgrade to current version applied successfully.</font></p>";
	} elseif ( is_string( $result ) ) {
		echo "<p><font color=red>" . $result . "</font></p>";
	} else {
		echo "<div style='color:red;'>";
		echo "<h3><font color=red>Database fixing errors:</font></h3>";
		$errors		=	$dbChecker->getErrors( false );
		foreach ( $errors as $err ) {
			echo '<div style="font-size:115%">' . $err[0];
			if ( $err[1] ) {
				echo '<div style="font-size:90%">' . $err[1] . '</div>';
			}
			echo '</div>';
		}
		echo "</div>";
	}
	if ( ( checkJversion() < 1 ) || ( $_CB_framework->getCfg( 'session_handler' ) != 'database' ) ) {
		// joomla 1.5 and 1.6 database session storage limited to 20kb, so do not display details in that case:
		$logs			=	$dbChecker->getLogs( false );
		if ( count( $logs ) > 0 ) {
			echo "<div><a href='#' id='cbdetailsLinkShow' onclick=\"document.getElementById('cbdetailsdbcheck').style.display='';return false;\">Click to Show details</a></div>";
			echo "<div id='cbdetailsdbcheck' style='color:green;display:none;'>";
			foreach ( $logs as $err ) {
				if ( $err[1] ) {
					// display only queries having effect (joomla database session storage limited to 20kb!):
					echo '<div>' . $err[0];
					echo '<div style="font-size:90%">' . $err[1] . '</div>';
					echo '</div>';
				}
			}
			echo '</div>';
		}
	}
	echo "<p>Core CB database upgrades done. If all lines above are in green, database upgrade completed successfully. Otherwise, please report exact errors and queries to forum, and try checking database again in components : community builder : tools : check database.</p>";

        ?>
		</code>
      </td>
    </tr>
    <tr>
	<td>
	<?php

$adminFS			=&	cbAdminFileSystem::getInstance();
$imagesPath			=	$_CB_framework->getCfg( 'absolute_path' ) . "/images";
$cbImages			=	$imagesPath . '/comprofiler';
$cbImagesGallery	=	$cbImages . '/gallery';

if ( $adminFS->isUsingStandardPHP() && ( ! $adminFS->file_exists( $cbImages ) ) && ! $adminFS->is_writable( $_CB_framework->getCfg( 'absolute_path' ) . "/images/" ) ) {
	print "<font color=red>". $imagesPath . "/ is not writable !</font><br />";
} else {
	if ( ! $adminFS->file_exists( $cbImages ) ) {
		if ( $adminFS->mkdir( $cbImages ) ) {
			print "<font color=green>" . $cbImages . "/ Successfully added.</font><br />";
		} else {
			print "<font color=red>" . $cbImages . "/ Failed to be to be created, please do so manually !</font><br />";
		}
	}  else {
		// print "<font color=green>" . $cbImages . "/ already exists.</font><br />";
	}
	if ( ! $adminFS->file_exists( $cbImagesGallery ) ) {
		if ( $adminFS->mkdir( $cbImagesGallery ) ) {
			print "<font color=green>" . $cbImagesGallery ."/ Successfully added.</font><br />";
		} else {
			print "<font color=red>" . $cbImagesGallery . "/ Failed to be to be created, please do so manually !</font><br />";
		}
	}  else {
		// print "<font color=green>" . $cbImagesGallery . "/ already exists.</font><br />";
	}
	if( $adminFS->file_exists( $cbImages ) ) {
		if ( ! is_writable( $cbImages ) ) {
			if( ! $adminFS->chmod( $cbImages, 0775 ) ) {
				if ( ! @chmod( $cbImages, 0775 ) ) {
					print "<font color=red>" . $cbImages . "/ Failed to be chmod'd to 775 please do so manually !</font><br />";
				}
			}
		}
		if( ! is_writable( $cbImages ) ) {
			print "<font color=red>" . $cbImages . "/ is not writable and failed to be chmod'd to 775 please do so manually !</font><br />";
		}
	}
	if ( $adminFS->file_exists( $cbImagesGallery ) ) {
		if( ! is_writable( $cbImagesGallery ) ) {
			if( ! $adminFS->chmod( $cbImagesGallery, 0775 ) ) {
				if ( ! @chmod( $cbImagesGallery, 0775 ) ) {
					print "<font color=red>" . $cbImagesGallery . "/ Failed to be chmod'd to 775 please do so manually !</font><br />";
				}
			}
		}
		if( ! is_writable( $cbImagesGallery ) ) {
			print "<font color=red>" . $cbImagesGallery . "/ is not writable and failed to be chmod'd to 755 please do so manually !</font><br />";
		}
		$galleryFiles = array("airplane.gif"
		,"ball.gif"
		,"butterfly.gif"
		,"car.gif"
		,"dog.gif"
		,"duck.gif"
		,"fish.gif"
		,"frog.gif"
		,"guitar.gif"
		,"kick.gif"
		,"pinkflower.gif"
		,"redflower.gif"
		,"skater.gif"
		,"index.html");
		foreach( $galleryFiles AS $galleryFile ) {
			if ( ! ( file_exists( $cbImagesGallery . '/' . $galleryFile ) && is_readable( $cbImagesGallery . '/' . $galleryFile ) ) ) {
				// try by www: we try it this way, as we can silence errors in php, but not in FTP:
				$result	=	@copy( $_CB_framework->getCfg( 'absolute_path' ) . "/components/com_comprofiler/images/gallery/".$galleryFile, $cbImagesGallery . '/' . $galleryFile );
				if ( ! $result ) {
					// otherwise try by FTP:
					$result		=	$adminFS->copy( $_CB_framework->getCfg( 'absolute_path' ) . "/components/com_comprofiler/images/gallery/".$galleryFile, $cbImagesGallery . '/' . $galleryFile );
				}
				if ( $result ) {
					// print "<font color=green>" . $galleryFile . " Successfully added to the gallery.</font><br />";
				} else {
					print "<font color=red>" . $galleryFile . " Failed to be added to the gallery please do so manually !</font><br />";
				}
			}
		}
	}
}
if ( ! ( $adminFS->file_exists( $cbImages ) && is_writable( $cbImages ) && $adminFS->file_exists( $cbImagesGallery ) ) ) {
		print "<br /><font color=red>Manually do the following:<br /> 1.) create ".$cbImages . "/ directory <br /> 2.) chmod it to 755 or if needed to 775 <br /> 3.) create ". $cbImagesGallery . "/ <br /> 4.) chmod it to 755 or if needed to 775 <br />5.) copy " . $_CB_framework->getCfg( 'absolute_path' ) . "/components/com_comprofiler/images/gallery/ and its contents to ". $cbImagesGallery . "/  </font><br />";
}
?>
      </td>
    </tr>
  </table>
 </div>
  <?php
 		$ret					=	ob_get_contents();
		ob_end_clean();
		$_CB_framework->setUserState( "com_comprofiler_install", $ret );
		// now treat special case of CB 1.2.2- installed and a plugin/mambot/module already loaded and the new function doesn't exist:
		if ( is_callable( array( $_CB_framework, 'backendUrl' ) ) ) {
			$stepTwoUrl			=	$_CB_framework->backendUrl( 'index.php?option=com_comprofiler&task=finishinstallation', false );
		} else {
			$stepTwoUrl			=	( checkJversion() < 1 ? 'index2.php' : 'index.php' ) . '?option=com_comprofiler&task=finishinstallation';
		}
?>
<div id="cbInstallNextStep" style="font-weight:bold;font-size:120%;background:#ffffdd;border:2px orange solid;padding:5px;">WAIT PLEASE: DO NOT INTERRUPT INSTALLATION PROCESS: PERFORMING SECOND INSTALLATION STEP: UNCOMPRESSING CORE PLUGINS: THIS CAN TAKE UP TO 2 MINUTES. <span id="cbstep2manual">If this screen stays for over 2 minutes, <a href="<?php echo htmlspecialchars( $stepTwoUrl ); ?>">please click here to continue next and last installation step</a>.</span></div>
<?php
		echo $ret;
								//	Add Javascript to go to step 2:
		$jsStepTwo				=	"	$('form table.adminform').hide();"		// hides other uploads in j 1.5.
								.	"	$('#cbstep2manual').hide();"		// hides Continue in j 1.0 + Mambo
								.	"	$('#cbInstallNextStep').hide().fadeIn('1500', function() { $(this).fadeOut('1000', function() { $(this).fadeIn('1500', function() {"
								//	Get the href of the user profile link:
								.	"\n			window.location = '" . addslashes( $stepTwoUrl ) . "';"
								.	"\n		} ) } ) } );"
								;

		$_CB_framework->document->_outputToHeadCollectionStart();
		if ( checkJversion() > 1 ) {
			// there is a redirect in j1.6 not buffering headers, so we have to output scripts in body:
			$_CB_framework->document->setCmsDoc( null );
		}
		$_CB_framework->outputCbJQuery( $jsStepTwo );
		$_CB_framework->getAllJsPageCodes();
		echo $_CB_framework->document->_outputToHead();
}
 /**
  * Deletes <files>
  *
  * @param  SimpleXMLElement   $files_element
  * @param  cbAdminFileSystem  $adminFS
  * @param  string|null        $installFileName
  * @return void
  */
 protected function deleteFiles(SimpleXMLElement $files_element, cbAdminFileSystem $adminFS, $installFileName)
 {
     foreach ($files_element->children() as $file) {
         // delete the files
         $filename = $file->data();
         if ($adminFS->file_exists($this->i_elementdir . $filename)) {
             $parts = pathinfo($filename);
             $subpath = $parts['dirname'];
             if ($subpath != '' && $subpath != '.' && $subpath != '..') {
                 $adminFS->deldir(_cbPathName($this->i_elementdir . $subpath . '/'));
             } else {
                 if ($file->getName() == 'foldername') {
                     $adminFS->deldir(_cbPathName($this->i_elementdir . $filename . '/'));
                 } elseif ($installFileName != $filename) {
                     $adminFS->unlink(_cbPathName($this->i_elementdir . $filename, false));
                 }
             }
         }
     }
 }
/**
* Joomla Community Builder User Plugin: plug_cbprofilegallery
* @version $Id$
* @package plug_cbprofilegallery
* @subpackage install.profilegallery.php
* @author Nant, JoomlaJoe and Beat
* @copyright (C) Nant, JoomlaJoe and Beat, www.joomlapolis.com
* @license Limited http://www.gnu.org/licenses/old-licenses/gpl-2.0.html GNU/GPL version 2
* @final 1.2.2 (compatible with CB 1.2)
*/
function plug_cb_profilegallery_install(){
	global $_CB_framework, $_CB_database;
	# Show installation result to user
  	?>
	<center>
	<table width="100%" border="0">
	<tr>
	<td>
	</td>
	</tr>
	<tr>
	<td>
	<br />CB Profile Gallery 1.2.1
    <br />Copyright 2006-2012 Nick A., MamboJoe/JoomlaJoe, Beat and CB team on joomlapolis.com.
    <br />This component is released under the GNU/GPL License. 
    <br />All copyright statements must be kept. 
    <br />Derivate work must prominently duly acknowledge original work and include visible online links. 
    <br />Official site: <a href="http://www.joomlapolis.com">www.joomlapolis.com</a>
	<br />
	</td>
	</tr>
	<tr>
	<td background="F0F0F0" colspan="2">
        <code>Installation Process:<br />
        <?php
 
 	cbimport( 'cb.adminfilesystem' );   
    $pgadminFS			=&	cbAdminFileSystem::getInstance();
    $cmsimagesPath		=	$_CB_framework->getCfg( 'absolute_path' ) . "/images";
	$cbImages			=	$cmsimagesPath . '/comprofiler';
	$pgImagesGallery	=	$cbImages . '/plug_profilegallery';

 	if ( $pgadminFS->isUsingStandardPHP() && ( ! $pgadminFS->file_exists( $pgImagesGallery ) ) && ! $pgadminFS->is_writable( $_CB_framework->getCfg( 'absolute_path' ) . "/images/comprofiler/" ) ) {
		print "<font color=red>". $cbImages . "/ is not! writable !</font><br />";
	} else {
		if (! $pgadminFS->file_exists( $pgImagesGallery ) ) {
			if ( $pgadminFS->mkdir( $pgImagesGallery ) ) {
				print "<font color=green>" . $pgImagesGallery . "/ Successfully added.</font><br />";
			} else {
				print "<font color=red>" . $pgImagesGallery . "/ Failed to be to be created, please do so manually !</font><br />";
			}	
		}  else {
			print "<font color=green>" . $pgImagesGallery . "/ already exists.</font><br />";
		}
	}

    $mode     = octdec( $_CB_framework->getCfg( 'dirperms' ) );
    if ( ! $mode ) {
        $mode     = 0755;
    }

	if ( $pgadminFS->file_exists( $pgImagesGallery ) ) {
		if( ! is_writable( $pgImagesGallery ) ) {
			if( ! $pgadminFS->chmod( $pgImagesGallery, $mode ) ) {
				if ( ! @chmod( $pgImagesGallery, $mode ) ) {
					print "<font color=red>" . $pgImagesGallery . "/ Failed to be chmod'd to 775 please do so manually !</font><br />";
				}
			}
		}
		if( ! is_writable( $pgImagesGallery ) ) {
			print "<font color=red>" . $pgImagesGallery . "/ is not writable and failed to be chmod'd to 775 please do so manually !</font><br />";
		}
 		$result	=	@copy( $_CB_framework->getCfg( 'absolute_path' ) . "/components/com_comprofiler/index.html", $_CB_framework->getCfg( 'absolute_path' ) . "/images/comprofiler/plug_profilegallery/index.html" );
		if ( ! $result ) {
			// otherwise try by FTP:
			$result	= $pgadminFS->copy($_CB_framework->getCfg( 'absolute_path' ). "/components/com_comprofiler/index.html" , $_CB_framework->getCfg( 'absolute_path' ) . "/images/comprofiler/plug_profilegallery/index.html");
		}
		if ( $result ) {
			print "<font color=green>index.html file successfully added to the profile gallery repository.</font><br />";
		} else {
			print "<font color=red>index.html failed to be added to the profile gallery repository at " . $_CB_framework->getCfg( 'absolute_path' ) . "/images/comprofiler/plug_profilegallery/" . " please do so manually !</font><br />";
		}
	}
	
    // query to calculate misaligned quotas for existing gallery table items
	$query = "SELECT user_id AS USER, cb_pgtotalitems as ITEMS, cb_pgtotalsize AS SIZE, "
        . "count(userid) AS CITEMS, SUM(pgitemsize) AS CSIZE "
        . "\n FROM #__comprofiler JOIN #__comprofiler_plug_profilegallery"
        . "\n ON user_id = userid"
        . "\n GROUP BY userid"
        . "\n HAVING (ITEMS <> CITEMS) OR (SIZE <> CSIZE) ";

    $_CB_database->setQuery($query);
    $cbusers=$_CB_database->loadObjectList();
    $cbuserscount=count($cbusers);

    //print_r($cbusers);
    //print($cbuserscount);
	$k = 0;
	if ($cbuserscount != 0) {    
        foreach ($cbusers as $cbuser) {                                  
            $cbu_userid = $cbuser->USER;
            $cbu_titems = $cbuser->ITEMS;
            $cbu_tsize = $cbuser->SIZE;
            $cbu_ctitems = $cbuser->CITEMS;
            $cbu_ctsize = $cbuser->CSIZE;

            // print  $cbu_userid . " , " . $cbu_titems . " , " . $cbu_tsize . " , " . $cbu_ctitems . " , " . $cbu_ctsize ; 
        
            if ( ($cbu_titems != $cbu_ctitems) || ($cbu_tsize != $cbu_ctsize) ) {
                $k++;
                cbu_adjust($cbu_userid, $cbu_ctitems, $cbu_ctsize);
                print "<br /><font color=green>Adjusted misaligned quotas for userid " . $cbu_userid 
                    . " ( " . $cbu_titems . "," . $cbu_tsize . " --> " . $cbu_ctitems . "," . $cbu_ctsize . " )</font>";
            }
    	}
    	print "<br /><font color=green>Adjusted total of " . $k . " user quotas for existing gallery items</font><br />";    
	}
 
    // query to calculate misaligned quotas for non existing gallery table items
    $query = "SELECT user_id AS USER, cb_pgtotalitems as ITEMS, cb_pgtotalsize AS SIZE "
        . "\n FROM #__comprofiler LEFT JOIN #__comprofiler_plug_profilegallery"
        . "\n ON user_id = userid"
        . "\n WHERE (cb_pgtotalitems <> 0 OR cb_pgtotalsize <> 0) AND pgitemsize IS NULL "
        . "\n GROUP BY userid";

    $_CB_database->setQuery($query);
    $cbusers=$_CB_database->loadObjectList();
    $cbuserscount=count($cbusers);

    //print_r($cbusers);
    //print($cbuserscount);
    $k = 0;
    if ($cbuserscount != 0) {    
        foreach ($cbusers as $cbuser) {                                  
            $cbu_userid = $cbuser->USER;
            $cbu_titems = $cbuser->ITEMS;
            $cbu_tsize = $cbuser->SIZE;
        
            $k++;
            cbu_adjust($cbu_userid, 0, 0);
            print "<br /><font color=green>Reset misaligned quotas for userid " . $cbu_userid 
                . " ( " . $cbu_titems . "," . $cbu_tsize . " -->  0,0 ) </font>";
        }
    }
    print "<br /><font color=green>Reset total of " . $k . " user quotas for non existing gallery items</font><br />";    
		
	?>
        <font color="green"><b>Installation finished.</b></font></code>
	</td>
	</tr>
	</table>
	</center>
	<?php
	return "";
}
 public function install($parent)
 {
     global $_CB_framework, $_CB_adminpath, $ueConfig;
     // Ensure PHP version is adaquete for CB:
     if (version_compare(phpversion(), '5.3.3', '<')) {
         JFactory::getApplication()->enqueueMessage(sprintf('As stated in README and prerequisites, PHP Version %s, which is obsolete since before 2009-11-19 and insecure, is not compatible with %s: Please upgrade to PHP %s or greater (CB is also compatible with PHP 5.4 and 5.5) before installing Community Builder.', phpversion(), 'Community Builder', sprintf('at least version %s, recommended version %s', '5.3.1', '5.3.10')), 'error');
         JFactory::getApplication()->enqueueMessage(sprintf('Installation failed. In all cases, please require your hoster to upgrade your PHP version as soon as possible.'), 'error');
         return false;
     }
     // Initialize CB Appplication library (which has delayed config lazy loading):
     if (is_readable(JPATH_SITE . '/libraries/CBLib/CB/Application/CBApplication.php')) {
         /** @noinspection PhpIncludeInspection */
         include_once JPATH_SITE . '/libraries/CBLib/CB/Application/CBApplication.php';
         \CB\Application\CBApplication::init();
     } else {
         JFactory::getApplication()->enqueueMessage("Mandatory Community Builder lib_CBLib not installed!", 'error');
         return false;
     }
     // Determine path to CBs backend file structure:
     $_CB_adminpath = JPATH_ADMINISTRATOR . '/components/com_comprofiler/';
     // Disable loading of config immediately after foundation include as the db may not exist yet:
     \CB\Application\CBConfig::setCbConfigReadyToLoad(false);
     // Check if CBLib can load:
     /** @noinspection PhpIncludeInspection */
     if (false === (include_once $_CB_adminpath . 'plugin.foundation.php')) {
         return false;
     }
     // Check if CBLib is up to date:
     if (version_compare(constant('CBLIB'), $ueConfig['version'], '<')) {
         JFactory::getApplication()->enqueueMessage(sprintf('Community Builder library lib_CBLib version %s is older than the Community Builder version %s tried to be installed.', constant('CBLIB'), $ueConfig['version']), 'error');
         return false;
     }
     // Set location to backend:
     $_CB_framework->cbset('_ui', 2);
     if ($_CB_framework->getCfg('debug')) {
         ini_set('display_errors', true);
         error_reporting(E_ALL);
     }
     // Load in CB API:
     cbimport('cb.tabs');
     cbimport('cb.adminfilesystem');
     cbimport('cb.dbchecker');
     // Define CB backend filesystem API:
     $adminFS = cbAdminFileSystem::getInstance();
     // Delete removed files on upgrade:
     $filesToDelete = array($_CB_adminpath . 'comprofileg.xml', $_CB_adminpath . 'comprofilej.xml', $_CB_adminpath . 'admin.comprofiler.php', $_CB_adminpath . 'ue_config_first.php');
     foreach ($filesToDelete as $deleteThisFile) {
         if ($adminFS->file_exists($deleteThisFile)) {
             $adminFS->unlink($deleteThisFile);
         }
     }
     $liveSite = $_CB_framework->getCfg('live_site');
     $return = '<div style="margin-bottom:10px;width:100%;text-align:center;"><img alt="' . htmlspecialchars(CBTxt::T('CB Logo')) . '" src="' . $liveSite . '/components/com_comprofiler/images/smcblogo.gif" /></div>' . '<div style="font-size:14px;margin-bottom:10px;">Copyright 2004-2015 Joomlapolis.com. ' . CBTxt::T('This component is released under the GNU/GPL version 2 License. All copyright statements must be kept. Derivate work must prominently duly acknowledge original work and include visible online links.') . '</div>';
     $cbDatabase = \CBLib\Application\Application::Database();
     // Core database fixes:
     $dbChecker = new \CB\Database\CBDatabaseChecker($cbDatabase);
     $result = $dbChecker->checkDatabase(true, false, null, null);
     if ($result == true) {
         // All ok, Nothing to alarm user here:
         // $return							.=	'<div style="font-size:18px;color:green;margin-bottom:10px;">' . CBTxt::T( 'Automatic database upgrade applied successfully.' ) . '</div>';
     } elseif (is_string($result)) {
         $return .= '<div style="font-size:18px;color:red;margin-bottom:10px;">' . $result . '</div>';
     } else {
         $errors = $dbChecker->getErrors(false);
         if ($errors) {
             $return .= '<div style="color:red;margin-bottom:10px;">' . '<div style="font-size:18px;font-weight:bold;padding-bottom:5px;margin-bottom:5px;border-bottom:1px solid red;">' . CBTxt::T('Database fixing errors') . '</div>';
             foreach ($errors as $error) {
                 $return .= '<div style="margin-bottom:10px;">' . '<div style="font-size:14px;">' . $error[0] . '</div>';
                 if ($error[1]) {
                     $return .= '<div style="font-size:12px;text-indent:15px;">' . $error[1] . '</div>';
                 }
                 $return .= '</div>';
             }
             $return .= '</div>';
         }
     }
     if ($_CB_framework->getCfg('session_handler') != 'database') {
         $logs = $dbChecker->getLogs(false);
         if (count($logs) > 0) {
             $return .= '<div style="margin-bottom:10px;">' . '<div style="font-size:14px;margin-bottom:5px;">' . '<a href="javascript: void(0);" id="cbdetailsLinkShow" onclick="this.style.display=\'none\';document.getElementById(\'cbdetailsdbcheck\').style.display=\'block\';document.getElementById(\'cbdetailsLinkHide\').style.display=\'block\';return false;">' . CBTxt::T('Click to Show details') . '</a>' . '<a href="javascript: void(0);" id="cbdetailsLinkHide" onclick="this.style.display=\'none\';document.getElementById(\'cbdetailsdbcheck\').style.display=\'block\';document.getElementById(\'cbdetailsLinkShow\').style.display=\'block\';return false;" style="display:none;">' . CBTxt::T('Click to Hide details') . '</a>' . '</div>' . '<div id="cbdetailsdbcheck" style="dsiplay:none;color:green;">';
             foreach ($logs as $log) {
                 $return .= '<div style="margin-bottom:10px;">' . '<div style="font-size:14px;">' . $log[0] . '</div>';
                 if ($log[1]) {
                     $return .= '<div style="font-size:12px;text-indent:15px;">' . $log[1] . '</div>';
                 }
                 $return .= '</div>';
             }
             $return .= '</div>' . '</div>';
         }
     }
     // Fix old 1.x usergroups-based permissions to 2.x access-levels in lists and in tabs:
     $this->convertUserGroupsToViewAccessLevels(new \CB\Database\Table\TabTable(), 'CB Tab access');
     $this->convertUserGroupsToViewAccessLevels(new \CB\Database\Table\ListTable(), 'CB Users list access');
     // Synchronize users to CB:
     $query = 'INSERT IGNORE INTO ' . $cbDatabase->NameQuote('#__comprofiler') . "\n (" . $cbDatabase->NameQuote('id') . ', ' . $cbDatabase->NameQuote('user_id') . ')' . "\n SELECT " . $cbDatabase->NameQuote('id') . ', ' . $cbDatabase->NameQuote('id') . "\n FROM " . $cbDatabase->NameQuote('#__users');
     $cbDatabase->setQuery($query);
     if (!$cbDatabase->query()) {
         $cbSpoofField = cbSpoofField();
         $cbSpoofString = cbSpoofString(null, 'plugin');
         $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::P('User synchronization failed. Please <a href="[url]" target="_blank">click here</a> to manually synchronize.', array('[url]' => $_CB_framework->backendUrl("index.php?option=com_comprofiler&view=syncUsers&{$cbSpoofField}={$cbSpoofString}"))) . '</div>';
     }
     // Fix images:
     $imagesPath = $_CB_framework->getCfg('absolute_path') . '/images';
     $cbImages = $imagesPath . '/comprofiler';
     $cbImagesGallery = $cbImages . '/gallery';
     $cbImagesCanvasGallery = $cbImages . '/gallery/canvas';
     if ($adminFS->isUsingStandardPHP() && !$adminFS->file_exists($cbImages) && !$adminFS->is_writable($_CB_framework->getCfg('absolute_path') . '/images/')) {
         $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::P('[path]/ is not writable.', array('[path]' => $imagesPath)) . '</div>';
     } else {
         if (!$adminFS->file_exists($cbImages)) {
             if ($adminFS->mkdir($cbImages)) {
                 // All ok, Nothing to alarm user here.
                 // $return						.=	'<div style="font-size:14px;color:green;margin-bottom:10px;">' . CBTxt::P( '[path]/ successfully added.', array( '[path]' => $cbImages ) ) . '</div>';
             } else {
                 $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::P('[path]/ failed to create, please do so manually.', array('[path]' => $cbImages)) . '</div>';
             }
         }
         if (!$adminFS->file_exists($cbImagesGallery)) {
             if ($adminFS->mkdir($cbImagesGallery)) {
                 // All ok, Nothing to alarm user here:
                 // $return					.=	'<div style="font-size:14px;color:green;margin-bottom:10px;">' . CBTxt::P( '[path]/ successfully added.', array( '[path]' => $cbImagesGallery ) ) . '</div>';
             } else {
                 $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::P('[path]/ failed to create, please do so manually.', array('[path]' => $cbImagesGallery)) . '</div>';
             }
         }
         if (!$adminFS->file_exists($cbImagesCanvasGallery)) {
             if ($adminFS->mkdir($cbImagesCanvasGallery)) {
                 // All ok, Nothing to alarm user here:
                 // $return					.=	'<div style="font-size:14px;color:green;margin-bottom:10px;">' . CBTxt::P( '[path]/ successfully added.', array( '[path]' => $cbImagesCanvasGallery ) ) . '</div>';
             } else {
                 $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::P('[path]/ failed to create, please do so manually.', array('[path]' => $cbImagesCanvasGallery)) . '</div>';
             }
         }
         if ($adminFS->file_exists($cbImages)) {
             if (!is_writable($cbImages)) {
                 if (!$adminFS->chmod($cbImages, 0775)) {
                     if (!@chmod($cbImages, 0775)) {
                         $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::P('[path]/ failed to chmod to 775 please do so manually.', array('[path]' => $cbImages)) . '</div>';
                     }
                 }
             }
             if (!is_writable($cbImages)) {
                 $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::P('[path]/ is not writable and failed to chmod to 775 please do so manually.', array('[path]' => $cbImages)) . '</div>';
             }
             if (!$adminFS->file_exists($cbImages . '/index.html')) {
                 $result = @copy($imagesPath . '/index.html', $cbImages . '/index.html');
                 if (!$result) {
                     $result = $adminFS->copy($imagesPath . '/index.html', $cbImages . '/index.html');
                 }
                 if (!$result) {
                     $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::P('index.html failed to be added to [path] please do so manually.', array('[path]' => $cbImages)) . '</div>';
                 }
             }
         }
         if ($adminFS->file_exists($cbImagesGallery)) {
             if (!is_writable($cbImagesGallery)) {
                 if (!$adminFS->chmod($cbImagesGallery, 0775)) {
                     if (!@chmod($cbImagesGallery, 0775)) {
                         $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::P('[path]/ failed to chmod to 775 please do so manually.', array('[path]' => $cbImagesGallery)) . '</div>';
                     }
                 }
             }
             if (!is_writable($cbImagesGallery)) {
                 $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::P('[path]/ is not writable and failed to chmod to 775 please do so manually.', array('[path]' => $cbImagesGallery)) . '</div>';
             }
             $galleryPath = $_CB_framework->getCfg('absolute_path') . '/components/com_comprofiler/images/gallery';
             $galleryDir = @opendir($galleryPath);
             $galleryFiles = array();
             while (true == ($file = @readdir($galleryDir))) {
                 if ($file != '.' && $file != '..') {
                     $galleryFiles[] = $file;
                 }
             }
             @closedir($galleryDir);
             foreach ($galleryFiles as $galleryFile) {
                 if (!(file_exists($cbImagesGallery . '/' . $galleryFile) && is_readable($cbImagesGallery . '/' . $galleryFile))) {
                     $result = @copy($galleryPath . '/' . $galleryFile, $cbImagesGallery . '/' . $galleryFile);
                     if (!$result) {
                         $result = $adminFS->copy($galleryPath . '/' . $galleryFile, $cbImagesGallery . '/' . $galleryFile);
                     }
                     if (!$result) {
                         $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::P('[file] failed to be added to the gallery please do so manually.', array('[file]' => $galleryFile)) . '</div>';
                     }
                 }
             }
             if (!$adminFS->file_exists($cbImagesGallery . '/index.html')) {
                 $result = @copy($imagesPath . '/index.html', $cbImagesGallery . '/index.html');
                 if (!$result) {
                     $result = $adminFS->copy($imagesPath . '/index.html', $cbImagesGallery . '/index.html');
                 }
                 if (!$result) {
                     $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::P('index.html failed to be added to [path] please do so manually.', array('[path]' => $cbImagesGallery)) . '</div>';
                 }
             }
         }
         if ($adminFS->file_exists($cbImagesCanvasGallery)) {
             if (!is_writable($cbImagesCanvasGallery)) {
                 if (!$adminFS->chmod($cbImagesCanvasGallery, 0775)) {
                     if (!@chmod($cbImagesCanvasGallery, 0775)) {
                         $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::P('[path]/ failed to chmod to 775 please do so manually.', array('[path]' => $cbImagesCanvasGallery)) . '</div>';
                     }
                 }
             }
             if (!is_writable($cbImagesCanvasGallery)) {
                 $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::P('[path]/ is not writable and failed to chmod to 775 please do so manually.', array('[path]' => $cbImagesCanvasGallery)) . '</div>';
             }
             $galleryPath = $_CB_framework->getCfg('absolute_path') . '/components/com_comprofiler/images/gallery/canvas';
             $galleryDir = @opendir($galleryPath);
             $galleryFiles = array();
             while (true == ($file = @readdir($galleryDir))) {
                 if ($file != '.' && $file != '..') {
                     $galleryFiles[] = $file;
                 }
             }
             @closedir($galleryDir);
             foreach ($galleryFiles as $galleryFile) {
                 if (!(file_exists($cbImagesCanvasGallery . '/' . $galleryFile) && is_readable($cbImagesCanvasGallery . '/' . $galleryFile))) {
                     $result = @copy($galleryPath . '/' . $galleryFile, $cbImagesCanvasGallery . '/' . $galleryFile);
                     if (!$result) {
                         $result = $adminFS->copy($galleryPath . '/' . $galleryFile, $cbImagesCanvasGallery . '/' . $galleryFile);
                     }
                     if (!$result) {
                         $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::P('[file] failed to be added to the gallery please do so manually.', array('[file]' => $galleryFile)) . '</div>';
                     }
                 }
             }
             if (!$adminFS->file_exists($cbImagesCanvasGallery . '/index.html')) {
                 $result = @copy($imagesPath . '/index.html', $cbImagesCanvasGallery . '/index.html');
                 if (!$result) {
                     $result = $adminFS->copy($imagesPath . '/index.html', $cbImagesCanvasGallery . '/index.html');
                 }
                 if (!$result) {
                     $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::P('index.html failed to be added to [path] please do so manually.', array('[path]' => $cbImagesCanvasGallery)) . '</div>';
                 }
             }
         }
     }
     if (!($adminFS->file_exists($cbImages) && is_writable($cbImages) && $adminFS->file_exists($cbImagesGallery) && $adminFS->file_exists($cbImagesCanvasGallery))) {
         $return .= '<div style="margin-bottom:10px;">' . '<div style="font-size:14px;">' . CBTxt::T('Manually do the following:') . '</div>' . '<div style="font-size:12px;text-indent:15px;">' . CBTxt::P('1. create [path]/ directory', array('[path]' => $cbImages)) . '</div>' . '<div style="font-size:12px;text-indent:15px;">' . CBTxt::T('2. chmod it to 755 or if needed to 775') . '</div>' . '<div style="font-size:12px;text-indent:15px;">' . CBTxt::P('3. create [path]/ directory', array('[path]' => $cbImagesGallery)) . '</div>' . '<div style="font-size:12px;text-indent:15px;">' . CBTxt::T('4. chmod it to 755 or if needed to 775') . '</div>' . '<div style="font-size:12px;text-indent:15px;">' . CBTxt::P('5. copy [from_path]/ and its contents to [to_path]/', array('[from_path]' => $_CB_framework->getCfg('absolute_path') . '/components/com_comprofiler/images/gallery', '[to_path]' => $cbImagesGallery)) . '</div>' . '<div style="font-size:12px;text-indent:15px;">' . CBTxt::P('6. create [path]/ directory', array('[path]' => $cbImagesCanvasGallery)) . '</div>' . '<div style="font-size:12px;text-indent:15px;">' . CBTxt::T('7. chmod it to 755 or if needed to 775') . '</div>' . '<div style="font-size:12px;text-indent:15px;">' . CBTxt::P('8. copy [from_path]/ and its contents to [to_path]/', array('[from_path]' => $_CB_framework->getCfg('absolute_path') . '/components/com_comprofiler/images/gallery/canvas', '[to_path]' => $cbImagesCanvasGallery)) . '</div>' . '</div>';
     }
     $pluginMessages = null;
     if (cbInstaller_install_plugins($pluginMessages)) {
         // All ok, Nothing to alarm user here-
         // $return							.=	'<div style="font-size:18px;color:green;margin-bottom:10px;">' . CBTxt::T( 'Core plugins installed successfully.' ) . '</div>';
     } else {
         $return .= '<div style="font-size:14px;color:red;margin-bottom:10px;">' . CBTxt::P('Core plugins installation failed. Please <a href="[url]" target="_blank">click here</a> to manually install.', array('[url]' => $_CB_framework->backendUrl('index.php?option=com_comprofiler&view=finishinstallation'))) . '</div>';
     }
     $return .= $pluginMessages . '<div style="color:green;font-size:18px;font-weight:bold;margin-top:15px;margin-bottom:15px;">' . CBTxt::P('Installation done.') . '</div>' . '<div style="color:green;font-size:18px;font-weight:bold;margin-top:15px;margin-bottom:15px;">' . CBTxt::P('Now is a great time to checkout the <a href="[help_url]" target="_blank">Getting Started</a> resources.', array('[help_url]' => 'http://www.joomlapolis.com/documentation/community-builder/getting-started?pk_campaign=in-cb&amp;pk_kwd=installedwelcomescreen')) . '</div>' . '<div style="margin-bottom:10px;">' . '<div style="font-size:12px;"><a href="http://www.joomlapolis.com/cb-solutions?pk_campaign=in-cb&amp;pk_kwd=installedwelcomescreen" target="_blank">' . CBTxt::T('Click here to see more CB Plugins (Languages, Fields, Tabs, Signup-Connect, Paid Memberships and over 30 more) by CB Team at joomlapolis.com') . '</a></div>' . '<div style="font-size:12px;"><a href="http://extensions.joomla.org/extensions/clients-a-communities/communities/210" target="_blank">' . CBTxt::T('Click here to see our CB listing on the Joomla! Extensions Directory (JED) and find third-party add-ons for your website.') . '</a></div>' . '<div style="font-size:12px;margin:10px 0 25px;">or &nbsp; <a href="index.php?option=com_comprofiler&view=showconfig" class="btn btn-primary">' . CBTxt::T('Start to Configure Community Builder') . '</a></div>' . '</div>';
     echo $return;
     // For display in packager:
     $_CB_framework->setUserState('com_comprofiler_install', $return);
     return true;
 }
Example #12
0
 /**
  * Cleans up (deletes) the installation directory if cleanup is needed
  *
  * @param  string  $manifestFilename  Name of the special manifest file
  * @param  string  $directoryName     Name and path of the directory to clean up
  * @return void
  */
 function cleanupInstall($manifestFilename, $directoryName)
 {
     if ($this->doCleanup() && file_exists($directoryName)) {
         $adminFS = cbAdminFileSystem::getInstance();
         $adminFS->deldir($directoryName);
         if ($manifestFilename) {
             $adminFS->unlink(_cbPathName($manifestFilename, false));
         }
     }
 }