/**
     * Internal utility function to output JS for the Ajax content for function currencyconvertercheck() to update currencies
     *
     * @param  string  $ajaxUrl
     * @param  string  $cssSelectorReply
     * @return void
     */
    protected function _ajaxContent($ajaxUrl, $cssSelectorReply)
    {
        global $_CB_framework;
        $cbSpoofField = cbSpoofField();
        $cbSpoofString = cbSpoofString(null, 'guiajax');
        $regAntiSpamFieldName = cbGetRegAntiSpamFieldName();
        $regAntiSpamValues = cbGetRegAntiSpams();
        cbGetRegAntiSpamInputTag($regAntiSpamValues);
        // sets the cookie
        $regAntiSpZ = $regAntiSpamValues[0];
        //$errorText				=	addslashes( $errorText );
        $_CB_framework->outputCbJQuery(<<<EOT
\t\$.ajax( {\ttype: 'POST',
\t\t\t\turl:  '{$ajaxUrl}',
\t\t\t\tdata: '{$cbSpoofField}=' + encodeURIComponent('{$cbSpoofString}') + '&{$regAntiSpamFieldName}=' + encodeURIComponent('{$regAntiSpZ}'),
\t\t\t\tsuccess: function(response) {
\t\t\t\t\t\$('{$cssSelectorReply}').hide().html(response).fadeIn('fast');
\t\t\t\t},
\t\t\t\terror: function (XMLHttpRequest, textStatus, errorThrown) {
\t\t\t\t\t\$('{$cssSelectorReply}').hide().html(errorThrown ? errorThrown.message : textStatus).fadeIn('fast');
\t\t\t\t},
\t\t\t\tdataType: 'html'
\t});
EOT
);
    }
    function _cbadmin_ajaxBatch($ajaxUrl, $cssSelectorReply, $formSelector, $postArray, $delay, $limitstart = 0, $limit = 30, $textDuringExecution = null, $textWhenDone = null, $cssSelectorTitle, $titleTextWhenDone)
    {
        global $_CB_framework;
        $ajaxUrl = addslashes($ajaxUrl);
        $cbSpoofField = cbSpoofField();
        $cbSpoofString = cbSpoofString(null, 'cbadmingui');
        $regAntiSpamFieldName = cbGetRegAntiSpamFieldName();
        $regAntiSpamValues = cbGetRegAntiSpams();
        cbGetRegAntiSpamInputTag($regAntiSpamValues);
        // sets the cookie
        $regAntiSpZ = $regAntiSpamValues[0];
        $postString = '';
        foreach ($postArray as $k => $v) {
            if (is_array($v)) {
                foreach ($v as $vv) {
                    $postString .= '&' . urlencode($k) . '[]=' . urlencode($vv);
                }
            } else {
                $postString .= '&' . urlencode($k) . '=' . urlencode($v);
            }
        }
        $postString = addslashes($postString);
        //$errorText				=	addslashes( $errorText );
        $textWaiting = addslashes(CBTxt::T('Waiting delay for next batch...'));
        $textExecuting = addslashes($textDuringExecution ? $textDuringExecution : CBTxt::T('Executing'));
        $textFinished = addslashes($textWhenDone ? $textWhenDone : CBTxt::T('Done'));
        $textError = addslashes(CBTxt::T('ERROR!'));
        $titleTextWhenDone = addslashes($titleTextWhenDone);
        $_CB_framework->outputCbJQuery(<<<EOT
\t{
\t\tvar cbanimate = function() {
\t\t\t\$(this).animate({width:'100%'},20000,function(){
\t\t\t\t\$(this).animate({width:'0%'},1000,cbanimate);
\t\t\t});
\t\t};
\t\tvar cbajaxjsonbatch = function(limitstart,limit,successFnct){
\t\t\t\$.ajax( {\ttype: 'POST',
\t\t\t\t\t\turl:  '{$ajaxUrl}',
\t\t\t\t\t\tdata: \$('{$formSelector}').serialize() + '&{$cbSpoofField}=' + encodeURIComponent('{$cbSpoofString}') + '&{$regAntiSpamFieldName}=' + encodeURIComponent('{$regAntiSpZ}') + '{$postString}' + '&limitstart=' + limitstart,
\t\t\t\t\t\tsuccess: function(response) {
\t\t\t\t\t\t\t\$('{$cssSelectorReply}'+'Bar div').stop().animate( {width:'100%'},500).animate( {width:'0%'},200, function() { \$(this).css({"background-color":"#8f8"}) });
\t\t\t\t\t\t\t\$('{$cssSelectorReply}').fadeOut(400, function() {
\t\t\t\t\t\t\t\t\$(this).html(response.htmlcontent).fadeIn(400, function() {
\t\t\t\t\t\t\t\t\tif ( response.result == 1 ) {
\t\t\t\t\t\t\t\t\t\$(this).each( function() {
\t\t\t\t\t\t\t\t\t\t\$('{$cssSelectorReply}'+'Bar span').html('{$textWaiting}')
\t\t\t\t\t\t\t\t\t\t.siblings('div').animate( {width:'100%'},{$delay}*1000,'linear', function() {
\t\t\t\t\t\t\t\t\t\t\t\$(this).animate( {width:'0%'},200, function() {
\t\t\t\t\t\t\t\t\t\t\t\tcbajaxjsonbatch(limitstart+limit,limit,successFnct);
\t\t\t\t\t\t\t\t\t\t\t});
\t\t\t\t\t\t\t\t\t\t});
\t\t\t\t\t\t\t\t\t});
\t\t\t\t\t\t\t\t\t} else if ( response.result == 2 ) {
\t\t\t\t\t\t\t\t\t\t\$('{$cssSelectorReply}'+'Bar span').html('{$textFinished}');
\t\t\t\t\t\t\t\t\t\tif (successFnct) {
\t\t\t\t\t\t\t\t\t\t\tsuccessFnct.call(response);
\t\t\t\t\t\t\t\t\t\t}
\t\t\t\t\t\t\t\t\t} else {
\t\t\t\t\t\t\t\t\t\t\$('{$cssSelectorReply}'+'Bar span').html('{$textError}')
\t\t\t\t\t\t\t\t\t\t.siblings('div').css({"background-color":"#fcc"});
\t\t\t\t\t\t\t\t\t}
\t\t\t\t\t\t\t\t});
\t\t\t\t\t\t\t})
\t\t\t\t\t\t},
\t\t\t\t\t\terror: function (XMLHttpRequest, textStatus, errorThrown) {
\t\t\t\t\t\t\t\$('{$cssSelectorReply}'+'Bar div').stop().animate( {width:'100%'},500).css({"background-color":"#f87"});
\t\t\t\t\t\t\t\$('{$cssSelectorReply}'+'Bar span').html('{$textError}');
\t\t\t\t\t\t\t\$('{$cssSelectorReply}').hide().html( ( errorThrown ? errorThrown : textStatus ? textStatus : 'No additional message' ).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;") ).fadeIn('fast');
\t\t\t\t\t\t},
\t\t\t\t\t\tdataType: 'json'
\t\t\t});
\t\t\t\$('{$cssSelectorReply}'+'Bar span').html('{$textExecuting}')
\t\t\t.siblings('div').css({"background-color":"#ee8"}).each(cbanimate);
\t\t};
\t\t
\t\tvar cbTitleSetDone = function() {
\t\t\t\$('{$cssSelectorTitle}').html('{$titleTextWhenDone}');
\t\t};
\t\t\tcbajaxjsonbatch({$limitstart},{$limit},cbTitleSetDone);
\t}
EOT
);
    }
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)));
}
Beispiel #4
0
	/**
	 * Loads the CB jQuery Validation into the header
	 *
	 * @param  string  $selector  The jQuery selector to bind validation to
	 * @return void
	 */
	static function loadValidation( $selector = '.cbValidation' )
	{
		global $_CB_framework;

		static $options				=	null;

		if ( ! $options ) {
			$liveSite				=	$_CB_framework->getCfg( 'live_site' ) . ( $_CB_framework->getUi() == 2 ? '/administrator' : null );
			$cbSpoofField			=	cbSpoofField();
			$cbSpoofString			=	cbSpoofString( null, 'fieldclass' );
			$regAntiSpamFieldName	=	cbGetRegAntiSpamFieldName();
			$regAntiSpamValues		=	cbGetRegAntiSpams();

			$messages				=	array(	'required' => addslashes( CBTxt::T( 'VALIDATION_ERROR_FIELD_REQUIRED', 'This field is required.' ) ),
													'remote' => addslashes( CBTxt::T( 'VALIDATION_ERROR_FIELD_NEEDS_FIX', 'Please fix this field.' ) ),
													'email' => addslashes( CBTxt::T( 'VALIDATION_ERROR_FIELD_EMAIL', 'Please enter a valid email address.' ) ),
													'url' => addslashes( CBTxt::T( 'VALIDATION_ERROR_FIELD_URL', 'Please enter a valid URL.' ) ),
													'date' => addslashes( CBTxt::T( 'VALIDATION_ERROR_FIELD_DATE', 'Please enter a valid date.' ) ),
													'dateISO' => addslashes( CBTxt::T( 'VALIDATION_ERROR_FIELD_DATE_ISO', 'Please enter a valid date (ISO).' ) ),
													'number' => addslashes( CBTxt::T( 'VALIDATION_ERROR_FIELD_NUMBER', 'Please enter a valid number.' ) ),
													'digits' => addslashes( CBTxt::T( 'VALIDATION_ERROR_FIELD_DIGITS_ONLY', 'Please enter only digits.' ) ),
													'creditcard' => addslashes( CBTxt::T( 'VALIDATION_ERROR_FIELD_CREDIT_CARD_NUMBER', 'Please enter a valid credit card number.' ) ),
													'equalTo' => addslashes( CBTxt::T( 'VALIDATION_ERROR_FIELD_SAME_VALUE_AGAIN', 'Please enter the same value again.' ) ),
													'notEqualTo' => addslashes( CBTxt::T( 'VALIDATION_ERROR_FIELD_DIFFERENT_VALUE', 'Please enter a different value, values must not be the same.' ) ),
													'accept' => addslashes( CBTxt::T( 'VALIDATION_ERROR_FIELD_EXTENSION', 'Please enter a value with a valid extension.' ) ),
													'maxlength' => addslashes( CBTxt::T( 'VALIDATION_ERROR_FIELD_MORE_THAN_CHARS', 'Please enter no more than {0} characters.' ) ),
													'minlength' => addslashes( CBTxt::T( 'VALIDATION_ERROR_FIELD_LEAST_CHARS', 'Please enter at least {0} characters.' ) ),
													'rangelength' => addslashes( CBTxt::T( 'VALIDATION_ERROR_FIELD_BETWEEN_AND_CHARS', 'Please enter a value between {0} and {1} characters long.' ) ),
													'range' => addslashes( CBTxt::T( 'VALIDATION_ERROR_FIELD_BETWEEN_AND_NUMBER', 'Please enter a value between {0} and {1}.' ) ),
													'max' => addslashes( CBTxt::T( 'VALIDATION_ERROR_FIELD_LESS_OR_EQUAL_TO', 'Please enter a value less than or equal to {0}.' ) ),
													'min' => addslashes( CBTxt::T( 'VALIDATION_ERROR_FIELD_GREATER_OR_EQUAL_TO', 'Please enter a value greater than or equal to {0}.' ) ),
													'maxWords' => addslashes( CBTxt::T( 'VALIDATION_ERROR_FIELD_MORE_THAN_WORDS', 'Please enter {0} words or less.' ) ),
													'minWords' => addslashes( CBTxt::T( 'VALIDATION_ERROR_FIELD_LEAST_WORDS', 'Please enter at least {0} words.' ) ),
													'rangeWords' => addslashes( CBTxt::T( 'VALIDATION_ERROR_FIELD_BETWEEN_AND_WORDS', 'Please enter between {0} and {1} words.' ) ),
													'extension' => addslashes( CBTxt::T( 'VALIDATION_ERROR_FIELD_EXTENSION', 'Please enter a value with a valid extension.' ) ),
													'pattern' => addslashes( CBTxt::T( 'VALIDATION_ERROR_FIELD_PATTERN', 'Invalid format.' ) ),
													'cbfield' => addslashes( CBTxt::T( 'VALIDATION_ERROR_FIELD_NEEDS_FIX', 'Please fix this field.' ) ),
													'cbremote' => addslashes( CBTxt::T( 'VALIDATION_ERROR_FIELD_NEEDS_FIX', 'Please fix this field.' ) ),
													'cbusername' => addslashes( CBTxt::T( 'VALIDATION_ERROR_FIELD_USERNAME', 'Please enter a valid username with no space at beginning or end and must not contain the following characters: < > \ " \' % ; ( ) &' ) ),
													'cburl' => addslashes( CBTxt::T( 'VALIDATION_ERROR_FIELD_URL', 'Please enter a valid URL.' ) ),
													'filesize' => addslashes( CBTxt::T( 'VALIDATION_ERROR_FILZSIZE', 'File size must exceed the minimum of {0} {2}s, but not the maximum of {1} {2}s.' ) ),
													'filesizemin' => addslashes( CBTxt::T( 'VALIDATION_ERROR_FILZSIZE_MIN', 'File size exceeds the minimum of {0} {2}s.' ) ),
													'filesizemax' => addslashes( CBTxt::T( 'VALIDATION_ERROR_FILZSIZE_MAX', 'File size exceeds the maximum of {1} {2}s.' ) )
			);

			$settings				=	array();

			$settings['cbfield']	=	array(	'url' => addslashes( $liveSite . '/index.php?option=com_comprofiler&view=fieldclass&function=[function]&user=[user]&field=[field]&reason=[reason]&format=raw' ),
												   'spooffield' => addslashes( $cbSpoofField ),
												   'spoofstring' => addslashes( $cbSpoofString ),
												   'spamfield' => addslashes( $regAntiSpamFieldName ),
												   'spamstring' => addslashes( $regAntiSpamValues[0] )
			);

			$options				=	array( 'messages' => $messages, 'settings' => $settings );
		}

		$js							=	null;

		static $selectors			=	array();

		if ( ! isset( $selectors[$selector] ) ) {
			$selectors[$selector]	=	true;

			$js						.=	"$( '" . addslashes( $selector ) . "' ).cbvalidate(" . json_encode( $options ) . ");";
		}

		static $rules				=	array();

		foreach ( self::$rules as $method => $rule ) {
			if ( ! isset( $rules[$method] ) ) {
				$rules[$method]		=	true;

				$js					.=	"$.validator.addMethod( '" . addslashes( $method ) . "', function( value, element, params ) {"
									.		$rule[0]
									.	"}, $.validator.format( '" . addslashes( $rule[1] ) . "' ) );";
			}
		}

		static $classRules			=	array();

		foreach ( self::$classRules as $class => $rules ) {
			if ( ! isset( $classRules[$class] ) ) {
				$classRules[$class]	=	true;

				$js					.=	"$.validator.addClassRules( '" . addslashes( $class ) . "', JSON.parse( '" . addcslashes( json_encode( $rules ), "'" ) . "' ) );";
			}
		}

		if ( $js ) {
			$_CB_framework->outputCbJQuery( $js, 'cbvalidate' );
		}
	}
    function ajaxCheckField(&$field, &$user, $reason, $validateParams = null)
    {
        global $_CB_framework;
        static $_CB_fieldajax_outputed = false;
        static $_CB_fieldajax_validator_outputed = false;
        $cbSpoofField = cbSpoofField();
        $cbSpoofString = cbSpoofString(null, 'fieldclass');
        $regAntiSpamFieldName = cbGetRegAntiSpamFieldName();
        $regAntiSpamValues = cbGetRegAntiSpams();
        $userid = (int) $user->id;
        $checking = _UE_CHECKING;
        // . '&start_debug=1',
        $live_site = $_CB_framework->getCfg('live_site');
        $regAntiSpZ = $regAntiSpamValues[0];
        $url = "index.php?option=com_comprofiler&task=fieldclass&function=checkvalue&user={$userid}&reason={$reason}";
        if ($_CB_framework->getUi() == 2) {
            $ajaxUrl = $live_site . '/administrator/' . $_CB_framework->backendUrl($url, false, 'raw');
        } else {
            $ajaxUrl = cbSef($url, false, 'raw');
        }
        if ($validateParams !== null && defined('_CB_VALIDATE_NEW')) {
            if ($_CB_fieldajax_validator_outputed !== true) {
                cbimport('cb.validator');
                cbValidator::addMethod('remotejhtml', <<<EOT
jQuery.validator.addMethod("remotejhtml", function(value, element, param) {
\t\t\tif ( this.optional(element) )
\t\t\t\treturn "dependency-mismatch";

\t\t\tvar previous = this.previousValue(element);

\t\t\tif (!this.settings.messages[element.name] )
\t\t\t\tthis.settings.messages[element.name] = {};
\t\t\tthis.settings.messages[element.name].remote = typeof previous.message == "function" ? previous.message(value) : previous.message;

\t\t\tparam = typeof param == "string" && {url:param} || param;

\t\t\tvar respField = \$('#'+\$(element).attr('id')+'__Response');
\t\t\tif ( respField.html() != '&nbsp;' ) {
\t\t\t\tif ( previous.old !== value ) {
\t\t\t\t\trespField.fadeOut('medium' );
\t\t\t\t} else {
\t\t\t\t\trespField.fadeIn('medium' );
\t\t\t\t}
\t\t\t}

\t\t\tif ( previous.old !== value && ! this.cbIsOnKeyUp && ! this.cbIsFormSubmitting ) {

\t\t\t\tvar inputid = \$(element).attr('id');
\t\t\t\tif ( ! \$('#'+inputid+'__Response').size() ) {
\t\t\t\t\tvar respField = '<div class=\\"cb_result_container\\"><div id=\\"' + inputid + '__Response\\">&nbsp;</div></div>';
\t\t\t\t\t\$(element).parent().each( function() {
\t\t\t\t\t\tif (this.tagName.toLowerCase() == 'td') {
\t\t\t\t\t\t\t\$(this).append(respField);
\t\t\t\t\t\t} else {
\t\t\t\t\t\t\t\$(this).after(respField);
\t\t\t\t\t\t}
\t\t\t\t\t\t\$(inputid+'__Response').hide();
\t\t\t\t\t} );
\t\t\t\t}

\t\t\t\tprevious.old = value;
\t\t\t\tvar validator = this;
\t\t\t\t// this.startRequest(element);
\t\t\t\tvar data = {};
\t\t\t\tdata[element.name] = value;
\t\t\t\t\$.ajax(\$.extend(true, {
\t\t\t\t\ttype: 'POST',
\t\t\t\t\turl:  '{$ajaxUrl}&field='+encodeURIComponent(inputid),
\t\t\t\t\tmode: "abort",
\t\t\t\t\tport: "validate" + element.name,
\t\t\t\t\tdataType: "html",\t/* """json", */
\t\t\t\t\tdata: 'value=' + encodeURIComponent(value) + '&{$cbSpoofField}=' + encodeURIComponent('{$cbSpoofString}') + '&{$regAntiSpamFieldName}=' + encodeURIComponent('{$regAntiSpZ}'),
\t\t\t\t\t/* data: data, */
\t\t\t\t\tsuccess: function(response) {
\t\t\t\t\t\t/* never errors on that one: */
\t\t\t\t\t\tvar submitted = validator.formSubmitted;
\t\t\t\t\t\tvalidator.prepareElement(element);
\t\t\t\t\t\tvalidator.formSubmitted = submitted;
\t\t\t\t\t\tvalidator.successList.push(element);
\t\t\t\t\t\tvalidator.showErrors();

\t\t\t\t\t\tprevious.valid = response;
\t\t\t\t\t\t// validator.stopRequest(element, response);

\t\t\t\t\t\tvar respField = \$('#'+\$(element).attr('id')+'__Response');
\t\t\t\t\t\trespField.fadeOut('fast', function() {
\t\t\t\t\t\t\trespField.html(response).fadeIn('fast');
\t\t\t\t\t\t} );
\t\t\t\t\t},
\t\t\t\t\terror: function(jqXHR, textStatus) {
\t\t\t\t\t\t// validator.stopRequest(element, textStatus);
\t\t\t\t\t\tvar respField = \$('#'+\$(element).attr('id')+'__Response');
\t\t\t\t\t\trespField.fadeOut('fast', function() {
\t\t\t\t\t\t\trespField.html(textStatus).fadeIn('fast');
\t\t\t\t\t\t} );
\t\t\t\t\t}
\t\t\t\t}, param));
\t\t\t\t\$('#'+inputid+'__Response').html('<img alt=\\"\\" src=\\"{$live_site}/components/com_comprofiler/images/wait.gif\\" /> {$checking}').fadeIn('fast');
\t\t\t\treturn true;\t\t// "pending";
\t\t\t} else if( this.pending[element.name] ) {
\t\t\t\treturn "pending";
\t\t\t}
\t\t\treturn true; // previous.valid;
}, 'Ajax Reply Error');
EOT
);
                /*
                jQuery.validator.addMethod("remotejhtml", function(value, element, param) {
                			if ( this.optional(element) )
                				return "dependency-mismatch";
                
                			var previous = this.previousValue(element);
                
                			if (!this.settings.messages[element.name] )
                				this.settings.messages[element.name] = {};
                			this.settings.messages[element.name].remote = typeof previous.message == "function" ? previous.message(value) : previous.message;
                
                			param = typeof param == "string" && {url:param} || param;
                
                			if ( previous.old !== value && ! this.cbIsOnKeyUp ) {
                				previous.old = value;
                				var validator = this;
                				this.startRequest(element);
                				var data = {};
                				data[element.name] = value;
                				$.ajax($.extend(true, {
                					type: 'POST',
                					url:  '$ajaxUrl&field='+encodeURIComponent(element.id),
                					mode: "abort",
                					port: "validate" + element.name,
                					dataType: "html",
                					data: 'value=' + encodeURIComponent(value) + '&$cbSpoofField=' + encodeURIComponent('$cbSpoofString') + '&$regAntiSpamFieldName=' + encodeURIComponent('$regAntiSpZ'),
                					success: function(response) {
                						if ( response == '' ) {
                							var submitted = validator.formSubmitted;
                							validator.prepareElement(element);
                							validator.formSubmitted = submitted;
                							validator.successList.push(element);
                							validator.showErrors();
                						} else {
                							var errors = {};
                							errors[element.name] =  response || validator.defaultMessage( element, "remote" );
                							validator.showErrors(errors);
                						}
                						previous.valid = response;
                						validator.stopRequest(element, response);
                					}
                				}, param));
                				return "pending";
                			} else if( this.pending[element.name] ) {
                				return "pending";
                			}
                			return previous.valid;
                }, 'Ajax Reply Error');
                */
                $_CB_fieldajax_validator_outputed = true;
            }
        } else {
            if ($_CB_fieldajax_outputed !== true) {
                $_CB_framework->outputCbJQuery(<<<EOT
\$.fn.cb_field_ajaxCheck = function() {
\tif ( ( \$(this).val() != '' ) && ( \$(this).val() != \$(this).data('cblastvalsent') ) ) {
\t\tvar inputid = \$(this).attr('id');
\t\tif ( ! \$('#'+inputid+'__Response').size() ) {
\t\t\tvar respField = '<div class=\\"cb_result_container\\"><div id=\\"' + inputid + '__Response\\">&nbsp;</div></div>';
\t\t\t\$(this).parent().each( function() {
\t\t\t\tif (this.tagName.toLowerCase() == 'td') {
\t\t\t\t\t\$(this).append(respField);
\t\t\t\t} else {
\t\t\t\t\t\$(this).after(respField);
\t\t\t\t}
\t\t\t\t\$(inputid+'__Response').hide();
\t\t\t} );
\t\t}
\t\tif (  \$('#'+inputid+'__Response').length > 0 ) {
\t\t\t\$('#'+inputid+'__Response').html('<img alt=\\"\\" src=\\"{$live_site}/components/com_comprofiler/images/wait.gif\\" /> {$checking}').fadeIn('fast');
\t\t\tvar cbInputField = this;
\t\t\tvar lastVal = \$(this).val();
\t\t\t\$(this).data('cblastvalsent', lastVal );
\t\t\t\$.ajax( {\ttype: 'POST',
\t\t\t\t\t\turl:  '{$ajaxUrl}&field='+encodeURIComponent(inputid),
\t\t\t\t\t\tdata: 'value=' + encodeURIComponent( lastVal ) + '&{$cbSpoofField}=' + encodeURIComponent('{$cbSpoofString}') + '&{$regAntiSpamFieldName}=' + encodeURIComponent('{$regAntiSpZ}'),
\t\t\t\t\t\tsuccess: function(response) {
\t\t\t\t\t\t\tvar respField = \$('#'+\$(cbInputField).attr('id')+'__Response');
\t\t\t\t\t\t\trespField.fadeOut('fast', function() {
\t\t\t\t\t\t\t\trespField.html(response).fadeIn('fast');
\t\t\t\t\t\t\t} );
\t\t\t\t\t\t\t\$(cbInputField).data( 'cblastvalchecked', lastVal );
\t\t\t\t\t\t},
\t\t\t\t\t\tdataType: 'html'
\t\t\t});
\t\t}
\t}
};
\$.fn.cb_field_ajaxClear = function() {
\tvar respField = \$('#'+\$(this).attr('id')+'__Response');
\tif ( respField.html() != '&nbsp;' ) {
\t\tif ( \$(this).val() != \$(this).data( 'cblastvalchecked' ) ) {
\t\t\trespField.fadeOut('medium' );
\t\t} else {
\t\t\trespField.fadeIn('medium' );
\t\t}
\t}
};
EOT
);
                $_CB_fieldajax_outputed = true;
            }
        }
        if ($validateParams !== null && defined('_CB_VALIDATE_NEW')) {
            $validateParams[] = 'remotejhtml:true';
            return $this->getMetaClass($field, $validateParams);
        } else {
            $_CB_framework->outputCbJQuery("\$('#" . $field->name . "').data( 'cblastvalsent', \$('#" . $field->name . "').val() ).blur( \$.fn.cb_field_ajaxCheck ).keyup( \$.fn.cb_field_ajaxClear );");
            return null;
        }
    }
Beispiel #6
0
 /**
  * Sends legacy mass mailer
  *
  * @deprecated 2.0
  *
  * @param  UserTable[]  $rows
  * @param  string       $emailSubject
  * @param  string       $emailBody
  * @param  string       $emailAttach
  * @param  string       $emailFromName
  * @param  string       $emailFromAddr
  * @param  string       $emailReplyName
  * @param  string       $emailReplyAddr
  * @param  int          $emailsPerBatch
  * @param  int          $emailsBatch
  * @param  int          $emailPause
  * @param  bool         $simulationMode
  * @param  array        $pluginRows
  * @return void
  */
 public function startEmailUsers($rows, $emailSubject, $emailBody, $emailAttach, $emailFromName, $emailFromAddr, $emailReplyName, $emailReplyAddr, $emailsPerBatch, $emailsBatch, $emailPause, $simulationMode, $pluginRows)
 {
     global $_CB_framework, $_CB_Backend_Title;
     _CBsecureAboveForm('showUsers');
     outputCbTemplate(2);
     outputCbJs(2);
     $_CB_Backend_Title = array(0 => array('fa fa-envelope-o', CBTxt::T('Community Builder: Sending Mass Mailer')));
     $userIds = array();
     foreach ($rows as $row) {
         $userIds[] = (int) $row->id;
     }
     $cbSpoofField = cbSpoofField();
     $cbSpoofString = cbSpoofString(null, 'cbadmingui');
     $regAntiSpamFieldName = cbGetRegAntiSpamFieldName();
     $regAntiSpamValues = cbGetRegAntiSpams();
     cbGetRegAntiSpamInputTag($regAntiSpamValues);
     $maximumBatches = count($rows) / $emailsPerBatch;
     if ($maximumBatches < 1) {
         $maximumBatches = 1;
     }
     $progressPerBatch = round(100 / $maximumBatches);
     $delayInMilliseconds = $emailPause ? 0 : $emailPause * 1000;
     $js = "var cbbatchemail = function( batch, emailsbatch, emailsperbatch ) {" . "\$.ajax({" . "type: 'POST'," . "url: '" . addslashes($_CB_framework->backendViewUrl('ajaxemailusers', false, array(), 'raw')) . "'," . "dataType: 'json'," . "data: {" . "emailsubject: '" . addslashes($emailSubject) . "'," . "emailbody: '" . addslashes(rawurlencode($emailBody)) . "'," . "emailattach: '" . addslashes($emailAttach) . "'," . "emailfromname: '" . addslashes($emailFromName) . "'," . "emailfromaddr: '" . addslashes($emailFromAddr) . "'," . "emailreplyname: '" . addslashes($emailReplyName) . "'," . "emailreplyaddr: '" . addslashes($emailReplyAddr) . "'," . "emailsperbatch: emailsperbatch," . "emailsbatch: emailsbatch," . "emailpause: '" . addslashes($emailPause) . "'," . "simulationmode: '" . addslashes($simulationMode) . "'," . "cid: " . json_encode($userIds) . "," . $cbSpoofField . ": '" . addslashes($cbSpoofString) . "'," . $regAntiSpamFieldName . ": '" . addslashes($regAntiSpamValues[0]) . "'" . "}," . "success: function( data, textStatus, jqXHR ) {" . "if ( data.result == 1 ) {" . "var progress = ( " . (int) $progressPerBatch . " * batch ) + '%';" . "\$( '#cbProgressIndicatorBar > .progress-bar' ).css({ width: progress });" . "\$( '#cbProgressIndicatorBar > .progress-bar > span' ).html( progress );" . "\$( '#cbProgressIndicator' ).html( data.htmlcontent );" . "setTimeout( cbbatchemail( ( batch + 1 ), ( emailsbatch + emailsperbatch ), emailsperbatch ), " . (int) $delayInMilliseconds . " );" . "} else if ( data.result == 2 ) {" . "\$( '#cbProgressIndicatorBar' ).removeClass( 'progress-striped active' );" . "\$( '#cbProgressIndicatorBar > .progress-bar' ).css({ width: '100%' });" . "\$( '#cbProgressIndicatorBar > .progress-bar' ).addClass( 'progress-bar-success' );" . "\$( '#cbProgressIndicatorBar > .progress-bar > span' ).html( '100%' );" . "\$( '#cbProgressIndicator' ).html( data.htmlcontent );" . "} else {" . "\$( '#cbProgressIndicatorBar' ).removeClass( 'progress-striped active' );" . "\$( '#cbProgressIndicatorBar > .progress-bar' ).css({ width: '100%' });" . "\$( '#cbProgressIndicatorBar > .progress-bar' ).addClass( 'progress-bar-danger' );" . "\$( '#cbProgressIndicatorBar > .progress-bar > span' ).html( '" . addslashes(CBTxt::T('Email failed to send')) . "' );" . "\$( '#cbProgressIndicator' ).html( data.htmlcontent );" . "}" . "}," . "error: function( jqXHR, textStatus, errorThrown ) {" . "\$( '#cbProgressIndicatorBar' ).removeClass( 'progress-striped active' );" . "\$( '#cbProgressIndicatorBar > .progress-bar' ).css({ width: '100%' });" . "\$( '#cbProgressIndicatorBar > .progress-bar' ).addClass( 'progress-bar-danger' );" . "\$( '#cbProgressIndicatorBar > .progress-bar > span' ).html( '" . addslashes(CBTxt::T('Email failed to send')) . "' );" . "\$( '#cbProgressIndicator' ).html( errorThrown );" . "}" . "});" . "};" . "cbbatchemail( 1, " . (int) $emailsBatch . ", " . (int) $emailsPerBatch . " );";
     $_CB_framework->outputCbJQuery($js);
     $return = '<form action="' . $_CB_framework->backendUrl('index.php') . '" method="post" id="cbmailbatchform" name="adminForm" class="cb_form form-auto cbEmailUsersBatchForm">';
     if ($simulationMode) {
         $return .= '<div class="form-group cb_form_line clearfix">' . '<label class="control-label col-sm-3">' . CBTxt::T('MASS_MAILER_SIMULATION_MODE_LABEL', 'Simulation Mode') . '</label>' . '<div class="cb_field col-sm-9">' . '<div><input type="checkbox" name="simulationmode" id="simulationmode" checked="checked" disabled="disabled" /> <label for="simulationmode">' . CBTxt::T('Do not send emails, just show me how it works') . '</label></div>' . '</div>' . '</div>';
     }
     $return .= $this->_pluginRows($pluginRows) . '<div class="form-group cb_form_line clearfix">' . '<label class="control-label col-sm-3">' . CBTxt::T('SEND_EMAIL_TO_TOTAL_USERS', 'Send Email to [total] users', array('[total]' => (int) count($rows))) . '</label>' . '<div class="cb_field col-sm-9">' . '<div>' . '<div id="cbProgressIndicatorBar" class="progress progress-striped active">' . '<div class="progress-bar" style="width: 0%;">' . '<span></span>' . '</div>' . '</div>' . '<div id="cbProgressIndicator"></div>' . '</div>' . '</div>' . '</div>' . $this->_pluginRows($pluginRows);
     if (!$simulationMode) {
         $return .= '<input type="hidden" name="simulationmode" value="' . htmlspecialchars($simulationMode) . '" />';
     }
     $return .= '<input type="hidden" name="option" value="com_comprofiler" />' . '<input type="hidden" name="view" value="ajaxemailusers" />' . '<input type="hidden" name="boxchecked" value="0" />';
     foreach ($rows as $row) {
         $return .= '<input type="hidden" name="cid[]" value="' . (int) $row->id . '">';
     }
     $return .= cbGetSpoofInputTag('user') . '</form>';
     echo $return;
 }
Beispiel #7
0
 /**
  * output points field html display
  *
  * @param  FieldTable  $field
  * @param  UserTable   $user
  * @param  string      $reason
  * @param  boolean     $ajax
  * @return string
  */
 private function getPointsHTML(&$field, &$user, $reason, $ajax = false)
 {
     global $_CB_framework;
     static $JS_loaded = 0;
     $userId = (int) $user->get('id');
     $fieldName = $field->get('name');
     $value = (int) $user->get($fieldName);
     $readOnly = $this->_isReadOnly($field, $user, $reason);
     $maxPoints = (int) $field->params->get('integer_maximum', '1000000');
     $pointsLayout = $field->params->get('points_layout', '');
     $userlistIncrement = (int) $field->params->get('points_list', 0);
     $userlistAccess = false;
     if ($reason == 'list') {
         $fieldName = $fieldName . $userId;
         if ($userlistIncrement) {
             $userlistAccess = true;
         }
     }
     $canIncrement = !$readOnly && $this->getIncrementAccess($field, $user) && ($reason == 'list' && $userlistAccess || $reason != 'list');
     if ($canIncrement) {
         $plusCSS = $field->params->get('points_plus_class', '');
         $minusCSS = $field->params->get('points_minus_class', '');
         $plusIcon = '<span class="' . ($plusCSS ? htmlspecialchars($plusCSS) : 'fa fa-plus-circle fa-lg') . '"></span>';
         $minusIcon = '<span class="' . ($minusCSS ? htmlspecialchars($minusCSS) : 'fa fa-minus-circle fa-lg') . '"></span>';
         $replace = array('[plus]' => $value < $maxPoints ? '<span class="cbPointsFieldIncrement cbPointsFieldIncrementPlus" data-value="plus" data-field="' . $field->get('name') . '" data-target="' . $userId . '">' . $plusIcon . '</span>' : null, '[minus]' => $value > 0 ? '<span class="cbPointsFieldIncrement cbPointsFieldIncrementMinus" data-value="minus" data-field="' . $field->get('name') . '" data-target="' . $userId . '">' . $minusIcon . '</span>' : null, '[value]' => '<span class="cbPointsFieldValue">' . $value . '</span>');
         if ($pointsLayout) {
             $pointsLayout = CBTxt::Th($pointsLayout, null, $replace);
         } else {
             $pointsLayout = CBTxt::Th('POINTS_FIELD_LAYOUT_VALUE_PLUS_MINUS', '[value] [plus] [minus]', $replace);
         }
         if ($ajax) {
             $return = $pointsLayout;
         } else {
             $return = '<span id="' . $fieldName . 'Container" class="cbPointsField' . ($userlistAccess ? ' cbClicksInside' : null) . '">' . $pointsLayout . '</span>';
             if (!$JS_loaded++) {
                 cbGetRegAntiSpamInputTag();
                 $cbGetRegAntiSpams = cbGetRegAntiSpams();
                 $js = "\$( '.cbPointsField' ).on( 'click', '.cbPointsFieldIncrement', function ( e ) {" . "var points = \$( this ).parents( '.cbPointsField' );" . "var increment = \$( this ).data( 'value' );" . "var field = \$( this ).data( 'field' );" . "var target = \$( this ).data( 'target' );" . "\$.ajax({" . "type: 'POST'," . "url: '" . addslashes(cbSef('index.php?option=com_comprofiler&view=fieldclass&function=savevalue&reason=' . urlencode($reason), false, 'raw')) . "'," . "data: {" . "field: field," . "user: target," . "value: increment," . cbSpoofField() . ": '" . addslashes(cbSpoofString(null, 'fieldclass')) . "'," . cbGetRegAntiSpamFieldName() . ": '" . addslashes($cbGetRegAntiSpams[0]) . "'" . "}" . "}).done( function( data, textStatus, jqXHR ) {" . "points.html( data );" . "});" . "});";
                 $_CB_framework->outputCbJQuery($js);
             }
         }
     } else {
         $return = parent::getField($field, $user, 'html', $reason, 0);
     }
     return $return;
 }
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>';
			}
		}
	}
/**
 * Checks spoof value and other spoofing and injection tricks
 *
 * @param  string   $secret   extra-hashing value for this particular spoofCheck
 * @param  string   $var      'POST', 'GET', 'REQUEST'
 * @param  int      $mode     1: exits with script to display error and go back, 2: returns true or false.
 * @return boolean  or exit   If $mode = 2 : returns false if session expired.
 */
function cbSpoofCheck( $secret = null, $var = 'POST', $mode = 1 ) {
	global $_POST, $_GET, $_REQUEST;

	if ( _CB_SPOOFCHECKS ) {
		if ( $var == 'GET' ) {
			$validateValue 	=	cbGetParam( $_GET,     cbSpoofField(), '' );
		} elseif ( $var == 'REQUEST' ) {
			$validateValue 	=	cbGetParam( $_REQUEST, cbSpoofField(), '' );
		} else {
			$validateValue 	=	cbGetParam( $_POST,    cbSpoofField(), '' );
		}
		if ( ( ! $validateValue ) || ( $validateValue != cbSpoofString( $validateValue, $secret ) ) ) {
			if ( $mode == 2 ) {
				return false;
			}
			_cbExpiredSessionJSterminate( 200 );
			exit;
		}
	}
	// First, make sure the form was posted from a browser.
	// For basic web-forms, we don't care about anything
	// other than requests from a browser:
	if (!isset( $_SERVER['HTTP_USER_AGENT'] )) {
		header( 'HTTP/1.0 403 Forbidden' );
		exit( _UE_NOT_AUTHORIZED );
	}

	// Make sure the form was indeed POST'ed:
	//  (requires your html form to use: action="post")
	if (!$_SERVER['REQUEST_METHOD'] == 'POST' ) {
		header( 'HTTP/1.0 403 Forbidden' );
		exit( _UE_NOT_AUTHORIZED );
	}

	// Attempt to defend against header injections:
	$badStrings = array(
		'Content-Type:',
		'MIME-Version:',
		'Content-Transfer-Encoding:',
		'bcc:',
		'cc:'
	);

	// Loop through each POST'ed value and test if it contains
	// one of the $badStrings:
	foreach ($_POST as $v){
		foreach ($badStrings as $v2) {
			if (is_array($v)) {
				_cbjosSpoofCheck($v, $badStrings);
			} else if (strpos( $v, $v2 ) !== false) {
				header( "HTTP/1.0 403 Forbidden" );
				exit( _UE_NOT_AUTHORIZED );
			}
		}
	}

	// Made it past spammer test, free up some memory
	// and continue rest of script:
	unset( $v, $v2, $badStrings );
	return true;
}
    static function registerForm($option, $emailpass, &$user, &$postvars, $regErrorMSG = null, $stillDisplayLoginModule = false)
    {
        global $_CB_framework, $_CB_database, $ueConfig, $_PLUGINS;
        $results = $_PLUGINS->trigger('onBeforeRegisterFormDisplay', array(&$user, $regErrorMSG));
        if ($_PLUGINS->is_errors()) {
            echo "<script type=\"text/javascript\">alert(\"" . $_PLUGINS->getErrorMSG() . "\"); window.history.go(-1); </script>\n";
            exit;
        }
        $cbTemplate = HTML_comprofiler::_cbTemplateLoad();
        outputCbTemplate(1);
        outputCbJs(1);
        initToolTip(1);
        $output = 'htmledit';
        $formatting = isset($ueConfig['use_divs']) && $ueConfig['use_divs'] ? 'divs' : 'tabletrs';
        // gets registration tabs from plugins (including the contacts tab core plugin for username, password, etc:
        $tabs = new cbTabs(0, 1, null, false);
        // do not output unused JS code in registration page (IE7 and Safari bugs on that)
        //$tabcontent							=	$tabs->getEditTabs( $user, $postvars, $output, 'tabletrs', 'register', false );
        $tabcontent = $tabs->getEditTabs($user, $postvars, $output, $formatting, 'register', false);
        // outputs the site terms and conditions link and approval checkbox: Not yet a CB field		//TBD
        if ($ueConfig['reg_enable_toc']) {
            global $_CB_OneTwoRowsStyleToggle;
            $class = 'sectiontableentry' . $_CB_OneTwoRowsStyleToggle;
            $_CB_OneTwoRowsStyleToggle = $_CB_OneTwoRowsStyleToggle == 1 ? 2 : 1;
            if ($formatting == 'divs') {
                $tabcontent .= "\t<div class=\"" . $class . " cb_form_line cbclearboth\" id=\"cbfr_termsc\">\n" . '<div class="cb_field"><div id="cbfv_termsc">';
            } else {
                $tabcontent .= "\t<tr class=\"" . $class . "\" id=\"cbfr_termsc\">\n" . "\t\t<td>&nbsp;</td>\n<td class='fieldCell'>";
            }
            $tabcontent .= "<div class=\"cbSnglCtrlLbl\"><input type='checkbox' name='acceptedterms' id='acceptedterms' class='required' value='1' mosReq='0' mosLabel='" . htmlspecialchars(_UE_TOC) . "' /> <label for='acceptedterms'>" . sprintf(_UE_TOC_LINK, "<a href='" . cbSef(htmlspecialchars($ueConfig['reg_toc_url'])) . "' target='_BLANK'> ", "</a>") . '</label>' . getFieldIcons($_CB_framework->getUi(), 1, null, null, null) . "</div>";
            if ($formatting == 'divs') {
                $tabcontent .= "</div></div></div>\n";
            } else {
                $tabcontent .= "</td>\n" . "\t</tr>\n";
            }
        }
        $_CB_framework->setPageTitle(_UE_REGISTRATION);
        $_CB_framework->appendPathWay(_UE_REGISTRATION);
        // starts outputing:
        // $cbSpoofField					=	cbSpoofField();
        $cbSpoofString = cbSpoofString(null, 'registerForm');
        // $regAntiSpamFieldName			=	cbGetRegAntiSpamFieldName();
        $regAntiSpamValues = cbGetRegAntiSpams();
        // <script type="text/javascript" src="includes/js/mambojavascript.js"></script>
        ob_start();
        if (defined('_CB_VALIDATE_NEW')) {
            cbimport('cb.validator');
            cbValidator::renderGenericJs();
            $cbjavascript = ob_get_contents();
            ob_end_clean();
            $_CB_framework->outputCbJQuery($cbjavascript, array('metadata', 'validate'));
        } else {
            // old way:
            ?>
var cbDefaultFieldBackground;
function cbFrmSubmitButton() {
	var me = this.elements;
<?php 
            $version = checkJversion();
            if ($version == 1) {
                // var r = new RegExp("^[a-zA-Z](([\.\-a-zA-Z0-9@])?[a-zA-Z0-9]*)*$", "i");
                ?>
	var r = new RegExp("[\<|\>|\"|\'|\%|\;|\(|\)|\&]", "i");
<?php 
            } elseif ($version == -1) {
                ?>
	var r = new RegExp("[^A-Za-z0-9]", "i");
<?php 
            } else {
                ?>
	var r = new RegExp("[\<|\>|\"|\'|\%|\;|\(|\)|\&|\+|\-]", "i");
<?php 
            }
            ?>
	var errorMSG = '';
	var iserror=0;
	if (cbDefaultFieldBackground === undefined && typeof(me['username'])!='undefined') cbDefaultFieldBackground = ((me['username'].style.getPropertyValue) ? me['username'].style.getPropertyValue("backgroundColor") : me['username'].style.backgroundColor);
<?php 
            echo $tabs->fieldJS;
            ?>
	if (typeof(me['username'])!='undefined' && me['username'].value == "") {
		errorMSG += "<?php 
            echo CBTxt::html_entity_decode(_REGWARN_UNAME);
            ?>
\n";
		me['username'].style.backgroundColor = "red";
		iserror=1;
	} else if (typeof(me['username'])!='undefined' && ( r.exec(me['username'].value) || (me['username'].value.length < 3))) {
		errorMSG += "<?php 
            printf(CBTxt::html_entity_decode(_VALID_AZ09), CBTxt::html_entity_decode(_PROMPT_UNAME), 2);
            ?>
\n";
		me['username'].style.backgroundColor = "red";
		iserror=1;
	} else if (typeof(me['username'])!='undefined' && me['username'].style.backgroundColor.slice(0,3)=="red") { me['username'].style.backgroundColor = cbDefaultFieldBackground;
<?php 
            if ($emailpass != "1") {
                ?>
	}
	if (typeof(me['password'])!='undefined' && me['password'].value.length < 6) {
		errorMSG += "<?php 
                printf(CBTxt::html_entity_decode(_VALID_AZ09), CBTxt::html_entity_decode(_REGISTER_PASS), 6);
                ?>
\n";
		me['password'].style.backgroundColor = "red";
		iserror=1;
	} else if (typeof(me['password'])!='undefined' && (me['password'].value != "") && (me['password'].value != me['password__verify'].value)){
		errorMSG += "<?php 
                echo CBTxt::html_entity_decode(_REGWARN_VPASS2);
                ?>
\n";
		me['password'].style.backgroundColor = "red"; me['password__verify'].style.backgroundColor = "red";
		iserror=1;
	} else if (typeof(me['password'])!='undefined') {
		if (me['password'].style.backgroundColor.slice(0,3)=="red") me['password'].style.backgroundColor = cbDefaultFieldBackground;
		if (me['password__verify'].style.backgroundColor.slice(0,3)=="red") me['password__verify'].style.backgroundColor = cbDefaultFieldBackground;
<?php 
            }
            ?>
	}
<?php 
            if ($ueConfig['reg_enable_toc']) {
                ?>
	if(!me['acceptedterms'].checked) {
		errorMSG += "<?php 
                echo CBTxt::html_entity_decode(_UE_TOC_REQUIRED);
                ?>
\n";
		iserror=1;
	}
<?php 
            }
            ?>
	// loop through all input elements in form
	var fieldErrorMessages = new Array;
	for (var i=0; i < me.length; i++) {
		// check if element is mandatory; here mosReq="1"
		var myenabled = (typeof(me[i].getAttribute('mosNoReq')) == 'undefined' ) || (me[i].getAttribute('mosNoReq') != 1);
		var mytyp = me[i].getAttribute('type');
		var myact = myenabled && mytyp != 'reset' && mytyp != 'button' && mytyp != 'submit' && mytyp != 'image';
		if ( myact && (typeof(me[i].getAttribute('mosReq')) != "undefined") && ( me[i].getAttribute('mosReq') == 1) ) {
			if (me[i].type == 'radio' || me[i].type == 'checkbox') {
				var rOptions = me[me[i].getAttribute('name')];
				var rChecked = 0;
				if(rOptions.length > 1) {
					for (var r=0; r < rOptions.length; r++) {
						if ( (typeof(rOptions[r].getAttribute('mosReq')) != "undefined") && ( rOptions[r].getAttribute('mosReq') == 1) ) {
							if (rOptions[r].checked) {
								rChecked=1;
							}
						}
					}
				} else {
					if (me[i].checked) {
						rChecked=1;
					}
				}
				if (rChecked==0) {
					for (var k=0; k < me.length; k++) {
						if (me[i].getAttribute('name') == me[k].getAttribute('name')) {
							if (me[k].checked) {
								rChecked=1;
								break;
							}
						}
					}
				}
				if (rChecked==0) {
					var alreadyFlagged = false;
					for (var j = 0, n = fieldErrorMessages.length; j < n; j++) {
						if (fieldErrorMessages[j] == me[i].getAttribute('name')) {
							alreadyFlagged = true;
							break
						}
					}
					if ( ! alreadyFlagged ) {
						fieldErrorMessages.push(me[i].getAttribute('name'));
						// add up all error messages
						errorMSG += me[i].getAttribute('mosLabel') + ' : <?php 
            echo CBTxt::html_entity_decode(_UE_REQUIRED_ERROR);
            ?>
\n';
						// notify user by changing background color, in this case to red
						me[i].style.backgroundColor = "red";
						iserror=1;
					}
				} else if (me[i].style.backgroundColor.slice(0,3)=="red") me[i].style.backgroundColor = cbDefaultFieldBackground;
			}
			if (me[i].value == '') {
				// add up all error messages
				errorMSG += me[i].getAttribute('mosLabel') + ' : <?php 
            echo CBTxt::html_entity_decode(_UE_REQUIRED_ERROR);
            ?>
\n';
				// notify user by changing background color, in this case to red
				me[i].style.backgroundColor = "red";
				iserror=1;
			} else if (me[i].style.backgroundColor.slice(0,3)=="red") me[i].style.backgroundColor = cbDefaultFieldBackground;
		}
	}
	if(iserror==1) {
		alert(errorMSG);
		return false;
	} else {
		return true;
	}
}
$('#cbcheckedadminForm').submit( cbFrmSubmitButton );
<?php 
            $cbjavascript = ob_get_contents();
            ob_end_clean();
            $_CB_framework->outputCbJQuery($cbjavascript);
            // end of old
        }
        if ($regErrorMSG) {
            echo "<div class='error'>" . $regErrorMSG . "</div>\n";
        }
        // output results of plugins event "onBeforeRegisterFormDisplay":
        if (is_array($results)) {
            echo implode('', $results);
        }
        $introMessage = isset($ueConfig['reg_intro_msg']) ? stripslashes(getLangDefinition($ueConfig['reg_intro_msg'])) : null;
        $conclusionMessage = isset($ueConfig['reg_conclusion_msg']) ? stripslashes(getLangDefinition($ueConfig['reg_conclusion_msg'])) : null;
        $https_post = checkCBPostIsHTTPS(true);
        $urlRegister = cbSef("index.php?option=" . $option);
        if ($https_post) {
            if (substr($urlRegister, 0, 5) != 'http:' && substr($urlRegister, 0, 6) != 'https:') {
                $urlRegister = $_CB_framework->getCfg('live_site') . '/' . $urlRegister;
            }
            $urlRegister = str_replace('http://', 'https://', $urlRegister);
        }
        $regFormTag = '<form action="' . $urlRegister . '" method="post" id="cbcheckedadminForm" name="adminForm" class="cb_form" enctype="multipart/form-data">
		<input type="hidden" name="id" value="0" />
		<input type="hidden" name="gid" value="0" />
		<input type="hidden" name="emailpass" value="' . $emailpass . '" />
		<input type="hidden" name="option" value="' . $option . '" />
		<input type="hidden" name="task" value="saveregisters" />
		' . cbGetSpoofInputTag(null, $cbSpoofString) . '
		' . cbGetRegAntiSpamInputTag($regAntiSpamValues) . "\n";
        $topIcons = null;
        $bottomIcons = null;
        if (!isset($ueConfig['reg_show_icons_explain']) || $ueConfig['reg_show_icons_explain'] > 0) {
            $icons = getFieldIcons(1, true, true, '', '', true);
            if (in_array($ueConfig['reg_show_icons_explain'], array(1, 3))) {
                $topIcons = $icons;
            }
            if (in_array($ueConfig['reg_show_icons_explain'], array(2, 3))) {
                $bottomIcons = $icons;
            }
        }
        $moduleContent = null;
        if (isset($ueConfig['reg_show_login_on_page']) && $ueConfig['reg_show_login_on_page'] == 1 && ($stillDisplayLoginModule || !$regErrorMSG)) {
            $params = null;
            $login_module_file = $_CB_framework->getCfg('absolute_path') . '/modules/' . (checkJversion() > 0 ? 'mod_cblogin/' : '') . 'mod_cblogin.php';
            if (file_exists($login_module_file)) {
                define('_UE_LOGIN_FROM', 'regform');
                $_CB_database->setQuery("SELECT params from #__modules WHERE module = 'mod_cblogin' ORDER BY ordering", 0, 1);
                $raw_params = $_CB_database->loadResult();
                $params = new cbParamsBase($raw_params);
                // needed for login module
                // $params of login module is needed for the include( $login_module_file ) below !!
                ob_start();
                include $login_module_file;
                $moduleContent = ob_get_contents();
                ob_end_clean();
            }
        }
        // renders using template viewer:
        echo HTML_comprofiler::_cbTemplateRender($cbTemplate, $user, 'RegisterForm', 'drawProfile', array(&$user, $tabcontent, $regFormTag, $introMessage, _LOGIN_REGISTER_TITLE, _REGISTER_TITLE, _UE_REGISTER, $moduleContent, $topIcons, $bottomIcons, $conclusionMessage, $formatting), $output);
        // finally small javascript to focus on first field on registration form if there is no introduction text and it's a text field:
        if (!(isset($ueConfig['reg_intro_msg']) && $ueConfig['reg_intro_msg'] || isset($ueConfig['reg_show_login_on_page']) && $ueConfig['reg_show_login_on_page'] == 1 || $regErrorMSG)) {
            $_CB_framework->outputCbJQuery('$("#cbcheckedadminForm input[type!=\'hidden\']:first").filter("[type=\'text\'],textarea,[type=\'password\']").focus();');
        }
    }
 /**
  * Shows result of database check or fix (with or without dryrun)
  *
  * @param  DatabaseUpgrade|CBDatabaseChecker|cbInstallerPlugin  $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
  */
 public static function renderDatabaseResults(&$dbChecker, $upgrade, $dryRun, $result, $messagesBefore, $messagesAfter, $dbName, $dbId, $showConclusion = true)
 {
     global $_CB_framework;
     static $JS_LOADED = 0;
     if (!$JS_LOADED++) {
         $js = "\$( '.cbDbResultsLogShow' ).on( 'click', function() {" . "\$( this ).addClass( 'hidden' );" . "\$( this ).siblings( '.cbDbResultsLogHide' ).removeClass( 'hidden' );" . "\$( this ).siblings( '.cbDbResultsLogMsgs' ).slideDown();" . "});" . "\$( '.cbDbResultsLogHide' ).on( 'click', function() {" . "\$( this ).addClass( 'hidden' );" . "\$( this ).siblings( '.cbDbResultsLogShow' ).removeClass( 'hidden' );" . "\$( this ).siblings( '.cbDbResultsLogMsgs' ).slideUp();" . "});" . "\$( '.cbDbResultsLogMsgs' ).hide();";
         $_CB_framework->outputCbJQuery($js);
     }
     $cbSpoofField = cbSpoofField();
     $cbSpoofString = cbSpoofString(null, 'plugin');
     $return = '<div class="cbDbResults">';
     if ($messagesBefore) {
         $return .= '<div class="form-group cb_form_line clearfix cbDbResultsMsgs">';
         foreach ($messagesBefore as $msg) {
             if ($msg) {
                 $return .= '<div class="cbDbResultsMsg">' . $msg . '</div>';
             }
         }
         $return .= '</div>';
     }
     if ($dbChecker !== null) {
         $return .= '<div class="form-group cb_form_line clearfix cbDbResultsCheck">';
         if ($result == true) {
             $return .= '<div class="text-success cbDbResultsSuccess">';
             if ($upgrade) {
                 if ($dryRun) {
                     $return .= CBTxt::T('NAME_DATABASE_ADJS_DRY_SUCCESS', '[name] database adjustments dryrun is successful. See results below.', array('[name]' => $dbName));
                 } else {
                     $return .= CBTxt::T('NAME_DATABASE_ADJS_SUCCESS', '[name] database adjustments have been performed successfully.', array('[name]' => $dbName));
                 }
             } else {
                 $return .= CBTxt::T('ALL_NAME_DATABASE_UPTODATE', 'All [name] database is up to date.', array('[name]' => $dbName));
             }
             $return .= '</div>';
         } elseif (is_string($result)) {
             $return .= '<div class="text-danger">' . $result . '</div>';
         } else {
             $return .= '<div class="text-danger cbDbResultsErrors">';
             if ($upgrade) {
                 $return .= CBTxt::T('NAME_DATABASE_ADJS_ERRORS', '[name] database adjustments errors:', array('[name]' => $dbName));
             } else {
                 $return .= CBTxt::T('NAME_DATABASE_STRUCT_DIFF', '[name] database structure differences:', array('[name]' => $dbName));
             }
             foreach ($dbChecker->getErrors(false) as $error) {
                 $return .= '<div class="text-large cbDbResultsError">' . htmlspecialchars($error[0]) . ($error[1] ? '<div class="text-small">' . htmlspecialchars($error[1]) . '</div>' : null) . '</div>';
             }
             $return .= '</div>';
             if (!$upgrade) {
                 $return .= '<div class="text-danger cbDbResultsErrorsFix">' . CBTxt::T('NAME_DATABASE_STRUCT_FIX', 'The [name] database structure differences can be fixed (adjusted) by clicking here:', array('[name]' => $dbName)) . ' <span class="alert alert-sm alert-danger text-large">' . '<a href="' . $_CB_framework->backendUrl("index.php?option=com_comprofiler&view=fixcbdb&dryrun=0&databaseid={$dbId}&{$cbSpoofField}={$cbSpoofString}") . '">' . CBTxt::T('NAME_DATABASE_DIFF_FIX_CLICK_HERE', 'Click here to fix (adjust) all [name] database differences listed above', array('[name]' => $dbName)) . '</a>' . '</span> ' . CBTxt::T('DATABASE_STRUCT_DRY_CLICK_HERE', '(you can also <a href="[url]">Click here to preview fixing (adjusting) queries in a dry-run</a>), but <strong class="text-large text-underline">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.', array('[url]' => $_CB_framework->backendUrl("index.php?option=com_comprofiler&view=fixcbdb&dryrun=1&databaseid={$dbId}&{$cbSpoofField}={$cbSpoofString}"))) . '</div>';
             }
         }
         $logs = $dbChecker->getLogs(false);
         if (count($logs) > 0) {
             $return .= '<div class="cbDbResultsLog">' . '<a href="javascript:void(0);" class="cbDbResultsLogShow">' . CBTxt::T('Click here to show details') . ' <span class="fa fa-caret-down"></span></a>' . '<a href="javascript:void(0);" class="cbDbResultsLogHide hidden">' . CBTxt::T('Click here to hide details') . ' <span class="fa fa-caret-up"></span></a>' . '<div class="text-success cbDbResultsLogMsgs" style="display: none;">';
             foreach ($logs as $log) {
                 $return .= '<div class="text-large cbDbResultsLogMsg">' . htmlspecialchars($log[0]) . ($log[1] ? '<div class="text-small">' . htmlspecialchars($log[1]) . '</div>' : null) . '</div>';
             }
             $return .= '</div>' . '</div>';
         }
         $return .= '</div>';
     }
     if ($showConclusion) {
         if ($upgrade) {
             if ($dryRun) {
                 $return .= '<div class="form-group cb_form_line clearfix cbDbResultsConclusion">' . CBTxt::T('NAME_DATABASE_ADJS_DRY', 'Dry-run of [name] database adjustments done. None of the queries listed in details have been performed.', array('[name]' => $dbName)) . '<br />' . CBTxt::T('NAME_DATABASE_ADJS_FIX', 'The [name] database adjustments listed above can be applied by clicking here:', array('[name]' => $dbName)) . ' <span class="alert alert-sm alert-danger text-large">' . '<a href="' . $_CB_framework->backendUrl("index.php?option=com_comprofiler&view=fixcbdb&dryrun=0&databaseid={$dbId}&{$cbSpoofField}={$cbSpoofString}") . '">' . CBTxt::T('NAME_DATABASE_DIFF_FIX_CLICK_HERE', 'Click here to fix (adjust) all [name] database differences listed above', array('[name]' => $dbName)) . '</a>' . '</span> ' . CBTxt::T('DATABASE_FIX_BACKUP_FIRST', '<strong class="text-danger text-large text-underline">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.') . '</div>';
             } else {
                 $return .= '<div class="form-group cb_form_line clearfix cbDbResultsConclusion">' . CBTxt::T('NAME_DATABASE_ADJS_DONE', 'The [name] 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.', array('[name]' => $dbName)) . '<br />' . CBTxt::T('NAME_DATABASE_STRUCT_CHECK', 'The [name] database structure can be checked again by clicking here:', array('[name]' => $dbName)) . ' <span class="alert alert-sm alert-warning text-large">' . '<a href="' . $_CB_framework->backendUrl("index.php?option=com_comprofiler&view=checkcbdb&databaseid={$dbId}&{$cbSpoofField}={$cbSpoofString}") . '">' . CBTxt::T('NAME_DATABASE_DIFF_CHECK_CLICK_HERE', 'Click here to check [name] database', array('[name]' => $dbName)) . '</a>' . '</span> ' . '</div>';
             }
         } else {
             $return .= '<div class="form-group cb_form_line clearfix cbDbResultsConclusion">' . CBTxt::T('NAME_DATABASE_CHECKS_DONE', '[name] database checks done. If all lines above are in green, test completed successfully. Otherwise, please take corrective measures proposed in red.', array('[name]' => $dbName)) . '</div>';
         }
     }
     if ($messagesAfter) {
         $return .= '<div class="form-group cb_form_line clearfix cbDbResultsMsgs">';
         foreach ($messagesAfter as $msg) {
             if ($msg) {
                 $return .= '<div class="cbDbResultsMsg">' . $msg . '</div>';
             }
         }
         $return .= '</div>';
     }
     $return .= '</div>';
     echo $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;
 }
 /**
  * Creates a cbpaidGatewaySelectorButton object for just changing the currency after asking for confirmation to change currency
  *
  * @param  cbpaidPaymentBasket  $paymentBasket
  * @param  string               $newCurrency
  * @param  string               $customImage
  * @param  string               $altText
  * @param  string               $titleText
  * @param  string               $payNameForCssClass
  * @param  string               $butId
  * @return cbpaidGatewaySelectorButton
  */
 public static function getChangeOfCurrencyButton($paymentBasket, $newCurrency, $customImage, $altText, $titleText, $payNameForCssClass, $butId)
 {
     list($pspUrl, $requestParams, $currencyInputName) = cbpaidControllerPaychoices::getCurrencyChangeFormParams($paymentBasket);
     $requestParams[$currencyInputName] = $newCurrency;
     $requestParams[cbSpoofField()] = cbSpoofString(null, 'plugin');
     return self::getPaymentButton(null, null, null, cbSef($pspUrl, false), $requestParams, $customImage, $altText, $titleText, $payNameForCssClass, $butId);
 }