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;
 }
 function constructElement($form_ele_id, $ele_value, $entry, $isDisabled = false, $screen = null)
 {
     if (strstr(getCurrentURL(), "printview.php")) {
         $isDisabled = true;
         // disabled all elements if we're on the printable view
     }
     global $xoopsUser, $xoopsModuleConfig, $separ, $myts;
     $myts =& MyTextSanitizer::getInstance();
     // $form_ele_id contains the ele_id of the current link select box, but we have to remove "ele_" from the front of it.
     //print "form_ele_id: $form_ele_id<br>"; // debug code
     if (strstr($form_ele_id, "de_")) {
         // display element uses a slightly different element name so it can be distinguished on subsequent page load from regular elements...THIS IS NOT TRUE/NECESSARY ANYMORE SINCE FORMULIZE 3, WHERE ALL ELEMENTS ARE DISPLAY ELEMENTS
         $true_ele_id = str_replace("de_" . $this->_ele->getVar('id_form') . "_" . $entry . "_", "", $form_ele_id);
         $displayElementInEffect = true;
     } else {
         $true_ele_id = str_replace("ele_", "", $form_ele_id);
         $displayElementInEffect = false;
     }
     // added July 6 2005.
     if (!$xoopsModuleConfig['delimeter']) {
         // assume that we're accessing a form from outside the Formulize module, therefore the Formulize delimiter setting is not available, so we have to query for it directly.
         global $xoopsDB;
         $delimq = q("SELECT conf_value FROM " . $xoopsDB->prefix("config") . ", " . $xoopsDB->prefix("modules") . " WHERE " . $xoopsDB->prefix("modules") . ".mid=" . $xoopsDB->prefix("config") . ".conf_modid AND " . $xoopsDB->prefix("modules") . ".dirname=\"formulize\" AND " . $xoopsDB->prefix("config") . ".conf_name=\"delimeter\"");
         $delimSetting = $delimq[0]['conf_value'];
     } else {
         $delimSetting = $xoopsModuleConfig['delimeter'];
     }
     $customElementHasData = false;
     $id_form = $this->_ele->getVar('id_form');
     $ele_caption = $this->_ele->getVar('ele_caption', 'e');
     $ele_caption = preg_replace('/\\{SEPAR\\}/', '', $ele_caption);
     // $ele_caption = stripslashes($ele_caption);
     // next line commented out to accomodate passing of ele_value from index.php
     // $ele_value = $this->_ele->getVar('ele_value');
     $ele_type = $this->_ele->getVar('ele_type');
     // call the text sanitizer, first try to convert HTML chars, and if there were no conversions, then do a textarea conversion to automatically make links clickable
     $ele_caption = trans($ele_caption);
     $htmlCaption = htmlspecialchars_decode($myts->undoHtmlSpecialChars($ele_caption));
     // do twice, because we need to handle &amp;lt; and other stupid stuff...do first time through XOOPS myts just because it might be doing a couple extra things that are useful...can probably just use PHP's own filter twice, not too big a deal
     if ($htmlCaption == $ele_caption) {
         $ele_caption = $myts->displayTarea($ele_caption);
     } else {
         $ele_caption = $htmlCaption;
     }
     $ele_caption = $this->formulize_replaceCurlyBracketVariables($ele_caption, $entry, $id_form);
     // ele_desc added June 6 2006 -- jwe
     $ele_desc = $this->_ele->getVar('ele_desc', "f");
     // the f causes no stupid reformatting by the ICMS core to take place
     // determine the entry owner
     if ($entry != "new") {
         $owner = getEntryOwner($entry, $id_form);
     } else {
         $owner = $xoopsUser ? $xoopsUser->getVar('uid') : 0;
     }
     // setup the previous entry UI if necessary -- this is an option that can be specified for certain screens
     $previousEntryUI = "";
     if ($screen and $ele_type != "derived") {
         if ($screen->getVar('paraentryform') > 0) {
             $previousEntryUI = $this->formulize_setupPreviousEntryUI($screen, $true_ele_id, $ele_type, $owner, $displayElementInEffect, $entry, $this->_ele->getVar('ele_handle'), $this->_ele->getVar('id_form'));
         }
     }
     $form_handler = xoops_getmodulehandler('forms', 'formulize');
     $formObject = $form_handler->get($id_form);
     switch ($ele_type) {
         case 'derived':
             if ($entry != "new") {
                 $form_ele = new xoopsFormLabel($this->_ele->getVar('ele_caption'), formulize_numberFormat($ele_value[5], $this->_ele->getVar('ele_handle')));
                 $form_ele->setDescription(html_entity_decode($ele_desc, ENT_QUOTES));
             } else {
                 $form_ele = new xoopsFormLabel($this->_ele->getVar('ele_caption'), _formulize_VALUE_WILL_BE_CALCULATED_AFTER_SAVE);
                 $form_ele->setDescription(html_entity_decode($ele_desc, ENT_QUOTES));
             }
             break;
         case 'ib':
             if (get_magic_quotes_gpc()) {
                 $ele_value[0] = stripslashes($ele_value[0]);
             }
             if (trim($ele_value[0]) == "") {
                 $ele_value[0] = $ele_caption;
             }
             if (strstr($ele_value[0], "\$value=") or strstr($ele_value[0], "\$value =")) {
                 $form_id = $id_form;
                 $entry_id = $entry;
                 $entryData = $this->formulize_getCachedEntryData($id_form, $entry);
                 $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] = $this->formulize_replaceCurlyBracketVariables($ele_value[0], $entry, $id_form);
             $form_ele = $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)
             break;
         case 'text':
             $ele_value[2] = stripslashes($ele_value[2]);
             //        $ele_value[2] = $myts->displayTarea($ele_value[2]); // commented by jwe 12/14/04 so that info displayed for viewing in a form box does not contain HTML formatting
             $ele_value[2] = getTextboxDefault($ele_value[2], $id_form, $entry);
             //if placeholder value is set
             if ($ele_value[11]) {
                 $placeholder = $ele_value[2];
                 $ele_value[2] = "";
             }
             if (!strstr(getCurrentURL(), "printview.php")) {
                 // nmc 2007.03.24 - added
                 $form_ele = new XoopsFormText($ele_caption, $form_ele_id, $ele_value[0], $ele_value[1], $ele_value[2]);
             } else {
                 // nmc 2007.03.24 - added
                 $form_ele = new XoopsFormLabel($ele_caption, formulize_numberFormat($ele_value[2], $this->_ele->getVar('ele_handle')));
                 // nmc 2007.03.24 - added
             }
             //if placeholder value is set
             if ($ele_value[11]) {
                 $form_ele->setExtra("placeholder='" . $placeholder . "'");
             }
             //if numbers-only option is set
             if ($ele_value[3]) {
                 $form_ele->setExtra("class='numbers-only-textbox'");
             }
             // if required unique option is set, create validation javascript that will ask the database if the value is unique or not
             if ($ele_value[9]) {
                 $eltname = $form_ele_id;
                 $eltcaption = $ele_caption;
                 $eltmsg = empty($eltcaption) ? sprintf(_FORM_ENTER, $eltname) : sprintf(_FORM_ENTER, $eltcaption);
                 $eltmsg = str_replace('"', '\\"', stripslashes($eltmsg));
                 $eltmsgUnique = empty($eltcaption) ? sprintf(_formulize_REQUIRED_UNIQUE, $eltname) : sprintf(_formulize_REQUIRED_UNIQUE, $eltcaption);
                 if ($this->_ele->getVar('ele_req')) {
                     // need to manually handle required setting, since only one validation routine can run for an element, so we need to include required checking in this unique checking routine, if the user selected required too
                     $form_ele->customValidationCode[] = "\nif ( myform.{$eltname}.value == '' ) {\n";
                     $form_ele->customValidationCode[] = "window.alert(\"{$eltmsg}\");\n myform.{$eltname}.focus();\n return false;\n";
                     $form_ele->customValidationCode[] = "}\n";
                 }
                 $form_ele->customValidationCode[] = "if(formulize_xhr_returned_check_for_unique_value != 'notreturned') {\n";
                 // a value has already been returned from xhr, so let's check that out...
                 $form_ele->customValidationCode[] = "if(formulize_xhr_returned_check_for_unique_value != 'valuenotfound') {\n";
                 // request has come back, form has been resubmitted, but the check turned up postive, ie: value is not unique, so we have to halt submission , and reset the check for unique flag so we can check again when the user has typed again and is ready to submit
                 $form_ele->customValidationCode[] = "window.alert(\"{$eltmsgUnique}\");\n";
                 $form_ele->customValidationCode[] = "formulize_xhr_returned_check_for_unique_value = 'notreturned'\n";
                 $form_ele->customValidationCode[] = "myform.{$eltname}.focus();\n return false;\n";
                 $form_ele->customValidationCode[] = "}\n";
                 $form_ele->customValidationCode[] = "} else {\n";
                 // do not submit the form, just send off the request, which will trigger a resubmission after setting the returned flag above to true so that we won't send again on resubmission
                 $form_ele->customValidationCode[] = "\nvar formulize_xhr_params = []\n";
                 $form_ele->customValidationCode[] = "formulize_xhr_params[0] = myform.{$eltname}.value;\n";
                 $form_ele->customValidationCode[] = "formulize_xhr_params[1] = " . $this->_ele->getVar('ele_id') . ";\n";
                 $xhr_entry_to_send = is_numeric($entry) ? $entry : 0;
                 $form_ele->customValidationCode[] = "formulize_xhr_params[2] = " . $xhr_entry_to_send . ";\n";
                 $form_ele->customValidationCode[] = "formulize_xhr_send('check_for_unique_value', formulize_xhr_params);\n";
                 $form_ele->customValidationCode[] = "return false;\n";
                 $form_ele->customValidationCode[] = "}\n";
             } elseif ($this->_ele->getVar('ele_req') and !$isDisabled) {
                 $eltname = $form_ele_id;
                 $eltcaption = $ele_caption;
                 $eltmsg = empty($eltcaption) ? sprintf(_FORM_ENTER, $eltname) : sprintf(_FORM_ENTER, $eltcaption);
                 $eltmsg = str_replace('"', '\\"', stripslashes($eltmsg));
                 $form_ele->customValidationCode[] = "if (myform.{$eltname}.value == \"\") { window.alert(\"{$eltmsg}\"); myform.{$eltname}.focus(); return false; }";
             }
             break;
         case 'textarea':
             $ele_value[0] = stripslashes($ele_value[0]);
             //        $ele_value[0] = $myts->displayTarea($ele_value[0]); // commented by jwe 12/14/04 so that info displayed for viewing in a form box does not contain HTML formatting
             $ele_value[0] = getTextboxDefault($ele_value[0], $id_form, $entry);
             if (!strstr(getCurrentURL(), "printview.php") and !$isDisabled) {
                 // nmc 2007.03.24 - added
                 if (isset($ele_value['use_rich_text']) and $ele_value['use_rich_text']) {
                     include_once XOOPS_ROOT_PATH . "/class/xoopsform/formeditor.php";
                     $form_ele = new XoopsFormEditor($ele_caption, 'FCKeditor', $editor_configs = array("name" => $form_ele_id, "value" => $ele_value[0]), $noHtml = false, $OnFailure = "");
                     $eltname = $form_ele_id;
                     $eltcaption = $ele_caption;
                     $eltmsg = empty($eltcaption) ? sprintf(_FORM_ENTER, $eltname) : sprintf(_FORM_ENTER, $eltcaption);
                     $eltmsg = str_replace('"', '\\"', stripslashes($eltmsg));
                     $form_ele->customValidationCode[] = "\n var FCKGetInstance = FCKeditorAPI.GetInstance('{$form_ele_id}');\n";
                     $form_ele->customValidationCode[] = "var getText = FCKGetInstance.EditorDocument.body.innerHTML; \n";
                     $form_ele->customValidationCode[] = "var StripTag = getText.replace(/(<([^>]+)>)/ig,''); \n";
                     $form_ele->customValidationCode[] = "if(StripTag=='' || StripTag=='&nbsp;') {\n";
                     $form_ele->customValidationCode[] = "window.alert(\"{$eltmsg}\");\n FCKGetInstance.Focus();\n return false;\n";
                     $form_ele->customValidationCode[] = "}\n";
                     $GLOBALS['formulize_fckEditors'] = true;
                 } else {
                     $form_ele = new XoopsFormTextArea($ele_caption, $form_ele_id, $ele_value[0], $ele_value[1], $ele_value[2]);
                 }
             } else {
                 // nmc 2007.03.24 - added
                 $form_ele = new XoopsFormLabel($ele_caption, str_replace("\n", "<br>", undoAllHTMLChars($ele_value[0], ENT_QUOTES)));
                 // nmc 2007.03.24 - added
             }
             break;
         case 'areamodif':
             if (strstr($ele_value[0], "\$value=") or strstr($ele_value[0], "\$value =")) {
                 $form_id = $id_form;
                 $entry_id = $entry;
                 $entryData = $this->formulize_getCachedEntryData($id_form, $entry);
                 $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] = $this->formulize_replaceCurlyBracketVariables($ele_value[0], $entry, $id_form);
             $form_ele = new XoopsFormLabel($ele_caption, $ele_value[0]);
             break;
         case 'select':
             if (is_string($ele_value[2]) and strstr($ele_value[2], "#*=:*")) {
                 // 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();
                 global $xoopsDB;
                 $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, $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]) {
                     $t4_ele_value = $this->_ele->getVar('ele_value');
                     if ($t4_ele_value[1]) {
                         // allows multiple selections
                         $restrictSQL = " AND (\n\t\t\t\t\t\tNOT EXISTS (\n\t\t\t\t\t\tSELECT 1 FROM " . $xoopsDB->prefix("formulize_" . $formObject->getVar('form_handle')) . " AS t4 WHERE t4.`" . $this->_ele->getVar('ele_handle') . "` LIKE CONCAT( '%,', t1.`entry_id` , ',%' ) AND t4.entry_id != " . intval($entry);
                     } else {
                         $restrictSQL = " AND (\n                                                    NOT EXISTS (\n                                                    SELECT 1 FROM " . $xoopsDB->prefix("formulize_" . $formObject->getVar('form_handle')) . " AS t4 WHERE t4.`" . $this->_ele->getVar('ele_handle') . "` = t1.`entry_id` AND t4.entry_id != " . intval($entry);
                         $restrictSQL .= $this->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                                                    SELECT 1 FROM " . $xoopsDB->prefix("formulize_" . $formObject->getVar('form_handle')) . " AS t4 WHERE t4.`" . $this->_ele->getVar('ele_handle') . "` = t1.`entry_id` AND t4.entry_id = " . intval($entry);
                     }
                     $restrictSQL .= $this->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\t\t\tSELECT 1 FROM " . $xoopsDB->prefix("formulize_" . $formObject->getVar('form_handle')) . " AS t4 WHERE t4.`" . $this->_ele->getVar('ele_handle') . "` LIKE CONCAT( '%,', t1.`entry_id` , ',%' ) AND t4.entry_id = " . intval($entry);
                     $restrictSQL .= $this->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 no extra elements are selected for display as a form element, then display the linked element
                 if (0 == count($ele_value[EV_MULTIPLE_FORM_COLUMNS]) or $ele_value[EV_MULTIPLE_FORM_COLUMNS][0] == 'none') {
                     $linked_columns = array($boxproperties[1]);
                 } else {
                     $linked_columns = convertElementIdsToElementHandles($ele_value[EV_MULTIPLE_FORM_COLUMNS], $sourceFormObject->getVar('id_form'));
                     // remove empty entries, which can happen if the "use the linked field selected above" option is selected
                     $linked_columns = array_filter($linked_columns);
                 }
                 if (is_array($linked_columns)) {
                     $select_column = "t1.`" . implode("`, t1.`", $linked_columns) . "`";
                 } else {
                     $select_column = "t1.`{$linked_columns}`";
                     // in this case, it's just one linked column
                 }
                 // if there is a groups filter, then join to the group ownership table
                 $extra_clause = "";
                 if ($pgroupsfilter) {
                     $extra_clause = ", " . $xoopsDB->prefix("formulize_entry_owner_groups") . " AS t2 {$parentFormFrom} WHERE {$pgroupsfilter}";
                 } else {
                     $extra_clause = " {$parentFormFrom} WHERE t1.entry_id>0";
                 }
                 $sourceValuesQ = "SELECT t1.entry_id, " . $select_column . " FROM " . $xoopsDB->prefix("formulize_" . $sourceFormObject->getVar('form_handle')) . " AS t1" . $extra_clause . "{$conditionsfilter} {$conditionsfilter_oom} {$restrictSQL}" . "GROUP BY t1.entry_id {$sortOrderClause}";
                 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 == "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($ele_caption, $form_ele_id, $defaultSelected, $ele_value[0], $ele_value[1]);
                     $form_ele->setExtra("onchange=\"javascript:formulizechanged=1;\" jquerytag='{$form_ele_id}'");
                     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) {
                         $linked_column_count = count($linked_columns);
                         while ($rowlinkedvaluesq = $xoopsDB->fetchRow($reslinkedvaluesq)) {
                             $linked_column_values = array();
                             foreach (range(1, $linked_column_count) as $linked_column_index) {
                                 if ($rowlinkedvaluesq[$linked_column_index] === "") {
                                     $linked_column_values[] = "";
                                 } else {
                                     if ($sourceElementObject->isLinked) {
                                         $linked_value = prepvalues($rowlinkedvaluesq[$linked_column_index], $boxproperties[1], $rowlinkedvaluesq[0]);
                                         $linked_column_values[] = $linked_value[0];
                                     } else {
                                         $linked_column_values[] = strip_tags(trim($rowlinkedvaluesq[$linked_column_index]));
                                     }
                                 }
                             }
                             $linkedElementOptions[$rowlinkedvaluesq[0]] = implode(" - ", $linked_column_values);
                         }
                     }
                     $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_");
                         $maxLength = 10;
                         $the_values = array();
                         asort($linkedElementOptions);
                         foreach ($linkedElementOptions as $id => $text) {
                             $the_values[$id] = trans($text);
                             $thisTextLength = strlen($text);
                             $maxLength = $thisTextLength > $maxLength ? $thisTextLength : $maxLength;
                         }
                         file_put_contents(XOOPS_ROOT_PATH . "/cache/{$cachedLinkedOptionsFileName}", "<?php\n\${$cachedLinkedOptionsFileName} = " . var_export($the_values, true) . ";\n");
                         $cachedSourceValuesAutocompleteFile[$sourceValuesQ] = $cachedLinkedOptionsFileName;
                         $cachedSourceValuesAutocompleteLength[$sourceValuesQ] = $maxLength;
                     }
                 }
                 if ($boxproperties[2]) {
                     $default_value = $boxproperties[2];
                     $default_value_user = $cachedSourceValuesQ[$sourceValuesQ][$boxproperties[2]];
                 }
                 // if we're rendering an autocomplete box
                 if (!$isDisabled and $ele_value[8] == 1) {
                     $renderedComboBox = $this->formulize_renderQuickSelect($form_ele_id, $cachedSourceValuesAutocompleteFile[$sourceValuesQ], $default_value, $default_value_user, $cachedSourceValuesAutocompleteLength[$sourceValuesQ]);
                     $form_ele = new xoopsFormLabel($ele_caption, $renderedComboBox);
                     $form_ele->setDescription(html_entity_decode($ele_desc, ENT_QUOTES));
                 } elseif ($isDisabled) {
                     $disabledOutputText[] = $default_value_user;
                 }
                 // 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] ? $form_ele_id . "[]" : $form_ele_id;
                             $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($ele_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 {
                 $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 (is_array($ele_value[2]) and $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();
                         $declaredUsersGroups = $groups;
                         if ($ele_value[3]) {
                             $scopegroups = explode(",", $ele_value[3]);
                             if (!in_array("all", $scopegroups)) {
                                 $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], $ele_value[4], $declaredUsersGroups);
                         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($ele_caption, $form_ele_id, $selected, $final_size, $ele_value[1]);
                 $form_ele1->setExtra("onchange=\"javascript:formulizechanged=1;\" jquerytag='{$form_ele_id}'");
                 // must check the options for uitext before adding to the element -- aug 25, 2007
                 foreach ($options as $okey => $ovalue) {
                     $options[$okey] = formulize_swapUIText($ovalue, $this->_ele->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
                     $cachedLinkedOptionsFileName = "formulize_Options_" . str_replace(".", "", microtime(true));
                     formulize_scandirAndClean(XOOPS_ROOT_PATH . "/cache/", "formulize_Options_");
                     $maxLength = 10;
                     $the_values = array();
                     foreach ($options as $id => $text) {
                         $the_values[$id] = trans($text);
                         $thisTextLength = strlen($the_values[$id]);
                         $maxLength = $thisTextLength > $maxLength ? $thisTextLength : $maxLength;
                     }
                     file_put_contents(XOOPS_ROOT_PATH . "/cache/{$cachedLinkedOptionsFileName}", "<?php\n\${$cachedLinkedOptionsFileName} = " . var_export($the_values, true) . ";\n");
                     $defaultSelected = is_array($selected) ? $selected[0] : $selected;
                     $renderedComboBox = $this->formulize_renderQuickSelect($form_ele_id, $cachedLinkedOptionsFileName, $defaultSelected, $options[$defaultSelected], $maxLength);
                     $form_ele2 = new xoopsFormLabel($ele_caption, $renderedComboBox);
                     $renderedElement = $form_ele2->render();
                 } else {
                     // normal element
                     $renderedElement = $form_ele1->render();
                 }
                 $form_ele = new XoopsFormLabel($ele_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
             // set required validation code
             if ($this->_ele->getVar('ele_req') and !$isDisabled) {
                 $eltname = $form_ele_id;
                 $eltcaption = $ele_caption;
                 $eltmsg = empty($eltcaption) ? sprintf(_FORM_ENTER, $eltname) : sprintf(_FORM_ENTER, $eltcaption);
                 $eltmsg = str_replace('"', '\\"', stripslashes($eltmsg));
                 if ($ele_value[8] == 1) {
                     // Has been edited in order to not allow the user to submit a form when "No match found" or "Choose an Option" is selected from the quickselect box.
                     $form_ele->customValidationCode[] = "\nif ( myform.{$eltname}.value == '' || myform.{$eltname}.value == 'none'  ) {\n window.alert(\"{$eltmsg}\");\n myform.{$eltname}_user.focus();\n return false;\n }\n";
                 } elseif ($ele_value[0] == 1) {
                     $form_ele->customValidationCode[] = "\nif ( myform.{$eltname}.options[0].selected ) {\n window.alert(\"{$eltmsg}\");\n myform.{$eltname}.focus();\n return false;\n }\n";
                 } elseif ($ele_value[0] > 1) {
                     $form_ele->customValidationCode[] = "selection = false;\n";
                     $form_ele->customValidationCode[] = "\nfor(i=0;i<myform.{$eltname}.options.length;i++) {\n";
                     $form_ele->customValidationCode[] = "if(myform.{$eltname}.options[i].selected) {\n";
                     $form_ele->customValidationCode[] = "selection = true;\n";
                     $form_ele->customValidationCode[] = "}\n";
                     $form_ele->customValidationCode[] = "}\n";
                     $form_ele->customValidationCode[] = "if(selection == false) { window.alert(\"{$eltmsg}\");\n myform.{$eltname}.focus();\n return false;\n }\n";
                 }
             }
             if ($isDisabled) {
                 $isDisabled = false;
                 // disabled stuff handled here in element, so don't invoke generic disabled handling below (which is only for textboxes and their variations)
             }
             break;
         case 'checkbox':
             $selected = array();
             $options = array();
             $disabledHiddenValue = array();
             $disabledHiddenValues = "";
             $disabledOutputText = array();
             $opt_count = 1;
             while ($i = each($ele_value)) {
                 $options[$opt_count] = $myts->stripSlashesGPC($i['key']);
                 if ($i['value'] > 0) {
                     $selected[] = $opt_count;
                     $disabledHiddenValue[] = "<input type=hidden name=\"" . $form_ele_id . "[]\" value=\"{$opt_count}\">";
                 }
                 $opt_count++;
             }
             if ($this->_ele->getVar('ele_delim') != "") {
                 $delimSetting = $this->_ele->getVar('ele_delim');
             }
             $delimSetting =& $myts->undoHtmlSpecialChars($delimSetting);
             if ($delimSetting == "br") {
                 $delimSetting = "<br />";
             }
             $hiddenOutOfRangeValuesToWrite = array();
             switch ($delimSetting) {
                 case 'space':
                     $form_ele1 = new XoopsFormCheckBox($ele_caption, $form_ele_id, $selected);
                     $counter = 0;
                     // counter used for javascript that works with 'Other' box
                     while ($o = each($options)) {
                         $o = formulize_swapUIText($o, $this->_ele->getVar('ele_uitext'));
                         $other = $this->optOther($o['value'], $form_ele_id, $entry, $counter, true);
                         if ($other != false) {
                             $form_ele1->addOption($o['key'], _formulize_OPT_OTHER . $other);
                             if (in_array($o['key'], $selected)) {
                                 $disabledOutputText[] = _formulize_OPT_OTHER . $other;
                             }
                         } else {
                             $form_ele1->addOption($o['key'], $o['value']);
                             if (in_array($o['key'], $selected)) {
                                 $disabledOutputText[] = $o['value'];
                             }
                             if (strstr($o['value'], _formulize_OUTOFRANGE_DATA)) {
                                 $hiddenOutOfRangeValuesToWrite[$o['key']] = str_replace(_formulize_OUTOFRANGE_DATA, "", $o['value']);
                                 // if this is an out of range value, grab the actual value so we can stick it in a hidden element later
                             }
                         }
                         $counter++;
                     }
                     $form_ele1->setExtra(" onchange=\"javascript:formulizechanged=1;\" jquerytag=\"{$form_ele_id}\" ");
                     break;
                 default:
                     $form_ele1 = new XoopsFormElementTray($ele_caption, $delimSetting);
                     $counter = 0;
                     // counter used for javascript that works with 'Other' box
                     while ($o = each($options)) {
                         $o = formulize_swapUIText($o, $this->_ele->getVar('ele_uitext'));
                         $other = $this->optOther($o['value'], $form_ele_id, $entry, $counter, true);
                         $t = new XoopsFormCheckBox('', $form_ele_id . '[]', $selected, $delimSetting);
                         if ($other != false) {
                             $t->addOption($o['key'], _formulize_OPT_OTHER . $other);
                             if (in_array($o['key'], $selected)) {
                                 $disabledOutputText[] = _formulize_OPT_OTHER . $other;
                             }
                         } else {
                             $t->addOption($o['key'], $o['value']);
                             if (in_array($o['key'], $selected)) {
                                 $disabledOutputText[] = $o['value'];
                             }
                             if (strstr($o['value'], _formulize_OUTOFRANGE_DATA)) {
                                 $hiddenOutOfRangeValuesToWrite[$o['key']] = str_replace(_formulize_OUTOFRANGE_DATA, "", $o['value']);
                                 // if this is an out of range value, grab the actual value so we can stick it in a hidden element later
                             }
                         }
                         $t->setExtra(" onchange=\"javascript:formulizechanged=1;\" jquerytag=\"{$form_ele_id}\" ");
                         $form_ele1->addElement($t);
                         unset($t);
                         $counter++;
                     }
                     break;
             }
             $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);
             } else {
                 $renderedElement = $form_ele1->render();
             }
             $form_ele = new XoopsFormLabel($ele_caption, "{$renderedElement}\n{$renderedHoorvs}\n{$disabledHiddenValues}\n");
             $form_ele->setDescription(html_entity_decode($ele_desc, ENT_QUOTES));
             if ($this->_ele->getVar('ele_req') and !$isDisabled) {
                 $eltname = $form_ele_id;
                 $eltcaption = $ele_caption;
                 $eltmsg = empty($eltcaption) ? sprintf(_FORM_ENTER, $eltname) : sprintf(_FORM_ENTER, $eltcaption);
                 $eltmsg = str_replace('"', '\\"', stripslashes($eltmsg));
                 $form_ele->customValidationCode[] = "selection = true;\n";
                 $form_ele->customValidationCode[] = "checkboxes = \$('[jquerytag={$eltname}]:checked');\n";
                 // need to use this made up attribute here, because there is no good way to select the checkboxes using the name or anything else that XOOPS/Impress is giving us!!
                 $form_ele->customValidationCode[] = "if(checkboxes.length == 0) { window.alert(\"{$eltmsg}\");\n \$('[jquerytag={$eltname}]').focus();\n return false;\n }\n";
             }
             if ($isDisabled) {
                 $isDisabled = false;
                 // disabled stuff handled here in element, so don't invoke generic disabled handling below (which is only for textboxes and their variations)
             }
             break;
         case 'radio':
         case 'yn':
             $selected = '';
             $disabledHiddenValue = "";
             $options = array();
             $opt_count = 1;
             while ($i = each($ele_value)) {
                 switch ($ele_type) {
                     case 'radio':
                         $options[$opt_count] = $myts->stripSlashesGPC($i['key']);
                         $options[$opt_count] = $myts->displayTarea($options[$opt_count]);
                         break;
                     case 'yn':
                         $options[$opt_count] = constant($i['key']);
                         $options[$opt_count] = $myts->stripSlashesGPC($options[$opt_count]);
                         break;
                 }
                 if ($i['value'] > 0) {
                     $selected = $opt_count;
                 }
                 $opt_count++;
             }
             if ($this->_ele->getVar('ele_delim') != "") {
                 $delimSetting = $this->_ele->getVar('ele_delim');
             }
             $delimSetting =& $myts->undoHtmlSpecialChars($delimSetting);
             if ($delimSetting == "br") {
                 $delimSetting = "<br />";
             }
             $hiddenOutOfRangeValuesToWrite = array();
             switch ($delimSetting) {
                 case 'space':
                     $form_ele1 = new XoopsFormRadio('', $form_ele_id, $selected);
                     $counter = 0;
                     while ($o = each($options)) {
                         $o = formulize_swapUIText($o, $this->_ele->getVar('ele_uitext'));
                         $other = $this->optOther($o['value'], $form_ele_id, $entry, $counter);
                         if ($other != false) {
                             $form_ele1->addOption($o['key'], _formulize_OPT_OTHER . $other);
                             if ($o['key'] == $selected) {
                                 $disabledOutputText = _formulize_OPT_OTHER . $other;
                             }
                         } else {
                             $o['value'] = get_magic_quotes_gpc() ? stripslashes($o['value']) : $o['value'];
                             $form_ele1->addOption($o['key'], $o['value']);
                             if ($o['key'] == $selected) {
                                 $disabledOutputText = $o['value'];
                             }
                             if (strstr($o['value'], _formulize_OUTOFRANGE_DATA)) {
                                 $hiddenOutOfRangeValuesToWrite[$o['key']] = str_replace(_formulize_OUTOFRANGE_DATA, "", $o['value']);
                                 // if this is an out of range value, grab the actual value so we can stick it in a hidden element later
                             }
                         }
                         $counter++;
                     }
                     $form_ele1->setExtra("onchange=\"javascript:formulizechanged=1;\"");
                     break;
                 default:
                     $form_ele1 = new XoopsFormElementTray('', $delimSetting);
                     $counter = 0;
                     while ($o = each($options)) {
                         $o = formulize_swapUIText($o, $this->_ele->getVar('ele_uitext'));
                         $t = new XoopsFormRadio('', $form_ele_id, $selected);
                         $other = $this->optOther($o['value'], $form_ele_id, $entry, $counter);
                         if ($other != false) {
                             $t->addOption($o['key'], _formulize_OPT_OTHER . "</label><label>{$other}");
                             // epic hack to terminate radio button's label so it doesn't include the clickable 'other' box!!
                             if ($o['key'] == $selected) {
                                 $disabledOutputText = _formulize_OPT_OTHER . $other;
                             }
                         } else {
                             $o['value'] = get_magic_quotes_gpc() ? stripslashes($o['value']) : $o['value'];
                             $t->addOption($o['key'], $o['value']);
                             if ($o['key'] == $selected) {
                                 $disabledOutputText = $o['value'];
                             }
                             if (strstr($o['value'], _formulize_OUTOFRANGE_DATA)) {
                                 $hiddenOutOfRangeValuesToWrite[$o['key']] = str_replace(_formulize_OUTOFRANGE_DATA, "", $o['value']);
                                 // if this is an out of range value, grab the actual value so we can stick it in a hidden element later
                             }
                         }
                         $t->setExtra("onchange=\"javascript:formulizechanged=1;\"");
                         $form_ele1->addElement($t);
                         unset($t);
                         $counter++;
                     }
                     break;
             }
             $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) {
                 $disabledHiddenValue = "<input type=hidden name=\"" . $form_ele_id . "\" value=\"{$selected}\">\n";
                 $renderedElement = $disabledOutputText;
                 // just text for disabled elements
             } else {
                 $renderedElement = $form_ele1->render();
             }
             $form_ele = new XoopsFormLabel($ele_caption, "{$renderedElement}\n{$renderedHoorvs}\n{$disabledHiddenValue}\n");
             $form_ele->setDescription(html_entity_decode($ele_desc, ENT_QUOTES));
             if ($this->_ele->getVar('ele_req') and !$isDisabled) {
                 $eltname = $form_ele_id;
                 $eltcaption = $ele_caption;
                 $eltmsg = empty($eltcaption) ? sprintf(_FORM_ENTER, $eltname) : sprintf(_FORM_ENTER, $eltcaption);
                 $eltmsg = str_replace('"', '\\"', stripslashes($eltmsg));
                 $form_ele->customValidationCode[] = "selection = false;\n";
                 $form_ele->customValidationCode[] = "if(myform.{$eltname}.length) {\n";
                 $form_ele->customValidationCode[] = "for(var i=0;i<myform.{$eltname}.length;i++){\n";
                 $form_ele->customValidationCode[] = "if(myform.{$eltname}[i].checked){\n";
                 $form_ele->customValidationCode[] = "selection = true;\n";
                 $form_ele->customValidationCode[] = "}\n";
                 $form_ele->customValidationCode[] = "}\n";
                 $form_ele->customValidationCode[] = "}\n";
                 $form_ele->customValidationCode[] = "if(selection == false) { window.alert(\"{$eltmsg}\");\n myform.{$eltname}.focus();\n return false;\n }\n";
             }
             if ($isDisabled) {
                 $isDisabled = false;
                 // disabled stuff handled here in element, so don't invoke generic disabled handling below (which is only for textboxes and their variations)
             }
             break;
         case 'date':
             // if there's no value (ie: it's blank) ... OR it's the default value because someone submitted a date field without actually specifying a date, that last part added by jwe 10/23/04
             if ($ele_value[0] == "" or $ele_value[0] == "YYYY-mm-dd") {
                 $form_ele = new XoopsFormTextDateSelect($ele_caption, $form_ele_id, 15, "");
                 $form_ele->setExtra(" onchange=\"javascript:formulizechanged=1;\" jquerytag=\"{$form_ele_id}\" ");
             } else {
                 $form_ele = new XoopsFormTextDateSelect($ele_caption, $form_ele_id, 15, getDateElementDefault($ele_value[0]));
                 $form_ele->setExtra(" onchange=\"javascript:formulizechanged=1;\" jquerytag=\"{$form_ele_id}\" ");
             }
             // end of check to see if the default setting is for real
             // added validation code - sept 5 2007 - jwe
             if ($this->_ele->getVar('ele_req') and !$isDisabled) {
                 $eltname = $form_ele_id;
                 $eltcaption = $ele_caption;
                 $eltmsg = empty($eltcaption) ? sprintf(_FORM_ENTER, $eltname) : sprintf(_FORM_ENTER, $eltcaption);
                 $eltmsg = str_replace('"', '\\"', stripslashes($eltmsg));
                 // parseInt() is used to determine if the element value contains a number
                 // Date.parse() would be better, except that it will fail for dd-mm-YYYY format, ie: 22-11-2013
                 $form_ele->customValidationCode[] = "\nif (isNaN(parseInt(myform.{$eltname}.value))) {\n window.alert(\"{$eltmsg}\");\n myform.{$eltname}.focus();\n return false;\n }\n";
             }
             if (!$isDisabled) {
                 $limit_past = (isset($ele_value["date_limit_past"]) and $ele_value["date_limit_past"] != "");
                 $limit_future = (isset($ele_value["date_limit_future"]) and $ele_value["date_limit_future"] != "");
                 if ($limit_past or $limit_future) {
                     $reference_date = time();
                     if ("new" != $entry) {
                         $entryData = $this->formulize_getCachedEntryData($id_form, $entry);
                         $reference_date = strtotime(display($entryData, "creation_date"));
                     }
                     if ($limit_past) {
                         $form_ele->setExtra(" min-date='" . date("Y-m-d", strtotime("-" . max(0, intval($ele_value["date_past_days"])) . " days", $reference_date)) . "' ");
                     }
                     if ($limit_future) {
                         $form_ele->setExtra(" max-date='" . date("Y-m-d", strtotime("+" . max(0, intval($ele_value["date_future_days"])) . " days", $reference_date)) . "' ");
                     }
                     $form_ele->setExtra(" onchange=\"javascript:formulizechanged=1;check_date_limits('{$form_ele_id}');\" onclick=\"javascript:check_date_limits('{$form_ele_id}');\" onblur=\"javascript:check_date_limits('{$form_ele_id}');\" jquerytag=\"{$form_ele_id}\" ");
                 } else {
                     $form_ele->setExtra(" onchange=\"javascript:formulizechanged=1;\" jquerytag=\"{$form_ele_id}\" ");
                 }
             }
             break;
         case 'sep':
             //$ele_value[0] = $myts->displayTarea($ele_value[0]);
             $ele_value[0] = $myts->xoopsCodeDecode($ele_value[0]);
             $form_ele = new XoopsFormLabel($ele_caption, $ele_value[0]);
             break;
         case 'upload':
             $form_ele = new XoopsFormFile($ele_caption, $form_ele_id, $ele_value[1]);
             break;
             /*
              * Hack by F�lix<INBOX International>
              * Adding colorpicker form element
              */
         /*
          * Hack by F�lix<INBOX International>
          * Adding colorpicker form element
          */
         case 'colorpick':
             if ($ele_value[0] == "") {
                 //print "Bad date";
                 $form_ele = new XoopsFormColorPicker($ele_caption, $form_ele_id, "");
             } else {
                 //print "good date";
                 $form_ele = new XoopsFormColorPicker($ele_caption, $form_ele_id, $ele_value[0]);
             }
             // end of check to see if the default setting is for real
             break;
             /*
              * End of Hack by F�lix<INBOX International>
              * Adding colorpicker form element
              */
         /*
          * End of Hack by F�lix<INBOX International>
          * Adding colorpicker form element
          */
         default:
             if (file_exists(XOOPS_ROOT_PATH . "/modules/formulize/class/" . $ele_type . "Element.php")) {
                 $elementTypeHandler = xoops_getmodulehandler($ele_type . "Element", "formulize");
                 $form_ele = $elementTypeHandler->render($ele_value, $ele_caption, $form_ele_id, $isDisabled, $this->_ele, $entry, $screen);
                 // $ele_value as passed in here, $caption, name that we use for the element in the markup, flag for whether it's disabled or not, element object, entry id number that this element belongs to, $screen is the screen object that was passed in, if any
                 // if form_ele is an array, then we want to treat it the same as an "insertbreak" element, ie: it's not a real form element object
                 if (is_object($form_ele)) {
                     if (!$isDisabled and ($this->_ele->getVar('ele_req') or $this->_ele->alwaysValidateInputs) and $this->_ele->hasData) {
                         // if it's not disabled, and either a declared required element according to the webmaster, or the element type itself always forces validation...
                         $form_ele->customValidationCode = $elementTypeHandler->generateValidationCode($ele_caption, $form_ele_id, $this->_ele, $entry);
                     }
                     $form_ele->setDescription(html_entity_decode($ele_desc, ENT_QUOTES));
                     $isDisabled = false;
                     // the render method must handle providing a disabled output, so as far as the rest of the logic here goes, the element is not disabled but should be rendered as is
                     $baseCustomElementObject = $elementTypeHandler->create();
                     if ($baseCustomElementObject->hasData) {
                         $customElementHasData = true;
                     }
                 }
             } else {
                 return false;
             }
             break;
     }
     // end element-type case
     if (is_object($form_ele) and !$isDisabled and $this->_ele->hasData) {
         if ($previousEntryUI) {
             $previousEntryUIRendered = "&nbsp;&nbsp;" . $previousEntryUI->render();
         } else {
             $previousEntryUIRendered = "";
         }
         // $ele_type is the type value...only put in a cue for certain kinds of elements, and definitely not for blank subforms
         if (substr($form_ele_id, 0, 9) != "desubform" and ($ele_type == "text" or $ele_type == "textarea" or $ele_type == "select" or $ele_type == "radio" or $ele_type == "checkbox" or $ele_type == "date" or $ele_type == "colorpick" or $ele_type == "yn" or $customElementHasData)) {
             $elementCue = "\n<input type=\"hidden\" id=\"decue_" . trim($form_ele_id, "de_") . "\" name=\"decue_" . trim($form_ele_id, "de_") . "\" value=1>\n";
         } else {
             $elementCue = "";
         }
         $form_ele->setExtra(" onchange=\"javascript:formulizechanged=1;\"");
         // reuse caption, put two spaces between element and previous entry UI
         $form_ele_new = new xoopsFormLabel($form_ele->getCaption(), $form_ele->render() . $previousEntryUIRendered . $elementCue);
         $form_ele_new->formulize_element = $this->_ele;
         if ($ele_desc != "") {
             $ele_desc = html_entity_decode($ele_desc, ENT_QUOTES);
             $ele_desc = $myts->makeClickable($ele_desc);
             $form_ele_new->setDescription($ele_desc);
         }
         $form_ele_new->setName($form_ele_id);
         // need to set this as the name, in case it is required and then the name will be picked up by any "required" checks that get done and used in the required validation javascript for textboxes
         if (!empty($form_ele->customValidationCode)) {
             $form_ele_new->customValidationCode = $form_ele->customValidationCode;
         }
         if ($form_ele->isRequired()) {
             $form_ele_new->setRequired();
         }
         return $form_ele_new;
     } elseif (is_object($form_ele) and $isDisabled and $this->_ele->hasData) {
         // element is disabled
         $form_ele = $this->formulize_disableElement($form_ele, $ele_type, $ele_desc);
         return $form_ele;
     } else {
         // form ele is not an object...and/or has no data.  Happens for IBs and for non-interactive elements, like grids.
         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";
    }
}
function formulize_screenLOEButton($button, $buttonText, $settings, $fid, $frid, $colhandles, $flatcols, $pubstart, $loadOnlyView, $calc_cols, $calc_calcs, $calc_blanks, $calc_grouping, $doNotForceSingle, $lastloaded, $currentview, $endstandard, $pickgroups, $viewoptions, $loadviewname, $advcalc_acid, $screen)
{
    static $importExportCleanupDone = false;
    if ($buttonText) {
        $buttonText = trans($buttonText);
        switch ($button) {
            case "modifyScreenLink":
                return "<a href=" . XOOPS_URL . "/modules/formulize/admin/ui.php?page=screen&sid=" . $screen->getVar('sid') . ">" . $buttonText . "</a>";
                break;
            case "changeColsButton":
                return "<input type=button class=\"formulize_button\" id=\"formulize_{$button}\" name=changecols value='" . $buttonText . "' onclick=\"javascript:showPop('" . XOOPS_URL . "/modules/formulize/include/changecols.php?fid={$fid}&frid={$frid}&cols={$colhandles}');\"></input>";
                break;
            case "calcButton":
                return "<input type=button class=\"formulize_button\" id=\"formulize_{$button}\" name=calculations value='" . $buttonText . "' onclick=\"javascript:showPop('" . XOOPS_URL . "/modules/formulize/include/pickcalcs.php?fid={$fid}&frid={$frid}&calc_cols=" . urlencode($calc_cols) . "&calc_calcs=" . urlencode($calc_calcs) . "&calc_blanks=" . urlencode($calc_blanks) . "&calc_grouping=" . urlencode($calc_grouping) . "&cols=" . urlencode($colhandles) . "&cols=" . urlencode($colhandles) . "');\"></input>";
                break;
            case "advCalcButton":
                // only if any procedures (advanced calculations) are defined for this form
                $procedureHandler = xoops_getmodulehandler('advancedCalculation', 'formulize');
                $procList = $procedureHandler->getList($fid);
                if (is_array($procList) and count($procList) > 0) {
                    return "<input type=button class=\"formulize_button\" id=\"formulize_{$button}\" name=advcalculations value='" . $buttonText . "' onclick=\"javascript:showPop('" . XOOPS_URL . "/modules/formulize/include/pickadvcalcs.php?fid={$fid}&frid={$frid}&{$advcalc_acid}');\"></input>";
                } else {
                    return false;
                }
                break;
            case "advSearchButton":
                $buttonCode = "<input type=button class=\"formulize_button\" id=\"formulize_{$button}\" name=advsearch value='" . $buttonText . "' onclick=\"javascript:showPop('" . XOOPS_URL . "/modules/formulize/include/advsearch.php?fid={$fid}&frid={$frid}";
                foreach ($settings as $k => $v) {
                    if (substr($k, 0, 3) == "as_") {
                        $v = str_replace("'", "&#39;", $v);
                        $v = stripslashes($v);
                        $buttonCode .= "&{$k}=" . urlencode($v);
                    }
                }
                $buttonCode .= "');\"></input>";
                return $buttonCode;
                break;
            case "exportCalcsButton":
                return "<input type=button class=\"formulize_button\" id=\"formulize_{$button}\" name=export value='" . $buttonText . "' onclick=\"javascript:showExport();\"></input>";
                break;
            case "exportButton":
            case "importButton":
                // need to write the query to the cache folder so it can be picked up when needed
                $exportTime = time();
                $queryForExportFile = fopen(XOOPS_ROOT_PATH . "/cache/exportQuery_" . $exportTime . ".formulize_cached_query_for_export", "w");
                fwrite($queryForExportFile, $fid . "\n");
                global $xoopsUser;
                $exportUid = $xoopsUser ? $xoopsUser->getVar('uid') : 0;
                fwrite($queryForExportFile, $exportUid . "\n");
                fwrite($queryForExportFile, $GLOBALS['formulize_queryForExport']);
                fclose($queryForExportFile);
                // cleanup old export files
                if (!$importExportCleanupDone) {
                    formulize_benchmark("before scandir during export/import button creation");
                    formulize_scandirAndClean(XOOPS_ROOT_PATH . "/cache/", "exportQuery");
                    formulize_benchmark("after scandir during export/import button creation. " . count($formulize_export_cache_files) . " files found");
                    $importExportCleanupDone = true;
                }
                if ($button == "exportButton") {
                    return "<input type=button class=\"formulize_button\" id=\"formulize_{$button}\" name=export value='" . $buttonText . "' onclick=\"javascript:showPop('" . XOOPS_URL . "/modules/formulize/include/export.php?fid={$fid}&frid={$frid}&cols={$colhandles}&eq={$exportTime}');\"></input>";
                } else {
                    return "<input type=button class=\"formulize_button\" id=\"formulize_{$button}\" name=impdata value='" . $buttonText . "' onclick=\"javascript:showPop('" . XOOPS_URL . "/modules/formulize/include/import.php?fid={$fid}&eq={$exportTime}');\"></input>";
                }
                break;
            case "addButton":
                $addNewParam = $doNotForceSingle ? "" : "'single'";
                // force the addNew behaviour to single entry unless this button is being used on a single entry form, in which case we don't need to force anything
                return "<input type=button class=\"formulize_button\" id=\"formulize_{$button}\" name=addentry value='" . $buttonText . "' onclick=\"javascript:addNew({$addNewParam});\"></input>";
                break;
            case "addMultiButton":
                return "<input type=button class=\"formulize_button\" id=\"formulize_{$button}\" name=addentry value='" . $buttonText . "' onclick=\"javascript:addNew();\"></input>";
                break;
            case "addProxyButton":
                return "<input type=button class=\"formulize_button\" id=\"formulize_{$button}\" name=addentry value='" . $buttonText . "' onclick=\"javascript:addNew('proxy');\"></input>";
                break;
            case "notifButton":
                return "<input type=button class=\"formulize_button\" id=\"formulize_{$button}\" name=notbutton value='" . $buttonText . "' onclick=\"javascript:showPop('" . XOOPS_URL . "/modules/formulize/include/setnot.php?fid={$fid}');\"></input>";
                break;
            case "cloneButton":
                return "<input type=button class=\"formulize_button\" id=\"formulize_{$button}\" name=clonesel value='" . $buttonText . "' onclick=\"javascript:confirmClone();\"></input>";
                break;
            case "deleteButton":
                return "<input type=button class=\"formulize_button\" id=\"formulize_{$button}\" name=deletesel value='" . $buttonText . "' onclick=\"javascript:confirmDel();\"></input>";
                break;
            case "selectAllButton":
                return "<input type=button class=\"formulize_button\" id=\"formulize_{$button}\" name=sellall value='" . $buttonText . "' onclick=selectAll(this.check); ></input>";
                break;
            case "clearSelectButton":
                return "<input type=button class=\"formulize_button\" id=\"formulize_{$button}\" name=clearall value='" . $buttonText . "' onclick=unselectAll(this.uncheck); ></input>";
                break;
            case "resetViewButton":
                return "<input type=button class=\"formulize_button\" id=\"formulize_{$button}\" name=resetviewbutton value='" . $buttonText . "' onclick=\"javascript:showLoadingReset();\"></input>";
                break;
            case "saveViewButton":
                return "<input type=button class=\"formulize_button\" id=\"formulize_{$button}\" name=save value='" . $buttonText . "' onclick=\"javascript:showPop('" . XOOPS_URL . "/modules/formulize/include/save.php?fid={$fid}&frid={$frid}&lastloaded={$lastloaded}&cols={$flatcols}&currentview={$currentview}&loadonlyview={$loadOnlyView}');\"></input>";
                break;
            case "deleteViewButton":
                return "<input type=button class=\"formulize_button\" id=\"formulize_{$button}\" name=delete value='" . $buttonText . "' onclick=\"javascript:delete_view(this.form, '{$pubstart}', '{$endstandard}');\"></input>";
                break;
            case "currentViewList":
                $currentViewList = "<b>" . $buttonText . "</b><br><SELECT style=\"width: 350px;\" name=currentview id=currentview size=1 onchange=\"javascript:change_view(this.form, '{$pickgroups}', '{$endstandard}');\">\n";
                $currentViewList .= $viewoptions;
                $currentViewList .= "\n</SELECT>\n";
                if (!$loadviewname and strstr($currentview, ",") and !$loadOnlyView) {
                    // if we're on a genuine pick-groups view (not a loaded view)...and the load-only-view override is not in place (which eliminates other viewing options besides the loaded view)
                    $currentViewList .= "<br><input type=button name=pickdiffgroup value='" . _formulize_DE_PICKDIFFGROUP . "' onclick=\"javascript:showPop('" . XOOPS_URL . "/modules/formulize/include/changescope.php?fid={$fid}&frid={$frid}&scope={$currentview}');\"></input>";
                }
                return $currentViewList;
                break;
            case "saveButton":
                return "<input type=button class=\"formulize_button\" id=\"formulize_{$button}\" name=deSaveButton value='" . $buttonText . "' onclick=\"javascript:showLoading();\"></input>";
            case "goButton":
                return "<input type=button class=\"formulize_button\" id=\"formulize_{$button}\" name=deSubmitButton value='" . $buttonText . "' onclick=\"javascript:showLoading();\"></input>";
                break;
            case "globalQuickSearch":
                return "<input type=text id=\"formulize_{$button}\" name=\"global_search\" placeholder='" . $buttonText . "' value='" . $settings['global_search'] . "' onchange=\"javascript:window.document.controls.ventry.value = '';\"></input>";
                break;
        }
    } elseif ($button == "currentViewList") {
        // must always set a currentview value in POST even if the list is not visible
        return "<input type=hidden name=currentview value='{$currentview}'></input>\n";
    } else {
        return false;
    }
}
Example #5
0
function prepExport($headers, $cols, $data, $fdchoice, $custdel = "", $title, $template = false, $fid, $groups)
{
    // export of calculations added August 22 2006
    // come up with a filename and then return it
    // rest of logic in entriesdisplay.php will take the filename and create a file with the calculations in it once they are performed
    if ($fdchoice == "calcs") {
        $tempfold = microtime(true);
        $exfilename = _formulize_DE_XF . $tempfold . ".html";
        return XOOPS_URL . SPREADSHEET_EXPORT_FOLDER . "{$exfilename}";
    }
    global $xoopsDB;
    include_once XOOPS_ROOT_PATH . "/modules/formulize/include/extract.php";
    if ($fdchoice == "update") {
        // reset headers and cols to include all data -- when creating a blank template, this reset has already happened before prepexport is called
        $fdchoice = "comma";
        $template = "update";
        $cols1 = getAllColList($fid, "", $groups);
        // $cols1 will be a multidimensional array, one "entry" per column, and for each column the entry is an assoc array with ele_id, ele_colhead, ele_caption and ele_handle.
        unset($cols);
        $cols = array();
        foreach ($cols1[$fid] as $col) {
            $cols[] = $col['ele_handle'];
        }
        unset($headers);
        $headers = getHeaders($cols, true);
        // array of element handles, boolean for if the cols are handles (or ids, which is the default assumption)
    }
    if ($fdchoice == "comma") {
        $fd = ",";
        $fxt = ".csv";
    }
    if ($fdchoice == "tab") {
        $fd = "\t";
        $fxt = ".tabDelimited";
    }
    if ($fdchoice == "custom") {
        $fd = $custdel;
        if (!$fd) {
            $fd = "**";
        }
        $fxt = ".customDelimited";
    }
    $lineStarted = false;
    if ($template) {
        // add in other profile fields -- username, realname, e-mail, password, registration code
        if ($template == "blankprofile") {
            $csvfile = "\"" . _formulize_DE_IMPORT_USERNAME . "\"{$fd}\"" . _formulize_DE_IMPORT_FULLNAME . "\"{$fd}\"" . _formulize_DE_IMPORT_PASSWORD . "\"{$fd}\"" . _formulize_DE_IMPORT_EMAIL . "\"{$fd}\"" . _formulize_DE_IMPORT_REGCODE . "\"";
            $lineStarted = true;
        } else {
            if ($template == "update") {
                $csvfile = "\"" . _formulize_DE_IMPORT_IDREQCOL . "\"{$fd}\"" . _formulize_DE_CALC_CREATOR . "\"";
                $lineStarted = true;
            } else {
                $csvfile = "\"" . _formulize_DE_CALC_CREATOR . "\"";
                $lineStarted = true;
            }
        }
    } elseif ($_POST['metachoice'] == 1) {
        // only include metadata columns if the user requested them
        $csvfile = "\"" . _formulize_ENTRY_ID . "\"{$fd}\"" . _formulize_DE_CALC_CREATOR . "\"{$fd}\"" . _formulize_DE_CALC_CREATEDATE . "\"{$fd}\"" . _formulize_DE_CALC_MODIFIER . "\"{$fd}\"" . _formulize_DE_CALC_MODDATE . "\"";
        $lineStarted = true;
    } else {
        if (in_array("entry_id", $cols)) {
            $csvfile .= "\"" . _formulize_ENTRY_ID . "\"";
            $lineStarted = true;
        }
        if (in_array("uid", $cols) or in_array("creation_uid", $cols)) {
            $csvfile .= $lineStarted ? $fd : "";
            $csvfile .= "\"" . _formulize_DE_CALC_CREATOR . "\"";
            $lineStarted = true;
        }
        if (in_array("proxyid", $cols) or in_array("mod_uid", $cols)) {
            $csvfile .= $lineStarted ? $fd : "";
            $csvfile .= "\"" . _formulize_DE_CALC_MODIFIER . "\"";
            $lineStarted = true;
        }
        if (in_array("creation_date", $cols) or in_array("creation_datetime", $cols)) {
            $csvfile .= $lineStarted ? $fd : "";
            $csvfile .= "\"" . _formulize_DE_CALC_CREATEDATE . "\"";
            $lineStarted = true;
        }
        if (in_array("mod_date", $cols) or in_array("mod_datetime", $cols)) {
            $csvfile .= $lineStarted ? $fd : "";
            $csvfile .= "\"" . _formulize_DE_CALC_MODDATE . "\"";
            $lineStarted = true;
        }
    }
    foreach ($headers as $header) {
        // ignore the metadata columns if they are selected, since we already handle them better above. as long as the user requested that they be included
        if ($header == "" or $_POST['metachoice'] == 1 and ($header == _formulized_ENTRY_ID or $header == _formulize_DE_CALC_CREATOR or $header == _formulize_DE_CALC_MODIFIER or $header == _formulize_DE_CALC_CREATEDATE or $header == _formulize_DE_CALC_MODDATE)) {
            continue;
        }
        $header = str_replace("\"", "\"\"", $header);
        $header = "\"" . trans($header) . "\"";
        if ($lineStarted) {
            $csvfile .= $fd;
        }
        $csvfile .= $header;
        $lineStarted = true;
    }
    $csvfile .= "\r\n";
    $colcounter = 0;
    $i = 0;
    foreach ($data as $entry) {
        $formhandle = getFormHandlesFromEntry($entry);
        $ids = internalRecordIds($entry, $formhandle[0]);
        $id = $ids[0];
        $id_req[] = $id;
        $c_uid = display($entry, 'creation_uid');
        $c_name_q = q("SELECT name, uname FROM " . $xoopsDB->prefix("users") . " WHERE uid='{$c_uid}'");
        $c_name = $c_name_q[0]['name'];
        if (!$c_name) {
            $c_name = $c_name_q[0]['uname'];
        }
        $c_date = display($entry, 'creation_datetime');
        $m_uid = display($entry, 'mod_uid');
        if ($m_uid) {
            $m_name_q = q("SELECT name, uname FROM " . $xoopsDB->prefix("users") . " WHERE uid='{$m_uid}'");
            $m_name = $m_name_q[0]['name'];
            if (!$m_name) {
                $m_name = $m_name_q[0]['uname'];
            }
        } else {
            $m_name = $c_name;
        }
        $m_date = display($entry, 'mod_datetime');
        // write in metadata
        $lineStarted = false;
        // will be update only, since blank ones have no data
        if ($template) {
            $csvfile .= $id . $fd . "\"{$c_name}\"";
            $lineStarted = true;
        } elseif ($_POST['metachoice'] == 1) {
            $csvfile .= "\"{$id}\"" . $fd . "\"{$c_name}\"" . $fd . "\"{$c_date}\"" . $fd . "\"{$m_name}\"" . $fd . "\"{$m_date}\"";
            $lineStarted = true;
        }
        // write in data
        foreach ($cols as $col) {
            // ignore the metadata columns if they are selected, since we already handle them better above
            if (isMetaDataField($col) and $_POST['metachoice'] == 1) {
                continue;
            }
            if ($col == "creation_uid" or $col == "mod_uid" or $col == "uid" or $col == "proxyid") {
                $name_q = q("SELECT name, uname FROM " . $xoopsDB->prefix("users") . " WHERE uid=" . intval(display($entry, $col)));
                $data_to_write = $name_q[0]['name'];
                if (!$data_to_write) {
                    $data_to_write = $name_q[0]['uname'];
                }
            } else {
                $data_to_write = displayTogether($entry, $col, ", ");
                $data_to_write = str_replace("&quot;", "\"\"", $data_to_write);
                $data_to_write = "\"" . trans($data_to_write) . "\"";
                $data_to_write = str_replace("\r\n", "\n", $data_to_write);
            }
            if ($lineStarted) {
                $csvfile .= $fd;
            }
            $csvfile .= $data_to_write;
            $lineStarted = true;
        }
        $csvfile .= "\r\n";
        // end of a line
    }
    $tempfold = microtime(true);
    $exfilename = _formulize_DE_XF . $tempfold . $fxt;
    // open the output file for writing
    $wpath = XOOPS_ROOT_PATH . SPREADSHEET_EXPORT_FOLDER . "{$exfilename}";
    $csvfile = html_entity_decode($csvfile, ENT_QUOTES);
    $exportfile = fopen($wpath, "w");
    fwrite($exportfile, $csvfile);
    fclose($exportfile);
    // garbage collection. delete files older than 6 hours
    formulize_scandirAndClean(XOOPS_ROOT_PATH . SPREADSHEET_EXPORT_FOLDER, _formulize_DE_XF);
    // write id_reqs and tempfold to the DB if we're making an update template
    if ($template == "update") {
        $sql = "INSERT INTO " . $xoopsDB->prefix("formulize_valid_imports") . " (file, id_reqs) VALUES (\"{$tempfold}\", \"" . serialize($id_req) . "\")";
        if (!($res = $xoopsDB->queryF($sql))) {
            exit("Error: could not write import information to the database.  SQL: {$sql}<br>" . $xoopsDB->error());
        }
    }
    // need to add in logic to cull old files
    return XOOPS_URL . SPREADSHEET_EXPORT_FOLDER . "{$exfilename}";
}