} else {
    include_once XOOPS_ROOT_PATH . "/modules/formulize/language/english/main.php";
}
include_once XOOPS_ROOT_PATH . '/modules/formulize/include/functions.php';
// Set some required variables
$mid = getFormulizeModId();
$fid = "";
if (!($fid = $_GET['fid'])) {
    $fid = intval($_POST['fid']);
}
$frid = "";
if (!($frid = $_GET['frid'])) {
    $frid = intval($_POST['frid']);
}
if ($_GET['advcalc_acid']) {
    formulize_addProcedureChoicesToPost(strip_tags(htmlspecialchars($_GET['advcalc_acid'])));
    $acid = $_POST['acid'];
} else {
    $acid = null;
}
if (!$acid and $_GET['acid']) {
    $acid = intval($_GET['acid']);
}
$gperm_handler =& xoops_gethandler('groupperm');
$member_handler =& xoops_gethandler('member');
$groups = $xoopsUser ? $xoopsUser->getGroups() : array(0 => XOOPS_GROUP_ANONYMOUS);
$uid = $xoopsUser ? $xoopsUser->getVar('uid') : 0;
if (!($scheck = security_check($fid, "", $uid, "", $groups, $mid, $gperm_handler))) {
    print "<p>" . _NO_PERM . "</p>";
    exit;
}
function displayEntries($formframe, $mainform = "", $loadview = "", $loadOnlyView = 0, $viewallforms = 0, $screen = null)
{
    formulize_benchmark("start of drawing list");
    global $xoopsDB, $xoopsUser;
    // Set some required variables
    $mid = getFormulizeModId();
    list($fid, $frid) = getFormFramework($formframe, $mainform);
    $gperm_handler =& xoops_gethandler('groupperm');
    $member_handler =& xoops_gethandler('member');
    $groups = $xoopsUser ? $xoopsUser->getGroups() : array(0 => XOOPS_GROUP_ANONYMOUS);
    $uid = $xoopsUser ? $xoopsUser->getVar('uid') : "0";
    if (!($scheck = security_check($fid, "", $uid, "", $groups, $mid, $gperm_handler))) {
        print "<p>" . _NO_PERM . "</p>";
        return;
    }
    // must wrap security check in only the conditions in which it is needed, so we don't interfere with saving data in a form (which independently checks the security token)
    $formulize_LOESecurityPassed = (isset($GLOBALS['formulize_securityCheckPassed']) and $GLOBALS['formulize_securityCheckPassed']) ? true : false;
    if (($_POST['delconfirmed'] or $_POST['cloneconfirmed'] or $_POST['delviewid_formulize'] or $_POST['saveid_formulize'] or is_numeric($_POST['caid'])) and !$formulize_LOESecurityPassed) {
        $module_handler =& xoops_gethandler('module');
        $config_handler =& xoops_gethandler('config');
        $formulizeModule =& $module_handler->getByDirname("formulize");
        $formulizeConfig =& $config_handler->getConfigsByCat(0, $formulizeModule->getVar('mid'));
        $modulePrefUseToken = $formulizeConfig['useToken'];
        $useToken = $screen ? $screen->getVar('useToken') : $modulePrefUseToken;
        if (isset($GLOBALS['xoopsSecurity']) and $useToken) {
            $formulize_LOESecurityPassed = $GLOBALS['xoopsSecurity']->check();
        } else {
            // if there is no security token, then assume true -- necessary for old versions of XOOPS.
            $formulize_LOESecurityPassed = true;
        }
    }
    // check for all necessary permissions
    $add_own_entry = $gperm_handler->checkRight("add_own_entry", $fid, $groups, $mid);
    $delete_own_reports = $gperm_handler->checkRight("delete_own_reports", $fid, $groups, $mid);
    $delete_other_reports = $gperm_handler->checkRight("delete_other_reports", $fid, $groups, $mid);
    $update_other_reports = $gperm_handler->checkRight("update_other_reports", $fid, $groups, $mid);
    $update_own_reports = $gperm_handler->checkRight("update_own_reports", $fid, $groups, $mid);
    $view_globalscope = $gperm_handler->checkRight("view_globalscope", $fid, $groups, $mid);
    $view_groupscope = $gperm_handler->checkRight("view_groupscope", $fid, $groups, $mid);
    // Question:  do we need to add check here to make sure that $loadview is an available report (move function call from the generateViews function) and if it is not, then nullify
    // we may want to be able to pass in any old report, it's kind of like a way to override the publishing process.  Problem is unpublished reports or reports that aren't actually published to the user won't show up in the list of views.
    // [update: loaded views do not include the list of views, they have no interface at all except quick searches and quick sorts.  Since the intention is clearly for them to be accessed through pageworks, we will leave the permission control up to the application designer for now]
    $currentURL = getCurrentURL();
    // get title
    $displaytitle = getFormTitle($fid);
    // get default info and info passed to page....
    // clear any default search text that has been passed (because the user didn't actually search for anything)
    foreach ($_POST as $k => $v) {
        if (substr($k, 0, 7) == "search_" and $v == _formulize_DE_SEARCH_HELP) {
            unset($_POST[$k]);
            break;
            // assume this is only sent once, since the help text only appears in the first column
        }
    }
    // check for deletion request (set by 'delete selected' button)
    if ($_POST['delconfirmed'] and $formulize_LOESecurityPassed) {
        foreach ($_POST as $k => $v) {
            if (substr($k, 0, 7) == "delete_" and $v != "") {
                $delete_entry_id = substr($k, 7);
                // confirm user has permission to delete this entry
                if (formulizePermHandler::user_can_delete_entry($fid, $uid, $delete_entry_id)) {
                    $GLOBALS['formulize_deletionRequested'] = true;
                    // new syntax for deleteEntry, Sept 18 2005 -- used to handle deleting all unified display entries that are linked to this entry.
                    if ($frid) {
                        deleteEntry($delete_entry_id, $frid, $fid, $gperm_handler, $member_handler, $mid);
                    } else {
                        deleteEntry($delete_entry_id, "", $fid);
                    }
                }
            }
        }
    }
    // check for cloning request and if present then clone entries
    if ($_POST['cloneconfirmed'] and $formulize_LOESecurityPassed and $add_own_entry) {
        foreach ($_POST as $k => $v) {
            if (substr($k, 0, 7) == "delete_" and $v != "") {
                $thisentry = substr($k, 7);
                cloneEntry($thisentry, $frid, $fid, $_POST['cloneconfirmed']);
                // cloneconfirmed is the number of copies required
            }
        }
    }
    // handle deletion of view...reset currentView
    if ($_POST['delview'] and $formulize_LOESecurityPassed and ($delete_other_reports or $delete_own_reports)) {
        if (substr($_POST['delviewid_formulize'], 1, 4) == "old_") {
            $delviewid_formulize = substr($_POST['delviewid_formulize'], 5);
        } else {
            $delviewid_formulize = substr($_POST['delviewid_formulize'], 1);
        }
        if ($delete_other_reports or $xoopsUser->getVar('uid') == getSavedViewOwner($delviewid_formulize)) {
            // "get saved view owner" only works with new saved view format in 2.0 or greater, but since that is 2.5 years old now, should be good to go!
            if (substr($_POST['delviewid_formulize'], 1, 4) == "old_") {
                $sql = "DELETE FROM " . $xoopsDB->prefix("formulize_reports") . " WHERE report_id='" . $delviewid_formulize . "'";
            } else {
                $sql = "DELETE FROM " . $xoopsDB->prefix("formulize_saved_views") . " WHERE sv_id='" . $delviewid_formulize . "'";
            }
            if (!($res = $xoopsDB->query($sql))) {
                exit("Error deleting report: " . $_POST['delviewid_formulize']);
            }
            unset($_POST['currentview']);
            $_POST['resetview'] = 1;
        }
    }
    // if resetview is set, then unset POST and then set currentview to resetview
    // intended for when a user switches from a locked view back to a basic view.  In that case we want all settings to be cleared and everything to work like the basic view, rather than remembering, for instance, that the previous view had a calculation or a search of something.
    // users who view reports (views) that aren't locked can switch back to a basic view and retain settings.  This is so they can make changes to a view and then save the updates.  It is also a little confusing to switch from a predefined view to a basic one but have the predefined view's settings still hanging around.
    // recommendation to users should be to lock the controls for all published views.
    // (this routine also invoked when a view has been deleted)
    $resetview = false;
    if ($_POST['resetview']) {
        $resetview = $_POST['currentview'];
        foreach ($_POST as $k => $v) {
            unset($_POST[$k]);
        }
        $_POST['currentview'] = $resetview;
    }
    // handle saving of the view if that has been requested
    // only do this if there's a saveid_formulize and they passed the security check, and any one of these:  they can update other reports, or this is a "new" view, or this is not a new view, and it belongs to them and they have update own reports permission
    if ($_POST['saveid_formulize'] and $formulize_LOESecurityPassed and ($update_other_reports or (is_numeric($_POST['saveid_formulize']) and ($update_own_reports and $xoopsUser->getVar('uid') == getSavedViewOwner($_POST['saveid_formulize'])) or $_POST['saveid_formulize'] == "new"))) {
        // gather all values
        //$_POST['currentview'] -- from save (they might have updated/changed the scope)
        //possible situations:
        // user replaced a report, so we need to set that report as the name of the dropdown, value is currentview
        // user made a new report, so we need to set that report as the name and the value is currentview
        // so name of the report gets sent to $loadedView, which also gets assigned to settings array
        // report is either newid or newname if newid is "new"
        // newscope goes to $_POST['currentview']
        //$_POST['oldcols'] -- from page
        //$_POST['asearch'] -- from page
        //$_POST['calc_cols'] -- from page
        //$_POST['calc_calcs'] -- from page
        //$_POST['calc_blanks'] -- from page
        //$_POST['calc_grouping'] -- from page
        //$_POST['sort'] -- from page
        //$_POST['order'] -- from page
        //$_POST['hlist'] -- passed from page
        //$_POST['hcalc'] -- passed from page
        //$_POST['lockcontrols'] -- passed from save
        //and quicksearches -- passed with the page
        // pubgroups -- passed from save
        $_POST['currentview'] = $_POST['savescope'];
        $saveid_formulize = $_POST['saveid_formulize'];
        $_POST['lockcontrols'] = $_POST['savelock'];
        $savegroups = $_POST['savegroups'];
        // put name into loadview
        if ($saveid_formulize != "new") {
            if (!strstr($saveid_formulize, "old_")) {
                // if it's not a legacy report...
                $sname = q("SELECT sv_name, sv_owner_uid FROM " . $xoopsDB->prefix("formulize_saved_views") . " WHERE sv_id = \"" . substr($saveid_formulize, 1) . "\"");
                if ($sname[0]['sv_owner_uid'] == $uid) {
                    $loadedView = $saveid_formulize;
                } else {
                    $loadedView = "p" . substr($saveid_formulize, 1);
                }
            }
        }
        $savename = $_POST['savename'];
        if (get_magic_quotes_gpc()) {
            $savename = stripslashes($savename);
        }
        // flatten quicksearches -- one value in the array for every column in the view
        $allcols = explode(",", $_POST['oldcols']);
        foreach ($allcols as $thiscol) {
            $allquicksearches[] = $_POST['search_' . $thiscol];
        }
        // need to grab all hidden quick searches and then add any hidden columns to the column list...need to reverse this process when loading views
        foreach ($_POST as $k => $v) {
            if (substr($k, 0, 7) == "search_" and $v != "") {
                if (!in_array(substr($k, 7), $allcols) and substr($v, 0, 1) == "!" and substr($v, -1) == "!") {
                    $_POST['oldcols'] .= ",hiddencolumn_" . substr($k, 7);
                    $allquicksearches[] = $v;
                }
            }
        }
        $qsearches = implode("&*=%4#", $allquicksearches);
        $savename = formulize_db_escape($savename);
        $savesearches = formulize_db_escape($_POST['asearch']);
        //print $_POST['asearch'] . "<br>";
        //print "$savesearches<br>";
        $qsearches = formulize_db_escape($qsearches);
        if ($frid) {
            $saveformframe = $frid;
            $savemainform = $fid;
        } else {
            $saveformframe = $fid;
            $savemainform = "";
        }
        if ($saveid_formulize == "new" or strstr($saveid_formulize, "old_")) {
            if ($saveid_formulize == "new") {
                $owneruid = $uid;
                $moduid = $uid;
            } else {
                // get existing uid
                $olduid = q("SELECT report_uid FROM " . $xoopsDB->prefix("formulize_reports") . " WHERE report_id = '" . substr($saveid_formulize, 5) . "'");
                $owneruid = $olduid[0]['report_uid'];
                $moduid = $uid;
            }
            $savesql = "INSERT INTO " . $xoopsDB->prefix("formulize_saved_views") . " (" . "sv_name, " . "sv_pubgroups, " . "sv_owner_uid, " . "sv_mod_uid, " . "sv_formframe, " . "sv_mainform, " . "sv_lockcontrols, " . "sv_hidelist, " . "sv_hidecalc, " . "sv_asearch, " . "sv_sort, " . "sv_order, " . "sv_oldcols, " . "sv_currentview, " . "sv_calc_cols, " . "sv_calc_calcs, " . "sv_calc_blanks, " . "sv_calc_grouping, " . "sv_quicksearches, " . "sv_global_search" . ") VALUES (" . "\"" . formulize_db_escape($savename) . "\", " . "\"" . formulize_db_escape($savegroups) . "\", " . "\"" . formulize_db_escape($owneruid) . "\", " . "\"" . formulize_db_escape($moduid) . "\", " . "\"" . formulize_db_escape($saveformframe) . "\", " . "\"" . formulize_db_escape($savemainform) . "\", " . "\"" . formulize_db_escape($_POST['savelock']) . "\", " . "\"" . formulize_db_escape($_POST['hlist']) . "\", " . "\"" . formulize_db_escape($_POST['hcalc']) . "\", " . "\"" . formulize_db_escape($savesearches) . "\", " . "\"" . formulize_db_escape($_POST['sort']) . "\", " . "\"" . formulize_db_escape($_POST['order']) . "\", " . "\"" . formulize_db_escape($_POST['oldcols']) . "\", " . "\"" . formulize_db_escape($_POST['savescope']) . "\", " . "\"" . formulize_db_escape($_POST['calc_cols']) . "\", " . "\"" . formulize_db_escape($_POST['calc_calcs']) . "\", " . "\"" . formulize_db_escape($_POST['calc_blanks']) . "\", " . "\"" . formulize_db_escape($_POST['calc_grouping']) . "\", " . "\"" . formulize_db_escape($qsearches) . "\", " . "\"" . formulize_db_escape($_POST['global_search']) . "\"  " . ")";
        } else {
            // print "UPDATE " . $xoopsDB->prefix("formulize_saved_views") . " SET sv_pubgroups=\"$savegroups\", sv_mod_uid=\"$uid\", sv_lockcontrols=\"{$_POST['savelock']}\", sv_hidelist=\"{$_POST['hlist']}\", sv_hidecalc=\"{$_POST['hcalc']}\", sv_asearch=\"$savesearches\", sv_sort=\"{$_POST['sort']}\", sv_order=\"{$_POST['order']}\", sv_oldcols=\"{$_POST['oldcols']}\", sv_currentview=\"{$_POST['savescope']}\", sv_calc_cols=\"{$_POST['calc_cols']}\", sv_calc_calcs=\"{$_POST['calc_calcs']}\", sv_calc_blanks=\"{$_POST['calc_blanks']}\", sv_calc_grouping=\"{$_POST['calc_grouping']}\", sv_quicksearches=\"$qsearches\" WHERE sv_id = \"" . substr($saveid_formulize, 1) . "\"";
            $savesql = "UPDATE " . $xoopsDB->prefix("formulize_saved_views") . " SET " . "sv_name \t\t\t= \"" . formulize_db_escape($savename) . "\", " . "sv_pubgroups \t\t= \"" . formulize_db_escape($savegroups) . "\", " . "sv_mod_uid \t\t= \"" . formulize_db_escape($uid) . "\", " . "sv_lockcontrols \t= \"" . formulize_db_escape($_POST['savelock']) . "\", " . "sv_hidelist \t\t= \"" . formulize_db_escape($_POST['hlist']) . "\", " . "sv_hidecalc \t\t= \"" . formulize_db_escape($_POST['hcalc']) . "\", " . "sv_asearch \t\t= \"" . formulize_db_escape($savesearches) . "\", " . "sv_sort \t\t\t= \"" . formulize_db_escape($_POST['sort']) . "\", " . "sv_order \t\t\t= \"" . formulize_db_escape($_POST['order']) . "\", " . "sv_oldcols \t\t= \"" . formulize_db_escape($_POST['oldcols']) . "\", " . "sv_currentview \t= \"" . formulize_db_escape($_POST['savescope']) . "\", " . "sv_calc_cols \t\t= \"" . formulize_db_escape($_POST['calc_cols']) . "\", " . "sv_calc_calcs \t\t= \"" . formulize_db_escape($_POST['calc_calcs']) . "\", " . "sv_calc_blanks \t= \"" . formulize_db_escape($_POST['calc_blanks']) . "\", " . "sv_calc_grouping \t= \"" . formulize_db_escape($_POST['calc_grouping']) . "\", " . "sv_quicksearches \t= \"" . formulize_db_escape($qsearches) . "\", " . "sv_global_search   = \"" . formulize_db_escape($_POST['global_search']) . "\"  " . " WHERE " . "sv_id = \"" . substr($saveid_formulize, 1) . "\"";
        }
        // save the report
        if (!($result = $xoopsDB->query($savesql))) {
            exit("Error:  unable to save the current view settings.  SQL dump: {$savesql}");
        }
        if ($saveid_formulize == "new" or strstr($saveid_formulize, "old_")) {
            if ($owneruid == $uid) {
                $loadedView = "s" . $xoopsDB->getInsertId();
            } else {
                $loadedView = "p" . $xoopsDB->getInsertId();
            }
        }
        $settings['loadedview'] = $loadedView;
        // delete legacy report if necessary
        if (strstr($saveid_formulize, "old_")) {
            $dellegacysql = "DELETE FROM " . $xoopsDB->prefix("formulize_reports") . " WHERE report_id=\"" . substr($saveid_formulize, 5) . "\"";
            if (!($result = $xoopsDB->query($dellegacysql))) {
                exit("Error:  unable to delete legacy report: " . substr($saveid_formulize, 5));
            }
        }
    }
    $forceLoadView = false;
    if ($screen) {
        $loadview = is_numeric($loadview) ? $loadview : $screen->getVar('defaultview');
        // flag the screen default for loading if no specific view has been requested
        if ($loadview == "mine" or $loadview == "group" or $loadview == "all" or $loadview == "blank" and (!isset($_POST['hlist']) and !isset($_POST['hcalc']))) {
            // only pay attention to the "blank" default list if we are on an initial page load, ie: no hcalc or hlist is set yet, and one of those is set on each page load hereafter
            $currentView = $loadview;
            // if the default is a standard view, then use that instead and don't load anything
            unset($loadview);
        } elseif ($_POST['userClickedReset']) {
            // only set if the user actually clicked that button, and in that case, we want to be sure we load the default as specified for the screen
            $forceLoadView = true;
        }
    }
    // set currentView to group if they have groupscope permission (overridden below by value sent from form)
    // override with loadview if that is specified
    if ($loadview and (!$_POST['currentview'] and $_POST['advscope'] == "" or $forceLoadView)) {
        if (substr($loadview, 0, 4) == "old_") {
            // this is a legacy view
            $loadview = "p" . $loadview;
        } elseif (is_numeric($loadview)) {
            // new view id
            $loadview = "p" . $loadview;
        } else {
            // new view name -- loading view by name -- note if two reports have the same name, then the first one created will be returned
            $viewnameq = q("SELECT sv_id FROM " . $xoopsDB->prefix("formulize_saved_views") . " WHERE sv_name='{$loadview}' ORDER BY sv_id");
            $loadview = "p" . $viewnameq[0]['sv_id'];
        }
        $_POST['currentview'] = $loadview;
        $_POST['loadreport'] = 1;
    } elseif ($view_globalscope and !$currentView) {
        $currentView = "all";
    } elseif ($view_groupscope and !$currentView) {
        $currentView = "group";
    } elseif (!$currentView) {
        $currentView = "mine";
    }
    // debug block to show key settings being passed back to the page
    /*
    	if($uid == 1) {
    	print "delview: " . $_POST['delview'] . "<br>";
    	print "advscope: " . $_POST['advscope'] . "<br>";
    	print "asearch: " . $_POST['asearch'] . "<br>";
    	print "Hidelist: " . $_POST['hlist'] . "<br>";
    	print "Hidecalc: " . $_POST['hcalc'] . "<br>";
    	print "Lock Controls: " . $_POST['lockcontrols'] . "<br>";
    	print "Sort: " . $_POST['sort'] . "<br>";
    	print "Order: " . $_POST['order'] . "<br>";
    	print	"Cols: " . $_POST['oldcols'] . "<br>";
    	print "Curview: " . $_POST['currentview'] . "<br>";
    	print "Calculation columns: " . $_POST['calc_cols'] . "<br>";
    	print "Calculation calcs: " . $_POST['calc_calcs'] . "<br>";
    	print "Calculation blanks: " . $_POST['calc_blanks'] . "<br>";
    	print "Calculation grouping: " . $_POST['calc_grouping'] . "<br>";
    	foreach($_POST as $k=>$v) {
    		if(substr($k, 0, 7) == "search_" AND $v != "") {
    			print "$k: $v<br>";
    		}
    	}
    	}*/
    // set flag to indicate whether we let the user's scope setting expand beyond their normal permission level (happens when unlocked published views are in effect)
    $currentViewCanExpand = false;
    // handling change in view, and loading reports/saved views if necessary
    if ($_POST['loadreport']) {
        if (substr($_POST['currentview'], 1, 4) == "old_") {
            // legacy report
            // load old report values and then assign them to the correct $_POST keys in order to present the view
            $loadedView = $_POST['currentview'];
            $settings['loadedview'] = $loadedView;
            // kill the quicksearches
            foreach ($_POST as $k => $v) {
                if (substr($k, 0, 7) == "search_" and $v != "") {
                    unset($_POST[$k]);
                }
            }
            list($_POST['currentview'], $_POST['oldcols'], $_POST['asearch'], $_POST['calc_cols'], $_POST['calc_calcs'], $_POST['calc_blanks'], $_POST['calc_grouping'], $_POST['sort'], $_POST['order'], $_POST['hlist'], $_POST['hcalc'], $_POST['lockcontrols']) = loadOldReport(substr($_POST['currentview'], 5), $fid, $view_groupscope);
        } elseif (is_numeric(substr($_POST['currentview'], 1))) {
            // saved or published view
            $loadedView = $_POST['currentview'];
            $settings['loadedview'] = $loadedView;
            // kill the quicksearches, unless we've found a special flag that will cause them to be preserved
            if (!isset($_POST['formulize_preserveQuickSearches']) and !isset($_GET['formulize_preserveQuickSearches'])) {
                foreach ($_POST as $k => $v) {
                    if (substr($k, 0, 7) == "search_" and $v != "") {
                        unset($_POST[$k]);
                    }
                }
            }
            list($_POST['currentview'], $_POST['oldcols'], $_POST['asearch'], $_POST['calc_cols'], $_POST['calc_calcs'], $_POST['calc_blanks'], $_POST['calc_grouping'], $_POST['sort'], $_POST['order'], $savedViewHList, $savedViewHCalc, $_POST['lockcontrols'], $quicksearches, $_POST['global_search']) = loadReport(substr($_POST['currentview'], 1), $fid, $frid);
            if (!isset($_POST['formulize_preserveListCalcPage']) and !isset($_GET['formulize_preserveListCalcPage'])) {
                $_POST['hlist'] = $savedViewHList;
                $_POST['hcalc'] = $savedViewHCalc;
            }
            // explode quicksearches into the search_ values
            $allqsearches = explode("&*=%4#", $quicksearches);
            $colsforsearches = explode(",", $_POST['oldcols']);
            for ($i = 0; $i < count($allqsearches); $i++) {
                if ($allqsearches[$i] != "") {
                    $_POST["search_" . str_replace("hiddencolumn_", "", dealWithDeprecatedFrameworkHandles($colsforsearches[$i], $frid))] = $allqsearches[$i];
                    // need to remove the hiddencolumn indicator if it is present
                    if (strstr($colsforsearches[$i], "hiddencolumn_")) {
                        unset($colsforsearches[$i]);
                        // remove columns that were added to the column list just so we would know the name of the hidden searches
                    }
                }
            }
            $_POST['oldcols'] = implode(",", $colsforsearches);
            // need to reconstruct this in case any columns were removed because of persistent searches on a hidden column
        }
        $currentView = $_POST['currentview'];
        // need to check that the user is allowed to have this scope, unless the view is unlocked
        // only works for the default levels of views, not specific group selections that a view might have...that would be more complicated and could be built in later
        if ($_POST['lockcontrols']) {
            if ($currentView == "all" and !$view_globalscope) {
                $currentView = "group";
            }
            if ($currentView == "group" and !$view_groupscope and !$view_globalscope) {
                $currentView = "mine";
            }
        }
        // must check for this and set it here, inside this section, where we know for sure that $_POST['lockcontrols'] has been set based on the database value for the saved view, and not anything else sent from the user!!!  Otherwise the user might be injecting a greater scope for themselves than they should have!
        $currentViewCanExpand = $_POST['lockcontrols'] ? false : true;
        // if the controls are not locked, then we can expand the view for the user so they can see things they wouldn't normally see
        // if there is a screen with a top template in effect, then do not lock the controls even if the saved view says we should.  Assume that the screen author has compensated for any permission issues.
        // we need to do this after rachetting down the visibility controls.  Fact is, controlling UI for users is one thing that we can trust the screen author to do, so we don't need to indicate that the controls are locked.  But we don't want the visibility to override what people can normally see, so we rachet that down above.
        if ($screen and $_POST['lockcontrols']) {
            if ($screen->getTemplate('toptemplate') != "") {
                $_POST['lockcontrols'] = 0;
            }
        }
    } elseif ($_POST['advscope'] and strstr($_POST['advscope'], ",")) {
        // looking for comma sort of means that we're checking that a valid advanced scope is being sent
        $currentView = $_POST['advscope'];
    } elseif ($_POST['currentview']) {
        // could have been unset by deletion of a view or something else, so we must check to make sure it exists before we override the default that was determined above
        if (is_numeric(substr($_POST['currentview'], 1))) {
            // a saved view was requested as the current view, but we don't want to load the entire thing....this means that we just want to use the view to generate the scope, we don't want to load all settings.  So we have to load the view, but discard everything but the view's currentview value
            // if we were supposed to load the whole thing, loadreport would have been set in post and the above code would have kicked in
            $loadedViewSettings = loadReport(substr($_POST['currentview'], 1), $fid, $frid);
            $currentview = $loadedViewSettings[0];
        } else {
            $currentView = $_POST['currentview'];
        }
    } elseif ($loadview) {
        $currentView = $loadview;
    }
    // get columns for this form/framework or use columns sent from interface
    // ele_handles for a form, handles for a framework, includes handles of all unified display forms
    if ($_POST['oldcols']) {
        $showcols = explode(",", $_POST['oldcols']);
    } else {
        // or use the defaults
        $showcols = getDefaultCols($fid, $frid);
    }
    if ($_POST['newcols']) {
        $temp_showcols = $_POST['newcols'];
        $showcols = explode(",", $temp_showcols);
    }
    // convert framework handles to element handles if necessary
    $showcols = dealWithDeprecatedFrameworkHandles($showcols, $frid);
    $showcols = removeNotAllowedCols($fid, $frid, $showcols, $groups);
    // converts old format metadata fields to new ones too if necessary
    // Create settings array to pass to form page or to other functions
    $settings['title'] = $displaytitle;
    // get export options
    if ($_POST['xport']) {
        $settings['xport'] = $_POST['xport'];
        if ($_POST['xport'] == "custom") {
            $settings['xport_cust'] = $_POST['xport_cust'];
        }
    }
    list($scope, $currentView) = buildScope($currentView, $member_handler, $gperm_handler, $uid, $groups, $fid, $mid, $currentViewCanExpand);
    // generate the available views
    // pubstart used to indicate to the delete button where the list of published views begins in the current view drop down (since you cannot delete published views)
    list($settings['viewoptions'], $settings['pubstart'], $settings['endstandard'], $settings['pickgroups'], $settings['loadviewname'], $settings['curviewid'], $settings['publishedviewnames']) = generateViews($fid, $uid, $groups, $frid, $currentView, $loadedView, $view_groupscope, $view_globalscope, $_POST['curviewid'], $loadOnlyView, $screen, $_POST['lastloaded']);
    // this param only used in case of loading of reports via passing in the report id or name through $loadview
    if ($_POST['loadviewname']) {
        $settings['loadviewname'] = $_POST['loadviewname'];
    }
    // if a view was loaded, then update the lastloaded value, otherwise preserve the previous value
    if ($settings['curviewid']) {
        $settings['lastloaded'] = $settings['curviewid'];
    } else {
        $settings['lastloaded'] = $_POST['lastloaded'];
    }
    // clear quick searches for any columns not included now
    // also, convert any { } terms to literal values for users who can't update other reports, if the last loaded report doesn't belong to them (they're presumably just report consumers, so they don't need to preserve the abstract terms)
    $hiddenQuickSearches = array();
    // array used to indicate quick searches that should be present even if the column is not displayed to the user
    foreach ($_POST as $k => $v) {
        if (substr($k, 0, 7) == "search_" and !in_array(substr($k, 7), $showcols)) {
            if (substr($v, 0, 1) == "!" and substr($v, -1) == "!") {
                // don't strip searches that have ! at front and back
                $hiddenQuickSearches[] = substr($k, 7);
                continue;
                // since the { } replacement is meant for the ease of use of non-admin users, and hiddenQuickSearches never show up to users on screen, we can skip the potentially expensive operations below in this loop
            } else {
                unset($_POST[$k]);
            }
        }
        // if this is not a report/view that was created by the user, and they don't have update permission, then convert any { } terms to literals
        // remove any { } terms that don't have a passed in value (so they appear as "" to users)
        // only deal with terms that start and end with { } and not ones where the { } terms is not the entire term
        if (is_string($v) and substr($v, 0, 1) == "{" and substr($v, -1) == "}" and substr($k, 0, 7) == "search_" and in_array(substr($k, 7), $showcols)) {
            $requestKeyToUse = substr($v, 1, -1);
            if (!strstr($requestKeyToUse, "}") and !strstr($requestKeyToUse, "{")) {
                // double check that there's no other { } in the term!
                $activeViewId = substr($settings['lastloaded'], 1);
                // will have a p in front of the number, to show it's a published view (or an s, but that's unlikely to ever happen in this case)
                $ownerOfLastLoadedViewData = q("SELECT sv_owner_uid FROM " . $xoopsDB->prefix("formulize_saved_views") . " WHERE sv_id=" . intval($activeViewId));
                $ownerOfLastLoadedView = $ownerOfLastLoadedViewData[0]['sv_owner_uid'];
                if (!$update_other_reports and $uid != $ownerOfLastLoadedView) {
                    if (isset($_POST[$requestKeyToUse])) {
                        $_POST[$k] = htmlspecialchars(strip_tags(trim($_POST[$requestKeyToUse])));
                    } elseif (isset($_GET[$requestKeyToUse])) {
                        $_POST[$k] = htmlspecialchars(strip_tags(trim($_GET[$requestKeyToUse])));
                    } elseif ($v == "{USER}" and $xoopsUser) {
                        $_POST[$k] = $xoopsUser->getVar('name') ? $xoopsUser->getVar('name') : $xoopsUser->getVar('uname');
                    } elseif (!strstr($v, "{BLANK}") and !strstr($v, "{TODAY") and !strstr($v, "{PERGROUPFILTER}") and !strstr($v, "{USER")) {
                        unset($_POST[$k]);
                        // clear terms where no match was found, because this term is not active on the current page, so don't confuse users by showing it
                    }
                }
            }
        }
    }
    $settings['currentview'] = $currentView;
    $settings['currentURL'] = $currentURL;
    // no need for both these values now, since framework handles are deprecated
    $settings['columns'] = $showcols;
    $settings['columnhandles'] = $showcols;
    $settings['hlist'] = $_POST['hlist'];
    $settings['hcalc'] = $_POST['hcalc'];
    // determine if the controls should really be locked...
    if ($_POST['lockcontrols']) {
        // if a view locks the controls
        // only lock the controls when the user is not a member of the currentview groups AND has no globalscope
        // OR if they are a member of the currentview groups AND has no groupscope or no globalscope
        switch ($currentView) {
            case "mine":
                $settings['lockcontrols'] = "";
                break;
            case "all":
                if ($view_globalscope) {
                    $settings['lockcontrols'] = "";
                } else {
                    $settings['lockcontrols'] = "1";
                }
                break;
            case "group":
                if ($view_groupscope or $view_globalscope) {
                    $settings['lockcontrols'] = "";
                } else {
                    $settings['lockcontrols'] = "1";
                }
                break;
            default:
                $viewgroups = explode(",", trim($currentView, ","));
                // get the groups that the current user has specified scope for, and if none, then look at view form
                $formulize_permHandler = new formulizePermHandler($fid);
                $groupsWithAccess = $formulize_permHandler->getGroupScopeGroupIds($groups);
                if ($groupsWithAccess === false) {
                    $groupsWithAccess = $gperm_handler->getGroupIds("view_form", $fid, $mid);
                    $groupsWithAccess = array_intersect($groups, $groupsWithAccess);
                    // limit to just the user's own groups that have this permission, since what we're checking of below is whether the user's groups with view form meet the condition or not
                }
                $diff = array_diff($viewgroups, $groupsWithAccess);
                if (!isset($diff[0]) and $view_groupscope) {
                    // if the scopegroups are completely included in the user's groups that have access to the form, and they have groupscope (ie: they would be allowed to see all these entries anyway)
                    $settings['lockcontrols'] = "";
                } elseif ($view_globalscope) {
                    // if they have global scope
                    $settings['lockcontrols'] = "";
                } else {
                    // no globalscope and even if they're a member of the scope for this view, they don't have groupscope
                    $settings['lockcontrols'] = "1";
                }
        }
    } else {
        $settings['lockcontrols'] = "";
    }
    $settings['asearch'] = $_POST['asearch'];
    if ($_POST['asearch']) {
        $as_array = explode("/,%^&2", $_POST['asearch']);
        foreach ($as_array as $k => $one_as) {
            $settings['as_' . $k] = $one_as;
        }
    }
    $settings['oldcols'] = implode(",", $showcols);
    $settings['ventry'] = $_POST['ventry'];
    // get sort and order options
    $_POST['sort'] = dealWithDeprecatedFrameworkHandles($_POST['sort'], $frid);
    $settings['sort'] = $_POST['sort'];
    $settings['order'] = $_POST['order'];
    //get all submitted search text
    foreach ($_POST as $k => $v) {
        if (substr($k, 0, 7) == "search_" and $v != "") {
            $thiscol = substr($k, 7);
            $searches[$thiscol] = $v;
            $temp_key = "search_" . $thiscol;
            $settings[$temp_key] = $v;
        }
    }
    // get the submitted global search text
    $settings['global_search'] = $_POST['global_search'];
    // get all requested calculations...assign to settings array.
    $settings['calc_cols'] = $_POST['calc_cols'];
    $settings['calc_calcs'] = $_POST['calc_calcs'];
    $settings['calc_blanks'] = $_POST['calc_blanks'];
    $settings['calc_grouping'] = $_POST['calc_grouping'];
    // grab all the locked columns so we can persist them
    if (strstr($_POST['formulize_lockedColumns'], ",")) {
        $settings['lockedColumns'] = array_unique(explode(",", trim($_POST['formulize_lockedColumns'], ",")));
    } elseif (strlen($_POST['formulize_lockedColumns']) > 0) {
        $settings['lockedColumns'] = array(intval($_POST['formulize_lockedColumns']));
    } else {
        $settings['lockedColumns'] = array();
    }
    // set the requested procedure, if any
    $settings['advcalc_acid'] = strip_tags(htmlspecialchars($_POST['advcalc_acid']));
    formulize_addProcedureChoicesToPost($settings['advcalc_acid']);
    // gather id of the cached data, if any
    $settings['formulize_cacheddata'] = strip_tags($_POST['formulize_cacheddata']);
    // process a clicked custom button
    // must do this before gathering the data!
    $messageText = "";
    if (isset($_POST['caid']) and $screen and $formulize_LOESecurityPassed) {
        $customButtonDetails = $screen->getVar('customactions');
        if (is_numeric($_POST['caid']) and isset($customButtonDetails[$_POST['caid']])) {
            list($caCode, $caElements, $caActions, $caValues, $caMessageText, $caApplyTo, $caPHP, $caInline) = processCustomButton($_POST['caid'], $customButtonDetails[$_POST['caid']]);
            // just processing to get the info so we can process the click.  Actual output of this button happens lower down
            $messageText = processClickedCustomButton($caElements, $caValues, $caActions, $caMessageText, $caApplyTo, $caPHP, $caInline);
        }
    }
    if ($_POST['ventry']) {
        // user clicked on a view this entry link
        include_once XOOPS_ROOT_PATH . '/modules/formulize/include/formdisplay.php';
        if ($_POST['ventry'] == "addnew" or $_POST['ventry'] == "single") {
            $this_ent = "";
        } elseif ($_POST['ventry'] == "proxy") {
            $this_ent = "proxy";
        } else {
            $this_ent = $_POST['ventry'];
        }
        if ($screen and $screen->getVar("viewentryscreen") != "none" and $screen->getVar("viewentryscreen") or $_POST['overridescreen']) {
            if (strstr($screen->getVar("viewentryscreen"), "p")) {
                // if there's a p in the specified viewentryscreen, then it's a pageworks page -- added April 16 2009 by jwe
                $page = intval(substr($screen->getVar("viewentryscreen"), 1));
                include XOOPS_ROOT_PATH . "/modules/pageworks/index.php";
                return;
            } else {
                $screen_handler = xoops_getmodulehandler('screen', 'formulize');
                if ($_POST['overridescreen']) {
                    $screenToLoad = intval($_POST['overridescreen']);
                } else {
                    $screenToLoad = intval($screen->getVar('viewentryscreen'));
                }
                $viewEntryScreenObject = $screen_handler->get($screenToLoad);
                if ($viewEntryScreenObject->getVar('type') == "listOfEntries") {
                    exit("You're sending the user to a list of entries screen instead of some kind of form screen, when they're editing an entry.  Check what screen is defined as the screen to use for editing an entry, or what screen id you're using in the viewEntryLink or viewEntryButton functions in the template.");
                }
                $viewEntryScreen_handler = xoops_getmodulehandler($viewEntryScreenObject->getVar('type') . 'Screen', 'formulize');
                $displayScreen = $viewEntryScreen_handler->get($viewEntryScreenObject->getVar('sid'));
                if ($displayScreen->getVar('type') == "form") {
                    if ($_POST['ventry'] != "single") {
                        $displayScreen->setVar('reloadblank', 1);
                        // if the user clicked the add multiple button, then specifically override that screen setting so they can make multiple entries
                    } else {
                        $displayScreen->setVar('reloadblank', 0);
                        // otherwise, if they did click the single button, make sure the form reloads with their entry
                    }
                }
                $viewEntryScreen_handler->render($displayScreen, $this_ent, $settings);
                global $renderedFormulizeScreen;
                // picked up at the end of initialize.php so we set the right info in the template when the whole page is rendered
                $renderedFormulizeScreen = $displayScreen;
                return;
            }
        } else {
            if ($_POST['ventry'] != "single") {
                if ($frid) {
                    displayForm($frid, $this_ent, $fid, $currentURL, "", $settings, "", "", "", "", $viewallforms);
                    // "" is the done text
                    return;
                } else {
                    displayForm($fid, $this_ent, "", $currentURL, "", $settings, "", "", "", "", $viewallforms);
                    // "" is the done text
                    return;
                }
            } else {
                // if a single entry was requested for a form that can have multiple entries, then specifically override the multiple entry UI (which causes a blank form to appear on save)
                if ($frid) {
                    displayForm($frid, $this_ent, $fid, $currentURL, "", $settings, "", "", "1", "", $viewallforms);
                    // "" is the done text
                    return;
                } else {
                    displayForm($fid, $this_ent, "", $currentURL, "", $settings, "", "", "1", "", $viewallforms);
                    // "" is the done text
                    return;
                }
            }
        }
        // end of "if there's a viewentryscreen, then show that"
    }
    // check if we're coming back from a page where a form entry was saved, and if so, synch any subform blanks that might have been written on this page load, synch them with the mainform entry that was written
    $formToSynch = isset($_POST['primaryfid']) ? intval($_POST['primaryfid']) : 0;
    if ($formToSynch) {
        if (isset($_POST['entry' . $formToSynch]) and $enryToSynch = $_POST['entry' . $formToSynch]) {
            synchSubformBlankDefaults($formToSynch, $entryToSynch);
        }
    }
    include_once XOOPS_ROOT_PATH . "/modules/formulize/include/extract.php";
    // create $data and $wq (writable query)
    formulize_benchmark("before gathering dataset");
    list($data, $wq, $regeneratePageNumbers) = formulize_gatherDataSet($settings, $searches, strip_tags($_POST['sort']), strip_tags($_POST['order']), $frid, $fid, $scope, $screen, $currentURL, intval($_POST['forcequery']));
    formulize_benchmark("after gathering dataset/before generating calcs");
    if ($settings['calc_cols'] and !$settings['hcalc']) {
        //formulize_benchmark("before performing calcs");
        $ccols = explode("/", $settings['calc_cols']);
        $ccalcs = explode("/", $settings['calc_calcs']);
        $cblanks = explode("/", $settings['calc_blanks']);
        $cgrouping = explode("/", $settings['calc_grouping']);
        $cResults = performCalcs($ccols, $ccalcs, $cblanks, $cgrouping, $frid, $fid);
    }
    //formulize_benchmark("after performing calcs");
    formulize_benchmark("after generating calcs/before creating pagenav");
    $formulize_LOEPageNav = formulize_LOEbuildPageNav($data, $screen, $regeneratePageNumbers);
    formulize_benchmark("after nav/before interface");
    $formulize_buttonCodeArray = array();
    list($formulize_buttonCodeArray) = drawInterface($settings, $fid, $frid, $groups, $mid, $gperm_handler, $loadview, $loadOnlyView, $screen, $searches, $formulize_LOEPageNav, $messageText, $hiddenQuickSearches);
    // if there is messageText and no custom top template, and no messageText variable in the bottom template, then we have to output the message text here
    if ($screen and $messageText) {
        if (trim($screen->getTemplate('toptemplate')) == "" and !strstr($screen->getTemplate('bottomtemplate'), 'messageText')) {
            print "<p><center><b>{$messageText}</b></center></p>\n";
        }
    }
    formulize_benchmark("before entries");
    drawEntries($fid, $showcols, $searches, $frid, $scope, "", $currentURL, $gperm_handler, $uid, $mid, $groups, $settings, $member_handler, $screen, $data, $wq, $regeneratePageNumbers, $hiddenQuickSearches, $cResults);
    // , $loadview); // -- loadview not passed any longer since the lockcontrols indicator is used to handle whether things should appear or not.
    formulize_benchmark("after entries");
    if ($screen) {
        formulize_screenLOETemplate($screen, "bottom", $formulize_buttonCodeArray, $settings);
    } else {
        print $formulize_LOEPageNav;
        // redraw page numbers if there is no screen in effect
    }
    if (isset($formulize_buttonCodeArray['submitButton'])) {
        // if a custom top template was in effect, this will have been sent back, so now we display it at the very bottom of the form so it doesn't take up a visible amount of space above (the submitButton is invisible, but does take up space)
        print "<p class=\"formulize_customTemplateSubmitButton\">" . $formulize_buttonCodeArray['submitButton'] . "</p>";
    }
    print "</form>\n";
    // end of the form started in drawInterface
    print "</div>\n";
    // end of the listofentries div, used to call up the working message when the page is reloading, started in drawInterface
}