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 render($ele_value, $caption, $markupName, $isDisabled, $element, $entry_id)
 {
     global $myts;
     $myts =& MyTextSanitizer::getInstance();
     $renderer =& new formulizeElementRenderer();
     $ele_desc = $element->getVar('ele_desc', "f");
     if (strstr($markupName, "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_" . $element->getVar('id_form') . "_" . $entry_id . "_", "", $markupName);
     } else {
         $true_ele_id = str_replace("ele_", "", $markupName);
     }
     $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=\"" . $markupName . "[]\" value=\"{$opt_count}\">";
         }
         $opt_count++;
     }
     if ($element->getVar('ele_delim') != "") {
         $delimSetting = $element->getVar('ele_delim');
     }
     $delimSetting =& $myts->undoHtmlSpecialChars($delimSetting);
     if ($delimSetting == "br") {
         $delimSetting = "<br />";
     }
     $hiddenOutOfRangeValuesToWrite = array();
     switch ($delimSetting) {
         case 'space':
             $form_ele1 = new XoopsFormCheckBox($caption, $markupName, $selected);
             $counter = 0;
             // counter used for javascript that works with 'Other' box
             while ($o = each($options)) {
                 $o = formulize_swapUIText($o, $element->getVar('ele_uitext'));
                 $other = $renderer->optOther($o['value'], $markupName, $entry_id, $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($caption, $delimSetting);
             $counter = 0;
             // counter used for javascript that works with 'Other' box
             while ($o = each($options)) {
                 $o = formulize_swapUIText($o, $element->getVar('ele_uitext'));
                 $t = new XoopsFormCheckBox('', $markupName . '[]', $selected);
                 $other = $renderer->optOther($o['value'], $markupName, $entry_id, $counter, true);
                 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($caption, "<nobr>{$renderedElement}</nobr>\n{$renderedHoorvs}\n{$disabledHiddenValues}\n");
     $form_ele->setDescription(html_entity_decode($ele_desc, ENT_QUOTES));
     return $form_ele;
 }
Beispiel #3
0
function prepvalues($value, $field, $entry_id)
{
    global $xoopsDB;
    // return metadata values without putting them in an array
    if (isMetaDataField($field)) {
        return $value;
    }
    $elementArray = formulize_getElementMetaData($field, true);
    $type = $elementArray['ele_type'];
    // handle yes/no cases
    if ($type == "yn") {
        // if we've found one
        if ($value == "1") {
            $value = _formulize_TEMP_QYES;
        } elseif ($value == "2") {
            $value = _formulize_TEMP_QNO;
        } else {
            $value = "";
        }
    }
    // decrypt encrypted values...pretty inefficient to do this here, one query in the DB per value to decrypt them....but we'd need proper select statements with field names specified in them, instead of *, in order to be able to swap in the AES DECRYPT at the time the data is retrieved in the master query
    if ($elementArray['ele_encrypt']) {
        $decryptSQL = "SELECT AES_DECRYPT('" . formulize_db_escape($value) . "', '" . getAESPassword() . "')";
        if ($decryptResult = $xoopsDB->query($decryptSQL)) {
            $decryptRow = $xoopsDB->fetchRow($decryptResult);
            return $decryptRow[0];
        } else {
            return "";
        }
    }
    // handle cases where the value is linked to another form
    if ($source_ele_value = formulize_isLinkedSelectBox($field, true)) {
        // value is an entry id in another form
        // need to get the form id by checking the ele_value[2] property of the element definition, to get the form id from the first part of that
        $sourceMeta = explode("#*=:*", $source_ele_value[2]);
        // [0] will be the fid of the form we're after, [1] is the handle of that element
        if ($value and $sourceMeta[1]) {
            // need to check if an alternative value field has been defined, or if we're in an export and an alterative field for exports has been defined
            // save the value before convertElementIdsToElementHandles()
            $before_conversion = $sourceMeta[1];
            $altFieldSource = "";
            if ($GLOBALS['formulize_doingExport'] and isset($source_ele_value[11]) and $source_ele_value[11] != "none") {
                $altFieldSource = $source_ele_value[11];
            } elseif (isset($source_ele_value[EV_MULTIPLE_LIST_COLUMNS]) and $source_ele_value[EV_MULTIPLE_LIST_COLUMNS] != "none") {
                $altFieldSource = $source_ele_value[EV_MULTIPLE_LIST_COLUMNS];
            }
            if ($altFieldSource) {
                $altFieldSource = is_array($altFieldSource) ? $altFieldSource : array($altFieldSource);
                $sourceMeta[1] = convertElementIdsToElementHandles($altFieldSource, $sourceMeta[0]);
                // remove empty entries, which can happen if the "use the linked field selected above" option is selected
                $sourceMeta[1] = array_filter($sourceMeta[1]);
                // unfortunately, sometimes sourceMeta[1] seems to be saved as element handles rather than element IDs, and in that case,
                // convertElementIdsToElementHandles() returns array(0 => 'none') which causes an error in the query below.
                // check for that case here and revert back to the value of sourceMeta[1] before convertElementIdsToElementHandles()
                if (1 == count($sourceMeta[1]) and isset($sourceMeta[1][0]) and "none" == $sourceMeta[1][0] or $sourceMeta[1] == "none") {
                    $sourceMeta[1] = $before_conversion;
                }
            }
            $form_handler = xoops_getmodulehandler('forms', 'formulize');
            $sourceFormObject = $form_handler->get($sourceMeta[0]);
            $sourceMeta[1] = is_array($sourceMeta[1]) ? $sourceMeta[1] : array($sourceMeta[1]);
            $query_columns = array();
            foreach ($sourceMeta[1] as $key => $handle) {
                // check if this is a link to a link
                if ($second_source_ele_value = formulize_isLinkedSelectBox($handle, true)) {
                    $secondSourceMeta = explode("#*=:*", $second_source_ele_value[2]);
                    $secondFormObject = $form_handler->get($secondSourceMeta[0]);
                    $sql = "SELECT t1.`" . $secondSourceMeta[1] . "` FROM " . DBPRE . "formulize_" . $secondFormObject->getVar('form_handle') . " as t1, " . DBPRE . "formulize_" . $sourceFormObject->getVar('form_handle') . " as t2 WHERE t2.`entry_id` IN (" . trim($value, ",") . ") AND t1.`entry_id` IN (TRIM(',' FROM t2.`" . $handle . "`)) ORDER BY t2.`entry_id`";
                    if (!($res = $xoopsDB->query($sql))) {
                        print "Error: could not retrieve the source values for a linked linked selectbox ({$field}) during data extraction for entry number {$entry_id}.  SQL:<br>{$sql}<br>";
                    } else {
                        $row = $xoopsDB->fetchRow($res);
                        $linkedvalue = prepvalues($row[0], $handle, $entry_id);
                        $query_columns[] = "'" . formulize_db_escape($linkedvalue[0]) . "'";
                    }
                } else {
                    $query_columns[] = "`{$handle}`";
                }
            }
            $sql = "SELECT " . implode(", ", $query_columns) . " FROM " . DBPRE . "formulize_" . $sourceFormObject->getVar('form_handle') . " WHERE entry_id IN (" . trim($value, ",") . ") ORDER BY entry_id";
            if (!($res = $xoopsDB->query($sql))) {
                print "Error: could not retrieve the source values for a linked selectbox during data extraction for entry number {$entry_id}.  SQL:<br>{$sql}<br>";
            } else {
                $value = "";
                while ($row = $xoopsDB->fetchRow($res)) {
                    $value .= "*=+*:" . implode(" - ", $row);
                }
            }
        } elseif ($value) {
            $value = "";
            // if there was no sourceMeta[1], which is the handle for the field in the source form, then the value should be empty, ie: we cannot make a link...this probably only happens in cases where there's a really old element that had its caption changed, and that happened before Formulize automatically updated all the linked selectboxes that rely on that element's caption, back when captions mattered in the pre F3 days
        }
    }
    // check if this is fullnames/usernames box
    // wickedly inefficient to go to DB for each value!!  This loop executes once per datapoint in the result set!!
    if ($type == "select") {
        $ele_value = unserialize($elementArray['ele_value']);
        if (is_array($ele_value[2])) {
            $listtype = key($ele_value[2]);
            if ($listtype === "{USERNAMES}" or $listtype === "{FULLNAMES}") {
                $uids = explode("*=+*:", $value);
                if (count($uids) > 0) {
                    if (count($uids) > 1) {
                        array_shift($uids);
                    }
                    $uidFilter = extract_makeUidFilter($uids);
                    $listtype = $listtype == "{USERNAMES}" ? 'uname' : 'name';
                    $value = "";
                    if (strlen($uidFilter) > 4) {
                        // skip this when $uidFilter = "uid=" becaues the query will fail
                        $names = go("SELECT uname, name FROM " . DBPRE . "users WHERE {$uidFilter} ORDER BY {$listtype}");
                        foreach ($names as $thisname) {
                            if ($thisname[$listtype]) {
                                $value .= "*=+*:" . $thisname[$listtype];
                            } else {
                                $value .= "*=+*:" . $thisname['uname'];
                            }
                        }
                    }
                } else {
                    $value = "";
                }
            }
        }
    }
    //and remove any leading *=+*: while we're at it...
    if (substr($value, 0, 5) == "*=+*:") {
        $value = substr_replace($value, "", 0, 5);
    }
    // Convert 'Other' options into the actual text the user typed
    if (($type == "radio" or $type == "checkbox") and preg_match('/\\{OTHER\\|+[0-9]+\\}/', $value)) {
        // convert ffcaption to regular and then query for id
        $realcap = str_replace("`", "'", $ffcaption);
        $newValueq = go("SELECT other_text FROM " . DBPRE . "formulize_other, " . DBPRE . "formulize WHERE " . DBPRE . "formulize_other.ele_id=" . DBPRE . "formulize.ele_id AND " . DBPRE . "formulize.ele_handle=\"" . formulize_db_escape($field) . "\" AND " . DBPRE . "formulize_other.id_req='" . intval($entry_id) . "' LIMIT 0,1");
        //$value_other = _formulize_OPT_OTHER . $newValueq[0]['other_text'];
        // removing the "Other: " part...we just want to show what people actually typed...doesn't have to be flagged specifically as an "other" value
        $value_other = $newValueq[0]['other_text'];
        $value = preg_replace('/\\{OTHER\\|+[0-9]+\\}/', $value_other, $value);
    } else {
        $value = formulize_swapUIText($value, unserialize($elementArray['ele_uitext']));
    }
    if (file_exists(XOOPS_ROOT_PATH . "/modules/formulize/class/" . $type . "Element.php")) {
        $elementTypeHandler = xoops_getmodulehandler($type . "Element", "formulize");
        $preppedValue = $elementTypeHandler->prepareDataForDataset($value, $field, $entry_id);
        if (!is_array($preppedValue)) {
            return array($preppedValue);
        } else {
            return $preppedValue;
        }
    }
    return explode("*=+*:", $value);
}
 function formulize_replaceCurlyBracketVariables($text, $entry, $id_form)
 {
     if (strstr($text, "}") and strstr($text, "{")) {
         $entryData = $this->formulize_getCachedEntryData($id_form, $entry);
         $bracketPos = -1;
         $start = true;
         // flag used to force the loop to execute, even if the 0th position has the {
         while ($bracketPos = strpos($text, "{", $bracketPos + 1) or $start == true) {
             $start = false;
             $endBracketPos = strpos($text, "}", $bracketPos + 1);
             $term = substr($text, $bracketPos + 1, $endBracketPos - $bracketPos - 1);
             $replacementTerm = display($entryData, $term);
             if ($replacementTerm !== "") {
                 // get the uitext value if necessary
                 $element_handler = xoops_getmodulehandler('elements', 'formulize');
                 $elementObject = $element_handler->get($term);
                 $replacementTerm = formulize_swapUIText($replacementTerm, $elementObject->getVar('ele_uitext'));
             } else {
                 $replacementTerm = "{" . $term . "}";
             }
             $text = str_replace("{" . $term . "}", $replacementTerm, $text);
             $bracketPos = $bracketPos + strlen($replacementTerm);
             // move ahead the length of what we replaced
         }
     }
     return $text;
 }
function printResults($masterResults, $blankSettings, $groupingSettings, $groupingValues, $masterResultsRaw, $filename = "", $title = "")
{
    $output = "";
    foreach ($masterResults as $elementId => $calcs) {
        $output .= "<tr><td class=head colspan=2>\n";
        $output .= printSmart(trans(getCalcHandleText($elementId)), 100);
        $output .= "\n</td></tr>\n";
        foreach ($calcs as $calc => $groups) {
            $countGroups = count($groups);
            $rowspan = ($countGroups > 1 and $calc != "count" and $calc != "sum") ? $countGroups : 1;
            $output .= "<tr><td class=even rowspan={$rowspan}>\n";
            // start of row with calculation results (possibly first row among many)
            switch ($calc) {
                case "sum":
                    $calc_name = _formulize_DE_CALC_SUM;
                    break;
                case "avg":
                    $calc_name = _formulize_DE_CALC_AVG;
                    break;
                case "min":
                    $calc_name = _formulize_DE_CALC_MIN;
                    break;
                case "max":
                    $calc_name = _formulize_DE_CALC_MAX;
                    break;
                case "count":
                    $calc_name = _formulize_DE_CALC_COUNT;
                    break;
                case "per":
                    $calc_name = _formulize_DE_CALC_PER;
                    break;
            }
            $output .= "<p><b>{$calc_name}</b></p>\n";
            switch ($blankSettings[$elementId][$calc]) {
                case "all":
                    $bsetting = _formulize_DE_INCLBLANKS;
                    break;
                case "noblanks":
                    $bsetting = _formulize_DE_EXCLBLANKS;
                    break;
                case "onlyblanks":
                    $bsetting = _formulize_DE_INCLONLYBLANKS;
                    break;
                case "justnoblanks":
                    $bsetting = _formulize_DE_EXCLONLYBLANKS;
                    break;
                case "justnozeros":
                    $bsetting = _formulize_DE_EXCLONLYZEROS;
                    break;
                default:
                    // must be custom
                    $bsetting = _formulize_DE_EXCLCUSTOM;
                    $setting = explode(",", substr(str_replace("!@^%*", ",", $blankSettings[$elementId][$calc]), 6));
                    // replace back the commas and remove the word custom from the front, and explode it into an array
                    $start = 1;
                    foreach ($setting as $thissetting) {
                        if (!$start) {
                            $bsetting .= ", ";
                        }
                        $start = 0;
                        if (substr($thissetting, 0, 1) == "!") {
                            $notText = strtolower(_formulize_NOT) . " ";
                            $thissetting = substr($thissetting, 1);
                        } else {
                            $notText = "";
                        }
                        $bsetting .= $notText . $thissetting;
                    }
                    break;
            }
            $output .= "<p class='formulize_blank_setting'>{$bsetting}</p>\n</td>\n";
            // start of right hand column for calculation results
            if ($calc == "count") {
                $output .= "<td class=odd>\n";
                // start of cell with calculations results
                if ($countGroups > 1) {
                    $theseGroupSettings = explode("!@^%*", $groupingSettings[$elementId][$calc]);
                    $firstGroupSettingText = printSmart(trans(getCalcHandleText($theseGroupSettings[0], true)));
                    $output .= "<table style='width: auto;'><tr><th>{$firstGroupSettingText}</th><td class='count-total' style='padding-left: 2em;'><center><b>" . _formulize_DE_CALC_NUMENTRIES . "</b><center></td><td class='count-unique' style='padding-left: 2em;'><center><b>" . _formulize_DE_CALC_NUMUNIQUE . "</b><center></td></tr>\n";
                    $totalCount = 0;
                    $totalUnique = 0;
                    foreach ($masterResultsRaw[$elementId][$calc] as $group => $rawResult) {
                        foreach ($theseGroupSettings as $id => $thisGroupSetting) {
                            if ($thisGroupSetting === "none") {
                                continue;
                            }
                            $elementMetaData = formulize_getElementMetaData($thisGroupSetting, false);
                            $groupText = formulize_swapUIText($groupingValues[$elementId][$calc][$group][$id], unserialize($elementMetaData['ele_uitext']));
                            $output .= "<tr><td>" . printSmart(trans($groupText)) . "</td><td class='count-total' style='text-align: right;'>" . $rawResult['count'] . "</td><td class='count-unique' style='text-align: right;'>" . $rawResult['countunique'] . "</td></tr>";
                            $totalCount += $rawResult['count'];
                            $totalUnique += $rawResult['countunique'];
                        }
                    }
                    $output .= "<tr><td style='border-top: 1px solid black;'><b>" . _formulize_DE_CALC_GRANDTOTAL . "</b></td><td style='border-top: 1px solid black; text-align: right;' class='count-total'><b>{$totalCount}</b></td><td style='border-top: 1px solid black; text-align: right;' class='count-unique'><b>{$totalUnique}</b></td></tr>\n";
                    $output .= "</table>";
                } else {
                    $rawResult = $masterResultsRaw[$elementId][$calc][0];
                    $output .= "<div class='count-total'><p><b>" . _formulize_DE_CALC_NUMENTRIES . " . . . " . $rawResult['count'] . "</b></p></div><div class='count-unique'><p><b>" . _formulize_DE_CALC_NUMUNIQUE . " . . . " . $rawResult['countunique'] . "</b></p></div>\n";
                }
                $output .= "</td></tr>";
                // end of the main row, and the specific cell with the calculations results
            } elseif ($calc == "sum") {
                $output .= "<td class=odd>\n";
                // start of cell with calculations results
                $handle = convertElementIdsToElementHandles($elementId);
                // returns an array, since it might be passed multiple values
                $handle = $handle[0];
                if ($countGroups > 1) {
                    $theseGroupSettings = explode("!@^%*", $groupingSettings[$elementId][$calc]);
                    $firstGroupSettingText = printSmart(trans(getCalcHandleText($theseGroupSettings[0], true)));
                    $output .= "<table style='width: auto;'><tr><th>{$firstGroupSettingText}</th><td class='sum-total' style='padding-left: 2em;'><center><b>" . _formulize_DE_CALC_SUM . "</b><center></td></tr>\n";
                    $totalSum = 0;
                    foreach ($masterResultsRaw[$elementId][$calc] as $group => $rawResult) {
                        foreach ($theseGroupSettings as $id => $thisGroupSetting) {
                            if ($thisGroupSetting === "none") {
                                continue;
                            }
                            $elementMetaData = formulize_getElementMetaData($thisGroupSetting, false);
                            $groupText = formulize_swapUIText($groupingValues[$elementId][$calc][$group][$id], unserialize($elementMetaData['ele_uitext']));
                            $output .= "<tr><td>" . printSmart(trans($groupText)) . "</td><td class='sum-total' style='text-align: right;'>" . formulize_numberFormat($rawResult['sum'], $handle) . "</td></tr>";
                            $totalSum += $rawResult['sum'];
                        }
                    }
                    $output .= "<tr><td style='border-top: 1px solid black;'><b>" . _formulize_DE_CALC_GRANDTOTAL . "</b></td><td style='border-top: 1px solid black; text-align: right;' class='sum-total'><b>" . formulize_numberFormat($totalSum, $handle) . "</b></td></tr>\n";
                    $output .= "</table>";
                } else {
                    $rawResult = $masterResultsRaw[$elementId][$calc][0];
                    $output .= "<div class='sum-total'><p><b>" . _formulize_DE_CALC_SUM . " . . . " . formulize_numberFormat($rawResult['sum'], $handle) . "</b></p></div>\n";
                }
                $output .= "</td></tr>";
                // end of the main row, and the specific cell with the calculations results
            } else {
                $start = 1;
                foreach ($groups as $group => $result) {
                    //foreach($result as $resultID=>$thisResult) {
                    if (!$start) {
                        $output .= "<tr>\n";
                    }
                    $start = 0;
                    $output .= "<td class=odd>\n";
                    //if(count($groups)>1) { // OR count($groups)>1) { // output the heading section for this group of results
                    $output .= "<p><b>";
                    $start2 = true;
                    foreach (explode("!@^%*", $groupingSettings[$elementId][$calc]) as $id => $thisGroupSetting) {
                        if ($thisGroupSetting === "none") {
                            continue;
                        }
                        if (!$start2) {
                            $output .= "<br>\n";
                        }
                        $start2 = false;
                        $elementMetaData = formulize_getElementMetaData($thisGroupSetting, false);
                        $groupText = formulize_swapUIText($groupingValues[$elementId][$calc][$group][$id], unserialize($elementMetaData['ele_uitext']));
                        $output .= printSmart(trans(getCalcHandleText($thisGroupSetting, true))) . ": " . printSmart(trans($groupText)) . "\n";
                    }
                    $output .= "</b></p>\n";
                    //}
                    $output .= "<p>{$result}</p>\n";
                    $output .= "</td></tr>\n";
                    //}
                }
            }
        }
    }
    print $output;
    // addition of calculation download, August 22 2006
    if ($filename) {
        // get the current CSS values for head, even and odd
        global $xoopsConfig;
        $head = "";
        $odd = "";
        $even = "";
        formulize_benchmark("before reading stylesheet");
        if (file_exists(XOOPS_ROOT_PATH . "/themes/" . $xoopsConfig['theme_set'] . "/style.css")) {
            if (!class_exists('csstidy')) {
                // use supplied csstidy in parent if one exists...
                if (file_exists(XOOPS_ROOT_PATH . "/plugins/csstidy/class.csstidy.php")) {
                    include_once XOOPS_ROOT_PATH . "/plugins/csstidy/class.csstidy.php";
                } else {
                    include_once XOOPS_ROOT_PATH . "/modules/formulize/class/class.csstidy.php";
                }
            }
            $css = new csstidy();
            $css->set_cfg('merge_selectors', 0);
            $css->parse_from_url(XOOPS_ROOT_PATH . "/themes/" . $xoopsConfig['theme_set'] . "/style.css");
            $parsed_css = $css->css;
            // parsed_css seems to have only one key when looking at the default template...key is the number of styles?
            foreach ($parsed_css as $thiscss) {
                $head = isset($thiscss['.head']['background-color']) ? $thiscss['.head']['background-color'] : isset($thiscss['.head']['background']) ? $thiscss['.head']['background'] : "";
                $even = isset($thiscss['.even']['background-color']) ? $thiscss['.even']['background-color'] : isset($thiscss['.even']['background']) ? $thiscss['.even']['background'] : "";
                $odd = isset($thiscss['.odd']['background-color']) ? $thiscss['.odd']['background-color'] : isset($thiscss['.odd']['background']) ? $thiscss['.odd']['background'] : "";
            }
        }
        formulize_benchmark("after reading stylesheet");
        unset($css);
        // if we couldn't find any values, use these:
        $head = $head ? $head : "#c2cdd6";
        $even = $even ? $even : "#dee3e7";
        $odd = $odd ? $odd : "#E9E9E9";
        // create the file
        formulize_benchmark("before creating file");
        $outputfile = "<HTML>\n<head>\n<meta name=\"generator\" content=\"Formulize -- form creation and data management for XOOPS\" />\n<title>" . _formulize_DE_EXPORTCALC_TITLE . " '{$title}'</title>\n<style type=\"text/css\">\n.outer {border: 1px solid silver;}\n.head { background-color: {$head}; padding: 5px; font-weight: bold; }\n.even { background-color: {$even}; padding: 5px; }\t\t\n.odd { background-color: {$odd}; padding: 5px; }\nbody {color: black; background: white; margin-top: 30px; margin-bottom: 30px; margin-left: 30px; margin-right: 30px; padding: 0; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 10pt;}\ntd { vertical-align: top; }\n</style>\n</head>\n<body>\n<h1>" . _formulize_DE_EXPORTCALC_TITLE . " '{$title}'</h1>\n<table class=outer>\n{$output}\n</table>\n</body>\n</html>";
        // output the file
        $exfilename = strrchr($filename, "/");
        $wpath = XOOPS_ROOT_PATH . SPREADSHEET_EXPORT_FOLDER . "{$exfilename}";
        $exportfile = fopen($wpath, "w");
        fwrite($exportfile, $outputfile);
        fclose($exportfile);
    }
    formulize_benchmark("after creating file");
}
function buildEvaluationCondition($match, $indexes, $filterElements, $filterOps, $filterTerms, $entry, $entryData)
{
    $evaluationCondition = "";
    // convert the internal database representation to the displayed value, if this element has uitext
    foreach ($filterElements as $key => $element) {
        $element_metadata = formulize_getElementMetaData($element, true);
        if (isset($element_metadata['ele_uitext'])) {
            $filterTerms[$key] = formulize_swapUIText($filterTerms[$key], unserialize($element_metadata['ele_uitext']));
        }
    }
    for ($io = 0; $io < count($indexes); $io++) {
        $i = $indexes[$io];
        if (!($evaluationCondition == "")) {
            $evaluationCondition .= " {$match} ";
        }
        switch ($filterOps[$i]) {
            case "=":
                $thisOp = "==";
                break;
            case "NOT":
                $thisOp = "!=";
                break;
            default:
                $thisOp = $filterOps[$i];
        }
        if ($filterTerms[$i] === "{BLANK}") {
            $filterTerms[$i] = "";
        }
        if (isset($GLOBALS['formulize_asynchronousFormDataInAPIFormat'][$entry][$filterElements[$i]])) {
            $compValue = $GLOBALS['formulize_asynchronousFormDataInAPIFormat'][$entry][$filterElements[$i]];
        } elseif ($entry == "new") {
            // for textboxes, let's try to get their default value
            // for other elements, generate the default is too tricky to get it to work at present, not enough time available
            $element_handler = xoops_getmodulehandler('elements', 'formulize');
            $elementObject = $element_handler->get($filterElements[$i]);
            if (is_object($elementObject)) {
                $ele_type = $elementObject->getVar('ele_type');
                if ($ele_type == "text" or $ele_type == "textarea") {
                    $ele_value = $elementObject->getVar('ele_value');
                    $defaultKey = $ele_type == "text" ? 2 : 0;
                    // default key is in different places for different types of elements
                    $compValue = getTextboxDefault($ele_value[$defaultKey], $elementObject->getVar('id_form'), $entry);
                } else {
                    $compValue = "";
                }
            } else {
                $compValue = "";
            }
        } else {
            $compValue = display($entryData[0], $filterElements[$i]);
        }
        if (is_array($compValue)) {
            if ($thisOp == "=") {
                $thisOp = "LIKE";
            }
            if ($thisOp == "!=") {
                $thisOp = "NOT LIKE";
            }
            $compValue = implode(",", $compValue);
        } else {
            $compValue = addslashes($compValue);
        }
        if ($thisOp == "LIKE") {
            $evaluationCondition .= "strstr('" . $compValue . "', '" . addslashes($filterTerms[$i]) . "')";
        } elseif ($thisOp == "NOT LIKE") {
            $evaluationCondition .= "!strstr('" . $compValue . "', '" . addslashes($filterTerms[$i]) . "')";
        } else {
            $evaluationCondition .= "'" . $compValue . "' {$thisOp} '" . addslashes($filterTerms[$i]) . "'";
        }
    }
    return $evaluationCondition;
}
Beispiel #7
0
function buildFilter($id, $ele_id, $defaulttext = "", $name = "", $overrides = array(0 => ""), $subfilter = false, $linked_ele_id = 0, $linked_data_id = 0, $limit = false)
{
    // Changes made to allow the linking of one filter to another. This is acheieved as follows:
    // 1. Create a formulize form for managing the Main Filter List (form M)
    // 2. Create a formulize form for managing the Sub Filter list (form S), which includes a linked element to the data in form M,
    //    so that relation between the Main Filter & Sub Filter data can be specified
    // 3. Create a formulize form for the data that the Main & SubFilter act upon (form D)
    ///
    // In such a case, the parameters have the following meaning:
    //  - $id is the element id of the field to be filtered in Form D
    //  - $ele_id is also the element id of the field to be filtered in Form D
    //  - $subfilter specifies if this filter is a subfilter
    //  - $linked_ele_id specifies the ele_id of the Main Filter field as it appears in Form S
    //  - $linked_data_id specifies the ele_id of the Main Filter field as it appears in Form D
    /* limit params work as follows: (a limit is some property of a field in the source entry in a linked selectbox)
       $limit = false, or if used then it's an array with these params
       'ele_id' = the id of the element to pay attention to for the limit condition
       'term' = the term used to build the condition
       'operator' = the operator used to build the condition
       */
    // limits are very similar to subfilters in their effect, but subfilters are meant for situations where one filter influences another filter
    // subfilters are kind of like dynamic limits, where the limit condition is not specified until the parent filter is chosen.
    global $xoopsDB;
    // required by q
    $form_handler = xoops_getmodulehandler('forms', 'formulize');
    $filter = "<SELECT name=\"{$id}\" id=\"{$id}\"";
    if ($name == "{listofentries}") {
        $filter .= " onchange='javascript:showLoading();'";
        // list of entries has a special javascript thing
    } elseif ($name) {
        $filter .= " onchange='javascript:document.{$name}.submit();'";
    }
    $filter .= ">\n";
    if ($subfilter and !isset($_POST[$linked_data_id]) and !isset($_GET[$linked_data_id])) {
        // If its a subfilter and the main filter is unselected, then put in 'Please select from above options first
        $filter .= "<option value=\"none\">Please select a primary filter first</option>\n";
    } else {
        // Either it is not a subfilter, or it is a subfilter with the linked values set
        $defaulttext = $defaulttext ? $defaulttext : _AM_FORMLINK_PICK;
        if ($name == "{listofentries}") {
            // must not pass back a value when we're putting a filter on the list of entries page
            $filter .= "<option value=\"\">" . $defaulttext . "</option>\n";
        } else {
            $filter .= "<option value=\"none\">" . $defaulttext . "</option>\n";
        }
        $form_element = q("SELECT ele_value, ele_type, ele_uitext FROM " . $xoopsDB->prefix("formulize") . " WHERE ele_id = " . $ele_id);
        $element_value = unserialize($form_element[0]["ele_value"]);
        $ele_uitext = unserialize($form_element[0]["ele_uitext"]);
        switch ($form_element[0]["ele_type"]) {
            case "select":
                $options = $element_value[2];
                break;
            case "radio":
            case "checkbox":
                $options = $element_value;
                break;
            default:
                $options = array();
        }
        // if the $options is from a linked selectbox, then figure that out and gather the possible values
        // only linked selectboxes have this string in their options field
        if (strstr($options, "#*=:*")) {
            $boxproperties = explode("#*=:*", $options);
            $source_form_id = $boxproperties[0];
            $source_element_handle = $boxproperties[1];
            // process the limits
            $limitCondition = "";
            // NOTE: LIMIT['ELE_ID'] MUST BE THE HANDLE OF THE ELEMENT, NOT THE ELEMENT ID...THIS OBSCURE FEATURE ONLY USED IN THE MAP SITE WAS NOT UPDATED FOR 3.1...AS LONG AS ELEMENT HANDLES ARE NOT CUSTOMIZED, THIS SHOULD NOT BE A PROBLEM
            if (is_array($limit)) {
                //$limitCondition = $limit['ele_id'] . "/**/" . $limit['term'];
                //$limitCondition .= isset($limit['operator']) ? "/**/" . $limit['operator'] : "";
                $limitOperator = isset($limit['operator']) ? $limit['operator'] : " LIKE ";
                $likebits = (strstr($limitOperator, "LIKE") and substr($limit['term'], 0, 1) != "%" and substr($limit['term'], -1) != "%") ? "%" : "";
                $limitCondition = " WHERE t1`" . $limit['ele_id'] . "` " . $limitOperator . " '{$likebits}" . formulize_db_escape($limit['term']) . "{$likebits}' ";
            } elseif ($subfilter) {
                // for subfilters, we're jumping back to another form to get the values, hence the join
                $element_handler = xoops_getmodulehandler('elements', 'formulize');
                $linkedSourceElementObject = $element_handler->get($linked_ele_id);
                $linkedSourceElementEleValue = $linkedSourceElementObject->getVar('ele_value');
                // first part will be the form id of the source form, second part will be the element handle in that form
                $linkedSourceElementEleValueParts = explode("#*=:*", $linkedSourceElementEleValue[2]);
                $linkedFormObject = $form_handler->get($linkedSourceElementEleValueParts[0]);
                $limitCondition = ", " . $xoopsDB->prefix("formulize_" . $linkedFormObject->getVar('form_handle')) . " as t2 WHERE t1.`{$linked_ele_id}` LIKE CONCAT('%',t2.entry_id,'%') AND t2.`" . $linkedSourceElementEleValueParts[1] . "` LIKE '%" . formulize_db_escape($_POST[$linked_data_id]) . "%'";
            }
            unset($options);
            $sourceFormObject = $form_handler->get($source_form_id);
            if ($dataResult = $xoopsDB->query("SELECT distinct(t1.`{$source_element_handle}`) FROM " . $xoopsDB->prefix("formulize_" . $sourceFormObject->getVar('form_handle')) . " as t1 " . $limitCondition . " ORDER BY t1.`{$source_element_handle}`")) {
                while ($dataArray = $xoopsDB->fetchArray($dataResult)) {
                    $options[$dataArray[$source_element_handle]] = "";
                }
            } else {
                $options = array();
            }
        }
        $nametype = "";
        // code copied from elementrender.php to make fullnames work for Drupalcamp demo
        if (key($options) === "{FULLNAMES}" or key($options) === "{USERNAMES}") {
            if (key($options) === "{FULLNAMES}") {
                $nametype = "name";
            }
            if (key($options) === "{USERNAMES}") {
                $nametype = "uname";
            }
            $pgroups = array();
            if ($element_value[3]) {
                $scopegroups = explode(",", $element_value[3]);
                global $xoopsUser;
                $groups = $xoopsUser ? $xoopsUser->getGroups() : array(0 => XOOPS_GROUP_ANONYMOUS);
                if (!in_array("all", $scopegroups)) {
                    // limit by users's groups
                    if ($element_value[4]) {
                        // loop so we can get rid of reg users group simply
                        foreach ($groups as $gid) {
                            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 {
                    // really use all (otherwise, we're just going will all user's groups, so existing value of $groups will be okay
                    if (!$element_value[4]) {
                        unset($groups);
                        global $xoopsDB;
                        $allgroupsq = q("SELECT groupid FROM " . $xoopsDB->prefix("groups") . " WHERE groupid != " . XOOPS_GROUP_USERS);
                        foreach ($allgroupsq as $thisgid) {
                            $groups[] = $thisgid['groupid'];
                        }
                    }
                }
                $options = array();
                $namelist = gatherNames($groups, $nametype);
                foreach ($namelist as $auid => $aname) {
                    $options[$aname] = $auid;
                    // backwards to how elementrenderer.php does it, since logic below to build list is different
                }
            }
        }
        if ($name != "{listofentries}") {
            ksort($options);
        }
        $counter = 0;
        foreach ($options as $option => $option_value) {
            if (is_array($overrides) and isset($overrides[$option])) {
                $selected = ($_POST[$id] == $option or $_GET[$id] == $option) ? "selected" : "";
                $filter .= "<option value=\"" . $overrides[$option][1] . "\" {$selected}>" . $overrides[$option][0] . "</option>\n";
            } else {
                if (preg_match('/\\{OTHER\\|+[0-9]+\\}/', $option)) {
                    $option = str_replace(":", "", _formulize_OPT_OTHER);
                }
                // if a nametype is in effect, then use the value, otherwise, use the key -- also, no longer swapping out spaces for underscores
                $passoption = $nametype ? $option_value : $option;
                if ((isset($_POST[$id]) or isset($_GET[$id])) and $overrides !== false) {
                    if ($name == "{listofentries}") {
                        $selected = (is_numeric($overrides) and $overrides == $counter or !is_numeric($overrides) and $overrides === $option) ? "selected" : "";
                    } else {
                        $selected = ($_POST[$id] == $passoption or $_GET[$id] == $passoption) ? "selected" : "";
                    }
                } else {
                    $selected = "";
                }
                if ($name == "{listofentries}") {
                    // need to pass this stupid thing back because we can't compare the option and the contents of $_POST...a typing problem in PHP??!!
                    $passoption = "qsf_" . $counter . "_{$passoption}";
                }
                $filter .= "<option value=\"{$passoption}\" {$selected}>" . formulize_swapUIText($option, $ele_uitext) . "</option>\n";
            }
            $counter++;
        }
    }
    $filter .= "</SELECT>\n";
    return $filter;
}