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
}
Example #2
0
function displayForm($formframe, $entry = "", $mainform = "", $done_dest = "", $button_text = "", $settings = "", $titleOverride = "", $overrideValue = "", $overrideMulti = "", $overrideSubMulti = "", $viewallforms = 0, $profileForm = 0, $printall = 0, $screen = null)
{
    include_once XOOPS_ROOT_PATH . '/modules/formulize/include/functions.php';
    include_once XOOPS_ROOT_PATH . '/modules/formulize/include/extract.php';
    formulize_benchmark("Start of formDisplay.");
    if ($titleOverride == "formElementsOnly") {
        $titleOverride = "all";
        $formElementsOnly = true;
    }
    if (!is_numeric($titleOverride) and $titleOverride != "" and $titleOverride != "all") {
        // we can pass in a text title for the form, and that will cause the $titleOverride "all" behaviour to be invoked, and meanwhile we will use this title for the top of the form
        $passedInTitle = $titleOverride;
        $titleOverride = "all";
    }
    //syntax:
    //displayform($formframe, $entry, $mainform)
    //$formframe is the id of the form OR title of the form OR name of the framework.  Can also be an array.  If it is an array, then flag 'formframe' is the $formframe variable, and flag 'elements' is an array of all the elements that are to be displayed.
    //the array option is intended for displaying only part of a form at a time
    //$entry is the numeric entry to display in the form -- if $entry is the word 'proxy' then it is meant to force a new form entry when the form is a single-entry form that the user already may have an entry in
    //$mainform is the starting form to use, if this is a framework (can be specified by form id or by handle)
    //$done_dest is the URL to go to after the form has been submitted
    //Steps:
    //1. identify form or framework
    //2. if framework, check for unified display options
    //3. if entry specified, then get data for that entry
    //4. drawform with data if necessary
    global $xoopsDB, $xoopsUser, $myts;
    global $sfidsDrawn;
    if (!is_array($sfidsDrawn)) {
        $sfidsDrawn = array();
    }
    $groups = $xoopsUser ? $xoopsUser->getGroups() : array(0 => XOOPS_GROUP_ANONYMOUS);
    $original_entry = $entry;
    // flag used to tell whether the function was called with an actual entry specified, ie: we're supposed to be editing this entry, versus the entry being set by coming back form a sub_form or other situation.
    $mid = getFormulizeModId();
    $currentURL = getCurrentURL();
    /* Alter currentURL if necessary.
     * Display list of entries screen on-click of form buttons "Save and Leave" and "Leave Page".
     */
    if (isset($_GET['sid'])) {
        $curr_screen = xoops_getmodulehandler('screen', 'formulize')->get($_GET['sid']);
        if ($curr_screen->getVar('type') == 'form') {
            $currentURL = $_SERVER['PHP_SELF'] . "?fid=" . $curr_screen->form_id();
        }
    } elseif (isset($_GET['ve']) && isset($_GET['fid'])) {
        $currentURL = $_SERVER['PHP_SELF'] . "?fid=" . $_GET['fid'];
    }
    // identify form or framework
    $elements_allowed = "";
    // if a screen object is passed in, select the elements for display based on the screen's settings
    if ($screen and is_a($screen, "formulizeFormScreen")) {
        $elements_allowed = $screen->getVar("formelements");
    }
    if (is_array($formframe)) {
        $elements_allowed = $formframe['elements'];
        $printViewPages = isset($formframe['pages']) ? $formframe['pages'] : "";
        $printViewPageTitles = isset($formframe['pagetitles']) ? $formframe['pagetitles'] : "";
        $formframetemp = $formframe['formframe'];
        unset($formframe);
        $formframe = $formframetemp;
    }
    list($fid, $frid) = getFormFramework($formframe, $mainform);
    if ($_POST['deletesubsflag']) {
        // if deletion of sub entries requested
        foreach ($_POST as $k => $v) {
            if (strstr($k, "delbox")) {
                $subs_to_del[] = $v;
            }
        }
        if (count($subs_to_del) > 0) {
            deleteFormEntries($subs_to_del, intval($_POST['deletesubsflag']));
            // deletesubsflag will be the sub form id
            sendNotifications($_POST['deletesubsflag'], "delete_entry", $subs_to_del, $mid, $groups);
        }
    }
    if ($_POST['parent_form']) {
        // if we're coming back from a subform
        $entry = $_POST['parent_entry'];
        $fid = $_POST['parent_form'];
    }
    if ($_POST['go_back_form']) {
        // we just received a subform submission
        $entry = $_POST['sub_submitted'];
        $fid = $_POST['sub_fid'];
        $go_back['form'] = $_POST['go_back_form'];
        $go_back['entry'] = $_POST['go_back_entry'];
    }
    // set $entry in the case of a form_submission where we were editing an entry (just in case that entry is not what is used to call this function in the first place -- ie: we're on a subform and the mainform has no entry specified, or we're clicking submit over again on a single-entry form where we started with no entry)
    $entrykey = "entry" . $fid;
    if ((!$entry or $entry == "proxy") and $_POST[$entrykey]) {
        // $entrykey will only be set when *editing* an entry, not on new saves
        $entry = $_POST[$entrykey];
    }
    // this is probably not necessary any more, due to architecture changes in Formulize 3
    // formulize_newEntryIds is set when saving data
    if (!$entry and isset($GLOBALS['formulize_newEntryIds'][$fid])) {
        $entry = $GLOBALS['formulize_newEntryIds'][$fid][0];
    }
    $member_handler =& xoops_gethandler('member');
    $gperm_handler =& xoops_gethandler('groupperm');
    if ($profileForm === "new") {
        // spoof the $groups array based on the settings for the regcode that has been validated by register.php
        $reggroupsq = q("SELECT reg_codes_groups FROM " . XOOPS_DB_PREFIX . "_reg_codes WHERE reg_codes_code=\"" . $GLOBALS['regcode'] . "\"");
        $groups = explode("&8(%\$", $reggroupsq[0]['reg_codes_groups']);
        if ($groups[0] === "") {
            unset($groups);
        }
        // if a code has no groups associated with it, then kill the null value that will be in position 0 in the groups array.
        $groups[] = XOOPS_GROUP_USERS;
        $groups[] = XOOPS_GROUP_ANONYMOUS;
    }
    $uid = $xoopsUser ? $xoopsUser->getVar('uid') : '0';
    $single_result = getSingle($fid, $uid, $groups, $member_handler, $gperm_handler, $mid);
    $single = $single_result['flag'];
    // if we're looking at a single entry form with no entry specified and where the user has no entry of their own, or it's an anonymous user, then set the entry based on a cookie if one is present
    // want to do this check here and override $entry prior to the security check since we don't like trusting cookies!
    $cookie_entry = (isset($_COOKIE['entryid_' . $fid]) and !$entry and $single and ($single_result['entry'] == "" or intval($uid) === 0)) ? $_COOKIE['entryid_' . $fid] : "";
    include_once XOOPS_ROOT_PATH . "/modules/formulize/class/data.php";
    $data_handler = new formulizeDataHandler($fid);
    if ($cookie_entry) {
        // check to make sure the cookie_entry exists...
        //$check_cookie_entry = q("SELECT id_req FROM " . $xoopsDB->prefix("formulize_form") . " WHERE id_req=" . intval($cookie_entry));
        //if($check_cookie_entry[0]['id_req'] > 0) {
        if ($data_handler->entryExists(intval($cookie_entry))) {
            $entry = $cookie_entry;
        } else {
            $cookie_entry = "";
        }
    }
    $owner = ($cookie_entry and $uid) ? $uid : getEntryOwner($entry, $fid);
    // if we're pulling a cookie value and there is a valid UID in effect, then assume this user owns the entry, otherwise, figure out who does own the entry
    $owner_groups = $data_handler->getEntryOwnerGroups($entry);
    if ($single and !$entry and !$overrideMulti and $profileForm !== "new") {
        // only adjust the active entry if we're not already looking at an entry, and there is no overrideMulti which can be used to display a new blank form even on a single entry form -- useful for when multiple anonymous users need to be able to enter information in a form that is "one per user" for registered users. -- the pressence of a cookie on the hard drive of a user will override other settings
        $entry = $single_result['entry'];
        $owner = getEntryOwner($entry, $fid);
        unset($owner_groups);
        //$owner_groups =& $member_handler->getGroupsByUser($owner, FALSE);
        $owner_groups = $data_handler->getEntryOwnerGroups($entry);
    }
    if ($entry == "proxy") {
        $entry = "";
    }
    // convert the proxy flag to the actual null value expected for new entry situations (do this after the single check!)
    $editing = is_numeric($entry);
    // will be true if there is an entry we're looking at already
    if (!($scheck = security_check($fid, $entry, $uid, $owner, $groups, $mid, $gperm_handler)) and !$viewallforms and !$profileForm) {
        print "<p>" . _NO_PERM . "</p>";
        return;
    }
    // main security check passed, so let's initialize flags
    $go_back['url'] = substr($done_dest, 0, 1) == "/" ? XOOPS_URL . $done_dest : $done_dest;
    // set these arrays for the one form, and they are added to by the framework if it is in effect
    $fids[0] = $fid;
    if ($entry) {
        $entries[$fid][0] = $entry;
    } else {
        $entries[$fid][0] = "";
    }
    if ($frid) {
        $linkResults = checkForLinks($frid, $fids, $fid, $entries, $gperm_handler, $owner_groups, $mid, $member_handler, $owner, true);
        // final true means only include entries from unified display linkages
        unset($entries);
        unset($fids);
        $fids = $linkResults['fids'];
        $entries = $linkResults['entries'];
        $sub_fids = $linkResults['sub_fids'];
        $sub_entries = $linkResults['sub_entries'];
    }
    // need to handle submission of entries
    $formulize_mgr =& xoops_getmodulehandler('elements', 'formulize');
    $info_received_msg = 0;
    $info_continue = 0;
    if ($entries[$fid][0]) {
        $info_continue = 1;
    }
    $add_own_entry = $gperm_handler->checkRight("add_own_entry", $fid, $groups, $mid);
    $add_proxy_entries = $gperm_handler->checkRight("add_proxy_entries", $fid, $groups, $mid);
    if ($_POST['form_submitted'] and $profileForm !== "new" and formulizePermHandler::user_can_edit_entry($fid, $uid, $entry)) {
        $info_received_msg = "1";
        // flag for display of info received message
        if (!isset($GLOBALS['formulize_readElementsWasRun'])) {
            include_once XOOPS_ROOT_PATH . "/modules/formulize/include/readelements.php";
        }
        $temp_entries = $GLOBALS['formulize_allWrittenEntryIds'];
        // set in readelements.php
        if (!$formElementsOnly and ($single or $_POST['target_sub'] or $entries[$fid][0] and ($original_entry or $_POST[$entrykey] and !$_POST['back_from_sub']) or $overrideMulti or $_POST['go_back_form'] and $overrideSubMulti)) {
            // if we just did a submission on a single form, or we just edited a multi, then assume the identity of the new entry.  Can be overridden by values passed to this function, to force multi forms to redisplay the just-saved entry.  Back_from_sub is used to override the override, when we're saving after returning from a multi-which is like editing an entry since entries are saved prior to going to a sub. -- Sept 4 2006: adding an entry in a subform forces us to stay on the same page too! -- Dec 21 2011: added check for !$formElementsOnly so that when we're getting just the elements in the form, we ignore any possible overriding, since that is an API driven situation where the called entry is the only one we want to display, period.
            $entry = $temp_entries[$fid][0];
            unset($entries);
            foreach ($fids as $thisWrittenFid) {
                $entries[$thisWrittenFid] = $temp_entries[$thisWrittenFid];
            }
            // also remove any fids that aren't part of the $temp_entries...added Oct 26 2011...checkforlinks now can return the mainform when we're on a sub!  It's smarter, but displayForm (and possibly other places) were not built to assume it was that smart.
            $writtenFids = array_keys($temp_entries);
            $fids = array_intersect($fids, $writtenFids);
            $owner = getEntryOwner($entry, $fid);
            unset($owner_groups);
            $owner_groups = $data_handler->getEntryOwnerGroups($entry);
            //$owner_groups =& $member_handler->getGroupsByUser($owner, FALSE);
            $info_continue = 1;
        } elseif (!$_POST['target_sub']) {
            // as long as the form was submitted and we're not going to a sub form, then display the info received message and carry on with a blank form
            if (!$original_entry) {
                // if we're on a multi-form where the display form function was called without an entry, then clear the entries and behave as if we're doing a new add
                unset($entries);
                unset($sub_entries);
                $entries[$fid][0] = "";
                $sub_entries[$sub_fids[0]][0] = "";
            }
            $info_continue = 2;
        }
    }
    $sub_entries_synched = synchSubformBlankDefaults($fid, $entry);
    foreach ($sub_entries_synched as $synched_sfid => $synched_ids) {
        foreach ($synched_ids as $synched_id) {
            $sub_entries[$synched_sfid][] = $synched_id;
        }
    }
    if (count($sub_entries_synched) > 0) {
        formulize_updateDerivedValues($entry, $fid, $frid);
    }
    // special use of $settings added August 2 2006 -- jwe -- break out of form if $settings so indicates
    // used to allow saving of information when you don't want the form itself to reappear
    if ($settings == "{RETURNAFTERSAVE}" and $_POST['form_submitted']) {
        return "returning_after_save";
    }
    // need to add code here to switch some things around if we're on a subform for the first time (add)
    // note: double nested sub forms will not work currently, since on the way back to the intermediate level, the go_back values will not be set correctly
    // target_sub is only set when adding a sub entry, and adding sub entries is now down by the subform ui
    //if($_POST['target_sub'] OR $_POST['goto_sfid']) {
    if ($_POST['goto_sfid']) {
        $info_continue = 0;
        if ($_POST['goto_sfid']) {
            $new_fid = $_POST['goto_sfid'];
        } else {
            $new_fid = $_POST['target_sub'];
        }
        $go_back['form'] = $fid;
        $go_back['entry'] = $temp_entries[$fid][0];
        unset($entries);
        unset($fids);
        unset($sub_fids);
        unset($sub_entries);
        $fid = $new_fid;
        $fids[0] = $new_fid;
        if ($_POST['target_sub']) {
            // if we're adding a new entry
            $entries[$new_fid][0] = "";
        } else {
            // if we're going to an existing entry
            $entries[$new_fid][0] = $_POST['goto_sub'];
        }
        $entry = $entries[$new_fid][0];
        $single_result = getSingle($fid, $uid, $groups, $member_handler, $gperm_handler, $mid);
        $single = $single_result['flag'];
        if ($single and !$entry) {
            $entry = $single_result['entry'];
            unset($entries);
            $entries[$fid][0] = $entry;
        }
        unset($owner);
        $owner = getEntryOwner($entries[$new_fid][0], $new_fid);
        $editing = is_numeric($entry);
        unset($owner_groups);
        //$owner_groups =& $member_handler->getGroupsByUser($owner, FALSE);
        $newFidData_handler = new formulizeDataHandler($new_fid);
        $owner_groups = $newFidData_handler->getEntryOwnerGroups($entries[$new_fid][0]);
        $info_received_msg = 0;
        // never display this message when a subform is displayed the first time.
        if ($entry) {
            $info_continue = 1;
        }
        if (!($scheck = security_check($fid, $entries[$fid][0], $uid, $owner, $groups, $mid, $gperm_handler)) and !$viewallforms) {
            print "<p>" . _NO_PERM . "</p>";
            return;
        }
    }
    // there are several points above where $entry is set, and now that we have a final value, store in ventry
    if ($entry > 0 and (!isset($settings['ventry']) or "addnew" != $settings['ventry'])) {
        $settings['ventry'] = $entry;
    }
    // set the alldoneoverride if necessary -- August 22 2006
    $config_handler =& xoops_gethandler('config');
    $formulizeConfig = $config_handler->getConfigsByCat(0, $mid);
    // remove the all done button if the config option says 'no', and we're on a single-entry form, or the function was called to look at an existing entry, or we're on an overridden Multi-entry form
    $allDoneOverride = (!$formulizeConfig['all_done_singles'] and !$profileForm and (($single or $overrideMulti or $original_entry) and !$_POST['target_sub'] and !$_POST['goto_sfid'] and !$_POST['deletesubsflag'] and !$_POST['parent_form'])) ? true : false;
    if (($allDoneOverride or isset($_POST['save_and_leave']) and $_POST['save_and_leave']) and $_POST['form_submitted']) {
        drawGoBackForm($go_back, $currentURL, $settings, $entry);
        print "<script type=\"text/javascript\">window.document.go_parent.submit();</script>\n";
        return;
    } else {
        // only do all this stuff below, the normal form displaying stuff, if we are not leaving this page now due to the all done button being overridden
        // we cannot have the back logic above invoked when dealing with a subform, but if the override is supposed to be in place, then we need to invoke it
        if (!$allDoneOverride and !$formulizeConfig['all_done_singles'] and !$profileForm and ($_POST['target_sub'] or $_POST['goto_sfid'] or $_POST['deletesubsflag'] or $_POST['parent_form']) and ($single or $original_entry or $overrideMulti)) {
            $allDoneOverride = true;
        }
        /*if($uid==1) {
        		print "Forms: ";
        		print_r($fids);
        		print "<br>Entries: ";
        		print_r($entries);
        		print "<br>Subforms: ";
        		print_r($sub_fids);
        		print "<br>Subentries: ";
        		print_r($sub_entries); // debug block - ONLY VISIBLE TO USER 1 RIGHT NOW 
        		} */
        formulize_benchmark("Ready to start building form.");
        $title = "";
        foreach ($fids as $this_fid) {
            if (!($scheck = security_check($this_fid, $entries[$this_fid][0], $uid, $owner, $groups, $mid, $gperm_handler)) and !$viewallforms) {
                continue;
            }
            // if there is more than one form, try to make the 1-1 links
            // and if we made any, then include the newly linked up entries
            // in the index of entries that we're keeping track of
            if (count($fids) > 1) {
                list($form1s, $form2s, $form1EntryIds, $form2EntryIds) = formulize_makeOneToOneLinks($frid, $this_fid);
                foreach ($form1EntryIds as $i => $form1EntryId) {
                    // $form1EntryId set above, now set other values for this iteration based on the key
                    $form2EntryId = $form2EntryIds[$i];
                    $form1 = $form1s[$i];
                    $form2 = $form2s[$i];
                    if ($form1EntryId) {
                        $entries[$form1][0] = $form1EntryId;
                    }
                    if ($form2EntryId) {
                        $entries[$form2][0] = $form2EntryId;
                    }
                }
            }
            unset($prevEntry);
            // if there is an entry, then get the data for that entry
            if ($entries[$this_fid]) {
                $groupEntryWithUpdateRights = ($single == "group" and $gperm_handler->checkRight("update_own_entry", $fid, $groups, $mid) and $entry == $single_result['entry']);
                $prevEntry = getEntryValues($entries[$this_fid][0], $formulize_mgr, $groups, $this_fid, $elements_allowed, $mid, $uid, $owner, $groupEntryWithUpdateRights);
            }
            // display the form
            //get the form title: (do only once)
            $firstform = 0;
            if (!$form) {
                $firstform = 1;
                $title = isset($passedInTitle) ? $passedInTitle : trans(getFormTitle($this_fid));
                if ($screen) {
                    $title = trans($screen->getVar('title'));
                }
                unset($form);
                if ($formElementsOnly) {
                    $form = new formulize_elementsOnlyForm($title, 'formulize', "{$currentURL}", "post", true);
                } else {
                    // extended class that puts formulize element names into the tr tags for the table, so we can show/hide them as required
                    $form = new formulize_themeForm($title, 'formulize', "{$currentURL}", "post", true);
                    // necessary to trigger the proper reloading of the form page, until Done is called and that form does not have this flag.
                    if (!isset($settings['ventry'])) {
                        $settings['ventry'] = 'new';
                    }
                    $form->addElement(new XoopsFormHidden('ventry', $settings['ventry']));
                }
                $form->setExtra("enctype='multipart/form-data'");
                // impératif!
                if (is_array($settings)) {
                    $form = writeHiddenSettings($settings, $form);
                }
                // include who the entry belongs to and the date
                // include acknowledgement that information has been updated if we have just done a submit
                // form_meta includes: last_update, created, last_update_by, created_by
                $breakHTML = "";
                if (!$profileForm and $titleOverride != "all") {
                    // build the break HTML and then add the break to the form
                    if (!strstr($currentURL, "printview.php")) {
                        $breakHTML .= "<center class=\"no-print\">";
                        $breakHTML .= "<p><b>";
                        if ($info_received_msg) {
                            $breakHTML .= _formulize_INFO_SAVED . "&nbsp;";
                        }
                        if ($info_continue == 1 and formulizePermHandler::user_can_edit_entry($fid, $uid, $entry)) {
                            $breakHTML .= "<p class=\"no-print\">" . _formulize_INFO_CONTINUE1 . "</p>";
                        } elseif ($info_continue == 2) {
                            $breakHTML .= "<p class=\"no-print\">" . _formulize_INFO_CONTINUE2 . "</p>";
                        } elseif (!$entry and formulizePermHandler::user_can_edit_entry($fid, $uid, $entry)) {
                            $breakHTML .= "<p class=\"no-print\">" . _formulize_INFO_MAKENEW . "</p>";
                        }
                        $breakHTML .= "</b></p>";
                        $breakHTML .= "</center>";
                    }
                    $breakHTML .= "<table cellpadding=5 width=100%><tr><td width=50% style=\"vertical-align: bottom;\">";
                    $breakHTML .= "<p><b>" . _formulize_FD_ABOUT . "</b><br>";
                    if ($entries[$this_fid][0]) {
                        $form_meta = getMetaData($entries[$this_fid][0], $member_handler, $this_fid);
                        $breakHTML .= _formulize_FD_CREATED . $form_meta['created_by'] . " " . formulize_formatDateTime($form_meta['created']) . "<br>" . _formulize_FD_MODIFIED . $form_meta['last_update_by'] . " " . formulize_formatDateTime($form_meta['last_update']) . "</p>";
                    } else {
                        $breakHTML .= _formulize_FD_NEWENTRY . "</p>";
                    }
                    $breakHTML .= "</td><td width=50% style=\"vertical-align: bottom;\">";
                    if (strstr($currentURL, "printview.php") or !formulizePermHandler::user_can_edit_entry($fid, $uid, $entry)) {
                        $breakHTML .= "<p>";
                    } else {
                        // get save and button button options
                        $save_button_text = "";
                        $done_button_text = "";
                        if (is_array($button_text)) {
                            $save_button_text = $button_text[1];
                            $done_button_text = $button_text[0];
                        } else {
                            $done_button_text = $button_text;
                        }
                        if (!$done_button_text and !$allDoneOverride) {
                            $done_button_text = _formulize_INFO_DONE1 . _formulize_DONE . _formulize_INFO_DONE2;
                        } elseif ($done_button_text != "{NOBUTTON}" and !$allDoneOverride) {
                            $done_button_text = _formulize_INFO_DONE1 . $done_button_text . _formulize_INFO_DONE2;
                            // check to see if the user is allowed to modify the existing entry, and if they're not, then we have to draw in the all done button so they have a way of getting back where they're going
                        } elseif ($entry and formulizePermHandler::user_can_edit_entry($fid, $uid, $entry) or !$entry) {
                            $done_button_text = "";
                        } else {
                            $done_button_text = _formulize_INFO_DONE1 . _formulize_DONE . _formulize_INFO_DONE2;
                        }
                        $nosave = false;
                        if (!$save_button_text and formulizePermHandler::user_can_edit_entry($fid, $uid, $entry)) {
                            $save_button_text = _formulize_INFO_SAVEBUTTON;
                        } elseif ($save_button_text != "{NOBUTTON}" and formulizePermHandler::user_can_edit_entry($fid, $uid, $entry)) {
                            $save_button_text = _formulize_INFO_SAVE1 . $save_button_text . _formulize_INFO_SAVE2;
                        } else {
                            $save_button_text = _formulize_INFO_NOSAVE;
                            $nosave = true;
                        }
                        $breakHTML .= "<p class='no-print'>" . $save_button_text;
                        if ($done_button_text) {
                            $breakHTML .= "<br>" . $done_button_text;
                        }
                    }
                    $breakHTML .= "</p></td></tr></table>";
                    $form->insertBreak($breakHTML, "even");
                } elseif ($profileForm) {
                    // if we have a profile form, put the profile fields at the top of the form, populated based on the DB values from the _users table
                    $form = addProfileFields($form, $profileForm);
                }
            }
            if ($titleOverride == "1" and !$firstform) {
                // set onetooneTitle flag to 1 when function invoked to force drawing of the form title over again
                $title = trans(getFormTitle($this_fid));
                $form->insertBreak("<table><th>{$title}</th></table>", "");
            }
            // if this form has a parent, then determine the $parentLinks
            if ($go_back['form'] and !$parentLinks[$this_fid]) {
                $parentLinks[$this_fid] = getParentLinks($this_fid, $frid);
            }
            formulize_benchmark("Before Compile Elements.");
            $form = compileElements($this_fid, $form, $formulize_mgr, $prevEntry, $entries[$this_fid][0], $go_back, $parentLinks[$this_fid], $owner_groups, $groups, $overrideValue, $elements_allowed, $profileForm, $frid, $mid, $sub_entries, $sub_fids, $member_handler, $gperm_handler, $title, $screen, $printViewPages, $printViewPageTitles);
            formulize_benchmark("After Compile Elements.");
        }
        // end of for each fids
        if (!is_object($form)) {
            exit("Error: the form cannot be displayed.  Does the current group have permission to access the form?");
        }
        // DRAW IN THE SPECIAL UI FOR A SUBFORM LINK (ONE TO MANY)
        if (count($sub_fids) > 0) {
            // if there are subforms, then draw them in...only once we have a bonafide entry in place already
            // draw in special params for this form, but only once per page
            global $formulize_subformHiddenFieldsDrawn;
            if ($formulize_subformHiddenFieldsDrawn != true) {
                $formulize_subformHiddenFieldsDrawn = true;
                $form->addElement(new XoopsFormHidden('target_sub', ''));
                $form->addElement(new XoopsFormHidden('target_sub_instance', ''));
                $form->addElement(new XoopsFormHidden('numsubents', 1));
                $form->addElement(new XoopsFormHidden('del_subs', ''));
                $form->addElement(new XoopsFormHidden('goto_sub', ''));
                $form->addElement(new XoopsFormHidden('goto_sfid', ''));
            }
            foreach ($sub_fids as $subform_id) {
                // only draw in the subform UI if the subform hasn't been drawn in previously, courtesy of a subform element in the form.
                // Subform elements are recommended since they provide 1. specific placement, 2. custom captions, 3. direct choice of form elements to include
                if (in_array($subform_id, $sfidsDrawn) or $elements_allowed or !($scheck = security_check($subform_id, "", $uid, $owner, $groups, $mid, $gperm_handler)) and !$viewallforms) {
                    // no entry passed so this will simply check whether they have permission for the form or not
                    continue;
                }
                $subUICols = drawSubLinks($subform_id, $sub_entries, $uid, $groups, $frid, $mid, $fid, $entry);
                unset($subLinkUI);
                if (isset($subUICols['single'])) {
                    $form->insertBreak($subUICols['single'], "even");
                } else {
                    $subLinkUI = new XoopsFormLabel($subUICols['c1'], $subUICols['c2']);
                    $form->addElement($subLinkUI);
                }
            }
        }
        // draw in proxy box if necessary (only if they have permission and only on new entries, not on edits)
        if (!strstr($_SERVER['PHP_SELF'], "formulize/printview.php")) {
            if ($gperm_handler->checkRight("add_proxy_entries", $fid, $groups, $mid) and !$entries[$fid][0]) {
                $form = addOwnershipList($form, $groups, $member_handler, $gperm_handler, $fid, $mid);
            } elseif ($entries[$fid][0] and $gperm_handler->checkRight("update_entry_ownership", $fid, $groups, $mid)) {
                $form = addOwnershipList($form, $groups, $member_handler, $gperm_handler, $fid, $mid, $entries[$fid][0]);
            }
        }
        // draw in the submitbutton if necessary
        if (!$formElementsOnly and formulizePermHandler::user_can_edit_entry($fid, $uid, $entry)) {
            $form = addSubmitButton($form, _formulize_SAVE, $go_back, $currentURL, $button_text, $settings, $temp_entries[$this_fid][0], $fids, $formframe, $mainform, $entry, $profileForm, $elements_allowed, $allDoneOverride, $printall, $screen);
        }
        if (!$formElementsOnly) {
            // add flag to indicate that the form has been submitted
            $form->addElement(new XoopsFormHidden('form_submitted', "1"));
            if ($go_back['form']) {
                // if this is set, then we're doing a subform, so put in a flag to prevent the parent from being drawn again on submission
                $form->addElement(new XoopsFormHidden('sub_fid', $fid));
                $form->addElement(new XoopsFormHidden('sub_submitted', $entries[$fid][0]));
                $form->addElement(new XoopsFormHidden('go_back_form', $go_back['form']));
                $form->addElement(new XoopsFormHidden('go_back_entry', $go_back['entry']));
            } else {
                // drawing a main form...put in the scroll position flag
                $form->addElement(new XoopsFormHidden('yposition', 0));
            }
            // saving message
            print "<div id=savingmessage style=\"display: none; position: absolute; width: 100%; right: 0px; text-align: center; padding-top: 50px;\">\n";
            global $xoopsConfig;
            if (file_exists(XOOPS_ROOT_PATH . "/modules/formulize/images/saving-" . $xoopsConfig['language'] . ".gif")) {
                print "<img src=\"" . XOOPS_URL . "/modules/formulize/images/saving-" . $xoopsConfig['language'] . ".gif\">\n";
            } else {
                print "<img src=\"" . XOOPS_URL . "/modules/formulize/images/saving-english.gif\">\n";
            }
            print "</div>\n";
            drawJavascript($nosave);
            if (count($GLOBALS['formulize_renderedElementHasConditions']) > 0) {
                drawJavascriptForConditionalElements($GLOBALS['formulize_renderedElementHasConditions'], $entries, $sub_entries);
            }
            print $form->addElement(new xoopsFormHidden('save_and_leave', 0));
            // lastly, put in a hidden element, that will tell us what the first, primary form was that we were working with on this form submission
            $form->addElement(new XoopsFormHidden('primaryfid', $fids[0]));
        }
        global $formulize_governingElements;
        global $formulize_oneToOneElements;
        global $formulize_oneToOneMetaData;
        if (!is_array($formulize_governingElements)) {
            $formulize_governingElements = array();
        }
        if (!is_array($formulize_oneToOneElements)) {
            $oneToOneElements = array();
        }
        if (!is_array($oneToOneMetaData)) {
            $oneToOneMetaData = array();
        }
        if (count($GLOBALS['formulize_renderedElementHasConditions']) > 0) {
            $governingElements1 = compileGoverningElementsForConditionalElements($GLOBALS['formulize_renderedElementHasConditions'], $entries, $sub_entries);
            foreach ($governingElements1 as $key => $value) {
                $oneToOneElements[$key] = false;
            }
            $formulize_governingElements = mergeGoverningElements($formulize_governingElements, $governingElements1);
        }
        // add in any onetoone elements that we need to deal with at the same time (in case their joining key value changes on the fly)
        if (count($fids) > 1) {
            $i = 1;
            while ($i <= count($fids)) {
                $relationship_handler = xoops_getmodulehandler('frameworks', 'formulize');
                $relationship = $relationship_handler->get($frid);
                foreach ($relationship->getVar('links') as $thisLink) {
                    if ($thisLink->getVar('form1') == $fids[$i]) {
                        $keyElement = $thisLink->getVar('key2');
                        break;
                    } elseif ($thisLink->getVar('form2') == $fids[$i]) {
                        $keyElement = $thisLink->getVar('key1');
                        break;
                    }
                }
                // prepare to loop through elements for the rendered entry, or 'new', if there is no rendered entry
                $entryToLoop = isset($entries[$fids[$i]][0]) ? $entries[$fids[$i]][0] : null;
                if (!$entryToLoop and isset($GLOBALS['formulize_renderedElementsForForm'][$fids[$i]]['new'])) {
                    $entryToLoop = 'new';
                }
                foreach ($GLOBALS['formulize_renderedElementsForForm'][$fids[$i]][$entryToLoop] as $renderedMarkupName => $thisElement) {
                    $GLOBALS['formulize_renderedElementHasConditions'][$renderedMarkupName] = $thisElement;
                    $governingElements2 = _compileGoverningElements($entries, _getElementObject($keyElement), $renderedMarkupName);
                    foreach ($governingElements2 as $key => $value) {
                        $formulize_oneToOneElements[$key] = true;
                        $formulize_oneToOneMetaData[$key] = array('onetoonefrid' => $frid, 'onetoonefid' => $fid, 'onetooneentries' => urlencode(serialize($entries)), 'onetoonefids' => urlencode(serialize($fids)));
                    }
                    $formulize_governingElements = mergeGoverningElements($formulize_governingElements, $governingElements2);
                }
                $i++;
            }
        }
        if (count($formulize_governingElements) > 0 and !$formElementsOnly) {
            // render this once at the end of rendering the main form!
            drawJavascriptForConditionalElements($GLOBALS['formulize_renderedElementHasConditions'], $formulize_governingElements, $formulize_oneToOneElements, $formulize_oneToOneMetaData);
        }
        $idForForm = $formElementsOnly ? "" : "id=\"formulizeform\"";
        // when rendering disembodied forms, don't use the master id!
        print "<div {$idForForm}>" . $form->render() . "</div><!-- end of formulizeform -->";
        // note, security token is included in the form by the xoops themeform render method, that's why there's no explicity references to the token in the compiling/generation of the main form object
        // floating save button
        if ($printall != 2 and $formulizeConfig['floatSave'] and !strstr($currentURL, "printview.php") and !$formElementsOnly) {
            print "<div id=floattest></div>";
            if ($done_text != "{NOBUTTON}" or $save_text != "{NOBUTTON}") {
                print "<div id=floatingsave>";
                if ($subButtonText == _formulize_SAVE) {
                    if ($save_text) {
                        $subButtonText = $save_text;
                    }
                    if ($subButtonText != "{NOBUTTON}") {
                        print "<input type='button' name='submitx' id='submitx' class=floatingsavebuttons onclick=javascript:validateAndSubmit(); value='" . _formulize_SAVE . "' >";
                        print "<input type='button' name='submit_save_and_leave' id='submit_save_and_leave' class=floatingsavebuttons onclick=javascript:validateAndSubmit('leave'); value='" . _formulize_SAVE_AND_LEAVE . "' >";
                    }
                }
                if (($button_text != "{NOBUTTON}" and !$done_text or isset($done_text) and $done_text != "{NOBUTTON}") and !$allDoneOverride) {
                    if ($done_text) {
                        $button_text = $done_text_temp;
                    }
                    print "<input type='button' class=floatingsavebuttons onclick=javascript:verifyDone(); value='" . _formulize_DONE . "' >";
                }
                print "</div>";
            }
        }
        // end floating save button
        // if we're in Drupal, include the main XOOPS js file, so the calendar will work if present...
        // assumption is that the calendar javascript has already been included by the datebox due to no
        // $xoopsTpl being in effect in Drupal -- this assumption will fail if Drupal is displaying a pageworks
        // page that uses the $xoopsTpl, for instance.  (Date select box file itself checks for $xoopsTpl)
        global $user;
        static $includedXoopsJs = false;
        if (is_object($user) and !$includedXoopsJs) {
            print "<script type=\"text/javascript\" src=\"" . XOOPS_URL . "/include/xoops.js\"></script>\n";
            $includedXoopsJs = true;
        }
    }
    // end of if we're not going back to the prev page because of an all done button override
}
function displayFormPages($formframe, $entry = "", $mainform = "", $pages, $conditions = "", $introtext = "", $thankstext = "", $done_dest = "", $button_text = "", $settings = "", $overrideValue = "", $printall = 0, $screen = null, $saveAndContinueButtonText = null)
{
    // nmc 2007.03.24 - added 'printall'
    formulize_benchmark("Start of displayFormPages.");
    // extract the optional page titles from the $pages array for use in the jump to box
    // NOTE: pageTitles array must start with key 1, not 0.  Page 1 is the first page of the form
    $pageTitles = array();
    if (isset($pages['titles'])) {
        $pageTitles = $pages['titles'];
        unset($pages['titles']);
    }
    if (!$saveAndContinueButtonText and isset($_POST['formulize_saveAndContinueButtonText'])) {
        $saveAndContinueButtonText = unserialize($_POST['formulize_saveAndContinueButtonText']);
    }
    if (!$done_dest and $_POST['formulize_doneDest']) {
        $done_dest = $_POST['formulize_doneDest'];
    }
    if (!$button_text and $_POST['formulize_buttonText']) {
        $button_text = $_POST['formulize_buttonText'];
    }
    list($fid, $frid) = getFormFramework($formframe, $mainform);
    $thankstext = $thankstext ? $thankstext : _formulize_DMULTI_THANKS;
    $introtext = $introtext ? $introtext : "";
    global $xoopsUser;
    $mid = getFormulizeModId();
    $groups = $xoopsUser ? $xoopsUser->getGroups() : array(0 => XOOPS_GROUP_ANONYMOUS);
    $uid = $xoopsUser ? $xoopsUser->getVar('uid') : 0;
    $gperm_handler =& xoops_gethandler('groupperm');
    $member_handler =& xoops_gethandler('member');
    $single_result = getSingle($fid, $uid, $groups, $member_handler, $gperm_handler, $mid);
    // if this function was called without an entry specified, then assume the identity of the entry we're editing (unless this is a new save, in which case no entry has been made yet)
    // no handling of cookies here, so anonymous multi-page surveys will not benefit from that feature
    // this emphasizes how we need to standardize a lot of these interfaces with a real class system
    if (!$entry and $_POST['entry' . $fid]) {
        $entry = $_POST['entry' . $fid];
    } elseif (!$entry) {
        // or check getSingle to see what the real entry is
        $entry = $single_result['flag'] ? $single_result['entry'] : 0;
    }
    // formulize_newEntryIds is set when saving data
    if (!$entry and isset($GLOBALS['formulize_newEntryIds'][$fid])) {
        $entry = $GLOBALS['formulize_newEntryIds'][$fid][0];
    }
    $owner = getEntryOwner($entry, $fid);
    $prevPage = isset($_POST['formulize_prevPage']) ? $_POST['formulize_prevPage'] : 1;
    // last page that the user was on, not necessarily the previous page numerically
    $currentPage = isset($_POST['formulize_currentPage']) ? $_POST['formulize_currentPage'] : 1;
    $thanksPage = count($pages) + 1;
    // debug control:
    $currentPage = (isset($_GET['debugpage']) and is_numeric($_GET['debugpage'])) ? $_GET['debugpage'] : $currentPage;
    $usersCanSave = formulizePermHandler::user_can_edit_entry($fid, $uid, $entry);
    if ($pages[$prevPage][0] !== "HTML" and $pages[$prevPage][0] !== "PHP") {
        // remember prevPage is the last page the user was on, not the previous page numerically
        if (isset($_POST['form_submitted']) and $usersCanSave) {
            include_once XOOPS_ROOT_PATH . "/modules/formulize/include/formread.php";
            include_once XOOPS_ROOT_PATH . "/modules/formulize/include/functions.php";
            include_once XOOPS_ROOT_PATH . "/modules/formulize/class/data.php";
            //$owner_groups =& $member_handler->getGroupsByUser($owner, FALSE);
            $data_handler = new formulizeDataHandler($fid);
            $owner_groups = $data_handler->getEntryOwnerGroups($entry);
            $entries[$fid][0] = $entry;
            if ($frid) {
                $linkResults = checkForLinks($frid, array(0 => $fid), $fid, $entries, $gperm_handler, $owner_groups, $mid, $member_handler, $owner);
                unset($entries);
                $entries = $linkResults['entries'];
            }
            $entries = $GLOBALS['formulize_allWrittenEntryIds'];
            // set in readelements.php
            // if there has been no specific entry specified yet, then assume the identity of the entry that was just saved -- assumption is it will be a new save
            // from this point forward in time, this is the only entry that should be involved, since the 'entry'.$fid condition above will put this value into $entry even if this function was called with a blank entry value
            if (!$entry) {
                $entry = $entries[$fid][0];
            }
            synchSubformBlankDefaults($fid, $entry);
        }
    }
    // there are several points above where $entry is set, and now that we have a final value, store in ventry
    if ($entry > 0) {
        $settings['ventry'] = $entry;
    }
    // check to see if there are conditions on this page, and if so are they met
    // if the conditions are not met, move on to the next page and repeat the condition check
    // conditions only checked once there is an entry!
    $pagesSkipped = false;
    if (is_array($conditions) and $entry) {
        $conditionsMet = false;
        while (!$conditionsMet) {
            if (isset($conditions[$currentPage]) and count($conditions[$currentPage][0]) > 0) {
                // conditions on the current page
                $thesecons = $conditions[$currentPage];
                $elements = $thesecons[0];
                $ops = $thesecons[1];
                $terms = $thesecons[2];
                $types = $thesecons[3];
                // indicates if the term is part of a must or may set, ie: boolean and or or
                $filter = "";
                $oomfilter = "";
                $blankORSearch = "";
                foreach ($elements as $i => $thisElement) {
                    if ($ops[$i] == "NOT") {
                        $ops[$i] = "!=";
                    }
                    if ($terms[$i] == "{BLANK}") {
                        // NOTE...USE OF BLANKS WON'T WORK CLEANLY IN ALL CASES DEPENDING WHAT OTHER TERMS HAVE BEEN SPECIFIED!!
                        if ($ops[$i] == "!=" or $ops[$i] == "NOT LIKE") {
                            if ($types[$i] != "oom") {
                                // add to the main filter, ie: entry id = 1 AND x=5 AND y IS NOT "" AND y IS NOT NULL
                                if (!$filter) {
                                    $filter = $entry . "][" . $elements[$i] . "/**//**/!=][" . $elements[$i] . "/**//**/IS NOT NULL";
                                } else {
                                    $filter .= "][" . $elements[$i] . "/**//**/!=][" . $elements[$i] . "/**//**/IS NOT NULL";
                                }
                            } else {
                                // Add to the OOM filter, ie: entry id = 1 AND (x=5 OR y IS NOT "" OR y IS NOT NULL)
                                if (!$oomfilter) {
                                    $oomfilter = $elements[$i] . "/**//**/=][" . $elements[$i] . "/**//**/IS NULL";
                                } else {
                                    $oomfilter .= "][" . $elements[$i] . "/**//**/=][" . $elements[$i] . "/**//**/IS NULL";
                                }
                            }
                        } else {
                            if ($types[$i] != "oom") {
                                // add to its own OR filter, since we MUST match this condition, but we don't care if it's "" OR NULL
                                // ie: entry id = 1 AND (x=5 OR y=10) AND (z = "" OR z IS NULL)
                                if (!$blankORSearch) {
                                    $blankORSearch = $elements[$i] . "/**//**/=][" . $elements[$i] . "/**//**/IS NULL";
                                } else {
                                    $blankORSearch .= "][" . $elements[$i] . "/**//**/=][" . $elements[$i] . "/**//**/IS NULL";
                                }
                            } else {
                                // it's part of the oom filters anyway, so we put it there, because we don't care if it's null or "" or neither
                                if (!$oomfilter) {
                                    $oomfilter = $elements[$i] . "/**//**/=][" . $elements[$i] . "/**//**/IS NULL";
                                } else {
                                    $oomfilter .= "][" . $elements[$i] . "/**//**/=][" . $elements[$i] . "/**//**/IS NULL";
                                }
                            }
                        }
                    } elseif ($types[$i] == "oom") {
                        if (!$oomfilter) {
                            $oomfilter = $elements[$i] . "/**/" . trans($terms[$i]) . "/**/" . $ops[$i];
                        } else {
                            $oomfilter .= "][" . $elements[$i] . "/**/" . trans($terms[$i]) . "/**/" . $ops[$i];
                        }
                    } else {
                        if (!$filter) {
                            $filter = $entry . "][" . $elements[$i] . "/**/" . trans($terms[$i]) . "/**/" . $ops[$i];
                        } else {
                            $filter .= "][" . $elements[$i] . "/**/" . trans($terms[$i]) . "/**/" . $ops[$i];
                        }
                    }
                }
                if ($oomfilter and $filter) {
                    $finalFilter = array();
                    $finalFilter[0][0] = "AND";
                    $finalFilter[0][1] = $filter;
                    $finalFilter[1][0] = "OR";
                    $finalFilter[1][1] = $oomfilter;
                    if ($blankORSearch) {
                        $finalFilter[2][0] = "OR";
                        $finalFilter[2][1] = $blankORSearch;
                    }
                } elseif ($oomfilter) {
                    // need to add the $entry as a separate filter from the oom, so the entry and oom get an AND in between them
                    $finalFilter = array();
                    $finalFilter[0][0] = "AND";
                    $finalFilter[0][1] = $entry;
                    $finalFilter[1][0] = "OR";
                    $finalFilter[1][1] = $oomfilter;
                    if ($blankORSearch) {
                        $finalFilter[2][0] = "OR";
                        $finalFilter[2][1] = $blankORSearch;
                    }
                } else {
                    if ($blankORSearch) {
                        $finalFilter[0][0] = "AND";
                        $finalFilter[0][1] = $filter ? $filter : $entry;
                        $finalFilter[1][0] = "OR";
                        $finalFilter[1][1] = $blankORSearch;
                    } else {
                        $finalFilter = $filter;
                    }
                }
                $masterBoolean = "AND";
                include_once XOOPS_ROOT_PATH . "/modules/formulize/include/extract.php";
                $data = getData($frid, $fid, $finalFilter, $masterBoolean, "", "", "", "", "", false, 0, false, "", false, true);
                if (!$data) {
                    if ($prevPage <= $currentPage) {
                        $currentPage++;
                    } else {
                        $currentPage--;
                    }
                    $pagesSkipped = true;
                } else {
                    $conditionsMet = true;
                }
            } else {
                // no conditions on the current page
                $conditionsMet = true;
            }
        }
    }
    if ($currentPage > 1) {
        $previousPage = $currentPage - 1;
        // previous page numerically
    } else {
        $previousPage = "none";
    }
    $nextPage = $currentPage + 1;
    $done_dest = $done_dest ? $done_dest : getCurrentURL();
    $done_dest = substr($done_dest, 0, 4) == "http" ? $done_dest : "http://" . $done_dest;
    // Set up the javascript that we need for the form-submit functionality to work
    // note that validateAndSubmit calls the form validation function again, but obviously it will pass if it passed here.  The validation needs to be called prior to setting the pages, or else you can end up on the wrong page after clicking an ADD button in a subform when you've missed a required field.
    // savedPage and savedPrevPage are used to pick up the page and prevpage only when a two step validation, such as checking for uniqueness, returns and calls validateAndSubmit again
    ?>
	
	<script type='text/javascript'>
	var savedPage;
	var savedPrevPage;
	function submitForm(page, prevpage) {
		var validate = xoopsFormValidate_formulize();
		if(validate) {
			savedPage = 0;
			savedPrevPage = 0;
			multipageSetHiddenFields(page, prevpage);
			if (formulizechanged) {
        validateAndSubmit();
      } else {
        jQuery("#formulizeform").animate({opacity:0.4}, 200, "linear");
        jQuery("input[name^='decue_']").remove();
        // 'rewritePage' will trigger the page to change after the locks have been removed
        removeEntryLocks('rewritePage');
      }
    } else {
			savedPage = page;
			savedPrevPage = prevpage;
		}
  }

	function multipageSetHiddenFields(page, prevpage) {
		<?php 
    // neuter the ventry which is the key thing that keeps us on the form page,
    //  if in fact we just came from a list screen of some kind.
    // need to use an unusual selector, because something about selecting by id wasn't working,
    //  apparently may be related to setting actions on forms with certain versions of jQuery?
    print "\r\n\t\t\tif(page == {$thanksPage}) {\r\n\t\t\t\twindow.document.formulize.ventry.value = '';\r\n\t\t\t\tjQuery('form[name=formulize]').attr('action', '{$done_dest}');\r\n      }\r\n";
    ?>
      window.document.formulize.formulize_currentPage.value = page;
      window.document.formulize.formulize_prevPage.value = prevpage;
      window.document.formulize.formulize_doneDest.value = '<?php 
    print $done_dest;
    ?>
';
      window.document.formulize.formulize_buttonText.value = '<?php 
    print $button_text;
    ?>
';
	}

	function pageJump(options, prevpage) {
		for (var i=0; i < options.length; i++) {
			if (options[i].selected) {
				submitForm(options[i].value, prevpage);
				return false;
			}
		}
	}
	
	</script><noscript>
	<h1>You do not have javascript enabled in your web browser.  This form will not work with your web browser.  Please contact the webmaster for assistance.</h1>
	</noscript>
	<?php 
    if ($currentPage == $thanksPage) {
        if ($screen and $screen->getVar('finishisdone')) {
            print "<script type='text/javascript'>location = '{$done_dest}';</script>";
            return;
            // if we've ended up on the thanks page via conditions (last page was not shown) then we should just bail if there is not supposed to be a thanks page
        }
        if (is_array($thankstext)) {
            if ($thankstext[0] === "PHP") {
                eval($thankstext[1]);
            } else {
                print $thankstext[1];
            }
        } else {
            // HTML
            print html_entity_decode($thankstext);
        }
        print "<br><hr><br><div id=\"thankYouNavigation\"><p><center>\n";
        if ($pagesSkipped) {
            print _formulize_DMULTI_SKIP . "</p><p>\n";
        }
        $button_text = $button_text ? $button_text : _formulize_DMULTI_ALLDONE;
        if ($button_text != "{NOBUTTON}") {
            print "<a href='{$done_dest}'";
            if (is_array($settings)) {
                print " onclick=\"javascript:window.document.calreturnform.submit();return false;\"";
            }
            print ">" . $button_text . "</a>\n";
        }
        print "</center></p></div>";
        if (is_array($settings)) {
            print "<form name=calreturnform action=\"{$done_dest}\" method=post>\n";
            writeHiddenSettings($settings);
            print "</form>";
        }
    }
    if ($currentPage == 1 and $pages[1][0] !== "HTML" and $pages[1][0] !== "PHP" and !$_POST['goto_sfid']) {
        // only show intro text on first page if there's actually a form there
        print html_entity_decode(html_entity_decode($introtext));
    }
    unset($_POST['form_submitted']);
    // display an HTML or PHP page if that's what this page is...
    if ($currentPage != $thanksPage and ($pages[$currentPage][0] === "HTML" or $pages[$currentPage][0] === "PHP")) {
        // PHP
        if ($pages[$currentPage][0] === "PHP") {
            eval($pages[$currentPage][1]);
            // HTML
        } else {
            print $pages[$currentPage][1];
        }
        // put in the form that passes the entry, page we're going to and page we were on
        include_once XOOPS_ROOT_PATH . "/modules/formulize/include/functions.php";
        ?>
	
		
		<form name=formulize id=formulize action=<?php 
        print getCurrentURL();
        ?>
 method=post>
		<input type=hidden name=entry<?php 
        print $fid;
        ?>
 id=entry<?php 
        print $fid;
        ?>
 value=<?php 
        print $entry;
        ?>
>
		<input type=hidden name=formulize_currentPage id=formulize_currentPage value="">
		<input type=hidden name=formulize_prevPage id=formulize_prevPage value="">
		writeHiddenSettings($settings);
		</form>
	
		<script type="text/javascript">
			function validateAndSubmit() {
				window.document.formulize.submit();
			}
		</script>
	
		<?php 
    }
    // display a form if that's what this page is...
    if ($currentPage != $thanksPage and $pages[$currentPage][0] !== "HTML" and $pages[$currentPage][0] !== "PHP") {
        $buttonArray = array(0 => "{NOBUTTON}", 1 => "{NOBUTTON}");
        foreach ($pages[$currentPage] as $element) {
            $elements_allowed[] = $element;
        }
        $forminfo['elements'] = $elements_allowed;
        $forminfo['formframe'] = $formframe;
        $titleOverride = isset($pageTitles[$currentPage]) ? trans($pageTitles[$currentPage]) : "all";
        // we can pass in any text value as the titleOverride, and it will have the same effect as "all", but the alternate text will be used as the title for the form
        $GLOBALS['nosubforms'] = true;
        // subforms cannot have a view button on multipage forms, since moving to a sub causes total confusion of which entry and fid you are looking at
        $settings['formulize_currentPage'] = $currentPage;
        $settings['formulize_prevPage'] = $currentPage;
        // now that we're done everything else, we can send the current page as the previous page when initializing the form.  Javascript will set the true value prior to submission.
        formulize_benchmark("Before drawing nav.");
        $previousButtonText = (is_array($saveAndContinueButtonText) and isset($saveAndContinueButtonText['previousButtonText'])) ? $saveAndContinueButtonText['previousButtonText'] : _formulize_DMULTI_PREV;
        if ($usersCanSave and $nextPage == $thanksPage) {
            $nextButtonText = (is_array($saveAndContinueButtonText) and $saveAndContinueButtonText['saveButtonText']) ? $saveAndContinueButtonText['saveButtonText'] : _formulize_DMULTI_SAVE;
        } else {
            $nextButtonText = (is_array($saveAndContinueButtonText) and $saveAndContinueButtonText['nextButtonText']) ? $saveAndContinueButtonText['nextButtonText'] : _formulize_DMULTI_NEXT;
        }
        $previousPageButton = generatePrevNextButtonMarkup("prev", $previousButtonText, $usersCanSave, $nextPage, $previousPage, $thanksPage);
        $nextPageButton = generatePrevNextButtonMarkup("next", $nextButtonText, $usersCanSave, $nextPage, $previousPage, $thanksPage);
        $savePageButton = generatePrevNextButtonMarkup("save", _formulize_SAVE, $usersCanSave, $nextPage, $previousPage, $thanksPage);
        $totalPages = count($pages);
        $skippedPageMessage = $pagesSkipped ? _formulize_DMULTI_SKIP : "";
        $pageSelectionList = pageSelectionList($currentPage, $totalPages, $pageTitles, "above");
        // calling for the 'above' drawPageNav
        // setting up the basic templateVars for all templates
        $templateVariables = array('previousPageButton' => $previousPageButton, 'nextPageButton' => $nextPageButton, 'savePageButton' => $savePageButton, 'totalPages' => $totalPages, 'currentPage' => $currentPage, 'skippedPageMessage' => $skippedPageMessage, 'pageSelectionList' => $pageSelectionList, 'pageTitles' => $pageTitles, 'entry_id' => $entry, 'form_id' => $fid, 'owner' => $owner);
        print "<form name=\"pageNavOptions_above\" id=\"pageNavOptions_above\">\n";
        if ($screen and $toptemplate = $screen->getTemplate('toptemplate')) {
            formulize_renderTemplate('toptemplate', $templateVariables, $screen->getVar('sid'));
        } else {
            drawPageNav($usersCanSave, $currentPage, $totalPages, "above", $nextPageButton, $previousPageButton, $skippedPageMessage, $pageSelectionList);
        }
        print "</form>";
        formulize_benchmark("After drawing nav/before displayForm.");
        // need to check for the existence of an elementtemplate property in the screen, like we did with the top and bottom templates
        // if there's an eleemnt template, then do this loop, otherwise, do the displayForm call like normal
        if ($screen and $elementtemplate = $screen->getTemplate('elementtemplate')) {
            // Code added by Julian 2012-09-04 and Gordon Woodmansey 2012-09-05 to render the elementtemplate
            if (!security_check($fid, $entry)) {
                exit;
            }
            // start the form manually...
            $formObjectForRequiredJS = new formulize_themeForm('form object for required js', 'formulize', getCurrentURL(), "post", true);
            $element_handler = xoops_getmodulehandler('elements', 'formulize');
            print "<div id='formulizeform'><form id='formulize' name='formulize' action='" . getCurrentURL() . "' method='post' onsubmit='return xoopsFormValidate_formulize();' enctype='multipart/form-data'>";
            foreach ($elements_allowed as $thisElement) {
                // entry is a recordid, $thisElement is the element id
                // to get the conditional logic to be captured, we should buffer the drawing of the displayElement, and then output that later, because when displayElement does NOT return an object, then we get conditional logic -- subform rendering does it this way
                unset($form_ele);
                // previously set elements may linger when added to the form object, due to assignment of objects by reference or something odd like that...legacy of old code in the form class I think
                $deReturnValue = displayElement("", $thisElement, $entry, false, $screen, null, false);
                if (is_array($deReturnValue)) {
                    $form_ele = $deReturnValue[0];
                    $isDisabled = $deReturnValue[1];
                    if (isset($deReturnValue[2])) {
                        $hiddenElements = $deReturnValue[2];
                    }
                } else {
                    $form_ele = $deReturnValue;
                    $isDisabled = false;
                }
                if ($form_ele == "not_allowed") {
                    continue;
                } elseif ($form_ele == "hidden") {
                    $cueEntryValue = $entry ? $entry : "new";
                    $cueElement = new xoopsFormHidden("decue_" . $fid . "_" . $cueEntryValue . "_" . $thisElement, 1);
                    print $cueElement->render();
                    if (is_array($hiddenElements)) {
                        foreach ($hiddenElements as $thisHiddenElement) {
                            if ($is_object($thisHiddenElement)) {
                                print $thisHiddenElement->render() . "\n";
                            }
                        }
                    } elseif (is_object($hiddenElements)) {
                        print $hiddenElements->render() . "\n";
                    }
                    continue;
                } else {
                    $thisElementObject = $element_handler->get($thisElement);
                    $req = !$isDisabled ? intval($thisElementObject->getVar('ele_req')) : 0;
                    $formObjectForRequiredJS->addElement($form_ele, $req);
                    $elementMarkup = $form_ele->render();
                    $elementCaption = displayCaption("", $thisElement);
                    $elementDescription = displayDescription("", $thisElement);
                    $templateVariables['elementObjectForRendering'] = $form_ele;
                    $templateVariables['elementCaption'] = $elementCaption;
                    // here we can assume that the $previousPageButton etc has not be changed before rendering
                    $templateVariables['elementMarkup'] = $elementMarkup;
                    $templateVariables['elementDescription'] = $elementDescription;
                    $templateVariables['element_id'] = $thisElement;
                    formulize_renderTemplate('elementtemplate', $templateVariables, $screen->getVar('sid'));
                }
            }
            // now we also need to add in some bits that are necessary for the form submission logic to work...borrowed from parts of formdisplay.php mostly...this should be put together into a more distinct rendering system for forms, so we can call the pieces as needed
            print "<input type=hidden name=formulize_currentPage value='" . $settings['formulize_currentPage'] . "'>";
            print "<input type=hidden name=formulize_prevPage value='" . $settings['formulize_prevPage'] . "'>";
            print "<input type=hidden name=formulize_doneDest value='" . $settings['formulize_doneDest'] . "'>";
            print "<input type=hidden name=formulize_buttonText value='" . $settings['formulize_buttonText'] . "'>";
            print "<input type=hidden name=ventry value='" . $settings['ventry'] . "'>";
            print $GLOBALS['xoopsSecurity']->getTokenHTML();
            if ($entry) {
                print "<input type=hidden name=entry" . $fid . " value=" . intval($entry) . ">";
                // need this to persist the entry that the user is
            }
            print "</form></div>";
            print "<div id=savingmessage style=\"display: none; position: absolute; width: 100%; right: 0px; text-align: center; padding-top: 50px;\">\n";
            if (file_exists(XOOPS_ROOT_PATH . "/modules/formulize/images/saving-" . $xoopsConfig['language'] . ".gif")) {
                print "<img src=\"" . XOOPS_URL . "/modules/formulize/images/saving-" . $xoopsConfig['language'] . ".gif\">\n";
            } else {
                print "<img src=\"" . XOOPS_URL . "/modules/formulize/images/saving-english.gif\">\n";
            }
            print "</div>\n";
            drawJavascript();
            // need to create the form object, and add all the rendered elements to it, and then we'll have working required elements if we render the validation logic for the form
            print $formObjectForRequiredJS->renderValidationJS(true, true);
            // with tags, true, skip the extra js that checks for the formulize theme form divs around the elements so that conditional animation works, true
            // print "<script type=\"text/javascript\">function xoopsFormValidate_formulize(){return true;}</script>"; // shim for the validation javascript that is created by the xoopsThemeForms, and which our saving logic currently references...saving won't work without this...we should actually render the proper validation logic at some point, but not today.
        } else {
            displayForm($forminfo, $entry, $mainform, "", $buttonArray, $settings, $titleOverride, $overrideValue, "", "", 0, 0, $printall, $screen);
            // nmc 2007.03.24 - added empty params & '$printall'
        }
        formulize_benchmark("After displayForm.");
    }
    if ($currentPage != $thanksPage and !$_POST['goto_sfid']) {
        // have to get the new value for $pageSelection list if the user requires it on the users view.
        $pageSelectionList = pageSelectionList($currentPage, $totalPages, $pageTitles, "below");
        print "<form name=\"pageNavOptions_below\" id=\"pageNavOptions_below\">\n";
        if ($screen and $bottomtemplate = $screen->getTemplate('bottomtemplate')) {
            $templateVariables['pageSelectionList'] = $pageSelectionList;
            // assign the new pageSelectionList, since it was redone for the bottom section
            formulize_renderTemplate('bottomtemplate', $templateVariables, $screen->getVar('sid'));
        } else {
            drawPageNav($usersCanSave, $currentPage, $totalPages, "below", $nextPageButton, $previousPageButton, $skippedPageMessage, $pageSelectionList);
        }
        print "</form>";
    }
    formulize_benchmark("End of displayFormPages.");
}