function render($ele_value, $caption, $markupName, $isDisabled, $element, $entry_id)
 {
     global $xoopsDB, $xoopsUser, $myts;
     $renderer = new formulizeElementRenderer();
     $form_handler = xoops_getmodulehandler('forms', 'formulize');
     $id_form = $element->getVar('id_form');
     if ($entry_id != "new") {
         $owner = getEntryOwner($entry_id, $id_form);
     } else {
         $owner = $xoopsUser ? $xoopsUser->getVar('uid') : 0;
     }
     $formObject = $form_handler->get($id_form);
     $isDisabled = false;
     if (strstr(getCurrentURL(), "printview.php")) {
         $isDisabled = true;
         // disabled all elements if we're on the printable view
     }
     $ele_desc = $element->getVar('ele_desc', "f");
     if (strstr($ele_value[2], "#*=:*")) {
         // if we've got a link on our hands... -- jwe 7/29/04
         // new process for handling links...May 10 2008...new datastructure for formulize 3.0
         $boxproperties = explode("#*=:*", $ele_value[2]);
         $sourceFid = $boxproperties[0];
         $sourceHandle = $boxproperties[1];
         $sourceEntryIds = explode(",", trim($boxproperties[2], ","));
         // grab the user's groups and the module id
         global $regcode;
         if ($regcode) {
             // if we're dealing with a registration code, determine group membership based on the code
             $reggroupsq = q("SELECT reg_codes_groups FROM " . XOOPS_DB_PREFIX . "_reg_codes WHERE reg_codes_code=\"{$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;
         } else {
             $groups = $xoopsUser ? $xoopsUser->getGroups() : array(0 => XOOPS_GROUP_ANONYMOUS);
         }
         $module_id = getFormulizeModId();
         $pgroups = array();
         // handle new linkscope option -- August 30 2006
         $emptylist = false;
         if ($ele_value[3]) {
             $scopegroups = explode(",", $ele_value[3]);
             if (!in_array("all", $scopegroups)) {
                 if ($ele_value[4]) {
                     // limit by user's groups
                     foreach ($groups as $gid) {
                         // want to loop so we can get rid of reg users group simply
                         if ($gid == XOOPS_GROUP_USERS) {
                             continue;
                         }
                         if (in_array($gid, $scopegroups)) {
                             $pgroups[] = $gid;
                         }
                     }
                 } else {
                     // just use scopegroups
                     $pgroups = $scopegroups;
                 }
                 if (count($pgroups) == 0) {
                     // specific scope was specified, and nothing found, so we should show nothing
                     $emptylist = true;
                 }
             } else {
                 if ($ele_value[4]) {
                     // all groups selected, but limiting by user's groups is turned on
                     foreach ($groups as $gid) {
                         // want to loop so we can get rid of reg users group simply
                         if ($gid == XOOPS_GROUP_USERS) {
                             continue;
                         }
                         $pgroups[] = $gid;
                     }
                 } else {
                     // all groups should be used
                     unset($pgroups);
                     $allgroupsq = q("SELECT groupid FROM " . $xoopsDB->prefix("groups"));
                     //  . " WHERE groupid != " . XOOPS_GROUP_USERS); // use all groups now, if all groups are picked, with no restrictions on membership or anything, then use all groups
                     foreach ($allgroupsq as $thisgid) {
                         $pgroups[] = $thisgid['groupid'];
                     }
                 }
             }
         }
         // Note: OLD WAY: if no groups were found, then pguidq will be empty and so all entries will be shown, no restrictions
         // NEW WAY: if a specific group(s) was specified, and no match with the current user was found, then we return an empty list
         array_unique($pgroups);
         // remove duplicate groups from the list
         if ($ele_value[6] and count($pgroups) > 0) {
             $pgroupsfilter = " (";
             $start = true;
             foreach ($pgroups as $thisPgroup) {
                 if (!$start) {
                     $pgroupsfilter .= " AND ";
                 }
                 $pgroupsfilter .= "EXISTS(SELECT 1 FROM " . $xoopsDB->prefix("formulize_entry_owner_groups") . " AS t2 WHERE t2.groupid={$thisPgroup} AND t2.fid={$sourceFid} AND t2.entry_id=t1.entry_id)";
                 $start = false;
             }
             $pgroupsfilter .= ")";
         } elseif (count($pgroups) > 0) {
             $pgroupsfilter = " t2.groupid IN (" . formulize_db_escape(implode(",", $pgroups)) . ") AND t2.entry_id=t1.entry_id AND t2.fid={$sourceFid}";
         } else {
             $pgroupsfilter = "";
         }
         $sourceFormObject = $form_handler->get($sourceFid);
         list($conditionsfilter, $conditionsfilter_oom, $parentFormFrom) = buildConditionsFilterSQL($ele_value[5], $sourceFid, $entry_id, $owner, $formObject, "t1");
         // if there is a restriction in effect, then add some SQL to reject options that have already been selected ??
         $restrictSQL = "";
         if ($ele_value[9]) {
             $restrictSQL = " AND (\n\t\t\t\tNOT EXISTS (\n\t\t\t\tSELECT 1 FROM " . $xoopsDB->prefix("formulize_" . $formObject->getVar('form_handle')) . " AS t4 WHERE t4.`" . $element->getVar('ele_handle') . "` LIKE CONCAT( '%,', t1.`entry_id` , ',%' ) AND t4.entry_id != " . intval($entry_id);
             $restrictSQL .= $renderer->addEntryRestrictionSQL($ele_value[9], $id_form, $groups);
             // pass in the flag about restriction scope, and the form id, and the groups
             $restrictSQL .= " ) OR EXISTS (\n\t\t\t\tSELECT 1 FROM " . $xoopsDB->prefix("formulize_" . $formObject->getVar('form_handle')) . " AS t4 WHERE t4.`" . $element->getVar('ele_handle') . "` LIKE CONCAT( '%,', t1.`entry_id` , ',%' ) AND t4.entry_id = " . intval($entry_id);
             $restrictSQL .= $renderer->addEntryRestrictionSQL($ele_value[9], $id_form, $groups);
             $restrictSQL .= ") )";
         }
         static $cachedSourceValuesQ = array();
         static $cachedSourceValuesAutocompleteFile = array();
         static $cachedSourceValuesAutocompleteLength = array();
         // setup the sort order based on ele_value[12], which is an element id number
         $sortOrder = $ele_value[15] == 2 ? " DESC" : "ASC";
         if ($ele_value[12] == "none" or !$ele_value[12]) {
             $sortOrderClause = " ORDER BY t1.`{$sourceHandle}` {$sortOrder}";
         } else {
             list($sortHandle) = convertElementIdsToElementHandles(array($ele_value[12]), $sourceFormObject->getVar('id_form'));
             $sortOrderClause = " ORDER BY t1.`{$sortHandle}` {$sortOrder}";
         }
         if ($pgroupsfilter) {
             // if there is a groups filter, then join to the group ownership table
             $sourceValuesQ = "SELECT t1.entry_id, t1.`" . $sourceHandle . "` FROM " . $xoopsDB->prefix("formulize_" . $sourceFormObject->getVar('form_handle')) . " AS t1, " . $xoopsDB->prefix("formulize_entry_owner_groups") . " AS t2 {$parentFormFrom} WHERE {$pgroupsfilter} {$conditionsfilter} {$conditionsfilter_oom} {$restrictSQL} GROUP BY t1.entry_id {$sortOrderClause}";
         } else {
             // otherwise just query the source table
             $sourceValuesQ = "SELECT t1.entry_id, t1.`" . $sourceHandle . "` FROM " . $xoopsDB->prefix("formulize_" . $sourceFormObject->getVar('form_handle')) . " AS t1 {$parentFormFrom} WHERE t1.entry_id>0 {$conditionsfilter} {$conditionsfilter_oom} {$restrictSQL} GROUP BY t1.entry_id {$sortOrderClause}";
         }
         //print "$sourceValuesQ<br><br>";
         if (!$isDisabled) {
             // set the default selections, based on the entry_ids that have been selected as the defaults, if applicable
             $hasNoValues = trim($boxproperties[2]) == "" ? true : false;
             $useDefaultsWhenEntryHasNoValue = $ele_value[14];
             if (($entry_id == "new" or $useDefaultsWhenEntryHasNoValue and $hasNoValues) and (is_array($ele_value[13]) and count($ele_value[13]) > 0 or $ele_value[13])) {
                 $defaultSelected = $ele_value[13];
             } else {
                 $defaultSelected = "";
             }
             $form_ele = new XoopsFormSelect($caption, $markupName, $defaultSelected, $ele_value[0], $ele_value[1]);
             $form_ele->setExtra("onchange=\"javascript:formulizechanged=1;\" jquerytag='{$markupName}'");
             if ($ele_value[0] == 1) {
                 // add the initial default entry, singular or plural based on whether the box is one line or not.
                 $form_ele->addOption("none", _AM_FORMLINK_PICK);
             }
         } else {
             $disabledHiddenValue = array();
             $disabledOutputText = array();
         }
         if (!isset($cachedSourceValuesQ[$sourceValuesQ])) {
             $element_handler = xoops_getmodulehandler('elements', 'formulize');
             $sourceElementObject = $element_handler->get($boxproperties[1]);
             if ($sourceElementObject->isLinked) {
                 // need to jump one more level back to get value that this value is pointing at
                 $sourceEleValue = $sourceElementObject->getVar('ele_value');
                 $originalSource = explode("#*=:*", $sourceEleValue[2]);
                 include_once XOOPS_ROOT_PATH . "/modules/formulize/class/data.php";
                 $data_handler = new formulizeDataHandler($originalSource[0]);
             }
             $reslinkedvaluesq = $xoopsDB->query($sourceValuesQ);
             if ($reslinkedvaluesq) {
                 while ($rowlinkedvaluesq = $xoopsDB->fetchRow($reslinkedvaluesq)) {
                     if ($rowlinkedvaluesq[1] === "") {
                         continue;
                     }
                     if ($sourceElementObject->isLinked) {
                         $rowlinkedvaluesq[1] = $data_handler->getElementValueInEntry(trim($rowlinkedvaluesq[1], ","), $originalSource[1]);
                     }
                     $linkedElementOptions[$rowlinkedvaluesq[0]] = strip_tags($rowlinkedvaluesq[1]);
                 }
             }
             $cachedSourceValuesQ[$sourceValuesQ] = $linkedElementOptions;
             /* ALTERED - 20100318 - freeform - jeff/julian - start */
             if (!$isDisabled and $ele_value[8] == 1) {
                 // write the possible values to a cached file so we can look them up easily when we need them, don't want to actually send them to the browser, since it could be huge, but don't want to replicate all the logic that has already gathered the values for us, each time there's an ajax request
                 $cachedLinkedOptionsFileName = "formulize_linkedOptions_" . str_replace(".", "", microtime(true));
                 formulize_scandirAndClean(XOOPS_ROOT_PATH . "/cache/", "formulize_linkedOptions_");
                 $cachedLinkedOptions = fopen(XOOPS_ROOT_PATH . "/cache/{$cachedLinkedOptionsFileName}", "w");
                 fwrite($cachedLinkedOptions, "<?php\n\r");
                 $maxLength = 0;
                 foreach ($linkedElementOptions as $id => $text) {
                     $thisTextLength = strlen($text);
                     $maxLength = $thisTextLength > $maxLength ? $thisTextLength : $maxLength;
                     $text = str_replace("\$", "\\\$", $text);
                     $quotedText = "\"" . str_replace("\"", "\\\"", html_entity_decode($text, ENT_QUOTES)) . "\"";
                     $singleQuotedText = str_replace("'", "\\'", "[{$quotedText},{$id}]");
                     fwrite($cachedLinkedOptions, "if(stristr({$quotedText}, \$term)){ \$found[]='" . $singleQuotedText . "'; }\n");
                 }
                 fwrite($cachedLinkedOptions, "?>");
                 fclose($cachedLinkedOptions);
                 $cachedSourceValuesAutocompleteFile[$sourceValuesQ] = $cachedLinkedOptionsFileName;
                 $cachedSourceValuesAutocompleteLength[$sourceValuesQ] = $maxLength;
             }
         }
         // if we're rendering an autocomplete box
         if (!$isDisabled and $ele_value[8] == 1) {
             // do autocomplete rendering logic here
             if ($boxproperties[2]) {
                 $default_value = trim($boxproperties[2], ",");
                 $data_handler_autocomplete = new formulizeDataHandler($boxproperties[0]);
                 $default_value_user = $data_handler_autocomplete->getElementValueInEntry(trim($boxproperties[2], ","), $boxproperties[1]);
             }
             $renderedComboBox = $renderer->formulize_renderQuickSelect($markupName, $cachedSourceValuesAutocompleteFile[$sourceValuesQ], $default_value, $default_value_user, $cachedSourceValuesAutocompleteLength[$sourceValuesQ]);
             $form_ele = new xoopsFormLabel($caption, $renderedComboBox);
             $form_ele->setDescription(html_entity_decode($ele_desc, ENT_QUOTES));
         }
         // only do this if we're rendering a normal element, that is not disabled
         if (!$isDisabled and $ele_value[8] == 0) {
             $form_ele->addOptionArray($cachedSourceValuesQ[$sourceValuesQ]);
         }
         // only do this if we're rendering a normal element (may be disabled)
         if ($ele_value[8] == 0) {
             foreach ($sourceEntryIds as $thisEntryId) {
                 if (!$isDisabled) {
                     $form_ele->setValue($thisEntryId);
                 } else {
                     $disabledName = $ele_value[1] ? $markupName . "[]" : $markupName;
                     $disabledHiddenValue[] = "<input type=hidden name=\"{$disabledName}\" value=\"{$thisEntryId}\">";
                     $disabledOutputText[] = $cachedSourceValuesQ[$sourceValuesQ][$thisEntryId];
                     // the text value of the option(s) that are currently selected
                 }
             }
         }
         if ($isDisabled) {
             $form_ele = new XoopsFormLabel($caption, implode(", ", $disabledOutputText) . implode("\n", $disabledHiddenValue));
             $form_ele->setDescription(html_entity_decode($ele_desc, ENT_QUOTES));
         } elseif ($ele_value[8] == 0) {
             // this is a hack because the size attribute is private and only has a getSize and not a setSize, setting the size can only be done through the constructor
             $count = count($form_ele->getOptions());
             $size = $ele_value[0];
             $new_size = $count < $size ? $count : $size;
             $form_ele->_size = $new_size;
         }
         /* ALTERED - 20100318 - freeform - jeff/julian - stop */
     } else {
         // or if we don't have a link...
         $selected = array();
         $options = array();
         $disabledOutputText = array();
         $disabledHiddenValue = array();
         $disabledHiddenValues = "";
         // add the initial default entry, singular or plural based on whether the box is one line or not.
         if ($ele_value[0] == 1) {
             $options["none"] = _AM_FORMLINK_PICK;
         }
         // set opt_count to 1 if the box is NOT a multiple selection box. -- jwe 7/26/04
         if ($ele_value[1]) {
             $opt_count = 0;
         } else {
             $opt_count = 1;
         }
         $hiddenOutOfRangeValuesToWrite = array();
         while ($i = each($ele_value[2])) {
             // handle requests for full names or usernames -- will only kick in if there is no saved value (otherwise ele_value will have been rewritten by the loadValues function in the form display
             // note: if the user is about to make a proxy entry, then the list of users displayed will be from their own groups, but not from the groups of the user they are about to make a proxy entry for.  ie: until the proxy user is known, the choice of users for this list can only be based on the current user.  This could lead to confusing or buggy situations, such as users being selected who are outside the groups of the proxy user (who will become the owner) and so there will be an invalid value stored for this element in the db.
             if ($i['key'] === "{FULLNAMES}" or $i['key'] === "{USERNAMES}") {
                 // ADDED June 18 2005 to handle pulling in usernames for the user's group(s)
                 if ($i['key'] === "{FULLNAMES}") {
                     $nametype = "name";
                 }
                 if ($i['key'] === "{USERNAMES}") {
                     $nametype = "uname";
                 }
                 if (isset($ele_value[2]['{OWNERGROUPS}'])) {
                     $groups = $ele_value[2]['{OWNERGROUPS}'];
                 } else {
                     global $regcode;
                     if ($regcode) {
                         // if we're dealing with a registration code, determine group membership based on the code
                         $reggroupsq = q("SELECT reg_codes_groups FROM " . XOOPS_DB_PREFIX . "_reg_codes WHERE reg_codes_code=\"{$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;
                     } else {
                         global $xoopsUser;
                         $groups = $xoopsUser ? $xoopsUser->getGroups() : array(0 => XOOPS_GROUP_ANONYMOUS);
                     }
                 }
                 $pgroups = array();
                 if ($ele_value[3]) {
                     $scopegroups = explode(",", $ele_value[3]);
                     if (!in_array("all", $scopegroups)) {
                         if ($ele_value[4]) {
                             // limit by users's groups
                             foreach ($groups as $gid) {
                                 // want to loop so we can get rid of reg users group simply
                                 if ($gid == XOOPS_GROUP_USERS) {
                                     continue;
                                 }
                                 if (in_array($gid, $scopegroups)) {
                                     $pgroups[] = $gid;
                                 }
                             }
                             if (count($pgroups) > 0) {
                                 unset($groups);
                                 $groups = $pgroups;
                             } else {
                                 $groups = array();
                             }
                         } else {
                             // don't limit by user's groups
                             $groups = $scopegroups;
                         }
                     } else {
                         // use all
                         if (!$ele_value[4]) {
                             // really use all (otherwise, we're just going with all user's groups, so existing value of $groups will be okay
                             unset($groups);
                             global $xoopsDB;
                             $allgroupsq = q("SELECT groupid FROM " . $xoopsDB->prefix("groups"));
                             //  . " WHERE groupid != " . XOOPS_GROUP_USERS); // removed exclusion of registered users group March 18 2009, since it doesn't make sense in this situation.  All groups should mean everyone, period.
                             foreach ($allgroupsq as $thisgid) {
                                 $groups[] = $thisgid['groupid'];
                             }
                         }
                     }
                 }
                 $namelist = gatherNames($groups, $nametype, $ele_value[6], $ele_value[5]);
                 foreach ($namelist as $auid => $aname) {
                     $options[$auid] = $aname;
                 }
             } elseif ($i['key'] === "{SELECTEDNAMES}") {
                 // loadValue in formDisplay will create a second option with this key that contains an array of the selected values
                 $selected = $i['value'];
             } elseif ($i['key'] === "{OWNERGROUPS}") {
                 // do nothing with this piece of metadata that gets set in loadValue, since it's used above
             } else {
                 // regular selection list....
                 $options[$opt_count] = $myts->stripSlashesGPC($i['key']);
                 if (strstr($i['key'], _formulize_OUTOFRANGE_DATA)) {
                     $hiddenOutOfRangeValuesToWrite[$opt_count] = str_replace(_formulize_OUTOFRANGE_DATA, "", $i['key']);
                     // if this is an out of range value, grab the actual value so we can stick it in a hidden element later
                 }
                 if ($i['value'] > 0) {
                     $selected[] = $opt_count;
                 }
                 $opt_count++;
             }
         }
         $count = count($options);
         $size = $ele_value[0];
         $final_size = $count < $size ? $count : $size;
         $form_ele1 = new XoopsFormSelect($caption, $markupName, $selected, $final_size, $ele_value[1]);
         $form_ele1->setExtra("onchange=\"javascript:formulizechanged=1;\" jquerytag='{$markupName}'");
         // must check the options for uitext before adding to the element -- aug 25, 2007
         foreach ($options as $okey => $ovalue) {
             $options[$okey] = formulize_swapUIText($ovalue, $element->getVar('ele_uitext'));
         }
         $form_ele1->addOptionArray($options);
         if ($selected) {
             if (is_array($selected)) {
                 $hiddenElementName = $ele_value[1] ? $form_ele1->getName() . "[]" : $form_ele1->getName();
                 foreach ($selected as $thisSelected) {
                     $disabledOutputText[] = $options[$thisSelected];
                     $disabledHiddenValue[] = "<input type=hidden name=\"{$hiddenElementName}\" value=\"{$thisSelected}\">";
                 }
             } elseif ($ele_value[1]) {
                 // need to keep [] in the hidden element name if multiple values are expected, even if only one is chosen
                 $disabledOutputText[] = $options[$selected];
                 $disabledHiddenValue[] = "<input type=hidden name=\"" . $form_ele1->getName() . "[]\" value=\"{$selected}\">";
             } else {
                 $disabledOutputText[] = $options[$selected];
                 $disabledHiddenValue[] = "<input type=hidden name=\"" . $form_ele1->getName() . "\" value=\"{$selected}\">";
             }
         }
         $renderedHoorvs = "";
         if (count($hiddenOutOfRangeValuesToWrite) > 0) {
             foreach ($hiddenOutOfRangeValuesToWrite as $hoorKey => $hoorValue) {
                 $thisHoorv = new xoopsFormHidden('formulize_hoorv_' . $true_ele_id . '_' . $hoorKey, $hoorValue);
                 $renderedHoorvs .= $thisHoorv->render() . "\n";
                 unset($thisHoorv);
             }
         }
         if ($isDisabled) {
             $disabledHiddenValues = implode("\n", $disabledHiddenValue);
             // glue the individual value elements together into a set of values
             $renderedElement = implode(", ", $disabledOutputText);
         } elseif ($ele_value[8] == 1) {
             // autocomplete construction: make sure that $renderedElement is the final output of this chunk of code
             // write the possible values to a cached file so we can look them up easily when we need them, don't want to actually send them to the browser, since it could be huge, but don't want to replicate all the logic that has already gathered the values for us, each time there's an ajax request
             $cachedOptionsFileName = "formulize_Options_" . str_replace(".", "", microtime(true));
             formulize_scandirAndClean(XOOPS_ROOT_PATH . "/cache/", "formulize_Options_");
             $cachedOptions = fopen(XOOPS_ROOT_PATH . "/cache/{$cachedOptionsFileName}", "w");
             fwrite($cachedOptions, "<?php\n\r");
             $maxLength = 0;
             foreach ($options as $id => $text) {
                 $thisTextLength = strlen($text);
                 $maxLength = $thisTextLength > $maxLength ? $thisTextLength : $maxLength;
                 //$quotedText = "\"".str_replace("\"", "\\\"", trim($text))."\"";
                 $quotedText = "\"" . str_replace("\"", "\\\"", $text) . "\"";
                 fwrite($cachedOptions, "if(stristr({$quotedText}, \$term)){ \$found[]='[{$quotedText},{$id}]'; }\n\r");
             }
             fwrite($cachedOptions, "?>");
             fclose($cachedOptions);
             //print_r($selected); print_r($options);
             $defaultSelected = is_array($selected) ? $selected[0] : $selected;
             $renderedComboBox = $renderer->formulize_renderQuickSelect($markupName, $cachedOptionsFileName, $defaultSelected, $options[$defaultSelected], $maxLength);
             $form_ele2 = new xoopsFormLabel($caption, $renderedComboBox);
             $renderedElement = $form_ele2->render();
         } else {
             // normal element
             $renderedElement = $form_ele1->render();
         }
         $form_ele = new XoopsFormLabel($caption, "<nobr>{$renderedElement}</nobr>\n{$renderedHoorvs}\n{$disabledHiddenValues}\n");
         $form_ele->setDescription(html_entity_decode($ele_desc, ENT_QUOTES));
     }
     // end of if we have a link on our hands. -- jwe 7/29/04
     return $form_ele;
 }
Example #2
0
function compileElements($fid, $form, $formulize_mgr, $prevEntry, $entry, $go_back, $parentLinks, $owner_groups, $groups, $overrideValue = "", $elements_allowed = "", $profileForm = "", $frid = "", $mid, $sub_entries, $sub_fids, $member_handler, $gperm_handler, $title, $screen = null, $printViewPages = "", $printViewPageTitles = "")
{
    include_once XOOPS_ROOT_PATH . '/modules/formulize/include/elementdisplay.php';
    $entryForDEElements = is_numeric($entry) ? $entry : "new";
    // if there is no entry, ie: a new entry, then $entry is "" so when writing the entry value into decue_ and other elements that go out to the HTML form, we need to use the keyword "new"
    global $xoopsDB, $xoopsUser;
    $elementsAvailableToUser = array();
    // set criteria for matching on display
    // set the basics that everything has to match
    $criteriaBase = new CriteriaCompo();
    $criteriaBase->add(new Criteria('ele_display', 1), 'OR');
    foreach ($groups as $thisgroup) {
        $criteriaBase->add(new Criteria('ele_display', '%,' . $thisgroup . ',%', 'LIKE'), 'OR');
    }
    if (is_array($elements_allowed) and count($elements_allowed) > 0) {
        // if we're limiting the elements, then add a criteria for that (multiple criteria are joined by AND unless you specify OR manually when adding them (as in the base above))
        $criteria = new CriteriaCompo();
        $criteria->add(new Criteria('ele_id', "(" . implode(",", $elements_allowed) . ")", "IN"));
        $criteria->add($criteriaBase);
    } else {
        $criteria = $criteriaBase;
        // otherwise, just use the base
    }
    $criteria->setSort('ele_order');
    $criteria->setOrder('ASC');
    $elements =& $formulize_mgr->getObjects($criteria, $fid, true);
    // true makes the keys of the returned array be the element ids
    $count = 0;
    global $gridCounter;
    $gridCounter = array();
    $inGrid = 0;
    formulize_benchmark("Ready to loop elements.");
    // set the array to be used as the structure of the loop, either the passed in elements in order, or the elements as gathered from the DB
    // ignore passed in element order if there's a screen in effect, since we assume that official element order is authoritative when screens are involved
    // API should still allow arbitrary ordering, so $element_allowed can still be set manually as part of a displayForm call, and the order will be respected then
    if (!is_array($elements_allowed) or $screen) {
        $element_order_array = $elements;
    } else {
        $element_order_array = $elements_allowed;
    }
    // if this is a printview page,
    foreach ($element_order_array as $thisElement) {
        if (is_numeric($thisElement)) {
            // if we're doing the order based on passed in element ids...
            if (isset($elements[$thisElement])) {
                $i = $elements[$thisElement];
                // set the element object for this iteration of the loop
            } else {
                continue;
                // do not try to render elements that don't exist in the form!! (they might have been deleted from a multipage definition, or who knows what)
            }
            $this_ele_id = $thisElement;
            // set the element ID number
        } else {
            // else...we're just looping through the elements directly from the DB
            $i = $thisElement;
            // set the element object
            $this_ele_id = $i->getVar('ele_id');
            // get the element ID number
        }
        // check if we're at the start of a page, when doing a printable view of all pages (only situation when printViewPageTitles and printViewPages will be present), and if we are, then put in a break for the page titles
        if ($printViewPages) {
            if (!$currentPrintViewPage) {
                $currentPrintViewPage = 1;
            }
            while (!in_array($this_ele_id, $printViewPages[$currentPrintViewPage]) and $currentPrintViewPage <= count($printViewPages)) {
                $currentPrintViewPage++;
            }
            if ($this_ele_id == $printViewPages[$currentPrintViewPage][0]) {
                $form->insertBreak("<div id=\"formulize-printpreview-pagetitle\">" . $printViewPageTitles[$currentPrintViewPage] . "</div>", "head");
            }
        }
        // check if this element is included in a grid, and if so, skip it
        // $inGrid will be a number indicating how many times we have to skip things
        if ($inGrid or isset($gridCounter[$this_ele_id])) {
            if (!$inGrid) {
                $inGrid = $gridCounter[$this_ele_id];
            }
            $inGrid--;
            continue;
        }
        $uid = is_object($xoopsUser) ? $xoopsUser->getVar('uid') : 0;
        $owner = getEntryOwner($entry, $fid);
        $ele_type = $i->getVar('ele_type');
        $ele_value = $i->getVar('ele_value');
        if ($go_back['form']) {
            // if there's a parent form...
            // check here to see if we need to initialize the value of a linked selectbox when it is the key field for a subform
            // although this is setup as a loop through all found parentLinks, only the last one will be used, since ele_value[2] is overwritten each time.
            // assumption is there will only be one parent link for this form
            for ($z = 0; $z < count($parentLinks['source']); $z++) {
                if ($this_ele_id == $parentLinks['self'][$z]) {
                    // this is the element
                    $ele_value[2] = $go_back['entry'];
                    // 3.0 datastructure...needs to be tested!! -- now updated for 5.0
                }
            }
        } elseif ($overrideValue) {
            // used to force a default setting in a form element, other than the normal default
            if (!is_array($overrideValue)) {
                //convert a string to an array so that strings don't screw up logic below (which is designed for arrays)
                $temp = $overrideValue;
                unset($overrideValue);
                $overrideValue[0] = $temp;
            }
            // currently only operative for select boxes
            switch ($ele_type) {
                case "select":
                    foreach ($overrideValue as $ov) {
                        if (array_key_exists($ov, $ele_value[2])) {
                            $ele_value[2][$ov] = 1;
                        }
                    }
                    break;
                case "date":
                    // debug
                    //var_dump($overrideValue);
                    foreach ($overrideValue as $ov) {
                        //if(ereg ("([0-9]{4})-([0-9]{2})-([0-9]{2})", $ov, $regs)) {
                        if (ereg("([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})", $ov, $regs)) {
                            $ele_value[0] = $ov;
                        }
                    }
                    break;
            }
        }
        if ($ele_type != "subform" and $ele_type != 'grid') {
            // "" is framework, ie: not applicable
            // $i is element object
            // $entry is entry_id
            // false is "nosave" param...only used to force element to not be picked up by readelements.php after saving
            // $screen is the screen object
            // false means don't print it out to screen, return it here
            $GLOBALS['formulize_sub_fids'] = $sub_fids;
            // set here so we can pick it up in the render method of elements, if necessary (only necessary for subforms?);
            $deReturnValue = displayElement("", $i, $entry, false, $screen, $prevEntry, false, $profileForm, $groups);
            if (is_array($deReturnValue)) {
                $form_ele = $deReturnValue[0];
                $isDisabled = $deReturnValue[1];
            } else {
                $form_ele = $deReturnValue;
                $isDisabled = false;
            }
            $elementsAvailableToUser[$this_ele_id] = true;
            if ($form_ele == "not_allowed" or $form_ele == "hidden") {
                if (isset($GLOBALS['formulize_renderedElementHasConditions']["de_" . $fid . "_" . $entryForDEElements . "_" . $this_ele_id])) {
                    // need to add a tr container for elements that are not allowed, since if it was a condition that caused them to not show up, they might appear later on asynchronously, and we'll need the row to attach them to
                    if ($ele_type == "ib" and $form_ele == "not_allowed") {
                        $rowHTML = "<tr style='display: none' id='formulize-de_" . $fid . "_" . $entryForDEElements . "_" . $this_ele_id . "'></tr>";
                    } elseif ($form_ele == "not_allowed") {
                        $rowHTML = "<tr style='display: none' id='formulize-de_" . $fid . "_" . $entryForDEElements . "_" . $this_ele_id . "' valign='top' align='" . _GLOBAL_LEFT . "'></tr>";
                    }
                    // need to also get the validation code for this element, wrap it in a check for the table row being visible, and assign that to the global array that contains all the validation javascript that we need to add to the form
                    // following code follows the pattern set in elementdisplay.php for actually creating rendered element objects
                    if ($ele_type != "ib") {
                        $conditionalValidationRenderer = new formulizeElementRenderer($i);
                        if ($prevEntry or $profileForm === "new") {
                            $data_handler = new formulizeDataHandler($i->getVar('id_form'));
                            $ele_value = loadValue($prevEntry, $i, $ele_value, $data_handler->getEntryOwnerGroups($entry), $groups, $entry, $profileForm);
                            // get the value of this element for this entry as stored in the DB -- and unset any defaults if we are looking at an existing entry
                        }
                        $conditionalElementForValidiationCode = $conditionalValidationRenderer->constructElement("de_" . $fid . "_" . $entryForDEElements . "_" . $this_ele_id, $ele_value, $entry, $isDisabled, $screen);
                        if ($js = $conditionalElementForValidiationCode->renderValidationJS()) {
                            $GLOBALS['formulize_renderedElementsValidationJS'][$GLOBALS['formulize_thisRendering']][$conditionalElementForValidiationCode->getName()] = "if(window.document.getElementById('formulize-" . $conditionalElementForValidiationCode->getName() . "').style.display != 'none') {\n" . $js . "\n}\n";
                        }
                        unset($conditionalElementForValidiationCode);
                        unset($conditionalValidationRenderer);
                    }
                    $form->addElement($rowHTML);
                    // since it was treated as a conditional element, and the user might interact with it, then we don't consider it a not-available-to-user element
                    unset($elementsAvailableToUser[$this_ele_id]);
                }
                continue;
            }
        }
        $req = !$isDisabled ? intval($i->getVar('ele_req')) : 0;
        $GLOBALS['sub_entries'] = $sub_entries;
        if ($ele_type == "subform") {
            $thissfid = $ele_value[0];
            if (!$thissfid) {
                continue;
            }
            // can't display non-specified subforms!
            $deReturnValue = displayElement("", $i, $entry, false, $screen, $prevEntry, false, $profileForm, $groups);
            // do this just to evaluate any conditions...it won't actually render anything, but will return "" for the first key in the array, if the element is allowed
            if (is_array($deReturnValue)) {
                $form_ele = $deReturnValue[0];
                $isDisabled = $deReturnValue[1];
            } else {
                $form_ele = $deReturnValue;
                $isDisabled = false;
            }
            if ($passed = security_check($thissfid) and $form_ele == "") {
                $GLOBALS['sfidsDrawn'][] = $thissfid;
                $customCaption = $i->getVar('ele_caption');
                $customElements = $ele_value[1] ? explode(",", $ele_value[1]) : "";
                if (isset($GLOBALS['formulize_inlineSubformFrid'])) {
                    $newLinkResults = checkForLinks($GLOBALS['formulize_inlineSubformFrid'][0], array($fid), $fid, array($fid => array($entry)), null, $owner_groups, $mid, null, $owner, true);
                    // final true means only include entries from unified display linkages
                    $sub_entries = $newLinkResults['sub_entries'];
                }
                // 2 is the number of default blanks, 3 is whether to show the view button or not, 4 is whether to use captions as headings or not, 5 is override owner of entry, $owner is mainform entry owner, 6 is hide the add button, 7 is the conditions settings for the subform element, 8 is the setting for showing just a row or the full form, 9 is text for the add entries button
                $subUICols = drawSubLinks($thissfid, $sub_entries, $uid, $groups, $frid, $mid, $fid, $entry, $customCaption, $customElements, intval($ele_value[2]), $ele_value[3], $ele_value[4], $ele_value[5], $owner, $ele_value[6], $ele_value[7], $this_ele_id, $ele_value[8], $ele_value[9], $thisElement);
                if (isset($subUICols['single'])) {
                    $form->insertBreak($subUICols['single'], "even");
                } else {
                    $subLinkUI = new XoopsFormLabel($subUICols['c1'], $subUICols['c2']);
                    $form->addElement($subLinkUI);
                }
                unset($subLinkUI);
            }
        } elseif ($ele_type == "grid") {
            // we are going to have to store some kind of flag/counter with the id number of the starting element in the table, and the number of times we need to ignore things
            // we need to then listen for this up above and skip those elements as they come up.  This is why grids must come before their elements in the form definition
            include_once XOOPS_ROOT_PATH . "/modules/formulize/include/griddisplay.php";
            list($grid_title, $grid_row_caps, $grid_col_caps, $grid_background, $grid_start, $grid_count) = compileGrid($ele_value, $title, $i);
            $headingAtSide = ($ele_value[5] and $grid_title) ? true : false;
            // if there is a value for ele_value[5], then the heading should be at the side, otherwise, grid spans form width as it's own chunk of HTML
            $gridCounter[$grid_start] = $grid_count;
            $gridContents = displayGrid($fid, $entry, $grid_row_caps, $grid_col_caps, $grid_title, $grid_background, $grid_start, "", "", true, $screen, $headingAtSide);
            if ($headingAtSide) {
                // grid contents is the two bits for the xoopsformlabel when heading is at side, otherwise, it's just the contents for the break
                $form->addElement(new XoopsFormLabel($gridContents[0], $gridContents[1]));
            } else {
                $form->insertBreak($gridContents, "head");
                // head is the css class of the cell
            }
        } elseif ($ele_type == "ib" or is_array($form_ele)) {
            // if it's a break, handle it differently...$form_ele may be an array if it's a non-interactive element such as a grid
            if (is_object($thisElement)) {
                // final param is used as id name in the table row where this element exists, so we can interact with it for showing and hiding
                $form->insertBreakFormulize("<div class=\"formulize-subform-heading\">" . trans(stripslashes($form_ele[0])) . "</div>", $form_ele[1], 'de_' . $fid . '_' . $entryForDEElements . '_' . $this_ele_id, $thisElement->getVar("ele_handle"));
            }
        } else {
            $form->addElement($form_ele, $req);
        }
        $count++;
        unset($hidden);
        unset($form_ele);
        // apparently necessary for compatibility with PHP 4.4.0 -- suggested by retspoox, sept 25, 2005
    }
    formulize_benchmark("Done looping elements.");
    // find any hidden elements in the form, that aren't available to the user in this rendering of the form...
    unset($criteria);
    $notAllowedCriteria = new CriteriaCompo();
    $notAllowedCriteria->add(new Criteria('ele_forcehidden', 1));
    foreach ($elementsAvailableToUser as $availElementId => $boolean) {
        $notAllowedCriteria->add(new Criteria('ele_id', $availElementId, '!='));
    }
    $notAllowedCriteria->setSort('ele_order');
    $notAllowedCriteria->setOrder('ASC');
    $notAllowedElements =& $formulize_mgr->getObjects($notAllowedCriteria, $fid);
    $hiddenElements = generateHiddenElements($notAllowedElements, $entryForDEElements);
    // in functions.php, keys in returned array will be the element ids
    foreach ($hiddenElements as $element_id => $thisHiddenElement) {
        $form->addElement(new xoopsFormHidden("decue_" . $fid . "_" . $entryForDEElements . "_" . $element_id, 1));
        if (is_array($thisHiddenElement)) {
            // could happen for checkboxes
            foreach ($thisHiddenElement as $thisIndividualHiddenElement) {
                $form->addElement($thisIndividualHiddenElement);
            }
        } else {
            $form->addElement($thisHiddenElement);
        }
        unset($thisHiddenElement);
        // some odd reference thing going on here...$thisHiddenElement is being added by reference or something like that, so that when $thisHiddenElement changes in the next run through, every previous element that was created by adding it is updated to point to the next element.  So if you unset at the end of the loop, it forces each element to be added as you would expect.
    }
    if ($entry and !is_a($form, 'formulize_elementsOnlyForm')) {
        // two hidden fields encode the main entry id, the first difficult-to-use format is a legacy thing
        // the 'lastentry' format is more sensible, but is only available when there was a real entry, not 'new' (also a legacy convention)
        $form->addElement(new XoopsFormHidden('entry' . $fid, $entry));
        if (is_numeric($entry)) {
            $form->addElement(new XoopsFormHidden('lastentry', $entry));
        }
    }
    if ($_POST['parent_form']) {
        // if we just came back from a parent form, then if they click save, we DO NOT want an override condition, even though we are now technically editing an entry that was previously saved when we went to the subform in the first place.  So the override logic looks for this hidden value as an exception.
        $form->addElement(new XoopsFormHidden('back_from_sub', 1));
    }
    // add a hidden element to carry all the validation javascript that might be associated with elements rendered with elementdisplay.php...only relevant for elements rendered inside subforms or grids...the validation code comes straight from the element, doesn't have a check around it for the conditional table row id, like the custom form classes at the top of the file use, since those elements won't render as hidden and show/hide in the same way
    if (isset($GLOBALS['formulize_renderedElementsValidationJS'][$GLOBALS['formulize_thisRendering']])) {
        $formulizeHiddenValidation = new XoopsFormHidden('validation', '');
        foreach ($GLOBALS['formulize_renderedElementsValidationJS'][$GLOBALS['formulize_thisRendering']] as $thisValidation) {
            // grab all the validation code we stored in the elementdisplay.php file and attach it to this element
            foreach (explode("\n", $thisValidation) as $thisValidationLine) {
                $formulizeHiddenValidation->customValidationCode[] = $thisValidationLine;
            }
        }
        $form->addElement($formulizeHiddenValidation, 1);
    }
    if (get_class($form) == "formulize_elementsOnlyForm") {
        // forms of this class are ones that we're rendering just the HTML for the elements, and we need to preserve any validation javascript to stick in the final, parent form when it's finished
        $validationJS = $form->renderValidationJS();
        if (trim($validationJS) != "") {
            $GLOBALS['formulize_elementsOnlyForm_validationCode'][] = $validationJS . "\n\n";
        }
    } elseif (count($GLOBALS['formulize_elementsOnlyForm_validationCode']) > 0) {
        $elementsonlyvalidation = new XoopsFormHidden('elementsonlyforms', '');
        $elementsonlyvalidation->customValidationCode = $GLOBALS['formulize_elementsOnlyForm_validationCode'];
        $form->addElement($elementsonlyvalidation, 1);
    }
    return $form;
}
 function render($ele_value, $caption, $markupName, $isDisabled, $element, $entry_id)
 {
     $elementrenderer = new formulizeElementRenderer();
     $id_form = $element->getVar('id_form');
     if (get_magic_quotes_gpc()) {
         $ele_value[0] = stripslashes($ele_value[0]);
     }
     if (trim($ele_value[0]) == "") {
         $ele_value[0] = $caption;
     }
     if (strstr($ele_value[0], "\$value=") or strstr($ele_value[0], "\$value =")) {
         $form_id = $id_form;
         // $entry_id = $entry;
         $entryData = $elementrenderer->formulize_getCachedEntryData($id_form, $entry_id);
         $creation_datetime = display($entryData, "creation_datetime");
         $evalResult = eval($ele_value[0]);
         if ($evalResult === false) {
             $ele_value[0] = _formulize_ERROR_IN_LEFTRIGHT;
         } else {
             $ele_value[0] = $value;
             // value is supposed to be the thing set in the eval'd code
         }
     }
     $ele_value[0] = $elementrenderer->formulize_replaceCurlyBracketVariables($ele_value[0], $entry_id, $id_form);
     return $ele_value;
     // an array, item 0 is the contents of the break, item 1 is the class of the table cell (for when the form is table rendered)
 }
 function render($ele_value, $caption, $markupName, $isDisabled, $element, $entry_id)
 {
     $renderer = new formulizeElementRenderer();
     if (strstr($ele_value[0], "\$value=") or strstr($ele_value[0], "\$value =")) {
         $form_id = $element->getVar('id_form');
         $entryData = $renderer->formulize_getCachedEntryData($id_form, $entry_id);
         $creation_datetime = display($entryData, "creation_datetime");
         $evalResult = eval($ele_value[0]);
         if ($evalResult === false) {
             $ele_value[0] = _formulize_ERROR_IN_LEFTRIGHT;
         } else {
             $ele_value[0] = $value;
             // value is supposed to be the thing set in the eval'd code
         }
     }
     $ele_value[0] = $renderer->formulize_replaceCurlyBracketVariables($ele_value[0], $entry_id, $id_form);
     $form_ele = new XoopsFormLabel($caption, $ele_value[0]);
     return $form_ele;
 }
function displayElement($formframe = "", $ele, $entry = "new", $noSave = false, $screen = null, $prevEntry = null, $renderElement = true, $profileForm = null, $groups = "")
{
    static $cachedPrevEntries = array();
    static $lockedEntries = array();
    // keep track of the entries we have determined are locked
    global $entriesThatHaveBeenLockedThisPageLoad;
    if (!is_array($entriesThatHaveBeenLockedThisPageLoad)) {
        // which entries we have locked as part of this page load, so we don't waste time setting locks again on entries we've already locked, and so we can ignore locks that were set by ourselves!
        $entriesThatHaveBeenLockedThisPageLoad = array();
    }
    $subformCreateEntry = strstr($entry, "subformCreateEntry") ? true : false;
    // check for this special flag, which is mostly like a "new" situation, except for the deh hidden flag that gets passed back, since we don't want the standard readelements logic to pickup these elements!
    if ($subformCreateEntry) {
        $subformMetaData = explode("_", $entry);
        $subformEntryIndex = $subformMetaData[1];
        $subformElementId = $subformMetaData[2];
    }
    if ($entry == "" or $subformCreateEntry) {
        $entry = "new";
    }
    $element = _formulize_returnElement($ele, $formframe);
    if (!is_object($element)) {
        return "invalid_element";
    }
    $form_id = $element->getVar('id_form');
    $deprefix = $noSave ? "denosave_" : "de_";
    $deprefix = $subformCreateEntry ? "desubform" . $subformEntryIndex . "x" . $subformElementId . "_" : $deprefix;
    // need to pass in an entry index so that all fields in the same element can be collected
    if ($noSave and !is_bool($noSave)) {
        $renderedElementName = $noSave;
        // if we've passed a specific string with $noSave, then we want to use that to override the name of the element, because the developer wants to pick up that form value later after submission
        $noSave = true;
    } else {
        $renderedElementName = $deprefix . $form_id . '_' . $entry . '_' . $element->getVar('ele_id');
    }
    global $xoopsUser;
    if (!$groups) {
        // groups might be passed in, which covers the case of the registration form and getting the groups from the registration code
        $groups = $xoopsUser ? $xoopsUser->getGroups() : array(0 => XOOPS_GROUP_ANONYMOUS);
    }
    $user_id = $xoopsUser ? $xoopsUser->getVar('uid') : 0;
    $username = $xoopsUser ? $xoopsUser->getVar('uname') : "unknown user";
    static $cachedEntryOwners = array();
    if (!isset($cachedEntryOwners[$form_id][$entry])) {
        $cachedEntryOwners[$form_id][$entry] = getEntryOwner($entry, $form_id);
    }
    $owner = $cachedEntryOwners[$form_id][$entry];
    $mid = getFormulizeModId();
    static $cachedViewPrivate = array();
    static $cachedUpdateOwnEntry = array();
    $gperm_handler = xoops_gethandler('groupperm');
    if (!isset($cachedViewPrivate[$form_id])) {
        $cachedViewPrivate[$form_id] = $gperm_handler->checkRight("view_private_elements", $form_id, $groups, $mid);
        $cachedUpdateOwnEntry[$form_id] = $gperm_handler->checkRight("update_own_entry", $form_id, $groups, $mid);
    }
    $view_private_elements = $cachedViewPrivate[$form_id];
    $update_own_entry = $cachedUpdateOwnEntry[$form_id];
    // check if the user is normally able to view this element or not, by checking their groups against the display groups -- added Nov 7 2005
    // messed up.  Private should not override the display settings.  And the $entry should be checked against the security check first to determine whether the user should even see this entry in the first place.
    $display = $element->getVar('ele_display');
    $private = $element->getVar('ele_private');
    $member_handler = xoops_gethandler('member');
    $single_result = getSingle($form_id, $user_id, $groups, $member_handler, $gperm_handler, $mid);
    $groupEntryWithUpdateRights = ($single_result['flag'] == "group" and $update_own_entry and $entry == $single_result['entry']) ? true : false;
    // need to test whether the display setting should be checked first?!  Order of checks here looks wrong.  JWE Nov 25 2010
    if ($private and $user_id != $owner and !$groupEntryWithUpdateRights and $entry != "new") {
        $allowed = $view_private_elements ? 1 : 0;
    } elseif (strstr($display, ",")) {
        $display_groups = explode(",", $display);
        $allowed = array_intersect($groups, $display_groups) ? 1 : 0;
    } elseif ($display == 1) {
        $allowed = 1;
    } else {
        $allowed = 0;
    }
    if ($prevEntry == null) {
        // preferable to pass in prevEntry!
        $prevEntry = getEntryValues($entry, "", $groups, $form_id, "", $mid, $user_id, $owner, $groupEntryWithUpdateRights);
    }
    // record the list of elements that are allowed in principle for a form (regardless of conditional status)
    if ($allowed) {
        $GLOBALS['formulize_renderedElementsForForm'][$form_id][$entry][$renderedElementName] = $element->getVar('ele_handle');
    }
    $elementFilterSettings = $element->getVar('ele_filtersettings');
    if ($allowed and count($elementFilterSettings[0]) > 0) {
        // cache the filterElements for this element, so we can build the right stuff with them later in javascript, to make dynamically appearing elements
        $GLOBALS['formulize_renderedElementHasConditions'][$renderedElementName] = $elementFilterSettings[0];
        // need to check if there's a condition on this element that is met or not
        static $cachedEntries = array();
        if ($entry != "new") {
            if (!isset($cachedEntries[$form_id][$entry])) {
                $cachedEntries[$form_id][$entry] = getData("", $form_id, $entry);
            }
            $entryData = $cachedEntries[$form_id][$entry];
        }
        $filterElements = $elementFilterSettings[0];
        $filterOps = $elementFilterSettings[1];
        $filterTerms = $elementFilterSettings[2];
        /* ALTERED - 20100316 - freeform - jeff/julian - start */
        $filterTypes = $elementFilterSettings[3];
        // find the filter indexes for 'match all' and 'match one or more'
        $filterElementsAll = array();
        $filterElementsOOM = array();
        for ($i = 0; $i < count($filterTypes); $i++) {
            if ($filterTypes[$i] == "all") {
                $filterElementsAll[] = $i;
            } else {
                $filterElementsOOM[] = $i;
            }
        }
        /* ALTERED - 20100316 - freeform - jeff/julian - stop */
        // setup evaluation condition as PHP and then eval it so we know if we should include this element or not
        $evaluationCondition = "\$passedCondition = false;\n";
        $evaluationCondition .= "if(";
        /* ALTERED - 20100316 - freeform - jeff/julian - start */
        $evaluationConditionAND = buildEvaluationCondition("AND", $filterElementsAll, $filterElements, $filterOps, $filterTerms, $entry, $entryData);
        $evaluationConditionOR = buildEvaluationCondition("OR", $filterElementsOOM, $filterElements, $filterOps, $filterTerms, $entry, $entryData);
        $evaluationCondition .= $evaluationConditionAND;
        if ($evaluationConditionOR) {
            if ($evaluationConditionAND) {
                $evaluationCondition .= " AND (" . $evaluationConditionOR . ")";
                //$evaluationCondition .= " OR (" . $evaluationConditionOR . ")";
            } else {
                $evaluationCondition .= $evaluationConditionOR;
            }
        }
        /* ALTERED - 20100316 - freeform - jeff/julian - stop */
        $evaluationCondition .= ") {\n";
        $evaluationCondition .= "  \$passedCondition = true;\n";
        $evaluationCondition .= "}\n";
        //print( $evaluationCondition );
        eval($evaluationCondition);
        if (!$passedCondition) {
            $allowed = 0;
        }
    }
    if ($allowed) {
        if ($element->getVar('ele_type') == "subform") {
            return array("", $isDisabled);
        }
        if (isset($GLOBALS['formulize_forceElementsDisabled']) and $GLOBALS['formulize_forceElementsDisabled'] == true) {
            $isDisabled = true;
        } else {
            $ele_disabled = $element->getVar('ele_disabled');
            $isDisabled = false;
            if ($ele_disabled == 1) {
                $isDisabled = true;
            } elseif (!is_numeric($ele_disabled)) {
                $disabled_groups = explode(",", $ele_disabled);
                if (array_intersect($groups, $disabled_groups) and !array_diff($groups, $disabled_groups)) {
                    $isDisabled = true;
                }
            }
        }
        // Another check to see if this element is disabled, for the case where the user can view the form, but not edit it.
        if (!$isDisabled) {
            // note that we're using the OPPOSITE of the permission because we want to know if the element should be disabled
            $isDisabled = !formulizePermHandler::user_can_edit_entry($form_id, $user_id, $entry);
        }
        // check whether the entry is locked, and if so, then the element is not allowed.  Set a message to say that elements were disabled due to entries being edited elsewhere (first time only).
        // groups with ignore lock permission bypass this, and therefore can save entries even when locked, and saving an entry removes the lock, so that gets you out of a jam if the lock is in place when it shouldn't be.
        // locks are only valid for the session time, so if a lock is older than that, it is ignored and cleared
        // Do this last, since locking overrides other permissions!
        $lockFileName = "entry_" . $entry . "_in_form_" . $form_id . "_is_locked_for_editing";
        // if we haven't found a lock for this entry, check if there is one...(as long as it's not an entry that we locked ourselves on this page load)
        if ($entry != "new" and !isset($lockedEntries[$form_id][$entry]) and !isset($entriesThatHaveBeenLockedThisPageLoad[$form_id][$entry]) and file_exists(XOOPS_ROOT_PATH . "/modules/formulize/temp/{$lockFileName}") and !$gperm_handler->checkRight("ignore_editing_lock", $form_id, $groups, $mid)) {
            $maxSessionLifeTime = ini_get("session.gc_maxlifetime");
            $fileCreationTime = filectime(XOOPS_ROOT_PATH . "/modules/formulize/temp/{$lockFileName}");
            if ($fileCreationTime + $maxSessionLifeTime > time()) {
                list($lockUid, $lockUsername) = explode(",", file_get_contents(XOOPS_ROOT_PATH . "/modules/formulize/temp/{$lockFileName}"));
                if ($lockUid != $user_id) {
                    // lock is still valid, hasn't expired yet.
                    if (count($lockedEntries) == 0) {
                        $label = json_encode(sprintf(_formulize_ENTRY_IS_LOCKED, $lockUsername));
                        print <<<EOF
<script type='text/javascript'>
\$(document).ready(function() {
    jQuery("<div id=\\"formulize-entry-lock-message\\"><i id=\\"formulize-entry-lock-icon\\" class=\\"icon-lock\\"></i><p>"+{$label}+"</p></div>").insertBefore("#formulize .xo-theme-form table");
});
</script>
EOF;
                    }
                    $lockedEntries[$form_id][$entry] = true;
                }
            } else {
                // clean up expired locks
                formulize_scandirAndClean(XOOPS_ROOT_PATH . "/modules/formulize/temp/", "_" . $entry . "_in_form_" . $form_id . "_", $maxSessionLifeTime);
            }
        }
        // if we've ever found a lock for this entry as part of this pageload...
        if (isset($lockedEntries[$form_id][$entry])) {
            $isDisabled = true;
        }
        $renderer = new formulizeElementRenderer($element);
        $ele_value = $element->getVar('ele_value');
        $ele_type = $element->getVar('ele_type');
        if (($prevEntry or $profileForm === "new") and $ele_type != 'subform' and $ele_type != 'grid') {
            $data_handler = new formulizeDataHandler($form_id);
            $ele_value = loadValue($prevEntry, $element, $ele_value, $data_handler->getEntryOwnerGroups($entry), $groups, $entry, $profileForm);
            // get the value of this element for this entry as stored in the DB -- and unset any defaults if we are looking at an existing entry
        }
        formulize_benchmark("About to render element " . $element->getVar('ele_caption') . ".");
        $form_ele =& $renderer->constructElement($renderedElementName, $ele_value, $entry, $isDisabled, $screen);
        if (strstr($_SERVER['PHP_SELF'], "formulize/printview.php") and is_object($form_ele)) {
            $form_ele->setDescription('');
        }
        formulize_benchmark("Done rendering element.");
        // put a lock on this entry in this form, so we know that the element is being edited.  Lock will be removed next time the entry is saved.
        if ($entry > 0 and !isset($lockedEntries[$form_id][$entry]) and !isset($entriesThatHaveBeenLockedThisPageLoad[$form_id][$entry])) {
            if (is_writable(XOOPS_ROOT_PATH . "/modules/formulize/temp/")) {
                $lockFile = fopen(XOOPS_ROOT_PATH . "/modules/formulize/temp/{$lockFileName}", "w");
                if (false !== $lockFile) {
                    fwrite($lockFile, "{$user_id},{$username}");
                    fclose($lockFile);
                    $entriesThatHaveBeenLockedThisPageLoad[$form_id][$entry] = true;
                }
            } else {
                if (defined("ICMS_ERROR_LOG_SEVERITY") and ICMS_ERROR_LOG_SEVERITY >= E_WARNING) {
                    static $lock_file_warning_issued = false;
                    if (!$lock_file_warning_issued) {
                        // cannot write to Formulize temp folder to create lock entries
                        error_log("Notice: Formulize temp folder does not exist or is not writeable, so lock file cannot be created in " . XOOPS_ROOT_PATH . "/modules/formulize/temp/");
                        $lock_file_warning_issued = true;
                    }
                }
            }
        }
        if (!$renderElement) {
            return array(0 => $form_ele, 1 => $isDisabled);
        } else {
            if ($element->getVar('ele_type') == "ib") {
                print $form_ele[0];
                return "rendered";
            } elseif (is_object($form_ele)) {
                print $form_ele->render();
                if (!empty($form_ele->customValidationCode) and !$isDisabled) {
                    $GLOBALS['formulize_renderedElementsValidationJS'][$GLOBALS['formulize_thisRendering']][$form_ele->getName()] = $form_ele->renderValidationJS();
                } elseif ($element->getVar('ele_req') and ($element->getVar('ele_type') == "text" or $element->getVar('ele_type') == "textarea") and !$isDisabled) {
                    $eltname = $form_ele->getName();
                    $eltcaption = $form_ele->getCaption();
                    $eltmsg = empty($eltcaption) ? sprintf(_FORM_ENTER, $eltname) : sprintf(_FORM_ENTER, $eltcaption);
                    $eltmsg = str_replace('"', '\\"', stripslashes($eltmsg));
                    $GLOBALS['formulize_renderedElementsValidationJS'][$GLOBALS['formulize_thisRendering']][$eltname] = "if ( myform." . $eltname . ".value == \"\" ) { window.alert(\"" . $eltmsg . "\"); myform." . $eltname . ".focus(); return false; }";
                }
                if ($isDisabled) {
                    return "rendered-disabled";
                } else {
                    return "rendered";
                }
            }
        }
        // or, even if the user is not supposed to see the element, put in a hidden element with its default value (only on new entries for elements with the forcehidden flag on)
        // NOTE: YOU CANNOT HAVE DEFAULT VALUES ON A LINKED FIELD CURRENTLY
        // So, no handling of linked values is included here.
    } elseif ($forcehidden = $element->getVar('ele_forcehidden') and $entry == "new" and !$noSave) {
        // hiddenElements keys will be the element ids
        $hiddenElements = generateHiddenElements(array($element), $entry);
        $thisHiddenElement = isset($hiddenElements[$element->getVar('ele_id')]) ? $hiddenElements[$element->getVar('ele_id')] : "";
        if (!$renderElement) {
            return array("hidden", $isDisabled, $thisHiddenElement);
            // if the element is hidden, then return an array, but with hidden as the first key, so that logic that was not expecting an element back, will still function as is.  This is a backwards compatibility thing.  For hidden elements, the element is in the third key, if in fact you need it/are looking for it in the user land code...note that in the case of checkboxes, the elements returned will be in an array
        } else {
            $cueElement = new xoopsFormHidden("decue_" . $fid . "_" . $entry . "_" . $element_id, 1);
            print $cueElement->render();
            if (is_array($thisHiddenElement)) {
                // could happen for checkboxes
                foreach ($thisHiddenElement as $thisIndividualHiddenElement) {
                    if (is_object($thisIndividualHiddenElement)) {
                        print $thisIndividualHiddenElement->render() . "\n";
                    }
                }
            } elseif (is_object($thisHiddenElement)) {
                print $thisHiddenElement->render() . "\n";
            }
            return "hidden";
        }
    } else {
        return "not_allowed";
    }
}