function insert($screen)
 {
     $update = $screen->getVar('sid') == 0 ? false : true;
     if (!($sid = parent::insert($screen))) {
         return false;
     }
     $screen->assignVar('sid', $sid);
     if (!$update) {
         $sql = sprintf("INSERT INTO %s (sid, custom_code, template) VALUES (%u, %s, %s)", $this->db->prefix('formulize_screen_template'), $screen->getVar('sid'), $this->db->quoteString(formulize_db_escape($screen->getVar('custom_code'))), $this->db->quoteString(formulize_db_escape($screen->getVar('template'))));
     } else {
         $sql = sprintf("UPDATE %s SET custom_code = %s, template = %s WHERE sid = %u", $this->db->prefix('formulize_screen_template'), formulize_db_escape($screen->getVar('custom_code')), formulize_db_escape($screen->getVar('template')), $sid);
     }
     $result = $this->db->query($sql);
     if (!$result) {
         print "Error: could not save template screen properly: " . $this->db->error() . " for query: {$sql}";
         return false;
     }
     $success1 = true;
     if (isset($_POST['screens-custom_code'])) {
         $success1 = $this->write_custom_code_to_file(trim($_POST['screens-custom_code']), $screen);
     }
     $success2 = true;
     if (isset($_POST['screens-template'])) {
         $success2 = $this->write_template_to_file(trim($_POST['screens-template']), $screen);
     }
     if (!$success1 || !$success2) {
         return false;
     }
     return $sid;
 }
function getUserID($stringName)
{
    global $xoopsDB, $xoopsUser;
    $sql = "SELECT uid FROM " . $xoopsDB->prefix("users") . " WHERE uname='" . formulize_db_escape($stringName) . "'";
    $result = $xoopsDB->query($sql);
    if ($xoopsDB->getRowsNum($result) > 0) {
        $item = $xoopsDB->fetchArray($result);
        if (@$item["uid"]) {
            return $item["uid"];
        }
    } else {
        // or, if no username match found, get the first matching full name
        $sql = "SELECT uid FROM " . $xoopsDB->prefix("users") . " WHERE name='" . formulize_db_escape($stringName) . "'";
        if ($result = $xoopsDB->query($sql)) {
            $item = $xoopsDB->fetchArray($result);
            if (@$item["uid"]) {
                return $item["uid"];
            }
        }
    }
    if (is_numeric($stringName)) {
        return $stringName;
    }
    // instead of returning 0, return the current user's ID
    return $xoopsUser->getVar('uid');
}
 function _getGroupsHavingScopeInfo($gids, $different = false)
 {
     if (!is_array($gids)) {
         $gids = array(0 => intval($gids));
     }
     global $xoopsDB;
     if (!$different) {
         $sql = "SELECT groupid FROM " . $xoopsDB->prefix("formulize_groupscope_settings") . " WHERE view_groupid IN (" . formulize_db_escape(implode(", ", $gids)) . ") AND fid=" . $this->fid;
     } else {
         $sql = "SELECT groupid FROM " . $xoopsDB->prefix("formulize_groupscope_settings") . " as t1 WHERE fid = " . $this->fid . " AND view_groupid != 0 AND NOT EXISTS(SELECT 1 FROM " . $xoopsDB->prefix("formulize_groupscope_settings") . " as t2 WHERE view_groupid IN (" . formulize_db_escape(implode(", ", $gids)) . ") AND fid=" . $this->fid . " AND t1.groupid = t2.groupid)";
     }
     $res = $xoopsDB->query($sql);
     $foundGids = array();
     while ($array = $xoopsDB->fetchArray($res)) {
         $foundGids[] = $array['groupid'];
     }
     return $foundGids;
 }
         $data_handler->writeEntry($entry_id, array($elementObject->getVar('ele_handle') => ''), false, true);
         print json_encode(array("element_id" => $element_id, "entry_id" => $entry_id));
     }
     break;
 case 'get_element_html':
     include_once XOOPS_ROOT_PATH . "/modules/formulize/include/elementdisplay.php";
     displayElement("", formulize_db_escape($_GET['param2']), intval($_GET['param3']));
     break;
 case 'get_element_value':
     $handle = $_GET['param1'];
     $entryId = intval($_GET['param3']);
     include_once XOOPS_ROOT_PATH . "/modules/formulize/include/functions.php";
     include_once XOOPS_ROOT_PATH . "/modules/formulize/include/extract.php";
     include_once XOOPS_ROOT_PATH . "/modules/formulize/class/data.php";
     $element_handler = xoops_getmodulehandler('elements', 'formulize');
     $elementObject = $element_handler->get(formulize_db_escape($handle));
     $data_handler = new formulizeDataHandler($elementObject->getVar('id_form'));
     $dbValue = $data_handler->getElementValueInEntry($entryId, $handle);
     $preppedValue = prepvalues($dbValue, $handle, $entryId);
     print getHTMLForList($preppedValue, $handle, $entryId, 1);
     // 1 is a flag to include the icon for switching to an editable element
     break;
 case 'get_element_row_html':
     include_once XOOPS_ROOT_PATH . "/modules/formulize/include/functions.php";
     include_once XOOPS_ROOT_PATH . "/modules/formulize/include/elementdisplay.php";
     include_once XOOPS_ROOT_PATH . "/modules/formulize/include/extract.php";
     $sendBackValue = array();
     $element_handler = xoops_getmodulehandler('elements', 'formulize');
     foreach ($_GET as $k => $v) {
         if ($k == 'elementId' or $k == 'entryId' or $k == 'fid' or $k == 'frid' or substr($k, 0, 8) == 'onetoone') {
             // serveral onetoone keys can be passed back too
 function prepareDataForSaving($value, $element)
 {
     global $myts;
     if (!$myts) {
         $myts =& MyTextSanitizer::getInstance();
     }
     $ele_value = $element->getVar('ele_value');
     $ele_id = $element->getVar('ele_id');
     if ($ele_value[3]) {
         // if $ele_value[3] is 1 (default is 0) then treat this as a numerical field
         $value = ereg_replace('[^0-9.-]+', '', $value);
     }
     if (get_magic_quotes_gpc()) {
         $value = stripslashes($value);
     }
     $value = $myts->htmlSpecialChars($value);
     return formulize_db_escape($value);
     // strictly speaking, formulize will already escape all values it writes to the database, but it's always a good habit to never trust what the user is sending you!
 }
 function prepareDataForSaving($value, $element)
 {
     global $myts;
     $ele = $value;
     $ele_value = $element->getVar('ele_value');
     // handle the new possible default value -- sept 7 2007
     if ($ele_value[0] == 1 and $ele == "none") {
         // none is the flag for the "Choose an option" default value
         $value = "{WRITEASNULL}";
         // this flag is used to terminate processing of this value
         break;
     }
     // section to handle linked select boxes differently from others...
     if (strstr($ele_value[2], "#*=:*")) {
         // if we've got a formlink, then handle it here...
         if (is_array($ele)) {
             $startWhatWasSelected = true;
             foreach ($ele as $whatwasselected) {
                 if (!is_numeric($whatwasselected)) {
                     continue;
                 }
                 if ($startWhatWasSelected) {
                     $value = ",";
                     $startWhatWasSelected = false;
                 }
                 $value .= $whatwasselected . ",";
             }
         } elseif (is_numeric($ele)) {
             $value = $ele;
         } else {
             $value = "";
         }
         break;
     } else {
         $value = '';
         // The following code block is a replacement for the previous method for reading a select box which didn't work reliably -- jwe 7/26/04
         // print_r($ele_value[2]);
         $temparraykeys = array_keys($ele_value[2]);
         if ($temparraykeys[0] === "{FULLNAMES}" or $temparraykeys[0] === "{USERNAMES}") {
             // ADDED June 18 2005 to handle pulling in usernames for the user's group(s) -- updated for real live use September 6 2006
             if (is_array($ele)) {
                 $value = "";
                 foreach ($ele as $auid) {
                     $value .= "*=+*:" . $auid;
                 }
             } else {
                 $value = $ele;
             }
             break;
         }
         // THIS REALLY OLD CODE IS HARD TO READ....HERE'S A GLOSS...
         // ele_value[2] is all the options that make up this element.  The values passed back from the form will be numbers indicating which value was selected.  First value is 0 for a multi-selection box, and 1 for a single selection box.
         // Subsequent values are one number higher and so on all the way to the end.  Five values in a multiple selection box, the numbers are 0, 1, 2, 3, 4.
         // masterentlistjwe and entrycounterjwe will be the same!!  There's these array_keys calls here, which result basically in a list of numbers being created, keysPassedBack, and that list is going to start at 0 and go up to whatever the last value is.  It always starts at zero, even if the list is a single selection list.  entrycounterjwe will also always start at zero.
         // After that, we basically just loop through all the possible places, 0 through n, that the user might have selected, and we check if they did.
         // The check lines are if($whattheuserselected == $masterentlistjwe) and $ele == ($masterentlistjwe+1) ....note the +1 to make this work for single selection boxes where the numbers start at 1 instead of 0.
         // This is all further complicated by the fact that we're grabbing values from $entriesPassedBack, which is just the list of options in the form, so that we can populate the ultimate $value that is going to be written to the database.
         $entriesPassedBack = array_keys($ele_value[2]);
         $keysPassedBack = array_keys($entriesPassedBack);
         $entrycounterjwe = 0;
         $numberOfSelectionsFound = 0;
         foreach ($keysPassedBack as $masterentlistjwe) {
             if (is_array($ele)) {
                 //foreach($ele as $whattheuserselected) // note this loop within a loop should not be necessary...we do not need to check all the submitted values from the form once for each possible value in the form!
                 if (in_array($masterentlistjwe, $ele)) {
                     if (get_magic_quotes_gpc()) {
                         $entriesPassedBack[$entrycounterjwe] = stripslashes($entriesPassedBack[$entrycounterjwe]);
                     }
                     $entriesPassedBack[$entrycounterjwe] = $myts->htmlSpecialChars($entriesPassedBack[$entrycounterjwe]);
                     $value = $value . "*=+*:" . $entriesPassedBack[$entrycounterjwe];
                     $numberOfSelectionsFound++;
                 }
                 $entrycounterjwe++;
             } else {
                 //print "internal loop $entrycounterjwe<br>userselected: $ele<br>selectbox contained: $masterentlistjwe<br><br>";
                 if ($ele == $masterentlistjwe + 1) {
                     //print "WE HAVE A MATCH!<BR>";
                     if (get_magic_quotes_gpc()) {
                         $entriesPassedBack[$entrycounterjwe] = stripslashes($entriesPassedBack[$entrycounterjwe]);
                     }
                     $entriesPassedBack[$entrycounterjwe] = $myts->htmlSpecialChars($entriesPassedBack[$entrycounterjwe]);
                     $value = $entriesPassedBack[$entrycounterjwe];
                 }
                 $entrycounterjwe++;
             }
         }
         // handle out of range values that are in the DB, added March 2 2008 by jwe
         if (is_array($ele)) {
             while ($numberOfSelectionsFound < count($ele) and $entrycounterjwe < 1000) {
                 // if a value was received that was out of range...added by jwe March 2 2008...in this case we are assuming that if there are more values passed back than selections found in the valid options for the element, then there are out-of-range values we want to preserve
                 if (in_array($entrycounterjwe, $ele)) {
                     // keep looking for more values...get them out of the hiddenOutOfRange info
                     $value = $value . '*=+*:' . $myts->htmlSpecialChars($_POST['formulize_hoorv_' . $ele_id . '_' . $entrycounterjwe]);
                     $numberOfSelectionsFound++;
                 }
                 $entrycounterjwe++;
             }
         } else {
             if ($ele > $entrycounterjwe) {
                 // if a value was received that was out of range...added by jwe March 2 2008 (note that unlike with radio buttons, we need to check only for greater than, due to the +1 (starting at 1) that happens with single option selectboxes
                 $value = $myts->htmlSpecialChars($_POST['formulize_hoorv_' . $ele_id . '_' . $ele]);
                 // get the out of range value from the hidden values that were passed back
             }
         }
     }
     // end of if that checks for a linked select box.
     return formulize_db_escape($value);
     // strictly speaking, formulize will already escape all values it writes to the database, but it's always a good habit to never trust what the user is sending you!
 }
Example #7
0
 function changeUserSubmittedValues($element_id_or_handle, $newValues)
 {
     if (!($element = _getElementObject($element_id_or_handle))) {
         return false;
     }
     // multiple selection elements have data saved with the special prefix to separate values in the cell:  *=+*:
     // we need to determine if this element allows multiple values and prepare to handle it
     $ele_type = $element->getVar('ele_type');
     $ele_value = $element->getVar('ele_value');
     switch ($ele_type) {
         case "check":
         case "radio":
             $oldValues = array_keys($ele_value);
             break;
         case "select":
             $oldValues = array_keys($ele_value[2]);
             // special check...if this is a linked selectbox or a fullnames/usernames selectbox, then fail
             if (!is_array($ele_value[2]) or isset($ele_value[2]["{FULLNAMES}"]) or isset($ele_value[2]["{USERNAMES}"])) {
                 return false;
             }
             break;
     }
     $prefix = ($ele_type == "check" or $ele_type == "select" and $ele_value[1]) ? "#*=:*" : "";
     // multiple selection possible? if so, setup prefix
     $newValues = array_keys($newValues);
     global $xoopsDB;
     $form_handler = xoops_getmodulehandler('forms', 'formulize');
     $formObject = $form_handler->get($this->fid);
     $sql = "SELECT `entry_id`, `" . $element->getVar('ele_handle') . "` FROM " . $xoopsDB->prefix("formulize_" . $formObject->getVar('form_handle'));
     if (!($res = $xoopsDB->query($sql))) {
         return false;
     }
     $updateSql = array();
     while ($array = $xoopsDB->fetchArray($res)) {
         // do a search/replace inside the returned value, then construct one insert for each (yuck)
         // necessary to do the search/replace inside PHP where we have more control, since the possible matching conditions when multiple options can be selected, are prohibitively difficult (impossible?) to capture.
         if ($prefix) {
             $currentValues = explode($prefix, ltrim($array[$element->getVar('ele_handle')], $prefix));
             // since prefix is at the beginning of the string, we need to remove it before doing the explode
         } else {
             $currentValues = array(0 => $array[$element->getVar('ele_handle')]);
         }
         for ($i = 0; $i < count($newValues); $i++) {
             if ($newValues[$i] === $oldValues[$i]) {
                 // ignore values that haven't changed
                 continue;
             }
             $foundIndex = array();
             $key = array_search($oldValues[$i], $currentValues);
             if ($key !== false and !isset($foundIndex[$key])) {
                 // if we find one of the old values in the current values, then swap in the new value it should have
                 // need to check that the match wasn't a 0 or on a string, etc...cannot use strict matching in array_search since that screws up all matches since the values don't really have their correct type owing to having been spun through lots of functions by now
                 if (!is_numeric($currentValues[$key]) and $oldValues[$i] == '0') {
                     continue;
                 }
                 $currentValues[$key] = $newValues[$i];
                 $foundIndex[$key] = true;
                 if (count($foundIndex) == count($currentValues)) {
                     break;
                     // all currentValues have been replaced, so let's move on
                 }
             }
         }
         if ($prefix) {
             $replacementString = $prefix . implode($prefix, $currentValues);
             // put prefix back at the beginning after the implode
         } else {
             $replacementString = $currentValues[0];
         }
         $updateSql[] = "UPDATE " . $xoopsDB->prefix("formulize_" . $formObject->getVar('form_handle')) . " SET `" . $element->getVar('ele_handle') . "` = '" . formulize_db_escape($replacementString) . "' WHERE entry_id = " . $array['entry_id'];
     }
     if (count($updateSql) > 0) {
         // if we have some SQL generated, then run it.
         foreach ($updateSql as $thisSql) {
             //print $thisSql."<br>";
             if (!($res = $xoopsDB->query($thisSql))) {
                 return false;
             }
         }
     }
     return true;
 }
Example #8
0
 public function titleForClonedForm($fid)
 {
     $foundTitle = 1;
     $titleCounter = 0;
     $form_handler = xoops_getmodulehandler('forms', 'formulize');
     $formObject = $form_handler->get($fid);
     $title = $formObject->getVar('title');
     while ($foundTitle) {
         $titleCounter++;
         if ($titleCounter > 1) {
             // add a number to the new form name to ensure it is unique
             $newtitle = sprintf(_FORM_MODCLONED, $title) . " {$titleCounter}";
         } else {
             $newtitle = sprintf(_FORM_MODCLONED, $title);
         }
         $titleCheckSQL = "SELECT desc_form FROM " . $this->db->prefix("formulize_id") . " WHERE desc_form = '" . formulize_db_escape($newtitle) . "'";
         $titleCheckResult = $this->db->query($titleCheckSQL);
         $foundTitle = $this->db->getRowsNum($titleCheckResult);
     }
     return $newtitle;
     // use the last searched title (because it was not found)
 }
Example #9
0
 function insertCloneIntoScreenTypeTable($sid, $newsid, $newtitle, $tablename)
 {
     $getrow = q("SELECT * FROM " . $this->db->prefix($tablename) . " WHERE sid = {$sid}");
     $insert_sql = "INSERT INTO " . $this->db->prefix($tablename) . " (";
     $start = 1;
     foreach ($getrow[0] as $field => $value) {
         if ($field == "formid" or $field == "listofentriesid" or $field == "multipageid" or $field == "templateid") {
             continue;
         }
         if (!$start) {
             $insert_sql .= ", ";
         }
         $start = 0;
         $insert_sql .= $field;
     }
     $insert_sql .= ") VALUES (";
     $start = 1;
     foreach ($getrow[0] as $field => $value) {
         if ($field == "formid" or $field == "listofentriesid" or $field == "multipageid" or $field == "templateid") {
             continue;
         }
         if ($field == "sid") {
             $value = $newsid;
         }
         if ($field == "title") {
             $value = $newtitle;
         }
         if (!$start) {
             $insert_sql .= ", ";
         }
         $start = 0;
         $insert_sql .= '"' . formulize_db_escape($value) . '"';
     }
     $insert_sql .= ")";
     if (!($result = $this->db->query($insert_sql))) {
         print "error cloning screen: '{$title}'<br>SQL: {$insert_sql}<br>" . $xoopsDB->error();
         return false;
     }
     return $result;
 }
 function prepareDataForSaving($value, $element)
 {
     global $myts;
     if (!$myts) {
         $myts =& MyTextSanitizer::getInstance();
     }
     $ele_value = $element->getVar('ele_value');
     $ele_id = $element->getVar('ele_id');
     $value = ereg_replace('[^0-9.-]+', '', $value);
     $value = $myts->htmlSpecialChars($value);
     return formulize_db_escape($value);
 }
$formObject = $form_handler->get($_POST['formulize_admin_key']);
$form_id = $formObject->getVar('id_form');
if ($formObject->getVar('lockedform')) {
    return;
}
// If the user doesn't have edit form permission, then do nothing
$formulize_module_id = getFormulizeModId();
if (!$gperm_handler->checkRight("edit_form", $form_id, $xoopsUser->getGroups(), $formulize_module_id)) {
    return;
}
global $xoopsDB;
// check to see if we're dealing with a grouplist save or deletion
if ($_POST['grouplistname']) {
    $groupListId = intval($_POST['grouplistid']);
    $groupListGroups = formulize_db_escape(implode(",", $_POST['groups']));
    $name = formulize_db_escape($_POST['grouplistname']);
    // are we inserting or updating?
    $newList = $groupListId == 0 ? true : false;
    if (!$newList) {
        // Get exisitng name to see if we update, or create new.
        $result = $xoopsDB->query("SELECT gl_name FROM " . $xoopsDB->prefix("group_lists") . " WHERE gl_id='" . intval($groupListId) . "'");
        if ($xoopsDB->getRowsNum($result) > 0) {
            $entry = $xoopsDB->fetchArray($result);
            if ($entry['gl_name'] != $name) {
                $newList = true;
            }
        }
    }
    if ($newList) {
        $grouplist_query = "INSERT INTO " . $xoopsDB->prefix("group_lists") . " (gl_name, gl_groups) VALUES ('" . $name . "', '" . $groupListGroups . "')";
        $groupListId = $xoopsDB->getInsertId();
 function prepareDataForSaving($value, $element)
 {
     $timestamp = strtotime($value);
     if ($value != _DATE_DEFAULT and $value != "" and $timestamp !== false) {
         // $timestamp !== false should catch everything by itself? under some circumstance not yet figured out, the other checks could be useful?
         $value = date("Y-m-d", $timestamp);
     } else {
         $value = "{WRITEASNULL}";
         // forget about this date element and go on to the next element in the form
     }
     $value = '' . $value;
     return formulize_db_escape($value);
     // strictly speaking, formulize will already escape all values it writes to the database, but it's always a good habit to never trust what the user is sending you!
 }
    }
}
// if the form name was changed, then force a reload of the page...reload will be the application id
if (isset($_POST['reload_settings']) and $_POST['reload_settings'] == 1 or $formulize_altered_form_handle or $newAppObject or $_POST['application_url_id'] and !in_array($_POST['application_url_id'], $selectedAppIds)) {
    if (!in_array($_POST['application_url_id'], $selectedAppIds)) {
        $appidToUse = intval($selectedAppIds[0]);
    } else {
        $appidToUse = intval($_POST['application_url_id']);
    }
    print "/* eval */ ";
    if ($formulize_altered_form_handle) {
        print " alert('Some characters, such as punctuation, were removed from the form handle because they " . "are not allowed in the database table names or PHP variables.');\n";
    }
    print " reloadWithScrollPosition('" . XOOPS_URL . "/modules/formulize/admin/ui.php?page=form&aid={$appidToUse}&fid={$fid}');";
}
// need to do some other stuff here later to setup defaults for...
// screens?
// menu items?
// permissions?
// Auto menu link creation
// The link is shown to to Webmaster and registered users only (1,2 in $menuitems)
if ($_POST['formulize_admin_key'] == "new") {
    $menuitems = "null::" . formulize_db_escape($formObject->getVar('title')) . "::fid=" . formulize_db_escape($fid) . "::::1,2::null";
    if (!empty($selectedAppIds)) {
        foreach ($selectedAppIds as $appid) {
            $application_handler->insertMenuLink(formulize_db_escape($appid), $menuitems);
        }
    } else {
        $application_handler->insertMenuLink(0, $menuitems);
    }
}
Example #14
0
 function link_options()
 {
     global $xoopsDB;
     $elements = array();
     // initialize the class that can read the ele_value field
     $formulize_mgr =& xoops_getmodulehandler('elements');
     // get a list of all the linked select boxes since we need to know if any fields in these two forms are the source for any links
     $resgetlinksq = $xoopsDB->query("SELECT id_form, ele_caption, ele_id, ele_handle FROM " . $xoopsDB->prefix("formulize") . " WHERE ele_type=\"select\" AND ele_value LIKE '%#*=:*%' ORDER BY id_form");
     while ($rowlinksq = $xoopsDB->fetchRow($resgetlinksq)) {
         $target_form_ids[] = $rowlinksq[0];
         $target_captions[] = $rowlinksq[1];
         $target_ele_ids[] = $rowlinksq[2];
         // returns an object containing all the details about the form
         $elements =& $formulize_mgr->getObjects($criteria, $rowlinksq[0]);
         // search for the elements where the link exists
         foreach ($elements as $e) {
             $ele_id = $e->getVar('ele_id');
             // if this is the right element, then proceed and get the source of the link
             if ($ele_id == $rowlinksq[2]) {
                 $ele_value = $e->getVar('ele_value');
                 $details = explode("#*=:*", $ele_value[2]);
                 $source_form_ids[] = $details[0];
                 //get the element ID for the source we've just found
                 $sourceq = "SELECT ele_id, ele_caption FROM " . $xoopsDB->prefix("formulize") . " WHERE ele_handle = '" . formulize_db_escape($details[1]) . "' AND id_form = '{$details['0']}'";
                 if ($ressourceq = $xoopsDB->query($sourceq)) {
                     $rowsourceq = $xoopsDB->fetchRow($ressourceq);
                     $source_ele_ids[] = $rowsourceq[0];
                     $source_captions[] = $rowsourceq[1];
                 } else {
                     print "Error:  Query failed.  Searching for element ID for the caption {$details['1']} in form {$details['0']}";
                 }
             }
         }
     }
     // Arrays now set as follows:
     // target_form_ids == the ID of the form where the current linked selectbox resides
     // target_captions == the caption of the current linked selectbox
     // target_ele_ids == the element ID of the current linked selectbox
     // source_form_ids == the ID of the form where the source for the current linked selectbox resides
     // source_captions == the caption of the source for the current linked selectbox
     // source_ele_ids == the element ID of the source for the current linked selectbox
     // each index in those arrays denotes a distinct linked selectbox
     // example:
     // target_form_ids == 11
     // target_captions == Link to Name
     // target_ele_ids == 22
     // source_form_ids == 10
     // source_captions == Name
     // source_ele_ids == 20
     //determine the contents of the linkage box
     //find all links between these forms, but add User ID as the top value in the box
     // 1. Find all target links for form 1
     // 2. Check if the source is form 2
     // 3. If yes, add to the stack
     // 4. Repeat for form 2, looking for form 1
     // 5. Draw entries in box as follows:
     // form 1 field name/form 2 field name
     // 6. Account for the current link if one is specified, and make that the default selection
     $hits12 = $this->_findlink($this->getVar('form1'), $this->getVar('form2'), $target_form_ids, $source_form_ids);
     $hits21 = $this->_findlink($this->getVar('form2'), $this->getVar('form1'), $target_form_ids, $source_form_ids);
     $link_options = array();
     $loi = 1;
     if ($this->getVar('common') == 1) {
         // must retrieve the names of the fields, since they won't be in the target and source caps arrays, since those are focused only on the linked fields
         $element_handler =& xoops_getmodulehandler('elements', 'formulize');
         $ele1 = $element_handler->get($this->getVar('key1'));
         $ele2 = $element_handler->get($this->getVar('key2'));
         if (is_object($ele1)) {
             $name1 = $ele1->getVar('ele_colhead') ? printSmart($ele1->getVar('ele_colhead')) : printSmart($ele1->getVar('ele_caption'));
         } else {
             $name1 = '';
         }
         if (is_object($ele2)) {
             $name2 = $ele2->getVar('ele_colhead') ? printSmart($ele2->getVar('ele_colhead')) : printSmart($ele2->getVar('ele_caption'));
         } else {
             $name2 = '';
         }
         $link_options[$loi]['value'] = $this->getVar('key1') . "+" . $this->getVar('key2');
         $link_options[$loi]['name'] = _AM_FRAME_COMMON_VALUES . printSmart($name1, 20) . " & " . printSmart($name2, 20);
         $loi++;
     }
     $this->_buildlinkoptions($hits12, 0, $this->getVar('key1'), $this->getVar('key2'), $target_ele_ids, $source_ele_ids, $target_captions, $source_captions, $link_options, $loi);
     $this->_buildlinkoptions($hits21, 1, $this->getVar('key1'), $this->getVar('key2'), $target_ele_ids, $source_ele_ids, $target_captions, $source_captions, $link_options, $loi);
     return $link_options;
 }
Example #15
0
 function updateMenuLink($appid, $menuitems)
 {
     global $xoopsDB;
     //0=menuid, 1=menuText, 2=screen, 3=url, 4=groupids, 5=default_screen 6=note
     $linkValues = explode("::", $menuitems);
     //error_log("link values ".print_r($linkValues));
     $updatesql = "UPDATE `" . $xoopsDB->prefix("formulize_menu_links") . "` SET screen= '" . formulize_db_escape($linkValues[2]) . "', url= '" . formulize_db_escape($linkValues[3]) . "', link_text='" . formulize_db_escape($linkValues[1]) . "',note='" . formulize_db_escape($linkValues[6]) . "' where menu_id=" . formulize_db_escape($linkValues[0]) . " AND appid=" . $appid . ";";
     if (!($result = $xoopsDB->query($updatesql))) {
         exit("Error updating Menu Item. SQL dump:\n" . $updatesql . "\n" . $xoopsDB->error() . "\nPlease contact <a href=mailto:formulize@freeformsolutions.ca>Freeform Solutions</a> for assistance.");
     } else {
         //delete existing permissions for this menu item
         $deletepermissions = "DELETE FROM `" . $xoopsDB->prefix("formulize_menu_permissions") . "` WHERE menu_id=" . formulize_db_escape($linkValues[0]) . ";";
         $result = $xoopsDB->query($deletepermissions);
         if ($linkValues[4] != "null" and count($linkValues[4]) > 0) {
             $groupsThatCanView = explode(",", $linkValues[4]);
             $groupsThatCanView = array_map(array($xoopsDB, 'escape'), $groupsThatCanView);
             $groupsWithDefaultPage = explode(",", $linkValues[5]);
             $groupsWithDefaultPage = array_map(array($xoopsDB, 'escape'), $groupsWithDefaultPage);
             $defaultScreen = 0;
             foreach ($groupsThatCanView as $groupid) {
                 //check for default screen
                 if (in_array($groupid, $groupsWithDefaultPage)) {
                     $defaultScreen = 1;
                 }
                 $permissionsql = "INSERT INTO `" . $xoopsDB->prefix("formulize_menu_permissions") . "` VALUES (null," . formulize_db_escape($linkValues[0]) . "," . $groupid . "," . $defaultScreen . ")";
                 if (!($result = $xoopsDB->query($permissionsql))) {
                     exit("Error updating Menu Item permissions." . $linkValues[4] . " SQL dump:\n" . $permissionsql . "\n" . $xoopsDB->error() . "\nPlease contact <a href=mailto:formulize@freeformsolutions.ca>Freeform Solutions</a> for assistance.");
                 }
                 $defaultScreen = 0;
             }
         }
     }
 }
Example #16
0
 function get($id)
 {
     static $cachedElements = array();
     if (isset($cachedElements[$id])) {
         return $cachedElements[$id];
     }
     if ($id > 0 and is_numeric($id)) {
         $sql = 'SELECT * FROM ' . formulize_TABLE . ' WHERE ele_id=' . $id;
         if (!($result = $this->db->query($sql))) {
             $cachedElements[$id] = false;
             return false;
         }
     } else {
         $sql = 'SELECT * FROM ' . formulize_TABLE . ' WHERE ele_handle="' . formulize_db_escape($id) . '"';
         if (!($result = $this->db->query($sql))) {
             $cachedElements[$id] = false;
             return false;
         }
     }
     $numrows = $this->db->getRowsNum($result);
     if ($numrows == 1) {
         // instantiate the right kind of element, depending on the type
         $array = $this->db->fetchArray($result);
         $ele_type = $array['ele_type'];
         if (file_exists(XOOPS_ROOT_PATH . "/modules/formulize/class/" . $ele_type . "Element.php")) {
             $customTypeHandler = xoops_getmodulehandler($ele_type . "Element", 'formulize');
             $element = $customTypeHandler->create();
         } else {
             $element = new formulizeformulize();
         }
         $element->assignVars($array);
         $element->isLinked = false;
         $ele_type = $element->getVar('ele_type');
         if ($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 $ele_type == "derived") {
             $element->hasData = true;
         }
         if ($ele_type == "select") {
             $ele_value = $element->getVar('ele_value');
             if (!is_array($ele_value[2])) {
                 $element->isLinked = strstr($ele_value[2], "#*=:*") ? true : false;
             }
         }
         $cachedElements[$id] = $element;
         return $element;
     }
     return false;
 }
 function prepareDataForSaving($value, $element)
 {
     global $myts;
     if (!$myts) {
         $myts =& MyTextSanitizer::getInstance();
     }
     if (get_magic_quotes_gpc()) {
         $value = stripslashes($value);
     }
     $value = $myts->htmlSpecialChars($value);
     return formulize_db_escape($value);
     // strictly speaking, formulize will already escape all values it writes to the database, but it's always a good habit to never trust what the user is sending you!
 }
function loadReport($id, $fid, $frid)
{
    global $xoopsDB;
    if (is_numeric($id)) {
        $thisview = q("SELECT * FROM " . $xoopsDB->prefix("formulize_saved_views") . " WHERE sv_id='{$id}'");
    } else {
        if ($frid) {
            $formframe = intval($frid);
            $mainform = intval($fid);
        } else {
            $formframe = intval($fid);
            $mainform = "''";
        }
        $thisview = q("SELECT * FROM " . $xoopsDB->prefix("formulize_saved_views") . " WHERE sv_name='" . formulize_db_escape($id) . "' AND sv_formframe = {$formframe} AND sv_mainform = {$mainform}");
    }
    if (!isset($thisview[0]['sv_currentview'])) {
        print "Error: could not load the specified saved view: '" . strip_tags(htmlspecialchars($id)) . "'";
        return false;
    }
    $to_return[0] = $thisview[0]['sv_currentview'];
    $to_return[1] = $thisview[0]['sv_oldcols'];
    $to_return[2] = $thisview[0]['sv_asearch'];
    $to_return[3] = $thisview[0]['sv_calc_cols'];
    $to_return[4] = $thisview[0]['sv_calc_calcs'];
    $to_return[5] = $thisview[0]['sv_calc_blanks'];
    $to_return[6] = $thisview[0]['sv_calc_grouping'];
    $to_return[7] = $thisview[0]['sv_sort'];
    $to_return[8] = $thisview[0]['sv_order'];
    $to_return[9] = $thisview[0]['sv_hidelist'];
    $to_return[10] = $thisview[0]['sv_hidecalc'];
    $to_return[11] = $thisview[0]['sv_lockcontrols'];
    $to_return[12] = $thisview[0]['sv_quicksearches'];
    $to_return[13] = $thisview[0]['sv_global_search'];
    return $to_return;
}
 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;
     }
 }
Example #20
0
function patch30DataStructure($auto = false)
{
    global $xoopsDB;
    // check for new data structure and don't run this patch if it already has been!
    // check that patch30 has been run and don't run this patch unless it already has been!
    // check that formulize_form table exists, or else don't run the patch
    $patchCheckSql = "SHOW TABLES";
    $resultPatchCheck = $xoopsDB->queryF($patchCheckSql);
    $entryOwnerGroupFound = false;
    $formulizeFormFound = false;
    $newStructureFound = false;
    while ($table = $xoopsDB->fetchRow($resultPatchCheck)) {
        $secondPart = substr($table[0], strlen($xoopsDB->prefix("formulize_")));
        if (is_numeric($secondPart) and strstr($table[0], $xoopsDB->prefix("formulize_"))) {
            // there will be a part after "formulize_" that is numeric in the new data structure
            $newStructureFound = true;
        }
        if ($table[0] == $xoopsDB->prefix("formulize_entry_owner_groups")) {
            $entryOwnerGroupFound = true;
        }
        if ($table[0] == $xoopsDB->prefix("formulize_form")) {
            $formulizeFormFound = true;
        }
    }
    if (!$formulizeFormFound and $entryOwnerGroupFound) {
        print "<h1>It appears you have not upgraded from a previous version of Formulize.  You do not need to apply this patch unless you are upgrading from a version prior to 3.0</h1>\n";
        print "<p>If you did upgrade from a previous version, please contact <a href=mailto:formulize@freeformsolutions.ca>Freeform Solutions</a> for assistance.</p>\n";
        return;
    }
    if (!$entryOwnerGroupFound) {
        print "<h1>You must run \"patch31\" before upgrading to the 3.0 data structure.</h1>\n";
        print "<p><a href=\"" . XOOPS_URL . "/modules/formulize/admin/formindex.php?op=patch31\">Click here to run \"patch31\".</a></p>\n";
        return;
    }
    if ($newStructureFound) {
        print "<h1>You cannot run this patch after upgrading to the 3.0 data structure.</h1>";
        return;
    }
    $carryon = true;
    if (!$auto) {
        // put UI control in if not called from another function....not actually used; this patch must be invoked manually on its own.
        if (!isset($_POST['patch30datastructure'])) {
            $carryon = false;
            print "<form action=\"formindex.php?op=patch30datastructure\" method=post>";
            print "<h1>Warning: this patch completely changes the structure of the formulize data in your database.  Backup your database prior to applying this patch!</h1>";
            print "<p>This patch may take a few minutes to apply.  Your page may take that long to reload, please be patient.</p>";
            print "<p>You may need to increase the memory limit and/or max execution time in PHP, if you have a large database (100,000 records or more, depending on the size of your forms).</p>";
            print "<p>If the first version of Formulize that you installed was 3.0 or higher, you DO NOT need to apply this patch!</p>";
            print "<input type = submit name=patch30datastructure value=\"Apply Data Structure Patch for upgrading to Formulize 3.0 and higher\">";
            print "</form>";
        }
    }
    if ($carryon) {
        print "<h2>Patch Results:</h2>";
        // 1. figure out all the forms in existence
        // 2. for each one, devise the field names in its table
        // 3. create its table
        // 4. import its data from formulize_form
        include_once XOOPS_ROOT_PATH . "/modules/formulize/class/forms.php";
        include_once XOOPS_ROOT_PATH . "/modules/formulize/include/functions.php";
        $formHandler =& xoops_getmodulehandler('forms', 'formulize');
        $allFormObjects = $formHandler->getAllForms(true);
        // true flag causes all elements to be included in objects, not just elements that are being displayed, which are ignored in every other situation
        foreach ($allFormObjects as $formObjectId => $thisFormObject) {
            if ($thisFormObject->getVar('tableform')) {
                continue;
            }
            // only process actual Formulize forms
            if (!($tableCreationResult = $formHandler->createDataTable($thisFormObject))) {
                exit("Error: could not make the necessary new datatable for form " . $thisFormObject->getVar('id_form') . ".<br>" . $xoopsDB->error() . "<br>Please report this error to <a href=\"mailto:formulize@freeformsolutions.ca\">Freeform Solutions</a>.");
            }
            print "Created data table formulize_" . $thisFormObject->getVar('id_form') . ".  result: OK<br>\n";
            // map data in formulize_form into new table
            // 1. get an index of the captions to element ids
            // 2. get all the data organized by id_req
            // 3. insert the data
            $captionPlusHandlesSQL = "SELECT ele_caption, ele_handle FROM " . $xoopsDB->prefix("formulize") . " WHERE id_form = " . $thisFormObject->getVar('id_form');
            $captionPlusHandlesRes = $xoopsDB->query($captionPlusHandlesSQL);
            $captionHandleIndex = array();
            while ($captionPlusHandlesArray = $xoopsDB->fetchArray($captionPlusHandlesRes)) {
                $captionHandleIndex[str_replace("'", "`", $captionPlusHandlesArray['ele_caption'])] = $captionPlusHandlesArray['ele_handle'];
            }
            $dataSQL = "SELECT id_req, ele_caption, ele_value, ele_type FROM " . $xoopsDB->prefix("formulize_form") . " WHERE id_form = " . $thisFormObject->getVar('id_form') . " AND ele_type != \"areamodif\" AND ele_type != \"sep\" ORDER BY id_req";
            // for some reason areamodif and sep are stored in some really old data
            $dataRes = $xoopsDB->query($dataSQL);
            $prevIdReq = "";
            $insertSQL = "";
            unset($foundCaptions);
            $foundCaptions = array();
            while ($dataArray = $xoopsDB->fetchArray($dataRes)) {
                if (!isset($captionHandleIndex[$dataArray['ele_caption']])) {
                    if ($dataArray['ele_caption'] === '') {
                        print "Warning: you have data saved, with no caption specified, for entry number " . $dataArray['id_req'] . " (id_req) in form " . $thisFormObject->getVar('id_form') . ".  This data will be ignored.  Please contact <a href=\"mailto:formulize@freeformsolutions.ca\">Freeform Solutions</a> if you would like assistance cleaning this up.  This will NOT affect the upgrade to version 3.<br>";
                        continue;
                    } else {
                        print "Warning: the form " . $thisFormObject->getVar('id_form') . " does not have an element with the caption '" . $dataArray['ele_caption'] . "', but you have saved data associated with that caption.  This data will be ignored.  Please contact <a href=\"mailto:formulize@freeformsolutions.ca\">Freeform Solutions</a> if you would like assistance cleaning this up.  This will NOT affect the upgrade to version 3.<br>";
                        continue;
                    }
                }
                if ($dataArray['id_req'] != $prevIdReq) {
                    // we're on a new entry
                    unset($foundCaptions);
                    $foundCaptions = array();
                    // reset the list of captions we've found in this entry so far, since we're moving onto a different entry
                    $prevIdReq = $dataArray['id_req'];
                    // write whatever we just finished working on
                    if ($insertSQL) {
                        if (!($insertRes = $xoopsDB->query($insertSQL))) {
                            exit("Error: could not write data to the new table structure with this SQL: {$insertSQL}.<br>" . $xoopsDB->error() . "<br>Please report this error to <a href=\"mailto:formulize@freeformsolutions.ca\">Freeform Solutions</a>.");
                        }
                        $insertSQL = "";
                    }
                    // build the SQL for inserting this entry
                    $insertSQL = "INSERT INTO " . $xoopsDB->prefix("formulize_" . $thisFormObject->getVar('id_form')) . " SET entry_id = \"" . $dataArray['id_req'] . "\"";
                    $metaData = getMetaData($dataArray['id_req'], "", "", true);
                    // special last param necessary because we need to use the old meta process when doing this patch!
                    $creation_uid = $metaData['created_by_uid'];
                    $mod_uid = $metaData['last_update_by_uid'];
                    $creation_datetime = $metaData['created'] == "???" ? "" : $metaData['created'];
                    $mod_datetime = $metaData['last_update'];
                    $insertSQL .= ", creation_datetime = \"{$creation_datetime}\", mod_datetime = \"{$mod_datetime}\", creation_uid = \"{$creation_uid}\", mod_uid = \"{$mod_uid}\"";
                    // derive the owner groups and write them to the owner groups table
                    $ownerGroups = array();
                    if ($creation_uid) {
                        $member_handler =& xoops_gethandler('member');
                        $creationUser = $member_handler->getUser($creation_uid);
                        if (is_object($creationUser)) {
                            $ownerGroups = $creationUser->getGroups();
                        } else {
                            $ownerGroups[] = XOOPS_GROUP_ANONYMOUS;
                        }
                    } else {
                        $ownerGroups[] = XOOPS_GROUP_ANONYMOUS;
                    }
                    foreach ($ownerGroups as $thisGroup) {
                        $ownerInsertSQL = "INSERT INTO " . $xoopsDB->prefix("formulize_entry_owner_groups") . " (`fid`, `entry_id`, `groupid`) VALUES ('" . intval($thisFormObject->getVar('id_form')) . "', '" . intval($dataArray['id_req']) . "', '" . intval($thisGroup) . "')";
                        if (!($ownerInsertRes = $xoopsDB->query($ownerInsertSQL))) {
                            print "Error: could not write owner information to new data structure, using this SQL:<br>{$ownerInsertSQL}<br>" . $xoopsDB->error() . "<br>Please report this error to <a href=\"mailto:formulize@freeformsolutions.ca\">Freeform Solutions</a>.";
                        }
                    }
                }
                // record the caption and go through to the next one if this one already exists in this form
                if (isset($foundCaptions[$dataArray['ele_caption']])) {
                    print "Warning: you have duplicate captions, '" . $dataArray['ele_caption'] . "', in your data, at entry number " . $dataArray['id_req'] . " (id_req) in form " . $thisFormObject->getVar('id_form') . ".  Only the first value found will be copied to the new data structure.  Please contact <a href=\"mailto:formulize@freeformsolutions.ca\">Freeform Solutions</a> if you would like assistance cleaning this up.  This will NOT affect the upgrade to version 3.<br>";
                    continue;
                } else {
                    $foundCaptions[$dataArray['ele_caption']] = true;
                }
                // need to handle linked selectboxes, and convert them to a different format, and store the entry_id of the sources
                // We are going to store a comma separated list of entry_ids, with leading and trailing commas so a LIKE operator can be used to do a join in the database
                if (strstr($dataArray['ele_value'], "#*=:*")) {
                    $boxproperties = explode("#*=:*", $dataArray['ele_value']);
                    $source_ele_ids = explode("[=*9*:", $boxproperties[2]);
                    // get the id_reqs of the source ele_ids
                    $sourceIdReqSQL = "SELECT id_req FROM " . $xoopsDB->prefix("formulize_form") . " WHERE ele_id = " . implode(" OR ele_id = ", $source_ele_ids) . " ORDER BY id_req";
                    $sourceIdReqRes = $xoopsDB->query($sourceIdReqSQL);
                    $dataArray['ele_value'] = "";
                    while ($sourceIdReqArray = $xoopsDB->fetchArray($sourceIdReqRes)) {
                        $dataArray['ele_value'] .= "," . $sourceIdReqArray['id_req'];
                    }
                    if ($dataArray['ele_value']) {
                        $dataArray['ele_value'] .= ",";
                    }
                }
                if ($dataArray['ele_type'] == "date" and $dataArray['ele_value'] == "") {
                    continue;
                    // don't write in blank date values, let them get the default NULL value for the field
                }
                $insertSQL .= ", `" . $captionHandleIndex[$dataArray['ele_caption']] . "`=\"" . formulize_db_escape($dataArray['ele_value']) . "\"";
            }
            if ($insertSQL) {
                if (!($insertRes = $xoopsDB->query($insertSQL))) {
                    exit("Error: could not write data to the new table structure with this SQL: {$insertSQL}.<br>" . $xoopsDB->error() . "<br>Please report this error to <a href=\"mailto:formulize@freeformsolutions.ca\">Freeform Solutions</a>.");
                }
            }
            print "Migrated data to new data structure for form " . $thisFormObject->getVar('id_form') . ".  result: OK<br>\n";
            unset($allFormObjects[$formObjectId]);
            // attempt to free up some memory
        }
        if ($derivedResult = formulize_createDerivedValueFieldsInDB()) {
            print "Created derived value fields in database.  result: OK<br>\n";
        } else {
            print "Unable to create derived value fields in database.  result: failed.  contact <a href=\"mailto:formulize@freeformsolutions.ca\">Freeform Solutions</a> for assistance.<br>\n";
        }
        // convert the captions in the linked selectbox defintions to the handles for those elements
        // 1. lookup all elements that are linked selectboxes in the formulize table (element table) -- db query for element ids
        // 2. for each one, get the caption that is stored there -- PHP level work with element handler
        // 3. get the handle corresponding to that caption
        // 4. rewrite the ele_value[2] with the handle instead of caption
        // 5. reinsert that value into the DB
        $sql = "SELECT ele_id FROM " . $xoopsDB->prefix("formulize") . " WHERE ele_value LIKE '%#*=:*%'";
        if (!($res = $xoopsDB->query($sql))) {
            exit("Error: cound not get the element ids of the linked selectboxes.  SQL: {$sql}<br>" . $xoopsDB->error() . "<br>Please report this error to <a href=\"mailto:formulize@freeformsolutions.ca\">Freeform Solutions</a>.");
        }
        $element_handler =& xoops_getmodulehandler('elements', 'formulize');
        while ($array = $xoopsDB->fetchArray($res)) {
            $elementObject = $element_handler->get($array['ele_id']);
            $ele_value = $elementObject->getVar('ele_value');
            $parts = explode("#*=:*", $ele_value[2]);
            $sql2 = "SELECT ele_handle FROM " . $xoopsDB->prefix("formulize") . " WHERE ele_caption = '" . formulize_db_escape($parts[1]) . "' AND id_form=" . $parts[0];
            //print "$sql2<br>";
            if (!($res2 = $xoopsDB->query($sql2))) {
                exit("Error: could not get the handle for a linked selectbox source.  SQL: {$sql2}<br>" . $xoopsDB->error() . "<br>Please report this error to <a href=\"mailto:formulize@freeformsolutions.ca\">Freeform Solutions</a>.");
            }
            $array2 = $xoopsDB->fetchArray($res2);
            if ($array2['ele_handle'] == "") {
                print "Warning: a handle could not be identified for this caption: '" . $parts[1] . "', in form " . $parts[0] . "  This breaks linked selectboxes for element number " . $array['ele_id'] . ".  This is most likely caused by an old caption that was changed for the element, in an old version of Formulize.<br>Please report this error to <a href=\"mailto:formulize@freeformsolutions.ca\">Freeform Solutions</a>.<br>";
            }
            $ele_value[2] = $parts[0] . "#*=:*" . $array2['ele_handle'];
            $elementObject->setVar('ele_value', $ele_value);
            if (!($res3 = $element_handler->insert($elementObject))) {
                exit("Error: could not update the linked selectbox metadata. <br>" . $xoopsDB->error() . "<br>Please report this error to <a href=\"mailto:formulize@freeformsolutions.ca\">Freeform Solutions</a>.");
            }
            unset($parts);
            unset($elementObject);
        }
        print "Updated the linked selectbox definitions new metadata.  result: OK<br><br><b>NOTE:</b> Although the 3.0 data structure is highly optimized compared to previous versions of Formulize, there are some situations which we cannot account for automatically in the upgrade process:  if you have elements in a form and users only enter numerical data there, you should edit those elements now and give them a truly numeric data type (use the new option on the element editing page to do this).  In Formulize 3 and higher, elements that have only numbers, but which are not stored as numbers in the database, will not sort properly and some calculations will not work correctly on them either.  Unfortunately, we cannot reliably determine which numeric data type should be used for all elements, therefore you will need to make this adjustment manually.  We apologize for any inconvenience.  Please contact <a href=\"mailto:formulize@freeformsolutions.ca\">Freeform Solutions</a> if you have any questions about this process.<br><br>\n";
        print "Data migration complete.  result: OK\n";
    }
}
Example #21
0
function parseTableFormFilter($filter, $andor, $elementsById)
{
    $whereClause = "";
    $andor = $andor == "AND" ? "AND" : "OR";
    foreach (explode("][", $filter) as $thisFilter) {
        if ($thisFilter == "") {
            continue;
        }
        if ($whereClause != "") {
            $whereClause .= " {$andor} ";
        }
        $filterParts = explode("/**/", $thisFilter);
        $operator = isset($filterParts[2]) ? $filterParts[2] : "LIKE";
        $likeparts = ($operator == "LIKE" or $operator == "NOT LIKE") ? "%" : "";
        $whereClause .= $elementsById[$filterParts[0]]['field'] . " {$operator} '{$likeparts}" . formulize_db_escape($filterParts[1]) . "{$likeparts}'";
    }
    return $whereClause;
}
Example #22
0
        $not_cons_elementuids = intval($_POST['ele_id']);
    } elseif ($_POST['setwho'] === "linkcreator" and intval($_POST['lc_ele_id']) > 0) {
        $not_cons_linkcreator = intval($_POST['lc_ele_id']);
    } elseif ($_POST['setwho'] === "elementemail" and intval($_POST['email_ele_id']) > 0) {
        $not_cons_elementemail = intval($_POST['email_ele_id']);
    } else {
        $not_cons_uid = $uid;
        // since this is a user specific notification, set a subscription for it
        $notification_handler =& xoops_gethandler('notification');
        $notification_handler->subscribe('form', $fid, $_POST['setwhen'], '', $mid, $not_cons_uid);
        $thisnot = $notification_handler->getNotification($mid, 'form', $fid, $_POST['setwhen'], $not_cons_uid);
    }
    $not_cons_con = ($_POST['setfor'] == "all" or count($_POST['terms']) == 0) ? "all" : serialize(array(serialize($_POST['elements']), serialize($_POST['ops']), serialize($_POST['terms'])));
    $template_filename = strstr($_POST['template'], ".tpl") ? str_replace(".tpl", "", $_POST['template']) : $_POST['template'];
    // strip .tpl out of the template name if it's present
    $sql = "INSERT INTO " . $xoopsDB->prefix("formulize_notification_conditions") . " (not_cons_fid, not_cons_event, not_cons_uid, not_cons_curuser, not_cons_groupid, not_cons_creator, not_cons_elementuids, not_cons_linkcreator, not_cons_elementemail, not_cons_con, not_cons_template, not_cons_subject) VALUES (\"{$fid}\", \"" . formulize_db_escape($_POST['setwhen']) . "\", \"{$not_cons_uid}\", \"{$not_cons_curuser}\", \"{$not_cons_groupid}\", \"{$not_cons_creator}\", \"{$not_cons_elementuids}\", \"{$not_cons_linkcreator}\", \"{$not_cons_elementemail}\", \"" . formulize_db_escape($not_cons_con) . "\", \"" . formulize_db_escape($template_filename) . "\", \"" . formulize_db_escape($_POST['subject']) . "\")";
    if (!($result = $xoopsDB->query($sql))) {
        exit("Error:  notification could not be saved.  SQL:<br>{$sql}<br>");
    }
    unset($_POST);
}
$deleted = handleDelete($uid, $fid, $mid);
// returns 1 if a deletion was made, 0 if not.
// Get all existing notifications
// $nots will be an array sent back by the q function
$nots = getCurNots($fid, $canSetNots, $xoopsUser->getVar('uid'));
$noNots = count($nots) == 0 ? true : false;
// get the groups and group names, and the elements with fullnames or usernames in them
if ($canSetNots) {
    $set_groups1 = $gperm_handler->getGroupIds("view_groupscope", $fid, $mid);
    $set_groups2 = $gperm_handler->getGroupIds("view_globalscope", $fid, $mid);
 function prepareDataForDataset($value, $handle, $entry_id)
 {
     if (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($handle) . "\" AND " . DBPRE . "formulize_other.id_req='" . intval($entry_id) . "' LIMIT 0,1");
         $value_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 = preg_replace('/\\{OTHER\\|+[0-9]+\\}/', $value_other, $value);
     }
     return $value;
     // we're not making any modifications for this element type
 }
 function setFilterVariables($filtersAndGroupings, $acid)
 {
     // need to construct user defined filter variables so they can be picked up in the evals below as required
     // 1. check this procedure to see what the filter options are
     // 2. grab required user info to build the filter option, from POST (since the user's defined choices will be in POST)
     // 3. make variables as text ready for use in SQL, including right table aliases, etc
     $packedFormFilters = array();
     $form_handler = xoops_getmodulehandler('forms', 'formulize');
     $element_handler = xoops_getmodulehandler('elements', 'formulize');
     foreach ($filtersAndGroupings as $thisFilter) {
         if ($thisFilter['is_filter']) {
             $fieldName = "";
             $formId = "";
             $filterValue = $thisFilter['form_alias'] ? $thisFilter['form_alias'] . "." : "";
             $postName = $acid . "_" . $thisFilter['handle'];
             if ($thisFilter['form'] and is_numeric($thisFilter['form'])) {
                 $elementObject = $element_handler->get($thisFilter['form']);
                 $formId = $elementObject->getVar('id_form');
                 if (is_object($elementObject)) {
                     $fieldName = $elementObject->getVar('ele_handle');
                     if ($thisFilter['type']['kind'] == 3) {
                         $filterValue .= "`" . $fieldName . "` IN (";
                     } else {
                         $filterValue .= "`" . $fieldName . "` = '";
                     }
                 }
             }
             if (isset($_POST[$postName]) and $_POST[$postName] == '' and $_POST[$postName] !== 0) {
                 $filterValue = " 1 ";
             } else {
                 if ($thisFilter['type']['kind'] == 3) {
                     // is a checkbox filter with possibly multiple selections
                     $options = array();
                     foreach ($_POST[$postName] as $index => $flag) {
                         $optionValue = explode("|", $thisFilter["type"]["options"][$index]);
                         if (count($optionValue) == 2) {
                             $optionValue = $optionValue[0];
                         }
                         $options[] = is_numeric($optionValue) ? $optionValue : "'" . formulize_db_escape($optionValue) . "'";
                     }
                     if (count($options) > 0) {
                         $filterValue .= implode(", ", $options);
                         if ($thisFilter['form'] and is_numeric($thisFilter['form'])) {
                             $filterValue .= ")";
                         }
                     } else {
                         $filterValue = " 1 ";
                     }
                 } else {
                     if ($thisFilter['type']['kind'] == 1) {
                         // 1 is dateboxes
                         $filterValue = date("Y-m-d", strtotime($_POST[$postName]));
                     } else {
                         $filterValue .= is_numeric($_POST[$postName]) ? $_POST[$postName] : formulize_db_escape($_POST[$postName]);
                         $filterValue .= $fieldName ? "'" : "";
                         // close out the ' started above after we figured out the field this filter belongs to
                     }
                 }
             }
             if ($formId) {
                 $packedFormFilters[$formId][$thisFilter['handle']] = $filterValue;
             } else {
                 $packedFormFilters[0][$thisFilter['handle']] = $filterValue;
             }
         }
     }
     /*global $xoopsUser;
         if($xoopsUser->getVar('uid')==1021) {
     	print_r( $packedFormFilters );
         }*/
     return $packedFormFilters;
 }
 function prepareDataForSaving($value, $element)
 {
     return formulize_db_escape($value);
     // strictly speaking, formulize will already escape all values it writes to the database, but it's always a good habit to never trust what the user is sending you!
 }
Example #26
0
function _buildConditionsFilterSQL($filterId, &$filterOps, &$filterTerms, $filterElementIds, $targetFormElementTypes, $curlyBracketEntry, $userComparisonId, $curlyBracketForm, $element_handler, $form_handler)
{
    global $xoopsUser, $xoopsDB;
    $conditionsFilterComparisonValue = "";
    $curlyBracketFormFrom = "";
    if ($filterOps[$filterId] == "NOT") {
        $filterOps[$filterId] = "!=";
    }
    if (strstr(strtoupper($filterOps[$filterId]), "LIKE")) {
        $likebits = "%";
        $origlikebits = "%";
        $quotes = "'";
    } else {
        $likebits = "";
        $origlikebits = "";
        $quotes = is_numeric($filterTerms[$filterId]) ? "" : "'";
    }
    if ($targetFormElementTypes[$filterElementIds[$filterId]] == "select") {
        // check for whether the source element is a linked selectbox, and if so, figure out the entry id of the record in the source of that linked selectbox which matches the filter term instead
        $targetElementObject = $element_handler->get($filterElementIds[$filterId]);
        if ($targetElementObject->isLinked) {
            $targetElementEleValue = $targetElementObject->getVar('ele_value');
            // get the properties of the source element
            $targetElementEleValueProperties = explode("#*=:*", $targetElementEleValue[2]);
            // split them up to get the properties of the linked selectbox that the source element is pointing at
            $targetSourceFid = $targetElementEleValueProperties[0];
            // get the Fid that the source element is point at (the source of the source)
            $targetSourceFormObject = $form_handler->get($targetSourceFid);
            // get the form object based on that fid (we'll need the form handle later)
            $targetSourceHandle = $targetElementEleValueProperties[1];
            // get the element handle in the source source form
            // now build a comparison value that contains a subquery on the source source form, instead of a literal match to the source form
            if (substr($filterTerms[$filterId], 0, 1) == "{" and substr($filterTerms[$filterId], -1) == "}") {
                if (isset($GLOBALS['formulize_asynchronousFormDataInDatabaseReadyFormat'][$curlyBracketEntry][substr($filterTerms[$filterId], 1, -1)])) {
                    $filterTermToUse = "'" . $GLOBALS['formulize_asynchronousFormDataInDatabaseReadyFormat'][$curlyBracketEntry][substr($filterTerms[$filterId], 1, -1)] . "'";
                } else {
                    $filterTermToUse = " curlybracketform.`" . formulize_db_escape(substr($filterTerms[$filterId], 1, -1)) . "` ";
                    $curlyBracketFormFrom = ", " . $xoopsDB->prefix("formulize_" . $curlyBracketForm->getVar('form_handle')) . " AS curlybracketform ";
                    // set as a single value, we're assuming all { } terms refer to the same form
                }
                // figure out if the curlybracketform field is linked and pointing to the same source as the target element is pointing to
                // because if it is, then we don't need to do a subquery later, we just compare directly to the $filterTermToUse
                $curlyBracketElementObject = $element_handler->get(substr($filterTerms[$filterId], 1, -1));
                if ($curlyBracketElementObject->isLinked) {
                    $curlyBracketTargetElementEleValue = $curlyBracketElementObject->getVar('ele_value');
                    $curlyBracketTargetElementEleValueProperties = explode("#*=:*", $curlyBracketTargetElementEleValue[2]);
                    $curlyBracketTargetSourceHandle = $curlyBracketTargetElementEleValueProperties[1];
                    if ($curlyBracketTargetSourceHandle == $targetSourceHandle) {
                        $conditionsFilterComparisonValue = " CONCAT('{$likebits}',{$filterTermToUse},'{$likebits}') ";
                        // filterTermToUse will already have , , around it so we don't need them in the two concat'd parts before and after
                    }
                }
                // curlybracket term found, but it's not linked to the same source as the target, so we have to work the likebits in as part of a concat, since our term is not a literal string anymore
                if ($likebits) {
                    $filterTermToUse = " CONCAT('{$likebits}',{$filterTermToUse},'{$likebits}') ";
                }
                // then neuter these, so they don't screw up the building of the query...note the use of origlikebits so that the higher level part of the query retains that logic if the user asked for it
                $quotes = "";
                $likebits = "";
            } else {
                $filterTermToUse = formulize_db_escape($filterTerms[$filterId]);
            }
            if (!$conditionsFilterComparisonValue) {
                if ($targetElementEleValue[1]) {
                    $conditionsFilterComparisonValue = " CONCAT('{$origlikebits},',(SELECT ss.entry_id FROM " . $xoopsDB->prefix("formulize_" . $targetSourceFormObject->getVar('form_handle')) . " AS ss WHERE `{$targetSourceHandle}` " . $filterOps[$filterId] . $quotes . $likebits . $filterTermToUse . $likebits . $quotes . "),',{$origlikebits}') ";
                } else {
                    $overrideReturnedOp = "";
                    if ($filterOps[$filterId] == "!=") {
                        $filterOps[$filterId] = "=";
                        $overrideReturnedOp = "!=";
                    }
                    $conditionsFilterComparisonValue = " (SELECT ss.entry_id FROM " . $xoopsDB->prefix("formulize_" . $targetSourceFormObject->getVar('form_handle')) . " AS ss WHERE `{$targetSourceHandle}` " . $filterOps[$filterId] . $quotes . $likebits . $filterTermToUse . $likebits . $quotes . ") ";
                    // need to change the filterOp being used, so when this is inserted into the main query, we have a different op introducing the subquery
                    if ($filterOps[$filterId] == "LIKE" or $filterOps[$filterId] == "NOT LIKE") {
                        $overrideReturnedOp = "IN";
                    }
                    $filterOps[$filterId] = $overrideReturnedOp ? $overrideReturnedOp : '=';
                }
            }
            if (substr($filterTerms[$filterId], 0, 1) == "{" and substr($filterTerms[$filterId], -1) == "}" and !isset($GLOBALS['formulize_asynchronousFormDataInDatabaseReadyFormat'][$curlyBracketEntry][substr($filterTerms[$filterId], 1, -1)])) {
                $conditionsFilterComparisonValue .= "  AND curlybracketform.`entry_id`={$curlyBracketEntry} ";
            }
        }
    } else {
        foreach ($filterTerms as $key => $value) {
            $filterTerms[$key] = parseUserAndToday($value);
        }
    }
    if ($filterOps[$filterId] == "=") {
        $filterTerms[$filterId] = prepareLiteralTextForDB($element_handler->get($filterElementIds[$filterId]), $filterTerms[$filterId], $curlyBracketEntry, $userComparisonId);
        // prepends checkbox characters and converts yes/nos, {USER}, etc
    }
    if ($filterTerms[$filterId] == "{BLANK}") {
        $conditionsFilterComparisonValue = 'NULL';
        $filterTerms[$filterId] = "";
        if ($filterOps[$filterId] == '!=' or $filterOps[$filterId] == 'NOT LIKE') {
            $filterOps[$filterId] = 'IS NOT';
        } else {
            $filterOps[$filterId] = 'IS';
        }
    }
    if (!$conditionsFilterComparisonValue) {
        $conditionsFilterComparisonValue = $quotes . $likebits . formulize_db_escape($filterTerms[$filterId]) . $likebits . $quotes;
    }
    // if it's a { } term, then assume it's a data handle for a field in the form where the element is being included
    if (substr($filterTerms[$filterId], 0, 1) == "{" and substr($filterTerms[$filterId], -1) == "}" and !$targetElementObject->isLinked) {
        if (isset($GLOBALS['formulize_asynchronousFormDataInDatabaseReadyFormat'][$curlyBracketEntry][substr($filterTerms[$filterId], 1, -1)])) {
            $conditionsFilterComparisonValue = "'" . formulize_db_escape($GLOBALS['formulize_asynchronousFormDataInDatabaseReadyFormat'][$curlyBracketEntry][substr($filterTerms[$filterId], 1, -1)]) . "'";
        } elseif ($curlyBracketEntry == "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
            $elementObject = $element_handler->get(substr($filterTerms[$filterId], 1, -1));
            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
                    $default = getTextboxDefault($ele_value[$defaultKey], $elementObject->getVar('id_form'), $curlyBracketEntry);
                    $conditionsFilterComparisonValue = is_numeric($default) ? $default : "'" . $default . "'";
                } else {
                    $conditionsFilterComparisonValue = "";
                }
            } else {
                $conditionsFilterComparisonValue = "";
            }
        } else {
            // set as a single value, we're assuming all { } terms refer to the same form
            $curlyBracketFormFrom = ", " . $xoopsDB->prefix("formulize_" . $curlyBracketForm->getVar('form_handle')) . " AS curlybracketform ";
            if ($likebits == "%") {
                $conditionsFilterComparisonValue = " CONCAT('%',curlybracketform.`" . substr($filterTerms[$filterId], 1, -1) . "`,'%') AND curlybracketform.`entry_id`={$curlyBracketEntry} ";
            } else {
                $conditionsFilterComparisonValue = " curlybracketform.`" . substr($filterTerms[$filterId], 1, -1) . "` AND curlybracketform.`entry_id`={$curlyBracketEntry} ";
            }
        }
    }
    return array($conditionsFilterComparisonValue, $curlyBracketFormFrom);
}