function checkcbdb($dbId = 0)
{
    global $_CB_database, $_CB_framework, $ueConfig, $_PLUGINS;
    // Try extending time, as unziping/ftping took already quite some... :
    @set_time_limit(240);
    _CBsecureAboveForm('checkcbdb');
    outputCbTemplate(2);
    outputCbJs(2);
    global $_CB_Backend_Title;
    $_CB_Backend_Title = array(0 => array('fa fa-wrench', CBTxt::T('CB Tools: Check database: Results')));
    $cbSpoofField = cbSpoofField();
    $cbSpoofString = cbSpoofString(null, 'plugin');
    $version = $_CB_database->getVersion();
    $version = substr($version, 0, strpos($version, '-'));
    if ($dbId == 0) {
        echo '<div class="text-left"><div class="form-group cb_form_line clearfix">' . CBTxt::T('Checking Community Builder Database') . ':</div>';
        // 1. check comprofiler_field_values table for bad rows
        $sql = "SELECT fieldvalueid,fieldid FROM #__comprofiler_field_values WHERE fieldid=0";
        $_CB_database->setQuery($sql);
        $bad_rows = $_CB_database->loadObjectList();
        if ($_CB_database->getErrorNum()) {
            echo '<div class="form-group cb_form_line clearfix text-danger">' . sprintf(CBTxt::T('ERROR: sql query: %s : returned error: %s'), htmlspecialchars($sql), stripslashes($_CB_database->getErrorMsg())) . '</div>';
        } elseif (count($bad_rows) != 0) {
            echo '<div class="form-group cb_form_line clearfix text-danger">' . sprintf(CBTxt::T('Warning: %s entries in Community Builder comprofiler_field_values have bad fieldid values.'), count($bad_rows)) . '</div>';
            foreach ($bad_rows as $bad_row) {
                if ($bad_row->fieldvalueid == 0) {
                    echo '<div class="form-group cb_form_line clearfix text-danger">' . sprintf(CBTxt::T('ZERO fieldvalueid illegal: fieldvalueid=%s fieldid=0'), $bad_row->fieldvalueid) . '</div>';
                } else {
                    echo '"<div class="form-group cb_form_line clearfix text-danger">fieldvalueid="' . $bad_row->fieldvalueid . " fieldid=0</div>";
                }
            }
            echo '<div class="form-group cb_form_line clearfix text-danger">' . CBTxt::T('This one can be fixed by <strong>first backing up database</strong>') . ' <a href="' . $_CB_framework->backendUrl("index.php?option=com_comprofiler&view=fixcbmiscdb&{$cbSpoofField}={$cbSpoofString}") . '"> ' . CBTxt::T('then by clicking here') . '</a>.</div>';
        } else {
            echo '<div class="form-group cb_form_line clearfix text-success">' . CBTxt::T('All Community Builder comprofiler_field_values table fieldid rows all match existing fields.') . '</div>';
        }
        // 2.	check if comprofiler_field_values table has entries where corresponding fieldtype value in comprofiler_fields table
        //		does not allow values
        $sql = "SELECT v.fieldvalueid, v.fieldid, f.name, f.type FROM #__comprofiler_field_values as v, #__comprofiler_fields as f WHERE v.fieldid = f.fieldid AND f.type NOT IN ('checkbox','multicheckbox','select','multiselect','radio')";
        $_CB_database->setQuery($sql);
        $bad_rows = $_CB_database->loadObjectList();
        if ($_CB_database->getErrorNum()) {
            echo '<div class="form-group cb_form_line clearfix text-danger">' . sprintf(CBTxt::T('ERROR: sql query: %s : returned error: %s'), htmlspecialchars($sql), stripslashes($_CB_database->getErrorMsg())) . '</div>';
        } elseif (count($bad_rows) != 0) {
            echo '<div class="form-group cb_form_line clearfix text-danger">' . sprintf(CBTxt::T('Warning: %s entries in Community Builder comprofiler_field_values link back to fields of wrong fieldtype.'), count($bad_rows)) . '</div>';
            foreach ($bad_rows as $bad_row) {
                echo '<div class="form-group cb_form_line clearfix text-danger">fieldvalueid=' . $bad_row->fieldvalueid . ' fieldtype=' . $bad_row->type . '</div>';
            }
            echo '<div class="form-group cb_form_line clearfix text-danger">' . CBTxt::T('This one can be fixed in SQL using a tool like phpMyAdmin.') . '</div>';
            // not done automatically since some fields might have field values ! echo '<p><font color=red>This one can be fixed by <strong>first backing up database</strong> then <a href="' . $_CB_framework->backendUrl( "index.php?option=com_comprofiler&task=fixcbmiscdb&$cbSpoofField=$cbSpoofString" ) . '">by clicking here</a>.</font></p>';
        } else {
            echo '<div class="form-group cb_form_line clearfix text-success">' . CBTxt::T('All Community Builder comprofiler_field_values table rows link to correct fieldtype fields in comprofiler_field table.') . '</div>';
        }
        // 5.	check if all cb defined fields have corresponding comprofiler columns
        $sql = "SELECT * FROM #__comprofiler";
        $_CB_database->setQuery($sql, 0, 1);
        $all_comprofiler_fields_and_values = $_CB_database->loadAssoc();
        $all_comprofiler_fields = array();
        if ($all_comprofiler_fields_and_values === null) {
            echo '<div class="form-group cb_form_line clearfix text-danger">' . sprintf(CBTxt::T('ERROR: sql query: %s : returned error: %s'), htmlspecialchars($sql), stripslashes($_CB_database->getErrorMsg())) . '</div>';
        } elseif (is_array($all_comprofiler_fields_and_values)) {
            while (false != (list($_cbfield) = each($all_comprofiler_fields_and_values))) {
                array_push($all_comprofiler_fields, $_cbfield);
            }
        }
        $sql = "SELECT * FROM #__comprofiler_fields WHERE `name` != 'NA' AND `table` = '#__comprofiler'";
        $_CB_database->setQuery($sql);
        $field_rows = $_CB_database->loadObjectList(null, '\\CB\\Database\\Table\\FieldTable', array(&$_CB_database));
        if ($_CB_database->getErrorNum()) {
            echo '<div class="form-group cb_form_line clearfix text-danger">' . sprintf(CBTxt::T('ERROR: sql query: %s : returned error: %s'), htmlspecialchars($sql), stripslashes($_CB_database->getErrorMsg())) . '</div>';
        } else {
            $html_output = array();
            $cb11 = true;
            foreach ($field_rows as $field_row) {
                if ($field_row->tablecolumns !== null) {
                    // CB 1.2 way:
                    if ($field_row->tablecolumns != '') {
                        $tableColumns = explode(',', $field_row->tablecolumns);
                        foreach ($tableColumns as $col) {
                            if (!in_array($col, $all_comprofiler_fields)) {
                                $html_output[] = '<div class="form-group cb_form_line clearfix text-danger">' . sprintf(CBTxt::T(' - Field %s - Column %s is missing from comprofiler table.'), $field_row->name, $col) . '</div>';
                            }
                        }
                    }
                    $cb11 = false;
                } else {
                    // cb 1.1 way
                    if (!in_array($field_row->name, $all_comprofiler_fields)) {
                        $html_output[] = '<div class="form-group cb_form_line clearfix text-danger">' . sprintf(CBTxt::T(' - Column %s is missing from comprofiler table.'), $field_row->name) . '</div>';
                    }
                }
            }
            if (count($html_output) > 0) {
                echo '<div class="form-group cb_form_line clearfix text-danger">' . sprintf(CBTxt::T('There are %s column(s) missing in the comprofiler table, which are defined as fields (rows in comprofiler_fields):'), count($html_output)) . '</div>';
                echo implode('', $html_output);
                echo '<div class="form-group cb_form_line clearfix text-danger">' . CBTxt::T('This one can be fixed by deleting and recreating the field(s) using components / Community Builder / Field Management.') . '<br />' . CBTxt::T('Please additionally make sure that columns in comprofiler table <strong>are not also duplicated in users table</strong>.') . '</div>';
            } elseif ($cb11) {
                echo '<div class="form-group cb_form_line clearfix text-danger">' . CBTxt::T('All Community Builder fields from comprofiler_fields are present as columns in the comprofiler table, but comprofiler_fields table is not yet upgraded to CB 1.2 table structure. Just going to Community Builder Fields Management will fix this automatically.') . '</div>';
            } else {
                echo '<div class="form-group cb_form_line clearfix text-success">' . CBTxt::T('All Community Builder fields from comprofiler_fields are present as columns in the comprofiler table.') . '</div>';
            }
        }
        // 9. Check if images/comprofiler is writable:
        $folder = 'images/comprofiler/';
        echo '<div class="form-group cb_form_line clearfix">' . CBTxt::T('Checking Community Builder folders:') . '</div>';
        if (!is_writable($_CB_framework->getCfg('absolute_path') . '/' . $folder)) {
            echo '<div class="form-group cb_form_line clearfix text-danger">' . sprintf(CBTxt::T('Avatars and thumbnails folder: %s/%s is NOT writeable by the webserver.'), $_CB_framework->getCfg('absolute_path'), $folder) . ' </div>';
        } else {
            echo '<div class="form-group cb_form_line clearfix text-success">' . CBTxt::T('Avatars and thumbnails folder is Writeable.') . '</div>';
        }
        // 10. check if depreciated core plugins are still core plugins
        $sql = "SELECT `name`, `id` FROM `#__comprofiler_plugin` WHERE `element` IN ( 'winclassic', 'webfx', 'osx', 'luna', 'dark', 'yanc', 'cb.mamblogtab', 'cb.simpleboardtab', 'cb.authortab' ) AND `iscore` = 1";
        $_CB_database->setQuery($sql);
        $bad_rows = $_CB_database->loadObjectList();
        if ($_CB_database->getErrorNum()) {
            echo '<div class="form-group cb_form_line clearfix text-danger">' . sprintf(CBTxt::T('ERROR: sql query: %s : returned error: %s'), htmlspecialchars($sql), stripslashes($_CB_database->getErrorMsg())) . '</div>';
        } elseif (count($bad_rows) != 0) {
            echo '<div class="form-group cb_form_line clearfix text-danger">' . sprintf(CBTxt::T('Warning: %s entries in Community Builder _comprofiler_plugin have bad iscore values.'), count($bad_rows)) . '</div>';
            foreach ($bad_rows as $bad_row) {
                echo '<div class="form-group cb_form_line clearfix text-danger">plugin=' . $bad_row->name . ' pluginid=' . $bad_row->id . '</div>';
            }
            echo '<div class="form-group cb_form_line clearfix text-danger">' . CBTxt::T('This one can be fixed by <strong>first backing up database</strong>') . ' <a href="' . $_CB_framework->backendUrl("index.php?option=com_comprofiler&view=fixcbdeprecdb&{$cbSpoofField}={$cbSpoofString}") . '"> ' . CBTxt::T('then by clicking here') . '</a>.</div>';
        } else {
            echo '<div class="form-group cb_form_line clearfix text-success">' . CBTxt::T('All Community Builder _comprofiler_plugin table iscore values are correct.') . '</div>';
        }
        // 11. check if depreciated core tabs are still system tabs
        $sql = "SELECT `title`, `tabid` FROM `#__comprofiler_tabs` WHERE `pluginclass` IN ( 'getNewslettersTab', 'getBlogTab', 'getForumTab', 'getAuthorTab' ) AND `sys` = 1";
        $_CB_database->setQuery($sql);
        $bad_rows = $_CB_database->loadObjectList();
        if ($_CB_database->getErrorNum()) {
            echo '<div class="form-group cb_form_line clearfix text-danger">' . sprintf(CBTxt::T('ERROR: sql query: %s : returned error: %s'), htmlspecialchars($sql), stripslashes($_CB_database->getErrorMsg())) . '</div>';
        } elseif (count($bad_rows) != 0) {
            echo '<div class="form-group cb_form_line clearfix text-danger">' . sprintf(CBTxt::T('Warning: %s entries in Community Builder _comprofiler_tabs have bad sys values.'), count($bad_rows)) . '</div>';
            foreach ($bad_rows as $bad_row) {
                echo '<div class="form-group cb_form_line clearfix text-danger">tab=' . $bad_row->title . ' tabid=' . $bad_row->tabid . '</div>';
            }
            echo '<div class="form-group cb_form_line clearfix text-danger">' . CBTxt::T('This one can be fixed by <strong>first backing up database</strong>') . ' <a href="' . $_CB_framework->backendUrl("index.php?option=com_comprofiler&view=fixcbdeprecdb&{$cbSpoofField}={$cbSpoofString}") . '"> ' . CBTxt::T('then by clicking here') . '</a>.</div>';
        } else {
            echo '<div class="form-group cb_form_line clearfix text-success">' . CBTxt::T('All Community Builder _comprofiler_tabs table sys values are correct.') . '</div>';
        }
        // 12. check if depreciated core fields are still system fields
        $sql = "SELECT `title`, `fieldid` FROM `#__comprofiler_fields` WHERE `type` IN ( 'forumstats', 'forumsettings' ) AND `sys` = 1";
        $_CB_database->setQuery($sql);
        $bad_rows = $_CB_database->loadObjectList();
        if ($_CB_database->getErrorNum()) {
            echo '<div class="form-group cb_form_line clearfix text-danger">' . sprintf(CBTxt::T('ERROR: sql query: %s : returned error: %s'), htmlspecialchars($sql), stripslashes($_CB_database->getErrorMsg())) . '</div>';
        } elseif (count($bad_rows) != 0) {
            echo '<div class="form-group cb_form_line clearfix text-danger">' . sprintf(CBTxt::T('Warning: %s entries in Community Builder _comprofiler_fields have bad sys values.'), count($bad_rows)) . '</div>';
            foreach ($bad_rows as $bad_row) {
                echo '<div class="form-group cb_form_line clearfix text-danger">field=' . $bad_row->title . ' fieldid=' . $bad_row->fieldid . '</div>';
            }
            echo '<div class="form-group cb_form_line clearfix text-danger">' . CBTxt::T('This one can be fixed by <strong>first backing up database</strong>') . ' <a href="' . $_CB_framework->backendUrl("index.php?option=com_comprofiler&view=fixcbdeprecdb&{$cbSpoofField}={$cbSpoofString}") . '"> ' . CBTxt::T('then by clicking here') . '</a>.</div>';
        } else {
            echo '<div class="form-group cb_form_line clearfix text-success">' . CBTxt::T('All Community Builder _comprofiler_fields table sys values are correct.') . '</div>';
        }
        // 13. check if new core plugins are core
        $sql = "SELECT `name`, `id` FROM `#__comprofiler_plugin` WHERE `element` IN ( 'cbarticles', 'cbforums', 'cbblogs' ) AND `iscore` != 1";
        $_CB_database->setQuery($sql);
        $bad_rows = $_CB_database->loadObjectList();
        if ($_CB_database->getErrorNum()) {
            echo '<div class="form-group cb_form_line clearfix text-danger">' . sprintf(CBTxt::T('ERROR: sql query: %s : returned error: %s'), htmlspecialchars($sql), stripslashes($_CB_database->getErrorMsg())) . '</div>';
        } elseif (count($bad_rows) != 0) {
            echo '<div class="form-group cb_form_line clearfix text-danger">' . sprintf(CBTxt::T('Warning: %s entries in Community Builder _comprofiler_plugin have bad iscore values.'), count($bad_rows)) . '</div>';
            foreach ($bad_rows as $bad_row) {
                echo '<div class="form-group cb_form_line clearfix text-danger">plugin=' . $bad_row->name . ' pluginid=' . $bad_row->id . '</div>';
            }
            echo '<div class="form-group cb_form_line clearfix text-danger">' . CBTxt::T('This one can be fixed by <strong>first backing up database</strong>') . ' <a href="' . $_CB_framework->backendUrl("index.php?option=com_comprofiler&view=fixcbdeprecdb&{$cbSpoofField}={$cbSpoofString}") . '"> ' . CBTxt::T('then by clicking here') . '</a>.</div>';
        } else {
            echo '<div class="form-group cb_form_line clearfix text-success">' . CBTxt::T('All Community Builder _comprofiler_plugin table iscore values are correct.') . '</div>';
        }
        // 13. check if new core tabs are core
        $sql = "SELECT `title`, `tabid` FROM `#__comprofiler_tabs` WHERE `pluginclass` IN ( 'cbarticlesTab', 'cbforumsTab', 'cbblogsTab' ) AND `sys` != 1";
        $_CB_database->setQuery($sql);
        $bad_rows = $_CB_database->loadObjectList();
        if ($_CB_database->getErrorNum()) {
            echo '<div class="form-group cb_form_line clearfix text-danger">' . sprintf(CBTxt::T('ERROR: sql query: %s : returned error: %s'), htmlspecialchars($sql), stripslashes($_CB_database->getErrorMsg())) . '</div>';
        } elseif (count($bad_rows) != 0) {
            echo '<div class="form-group cb_form_line clearfix text-danger">' . sprintf(CBTxt::T('Warning: %s entries in Community Builder _comprofiler_tabs have bad sys values.'), count($bad_rows)) . '</div>';
            foreach ($bad_rows as $bad_row) {
                echo '<div class="form-group cb_form_line clearfix text-danger">plugin=' . $bad_row->name . ' pluginid=' . $bad_row->id . '</div>';
            }
            echo '<div class="form-group cb_form_line clearfix text-danger">' . CBTxt::T('This one can be fixed by <strong>first backing up database</strong>') . ' <a href="' . $_CB_framework->backendUrl("index.php?option=com_comprofiler&view=fixcbdeprecdb&{$cbSpoofField}={$cbSpoofString}") . '"> ' . CBTxt::T('then by clicking here') . '</a>.</div>';
        } else {
            echo '<div class="form-group cb_form_line clearfix text-success">' . CBTxt::T('All Community Builder _comprofiler_tabs table sys values are correct.') . '</div>';
        }
        // 14. check if there are duplicate plugins
        $sql = 'SELECT p1.' . $_CB_database->NameQuote('name') . ', p1.' . $_CB_database->NameQuote('id') . "\n FROM " . $_CB_database->NameQuote('#__comprofiler_plugin') . " AS p1" . "\n INNER JOIN " . $_CB_database->NameQuote('#__comprofiler_plugin') . " AS p2" . "\n WHERE p1." . $_CB_database->NameQuote('id') . " > p2." . $_CB_database->NameQuote('id') . "\n AND p1." . $_CB_database->NameQuote('element') . " = p2." . $_CB_database->NameQuote('element');
        $_CB_database->setQuery($sql);
        $bad_rows = $_CB_database->loadObjectList();
        if ($_CB_database->getErrorNum()) {
            echo '<div class="form-group cb_form_line clearfix text-danger">' . sprintf(CBTxt::T('ERROR: sql query: %s : returned error: %s'), htmlspecialchars($sql), stripslashes($_CB_database->getErrorMsg())) . '</div>';
        } elseif (count($bad_rows) != 0) {
            echo '<div class="form-group cb_form_line clearfix text-danger">' . sprintf(CBTxt::T('Warning: %s entries in Community Builder __comprofiler_plugin are duplicates.'), count($bad_rows)) . '</div>';
            foreach ($bad_rows as $bad_row) {
                echo '<div class="form-group cb_form_line clearfix text-danger">plugin=' . $bad_row->name . ' pluginid=' . $bad_row->id . '</div>';
            }
            echo '<div class="form-group cb_form_line clearfix text-danger">' . CBTxt::T('This one can be fixed by <strong>first backing up database</strong>') . ' <a href="' . $_CB_framework->backendUrl("index.php?option=com_comprofiler&view=fixcbmiscdb&{$cbSpoofField}={$cbSpoofString}") . '"> ' . CBTxt::T('then by clicking here') . '</a>.</div>';
        } else {
            echo '<div class="form-group cb_form_line clearfix text-success">' . CBTxt::T('All Community Builder __comprofiler_plugin table rows are unique.') . '</div>';
        }
        cbimport('cb.dbchecker');
        $dbChecker = new CBDatabaseChecker();
        $result = $dbChecker->checkCBMandatoryDb(false);
        $dbName = CBTxt::T('Core CB mandatory basics');
        $messagesAfter = array();
        $messagesBefore = array();
        CBDatabaseChecker::renderDatabaseResults($dbChecker, false, false, $result, $messagesBefore, $messagesAfter, $dbName, $dbId);
        $dbChecker = new CBDatabaseChecker();
        $result = $dbChecker->checkDatabase(false);
        $_PLUGINS->loadPluginGroup('user');
        $messagesAfter = $_PLUGINS->trigger('onAfterCheckCbDb', array(true));
        $dbName = CBTxt::T('Core CB');
        $messagesBefore = array();
        CBDatabaseChecker::renderDatabaseResults($dbChecker, false, false, $result, $messagesBefore, $messagesAfter, $dbName, $dbId);
        echo '</div>';
        // adapt published fields to global CB config (regarding name type)
        _cbAdaptNameFieldsPublished($ueConfig);
    } elseif ($dbId == 1) {
        // Check plugins db:
        $dbName = CBTxt::T('CB plugin');
        $messagesBefore = array();
        $messagesAfter = array();
        $result = true;
        cbimport('cb.installer');
        $sql = 'SELECT `id`, `name` FROM `#__comprofiler_plugin` ORDER BY `ordering`';
        $_CB_database->setQuery($sql);
        $plugins = $_CB_database->loadObjectList();
        if (!$_CB_database->getErrorNum()) {
            $cbInstaller = new cbInstallerPlugin();
            foreach ($plugins as $plug) {
                $result = $cbInstaller->checkDatabase($plug->id, false);
                if (is_bool($result)) {
                    CBDatabaseChecker::renderDatabaseResults($cbInstaller, false, false, $result, $messagesBefore, $messagesAfter, $dbName . ' "' . $plug->name . '"', $dbId, false);
                } elseif (is_string($result)) {
                    echo '<div class="form-group cb_form_line clearfix text-warning">' . $dbName . ' "' . $plug->name . '"' . ': ' . $result . '</div>';
                } else {
                    echo '<div class="form-group cb_form_line clearfix">' . sprintf(CBTxt::T('%s "%s": no database or no database description.'), $dbName, $plug->name) . '</div>';
                }
            }
        }
        $dbName = CBTxt::T('CB plugins');
        $null = null;
        CBDatabaseChecker::renderDatabaseResults($null, false, false, $result, array(), array(), $dbName, $dbId, true);
    } elseif ($dbId == 2) {
        echo '<div class="text-left"><div class="form-group cb_form_line clearfix">' . CBTxt::T('Checking Users Database') . ':</div>';
        // 3.	check if comprofiler table is in sync with users table
        $sql = "SELECT c.id FROM #__comprofiler c LEFT JOIN #__users u ON u.id = c.id WHERE u.id IS NULL";
        $_CB_database->setQuery($sql);
        $bad_rows = $_CB_database->loadObjectList();
        if ($_CB_database->getErrorNum()) {
            echo '<div class="form-group cb_form_line clearfix text-danger">' . sprintf(CBTxt::T('ERROR: sql query: %s : returned error: %s'), htmlspecialchars($sql), stripslashes($_CB_database->getErrorMsg())) . '</div>';
        } elseif (count($bad_rows) != 0) {
            echo '<div class="form-group cb_form_line clearfix text-danger">' . sprintf(CBTxt::T('Warning: %s entries in Community Builder comprofiler table without corresponding user table rows.'), count($bad_rows)) . '</div>';
            $badids = array();
            foreach ($bad_rows as $bad_row) {
                $badids[(int) $bad_row->id] = $bad_row->id;
            }
            echo '<div class="form-group cb_form_line clearfix text-danger">' . sprintf(CBTxt::T('Following comprofiler id: %s are missing in user table'), implode(', ', $badids)) . (isset($badids[0]) ? " " . CBtxt::T('This comprofiler entry with id 0 should be removed, as it\'s not allowed.') : "") . '</div>';
            echo '<div class="form-group cb_form_line clearfix text-danger">' . CBTxt::Th('This one can be fixed using menu Components / Community Builder / tools and then click "Synchronize users".') . '</div>';
        } else {
            echo '<div class="form-group cb_form_line clearfix text-success">' . CBTxt::T('All Community Builder comprofiler table rows have links to user table.') . '</div>';
        }
        // 4.	check if users table is in sync with comprofiler table
        $sql = "SELECT u.id FROM #__users u LEFT JOIN #__comprofiler c ON c.id = u.id WHERE c.id IS NULL";
        $_CB_database->setQuery($sql);
        $bad_rows = $_CB_database->loadObjectList();
        if ($_CB_database->getErrorNum()) {
            echo '<div class="form-group cb_form_line clearfix text-danger">' . sprintf(CBTxt::T('ERROR: sql query: %s : returned error: %s'), htmlspecialchars($sql), stripslashes($_CB_database->getErrorMsg())) . '</div>';
        } elseif (count($bad_rows) != 0) {
            echo '<div class="form-group cb_form_line clearfix text-danger">' . sprintf(CBTxt::T('Warning: %s entries in users table without corresponding comprofiler table rows.'), count($bad_rows)) . '</div>';
            $badids = array();
            foreach ($bad_rows as $bad_row) {
                $badids[(int) $bad_row->id] = $bad_row->id;
            }
            echo '<div class="form-group cb_form_line clearfix text-danger">' . sprintf(CBTxt::T('users id: %s are missing in comprofiler table'), implode(', ', $badids)) . '</div>';
            echo '<div class="form-group cb_form_line clearfix text-danger">' . CBTxt::Th('This one can be fixed using menu Components / Community Builder / tools and then click "Synchronize users".') . '</div>';
        } else {
            echo '<div class="form-group cb_form_line clearfix text-success">' . CBTxt::T('All users table rows have links to comprofiler table.') . '</div>';
        }
        // 6.	check if users table has id=0 in it
        $sql = "SELECT u.id FROM #__users u WHERE u.id = 0";
        $_CB_database->setQuery($sql);
        $bad_rows = $_CB_database->loadObjectList();
        if ($_CB_database->getErrorNum()) {
            echo '<div class="form-group cb_form_line clearfix text-danger">' . sprintf(CBTxt::T('ERROR: sql query: %s : returned error: %s'), htmlspecialchars($sql), stripslashes($_CB_database->getErrorMsg())) . '</div>';
        } elseif (count($bad_rows) != 0) {
            echo '<div class="form-group cb_form_line clearfix text-danger">' . sprintf(CBTxt::T('Warning: %s entries in users table with id=0.'), count($bad_rows)) . '</div>';
            foreach ($bad_rows as $bad_row) {
                echo '<div class="form-group cb_form_line clearfix text-danger">' . sprintf(CBTxt::T('users id=%s is not allowed.'), $bad_row->id) . '</div>';
            }
            echo '<div class="form-group cb_form_line clearfix text-danger">' . CBTxt::Th('This one can be fixed using menu Components / Community Builder / tools and then click "Synchronize users".') . '</div>';
            // echo '<div class="form-group cb_form_line clearfix text-danger">' . CBTxt::T('This one can be fixed in SQL using a tool like phpMyAdmin.') . " <strong><u>" . CBTxt::T('You also need to check in SQL if id is autoincremented.') . "<u><strong></font></p>";
        } else {
            echo '<div class="form-group cb_form_line clearfix text-success">' . CBTxt::T('users table has no zero id row.') . '</div>';
        }
        // 7.	check if comprofiler table has id=0 in it
        $sql = "SELECT c.id FROM #__comprofiler c WHERE c.id = 0";
        $_CB_database->setQuery($sql);
        $bad_rows = $_CB_database->loadObjectList();
        if ($_CB_database->getErrorNum()) {
            echo '<div class="form-group cb_form_line clearfix text-danger">' . sprintf(CBTxt::T('ERROR: sql query: %s : returned error: %s'), htmlspecialchars($sql), stripslashes($_CB_database->getErrorMsg())) . '</div>';
        } elseif (count($bad_rows) != 0) {
            echo '<div class="form-group cb_form_line clearfix text-danger">' . sprintf(CBTxt::T('Warning: %s entries in comprofiler table with id=0.'), count($bad_rows)) . '</div>';
            foreach ($bad_rows as $bad_row) {
                echo '<div class="form-group cb_form_line clearfix text-danger">' . sprintf(CBTxt::T('comprofiler id=%s is not allowed.'), $bad_row->id) . '</div>';
            }
            echo '<div class="form-group cb_form_line clearfix text-danger">' . CBTxt::Th('This one can be fixed using menu Components / Community Builder / Tools and then click "Synchronize users".') . '</div>';
        } else {
            echo '<div class="form-group cb_form_line clearfix text-success">' . CBTxt::T('comprofiler table has no zero id row.') . '</div>';
        }
        // 8.	check if comprofiler table has user_id != id in it
        $sql = "SELECT c.id, c.user_id FROM #__comprofiler c WHERE c.id <> c.user_id";
        $_CB_database->setQuery($sql);
        $bad_rows = $_CB_database->loadObjectList();
        if ($_CB_database->getErrorNum()) {
            echo '<div class="form-group cb_form_line clearfix text-danger">' . sprintf(CBTxt::T('ERROR: sql query: %s : returned error: %s'), htmlspecialchars($sql), stripslashes($_CB_database->getErrorMsg())) . '</div>';
        } elseif (count($bad_rows) != 0) {
            echo '<div class="form-group cb_form_line clearfix text-danger">' . sprintf(CBTxt::T('Warning: %s entries in comprofiler table with user_id <> id.'), count($bad_rows)) . '</div>';
            foreach ($bad_rows as $bad_row) {
                echo '<div class="form-group cb_form_line clearfix text-danger">' . sprintf(CBTxt::T('comprofiler id=%s is different from user_id=%s.'), $bad_row->id, $bad_row->user_id) . '</div>';
            }
            echo '<div class="form-group cb_form_line clearfix text-danger">' . CBTxt::Th('This one can be fixed using menu Components / Community Builder / tools and then click "Synchronize users".') . '</div>';
        } else {
            echo '<div class="form-group cb_form_line clearfix text-success">' . CBTxt::T('All rows in comprofiler table have user_id columns identical to id columns.') . '</div>';
        }
        // 10.	check if #__user_usergroup_map table is in sync with users table	: A: user -> aro
        if (!cbStartOfStringMatch($version, '3.23')) {
            $sql = "SELECT u.id FROM #__users u LEFT JOIN #__user_usergroup_map a ON a.user_id = CAST( u.id AS CHAR ) WHERE a.user_id IS NULL";
        } else {
            $sql = "SELECT u.id FROM #__users u LEFT JOIN #__user_usergroup_map a ON a.user_id = u.id WHERE a.user_id IS NULL";
        }
        $_CB_database->setQuery($sql);
        $bad_rows = $_CB_database->loadObjectList();
        if ($_CB_database->getErrorNum()) {
            echo '<div class="form-group cb_form_line clearfix text-danger">' . sprintf(CBTxt::T('ERROR: sql query: %s : returned error: %s'), htmlspecialchars($sql), stripslashes($_CB_database->getErrorMsg())) . '</div>';
        } elseif (count($bad_rows) != 0) {
            echo '<div class="form-group cb_form_line clearfix text-danger">' . sprintf(CBTxt::T('Warning: %s entries in the users table without corresponding user_usergroup_map table rows.'), count($bad_rows)) . '</div>';
            $badids = array();
            foreach ($bad_rows as $bad_row) {
                $badids[(int) $bad_row->id] = $bad_row->id;
            }
            echo '<div class="form-group cb_form_line clearfix text-danger">' . sprintf(CBTxt::T('user id: %s are missing in user_usergroup_map table'), implode(', ', $badids));
            echo (isset($badids[0]) ? " " . CBTxt::T('This user entry with id 0 should be removed, as it\'s not allowed.') : "") . '</div>';
            echo '<div class="form-group cb_form_line clearfix text-danger">' . CBTxt::T('This one can be fixed by <strong>first backing up database</strong>') . ' <a href="' . $_CB_framework->backendUrl("index.php?option=com_comprofiler&view=fixacldb&{$cbSpoofField}={$cbSpoofString}") . '">' . CBTxt::T('then by clicking here') . '</a>.</div>';
        } else {
            echo '<div class="form-group cb_form_line clearfix text-success">' . CBTxt::T('All users table rows have ACL entries in user_usergroup_map table.') . '</div>';
        }
        // 11.	check if #__user_usergroup_map table is in sync with users table	: B: aro -> user
        $sql = "SELECT a.user_id AS id FROM #__user_usergroup_map a LEFT JOIN #__users u ON u.id = a.user_id WHERE u.id IS NULL";
        $_CB_database->setQuery($sql);
        $bad_rows = $_CB_database->loadObjectList();
        if ($_CB_database->getErrorNum()) {
            echo '<div class="form-group cb_form_line clearfix text-danger">' . sprintf(CBTxt::Th('ERROR: sql query: %s : returned error: %s'), htmlspecialchars($sql), stripslashes($_CB_database->getErrorMsg())) . '</div>';
        } elseif (count($bad_rows) != 0) {
            echo '<div class="form-group cb_form_line clearfix text-danger">' . sprintf(CBTxt::Th('Warning: %s entries in the __user_usergroup_map table without corresponding users table rows.'), count($bad_rows)) . '</div>';
            $badids = array();
            foreach ($bad_rows as $bad_row) {
                $badids[(int) $bad_row->id] = "user id=" . $bad_row->id;
            }
            echo '<div class="form-group cb_form_line clearfix text-danger">' . CBTxt::Th('DATABASE_CHECK_ENTRIES_OF_TABLE_MISSING_IN_TABLE', 'Following entries of [tablename1] table are missing in [tablename2] table: [badids].', array('[tablename1]' => 'user_usergroup_map', '[tablename2]' => 'users', '[badids]' => implode(', ', $badids))) . (isset($badids[0]) ? "<br /> " . CBTxt::T('This user_usergroup_map entry with (user) value 0 should be removed, as it\'s not allowed.') : "") . '</div>';
            echo '<div class="form-group cb_form_line clearfix text-danger">' . CBTxt::Th('This one can be fixed by <strong>first backing up database</strong>') . ' <a href="' . $_CB_framework->backendUrl("index.php?option=com_comprofiler&view=fixacldb&{$cbSpoofField}={$cbSpoofString}") . '">' . CBTxt::T('then by clicking here') . '</a>.</div>';
        } else {
            echo '<div class="form-group cb_form_line clearfix text-success">' . CBTxt::Th('DATABASE_CHECK_ALL_ENTRIES_OF_TABLE_HAVE_CORRESPONDANCE_IN_TABLE', 'All [tablename1] table rows have corresponding entries in [tablename2] table.', array('[tablename1]' => 'ACL user_usergroup_map', '[tablename2]' => 'users')) . '</div>';
        }
        $dbName = CBTxt::T('Users');
        echo '</div>';
    } elseif ($dbId == 3) {
        // adapt published fields to global CB config (regarding name type)
        _cbAdaptNameFieldsPublished($ueConfig);
        $strictcolumns = cbGetParam($_REQUEST, 'strictcolumns', 0) == 1;
        // Check fields db:
        cbimport('cb.dbchecker');
        $dbChecker = new CBDatabaseChecker();
        $result = $dbChecker->checkAllCBfieldsDb(false, false, $strictcolumns);
        $dbName = CBTxt::T('CB fields data storage');
        $messagesBefore = array();
        $_PLUGINS->loadPluginGroup('user');
        $messagesAfter = $_PLUGINS->trigger('onAfterCheckCbFieldsDb', array(true));
        if ($strictcolumns) {
            $dbId = $dbId . '&strictcolumns=1';
        }
        CBDatabaseChecker::renderDatabaseResults($dbChecker, false, false, $result, $messagesBefore, $messagesAfter, $dbName, $dbId);
    } else {
        $dbName = CBTxt::T('DATABASE_CHECK_NO_DATABASE_SPECIFIED', 'No Database Specified');
    }
    global $_CB_Backend_Title;
    $_CB_Backend_Title = array(0 => array('fa fa-wrench', sprintf(CBTxt::T("CB Tools: Check %s database: Results"), $dbName)));
}
	function editTab( $tid='0', $option='com_comprofiler', $task='editTab' ) {
		global $_CB_database, $_CB_framework, $_PLUGINS;

		$this->_importNeeded();

		$row = new moscomprofilerTabs( $_CB_database );
		// load the row from the db table
		$row->load( (int) $tid );
	
		if ( $tid && ! in_array( $row->useraccessgroupid, getChildGIDS( userGID( $_CB_framework->myId() ) ) ) ) {
			echo "<script type=\"text/javascript\"> alert('" . addslashes( CBTxt::T('Unauthorized Access') ) . "'); window.history.go(-1);</script>\n";
			exit;
		}
	 	$lists = array();
		if($row->sys=='2') $lists['enabled'] = "Yes";
		else $lists['enabled'] = moscomprofilerHTML::yesnoSelectList( 'enabled', 'class="inputbox" size="1"', ( $row->enabled !== null ? $row->enabled : 1 ) );
	
		/*
		-------------------------
		!          head         !
		!-----------------------!
		!      !        !       !
		! left ! middle ! right !
		!      !        !       !
		!-----------------------!
		!                       !
		!        tabmain        !
		!                       !
		!-----------------------!
		!        underall       !
		-------------------------
		!      !        !       !
		! L1C1 ! L1C2   ! L1C3  !   L1C1...C9
		!      !        !       !
		!-----------------------!
		!      !        !       !
		! L2C1 ! L2C4   ! L2C8  !   ...
		!      !        !       !
		!-----------------------!
		!                       !
		!        L4C7           !
		!                       !
		!-----------------------!
		!          !            !
		!   L8C3   !    L8C4    !   ...L9C9
		!          !            !
		!-----------------------!
	    ! + not_on_profile_1..9
		*/
		$position = array();
		$position[] = moscomprofilerHTML::makeOption( 'cb_head', _UE_POS_CB_HEAD );
		$position[] = moscomprofilerHTML::makeOption( 'cb_left', _UE_POS_CB_LEFT );
		$position[] = moscomprofilerHTML::makeOption( 'cb_middle', _UE_POS_CB_MIDDLE );
		$position[] = moscomprofilerHTML::makeOption( 'cb_right', _UE_POS_CB_RIGHT );
		$position[] = moscomprofilerHTML::makeOption( 'cb_tabmain', _UE_POS_CB_MAIN );
		$position[] = moscomprofilerHTML::makeOption( 'cb_underall', _UE_POS_CB_BOTTOM );
		for ( $i = 1 ; $i <= 9; $i++ ) {
			for ( $j = 1 ; $j <= 9; $j++ ) {
				$position[] = moscomprofilerHTML::makeOption( 'L'.$i.'C'.$j, CBTxt::T('Line') . ' ' . $i . ' ' . CBTxt::T('Column') . ' ' . $j );
			}
		}
		for ( $i = 1 ; $i <= 9; $i++ ) {
			$position[] = moscomprofilerHTML::makeOption( 'not_on_profile_'.$i, CBTxt::T('Not displayed on profile') . ' ' . $i );
		}
	
		if ( ! $row->position ) {
			$row->position		=	'cb_tabmain';
		}
		$lists['position'] = moscomprofilerHTML::selectList( $position, 'position', 'class="inputbox" size="1"', 'value', 'text', $row->position, 2 );
	
		$displaytype = array();
		$displaytype[] = moscomprofilerHTML::makeOption( 'tab', _UE_DISPLAY_TAB );
		$displaytype[] = moscomprofilerHTML::makeOption( 'div', _UE_DISPLAY_DIV );
		$displaytype[] = moscomprofilerHTML::makeOption( 'rounddiv', _UE_DISPLAY_ROUNDED_DIV );
		$displaytype[] = moscomprofilerHTML::makeOption( 'html', _UE_DISPLAY_HTML );
		$displaytype[] = moscomprofilerHTML::makeOption( 'overlib', _UE_DISPLAY_OVERLIB );
		$displaytype[] = moscomprofilerHTML::makeOption( 'overlibfix', _UE_DISPLAY_OVERLIBFIX );
		$displaytype[] = moscomprofilerHTML::makeOption( 'overlibsticky', _UE_DISPLAY_OVERLIBSTICKY );
		if ( ! $row->displaytype ) {
			$row->displaytype	=	'tab';
		}
		$lists['displaytype'] = moscomprofilerHTML::selectList( $displaytype, 'displaytype', 'class="inputbox" size="1"', 'value', 'text', $row->displaytype, 2 );
	
		if ($tid) {
			if ( $row->ordering > -10000 && $row->ordering < 10000 ) {
				// build the html select list for ordering
				$query = "SELECT ordering AS value, title AS text"
				. "\n FROM #__comprofiler_tabs"
				. "\n WHERE position='" . $_CB_database->getEscaped( $row->position ) . "'"
				. "\n AND enabled > 0"
				. "\n AND ordering > -10000"
				. "\n AND ordering < 10000"
				. "\n ORDER BY ordering"
				;
				$order = $this->_cbGetOrderingList( $query );
				$lists['ordering'] = moscomprofilerHTML::selectList( $order, 'ordering', 'class="inputbox" size="1"', 'value', 'text', intval( $row->ordering ), 2 );
			} else {
				$lists['ordering'] = '<input type="hidden" name="ordering" value="'. $row->ordering .'" />' . CBTxt::T('This plugin cannot be reordered') ;
			}
		} else {
			$row->ordering 				= 999;
			$row->ordering_register		= 10;
			$row->published 			= 1;
			$row->description 			= '';
			$row->useraccessgroupid		= -2;
			$lists['ordering']	= '<input type="hidden" name="ordering" value="'. $row->ordering
								.'" />'. CBTxt::T('New items default to the last place. Ordering can be changed after this item is saved.');
		}
	
		$gtree3=array();
	    $gtree3[] = moscomprofilerHTML::makeOption( -2 , '- ' . CBtxt::T('Everybody') . ' -' );
	    $gtree3[] = moscomprofilerHTML::makeOption( -1 , '- ' . CBtxt::T('All Registered Users') . ' -' );
		$gtree3 = array_merge( $gtree3, $_CB_framework->acl->get_group_children_tree( null, 'USERS', false ));
	
		$lists['useraccessgroup']=moscomprofilerHTML::selectList( $gtree3, 'useraccessgroupid', 'size="4"', 'value', 'text', $row->useraccessgroupid, 2, false );
	
		// params:
		$paramsEditorHtml			=	array();
		$options					=	array( 'option' => $option, 'task' => $task, 'cid' => $row->tabid );
	
		// additional non-specific other parameters:
		$_PLUGINS->loadPluginGroup( 'user' );
	
		$fieldsParamsPlugins		=	$_PLUGINS->getUserTabParamsPluginIds();
		foreach ($fieldsParamsPlugins as $pluginId => $fieldParamHandlerClassName ) {
			$fieldParamHandler		=	new $fieldParamHandlerClassName( $pluginId, $row );			// cbFieldParamsHandler();
			$addParamsHtml			=	$fieldParamHandler->drawParamsEditor( $options );
			if ( $addParamsHtml ) {
				$addParamsTitle		=	$fieldParamHandler->getFieldsParamsLabel();
				$paramsEditorHtml[]	=	array( 'title' => $addParamsTitle, 'content' => $addParamsHtml );
			}
		}
	
		$pluginView				=	_CBloadView( 'tab' );
		$pluginView->edittab( $row, $option, $lists, $tid, $paramsEditorHtml );
	}
function checkcbdb($dbId = 0)
{
    global $_CB_database, $_CB_framework, $ueConfig, $_PLUGINS;
    // Try extending time, as unziping/ftping took already quite some... :
    @set_time_limit(240);
    HTML_comprofiler::secureAboveForm('checkcbdb');
    outputCbTemplate(2);
    outputCbJs(2);
    global $_CB_Backend_Title;
    $_CB_Backend_Title = array(0 => array('cbicon-48-tools', CBTxt::T('CB Tools: Check database: Results')));
    $cbSpoofField = cbSpoofField();
    $cbSpoofString = cbSpoofString(null, 'cbtools');
    $version = $_CB_database->getVersion();
    $version = substr($version, 0, strpos($version, '-'));
    if ($dbId == 0) {
        echo "<div style='text-align:left;'><p>" . CBTxt::T('Checking Community Builder Database') . ":</p>";
        // 1. check comprofiler_field_values table for bad rows
        $sql = "SELECT fieldvalueid,fieldid FROM #__comprofiler_field_values WHERE fieldid=0";
        $_CB_database->setQuery($sql);
        $bad_rows = $_CB_database->loadObjectList();
        if ($_CB_database->getErrorNum()) {
            echo "<p><font color=red>" . sprintf(CBTxt::T('ERROR: sql query: %s : returned error: %s'), htmlspecialchars($sql), stripslashes($_CB_database->getErrorMsg())) . "</font></p>";
        } elseif (count($bad_rows) != 0) {
            echo "<p><font color=red>" . sprintf(CBTxt::T('Warning: %s entries in Community Builder comprofiler_field_values have bad fieldid values.'), count($bad_rows)) . "</font></p>";
            foreach ($bad_rows as $bad_row) {
                if ($bad_row->fieldvalueid == 0) {
                    echo "<p><font color=red>" . sprintf(CBTxt::T('ZERO fieldvalueid illegal: fieldvalueid=%s fieldid=0'), $bad_row->fieldvalueid) . "</font></p>";
                } else {
                    echo "<p><font color=red>fieldvalueid=" . $bad_row->fieldvalueid . " fieldid=0</font></p>";
                }
            }
            echo '<p><font color=red>' . CBTxt::T('This one can be fixed by <strong>first backing up database</strong>') . ' <a href="' . $_CB_framework->backendUrl("index.php?option=com_comprofiler&task=fixcbmiscdb&{$cbSpoofField}={$cbSpoofString}") . '"> ' . CBTxt::T('then by clicking here') . '</a>.</font></p>';
        } else {
            echo "<p><font color=green>" . CBTxt::T('All Community Builder comprofiler_field_values table fieldid rows all match existing fields.') . "</font></p>";
        }
        // 2.	check if comprofiler_field_values table has entries where corresponding fieldtype value in comprofiler_fields table
        //		does not allow values
        $sql = "SELECT v.fieldvalueid, v.fieldid, f.name, f.type FROM #__comprofiler_field_values as v, #__comprofiler_fields as f WHERE v.fieldid = f.fieldid AND f.type NOT IN ('checkbox','multicheckbox','select','multiselect','radio')";
        $_CB_database->setQuery($sql);
        $bad_rows = $_CB_database->loadObjectList();
        if ($_CB_database->getErrorNum()) {
            echo "<p><font color=red>" . sprintf(CBTxt::T('ERROR: sql query: %s : returned error: %s'), htmlspecialchars($sql), stripslashes($_CB_database->getErrorMsg())) . "</font></p>";
        } elseif (count($bad_rows) != 0) {
            echo "<p><font color=red>" . sprintf(CBTxt::T('Warning: %s entries in Community Builder comprofiler_field_values link back to fields of wrong fieldtype.'), count($bad_rows)) . "</font></p>";
            foreach ($bad_rows as $bad_row) {
                echo "<p><font color=red>fieldvalueid=" . $bad_row->fieldvalueid . " fieldtype=" . $bad_row->type . "</font></p>";
            }
            echo "<p><font color=red>" . CBTxt::T('This one can be fixed in SQL using a tool like phpMyAdmin.') . "</font></p>";
            // not done automatically since some fields might have field values ! echo '<p><font color=red>This one can be fixed by <strong>first backing up database</strong> then <a href="' . $_CB_framework->backendUrl( "index.php?option=com_comprofiler&task=fixcbmiscdb&$cbSpoofField=$cbSpoofString" ) . '">by clicking here</a>.</font></p>';
        } else {
            echo "<p><font color=green>" . CBTxt::T('All Community Builder comprofiler_field_values table rows link to correct fieldtype fields in comprofiler_field table.') . "</font></p>";
        }
        // 5.	check if all cb defined fields have corresponding comprofiler columns
        $sql = "SELECT * FROM #__comprofiler";
        $_CB_database->setQuery($sql, 0, 1);
        $all_comprofiler_fields_and_values = $_CB_database->loadAssoc();
        $all_comprofiler_fields = array();
        if ($all_comprofiler_fields_and_values === null) {
            echo "<p><font color=red>" . sprintf(CBTxt::T('ERROR: sql query: %s : returned error: %s'), htmlspecialchars($sql), stripslashes($_CB_database->getErrorMsg())) . "</font></p>";
        } elseif (is_array($all_comprofiler_fields_and_values)) {
            while (false != (list($_cbfield) = each($all_comprofiler_fields_and_values))) {
                array_push($all_comprofiler_fields, $_cbfield);
            }
        }
        $sql = "SELECT * FROM #__comprofiler_fields WHERE `name` != 'NA' AND `table` = '#__comprofiler'";
        $_CB_database->setQuery($sql);
        $field_rows = $_CB_database->loadObjectList(null, 'moscomprofilerFields', array(&$_CB_database));
        if ($_CB_database->getErrorNum()) {
            echo "<p><font color=red>" . sprintf(CBTxt::T('ERROR: sql query: %s : returned error: %s'), htmlspecialchars($sql), stripslashes($_CB_database->getErrorMsg())) . "</font></p>";
        } else {
            $html_output = array();
            $cb11 = true;
            foreach ($field_rows as $field_row) {
                if ($field_row->tablecolumns !== null) {
                    // CB 1.2 way:
                    if ($field_row->tablecolumns != '') {
                        $tableColumns = explode(',', $field_row->tablecolumns);
                        foreach ($tableColumns as $col) {
                            if (!in_array($col, $all_comprofiler_fields)) {
                                $html_output[] = "<p><font color=red>" . sprintf(CBTxt::T(' - Field %s - Column %s is missing from comprofiler table.'), $field_row->name, $col) . "</font></p>";
                            }
                        }
                    }
                    $cb11 = false;
                } else {
                    // cb 1.1 way
                    if (!in_array($field_row->name, $all_comprofiler_fields)) {
                        $html_output[] = "<p><font color=red>" . sprintf(CBTxt::T(' - Column %s is missing from comprofiler table.'), $field_row->name) . "</font></p>";
                    }
                }
            }
            if (count($html_output) > 0) {
                echo "<p><font color=red>" . sprintf(CBTxt::T('There are %s column(s) missing in the comprofiler table, which are defined as fields (rows in comprofiler_fields):'), count($html_output)) . "</font></p>";
                echo implode('', $html_output);
                echo "<p><font color=red>" . CBTxt::T('This one can be fixed by deleting and recreating the field(s) using components / Community Builder / Field Management.') . '<br />' . CBTxt::T('Please additionally make sure that columns in comprofiler table <strong>are not also duplicated in users table</strong>.') . "</font></p>";
            } elseif ($cb11) {
                echo "<p><font color=red>" . CBTxt::T('All Community Builder fields from comprofiler_fields are present as columns in the comprofiler table, but comprofiler_fields table is not yet upgraded to CB 1.2 table structure. Just going to Community Builder Fields Management will fix this automatically.') . "</font></p>";
            } else {
                echo "<p><font color=green>" . CBTxt::T('All Community Builder fields from comprofiler_fields are present as columns in the comprofiler table.') . "</font></p>";
            }
        }
        // 9. Check if images/comprofiler is writable:
        $folder = 'images/comprofiler/';
        if ($ueConfig['allowAvatarUpload'] == 1) {
            echo "<p>Checking Community Builder folders:</p>";
            if (!is_writable($_CB_framework->getCfg('absolute_path') . '/' . $folder)) {
                echo '<font color="red">' . sprintf(CBTxt::T('Avatars and thumbnails folder: %s/%s is NOT writeable by the webserver.'), $_CB_framework->getCfg('absolute_path'), $folder) . ' </font>';
            } else {
                echo '<font color="green">' . CBTxt::T('Avatars and thumbnails folder is Writeable.') . '</font>';
            }
        }
        cbimport('cb.dbchecker');
        $dbChecker = new CBdbChecker($_CB_database);
        $result = $dbChecker->checkCBMandatoryDb(false);
        $dbName = CBTxt::T('Core CB mandatory basics');
        $messagesAfter = array();
        $messagesBefore = array();
        HTML_comprofiler::fixcbdbShowResults($dbChecker, false, false, $result, $messagesBefore, $messagesAfter, $dbName, $dbId);
        $dbChecker = new CBdbChecker($_CB_database);
        $result = $dbChecker->checkDatabase(false);
        $_PLUGINS->loadPluginGroup('user');
        $messagesAfter = $_PLUGINS->trigger('onAfterCheckCbDb', true);
        $dbName = CBTxt::T('Core CB');
        $messagesBefore = array();
        HTML_comprofiler::fixcbdbShowResults($dbChecker, false, false, $result, $messagesBefore, $messagesAfter, $dbName, $dbId);
        echo '</div>';
        // adapt published fields to global CB config (regarding name type)
        _cbAdaptNameFieldsPublished($ueConfig);
    } elseif ($dbId == 1) {
        // Check plugins db:
        $dbName = CBTxt::T('CB plugin');
        $messagesBefore = array();
        $messagesAfter = array();
        cbimport('cb.installer');
        $sql = 'SELECT `id`, `name` FROM `#__comprofiler_plugin` ORDER BY `ordering`';
        $_CB_database->setQuery($sql);
        $plugins = $_CB_database->loadObjectList();
        if (!$_CB_database->getErrorNum()) {
            $cbInstaller = new cbInstallerPlugin();
            foreach ($plugins as $plug) {
                $result = $cbInstaller->checkDatabase($plug->id, false);
                if (is_bool($result)) {
                    HTML_comprofiler::fixcbdbShowResults($cbInstaller, false, false, $result, $messagesBefore, $messagesAfter, $dbName . ' "' . $plug->name . '"', $dbId, false);
                } elseif (is_string($result)) {
                    echo '<div style="color:orange;">' . $dbName . ' "' . $plug->name . '"' . ': ' . $result . '</div>';
                } else {
                    echo '<div style="color:black;">' . sprintf(CBTxt::T('%s "%s": no database or no database description.'), $dbName, $plug->name) . '</div>';
                }
            }
        }
        $dbName = CBTxt::T('CB plugins');
        $null = null;
        HTML_comprofiler::fixcbdbShowResults($null, false, false, $result, array(), array(), $dbName, $dbId, true);
    } elseif ($dbId == 2) {
        echo "<div style='text-align:left;'><p>" . CBTxt::T('Checking Users Database') . ":</p>";
        // 3.	check if comprofiler table is in sync with users table
        $sql = "SELECT c.id FROM #__comprofiler c LEFT JOIN #__users u ON u.id = c.id WHERE u.id IS NULL";
        $_CB_database->setQuery($sql);
        $bad_rows = $_CB_database->loadObjectList();
        if ($_CB_database->getErrorNum()) {
            echo "<p><font color=red>" . sprintf(CBTxt::T('ERROR: sql query: %s : returned error: %s'), htmlspecialchars($sql), stripslashes($_CB_database->getErrorMsg())) . "</font></p>";
        } elseif (count($bad_rows) != 0) {
            echo "<p><font color=red>" . sprintf(CBTxt::T('Warning: %s entries in Community Builder comprofiler table without corresponding user table rows.'), count($bad_rows)) . "</font></p>";
            $badids = array();
            foreach ($bad_rows as $bad_row) {
                $badids[(int) $bad_row->id] = $bad_row->id;
            }
            echo "<p><font color=red>" . sprintf(CBTxt::T('Following comprofiler id: %s are missing in user table'), implode(', ', $badids)) . (isset($badids[0]) ? " " . CBtxt::T('This comprofiler entry with id 0 should be removed, as it\'s not allowed.') : "") . "</font></p>";
            echo "<p><font color=red>" . CBTxt::T('This one can be fixed using menu Components-&gt; Community Builder-&gt; tools and then click `Synchronize users`.') . "</font></p>";
        } else {
            echo "<p><font color=green>" . CBTxt::T('All Community Builder comprofiler table rows have links to user table.') . "</font></p>";
        }
        // 4.	check if users table is in sync with comprofiler table
        $sql = "SELECT u.id FROM #__users u LEFT JOIN #__comprofiler c ON c.id = u.id WHERE c.id IS NULL";
        $_CB_database->setQuery($sql);
        $bad_rows = $_CB_database->loadObjectList();
        if ($_CB_database->getErrorNum()) {
            echo "<p><font color=red>" . sprintf(CBTxt::T('ERROR: sql query: %s : returned error: %s'), htmlspecialchars($sql), stripslashes($_CB_database->getErrorMsg())) . "</font></p>";
        } elseif (count($bad_rows) != 0) {
            echo "<p><font color=red>" . sprintf(CBTxt::T('Warning: %s entries in users table without corresponding comprofiler table rows.'), count($bad_rows)) . "</font></p>";
            $badids = array();
            foreach ($bad_rows as $bad_row) {
                $badids[(int) $bad_row->id] = $bad_row->id;
            }
            echo "<p><font color=red>" . sprintf(CBTxt::T('users id: %s are missing in comprofiler table'), implode(', ', $badids)) . "</font></p>";
            echo "<p><font color=red>" . CBTxt::T('This one can be fixed using menu Components-&gt; Community Builder-&gt; tools and then click `Synchronize users`.') . "</font></p>";
        } else {
            echo "<p><font color=green>" . CBTxt::T('All users table rows have links to comprofiler table.') . "</font></p>";
        }
        // 6.	check if users table has id=0 in it
        $sql = "SELECT u.id FROM #__users u WHERE u.id = 0";
        $_CB_database->setQuery($sql);
        $bad_rows = $_CB_database->loadObjectList();
        if ($_CB_database->getErrorNum()) {
            echo "<p><font color=red>" . sprintf(CBTxt::T('ERROR: sql query: %s : returned error: %s'), htmlspecialchars($sql), stripslashes($_CB_database->getErrorMsg())) . "</font></p>";
        } elseif (count($bad_rows) != 0) {
            echo "<p><font color=red>" . sprintf(CBTxt::T('Warning: %s entries in users table with id=0.'), count($bad_rows)) . "</font></p>";
            foreach ($bad_rows as $bad_row) {
                echo "<p><font color=red>" . sprintf(CBTxt::T('users id=%s is not allowed.'), $bad_row->id) . "</font></p>";
            }
            echo "<p><font color=red>" . CBTxt::T('This one can be fixed using menu Components-&gt; Community Builder-&gt; tools and then click `Synchronize users`.') . "</font></p>";
            // echo "<p><font color=red>" . CBTxt::T('This one can be fixed in SQL using a tool like phpMyAdmin.') . " <strong><u>" . CBTxt::T('You also need to check in SQL if id is autoincremented.') . "<u><strong></font></p>";
        } else {
            echo "<p><font color=green>" . CBTxt::T('users table has no zero id row.') . "</font></p>";
        }
        // 7.	check if comprofiler table has id=0 in it
        $sql = "SELECT c.id FROM #__comprofiler c WHERE c.id = 0";
        $_CB_database->setQuery($sql);
        $bad_rows = $_CB_database->loadObjectList();
        if ($_CB_database->getErrorNum()) {
            echo "<p><font color=red>" . sprintf(CBTxt::T('ERROR: sql query: %s : returned error: %s'), htmlspecialchars($sql), stripslashes($_CB_database->getErrorMsg())) . "</font></p>";
        } elseif (count($bad_rows) != 0) {
            echo "<p><font color=red>" . sprintf(CBTxt::T('Warning: %s entries in comprofiler table with id=0.'), count($bad_rows)) . "</font></p>";
            foreach ($bad_rows as $bad_row) {
                echo "<p><font color=red>" . sprintf(CBTxt::T('comprofiler id=%s is not allowed.'), $bad_row->id) . "</font></p>";
            }
            echo "<p><font color=red>" . CBTxt::T('This one can be fixed using menu Components / Community Builder / Tools and then click "Synchronize users".') . "</font></p>";
        } else {
            echo "<p><font color=green>" . CBTxt::T('comprofiler table has no zero id row.') . "</font></p>";
        }
        // 8.	check if comprofiler table has user_id != id in it
        $sql = "SELECT c.id, c.user_id FROM #__comprofiler c WHERE c.id <> c.user_id";
        $_CB_database->setQuery($sql);
        $bad_rows = $_CB_database->loadObjectList();
        if ($_CB_database->getErrorNum()) {
            echo "<p><font color=red>" . sprintf(CBTxt::T('ERROR: sql query: %s : returned error: %s'), htmlspecialchars($sql), stripslashes($_CB_database->getErrorMsg())) . "</font></p>";
        } elseif (count($bad_rows) != 0) {
            echo "<p><font color=red>" . sprintf(CBTxt::T('Warning: %s entries in comprofiler table with user_id <> id.'), count($bad_rows)) . "</font></p>";
            foreach ($bad_rows as $bad_row) {
                echo "<p><font color=red>" . sprintf(CBTxt::T('comprofiler id=%s is different from user_id=%s.'), $bad_row->id, $bad_row->user_id) . "</font></p>";
            }
            echo "<p><font color=red>" . CBTxt::T('This one can be fixed using menu Components-&gt; Community Builder-&gt; tools and then click `Synchronize users`.') . "</font></p>";
        } else {
            echo "<p><font color=green>" . CBTxt::T('All rows in comprofiler table have user_id columns identical to id columns.') . "</font></p>";
        }
        // 10.	check if #__core_acl_aro table is in sync with users table	: A: user -> aro
        if (!cbStartOfStringMatch($version, '3.23')) {
            if (checkJversion() == 2) {
                $sql = "SELECT u.id FROM #__users u LEFT JOIN #__user_usergroup_map a ON a.user_id = CAST( u.id AS CHAR ) WHERE a.user_id IS NULL";
            } else {
                $sql = "SELECT u.id FROM #__users u LEFT JOIN #__core_acl_aro a ON a.section_value = 'users' AND a.value = CAST( u.id AS CHAR ) WHERE a.value IS NULL";
            }
        } else {
            if (checkJversion() == 2) {
                $sql = "SELECT u.id FROM #__users u LEFT JOIN #__user_usergroup_map a ON a.user_id = u.id WHERE a.user_id IS NULL";
            } else {
                $sql = "SELECT u.id FROM #__users u LEFT JOIN #__core_acl_aro a ON a.section_value = 'users' AND a.value = u.id WHERE a.value IS NULL";
            }
        }
        // SELECT u.id FROM jos_users u LEFT JOIN jos_core_acl_aro a ON a.section_value = 'users' AND a.value = CAST( u.id AS CHAR ) WHERE a.value IS NULL
        // INSERT INTO jos_core_acl_aro (section_value,value,order_value,name,hidden) SELECT 'users' AS section_value, u.id AS value, 0 AS order_value, u.name as name, 0 AS hidden FROM jos_users u LEFT JOIN jos_core_acl_aro a ON a.section_value = 'users' AND a.value = CAST( u.id AS CHAR ) WHERE a.value IS NULL;
        $_CB_database->setQuery($sql);
        $bad_rows = $_CB_database->loadObjectList();
        if ($_CB_database->getErrorNum()) {
            echo "<p><font color=red>" . sprintf(CBTxt::T('ERROR: sql query: %s : returned error: %s'), htmlspecialchars($sql), stripslashes($_CB_database->getErrorMsg())) . "</font></p>";
        } elseif (count($bad_rows) != 0) {
            echo "<p><font color=red>";
            if (checkJversion() == 2) {
                echo sprintf(CBTxt::T('Warning: %s entries in the users table without corresponding user_usergroup_map table rows.'), count($bad_rows));
            } else {
                echo sprintf(CBTxt::T('Warning: %s entries in the users table without corresponding core_acl_aro table rows.'), count($bad_rows));
            }
            echo "</font></p>";
            $badids = array();
            foreach ($bad_rows as $bad_row) {
                $badids[(int) $bad_row->id] = $bad_row->id;
            }
            echo "<p><font color=red>";
            if (checkJversion() == 2) {
                echo sprintf(CBTxt::T('user id: %s are missing in user_usergroup_map table'), implode(', ', $badids));
            } else {
                echo sprintf(CBTxt::T('user id: %s are missing in core_acl_aro table'), implode(', ', $badids));
            }
            echo (isset($badids[0]) ? " " . CBTxt::T('This user entry with id 0 should be removed, as it\'s not allowed.') : "") . "</font></p>";
            echo '<p><font color=red>' . CBTxt::T('This one can be fixed by <strong>first backing up database</strong>') . ' <a href="' . $_CB_framework->backendUrl("index.php?option=com_comprofiler&task=fixacldb&{$cbSpoofField}={$cbSpoofString}") . '">' . CBTxt::T('then by clicking here') . '</a>.</font></p>';
        } else {
            echo "<p><font color=green>";
            if (checkJversion() == 2) {
                echo CBTxt::T('All users table rows have ACL entries in user_usergroup_map table.');
            } else {
                echo CBTxt::T('All users table rows have ACL entries in core_acl_aro table.');
            }
            echo "</font></p>";
        }
        // 11.	check if #__core_acl_aro table is in sync with users table	: B: aro -> user
        if (checkJversion() == 2) {
            $sql = "SELECT a.user_id AS id FROM #__user_usergroup_map a LEFT JOIN #__users u ON u.id = a.user_id WHERE u.id IS NULL";
        } elseif (checkJversion() == 1) {
            $sql = "SELECT a.value AS id, a.id AS aro_id FROM #__core_acl_aro a LEFT JOIN #__users u ON u.id = a.value WHERE a.section_value = 'users' AND u.id IS NULL";
        } else {
            $sql = "SELECT a.value AS id, a.aro_id FROM #__core_acl_aro a LEFT JOIN #__users u ON u.id = a.value WHERE a.section_value = 'users' AND u.id IS NULL";
            // SELECT a.value AS id, a.aro_id FROM jos_core_acl_aro a LEFT JOIN jos_users u ON u.id = a.value WHERE a.section_value = 'users' AND u.id IS NULL
            // DELETE a FROM jos_core_acl_aro AS a LEFT JOIN jos_users AS u ON u.id = a.value WHERE a.section_value = 'users' AND u.id IS NULL
        }
        $_CB_database->setQuery($sql);
        $bad_rows = $_CB_database->loadObjectList();
        if ($_CB_database->getErrorNum()) {
            echo "<p><font color=red>" . sprintf(CBTxt::T('ERROR: sql query: %s : returned error: %s'), htmlspecialchars($sql), stripslashes($_CB_database->getErrorMsg())) . "</font></p>";
        } elseif (count($bad_rows) != 0) {
            echo "<p><font color=red>" . sprintf(CBTxt::T('Warning: %s entries in the core_acl_aro table without corresponding users table rows.'), count($bad_rows)) . "</font></p>";
            $badids = array();
            foreach ($bad_rows as $bad_row) {
                $badids[(int) $bad_row->id] = "user id=" . $bad_row->id . " (aro_id=" . $bad_row->aro_id . ")";
            }
            echo "<p><font color=red>" . CBTxt::P('Following entries of [tablename1] table are missing in [tablename2] table: [badids].', array('[tablename1]' => checkJversion() == 2 ? 'user_usergroup_map' : 'core_acl_aro', '[tablename2]' => 'users', '[badids]' => implode(', ', $badids))) . (isset($badids[0]) ? "<br /> " . CBTxt::T('This core_acl_aro entry with (user) value 0 should be removed, as it\'s not allowed.') : "") . ($bad_row->aro_id == 0 ? " " . CBtxt::T('This core_acl_aro entry with aro_id 0 should be removed, as it\'s not allowed.') : "") . "</font></p>";
            echo '<p><font color=red>' . CBTxt::T('This one can be fixed by <strong>first backing up database</strong>') . ' <a href="' . $_CB_framework->backendUrl("index.php?option=com_comprofiler&task=fixacldb&{$cbSpoofField}={$cbSpoofString}") . '">' . CBTxt::T('then by clicking here') . '</a>.</font></p>';
        } else {
            echo "<p><font color=green>" . CBTxt::P('All [tablename1] table rows have corresponding entries in [tablename2] table.', array('[tablename1]' => checkJversion() == 2 ? 'ACL user_usergroup_map' : 'ACL core_acl_aro', '[tablename2]' => 'users')) . "</font></p>";
        }
        // 12.	check if #__core_acl_groups_aro_map table is in sync with #__core_acl_aro table	A: aro -> groups
        if (checkJversion() <= 1) {
            if (checkJversion() == 1) {
                $sql = "SELECT a.value AS id, a.id AS aro_id FROM #__core_acl_aro a LEFT JOIN #__core_acl_groups_aro_map g ON g.aro_id = a.id WHERE g.aro_id IS NULL";
            } else {
                $sql = "SELECT a.value AS id, a.aro_id FROM #__core_acl_aro a LEFT JOIN #__core_acl_groups_aro_map g ON g.aro_id = a.aro_id WHERE g.aro_id IS NULL";
                // SELECT a.value AS id, a.aro_id FROM jos_core_acl_aro a LEFT JOIN jos_core_acl_groups_aro_map g ON g.aro_id = a.aro_id WHERE g.aro_id IS NULL
                // INSERT INTO jos_core_acl_groups_aro_map (aro_id,section_value,group_id) SELECT a.aro_id, '', 18 AS group_id FROM jos_core_acl_aro a LEFT JOIN jos_core_acl_groups_aro_map g ON g.aro_id = a.aro_id WHERE g.aro_id IS NULL
            }
            $_CB_database->setQuery($sql);
            $bad_rows = $_CB_database->loadObjectList();
            if ($_CB_database->getErrorNum()) {
                echo "<p><font color=red>" . sprintf(CBTxt::T('ERROR: sql query: %s : returned error: %s'), htmlspecialchars($sql), stripslashes($_CB_database->getErrorMsg())) . "</font></p>";
            } elseif (count($bad_rows) != 0) {
                echo "<p><font color=red>" . sprintf(CBTxt::T('Warning: %s entries in the core_acl_aro table without corresponding core_acl_groups_aro_map table rows.'), count($bad_rows)) . "</font></p>";
                $badids = array();
                foreach ($bad_rows as $bad_row) {
                    $badids[(int) $bad_row->id] = "user id=" . $bad_row->id . " (aro_id=" . $bad_row->aro_id . ")";
                }
                echo "<p><font color=red>" . sprintf(CBTxt::T('Following entries of core_acl_aro table are missing in core_acl_groups_aro_map table: %s.'), implode(', ', $badids)) . (isset($badids[0]) ? "<br /> " . CBTxt::T('This core_acl_aro entry with (user) value 0 should be removed, as it\'s not allowed.') : "") . ($bad_row->aro_id == 0 ? " " . CBtxt::T('This core_acl_aro entry with aro_id 0 should be removed, as it\'s not allowed.') : "") . "</font></p>";
                echo '<p><font color=red>' . CBTxt::T('This one can be fixed by <strong>first backing up database</strong>') . ' <a href="' . $_CB_framework->backendUrl("index.php?option=com_comprofiler&task=fixacldb&{$cbSpoofField}={$cbSpoofString}") . '">' . CBTxt::T('then by clicking here') . '</a>.</font></p>';
            } else {
                echo "<p><font color=green>" . CBTxt::T('All core_acl_aro table rows have ACL entries in core_acl_groups_aro_map table.') . "</font></p>";
            }
        }
        // 13.	check if #__core_acl_groups_aro_map table is in sync with #__core_acl_aro table	B: groups -> aro
        if (checkJversion() <= 1) {
            if (checkJversion() == 1) {
                $sql = "SELECT g.aro_id AS id FROM #__core_acl_groups_aro_map g LEFT JOIN #__core_acl_aro a ON a.id = g.aro_id WHERE a.id IS NULL";
            } else {
                $sql = "SELECT g.aro_id AS id FROM #__core_acl_groups_aro_map g LEFT JOIN #__core_acl_aro a ON a.aro_id = g.aro_id WHERE a.aro_id IS NULL";
                // SELECT g.aro_id AS id FROM jos_core_acl_groups_aro_map g LEFT JOIN jos_core_acl_aro a ON a.aro_id = g.aro_id WHERE a.aro_id IS NULL
                // DELETE g FROM jos_core_acl_groups_aro_map g LEFT JOIN jos_core_acl_aro a ON a.aro_id = g.aro_id WHERE a.aro_id IS NULL
            }
            $_CB_database->setQuery($sql);
            $bad_rows = $_CB_database->loadObjectList();
            if ($_CB_database->getErrorNum()) {
                echo "<p><font color=red>" . sprintf(CBTxt::T('ERROR: sql query: %s : returned error: %s'), htmlspecialchars($sql), stripslashes($_CB_database->getErrorMsg())) . "</font></p>";
            } elseif (count($bad_rows) != 0) {
                echo "<p><font color=red>" . sprintf(CBTxt::T('Warning: %s entries in the core_acl_groups_aro_map without corresponding core_acl_aro table table rows.'), count($bad_rows)) . "</font></p>";
                $badids = array();
                foreach ($bad_rows as $bad_row) {
                    $badids[(int) $bad_row->id] = $bad_row->id;
                }
                echo "<p><font color=red>" . sprintf(CBTxt::T('aro_id = %s are missing in core_acl_aro table table.'), implode(', ', $badids)) . (isset($badids[0]) ? " " . CBTxt::T('This entry with aro_id 0 should be removed, as it\'s not allowed.') : "") . "</font></p>";
                echo '<p><font color=red>' . CBTxt::T('This one can be fixed by <strong>first backing up database</strong>') . ' <a href="' . $_CB_framework->backendUrl("index.php?option=com_comprofiler&task=fixacldb&{$cbSpoofField}={$cbSpoofString}") . '">' . CBTxt::T('by clicking here') . '</a>.</font></p>';
            } else {
                echo "<p><font color=green>" . CBTxt::T('All core_acl_aro table rows have ACL entries in core_acl_groups_aro_map table.') . "</font></p>";
            }
        }
        $dbName = CBTxt::T('Users');
        echo '</div>';
    } elseif ($dbId == 3) {
        // adapt published fields to global CB config (regarding name type)
        _cbAdaptNameFieldsPublished($ueConfig);
        // Check fields db:
        cbimport('cb.dbchecker');
        $dbChecker = new CBdbChecker($_CB_database);
        $result = $dbChecker->checkAllCBfieldsDb(false);
        $dbName = CBTxt::T('CB fields data storage');
        $messagesBefore = array();
        $_PLUGINS->loadPluginGroup('user');
        $messagesAfter = $_PLUGINS->trigger('onAfterCheckCbFieldsDb', true);
        HTML_comprofiler::fixcbdbShowResults($dbChecker, false, false, $result, $messagesBefore, $messagesAfter, $dbName, $dbId);
        echo '</div>';
    }
    global $_CB_Backend_Title;
    $_CB_Backend_Title = array(0 => array('cbicon-48-tools', sprintf(CBTxt::T("CB Tools: Check %s database: Results"), $dbName)));
}
	/**
	 * Shows result of database check or fix (with or without dryrun)
	 *
	 * @param  CBdbChecker  $dbChecker
	 * @param  boolean      $upgrade
	 * @param  boolean      $dryRun
	 * @param  boolean      $result
	 * @param  array        $messagesBefore
	 * @param  array        $messagesAfter
	 * @param  string       $dbName
	 * @param  int          $dbId
	 * @param  boolean      $showConclusion
	 */
	static function fixcbdbShowResults( &$dbChecker, $upgrade, $dryRun, $result, $messagesBefore, $messagesAfter, $dbName, $dbId, $showConclusion = true ) {
		global $_CB_framework;

		static $jsId = 0;
		++$jsId;

		$cbSpoofField			=	cbSpoofField();
		$cbSpoofString			=	cbSpoofString( null, 'cbtools' );

		foreach ( $messagesBefore as $msg ) {
			if ( $msg ) {
				echo '<p>' . $msg . '</p>';
			}
		}

		if ( $dbChecker !== null ) {
			if ( $result == true ) {
				echo '<div><font color="green">'
					. htmlspecialchars( $upgrade ? ( $dryRun ? $dbName . ' ' . CBTxt::T('Database adjustments dryrun is successful, see results below') : $dbName . ' ' . CBTxt::T('Database adjustments have been performed successfully.') ) : CBTxt::T('All') . ' ' . $dbName . ' ' . CBTxt::T('Database is up to date.') )
					. '</font></div>';
			} elseif ( is_string( $result ) ) {
				echo '<div><font color="red">' . $result . '</font></div>';
			} else {
				echo '<div style="color:red;">';
				echo '<h3><font color="red">'
					.	htmlspecialchars( $dbName . ' ' . ( $upgrade ? CBTxt::T('Database adjustments errors:') : CBTxt::T('Database structure differences:') ) )
					.	'</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 ( ! $upgrade ) {
					echo '<p><font color="red">'
						. htmlspecialchars( sprintf( CBtxt::T('The %s database structure differences can be fixed (adjusted) by clicking here'), $dbName ) )
						. ': <a href="' . $_CB_framework->backendUrl( "index.php?option=com_comprofiler&task=fixcbdb&dryrun=0&databaseid=$dbId&$cbSpoofField=$cbSpoofString" ) . '">'
						. '<span style="font-size:125%; padding: 4px; border: 1px red solid; background-color: #ffd">'
						. htmlspecialchars( sprintf( CBTxt::T('Click here to Fix (adjust) all %s database differences listed above'), $dbName ) )
						. '</span></a> '
						. str_replace( array( '<a href="#">', '</a>', '<strong>', '</strong>' ),
									   array( '<a href="' . $_CB_framework->backendUrl( "index.php?option=com_comprofiler&task=fixcbdb&dryrun=1&databaseid=$dbId&$cbSpoofField=$cbSpoofString" ) . '"><span style="padding: 4px; border: 1px green solid; background-color: #ffd">',
									   		  '</span></a>', '<strong><u><span style="font-size:125%;color:red;">', '</span></u></strong>' ),
									   CBTxt::T('(you can also <a href="#">Click here to preview fixing (adjusting) queries in a dry-run</a>), but <strong>in all cases you need to backup database first</strong> as this adjustment is changing the database structure to match the needed structure for the installed version.') )
						. '</font></p>';
				}
			}
			$logs			=	$dbChecker->getLogs( false );
			if ( count( $logs ) > 0 ) {
				echo "<div style='margin-bottom:15px;'><a href='#' id='cbdetailsLinkShow_" . $jsId . "'>" . htmlspecialchars( CBTxt::T('Click here to Show details') ) . "</a></div>";
				echo "<div id='cbdetailsdbcheck_" . $jsId . "' style='color:green;margin-bottom:15px;'>";
				foreach ( $logs as $err ) {
					echo '<div style="font-size:100%">' . $err[0];
					if ( $err[1] ) {
						echo '<div style="font-size:90%">' . $err[1] . '</div>';
					}
					echo '</div>';
				}
				echo '</div>';
				$_CB_framework->outputCbJQuery( "$('#cbdetailsdbcheck_" . $jsId . "').hide();      $('#cbdetailsLinkShow_" . $jsId . "').click( function() { $('#cbdetailsdbcheck_" . $jsId . "').toggle('slow'); $('#cbdetailsLinkShow_" . $jsId . "').html( $('#cbdetailsLinkShow_" . $jsId . "').html() == '" . addslashes( CBTxt::T('Click here to Show details') ) . "' ? '" . addslashes( CBTxt::T('Click here to Hide details') ) . "' : '" . addslashes( CBTxt::T('Click here to Show details') ) . "' ); return false; } );");
			}
		}
		if ( $showConclusion ) {
			if ( $upgrade ) {
				if ( $dryRun ) {
					echo "<p>" . htmlspecialchars( sprintf(CBTxt::T('Dry-run of %s database adjustments done. None of the queries listed in details have been performed.') , $dbName) ) . "</p>";
					echo '<p>' . htmlspecialchars( CBTxt::T('The database adjustments listed above can be applied by clicking here') )
						. ': <a href="' . $_CB_framework->backendUrl( "index.php?option=com_comprofiler&task=fixcbdb&dryrun=0&databaseid=$dbId&$cbSpoofField=$cbSpoofString" ) . '">'
						. '<span style="font-size:125%; padding: 4px; border: 1px red solid; background-color: #ffd">'
						. htmlspecialchars( CBTxt::T('Click here to Fix (adjust) all database differences listed above.') )
						. '</span></a> '
						. str_replace( array( '<strong>', '</strong>' ),
									   array( '<strong><u><span style="font-size:125%;color:red;">', '</span></u></strong>' ),
										CBTxt::T('<strong>You need to backup database first</strong> as this fixing/adjusting is changing the database structure to match the needed structure for the installed version.') )
						. '</p>';
				} else {
					echo '<p>' . htmlspecialchars( sprintf( CBTxt::T('The %s database adjustments have been done. If all lines above are in green, database adjustments completed successfully. Otherwise, if some lines are red, please report exact errors and queries to authors forum, and try checking database again.'), $dbName ) ) . '</p>';
					echo '<p>' . htmlspecialchars( CBTxt::T('The database structure can be checked again by clicking here') )
						. ': <a href="' . $_CB_framework->backendUrl( "index.php?option=com_comprofiler&task=checkcbdb&databaseid=$dbId&$cbSpoofField=$cbSpoofString" ) . '">'
						. '<span style="font-size:125%; padding: 4px; border: 1px orange solid; background-color: #ffd">' . htmlspecialchars( sprintf( CBTxt::T('Click here to Check %s database'), $dbName ) ) . '</span></a>'
						. '</p>';
				}
			} else {
				echo '<p>' . $dbName . ' ' . htmlspecialchars( CBTxt::T('database checks done. If all lines above are in green, test completed successfully. Otherwise, please take corrective measures proposed in red.') ) . '</p>';
			}
		}
		foreach ( $messagesAfter as $msg ) {
			if ( $msg ) {
				echo '<p>' . $msg . '</p>';
			}
		}
	}
 function editTab($tid = '0', $option = 'com_comprofiler', $task = 'editTab')
 {
     global $_CB_database, $_CB_framework, $_PLUGINS;
     $this->_importNeeded();
     $canEditState = CBuser::getMyInstance()->authoriseAction('core.edit.state');
     $row = new moscomprofilerTabs($_CB_database);
     if ($tid) {
         // load the row from the db table
         $row->load((int) $tid);
         // Check if user is a super user:
         if (!$_CB_framework->acl->amIaSuperAdmin()) {
             // Check if user belongs to useraccessgroupid:
             if (!in_array($row->useraccessgroupid, $_CB_framework->acl->get_groups_below_me(null, true))) {
                 echo "<script type=\"text/javascript\"> alert('" . addslashes(CBTxt::T('Unauthorized Access')) . "'); window.history.go(-1);</script>\n";
                 exit;
             }
             // Check if user belongs to viewaccesslevel:
             if (!in_array($row->viewaccesslevel, CBuser::getMyInstance()->getAuthorisedViewLevelsIds(false))) {
                 echo "<script type=\"text/javascript\"> alert('" . addslashes(CBTxt::T('Unauthorized Access')) . "'); window.history.go(-1);</script>\n";
                 exit;
             }
         }
     }
     $lists = array();
     if ($row->sys == '2') {
         $lists['enabled'] = "Yes";
     } else {
         $lists['enabled'] = moscomprofilerHTML::yesnoSelectList('enabled', 'class="inputbox" size="1"' . ($canEditState ? '' : ' disabled="disabled"'), $row->enabled !== null ? $row->enabled : 1);
     }
     /*
     -------------------------
     !          head         !
     !-----------------------!
     !      !        !       !
     ! left ! middle ! right !
     !      !        !       !
     !-----------------------!
     !                       !
     !        tabmain        !
     !                       !
     !-----------------------!
     !        underall       !
     -------------------------
     !      !        !       !
     ! L1C1 ! L1C2   ! L1C3  !   L1C1...C9
     !      !        !       !
     !-----------------------!
     !      !        !       !
     ! L2C1 ! L2C4   ! L2C8  !   ...
     !      !        !       !
     !-----------------------!
     !                       !
     !        L4C7           !
     !                       !
     !-----------------------!
     !          !            !
     !   L8C3   !    L8C4    !   ...L9C9
     !          !            !
     !-----------------------!
     	    ! + not_on_profile_1..9
     */
     $position = array();
     $position[] = moscomprofilerHTML::makeOption('cb_head', _UE_POS_CB_HEAD);
     $position[] = moscomprofilerHTML::makeOption('cb_left', _UE_POS_CB_LEFT);
     $position[] = moscomprofilerHTML::makeOption('cb_middle', _UE_POS_CB_MIDDLE);
     $position[] = moscomprofilerHTML::makeOption('cb_right', _UE_POS_CB_RIGHT);
     $position[] = moscomprofilerHTML::makeOption('cb_tabmain', _UE_POS_CB_MAIN);
     $position[] = moscomprofilerHTML::makeOption('cb_underall', _UE_POS_CB_BOTTOM);
     for ($i = 1; $i <= 9; $i++) {
         for ($j = 1; $j <= 9; $j++) {
             $position[] = moscomprofilerHTML::makeOption('L' . $i . 'C' . $j, CBTxt::T('Line') . ' ' . $i . ' ' . CBTxt::T('Column') . ' ' . $j);
         }
     }
     for ($i = 1; $i <= 9; $i++) {
         $position[] = moscomprofilerHTML::makeOption('not_on_profile_' . $i, CBTxt::T('Not displayed on profile') . ' ' . $i);
     }
     if (!$row->position) {
         $row->position = 'cb_tabmain';
     }
     $lists['position'] = moscomprofilerHTML::selectList($position, 'position', 'class="inputbox" size="1"', 'value', 'text', $row->position, 2);
     $displaytype = array();
     $displaytype[] = moscomprofilerHTML::makeOption('tab', _UE_DISPLAY_TAB);
     $displaytype[] = moscomprofilerHTML::makeOption('div', _UE_DISPLAY_DIV);
     $displaytype[] = moscomprofilerHTML::makeOption('rounddiv', _UE_DISPLAY_ROUNDED_DIV);
     $displaytype[] = moscomprofilerHTML::makeOption('html', _UE_DISPLAY_HTML);
     $displaytype[] = moscomprofilerHTML::makeOption('overlib', _UE_DISPLAY_OVERLIB);
     $displaytype[] = moscomprofilerHTML::makeOption('overlibfix', _UE_DISPLAY_OVERLIBFIX);
     $displaytype[] = moscomprofilerHTML::makeOption('overlibsticky', _UE_DISPLAY_OVERLIBSTICKY);
     if (!$row->displaytype) {
         $row->displaytype = 'tab';
     }
     $lists['displaytype'] = moscomprofilerHTML::selectList($displaytype, 'displaytype', 'class="inputbox" size="1"', 'value', 'text', $row->displaytype, 2);
     if ($tid) {
         if ($row->ordering > -10000 && $row->ordering < 10000) {
             // build the html select list for ordering
             $query = "SELECT ordering AS value, title AS text" . "\n FROM #__comprofiler_tabs" . "\n WHERE position='" . $_CB_database->getEscaped($row->position) . "'" . "\n AND enabled > 0" . "\n AND ordering > -10000" . "\n AND ordering < 10000" . "\n ORDER BY ordering";
             $order = $this->_cbGetOrderingList($query);
             $lists['ordering'] = moscomprofilerHTML::selectList($order, 'ordering', 'class="inputbox" size="1"' . ($canEditState ? '' : ' disabled="disabled"'), 'value', 'text', intval($row->ordering), 2);
         } else {
             $lists['ordering'] = '<input type="hidden" name="ordering" value="' . $row->ordering . '" />' . CBTxt::T('This plugin cannot be reordered');
         }
     } else {
         $row->ordering = 999;
         $row->ordering_register = 10;
         $row->published = 1;
         $row->description = '';
         $row->useraccessgroupid = -2;
         $row->viewaccesslevel = 1;
         $lists['ordering'] = '<input type="hidden" name="ordering" value="' . $row->ordering . '" />' . CBTxt::T('New items default to the last place. Ordering can be changed after this item is saved.');
     }
     $lists['ordering_register'] = '<input type="text" name="ordering_register" class="inputbox"' . ($canEditState ? '' : ' disabled="disabled"') . ' size="40" value="' . $row->ordering_register . '" />';
     // build the html select list for the view level access (filtered by View Access Levels visible by the admin if not super user:
     $accessTree = $_CB_framework->acl->get_access_children_tree(true, false, !$_CB_framework->acl->amIaSuperAdmin());
     $lists['viewaccesslevel'] = moscomprofilerHTML::selectList($accessTree, 'viewaccesslevel', 'class="inputbox"' . ($canEditState ? '' : ' disabled="disabled"'), 'value', 'text', intval($row->viewaccesslevel), 2);
     // We want to use View Access Levels in Joomla 1.6, and hide old method if unused:
     if (isStillUsingGroupsForViewAccess($row->_tbl)) {
         $gtree3 = array();
         $gtree3[] = moscomprofilerHTML::makeOption(-2, '- ' . CBtxt::T('Everybody') . ' -');
         $gtree3[] = moscomprofilerHTML::makeOption(-1, '- ' . CBtxt::T('All Registered Users') . ' -');
         if (!$_CB_framework->acl->amIaSuperAdmin() && in_array((int) $row->useraccessgroupid, $_CB_framework->acl->get_groups_below_me(null, true))) {
             // This should always be the case:
             // ensure user can't add group higher than themselves:
             $gtree3 = array_merge($gtree3, $_CB_framework->acl->get_groups_below_me());
             // vs $_CB_framework->acl->get_groups_below_me( null, true )  in tab lists
         } else {
             // Just in case we missed one, and as super-admin we should see everything:
             $gtree3 = array_merge($gtree3, $_CB_framework->acl->get_group_children_tree(null, 'USERS', false));
         }
         $lists['useraccessgroup'] = moscomprofilerHTML::selectList($gtree3, 'useraccessgroupid', 'size="4"' . ($canEditState ? '' : ' disabled="disabled"'), 'value', 'text', $row->useraccessgroupid, 2, false);
     } else {
         $lists['useraccessgroup'] = null;
     }
     // params:
     $paramsEditorHtml = array();
     $options = array('option' => $option, 'task' => $task, 'cid' => $row->tabid);
     // additional non-specific other parameters:
     $_PLUGINS->loadPluginGroup('user');
     $fieldsParamsPlugins = $_PLUGINS->getUserTabParamsPluginIds();
     foreach ($fieldsParamsPlugins as $pluginId => $fieldParamHandlerClassName) {
         $fieldParamHandler = new $fieldParamHandlerClassName($pluginId, $row);
         // cbFieldParamsHandler();
         $addParamsHtml = $fieldParamHandler->drawParamsEditor($options);
         if ($addParamsHtml) {
             $addParamsTitle = $fieldParamHandler->getFieldsParamsLabel();
             $paramsEditorHtml[] = array('title' => $addParamsTitle, 'content' => $addParamsHtml);
         }
     }
     $pluginView = _CBloadView('tab');
     $pluginView->edittab($row, $option, $lists, $tid, $paramsEditorHtml);
 }