/**
     * 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)));
}
Example #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;
        }
    }
Example #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;
 }
Example #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;
 }
Example #8
0
 /**
  * Saves the CB plugin view after an edit view form submit
  *
  * @param  array                     $options
  * @param  array                     $actionPath
  * @param  array                     $keyValues
  * @param  array                     $parametersValues
  * @param  SimpleXMLElement          $viewModel
  * @param  TableInterface            $data
  * @param  RegistryEditController    $params
  * @param  string                    $mode
  * @param  string                    $dataModelType
  * @param  PluginTable               $plugin
  * @param  SimpleXMLElement          $dataModel
  * @param  RegistryInterface         $pluginParams
  * @param  string                    $cbprevstate
  * @param  int                       $ui
  * @return null|string                                  NULL: ok, STRING: error
  */
 protected function savePluginView($options, $actionPath, $keyValues, $parametersValues, $viewModel, $data, $params, &$mode, $dataModelType, $plugin, $dataModel, $pluginParams, $cbprevstate, $ui)
 {
     global $_CB_framework;
     new cbTabs(false, 2, -1, false);
     // prevents output of CB tabs js code until we are done with drawing (or redirecting)
     $resultingMsg = null;
     cbSpoofCheck('plugin');
     $postArray = $this->input->getNamespaceRegistry('post')->asArray();
     // List of variables to exclude from the $postArray:
     $exclude = array('option', 'cid', 'cbprevstate', cbSpoofField());
     foreach ($actionPath as $k => $v) {
         $exclude[] = $k;
     }
     // Remove the exclude variables from the $postArray before being used in the below cases:
     foreach ($exclude as $v) {
         if (isset($postArray[$v])) {
             unset($postArray[$v]);
         }
     }
     // Fix multi-selects and multi-checkboxes arrays to |*|-delimited strings:
     $postArray = $this->recursiveMultiSelectFix($postArray);
     foreach ($postArray as $key => $value) {
         if (property_exists($data, $key)) {
             $postArray[$key] = is_array($value) ? json_encode($value) : $value;
         }
     }
     $errorMsg = null;
     switch ($dataModelType) {
         case 'sql:row':
             if ($ui == 2) {
                 if (true !== ($error = RegistryEditView::validateAndBindPost($params, $postArray))) {
                     $errorMsg = $error;
                     break;
                 }
                 if (!$data->bind($postArray)) {
                     $errorMsg = $data->getError();
                     break;
                 }
             } else {
                 RegistryEditView::setFieldsListArrayValues(true);
                 $fields = $params->draw(null, null, null, null, null, null, false, 'param', 'fieldsListArray');
                 // New CB2.0 way for bind():
                 foreach ($fields as $key => $value) {
                     if (property_exists($data, $key)) {
                         $data->{$key} = is_array($value) ? json_encode($value) : $value;
                     }
                 }
             }
             if (!$data->check()) {
                 $errorMsg = $data->getError();
                 break;
             }
             $dataModelKey = $data->getKeyName();
             $dataModelValueOld = $data->{$dataModelKey};
             if ($mode == 'savecopy') {
                 if (!$data->canCopy($data)) {
                     $errorMsg = $data->getError();
                     break;
                 }
                 if (!$data->copy($data)) {
                     $errorMsg = $data->getError();
                     break;
                 }
             } else {
                 if (!$data->store()) {
                     $errorMsg = $data->getError();
                     break;
                 }
             }
             $dataModelValue = $data->{$dataModelKey};
             // Id changed; be sure to update the url encase of redirect:
             if (count($keyValues) == 1) {
                 $urlKeys = array_keys($keyValues);
                 $urlDataKey = $urlKeys[0];
                 if ($mode == 'savenew') {
                     unset($actionPath[$urlDataKey]);
                 } elseif ($dataModelValue != $dataModelValueOld) {
                     $actionPath[$urlDataKey] = $dataModelValue;
                 }
             }
             if ($data->hasFeature('checkout')) {
                 /** @var \CBLib\Database\Table\CheckedOrderedTable $data */
                 $data->checkin();
             }
             $this->savePluginViewOrder($data, $viewModel);
             $resultingMsg = $data->cbResultOfStore();
             break;
         case 'sql:field':
             // <data name="params" type="sql:field" table="#__cbsubs_config" class="cbpaidConfig" key="id" value="1" valuetype="sql:int" />
             $dataModelName = $dataModel->attributes('name');
             $dataModelKey = $dataModel->attributes('key');
             $dataModelValue = $dataModel->attributes('value');
             if ($ui == 2) {
                 if (true !== ($error = RegistryEditView::validateAndBindPost($params, $postArray))) {
                     $errorMsg = $error;
                     break;
                 }
             }
             $rawParams = array();
             $rawParams[$dataModelName] = json_encode($postArray);
             $xmlsql = new XmlQuery($this->db, null, $pluginParams);
             $xmlsql->process_data($dataModel);
             if ($dataModelValue) {
                 $result = $xmlsql->queryUpdate($rawParams);
             } else {
                 $result = $xmlsql->queryInsert($rawParams, $dataModelKey);
             }
             if (!$result) {
                 $errorMsg = $xmlsql->getErrorMsg();
             }
             break;
         case 'parameters':
             if ($ui == 2) {
                 if (true !== ($error = RegistryEditView::validateAndBindPost($params, $postArray))) {
                     $errorMsg = $error;
                     break;
                 }
             }
             $rawParams = array();
             $rawParams['params'] = json_encode($postArray);
             // $plugin = new PluginTable( $this->_db );
             // $plugin->load( $pluginId );
             if (!$plugin->bind($rawParams)) {
                 $errorMsg = $plugin->getError();
                 break;
             }
             if (!$plugin->check()) {
                 $errorMsg = $plugin->getError();
                 break;
             }
             if (!$plugin->store()) {
                 $errorMsg = $plugin->getError();
                 break;
             }
             $plugin->checkin();
             $plugin->updateOrder("type='" . $plugin->getDbo()->getEscaped($plugin->type) . "' AND ordering > -10000 AND ordering < 10000 ");
             $resultingMsg = $plugin->cbResultOfStore();
             break;
         case 'class':
             if ($ui == 2) {
                 if (true !== ($error = RegistryEditView::validateAndBindPost($params, $postArray))) {
                     $errorMsg = $error;
                     break;
                 }
             }
             if (!$data->bind($postArray)) {
                 $errorMsg = $data->getError();
                 break;
             }
             if (!$data->check()) {
                 $errorMsg = $data->getError();
                 break;
             }
             if (!$data->store()) {
                 $errorMsg = $data->getError();
                 break;
             }
             if ($data->hasFeature('checkout')) {
                 /** @var \CBLib\Database\Table\CheckedOrderedTable $data */
                 $data->checkin();
             }
             $this->savePluginViewOrder($data, $viewModel);
             $resultingMsg = $data->cbResultOfStore();
             break;
         case 'sql:multiplerows':
         default:
             echo 'Save error: showview data type: ' . $dataModelType . ' not implemented !';
             exit;
             break;
     }
     if ($ui == 2) {
         $url = 'index.php?option=' . $options['option'] . '&view=' . $options['view'];
         if ($options['view'] == 'editPlugin') {
             $url .= '&cid=' . $options['pluginid'];
         }
         $url = $_CB_framework->backendUrl($url);
     } else {
         $url = 'index.php';
         if (count($options) > 0) {
             $fixOptions = array();
             foreach ($options as $k => $v) {
                 $fixOptions[$k] = $k . '=' . urlencode($v);
             }
             $url .= '?' . implode('&', $fixOptions);
         }
     }
     if (isset($data->title)) {
         $dataItem = CBTxt::T($data->title);
     } elseif (isset($data->name)) {
         $dataItem = CBTxt::T($data->name);
     } else {
         $dataItem = null;
     }
     if ($errorMsg) {
         if (in_array($mode, array('save', 'savenew', 'savecopy'))) {
             $mode = 'apply';
         }
         $msg = CBTxt::T('FAILED_TO_SAVE_LABEL_ITEM_BECAUSE_ERROR', 'Failed to save [label] [item] because: [error]', array('[label]' => $viewModel->attributes('label'), '[item]' => $dataItem, '[error]' => $errorMsg));
         $msgType = 'error';
     } else {
         $msg = CBTxt::T('SUCCESSFULLY_SAVED_LABEL_ITEM', 'Successfully saved [label] [item]', array('[label]' => $viewModel->attributes('label'), '[item]' => $dataItem));
         $msgType = 'message';
     }
     switch ($mode) {
         case 'apply':
         case 'savenew':
         case 'savecopy':
             unset($actionPath['view']);
             foreach ($actionPath as $k => $v) {
                 if ($v !== '') {
                     $url .= '&' . $k . '=' . $v;
                 }
             }
             foreach ($parametersValues as $k => $v) {
                 $url .= '&' . $k . '=' . $v;
             }
             if ($cbprevstate) {
                 $url .= '&cbprevstate=' . $cbprevstate;
             }
             break;
         case 'save':
             if ($cbprevstate) {
                 $prevUrl = base64_decode($cbprevstate);
                 // $parametersValues[]		=	"'" . base64_encode( implode( '&', $cbprevstate ) ) . "'";
                 if (!preg_match('$[:/]$', $prevUrl)) {
                     $prevUrl = str_replace('&pluginid=', '&cid=', $prevUrl);
                     if ($ui == 2) {
                         $url = $_CB_framework->backendUrl('index.php?' . $prevUrl);
                     } else {
                         $url = 'index.php?' . $prevUrl;
                     }
                 }
             }
             break;
     }
     if ($resultingMsg) {
         if ($ui != 2) {
             return $resultingMsg;
             // in frontend, for now, don't redirect here: think this is right !
         } else {
             // If not an apply then change it to an apply so we can redisplay the view with the resulting message above it:
             if (in_array($mode, array('save', 'savenew', 'savecopy'))) {
                 $mode = 'apply';
             }
             echo $resultingMsg;
         }
     } else {
         if ($ui != 2) {
             return null;
             // in frontend, for now, don't redirect here: think this is right !
             // $url	=	cbUnHtmlspecialchars( cbSef( $url ) );
         }
         if ($mode == 'apply' && $errorMsg) {
             $_CB_framework->enqueueMessage($msg, $msgType);
         } else {
             cbRedirect($ui == 2 ? $url : cbSef(htmlspecialchars($url), false), $msg, $msgType);
         }
     }
     return null;
 }
	/**
	 * 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>';
			}
		}
	}
Example #10
0
/**
 * 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;
}
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)));
}
    static function lostPassForm($option)
    {
        global $_CB_framework, $ueConfig, $_PLUGINS;
        $_PLUGINS->loadPluginGroup('user');
        $results = $_PLUGINS->trigger('onLostPassForm', array(1));
        //$ui=1
        if ($_PLUGINS->is_errors()) {
            echo "<script type=\"text/javascript\">alert(\"" . $_PLUGINS->getErrorMSG() . "\"); window.history.go(-1); </script>\n";
            exit;
        }
        $cbSpoofField = cbSpoofField();
        $cbSpoofString = cbSpoofString(null, 'registerForm');
        $regAntiSpamFieldName = cbGetRegAntiSpamFieldName();
        $regAntiSpamValues = cbGetRegAntiSpams();
        $checkUsername = isset($ueConfig['reg_username_checker']) && $ueConfig['reg_username_checker'];
        $checkEmail = isset($ueConfig['reg_email_checker']) && $ueConfig['reg_email_checker'] > 1;
        $usernameExists = isset($ueConfig['login_type']) && $ueConfig['login_type'] != 2;
        $https_post = checkCBPostIsHTTPS(true);
        $urlLostPass = cbSef('index.php');
        if ($https_post) {
            if (substr($urlLostPass, 0, 5) != 'http:' && substr($urlLostPass, 0, 6) != 'https:') {
                $urlLostPass = $_CB_framework->getCfg('live_site') . '/' . $urlLostPass;
            }
            $urlLostPass = str_replace('http://', 'https://', $urlLostPass);
        }
        outputCbTemplate(1);
        ob_start();
        /*
        $('#adminForm').validate( {
        		errorClass: 'cb_result_warning',
                rules: { 
                    checkusername: { 
                        required: false, 
                        minlength: 3 //, 
                        			// remote: "users.php" 
                    }, 
        /*            password: { 
                        required: true, 
                        minlength: 5 
                    }, 
                    password_confirm: { 
                        required: true, 
                        minlength: 5, 
                        equalTo: "#password" 
                    }, 
        *
                    checkemail: { 
                        required: true, 
                        email: true, 
              //          remote: "emails.php" 
                    }, 
                }, 
                messages: { 
                    checkusername: { 
                        required: "Enter a username", 
                        minlength: jQuery.format("Enter at least {0} characters"), 
                        remote: jQuery.format("{0} is already in use") 
                    }, 
        /*
                    password: { 
                        required: "Provide a password", 
                        rangelength: jQuery.format("Enter at least {0} characters") 
                    }, 
                    password_confirm: { 
                        required: "Repeat your password", 
                        minlength: jQuery.format("Enter at least {0} characters"), 
                        equalTo: "Enter the same password as above" 
                    }, 
        *
                    checkemail: { 
                        required: "Please enter a valid email address", 
                        minlength: "Please enter a valid email address", 
                        remote: jQuery.format("{0} is already in use") 
                    }, 
                },
                errorPlacement: function(error, element) { 
                    if ( element.is(":radio") ) 
                        error.appendTo( element.parent().next().next() ); 
                    else if ( element.is(":checkbox") ) 
                        error.appendTo ( element.next() ); 
                    else 
                        // error.appendTo( element.parent().next() );
                        error.appendTo( element.parent().next().children()[0] );
                }
        } );
        */
        /*
        $('#adminForm').ajaxForm( {	url: '< ?php echo $_CB_framework->getCfg( 'live_site' ); ? >/index2.php?no_html=1&output=raw',
        							target: '#cb_lost_username_passwd_content',
        							beforeSubmit: function(formData, jqForm, options) {
        								$('#cb_line_lostbutton').fadeOut('fast', function() { $('#cb_line_lostbutton').html('<img src=\"< ?php echo $_CB_framework->getCfg( 'live_site' ); ?>/components/com_comprofiler/images/wait.gif\" /> <?php echo _UE_CHECKING; ? >').fadeIn('fast'); } );
        								return true;
        							},
        							success: function(responseText, statusText) {
        								alert('Got reply !status: ' + statusText + '\n\nresponseText: \n' + responseText + 
            							      '\n\nThe output div should have already been updated with the responseText.'); }
        						   } );
        */
        // checkboxes onchange trigger only on blur:
        ?>
$.fn.cb_uncheck = function() {
	return this.each( function() {
		this.checked = false;
	});
};
$('#boxLostUsername,#boxLostPassword').click( function() {
	if ( $('#boxLostUsername').get(0).checked ) {
		$('#cb_step1_form').slideDown('medium');
		$('#cb_line_checkusername').slideUp('medium');
		if ( $('#boxLostPassword').get(0).checked ) {
			$('#cbsendnewuspass').val('<?php 
        echo addslashes(_UE_BUTTON_SEND_USERNAME_PASS);
        ?>
');
			$('#cb_lost_username_password').slideDown('medium');
			$('#cb_lost_username,#cb_lost_password').slideUp('medium');
		} else {
			$('#cbsendnewuspass').val('<?php 
        echo addslashes(_UE_BUTTON_SEND_USERNAME);
        ?>
');
			$('#cb_lost_username').slideDown('medium');
			$('#cb_lost_password,#cb_lost_username_password').slideUp('medium');
		}
	} else {
		if ( $('#boxLostPassword').get(0).checked ) {
			$('#cbsendnewuspass').val('<?php 
        echo addslashes(_UE_BUTTON_SEND_PASS);
        ?>
');
			$('#cb_step1_form,#cb_lost_password,#cb_line_checkusername').slideDown('medium');
			$('#cb_lost_username,#cb_lost_username_password').slideUp('medium');
		} else {
			$('#cb_lost_username,#cb_lost_password,#cb_lost_username_password,#cb_step1_form').slideUp('medium');
		}
	}
	return true;
} );
<?php 
        if ($usernameExists) {
            ?>
$('#cb_lost_username,#cb_lost_password,#cb_lost_username_password,#cb_step1_form,#cb_line_checkusername').hide();
<?php 
        }
        ?>
$('#boxLostUsername,#boxLostPassword').cb_uncheck();
$('#checkusername,#checkemail').val('');
$('#cbsendnewuspass').attr('disabled',true);
$('#cb_lost_username').html('<?php 
        echo addslashes(defined('_UE_LOST_USERNAME_ONLY_DESC') ? _UE_LOST_USERNAME_ONLY_DESC : _UE_LOST_USERNAME_DESC);
        /* if we have ajax, no need for saying to leave username blank */
        ?>
');

$('#checkusername,#checkemail').keyup( function() {
	var respField = $('#'+$(this).attr('id')+'Response');
	if ( respField.html() != '&nbsp;' ) {
		respField.fadeOut('medium', function() { respField.html('&nbsp;'); } );
	}
	if ( $.trim( $('#checkusername').val() ) == '' ) {
		if ( $.trim( $('#checkemail').val() ) == '' ) {
			$('#cbsendnewuspass').attr('disabled',true);
		} else {
			$('#cbsendnewuspass').attr('disabled',false);
		}
	} else {
		$('#cbsendnewuspass').attr('disabled',false);
	}
	return true;
} );
<?php 
        if ($checkUsername || $checkEmail) {
            ?>

$('#checkusername,#checkemail').change( function() {
	if ( ( $(this).val() != '' ) && ( $('#'+$(this).attr('id')+'Response').length ) ) {
		$('#'+$(this).attr('id')+'Response').html('<img alt="" src=\"<?php 
            echo $_CB_framework->getCfg('live_site');
            ?>
/components/com_comprofiler/images/wait.gif\" /> <?php 
            echo _UE_CHECKING;
            ?>
').fadeIn('fast');
		var cbInputField = this;
		$.ajax( {	type: 'POST',
					url: '<?php 
            echo cbSef('index.php?option=com_comprofiler', false, 'raw');
            ?>
&task=perform'+$(this).attr('id')+'&function=testexists',
					data: 'value=' + encodeURIComponent( $(this).val() ) + '&<?php 
            echo $cbSpoofField;
            ?>
=' + encodeURIComponent('<?php 
            echo $cbSpoofString;
            ?>
') + '&<?php 
            echo $regAntiSpamFieldName;
            ?>
=' + encodeURIComponent('<?php 
            echo $regAntiSpamValues[0];
            ?>
'),
					success: function(response) { var respField = $('#'+$(cbInputField).attr('id')+'Response'); respField.fadeOut('fast', function() { respField.html(response).fadeIn('fast'); } ); },
					dataType: 'html'
		});
	} else {
		$('#'+$(this).attr('id')+'Response').html('&nbsp;');
	}
} );

<?php 
        }
        $jsContent = ob_get_contents();
        ob_end_clean();
        $_CB_framework->outputCbJQuery($jsContent);
        //TODO: Add ability to change password on form.
        ?>
<div class="componentheading"><?php 
        echo $usernameExists ? _UE_LOST_USERNAME_OR_PASSWORD : _UE_LOST_YOUR_PASSWORD;
        ?>
</div>
<div class="cbPageOuter" id="cbLostPasswordPage"><div class="cbPageInner">
	<div class="contentpaneopen" id="cb_lost_username_passwd_content">
		<form action="<?php 
        echo $urlLostPass;
        ?>
" class="cb_form" id="adminForm" name="adminForm" method="post">
		<?php 
        if ($usernameExists) {
            ?>
			<div class="cb_form_line" id="cb_lost_choice">
				<label for="cb_lost_choice"><?php 
            echo _UE_REMINDER_NEEDED_FOR;
            ?>
:</label>
				<div class="cb_field">
					<div><input type="checkbox" id="boxLostUsername" name="typeofloose[]" value="username" /> <label for="boxLostUsername"><?php 
            echo _UE_LOST__USERNAME;
            ?>
</label></div>
					<div><input type="checkbox" id="boxLostPassword" name="typeofloose[]" value="password" /> <label for="boxLostPassword"><?php 
            echo _UE_LOST__PASSWORD;
            ?>
</label></div>
				</div>
			</div>
		<?php 
        } else {
            ?>
			<input type="hidden" name="typeofloose[]" value="password" />
		<?php 
        }
        ?>
			<div class="cb_form_instructions">
				<ul>
		<?php 
        if ($usernameExists) {
            ?>
					<li id="cb_lost_username"><?php 
            echo getLangDefinition('_UE_LOST_USERNAME_DESC');
            ?>
</li>
					<li id="cb_lost_password"><?php 
            echo getLangDefinition('_UE_LOST_PASSWORD_DESC');
            ?>
</li>
					<li id="cb_lost_username_password"><?php 
            echo getLangDefinition('_UE_LOST_USERNAME_PASSWORD_DESC');
            ?>
</li>
		<?php 
        } else {
            ?>
					<li id="cb_lost_password"><?php 
            echo getLangDefinition('_UE_LOST_PASSWORD_EMAIL_ONLY_DESC');
            ?>
</li>
		<?php 
        }
        ?>
				</ul>
			</div>
			<div id="cb_step1_form">
<?php 
        if ($usernameExists) {
            ?>
				<div class="cb_form_line" id="cb_line_checkusername">
					<label for="checkusername"><?php 
            echo _PROMPT_UNAME;
            ?>
</label>
					<div class="cb_field">
						<div><input type="text" name="checkusername" id="checkusername" class="inputbox" size="30" maxlength="255" /></div>
<?php 
            if ($checkUsername) {
                ?>

						<div class="cb_result_container"><div id="checkusernameResponse">&nbsp;</div></div>
<?php 
            }
            ?>

					</div>
				</div>
<?php 
        }
        ?>

				<div class="cb_form_line" id="cb_line_checkemail">
					<label for="checkemail"><?php 
        echo _PROMPT_EMAIL;
        ?>
</label>
					<div class="cb_field">
						<div><input type="text" name="checkemail" id="checkemail" class="inputbox" size="30" maxlength="255" /></div>
<?php 
        if ($checkEmail) {
            ?>

						<div class="cb_result_container"><div id="checkemailResponse">&nbsp;</div></div>
<?php 
        }
        ?>

					</div>
				</div>
<?php 
        if (is_array($results)) {
            foreach ($results as $r) {
                ?>
				<div class="cb_form_line">
					<label<?php 
                if (isset($r[2])) {
                    echo ' for="' . $r[2] . '"';
                }
                ?>
><?php 
                echo $r[0];
                ?>
</label>
					<div class="cb_field"><?php 
                echo $r[1];
                ?>
</div>
				</div>
<?php 
            }
        }
        ?>

				<div class="cb_form_buttons_line" id="cb_line_lostbutton">
					<input type="submit" class="button" id="cbsendnewuspass" value="<?php 
        echo $usernameExists ? _UE_BUTTON_SEND_USERNAME_PASS : _UE_BUTTON_SEND_PASS;
        ?>
" />
				</div>
			</div>
			<input type="hidden" name="option" value="<?php 
        echo $option;
        ?>
" />
			<input type="hidden" name="task" value="sendNewPass" />
			<?php 
        echo cbGetSpoofInputTag('lostPassForm');
        echo "\t\t\t" . cbGetRegAntiSpamInputTag($regAntiSpamValues);
        ?>
		</form>
	</div>
</div></div>
<div class="cbClr"> </div>
<?php 
    }
Example #13
0
	function _process( $url ) {
		// Clean url
		$reg[] = "/<span[^>]*?>/si";
		$repl[] = '';
		$reg[] = "/<\/span>/si";
		$repl[] = '';
		$url = preg_replace( $reg, $repl, trim($url) );
		$origurl = JUri::root(true).$url;
		$origurl = preg_replace('/&amp;/', '&', $origurl);
		
		if (strpos($url, 'index.php')!== false||$this->ignoresef=="1") {
			$sef=false;
			$url = $url.((strpos($url, '?')===false)?'?':'&').'tmpl=component'.(($this->urlprint=='1')?'&print=1':'');
			// Add origin too to the component so it can redirect to the origin if something goes wrong
			$url .= '&origin='.base64_encode( JUri::getInstance()->toString() );
		} else {
			$sef=true;
			$url = $url.((substr($url, -1)!='/')?'/':'').'tmpl,component'.(($this->urlprint=='1')?'/print,1':'');
			// Add origin too to the component so it can redirect to the origin if something goes wrong		
			$url .= '/origin='.base64_encode( JUri::getInstance()->toString() );
		}
	
		$url = str_replace('http://', $this->protocol, JUri::root()).$url;
		// We need to replace the &amp; to & because the &amp; is not recognized
		$url = preg_replace('/&amp;/', '&', $url);
		
		// Close session so the other component can use it
		if ($this->closesession=="1") {
			$session =& JFactory::getSession();
			$session->close();
		}
		
		$cache = & JFactory::getCache('plugin_component');
		if ($this->caching=="1")
			$cache->setCaching( 1 );
			
		$response = $cache->call(array ( $this, '_getURL'), $url, $sef); 
		
		// Start the session again?
	
		if ($response!="") {
			// Clean the returned page of all html tags
	
			// get head and remove it
			// to do move meta tags, scripts and links to header?
			$reg = "/(<HEAD[^>]*>)(.*?)(<\/HEAD>)(.*)/si";
			$count = preg_match_all($reg,$response,$html);	
			if ($count>0) {
				$head=$html[2][0];
				$response= $html[4][0];
			} else {
				$head='';
			}
	
			if ($this->doctype!="feed"&&$this->doctype!="pdf"&&$this->ignore_allscripts!='1') {
				// Find stylesheets and javascripts and add them to this document
				// javascript scripts
				$reg = '/<script.*src=[\'\"](.*?)[\'\"][^>]*[^<]*(<\/script>)?/i';

				$count = preg_match_all($reg,$head,$scripts);	
				if ($count>0)
					foreach ($scripts[1] as $script) {
						$this->_addScript($script);
					}
				
				// javascript embedded
				$reg = '/<script[^>]*>(.*?)<\/script>/si';
				$scripts= array();
				$count = preg_match_all($reg,$head,$scripts);	
				if ($count>0)
					foreach ($scripts[1] as $script) {
						if (trim($script)!='') {
							// remove special contents type around scripts
							$script = str_replace('<!--', '', $script);
							$script = str_replace('-->', '', $script);
							$this->document->addScriptDeclaration($script);
						}
					}
			}
	
			if ($this->doctype!="feed"&&$this->ignore_allstyles!='1') {
				// stylesheet links
				$reg = '/<link.*href=[\'\"](.*?)[\'\"][^>]*[^<]*(<\/link>)?/i';
				$count = preg_match_all($reg,$head,$styles);	
				if ($count>0)
					for ($x=0;$x<$count;$x++) {
						if ((preg_match('/type=[\'"]text\/css[\'"]/i', $styles[0][$x])>0)||(preg_match('/rel=[\'"]stylesheet[\'"]/i', $styles[0][$x])>0))
							$this->_addStyleSheet($styles[1][$x]);
					}
				
				// Embedded styles
				$reg = '/<style[^>]*>(.*?)<\/style>/si';
				$styles = array();
				$count = preg_match_all($reg,$head,$styles);	
				if ($count>0)
					foreach ($styles[1] as $style) {
						if (trim($style)!='')
							$this->document->addStyleDeclaration($style);
					}
			}
			
			if ($this->doctype!="feed") {
				// Add meta tags and description to calling page
				$reg = '/<meta.*name=[\'\"](keywords|description)[\'\"].*content=[\'\"](.*?)[\'\"][^\/>]*/i';
				$count = preg_match_all($reg,$head,$meta);	
				if ($count>0)
					for ($x=0;$x<$count;$x++) {
						$old = $this->document->getMetaData ($meta[1][$x]);
						// Check if not already added?
						if ($meta[2][$x]!="")
							if (strpos($old, $meta[2][$x])===false) {
								if (strlen($old)>0&&strlen($meta[2][$x])>0)
									if ($meta[1][$x]=='keywords')
										$meta[2][$x] = ", ".$meta[2][$x];
									else
										$meta[2][$x] = " ".$meta[2][$x];
									
								$this->document->setMetaData ($meta[1][$x], $old.$meta[2][$x]);
							}
					}
			}
			
			// get body and remove it
			// to do attributes of body onload and other move to the real page?
			$reg = '/(<BODY[^>]*>)(.*)(<\/BODY>)/si';
			$count = preg_match_all($reg,$response,$html);	
			if ($count>0)
				$response=$html[2][0];
	
			$reg = array();
			$repl = array();
			
			// clean javascript for feeds and pdf
			if ($this->doctype=="feed"||$this->doctype=="pdf"||$this->ignore_allscripts=='1') {
				// Find stylesheets and javascripts and remove them
				// javascript scripts
				$reg[] = '/<script.*src=[\'\"](.*?)[\'\"][^>]*[^<]*(<\/script>)?/i';
				$repl[] = '';
				// javascript embedded
				$reg[] = '/<script[^>]*>(.*?)<\/script>/si';
				$repl[] = '';
			}
	
			if ($this->doctype=="feed"||$this->ignore_allstyles=='1') {
				// stylesheet links
				$reg[] = '/<link.*href=[\'\"](.*?)[\'\"][^>]*[^<]*(<\/link>)?/i';
				$repl[] = '';
				// Embedded styles
				$reg[] = '/<style[^>]*>(.*?)<\/style>/si';
				$repl[] = '';
			}
	
			// Replace links
			if ($this->replprint=='1') {
				$reg[] = "/&amp;print=1/";
				$repl[] = '';
				$reg[] = "/&print=1/";
				$repl[] = '';
			}
			if ($this->repltmpl=='1') {
				$reg[] = "/&amp;tmpl=component/";
				$repl[] = '';
				$reg[] = "/&tmpl=component/";
				$repl[] = '';
				$reg[] = "/\?tmpl=component&/";
				$repl[] = '?';
			}
			$reg[] = "/index2.php/";
			$repl[] = 'index.php';
			$reg[] = '/\$/';
			$repl[] = '\\\$';
			$response = preg_replace( $reg, $repl, $response );
			
			// Replace forms with empty action or no action attribute with original url
			$reg = '/<form[^>](.*?)>/i';
			$forms = array();
			$count = preg_match_all($reg,$response,$forms);
	
			if ($count>0)
				for ($cnt=0;$cnt<$count;$cnt++) {
					$reg = '/action=[\'\"](.*?)[\'\"]/i';
					$actions = array();
					$c = preg_match_all($reg,$forms[1][$cnt],$actions);
					if ($c>0) {
						// Check empty to replace
						if ($actions[1][0]=="")
							$newform = str_replace ($actions[0][0], 'action="'.$origurl.'"', $forms[0][$cnt]);
						else 
							$newform = $forms[0][$cnt];
					} else {
						// Toevoegen
						$newform = str_replace (">", ' action="'.$origurl.'">', $forms[0][$cnt]);
					}
					
					$response = str_replace ($forms[0][$cnt], $newform, $response);						
				}
			
			
			// Replace tokes
			$reg = '/<input type=["\']hidden["\'] name=["\'][a-f0-9]+["\'] value=["\']1["\'] \/>/si';
			$tokens = array();
			$count = preg_match_all($reg,$response,$tokens);
			if ($count>0)
				foreach ($tokens[0] as $token) {
					$response = str_replace ($token, JHTML::_( 'form.token' ), $response);
				}
	
			// Replace CB tokens
			$cbfile0 = JPATH_ADMINISTRATOR."/components/com_comprofiler/plugin.class.php";
			$cbfile1 = JPATH_ADMINISTRATOR.DS.'components'.DS.'com_comprofiler'.DS.'comprofiler.class.php';
			$cbfile2 = JPATH_ADMINISTRATOR.DS.'components'.DS.'com_comprofiler'.DS.'plugin.foundation.php';
			if ($this->cbreplace&&file_exists($cbfile0)&&file_exists($cbfile1)&&file_exists($cbfile2)) {
				require_once($cbfile0);
				require_once($cbfile1);
				require_once($cbfile2);
				$reg = '/<input type=["\']hidden["\'] name=["\']'.cbSpoofField().'["\'] value=["\'].*?["\'] \/>/si';
				$tokens = array();
				$count = preg_match_all($reg,$response,$tokens);
				if ($count>0)
					foreach ($tokens[0] as $token) {
						$response = str_replace ($token, cbGetSpoofInputTag('registerForm', null), $response);
					}
				$reg = '/<input type=["\']hidden["\'] name=["\']'.cbGetRegAntiSpamFieldName().'["\'] value=["\'].*?["\'] \/>/si';
				$tokens = array();
				$count = preg_match_all($reg,$response,$tokens);
				if ($count>0)
					foreach ($tokens[0] as $token) {
						$response = str_replace ($token, cbGetRegAntiSpamInputTag(), $response);
					}
			}
		}

		$content = "\n<!-- Plugin Include component version 1.13 by Mike Reumer";
		$content .= "\n     for: ".$url." -->";
		$content .= "\n".$response;
		$content .= "\n<!-- End Plugin Include component -->";

		return $content;	
	}
 /**
  * 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);
 }