Example #1
0
function compileElements($fid, $form, $formulize_mgr, $prevEntry, $entry, $go_back, $parentLinks, $owner_groups, $groups, $overrideValue = "", $elements_allowed = "", $profileForm = "", $frid = "", $mid, $sub_entries, $sub_fids, $member_handler, $gperm_handler, $title, $screen = null, $printViewPages = "", $printViewPageTitles = "")
{
    include_once XOOPS_ROOT_PATH . '/modules/formulize/include/elementdisplay.php';
    $entryForDEElements = is_numeric($entry) ? $entry : "new";
    // if there is no entry, ie: a new entry, then $entry is "" so when writing the entry value into decue_ and other elements that go out to the HTML form, we need to use the keyword "new"
    global $xoopsDB, $xoopsUser;
    $elementsAvailableToUser = array();
    // set criteria for matching on display
    // set the basics that everything has to match
    $criteriaBase = new CriteriaCompo();
    $criteriaBase->add(new Criteria('ele_display', 1), 'OR');
    foreach ($groups as $thisgroup) {
        $criteriaBase->add(new Criteria('ele_display', '%,' . $thisgroup . ',%', 'LIKE'), 'OR');
    }
    if (is_array($elements_allowed) and count($elements_allowed) > 0) {
        // if we're limiting the elements, then add a criteria for that (multiple criteria are joined by AND unless you specify OR manually when adding them (as in the base above))
        $criteria = new CriteriaCompo();
        $criteria->add(new Criteria('ele_id', "(" . implode(",", $elements_allowed) . ")", "IN"));
        $criteria->add($criteriaBase);
    } else {
        $criteria = $criteriaBase;
        // otherwise, just use the base
    }
    $criteria->setSort('ele_order');
    $criteria->setOrder('ASC');
    $elements =& $formulize_mgr->getObjects($criteria, $fid, true);
    // true makes the keys of the returned array be the element ids
    $count = 0;
    global $gridCounter;
    $gridCounter = array();
    $inGrid = 0;
    formulize_benchmark("Ready to loop elements.");
    // set the array to be used as the structure of the loop, either the passed in elements in order, or the elements as gathered from the DB
    // ignore passed in element order if there's a screen in effect, since we assume that official element order is authoritative when screens are involved
    // API should still allow arbitrary ordering, so $element_allowed can still be set manually as part of a displayForm call, and the order will be respected then
    if (!is_array($elements_allowed) or $screen) {
        $element_order_array = $elements;
    } else {
        $element_order_array = $elements_allowed;
    }
    // if this is a printview page,
    foreach ($element_order_array as $thisElement) {
        if (is_numeric($thisElement)) {
            // if we're doing the order based on passed in element ids...
            if (isset($elements[$thisElement])) {
                $i = $elements[$thisElement];
                // set the element object for this iteration of the loop
            } else {
                continue;
                // do not try to render elements that don't exist in the form!! (they might have been deleted from a multipage definition, or who knows what)
            }
            $this_ele_id = $thisElement;
            // set the element ID number
        } else {
            // else...we're just looping through the elements directly from the DB
            $i = $thisElement;
            // set the element object
            $this_ele_id = $i->getVar('ele_id');
            // get the element ID number
        }
        // check if we're at the start of a page, when doing a printable view of all pages (only situation when printViewPageTitles and printViewPages will be present), and if we are, then put in a break for the page titles
        if ($printViewPages) {
            if (!$currentPrintViewPage) {
                $currentPrintViewPage = 1;
            }
            while (!in_array($this_ele_id, $printViewPages[$currentPrintViewPage]) and $currentPrintViewPage <= count($printViewPages)) {
                $currentPrintViewPage++;
            }
            if ($this_ele_id == $printViewPages[$currentPrintViewPage][0]) {
                $form->insertBreak("<div id=\"formulize-printpreview-pagetitle\">" . $printViewPageTitles[$currentPrintViewPage] . "</div>", "head");
            }
        }
        // check if this element is included in a grid, and if so, skip it
        // $inGrid will be a number indicating how many times we have to skip things
        if ($inGrid or isset($gridCounter[$this_ele_id])) {
            if (!$inGrid) {
                $inGrid = $gridCounter[$this_ele_id];
            }
            $inGrid--;
            continue;
        }
        $uid = is_object($xoopsUser) ? $xoopsUser->getVar('uid') : 0;
        $owner = getEntryOwner($entry, $fid);
        $ele_type = $i->getVar('ele_type');
        $ele_value = $i->getVar('ele_value');
        if ($go_back['form']) {
            // if there's a parent form...
            // check here to see if we need to initialize the value of a linked selectbox when it is the key field for a subform
            // although this is setup as a loop through all found parentLinks, only the last one will be used, since ele_value[2] is overwritten each time.
            // assumption is there will only be one parent link for this form
            for ($z = 0; $z < count($parentLinks['source']); $z++) {
                if ($this_ele_id == $parentLinks['self'][$z]) {
                    // this is the element
                    $ele_value[2] = $go_back['entry'];
                    // 3.0 datastructure...needs to be tested!! -- now updated for 5.0
                }
            }
        } elseif ($overrideValue) {
            // used to force a default setting in a form element, other than the normal default
            if (!is_array($overrideValue)) {
                //convert a string to an array so that strings don't screw up logic below (which is designed for arrays)
                $temp = $overrideValue;
                unset($overrideValue);
                $overrideValue[0] = $temp;
            }
            // currently only operative for select boxes
            switch ($ele_type) {
                case "select":
                    foreach ($overrideValue as $ov) {
                        if (array_key_exists($ov, $ele_value[2])) {
                            $ele_value[2][$ov] = 1;
                        }
                    }
                    break;
                case "date":
                    // debug
                    //var_dump($overrideValue);
                    foreach ($overrideValue as $ov) {
                        //if(ereg ("([0-9]{4})-([0-9]{2})-([0-9]{2})", $ov, $regs)) {
                        if (ereg("([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})", $ov, $regs)) {
                            $ele_value[0] = $ov;
                        }
                    }
                    break;
            }
        }
        if ($ele_type != "subform" and $ele_type != 'grid') {
            // "" is framework, ie: not applicable
            // $i is element object
            // $entry is entry_id
            // false is "nosave" param...only used to force element to not be picked up by readelements.php after saving
            // $screen is the screen object
            // false means don't print it out to screen, return it here
            $GLOBALS['formulize_sub_fids'] = $sub_fids;
            // set here so we can pick it up in the render method of elements, if necessary (only necessary for subforms?);
            $deReturnValue = displayElement("", $i, $entry, false, $screen, $prevEntry, false, $profileForm, $groups);
            if (is_array($deReturnValue)) {
                $form_ele = $deReturnValue[0];
                $isDisabled = $deReturnValue[1];
            } else {
                $form_ele = $deReturnValue;
                $isDisabled = false;
            }
            $elementsAvailableToUser[$this_ele_id] = true;
            if ($form_ele == "not_allowed" or $form_ele == "hidden") {
                if (isset($GLOBALS['formulize_renderedElementHasConditions']["de_" . $fid . "_" . $entryForDEElements . "_" . $this_ele_id])) {
                    // need to add a tr container for elements that are not allowed, since if it was a condition that caused them to not show up, they might appear later on asynchronously, and we'll need the row to attach them to
                    if ($ele_type == "ib" and $form_ele == "not_allowed") {
                        $rowHTML = "<tr style='display: none' id='formulize-de_" . $fid . "_" . $entryForDEElements . "_" . $this_ele_id . "'></tr>";
                    } elseif ($form_ele == "not_allowed") {
                        $rowHTML = "<tr style='display: none' id='formulize-de_" . $fid . "_" . $entryForDEElements . "_" . $this_ele_id . "' valign='top' align='" . _GLOBAL_LEFT . "'></tr>";
                    }
                    // need to also get the validation code for this element, wrap it in a check for the table row being visible, and assign that to the global array that contains all the validation javascript that we need to add to the form
                    // following code follows the pattern set in elementdisplay.php for actually creating rendered element objects
                    if ($ele_type != "ib") {
                        $conditionalValidationRenderer = new formulizeElementRenderer($i);
                        if ($prevEntry or $profileForm === "new") {
                            $data_handler = new formulizeDataHandler($i->getVar('id_form'));
                            $ele_value = loadValue($prevEntry, $i, $ele_value, $data_handler->getEntryOwnerGroups($entry), $groups, $entry, $profileForm);
                            // get the value of this element for this entry as stored in the DB -- and unset any defaults if we are looking at an existing entry
                        }
                        $conditionalElementForValidiationCode = $conditionalValidationRenderer->constructElement("de_" . $fid . "_" . $entryForDEElements . "_" . $this_ele_id, $ele_value, $entry, $isDisabled, $screen);
                        if ($js = $conditionalElementForValidiationCode->renderValidationJS()) {
                            $GLOBALS['formulize_renderedElementsValidationJS'][$GLOBALS['formulize_thisRendering']][$conditionalElementForValidiationCode->getName()] = "if(window.document.getElementById('formulize-" . $conditionalElementForValidiationCode->getName() . "').style.display != 'none') {\n" . $js . "\n}\n";
                        }
                        unset($conditionalElementForValidiationCode);
                        unset($conditionalValidationRenderer);
                    }
                    $form->addElement($rowHTML);
                    // since it was treated as a conditional element, and the user might interact with it, then we don't consider it a not-available-to-user element
                    unset($elementsAvailableToUser[$this_ele_id]);
                }
                continue;
            }
        }
        $req = !$isDisabled ? intval($i->getVar('ele_req')) : 0;
        $GLOBALS['sub_entries'] = $sub_entries;
        if ($ele_type == "subform") {
            $thissfid = $ele_value[0];
            if (!$thissfid) {
                continue;
            }
            // can't display non-specified subforms!
            $deReturnValue = displayElement("", $i, $entry, false, $screen, $prevEntry, false, $profileForm, $groups);
            // do this just to evaluate any conditions...it won't actually render anything, but will return "" for the first key in the array, if the element is allowed
            if (is_array($deReturnValue)) {
                $form_ele = $deReturnValue[0];
                $isDisabled = $deReturnValue[1];
            } else {
                $form_ele = $deReturnValue;
                $isDisabled = false;
            }
            if ($passed = security_check($thissfid) and $form_ele == "") {
                $GLOBALS['sfidsDrawn'][] = $thissfid;
                $customCaption = $i->getVar('ele_caption');
                $customElements = $ele_value[1] ? explode(",", $ele_value[1]) : "";
                if (isset($GLOBALS['formulize_inlineSubformFrid'])) {
                    $newLinkResults = checkForLinks($GLOBALS['formulize_inlineSubformFrid'][0], array($fid), $fid, array($fid => array($entry)), null, $owner_groups, $mid, null, $owner, true);
                    // final true means only include entries from unified display linkages
                    $sub_entries = $newLinkResults['sub_entries'];
                }
                // 2 is the number of default blanks, 3 is whether to show the view button or not, 4 is whether to use captions as headings or not, 5 is override owner of entry, $owner is mainform entry owner, 6 is hide the add button, 7 is the conditions settings for the subform element, 8 is the setting for showing just a row or the full form, 9 is text for the add entries button
                $subUICols = drawSubLinks($thissfid, $sub_entries, $uid, $groups, $frid, $mid, $fid, $entry, $customCaption, $customElements, intval($ele_value[2]), $ele_value[3], $ele_value[4], $ele_value[5], $owner, $ele_value[6], $ele_value[7], $this_ele_id, $ele_value[8], $ele_value[9], $thisElement);
                if (isset($subUICols['single'])) {
                    $form->insertBreak($subUICols['single'], "even");
                } else {
                    $subLinkUI = new XoopsFormLabel($subUICols['c1'], $subUICols['c2']);
                    $form->addElement($subLinkUI);
                }
                unset($subLinkUI);
            }
        } elseif ($ele_type == "grid") {
            // we are going to have to store some kind of flag/counter with the id number of the starting element in the table, and the number of times we need to ignore things
            // we need to then listen for this up above and skip those elements as they come up.  This is why grids must come before their elements in the form definition
            include_once XOOPS_ROOT_PATH . "/modules/formulize/include/griddisplay.php";
            list($grid_title, $grid_row_caps, $grid_col_caps, $grid_background, $grid_start, $grid_count) = compileGrid($ele_value, $title, $i);
            $headingAtSide = ($ele_value[5] and $grid_title) ? true : false;
            // if there is a value for ele_value[5], then the heading should be at the side, otherwise, grid spans form width as it's own chunk of HTML
            $gridCounter[$grid_start] = $grid_count;
            $gridContents = displayGrid($fid, $entry, $grid_row_caps, $grid_col_caps, $grid_title, $grid_background, $grid_start, "", "", true, $screen, $headingAtSide);
            if ($headingAtSide) {
                // grid contents is the two bits for the xoopsformlabel when heading is at side, otherwise, it's just the contents for the break
                $form->addElement(new XoopsFormLabel($gridContents[0], $gridContents[1]));
            } else {
                $form->insertBreak($gridContents, "head");
                // head is the css class of the cell
            }
        } elseif ($ele_type == "ib" or is_array($form_ele)) {
            // if it's a break, handle it differently...$form_ele may be an array if it's a non-interactive element such as a grid
            if (is_object($thisElement)) {
                // final param is used as id name in the table row where this element exists, so we can interact with it for showing and hiding
                $form->insertBreakFormulize("<div class=\"formulize-subform-heading\">" . trans(stripslashes($form_ele[0])) . "</div>", $form_ele[1], 'de_' . $fid . '_' . $entryForDEElements . '_' . $this_ele_id, $thisElement->getVar("ele_handle"));
            }
        } else {
            $form->addElement($form_ele, $req);
        }
        $count++;
        unset($hidden);
        unset($form_ele);
        // apparently necessary for compatibility with PHP 4.4.0 -- suggested by retspoox, sept 25, 2005
    }
    formulize_benchmark("Done looping elements.");
    // find any hidden elements in the form, that aren't available to the user in this rendering of the form...
    unset($criteria);
    $notAllowedCriteria = new CriteriaCompo();
    $notAllowedCriteria->add(new Criteria('ele_forcehidden', 1));
    foreach ($elementsAvailableToUser as $availElementId => $boolean) {
        $notAllowedCriteria->add(new Criteria('ele_id', $availElementId, '!='));
    }
    $notAllowedCriteria->setSort('ele_order');
    $notAllowedCriteria->setOrder('ASC');
    $notAllowedElements =& $formulize_mgr->getObjects($notAllowedCriteria, $fid);
    $hiddenElements = generateHiddenElements($notAllowedElements, $entryForDEElements);
    // in functions.php, keys in returned array will be the element ids
    foreach ($hiddenElements as $element_id => $thisHiddenElement) {
        $form->addElement(new xoopsFormHidden("decue_" . $fid . "_" . $entryForDEElements . "_" . $element_id, 1));
        if (is_array($thisHiddenElement)) {
            // could happen for checkboxes
            foreach ($thisHiddenElement as $thisIndividualHiddenElement) {
                $form->addElement($thisIndividualHiddenElement);
            }
        } else {
            $form->addElement($thisHiddenElement);
        }
        unset($thisHiddenElement);
        // some odd reference thing going on here...$thisHiddenElement is being added by reference or something like that, so that when $thisHiddenElement changes in the next run through, every previous element that was created by adding it is updated to point to the next element.  So if you unset at the end of the loop, it forces each element to be added as you would expect.
    }
    if ($entry and !is_a($form, 'formulize_elementsOnlyForm')) {
        // two hidden fields encode the main entry id, the first difficult-to-use format is a legacy thing
        // the 'lastentry' format is more sensible, but is only available when there was a real entry, not 'new' (also a legacy convention)
        $form->addElement(new XoopsFormHidden('entry' . $fid, $entry));
        if (is_numeric($entry)) {
            $form->addElement(new XoopsFormHidden('lastentry', $entry));
        }
    }
    if ($_POST['parent_form']) {
        // if we just came back from a parent form, then if they click save, we DO NOT want an override condition, even though we are now technically editing an entry that was previously saved when we went to the subform in the first place.  So the override logic looks for this hidden value as an exception.
        $form->addElement(new XoopsFormHidden('back_from_sub', 1));
    }
    // add a hidden element to carry all the validation javascript that might be associated with elements rendered with elementdisplay.php...only relevant for elements rendered inside subforms or grids...the validation code comes straight from the element, doesn't have a check around it for the conditional table row id, like the custom form classes at the top of the file use, since those elements won't render as hidden and show/hide in the same way
    if (isset($GLOBALS['formulize_renderedElementsValidationJS'][$GLOBALS['formulize_thisRendering']])) {
        $formulizeHiddenValidation = new XoopsFormHidden('validation', '');
        foreach ($GLOBALS['formulize_renderedElementsValidationJS'][$GLOBALS['formulize_thisRendering']] as $thisValidation) {
            // grab all the validation code we stored in the elementdisplay.php file and attach it to this element
            foreach (explode("\n", $thisValidation) as $thisValidationLine) {
                $formulizeHiddenValidation->customValidationCode[] = $thisValidationLine;
            }
        }
        $form->addElement($formulizeHiddenValidation, 1);
    }
    if (get_class($form) == "formulize_elementsOnlyForm") {
        // forms of this class are ones that we're rendering just the HTML for the elements, and we need to preserve any validation javascript to stick in the final, parent form when it's finished
        $validationJS = $form->renderValidationJS();
        if (trim($validationJS) != "") {
            $GLOBALS['formulize_elementsOnlyForm_validationCode'][] = $validationJS . "\n\n";
        }
    } elseif (count($GLOBALS['formulize_elementsOnlyForm_validationCode']) > 0) {
        $elementsonlyvalidation = new XoopsFormHidden('elementsonlyforms', '');
        $elementsonlyvalidation->customValidationCode = $GLOBALS['formulize_elementsOnlyForm_validationCode'];
        $form->addElement($elementsonlyvalidation, 1);
    }
    return $form;
}
Example #2
0
function formulize_calcDerivedColumns($entry, $metadata, $relationship_id, $form_id)
{
    global $xoopsDB;
    static $parsedFormulas = array();
    include_once XOOPS_ROOT_PATH . "/modules/formulize/class/data.php";
    foreach ($entry as $formHandle => $record) {
        $data_handler = new formulizeDataHandler(formulize_getFormIdFromName($formHandle));
        $formHandle = htmlspecialchars_decode($formHandle, ENT_QUOTES);
        if (isset($metadata[$formHandle])) {
            // if there are derived value formulas for this form
            if (!isset($parsedFormulas[$formHandle])) {
                formulize_includeDerivedValueFormulas($metadata[$formHandle], $formHandle, $relationship_id, $form_id);
                $parsedFormulas[$formHandle] = true;
            }
            foreach ($record as $primary_entry_id => $elements) {
                $dataToWrite = array();
                foreach ($metadata[$formHandle] as $formulaNumber => $thisMetaData) {
                    // if there's nothing already in the DB, then derive it, unless we're being asked specifically to update the derived values, which happens during a save operation.  In that case, always do a derivation regardless of what's in the DB.
                    if (isset($GLOBALS['formulize_forceDerivedValueUpdate']) and !isset($GLOBALS['formulize_doingExport'])) {
                        $functionName = "derivedValueFormula_" . str_replace(array(" ", "-", "/", "'", "`", "\\", ".", "’", ",", ")", "(", "[", "]"), "_", $formHandle) . "_" . $formulaNumber;
                        // want to turn off the derived value update flag for the actual processing of a value, since the function might have a getData call in it!!
                        $resetDerivedValueFlag = false;
                        if (isset($GLOBALS['formulize_forceDerivedValueUpdate'])) {
                            unset($GLOBALS['formulize_forceDerivedValueUpdate']);
                            $resetDerivedValueFlag = true;
                        }
                        $derivedValue = $functionName($entry, $form_id, $primary_entry_id, $relationship_id);
                        if ($resetDerivedValueFlag) {
                            $GLOBALS['formulize_forceDerivedValueUpdate'] = true;
                        }
                        // if the new value is the same as the previous one, then skip updating and saving
                        if ($derivedValue != $entry[$formHandle][$primary_entry_id][$thisMetaData['handle']][0]) {
                            $entry[$formHandle][$primary_entry_id][$thisMetaData['handle']][0] = $derivedValue;
                            if ($xoopsDB) {
                                // save value for writing to database if XOOPS is active
                                $elementID = formulize_getIdFromElementHandle($thisMetaData['handle']);
                                $dataToWrite[$elementID] = $derivedValue;
                            }
                        }
                    }
                }
                if ($xoopsDB and count($dataToWrite) > 0) {
                    // false for no proxy user, true to force the update even on get requests, false is do not update the metadata (modification user)
                    $data_handler->writeEntry($primary_entry_id, $dataToWrite, false, true, false);
                }
            }
        }
    }
    return $entry;
}
Example #3
0
 // check if the user is allowed to see this element in the form
 $ele_display = $elementObject->getVar('ele_display');
 $userCanAccessElement = false;
 if ($ele_display == 1) {
     $userCanAccessElement = true;
 } elseif (strstr($ele_display, ",")) {
     // comma separated list of groups
     $allowedGroups = explode(",", trim($ele_display, ","));
     if (array_intersect($groups, $allowedGroups)) {
         $userCanAccessElement = true;
     }
 }
 if ($userCanAccessElement) {
     // USER IS ALLOWED TO SEE THIS ELEMENT
     include_once XOOPS_ROOT_PATH . "/modules/formulize/class/data.php";
     $data_handler = new formulizeDataHandler($fid);
     $fileInfo = $data_handler->getElementValueInEntry($entry_id, $elementObject);
     $fileInfo = unserialize($fileInfo);
     $filePath = XOOPS_ROOT_PATH . "/uploads/formulize_" . $fid . "_" . $entry_id . "_" . $element_id . "/" . $fileInfo['name'];
     if (file_exists($filePath)) {
         header('Content-Description: File Transfer');
         header('Content-Type: ' . $fileInfo['type']);
         header('Content-Disposition: attachment; filename=' . $element_handler->getFileDisplayName($fileInfo['name']));
         header('Content-Transfer-Encoding: binary');
         header('Expires: 0');
         header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
         header('Pragma: public');
         header('Content-Length: ' . $fileInfo['size']);
         readfile($filePath);
         exit;
     } else {
Example #4
0
 function cloneForm($fid, $clonedata = false)
 {
     if (is_object($fid)) {
         if (!get_class($fid) == "formulizeForm") {
             return false;
         }
         $fid = $fid->getVar('id_form');
     } elseif (!is_numeric($fid)) {
         return false;
     }
     // procedure:
     // duplicate row for that fid in db but use next incremental fid
     // duplicate rows in form table for that fid, but use new fid and increment ele_ids of course
     // redraw page
     $newtitle = $this->titleForClonedForm($fid);
     $getrow = q("SELECT * FROM " . $this->db->prefix("formulize_id") . " WHERE id_form = {$fid}");
     $insert_sql = "INSERT INTO " . $this->db->prefix("formulize_id") . " (";
     $start = 1;
     foreach ($getrow[0] as $field => $value) {
         if (is_null($value)) {
             continue;
         }
         if ($this->fieldShouldBeSkippedInCloning($field)) {
             continue;
         }
         if (!$start) {
             $insert_sql .= ", ";
         }
         $start = 0;
         $insert_sql .= $field;
     }
     $insert_sql .= ") VALUES (";
     $start = 1;
     foreach ($getrow[0] as $field => $value) {
         if (is_null($value)) {
             continue;
         }
         if ($this->fieldShouldBeSkippedInCloning($field)) {
             continue;
         }
         if ($field == "desc_form") {
             $value = $newtitle;
         }
         if ($field == "form_handle") {
             $oldFormHandle = $value;
             $value = "replace_with_handle_and_id";
         }
         if (!$start) {
             $insert_sql .= ", ";
         }
         $start = 0;
         $insert_sql .= '"' . formulize_db_escape($value) . '"';
     }
     $insert_sql .= ")";
     if (!($result = $this->db->query($insert_sql))) {
         print "error duplicating form: '{$title}'<br>SQL: {$insert_sql}<br>" . $xoopsDB->error();
         return false;
     }
     $newfid = $this->db->getInsertId();
     // replace formhandle of the new form
     $replaceSQL = "UPDATE " . $this->db->prefix("formulize_id") . " SET form_handle='" . formulize_db_escape($oldFormHandle . "_" . $newfid) . "' WHERE form_handle=\"replace_with_handle_and_id\"";
     if (!($result = $this->db->queryF($replaceSQL))) {
         print "error setting the form_handle for the new form.<br>" . $xoopsDB->error();
         return false;
     }
     $getelements = q("SELECT * FROM " . $this->db->prefix("formulize") . " WHERE id_form = {$fid}");
     $oldNewEleIdMap = array();
     foreach ($getelements as $ele) {
         // for each element in the form....
         $insert_sql = "INSERT INTO " . $this->db->prefix("formulize") . " (";
         $start = 1;
         foreach ($ele as $field => $value) {
             if ($field == "ele_id") {
                 continue;
             }
             if (!$start) {
                 $insert_sql .= ", ";
             }
             $start = 0;
             $insert_sql .= $field;
         }
         $insert_sql .= ") VALUES (";
         $start = 1;
         foreach ($ele as $field => $value) {
             if ($field == "id_form") {
                 $value = "{$newfid}";
             }
             if ($field == "ele_id") {
                 continue;
             }
             if ($field == "ele_handle") {
                 if ($value === $ele['ele_id']) {
                     $value = "replace_with_ele_id";
                 } else {
                     $firstUniqueCheck = true;
                     $value .= "_cloned";
                     while (!($uniqueCheck = $this->isHandleUnique($value))) {
                         if ($firstUniqueCheck) {
                             $value = $value . "_" . $newfid;
                             $firstUniqueCheck = false;
                         } else {
                             $value = $value . "_copy";
                         }
                     }
                 }
                 $oldNewEleIdMap[$ele['ele_handle']] = $value;
             }
             if (!$start) {
                 $insert_sql .= ", ";
             }
             $start = 0;
             $value = addslashes($value);
             $insert_sql .= "\"{$value}\"";
         }
         $insert_sql .= ")";
         if (!($result = $this->db->query($insert_sql))) {
             print "error duplicating elements in form: '{$title}'<br>SQL: {$insert_sql}<br>" . $xoopsDB->error();
             return false;
         }
         if ($oldNewEleIdMap[$ele['ele_handle']] == "replace_with_ele_id") {
             $oldNewEleIdMap[$ele['ele_handle']] = $this->db->getInsertId();
         }
     }
     // replace ele_id flags that need replacing
     $replaceSQL = "UPDATE " . $this->db->prefix("formulize") . " SET ele_handle=ele_id WHERE ele_handle=\"replace_with_ele_id\"";
     if (!($result = $this->db->queryF($replaceSQL))) {
         print "error setting the ele_handle values for the new form.<br>" . $xoopsDB->error();
         return false;
     }
     // Need to create the new data table now -- July 1 2007
     if (!($tableCreationResult = $this->createDataTable($newfid, $fid, $oldNewEleIdMap))) {
         print "Error: could not make the necessary new datatable for form " . $newfid . ".  Please delete the cloned form and report this error to <a href=\"mailto:formulize@freeformsolutions.ca\">Freeform Solutions</a>.<br>" . $xoopsDB->error();
         return false;
     }
     if ($clonedata) {
         // July 1 2007 -- changed how cloning happens with new data structure
         include_once XOOPS_ROOT_PATH . "/modules/formulize/class/data.php";
         // formulize data handler
         $dataHandler = new formulizeDataHandler($newfid);
         if (!($cloneResult = $dataHandler->cloneData($fid, $oldNewEleIdMap))) {
             print "Error:  could not clone the data from the old form to the new form.  Please delete the cloned form and report this error to <a href=\"mailto:formulize@freeformsolutions.ca\">Freeform Solutions</a>.<br>" . $xoopsDB->error();
             return false;
         }
     }
     // if revisions are enabled for the cloned form, then create the revisions table
     $form_handler = xoops_getmodulehandler('forms', 'formulize');
     $clonedFormObject = $form_handler->get($newfid);
     if ($clonedFormObject->getVar('store_revisions')) {
         if (!($tableCreationResult = $this->createDataTable($newfid, 0, false, true))) {
             print "Error: could not create revisions table for form {$newfid}. " . "Please delete the cloned form and report this error to " . "<a href=\"mailto:formulize@freeformsolutions.ca\">Freeform Solutions</a>.<br>" . $xoopsDB->error();
             return false;
         }
     }
     $this->setPermissionsForClonedForm($fid, $newfid);
     // create and insert new defaultlist screen and defaultform screen using $newfid and $newtitle
     $defaultFormScreenId = $this->formScreenForClonedForm($newtitle, $newfid);
     $defaultListScreenId = $this->listScreenForClonedForm($defaultFormScreenId, $newtitle, $newfid);
     $clonedFormObject->setVar('defaultform', $defaultFormScreenId);
     $clonedFormObject->setVar('defaultlist', $defaultListScreenId);
     if (!$form_handler->insert($clonedFormObject)) {
         print "Error: could not update form object with default screen ids: " . $xoopsDB->error();
     }
     $this->setClonedFormAppId($newfid, $xoopsDB);
 }
Example #5
0
function generateHiddenElements($elements, $entry)
{
    $hiddenElements = array();
    foreach ($elements as $thisElement) {
        // display these elements as hidden elements with the default value
        $fid = $thisElement->getVar('id_form');
        switch ($thisElement->getVar('ele_type')) {
            case "radio":
                if ($entry == "new") {
                    $indexer = 1;
                    foreach ($thisElement->getVar('ele_value') as $k => $v) {
                        if ($v == 1) {
                            $hiddenElements[$thisElement->getVar('ele_id')] = new xoopsFormHidden('de_' . $fid . '_' . $entry . '_' . $thisElement->getVar('ele_id'), $indexer);
                        }
                        $indexer++;
                    }
                }
                break;
            case "checkbox":
                if ($entry == "new") {
                    $indexer = 1;
                    foreach ($thisElement->getVar('ele_value') as $k => $v) {
                        if ($v == 1) {
                            $hiddenElements[$thisElement->getVar('ele_id')][] = new xoopsFormHidden('de_' . $fid . '_' . $entry . '_' . $thisElement->getVar('ele_id') . "[]", $indexer);
                        }
                        $indexer++;
                    }
                } else {
                    $data_handler = new formulizeDataHandler($thisElement->getVar('id_form'));
                    $checkBoxOptions = $data_handler->getElementValueInEntry($entry, $thisElement);
                    $indexer = 1;
                    foreach ($thisElement->getVar('ele_value') as $k => $v) {
                        if (strstr($checkBoxOptions, $k)) {
                            $hiddenElements[$thisElement->getVar('ele_id')][] = new xoopsFormHidden('de_' . $fid . '_' . $entry . '_' . $thisElement->getVar('ele_id') . "[]", $indexer);
                        }
                        $indexer++;
                    }
                }
                break;
            case "yn":
                if ($entry == "new") {
                    $ele_value = $thisElement->getVar('ele_value');
                    // check to see if Yes is the value, and if so, set 1, otherwise, set 2.  2 is the value used when No is the selected option in YN radio buttons
                    $yesNoValue = $ele_value['_YES'] == 1 ? 1 : 2;
                    $hiddenElements[$thisElement->getVar('ele_id')] = new xoopsFormHidden('de_' . $fid . '_' . $entry . '_' . $thisElement->getVar('ele_id'), $yesNoValue);
                }
                break;
            case "text":
                if ($entry == "new") {
                    global $myts;
                    if (!$myts) {
                        $myts =& MyTextSanitizer::getInstance();
                    }
                    $ele_value = $thisElement->getVar('ele_value');
                    $hiddenElements[$thisElement->getVar('ele_id')] = new xoopsFormHidden('de_' . $fid . '_' . $entry . '_' . $thisElement->getVar('ele_id'), $myts->htmlSpecialChars(getTextboxDefault($ele_value[2], $thisElement->getVar('id_form'), $entry)));
                } else {
                    include_once XOOPS_ROOT_PATH . "/modules/formulize/class/data.php";
                    $data_handler = new formulizeDataHandler($fid);
                    $hiddenElements[$thisElement->getVar('ele_id')] = new xoopsFormHidden('de_' . $fid . '_' . $entry . '_' . $thisElement->getVar('ele_id'), $data_handler->getElementValueInEntry($entry, $thisElement));
                }
                break;
            case "textarea":
                if ($entry == "new") {
                    global $myts;
                    if (!$myts) {
                        $myts =& MyTextSanitizer::getInstance();
                    }
                    $ele_value = $thisElement->getVar('ele_value');
                    $hiddenElements[$thisElement->getVar('ele_id')] = new xoopsFormHidden('de_' . $fid . '_' . $entry . '_' . $thisElement->getVar('ele_id'), $myts->htmlSpecialChars(getTextboxDefault($ele_value[0], $thisElement->getVar('id_form'), $entry)));
                } else {
                    include_once XOOPS_ROOT_PATH . "/modules/class/data.php";
                    $data_handler = new formulizeDataHandler($fid);
                    $hiddenElements[$thisElement->getVar('ele_id')] = new xoopsFormHidden('de_' . $fid . '_' . $entry . '_' . $thisElement->getVar('ele_id'), $data_handler->getElementValueInEntry($entry, $thisElement));
                }
                break;
            case "date":
                if ($entry == "new") {
                    $ele_value = $thisElement->getVar('ele_value');
                    if ($ele_value[0] == "" or $ele_value[0] == "YYYY-mm-dd") {
                        $valueToUse = "";
                    } elseif (ereg_replace("[^A-Z{}]", "", $ele_value[0]) === "{TODAY}") {
                        $number = ereg_replace("[^0-9+-]", "", $ele_value[0]);
                        $valueToUse = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d") + $number, date("Y")));
                    } else {
                        $valueToUse = $ele_value[0];
                    }
                    $hiddenElements[$thisElement->getVar('ele_id')] = new xoopsFormHidden('de_' . $fid . '_' . $entry . '_' . $thisElement->getVar('ele_id'), $valueToUse);
                }
                break;
        }
    }
    return $hiddenElements;
}
function importCsvProcess(&$importSet, $id_reqs, $regfid, $validateOverride)
{
    global $xoopsDB, $xoopsUser, $xoopsConfig, $myts;
    // $xoopsDB is required by q
    if (!$myts) {
        $myts =& MyTextSanitizer::getInstance();
    }
    echo "<b>** Importing</b><br><br>";
    $form_uid = "0";
    global $override_import_proxyid;
    if ($override_import_proxyid) {
        $form_proxyid = $override_import_proxyid;
    } else {
        $form_proxyid = $xoopsUser->getVar('uid');
    }
    // lock formulize_form -- note that every table we use needs to be locked, so linked selectbox lookups may fail
    if ($regfid == $importSet[4]) {
        // only lockup reg codes table if we're dealing with a profile form, in which case we assume reg codes is installed and the table exists
        $xoopsDB->query("LOCK TABLES " . $xoopsDB->prefix("formulize_" . $importSet[8]) . " WRITE, " . $xoopsDB->prefix("users") . " WRITE, " . $xoopsDB->prefix("formulize_entry_owner_groups") . " WRITE, " . $xoopsDB->prefix("reg_codes") . " WRITE, " . $xoopsDB->prefix("groups_users_link") . " WRITE, " . $xoopsDB->prefix("modules") . " READ, " . $xoopsDB->prefix("config") . " READ, " . $xoopsDB->prefix("formulize") . " READ, " . $xoopsDB->prefix("formulize_id") . " READ, " . $xoopsDB->prefix("formulize_saved_views") . " READ, " . $xoopsDB->prefix("formulize_group_filters") . " READ");
    } else {
        $xoopsDB->query("LOCK TABLES " . $xoopsDB->prefix("formulize_" . $importSet[8]) . " WRITE, " . $xoopsDB->prefix("users") . " READ, " . $xoopsDB->prefix("formulize_entry_owner_groups") . " WRITE, " . $xoopsDB->prefix("groups_users_link") . " READ, " . $xoopsDB->prefix("formulize") . " READ, " . $xoopsDB->prefix("formulize_id") . " READ, " . $xoopsDB->prefix("formulize_saved_views") . " READ, " . $xoopsDB->prefix("formulize_group_filters") . " READ");
    }
    $rowCount = 1;
    $other_values = array();
    $usersMap = array();
    $entriesMap = array();
    while (!feof($importSet[1])) {
        $row = fgetcsv($importSet[1], 99999);
        if (is_array($row) and count($row) > 1) {
            $rowCount++;
            $this_id_req = "";
            if (is_array($id_reqs)) {
                // get the id_req if necessary.  will happen regardless of position of idreq column
                $this_id_req = $row[$importSet[7]['idreqs']];
            }
            $links = count($importSet[6]);
            for ($link = 0; $link < $links; $link++) {
                if (isset($GLOBALS['formulize_ignoreColumnsOnImport'][$link])) {
                    continue;
                }
                if ($importSet[6][$link] == -1) {
                    if ($importSet[3][$link] == _formulize_DE_CALC_CREATOR) {
                        $form_uid = getUserId($row[$link]);
                    }
                }
            }
            // get the current max id_req
            if (!$this_id_req) {
                $max_id_reqq = q("SELECT MAX(entry_id) FROM " . $xoopsDB->prefix("formulize_" . $importSet[8]));
                $max_id_req = $max_id_reqq[0]["MAX(entry_id)"] + 1;
            } else {
                $max_id_req = $this_id_req;
                // get the uid and creation date too
                $member_handler =& xoops_gethandler('member');
                $this_metadata = getMetaData($this_id_req, $member_handler, $importSet[4]);
                // importSet[4] is id_form (fid)
                $this_uid = $this_metadata['created_by_uid'];
                $this_creation_date = $this_metadata['created'];
            }
            // if this is the registration form, and we're making new entries, then handle the creation of the necessary user account
            // need to get the five userprofile fields from the form, $importSet[7] contains the keys for them -- email, username, fullname, password, regcode
            if ($regfid == $importSet[4] and !is_array($id_reqs)) {
                $up_regcode = $row[$importSet[7]['regcode']];
                $up_username = $row[$importSet[7]['username']];
                $up_fullname = $row[$importSet[7]['fullname']];
                $up_password = $row[$importSet[7]['password']];
                $up_email = $row[$importSet[7]['email']];
                $tz = $xoopsConfig['default_TZ'];
                list($newid, $actkey) = createMember(array('regcode' => '', 'approval' => false, 'user_viewemail' => 0, 'uname' => $up_username, 'name' => $up_fullname, 'email' => $up_email, 'pass' => $up_password, 'timezone_offset' => $tz));
                processCode($up_regcode, $newid);
                $form_uid = $newid;
                // put in new user id here
            }
            $links = count($importSet[6]);
            $fieldValues = array();
            $newEntryId = "";
            for ($link = 0; $link < $links; $link++) {
                // used as a flag to indicate whether we're dealing with a linked selectbox or not, since if we are, that is the only case where we don't want to do HTML special chars on the value // deprecated in 3.0
                $all_valid_options = false;
                if ($importSet[6][$link] != -1) {
                    $element = $importSet[5][0][$importSet[6][$link]];
                    $id_form = $importSet[4];
                    if ($link == $links - 1) {
                        // remove some really odd line endings if present, only happens when dealing with legacy outputs of really old/odd systems
                        $row_value = str_replace(chr(19) . chr(16), "", $row[$link]);
                    } else {
                        $row_value = $row[$link];
                    }
                    if ($row_value != "") {
                        switch ($element["ele_type"]) {
                            case "select":
                                if ($importSet[5][1][$link] and !strstr($row_value, ",") and (!is_numeric($row_value) or $row_value < 10000000)) {
                                    // Linked element
                                    $linkElement = $importSet[5][1][$link];
                                    $ele_value = unserialize($element["ele_value"]);
                                    list($all_valid_options, $all_valid_options_ids) = getElementOptions($linkElement[2]['ele_handle'], $linkElement[2]['id_form']);
                                    if ($ele_value[1]) {
                                        // Multiple options
                                        $element_value = $linkElement[0] . "#*=:*" . $linkElement[1] . "#*=:*";
                                        $items = explode("\n", $row_value);
                                        $row_value = ",";
                                        foreach ($items as $item) {
                                            $item_value = trim($item);
                                            if ($optionIndex = array_search($item_value, $all_valid_options)) {
                                                $ele_id = $all_valid_options_ids[$optionIndex];
                                            } else {
                                                foreach ($all_valid_options as $optionIndex => $thisoption) {
                                                    if (trim($item_value) == trim(trans($thisoption))) {
                                                        $item_value = $thisoption;
                                                        $ele_id = $all_valid_options_ids[$optionIndex];
                                                        break;
                                                    }
                                                }
                                            }
                                            $row_value .= $ele_id . ",";
                                        }
                                    } else {
                                        // Single option
                                        if ($optionIndex = array_search($row_value, $all_valid_options)) {
                                            $ele_id = $all_valid_options_ids[$optionIndex];
                                        } else {
                                            foreach ($all_valid_options as $optionIndex => $thisoption) {
                                                if (trim($row_value) == trim(trans($thisoption))) {
                                                    $row_value = $thisoption;
                                                    $ele_id = $all_valid_options_ids[$optionIndex];
                                                    break;
                                                }
                                            }
                                        }
                                        $row_value = $ele_id;
                                    }
                                } elseif (!strstr($row_value, ",") and (!is_numeric($row_value) or $row_value < 10000000)) {
                                    // Not-Linked element
                                    $ele_value = unserialize($element["ele_value"]);
                                    // handle fullnames or usernames
                                    $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 ($temparraykeys[0] === "{FULLNAMES}") {
                                            $nametype = "name";
                                        }
                                        if ($temparraykeys[0] === "{USERNAMES}") {
                                            $nametype = "uname";
                                        }
                                        if (!isset($fullnamelist)) {
                                            $fullnamelistq = q("SELECT uid, {$nametype} FROM " . $xoopsDB->prefix("users") . " ORDER BY uid");
                                            static $fullnamelist = array();
                                            foreach ($fullnamelistq as $thisname) {
                                                $fullnamelist[$thisname['uid']] = $thisname[$nametype];
                                            }
                                        }
                                        if ($ele_value[1]) {
                                            // multiple
                                            $items = explode("\n", $row_value);
                                        } else {
                                            $items = array(0 => $row_value);
                                        }
                                        $numberOfNames = 0;
                                        $row_value = "";
                                        foreach ($items as $item) {
                                            if (is_numeric($item)) {
                                                $row_value .= "*=+*:" . $item;
                                                $numberOfNames++;
                                            } else {
                                                $uids = array_keys($fullnamelist, $item);
                                                // instead of matching on all values, like we used to, match only the first name found (lowest user id)
                                                // to match other users besides the first one, use a user id number instead of a name in the import spreadsheet
                                                $row_value .= "*=+*:" . $uids[0];
                                                $numberOfNames++;
                                            }
                                        }
                                        if ($numberOfNames == 1) {
                                            // single entries are not supposed to have the separator at the front
                                            $row_value = substr_replace($row_value, "", 0, 5);
                                        }
                                        break;
                                    }
                                    if ($ele_value[1]) {
                                        // Multiple options
                                        $element_value = "";
                                        $options = $ele_value[2];
                                        $items = explode("\n", $row_value);
                                        foreach ($items as $item) {
                                            $item_value = trim($item);
                                            if (!in_array($item_value, $options, true)) {
                                                // last option causes strict matching by type
                                                foreach ($options as $thisoption => $default_value) {
                                                    if (trim($item_value) == trim(trans($thisoption))) {
                                                        $item_value = $thisoption;
                                                        break;
                                                    }
                                                }
                                            }
                                            $element_value .= "*=+*:" . $item_value;
                                        }
                                        $row_value = $element_value;
                                    } else {
                                        // Single option
                                        $options = $ele_value[2];
                                        if (!in_array($row_value, $options, true)) {
                                            // last option causes strict matching by type
                                            foreach ($options as $thisoption => $default_value) {
                                                if (trim($row_value) == trim(trans($thisoption))) {
                                                    $row_value = $thisoption;
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                } elseif (strstr($row_value, ",") or is_numeric($row_value) and $row_value > 10000000) {
                                    // the value is a comma separated list of linked values, so we need to add commas before and after, to adhere to the Formulize data storage spec
                                    if (substr($row_value, 0, 1) != ",") {
                                        $row_value = "," . $row_value;
                                    }
                                    if (substr($row_value, -1) != ",") {
                                        $row_value = $row_value . ",";
                                    }
                                }
                                break;
                            case "checkbox":
                                $options = unserialize($element["ele_value"]);
                                $element_value = "";
                                $items = explode("\n", $row_value);
                                foreach ($items as $item) {
                                    $item_value = trim($item);
                                    if (!in_array($item_value, $options, true)) {
                                        // last option causes strict matching by type
                                        $foundit = false;
                                        $hasother = false;
                                        foreach ($options as $thisoption => $default_value) {
                                            if (trim($item_value) == trim(trans($thisoption))) {
                                                $item_value = $thisoption;
                                                $foundit = true;
                                                break;
                                            }
                                            if (preg_match('/\\{OTHER\\|+[0-9]+\\}/', $thisoption)) {
                                                $hasother = $thisoption;
                                            }
                                        }
                                        if ($foundit) {
                                            $element_value .= "*=+*:" . $item_value;
                                        } elseif ($hasother) {
                                            $other_values[] = "INSERT INTO " . $xoopsDB->prefix("formulize_other") . " (id_req, ele_id, other_text) VALUES (\"{$max_id_req}\", \"" . $element["ele_id"] . "\", \"" . $myts->htmlSpecialChars(trim($item_value)) . "\")";
                                            $element_value .= "*=+*:" . $hasother;
                                        } elseif (!$validateOverride) {
                                            print "ERROR: INVALID TEXT FOUND FOR A CHECKBOX ITEM -- {$item_value} -- IN ROW:<BR>";
                                            print_r($row);
                                            print "<br><br>";
                                        }
                                    } else {
                                        $element_value .= "*=+*:" . $item_value;
                                    }
                                }
                                $row_value = $element_value;
                                break;
                            case "radio":
                                $options = unserialize($element["ele_value"]);
                                if (!in_array($row_value, $options, true)) {
                                    // last option causes strict matching by type
                                    $foundit = false;
                                    $hasother = false;
                                    foreach ($options as $thisoption => $default_value) {
                                        if (trim($row_value) == trim(trans($thisoption))) {
                                            $row_value = $thisoption;
                                            $foundit = true;
                                            break;
                                        }
                                        if (preg_match('/\\{OTHER\\|+[0-9]+\\}/', $thisoption)) {
                                            $hasother = $thisoption;
                                        }
                                    }
                                    if (!$foundit and $hasother) {
                                        $other_values[] = "INSERT INTO " . $xoopsDB->prefix("formulize_other") . " (id_req, ele_id, other_text) VALUES (\"{$max_id_req}\", \"" . $element["ele_id"] . "\", \"" . $myts->htmlSpecialChars(trim($row_value)) . "\")";
                                        $row_value = $hasother;
                                    } elseif (!$foundit and !$validateOverride) {
                                        print "ERROR: INVALID TEXT FOUND FOR A RADIO BUTTON ITEM -- {$row_value} -- IN ROW:<BR>";
                                        print_r($row);
                                        print "<br><br>";
                                    }
                                }
                                break;
                            case "date":
                                $row_value = date("Y-m-d", strtotime(str_replace("/", "-", $row_value)));
                                break;
                            case "yn":
                                if (!is_numeric($row_value)) {
                                    $yn_value = strtoupper($row_value);
                                    if ($yn_value == "YES") {
                                        $row_value = 1;
                                    } else {
                                        if ($yn_value == "NO") {
                                            $row_value = 2;
                                        }
                                    }
                                }
                                break;
                        }
                        // record the values for inserting as part of this record
                        // prior to 3.0 we did not do the htmlspecialchars conversion if this was a linked selectbox...don't think that's a necessary exception in 3.0 with new data structure
                        $fieldValues[$element['ele_handle']] = $myts->htmlSpecialChars($row_value);
                    }
                    // end of if there's a value in the current column
                } elseif (isset($importSet[7]['usethisentryid']) and $link == $importSet[7]['usethisentryid']) {
                    // if this is not a valid column, but it is an entry id column, then capture the entry id from the cell
                    $newEntryId = $row[$link] ? $row[$link] : "";
                }
                // end of if this is a valid column
            }
            // end of looping through $links (columns?)
            // now that we've recorded all the values, do the actual updating/inserting of this record
            if ($this_id_req) {
                // updating an entry
                $form_uid = $this_uid;
                $updateSQL = "UPDATE " . $xoopsDB->prefix("formulize_" . $importSet[8]) . " SET ";
                $start = true;
                foreach ($fieldValues as $elementHandle => $fieldValue) {
                    if (!$start) {
                        // on subsequent fields, add a comma
                        $updateSQL .= ", ";
                    }
                    $start = false;
                    $updateSQL .= "`{$elementHandle}` = '" . formulize_db_escape($fieldValue) . "'";
                }
                $updateSQL .= ", mod_datetime=NOW(), mod_uid={$form_proxyid} WHERE entry_id=" . intval($this_id_req);
                if (IMPORT_WRITE) {
                    if (!($result = $xoopsDB->queryF($updateSQL))) {
                        print "<br><b>FAILED</b> to update data, SQL: {$updateSQL}<br>" . $xoopsDB->error() . "<br>";
                    }
                }
            } else {
                // inserting a new entry
                $fields = "";
                $values = "";
                $element_handler = xoops_getmodulehandler('elements', 'formulize');
                foreach ($fieldValues as $elementHandle => $fieldValue) {
                    $fields .= ", `" . $elementHandle . "`";
                    $values .= ", '" . formulize_db_escape($fieldValue) . "'";
                    $elementObject = $element_handler->get($elementHandle);
                    if ($elementObject->getVar('ele_desc') == "Primary Key") {
                        $newEntryId = $fieldValue;
                    }
                }
                if ($form_uid == 0) {
                    $form_uid = $form_proxyid;
                }
                $entryIdFieldText = $newEntryId ? "entry_id, " : "";
                $newEntryId .= $newEntryId ? ", " : "";
                $insertElement = "INSERT INTO " . $xoopsDB->prefix("formulize_" . $importSet[8]) . " (" . $entryIdFieldText . "creation_datetime, mod_datetime, creation_uid, mod_uid" . $fields . ") VALUES (" . $newEntryId . "NOW(), NOW(), '" . intval($form_uid) . "', '" . intval($form_proxyid) . "'" . $values . ")";
                if (IMPORT_WRITE) {
                    if (!($result = $xoopsDB->queryF($insertElement))) {
                        static $duplicatesFound = false;
                        if (strstr($xoopsDB->error(), "Duplicate entry")) {
                            if (!$duplicatesFound) {
                                print "<br><b>FAILED</b> to insert <i>some</i> data.  At least one duplicate value was found in a column that does not allow duplicate values.<br>";
                                $duplicatesFound = true;
                            }
                        } else {
                            print "<br><b>FAILED</b> to insert data, SQL: {$insertElement}<br>" . $xoopsDB->error() . "<br>";
                        }
                    } else {
                        // need to record new group ownership info too
                        $usersMap[] = $form_uid;
                        $entriesMap[] = $xoopsDB->getInsertId();
                    }
                } else {
                    echo "<br>" . $insertElement . "<br>";
                }
            }
            $idToShow = $newEntryId ? $newEntryId : $max_id_req;
            //echo "line $rowCount, id $idToShow<br>";
        }
        // end of if we have contents in this row
    }
    // end of looping through each row of the file
    if (count($usersMap) > 0) {
        // if new entries were created...
        include_once XOOPS_ROOT_PATH . "/modules/formulize/class/data.php";
        $data_handler = new formulizeDataHandler($id_form);
        if (!($groupResult = $data_handler->setEntryOwnerGroups($usersMap, $entriesMap))) {
            print "ERROR: failed to write the entry ownership information to the database.<br>" . $xoopsDB->error() . "<br>";
        }
    }
    // unlock tables
    $xoopsDB->query("UNLOCK TABLES");
    // insert all the other values that were recorded
    foreach ($other_values as $other) {
        if (!($result = $xoopsDB->query($other))) {
            print "ERROR: could not insert 'other' value: {$other}<br>";
        }
    }
}
}
// check if the user has permission to edit the form
if (!$gperm_handler->checkRight("edit_form", $fid, $groups, $mid)) {
    return;
}
$ele_value = $element->getVar('ele_value');
$ele_encrypt = $_POST['elements-ele_encrypt'];
$databaseElement = ($ele_type == "areamodif" or $ele_type == "ib" or $ele_type == "sep" or $ele_type == "subform" or $ele_type == "grid" or property_exists($element, 'hasData') and $element->hasData == false) ? false : true;
$reloadneeded = false;
if ($ele_encrypt != $element->getVar('ele_encrypt') and $databaseElement and !$_GET['ele_id']) {
    // the setting has changed on this pageload, and it's a database element, and it's not new
    $reloadneeded = true;
    // display of data type goes on/off when encryption is off/on
    // if the encryption setting changed, then we need to encrypt/decrypt all the existing data
    include_once XOOPS_ROOT_PATH . "/modules/formulize/class/data.php";
    $data_handler = new formulizeDataHandler($fid);
    if (!$data_handler->toggleEncryption($_POST['original_handle'], $element->getVar('ele_encrypt'))) {
        print "Warning:  unable to toggle the encryption of the '" . $_POST['original_handle'] . "' field on/off!";
    }
}
if ($databaseElement and $_GET['ele_id']) {
    // ele_id is only in the URL when we're on the first save for a new element
    global $xoopsDB;
    // figure out what the data type should be.
    // the rules:
    // if it's encrypted, it's a BLOB, otherwise...
    // date fields get 'date'
    // colorpicker gets 'text'
    // for text element types...
    // if 'text' is the specified type, and it's numbers only with a decimal, then use decimal with that number of spaces
    // if 'text' is the specified type, and it's numbers only with 0 decimals, then use int
$ele_value_after_adminSave = "";
if (file_exists(XOOPS_ROOT_PATH . "/modules/formulize/class/" . $ele_type . "Element.php")) {
    $customTypeHandler = xoops_getmodulehandler($ele_type . "Element", 'formulize');
    $ele_value_before_adminSave = serialize($element->getVar('ele_value'));
    $changed = $customTypeHandler->adminSave($element, $processedValues['elements']['ele_value']);
    // cannot use getVar to retrieve ele_value from element, due to limitation of the base object class, when dealing with set values that are arrays and not being gathered directly from the database (it wants to unserialize them instead of treating them as literals)
    $ele_value_after_adminSave = serialize($element->getVar('ele_value'));
    if ($changed) {
        $_POST['reload_option_page'] = true;
        // force a reload, since the developer probably changed something the user did in the form, so we should reload to show the effect of this change
    }
}
// check to see if we should be reassigning user submitted values, and if so, trap the old ele_value settings, and the new ones, and then pass off the job to the handling function that does that change
if (isset($_POST['changeuservalues']) and $_POST['changeuservalues'] == 1) {
    include_once XOOPS_ROOT_PATH . "/modules/formulize/class/data.php";
    $data_handler = new formulizeDataHandler($fid);
    switch ($ele_type) {
        case "radio":
        case "check":
            $newValues = $processedValues['elements']['ele_value'];
            break;
        case "select":
            $newValues = $processedValues['elements']['ele_value'][2];
            break;
    }
    if (!($changeResult = $data_handler->changeUserSubmittedValues($ele_id, $newValues))) {
        print "Error updating user submitted values for the options in element {$ele_id}";
    }
}
/**newly added for autocomplete box to make sure when {USERNAMES} and {FULLNAMES} are selected, system will not allow new entries to be added
*ele_value[8] ==1 will make sure it's an autocomplete box
                afterSavingLogic($values, $writtenEntryId);
            }
        }
    }
}
unset($GLOBALS['formulize_afterSavingLogicRequired']);
// now that saving is done, we don't need this any longer, so clean up
// set the ownership info of the new entries created...use a custom named handler, so we don't conflict with any other data handlers that might be using the more conventional 'data_handler' name, which can happen depending on the scope within which this file is included
foreach ($formulize_newEntryIds as $newEntryFid => $entries) {
    $data_handler_for_owner_groups = new formulizeDataHandler($newEntryFid);
    $data_handler_for_owner_groups->setEntryOwnerGroups($formulize_newEntryUsers[$newEntryFid], $formulize_newEntryIds[$newEntryFid]);
    unset($data_handler_for_owner_groups);
}
// reassign entry ownership for an entry if the user requested that, and has permission
if (isset($updateOwnerFid) and $gperm_handler->checkRight("update_entry_ownership", $updateOwnerFid, $groups, $mid)) {
    $data_handler_for_owner_updating = new formulizeDataHandler($updateOwnerFid);
    if (!$data_handler_for_owner_updating->setEntryOwnerGroups($updateOwnerNewOwnerId, $updateOwnerEntryId, true)) {
        // final true causes an update, instead of a normal setting of the groups from scratch.  Entry's creation user is updated too.
        print "<b>Error: could not update the entry ownership information.  Please report this to the webmaster right away, including which entry you were trying to update.</b>";
    }
    $data_handler_for_owner_updating->updateCaches($updateOwnerEntryId);
}
// update the derived values for all forms that we saved data for, now that we've saved all the data from all the forms
$form_handler = xoops_getmodulehandler('forms', 'formulize');
$mainFormHasDerived = false;
if ($fid) {
    $mainFormObject = $form_handler->get($fid, true);
    // true causes all elements to be gathered, including ones that are not displayed to the users
    $mainFormHasDerived = array_search("derived", $mainFormObject->getVar('elementTypes'));
}
$mainFormEntriesUpdatedForDerived = array();
Example #10
0
function displayGrid($fid, $entry = "", $rowcaps, $colcaps, $title = "", $orientation = "horizontal", $startID = "first", $finalCell = "", $finalRow = "", $calledInternal = false, $screen = null, $headingAtSide = "")
{
    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/class/data.php';
    global $xoopsUser, $xoopsDB;
    $numcols = count($colcaps);
    if (is_array($finalCell)) {
        $numcols = $numcols + 2;
    } else {
        $numcols = $numcols + 1;
    }
    $numrows = count($rowcaps);
    $actual_numrows = count(array_filter($rowcaps));
    # count non-null row captions
    if ($title == "{FORMTITLE}") {
        $title = trans(getFormTitle($fid));
    } else {
        $title = trans($title);
    }
    $currentURL = getCurrentURL();
    $uid = $xoopsUser ? $xoopsUser->getVar('uid') : '0';
    $mid = getFormulizeModId();
    $gperm_handler =& xoops_gethandler('groupperm');
    $owner = getEntryOwner($entry, $fid);
    $member_handler =& xoops_gethandler('member');
    //$owner_groups = $owner ? $member_handler->getGroupsByUser($owner, FALSE) : array(0=>XOOPS_GROUP_ANONYMOUS);
    $data_handler = new formulizeDataHandler($fid);
    $owner_groups = $owner ? $data_handler->getEntryOwnerGroups($entry) : array(0 => XOOPS_GROUP_ANONYMOUS);
    $groups = $xoopsUser ? $xoopsUser->getGroups() : array(0 => XOOPS_GROUP_ANONYMOUS);
    if (!$calledInternal) {
        if (!($scheck = security_check($fid, $entry, $uid, $owner, $groups, $mid, $gperm_handler))) {
            print "<p>" . _NO_PERM . "</p>";
            return;
        }
    }
    // determine if the form is a single entry form and so whether an entry already exists for this form...
    $single_result = getSingle($fid, $uid, $groups, $member_handler, $gperm_handler, $mid);
    $single = $single_result['flag'];
    if ($single and !$entry) {
        $entry = $single_result['entry'];
    }
    if (!$entry) {
        $entry = "new";
    }
    // figure out where we are supposed to start in the form
    if (!is_numeric($startID) and $startID !== "first") {
        $order_query = q("SELECT ele_order FROM " . $xoopsDB->prefix("formulize") . " WHERE ele_caption = \"{$startID}\" AND id_form=\"{$fid}\"");
    } elseif ($startID === "first") {
        // get the ele_id of the element with the lowest weight
        $order_query = q("SELECT ele_order FROM " . $xoopsDB->prefix("formulize") . " WHERE id_form=\"{$fid}\" ORDER BY ele_order LIMIT 0,1");
    } else {
        $order_query = q("SELECT ele_order FROM " . $xoopsDB->prefix("formulize") . " WHERE id_form=\"{$fid}\" AND ele_id =\"{$startID}\"");
    }
    $starting_order = $order_query[0]['ele_order'];
    // gather the element IDs that are to be displayed, in order (include to the end of the form, whereas we actually only will display until we run out of cells)
    $element_ids_query = q("SELECT ele_id FROM " . $xoopsDB->prefix("formulize") . " WHERE ele_order >= '{$starting_order}' AND id_form='{$fid}' AND ele_type != 'subform' ORDER BY ele_order");
    // initialize form
    if (!$calledInternal) {
        print $GLOBALS['xoopsSecurity']->getTokenHTML();
    }
    // start buffering the output
    ob_start();
    // set the title row
    if ($headingAtSide) {
        $gridContents[0] = $title;
        $class = "even";
        print "<table class='outer'>\n<tr>";
        if ($actual_numrows > 0) {
            echo "<td class=head></td>";
        }
    } else {
        print "<table class=outer>\n";
        $class = "head";
        if ($title) {
            print "<tr><th colspan='{$numcols}'>{$title}</th></tr>\n";
        }
        print "<tr>\n<td class=\"head\">&nbsp;</td>\n";
    }
    // draw top row
    foreach ($colcaps as $thiscap) {
        if ($headingAtSide) {
            print "<td class=head>{$thiscap}</td>\n";
        } else {
            if ($orientation == "vertical" and $class == "even" and !$headingAtSide) {
                // only alternate rows
                $class = "odd";
            } elseif ($orientation == "vertical") {
                $class = "even";
            }
            print "<td class={$class}>{$thiscap}</td>\n";
        }
    }
    if (is_array($finalCell)) {
        // draw blank header for last column if there is such a thing
        print "<td class=head>&nbsp;</td>\n";
    }
    print "</tr>\n";
    // draw regular rows
    $class = "head";
    $row_index = 0;
    $ele_index = 0;
    foreach ($rowcaps as $thiscap) {
        if ($orientation == "horizontal" and $class == "even") {
            $class = "odd";
        } elseif ($orientation == "horizontal") {
            $class = "even";
        } else {
            $class = "head";
        }
        print "<tr>\n";
        if ($headingAtSide) {
            if ($actual_numrows > 0) {
                print "<td class=\"head\">{$thiscap}</td>\n";
            }
        } else {
            print "<td class={$class}>{$thiscap}</td>\n";
        }
        foreach ($colcaps as $thiscolcap) {
            if ($orientation == "vertical" and $class == "even") {
                $class = "odd";
            } elseif ($orientation == "vertical") {
                $class = "even";
            }
            print "<td class={$class}>\n";
            // display the element starting with the initial one.  Keep trying to display something until we're successful (displaying the element might fail if the user does not have permission to view (based on which groups are allowed to view this element)
            $rendered = "start";
            while ($rendered != "rendered" and $rendered != "rendered-disabled" and isset($element_ids_query[$ele_index])) {
                $rendered = displayElement("", $element_ids_query[$ele_index]['ele_id'], $entry, false, $screen);
                $ele_index++;
            }
            if ($rendered != "rendered" and $rendered != "rendered-disabled") {
                print "&nbsp;";
            }
            print "</td>\n";
        }
        if (is_array($finalCell)) {
            // draw final cell values if they exist
            if ($orientation == "vertical") {
                $class = "head";
            }
            if ($finalCell[$row_index]) {
                print "<td class={$class}>" . $finalCell[$row_index] . "</td>\n";
            } else {
                print "<td class={$class}>&nbsp;</td>\n";
            }
        }
        print "</tr>\n";
        $row_index++;
    }
    // draw final row if necessary
    if ($finalRow) {
        print "<tr>{$finalRow}</tr>\n";
    }
    print "</table>";
    $gridContents[1] = trans(ob_get_clean());
    if ($headingAtSide === "") {
        // if $headingAtSide is "" (not false) then we print out the grid contents here.  Only pass back contents if $headingAtSide is specified as true or false (presumably by the formdisplay.php file), since otherwise for backwards compatibility we need to printout contents here because that's what the behaviour used to be.
        print $gridContents[1];
    } elseif ($headingAtSide) {
        return $gridContents;
    } else {
        return $gridContents[1];
    }
}
        } else {
            include_once XOOPS_ROOT_PATH . "/modules/formulize/class/data.php";
            $data_handler = new formulizeDataHandler($element->getVar('id_form'));
            if (!$data_handler->convertCheckboxDataToRadio($element)) {
                print "Error: " . _AM_ELE_RADIO_DATA_NOT_READY;
            }
        }
    } elseif ($ele_type == "select") {
        $element->setVar('ele_type', 'checkbox');
        $old_ele_value = $element->getVar('ele_value');
        if ($element->isLinked) {
            // get all the source values, and make an array of those...ignore filters and so on
            $boxproperties = explode("#*=:*", $old_ele_value[2]);
            $sourceFid = $boxproperties[0];
            $sourceHandle = $boxproperties[1];
            $data_handler = new formulizeDataHandler($sourceFid);
            $options = $data_handler->findAllValuesForField($sourceHandle, "ASC");
            foreach ($options as $option) {
                $new_ele_value[$option] = 0;
            }
        } else {
            $new_ele_value = $old_ele_value[2];
        }
        $element->setVar('ele_value', $new_ele_value);
        $element->setVar('ele_delim', 'br');
        if (!$element_handler->insert($element)) {
            print "Error: could not complete conversion of the element";
        }
    }
}
if ($_POST['deleteelement']) {
         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
             if ($k == 'onetooneentries' or $k == 'onetoonefids') {
function displayElement($formframe = "", $ele, $entry = "new", $noSave = false, $screen = null, $prevEntry = null, $renderElement = true, $profileForm = null, $groups = "")
{
    static $cachedPrevEntries = array();
    static $lockedEntries = array();
    // keep track of the entries we have determined are locked
    global $entriesThatHaveBeenLockedThisPageLoad;
    if (!is_array($entriesThatHaveBeenLockedThisPageLoad)) {
        // which entries we have locked as part of this page load, so we don't waste time setting locks again on entries we've already locked, and so we can ignore locks that were set by ourselves!
        $entriesThatHaveBeenLockedThisPageLoad = array();
    }
    $subformCreateEntry = strstr($entry, "subformCreateEntry") ? true : false;
    // check for this special flag, which is mostly like a "new" situation, except for the deh hidden flag that gets passed back, since we don't want the standard readelements logic to pickup these elements!
    if ($subformCreateEntry) {
        $subformMetaData = explode("_", $entry);
        $subformEntryIndex = $subformMetaData[1];
        $subformElementId = $subformMetaData[2];
    }
    if ($entry == "" or $subformCreateEntry) {
        $entry = "new";
    }
    $element = _formulize_returnElement($ele, $formframe);
    if (!is_object($element)) {
        return "invalid_element";
    }
    $form_id = $element->getVar('id_form');
    $deprefix = $noSave ? "denosave_" : "de_";
    $deprefix = $subformCreateEntry ? "desubform" . $subformEntryIndex . "x" . $subformElementId . "_" : $deprefix;
    // need to pass in an entry index so that all fields in the same element can be collected
    if ($noSave and !is_bool($noSave)) {
        $renderedElementName = $noSave;
        // if we've passed a specific string with $noSave, then we want to use that to override the name of the element, because the developer wants to pick up that form value later after submission
        $noSave = true;
    } else {
        $renderedElementName = $deprefix . $form_id . '_' . $entry . '_' . $element->getVar('ele_id');
    }
    global $xoopsUser;
    if (!$groups) {
        // groups might be passed in, which covers the case of the registration form and getting the groups from the registration code
        $groups = $xoopsUser ? $xoopsUser->getGroups() : array(0 => XOOPS_GROUP_ANONYMOUS);
    }
    $user_id = $xoopsUser ? $xoopsUser->getVar('uid') : 0;
    $username = $xoopsUser ? $xoopsUser->getVar('uname') : "unknown user";
    static $cachedEntryOwners = array();
    if (!isset($cachedEntryOwners[$form_id][$entry])) {
        $cachedEntryOwners[$form_id][$entry] = getEntryOwner($entry, $form_id);
    }
    $owner = $cachedEntryOwners[$form_id][$entry];
    $mid = getFormulizeModId();
    static $cachedViewPrivate = array();
    static $cachedUpdateOwnEntry = array();
    $gperm_handler = xoops_gethandler('groupperm');
    if (!isset($cachedViewPrivate[$form_id])) {
        $cachedViewPrivate[$form_id] = $gperm_handler->checkRight("view_private_elements", $form_id, $groups, $mid);
        $cachedUpdateOwnEntry[$form_id] = $gperm_handler->checkRight("update_own_entry", $form_id, $groups, $mid);
    }
    $view_private_elements = $cachedViewPrivate[$form_id];
    $update_own_entry = $cachedUpdateOwnEntry[$form_id];
    // check if the user is normally able to view this element or not, by checking their groups against the display groups -- added Nov 7 2005
    // messed up.  Private should not override the display settings.  And the $entry should be checked against the security check first to determine whether the user should even see this entry in the first place.
    $display = $element->getVar('ele_display');
    $private = $element->getVar('ele_private');
    $member_handler = xoops_gethandler('member');
    $single_result = getSingle($form_id, $user_id, $groups, $member_handler, $gperm_handler, $mid);
    $groupEntryWithUpdateRights = ($single_result['flag'] == "group" and $update_own_entry and $entry == $single_result['entry']) ? true : false;
    // need to test whether the display setting should be checked first?!  Order of checks here looks wrong.  JWE Nov 25 2010
    if ($private and $user_id != $owner and !$groupEntryWithUpdateRights and $entry != "new") {
        $allowed = $view_private_elements ? 1 : 0;
    } elseif (strstr($display, ",")) {
        $display_groups = explode(",", $display);
        $allowed = array_intersect($groups, $display_groups) ? 1 : 0;
    } elseif ($display == 1) {
        $allowed = 1;
    } else {
        $allowed = 0;
    }
    if ($prevEntry == null) {
        // preferable to pass in prevEntry!
        $prevEntry = getEntryValues($entry, "", $groups, $form_id, "", $mid, $user_id, $owner, $groupEntryWithUpdateRights);
    }
    // record the list of elements that are allowed in principle for a form (regardless of conditional status)
    if ($allowed) {
        $GLOBALS['formulize_renderedElementsForForm'][$form_id][$entry][$renderedElementName] = $element->getVar('ele_handle');
    }
    $elementFilterSettings = $element->getVar('ele_filtersettings');
    if ($allowed and count($elementFilterSettings[0]) > 0) {
        // cache the filterElements for this element, so we can build the right stuff with them later in javascript, to make dynamically appearing elements
        $GLOBALS['formulize_renderedElementHasConditions'][$renderedElementName] = $elementFilterSettings[0];
        // need to check if there's a condition on this element that is met or not
        static $cachedEntries = array();
        if ($entry != "new") {
            if (!isset($cachedEntries[$form_id][$entry])) {
                $cachedEntries[$form_id][$entry] = getData("", $form_id, $entry);
            }
            $entryData = $cachedEntries[$form_id][$entry];
        }
        $filterElements = $elementFilterSettings[0];
        $filterOps = $elementFilterSettings[1];
        $filterTerms = $elementFilterSettings[2];
        /* ALTERED - 20100316 - freeform - jeff/julian - start */
        $filterTypes = $elementFilterSettings[3];
        // find the filter indexes for 'match all' and 'match one or more'
        $filterElementsAll = array();
        $filterElementsOOM = array();
        for ($i = 0; $i < count($filterTypes); $i++) {
            if ($filterTypes[$i] == "all") {
                $filterElementsAll[] = $i;
            } else {
                $filterElementsOOM[] = $i;
            }
        }
        /* ALTERED - 20100316 - freeform - jeff/julian - stop */
        // setup evaluation condition as PHP and then eval it so we know if we should include this element or not
        $evaluationCondition = "\$passedCondition = false;\n";
        $evaluationCondition .= "if(";
        /* ALTERED - 20100316 - freeform - jeff/julian - start */
        $evaluationConditionAND = buildEvaluationCondition("AND", $filterElementsAll, $filterElements, $filterOps, $filterTerms, $entry, $entryData);
        $evaluationConditionOR = buildEvaluationCondition("OR", $filterElementsOOM, $filterElements, $filterOps, $filterTerms, $entry, $entryData);
        $evaluationCondition .= $evaluationConditionAND;
        if ($evaluationConditionOR) {
            if ($evaluationConditionAND) {
                $evaluationCondition .= " AND (" . $evaluationConditionOR . ")";
                //$evaluationCondition .= " OR (" . $evaluationConditionOR . ")";
            } else {
                $evaluationCondition .= $evaluationConditionOR;
            }
        }
        /* ALTERED - 20100316 - freeform - jeff/julian - stop */
        $evaluationCondition .= ") {\n";
        $evaluationCondition .= "  \$passedCondition = true;\n";
        $evaluationCondition .= "}\n";
        //print( $evaluationCondition );
        eval($evaluationCondition);
        if (!$passedCondition) {
            $allowed = 0;
        }
    }
    if ($allowed) {
        if ($element->getVar('ele_type') == "subform") {
            return array("", $isDisabled);
        }
        if (isset($GLOBALS['formulize_forceElementsDisabled']) and $GLOBALS['formulize_forceElementsDisabled'] == true) {
            $isDisabled = true;
        } else {
            $ele_disabled = $element->getVar('ele_disabled');
            $isDisabled = false;
            if ($ele_disabled == 1) {
                $isDisabled = true;
            } elseif (!is_numeric($ele_disabled)) {
                $disabled_groups = explode(",", $ele_disabled);
                if (array_intersect($groups, $disabled_groups) and !array_diff($groups, $disabled_groups)) {
                    $isDisabled = true;
                }
            }
        }
        // Another check to see if this element is disabled, for the case where the user can view the form, but not edit it.
        if (!$isDisabled) {
            // note that we're using the OPPOSITE of the permission because we want to know if the element should be disabled
            $isDisabled = !formulizePermHandler::user_can_edit_entry($form_id, $user_id, $entry);
        }
        // check whether the entry is locked, and if so, then the element is not allowed.  Set a message to say that elements were disabled due to entries being edited elsewhere (first time only).
        // groups with ignore lock permission bypass this, and therefore can save entries even when locked, and saving an entry removes the lock, so that gets you out of a jam if the lock is in place when it shouldn't be.
        // locks are only valid for the session time, so if a lock is older than that, it is ignored and cleared
        // Do this last, since locking overrides other permissions!
        $lockFileName = "entry_" . $entry . "_in_form_" . $form_id . "_is_locked_for_editing";
        // if we haven't found a lock for this entry, check if there is one...(as long as it's not an entry that we locked ourselves on this page load)
        if ($entry != "new" and !isset($lockedEntries[$form_id][$entry]) and !isset($entriesThatHaveBeenLockedThisPageLoad[$form_id][$entry]) and file_exists(XOOPS_ROOT_PATH . "/modules/formulize/temp/{$lockFileName}") and !$gperm_handler->checkRight("ignore_editing_lock", $form_id, $groups, $mid)) {
            $maxSessionLifeTime = ini_get("session.gc_maxlifetime");
            $fileCreationTime = filectime(XOOPS_ROOT_PATH . "/modules/formulize/temp/{$lockFileName}");
            if ($fileCreationTime + $maxSessionLifeTime > time()) {
                list($lockUid, $lockUsername) = explode(",", file_get_contents(XOOPS_ROOT_PATH . "/modules/formulize/temp/{$lockFileName}"));
                if ($lockUid != $user_id) {
                    // lock is still valid, hasn't expired yet.
                    if (count($lockedEntries) == 0) {
                        $label = json_encode(sprintf(_formulize_ENTRY_IS_LOCKED, $lockUsername));
                        print <<<EOF
<script type='text/javascript'>
\$(document).ready(function() {
    jQuery("<div id=\\"formulize-entry-lock-message\\"><i id=\\"formulize-entry-lock-icon\\" class=\\"icon-lock\\"></i><p>"+{$label}+"</p></div>").insertBefore("#formulize .xo-theme-form table");
});
</script>
EOF;
                    }
                    $lockedEntries[$form_id][$entry] = true;
                }
            } else {
                // clean up expired locks
                formulize_scandirAndClean(XOOPS_ROOT_PATH . "/modules/formulize/temp/", "_" . $entry . "_in_form_" . $form_id . "_", $maxSessionLifeTime);
            }
        }
        // if we've ever found a lock for this entry as part of this pageload...
        if (isset($lockedEntries[$form_id][$entry])) {
            $isDisabled = true;
        }
        $renderer = new formulizeElementRenderer($element);
        $ele_value = $element->getVar('ele_value');
        $ele_type = $element->getVar('ele_type');
        if (($prevEntry or $profileForm === "new") and $ele_type != 'subform' and $ele_type != 'grid') {
            $data_handler = new formulizeDataHandler($form_id);
            $ele_value = loadValue($prevEntry, $element, $ele_value, $data_handler->getEntryOwnerGroups($entry), $groups, $entry, $profileForm);
            // get the value of this element for this entry as stored in the DB -- and unset any defaults if we are looking at an existing entry
        }
        formulize_benchmark("About to render element " . $element->getVar('ele_caption') . ".");
        $form_ele =& $renderer->constructElement($renderedElementName, $ele_value, $entry, $isDisabled, $screen);
        if (strstr($_SERVER['PHP_SELF'], "formulize/printview.php") and is_object($form_ele)) {
            $form_ele->setDescription('');
        }
        formulize_benchmark("Done rendering element.");
        // put a lock on this entry in this form, so we know that the element is being edited.  Lock will be removed next time the entry is saved.
        if ($entry > 0 and !isset($lockedEntries[$form_id][$entry]) and !isset($entriesThatHaveBeenLockedThisPageLoad[$form_id][$entry])) {
            if (is_writable(XOOPS_ROOT_PATH . "/modules/formulize/temp/")) {
                $lockFile = fopen(XOOPS_ROOT_PATH . "/modules/formulize/temp/{$lockFileName}", "w");
                if (false !== $lockFile) {
                    fwrite($lockFile, "{$user_id},{$username}");
                    fclose($lockFile);
                    $entriesThatHaveBeenLockedThisPageLoad[$form_id][$entry] = true;
                }
            } else {
                if (defined("ICMS_ERROR_LOG_SEVERITY") and ICMS_ERROR_LOG_SEVERITY >= E_WARNING) {
                    static $lock_file_warning_issued = false;
                    if (!$lock_file_warning_issued) {
                        // cannot write to Formulize temp folder to create lock entries
                        error_log("Notice: Formulize temp folder does not exist or is not writeable, so lock file cannot be created in " . XOOPS_ROOT_PATH . "/modules/formulize/temp/");
                        $lock_file_warning_issued = true;
                    }
                }
            }
        }
        if (!$renderElement) {
            return array(0 => $form_ele, 1 => $isDisabled);
        } else {
            if ($element->getVar('ele_type') == "ib") {
                print $form_ele[0];
                return "rendered";
            } elseif (is_object($form_ele)) {
                print $form_ele->render();
                if (!empty($form_ele->customValidationCode) and !$isDisabled) {
                    $GLOBALS['formulize_renderedElementsValidationJS'][$GLOBALS['formulize_thisRendering']][$form_ele->getName()] = $form_ele->renderValidationJS();
                } elseif ($element->getVar('ele_req') and ($element->getVar('ele_type') == "text" or $element->getVar('ele_type') == "textarea") and !$isDisabled) {
                    $eltname = $form_ele->getName();
                    $eltcaption = $form_ele->getCaption();
                    $eltmsg = empty($eltcaption) ? sprintf(_FORM_ENTER, $eltname) : sprintf(_FORM_ENTER, $eltcaption);
                    $eltmsg = str_replace('"', '\\"', stripslashes($eltmsg));
                    $GLOBALS['formulize_renderedElementsValidationJS'][$GLOBALS['formulize_thisRendering']][$eltname] = "if ( myform." . $eltname . ".value == \"\" ) { window.alert(\"" . $eltmsg . "\"); myform." . $eltname . ".focus(); return false; }";
                }
                if ($isDisabled) {
                    return "rendered-disabled";
                } else {
                    return "rendered";
                }
            }
        }
        // or, even if the user is not supposed to see the element, put in a hidden element with its default value (only on new entries for elements with the forcehidden flag on)
        // NOTE: YOU CANNOT HAVE DEFAULT VALUES ON A LINKED FIELD CURRENTLY
        // So, no handling of linked values is included here.
    } elseif ($forcehidden = $element->getVar('ele_forcehidden') and $entry == "new" and !$noSave) {
        // hiddenElements keys will be the element ids
        $hiddenElements = generateHiddenElements(array($element), $entry);
        $thisHiddenElement = isset($hiddenElements[$element->getVar('ele_id')]) ? $hiddenElements[$element->getVar('ele_id')] : "";
        if (!$renderElement) {
            return array("hidden", $isDisabled, $thisHiddenElement);
            // if the element is hidden, then return an array, but with hidden as the first key, so that logic that was not expecting an element back, will still function as is.  This is a backwards compatibility thing.  For hidden elements, the element is in the third key, if in fact you need it/are looking for it in the user land code...note that in the case of checkboxes, the elements returned will be in an array
        } else {
            $cueElement = new xoopsFormHidden("decue_" . $fid . "_" . $entry . "_" . $element_id, 1);
            print $cueElement->render();
            if (is_array($thisHiddenElement)) {
                // could happen for checkboxes
                foreach ($thisHiddenElement as $thisIndividualHiddenElement) {
                    if (is_object($thisIndividualHiddenElement)) {
                        print $thisIndividualHiddenElement->render() . "\n";
                    }
                }
            } elseif (is_object($thisHiddenElement)) {
                print $thisHiddenElement->render() . "\n";
            }
            return "hidden";
        }
    } else {
        return "not_allowed";
    }
}
 function render($ele_value, $caption, $markupName, $isDisabled, $element, $entry_id)
 {
     global $xoopsDB, $xoopsUser, $myts;
     $renderer = new formulizeElementRenderer();
     $form_handler = xoops_getmodulehandler('forms', 'formulize');
     $id_form = $element->getVar('id_form');
     if ($entry_id != "new") {
         $owner = getEntryOwner($entry_id, $id_form);
     } else {
         $owner = $xoopsUser ? $xoopsUser->getVar('uid') : 0;
     }
     $formObject = $form_handler->get($id_form);
     $isDisabled = false;
     if (strstr(getCurrentURL(), "printview.php")) {
         $isDisabled = true;
         // disabled all elements if we're on the printable view
     }
     $ele_desc = $element->getVar('ele_desc', "f");
     if (strstr($ele_value[2], "#*=:*")) {
         // if we've got a link on our hands... -- jwe 7/29/04
         // new process for handling links...May 10 2008...new datastructure for formulize 3.0
         $boxproperties = explode("#*=:*", $ele_value[2]);
         $sourceFid = $boxproperties[0];
         $sourceHandle = $boxproperties[1];
         $sourceEntryIds = explode(",", trim($boxproperties[2], ","));
         // grab the user's groups and the module id
         global $regcode;
         if ($regcode) {
             // if we're dealing with a registration code, determine group membership based on the code
             $reggroupsq = q("SELECT reg_codes_groups FROM " . XOOPS_DB_PREFIX . "_reg_codes WHERE reg_codes_code=\"{$regcode}\"");
             $groups = explode("&8(%\$", $reggroupsq[0]['reg_codes_groups']);
             if ($groups[0] === "") {
                 unset($groups);
             }
             // if a code has no groups associated with it, then kill the null value that will be in position 0 in the groups array.
             $groups[] = XOOPS_GROUP_USERS;
             $groups[] = XOOPS_GROUP_ANONYMOUS;
         } else {
             $groups = $xoopsUser ? $xoopsUser->getGroups() : array(0 => XOOPS_GROUP_ANONYMOUS);
         }
         $module_id = getFormulizeModId();
         $pgroups = array();
         // handle new linkscope option -- August 30 2006
         $emptylist = false;
         if ($ele_value[3]) {
             $scopegroups = explode(",", $ele_value[3]);
             if (!in_array("all", $scopegroups)) {
                 if ($ele_value[4]) {
                     // limit by user's groups
                     foreach ($groups as $gid) {
                         // want to loop so we can get rid of reg users group simply
                         if ($gid == XOOPS_GROUP_USERS) {
                             continue;
                         }
                         if (in_array($gid, $scopegroups)) {
                             $pgroups[] = $gid;
                         }
                     }
                 } else {
                     // just use scopegroups
                     $pgroups = $scopegroups;
                 }
                 if (count($pgroups) == 0) {
                     // specific scope was specified, and nothing found, so we should show nothing
                     $emptylist = true;
                 }
             } else {
                 if ($ele_value[4]) {
                     // all groups selected, but limiting by user's groups is turned on
                     foreach ($groups as $gid) {
                         // want to loop so we can get rid of reg users group simply
                         if ($gid == XOOPS_GROUP_USERS) {
                             continue;
                         }
                         $pgroups[] = $gid;
                     }
                 } else {
                     // all groups should be used
                     unset($pgroups);
                     $allgroupsq = q("SELECT groupid FROM " . $xoopsDB->prefix("groups"));
                     //  . " WHERE groupid != " . XOOPS_GROUP_USERS); // use all groups now, if all groups are picked, with no restrictions on membership or anything, then use all groups
                     foreach ($allgroupsq as $thisgid) {
                         $pgroups[] = $thisgid['groupid'];
                     }
                 }
             }
         }
         // Note: OLD WAY: if no groups were found, then pguidq will be empty and so all entries will be shown, no restrictions
         // NEW WAY: if a specific group(s) was specified, and no match with the current user was found, then we return an empty list
         array_unique($pgroups);
         // remove duplicate groups from the list
         if ($ele_value[6] and count($pgroups) > 0) {
             $pgroupsfilter = " (";
             $start = true;
             foreach ($pgroups as $thisPgroup) {
                 if (!$start) {
                     $pgroupsfilter .= " AND ";
                 }
                 $pgroupsfilter .= "EXISTS(SELECT 1 FROM " . $xoopsDB->prefix("formulize_entry_owner_groups") . " AS t2 WHERE t2.groupid={$thisPgroup} AND t2.fid={$sourceFid} AND t2.entry_id=t1.entry_id)";
                 $start = false;
             }
             $pgroupsfilter .= ")";
         } elseif (count($pgroups) > 0) {
             $pgroupsfilter = " t2.groupid IN (" . formulize_db_escape(implode(",", $pgroups)) . ") AND t2.entry_id=t1.entry_id AND t2.fid={$sourceFid}";
         } else {
             $pgroupsfilter = "";
         }
         $sourceFormObject = $form_handler->get($sourceFid);
         list($conditionsfilter, $conditionsfilter_oom, $parentFormFrom) = buildConditionsFilterSQL($ele_value[5], $sourceFid, $entry_id, $owner, $formObject, "t1");
         // if there is a restriction in effect, then add some SQL to reject options that have already been selected ??
         $restrictSQL = "";
         if ($ele_value[9]) {
             $restrictSQL = " AND (\n\t\t\t\tNOT EXISTS (\n\t\t\t\tSELECT 1 FROM " . $xoopsDB->prefix("formulize_" . $formObject->getVar('form_handle')) . " AS t4 WHERE t4.`" . $element->getVar('ele_handle') . "` LIKE CONCAT( '%,', t1.`entry_id` , ',%' ) AND t4.entry_id != " . intval($entry_id);
             $restrictSQL .= $renderer->addEntryRestrictionSQL($ele_value[9], $id_form, $groups);
             // pass in the flag about restriction scope, and the form id, and the groups
             $restrictSQL .= " ) OR EXISTS (\n\t\t\t\tSELECT 1 FROM " . $xoopsDB->prefix("formulize_" . $formObject->getVar('form_handle')) . " AS t4 WHERE t4.`" . $element->getVar('ele_handle') . "` LIKE CONCAT( '%,', t1.`entry_id` , ',%' ) AND t4.entry_id = " . intval($entry_id);
             $restrictSQL .= $renderer->addEntryRestrictionSQL($ele_value[9], $id_form, $groups);
             $restrictSQL .= ") )";
         }
         static $cachedSourceValuesQ = array();
         static $cachedSourceValuesAutocompleteFile = array();
         static $cachedSourceValuesAutocompleteLength = array();
         // setup the sort order based on ele_value[12], which is an element id number
         $sortOrder = $ele_value[15] == 2 ? " DESC" : "ASC";
         if ($ele_value[12] == "none" or !$ele_value[12]) {
             $sortOrderClause = " ORDER BY t1.`{$sourceHandle}` {$sortOrder}";
         } else {
             list($sortHandle) = convertElementIdsToElementHandles(array($ele_value[12]), $sourceFormObject->getVar('id_form'));
             $sortOrderClause = " ORDER BY t1.`{$sortHandle}` {$sortOrder}";
         }
         if ($pgroupsfilter) {
             // if there is a groups filter, then join to the group ownership table
             $sourceValuesQ = "SELECT t1.entry_id, t1.`" . $sourceHandle . "` FROM " . $xoopsDB->prefix("formulize_" . $sourceFormObject->getVar('form_handle')) . " AS t1, " . $xoopsDB->prefix("formulize_entry_owner_groups") . " AS t2 {$parentFormFrom} WHERE {$pgroupsfilter} {$conditionsfilter} {$conditionsfilter_oom} {$restrictSQL} GROUP BY t1.entry_id {$sortOrderClause}";
         } else {
             // otherwise just query the source table
             $sourceValuesQ = "SELECT t1.entry_id, t1.`" . $sourceHandle . "` FROM " . $xoopsDB->prefix("formulize_" . $sourceFormObject->getVar('form_handle')) . " AS t1 {$parentFormFrom} WHERE t1.entry_id>0 {$conditionsfilter} {$conditionsfilter_oom} {$restrictSQL} GROUP BY t1.entry_id {$sortOrderClause}";
         }
         //print "$sourceValuesQ<br><br>";
         if (!$isDisabled) {
             // set the default selections, based on the entry_ids that have been selected as the defaults, if applicable
             $hasNoValues = trim($boxproperties[2]) == "" ? true : false;
             $useDefaultsWhenEntryHasNoValue = $ele_value[14];
             if (($entry_id == "new" or $useDefaultsWhenEntryHasNoValue and $hasNoValues) and (is_array($ele_value[13]) and count($ele_value[13]) > 0 or $ele_value[13])) {
                 $defaultSelected = $ele_value[13];
             } else {
                 $defaultSelected = "";
             }
             $form_ele = new XoopsFormSelect($caption, $markupName, $defaultSelected, $ele_value[0], $ele_value[1]);
             $form_ele->setExtra("onchange=\"javascript:formulizechanged=1;\" jquerytag='{$markupName}'");
             if ($ele_value[0] == 1) {
                 // add the initial default entry, singular or plural based on whether the box is one line or not.
                 $form_ele->addOption("none", _AM_FORMLINK_PICK);
             }
         } else {
             $disabledHiddenValue = array();
             $disabledOutputText = array();
         }
         if (!isset($cachedSourceValuesQ[$sourceValuesQ])) {
             $element_handler = xoops_getmodulehandler('elements', 'formulize');
             $sourceElementObject = $element_handler->get($boxproperties[1]);
             if ($sourceElementObject->isLinked) {
                 // need to jump one more level back to get value that this value is pointing at
                 $sourceEleValue = $sourceElementObject->getVar('ele_value');
                 $originalSource = explode("#*=:*", $sourceEleValue[2]);
                 include_once XOOPS_ROOT_PATH . "/modules/formulize/class/data.php";
                 $data_handler = new formulizeDataHandler($originalSource[0]);
             }
             $reslinkedvaluesq = $xoopsDB->query($sourceValuesQ);
             if ($reslinkedvaluesq) {
                 while ($rowlinkedvaluesq = $xoopsDB->fetchRow($reslinkedvaluesq)) {
                     if ($rowlinkedvaluesq[1] === "") {
                         continue;
                     }
                     if ($sourceElementObject->isLinked) {
                         $rowlinkedvaluesq[1] = $data_handler->getElementValueInEntry(trim($rowlinkedvaluesq[1], ","), $originalSource[1]);
                     }
                     $linkedElementOptions[$rowlinkedvaluesq[0]] = strip_tags($rowlinkedvaluesq[1]);
                 }
             }
             $cachedSourceValuesQ[$sourceValuesQ] = $linkedElementOptions;
             /* ALTERED - 20100318 - freeform - jeff/julian - start */
             if (!$isDisabled and $ele_value[8] == 1) {
                 // write the possible values to a cached file so we can look them up easily when we need them, don't want to actually send them to the browser, since it could be huge, but don't want to replicate all the logic that has already gathered the values for us, each time there's an ajax request
                 $cachedLinkedOptionsFileName = "formulize_linkedOptions_" . str_replace(".", "", microtime(true));
                 formulize_scandirAndClean(XOOPS_ROOT_PATH . "/cache/", "formulize_linkedOptions_");
                 $cachedLinkedOptions = fopen(XOOPS_ROOT_PATH . "/cache/{$cachedLinkedOptionsFileName}", "w");
                 fwrite($cachedLinkedOptions, "<?php\n\r");
                 $maxLength = 0;
                 foreach ($linkedElementOptions as $id => $text) {
                     $thisTextLength = strlen($text);
                     $maxLength = $thisTextLength > $maxLength ? $thisTextLength : $maxLength;
                     $text = str_replace("\$", "\\\$", $text);
                     $quotedText = "\"" . str_replace("\"", "\\\"", html_entity_decode($text, ENT_QUOTES)) . "\"";
                     $singleQuotedText = str_replace("'", "\\'", "[{$quotedText},{$id}]");
                     fwrite($cachedLinkedOptions, "if(stristr({$quotedText}, \$term)){ \$found[]='" . $singleQuotedText . "'; }\n");
                 }
                 fwrite($cachedLinkedOptions, "?>");
                 fclose($cachedLinkedOptions);
                 $cachedSourceValuesAutocompleteFile[$sourceValuesQ] = $cachedLinkedOptionsFileName;
                 $cachedSourceValuesAutocompleteLength[$sourceValuesQ] = $maxLength;
             }
         }
         // if we're rendering an autocomplete box
         if (!$isDisabled and $ele_value[8] == 1) {
             // do autocomplete rendering logic here
             if ($boxproperties[2]) {
                 $default_value = trim($boxproperties[2], ",");
                 $data_handler_autocomplete = new formulizeDataHandler($boxproperties[0]);
                 $default_value_user = $data_handler_autocomplete->getElementValueInEntry(trim($boxproperties[2], ","), $boxproperties[1]);
             }
             $renderedComboBox = $renderer->formulize_renderQuickSelect($markupName, $cachedSourceValuesAutocompleteFile[$sourceValuesQ], $default_value, $default_value_user, $cachedSourceValuesAutocompleteLength[$sourceValuesQ]);
             $form_ele = new xoopsFormLabel($caption, $renderedComboBox);
             $form_ele->setDescription(html_entity_decode($ele_desc, ENT_QUOTES));
         }
         // only do this if we're rendering a normal element, that is not disabled
         if (!$isDisabled and $ele_value[8] == 0) {
             $form_ele->addOptionArray($cachedSourceValuesQ[$sourceValuesQ]);
         }
         // only do this if we're rendering a normal element (may be disabled)
         if ($ele_value[8] == 0) {
             foreach ($sourceEntryIds as $thisEntryId) {
                 if (!$isDisabled) {
                     $form_ele->setValue($thisEntryId);
                 } else {
                     $disabledName = $ele_value[1] ? $markupName . "[]" : $markupName;
                     $disabledHiddenValue[] = "<input type=hidden name=\"{$disabledName}\" value=\"{$thisEntryId}\">";
                     $disabledOutputText[] = $cachedSourceValuesQ[$sourceValuesQ][$thisEntryId];
                     // the text value of the option(s) that are currently selected
                 }
             }
         }
         if ($isDisabled) {
             $form_ele = new XoopsFormLabel($caption, implode(", ", $disabledOutputText) . implode("\n", $disabledHiddenValue));
             $form_ele->setDescription(html_entity_decode($ele_desc, ENT_QUOTES));
         } elseif ($ele_value[8] == 0) {
             // this is a hack because the size attribute is private and only has a getSize and not a setSize, setting the size can only be done through the constructor
             $count = count($form_ele->getOptions());
             $size = $ele_value[0];
             $new_size = $count < $size ? $count : $size;
             $form_ele->_size = $new_size;
         }
         /* ALTERED - 20100318 - freeform - jeff/julian - stop */
     } else {
         // or if we don't have a link...
         $selected = array();
         $options = array();
         $disabledOutputText = array();
         $disabledHiddenValue = array();
         $disabledHiddenValues = "";
         // add the initial default entry, singular or plural based on whether the box is one line or not.
         if ($ele_value[0] == 1) {
             $options["none"] = _AM_FORMLINK_PICK;
         }
         // set opt_count to 1 if the box is NOT a multiple selection box. -- jwe 7/26/04
         if ($ele_value[1]) {
             $opt_count = 0;
         } else {
             $opt_count = 1;
         }
         $hiddenOutOfRangeValuesToWrite = array();
         while ($i = each($ele_value[2])) {
             // handle requests for full names or usernames -- will only kick in if there is no saved value (otherwise ele_value will have been rewritten by the loadValues function in the form display
             // note: if the user is about to make a proxy entry, then the list of users displayed will be from their own groups, but not from the groups of the user they are about to make a proxy entry for.  ie: until the proxy user is known, the choice of users for this list can only be based on the current user.  This could lead to confusing or buggy situations, such as users being selected who are outside the groups of the proxy user (who will become the owner) and so there will be an invalid value stored for this element in the db.
             if ($i['key'] === "{FULLNAMES}" or $i['key'] === "{USERNAMES}") {
                 // ADDED June 18 2005 to handle pulling in usernames for the user's group(s)
                 if ($i['key'] === "{FULLNAMES}") {
                     $nametype = "name";
                 }
                 if ($i['key'] === "{USERNAMES}") {
                     $nametype = "uname";
                 }
                 if (isset($ele_value[2]['{OWNERGROUPS}'])) {
                     $groups = $ele_value[2]['{OWNERGROUPS}'];
                 } else {
                     global $regcode;
                     if ($regcode) {
                         // if we're dealing with a registration code, determine group membership based on the code
                         $reggroupsq = q("SELECT reg_codes_groups FROM " . XOOPS_DB_PREFIX . "_reg_codes WHERE reg_codes_code=\"{$regcode}\"");
                         $groups = explode("&8(%\$", $reggroupsq[0]['reg_codes_groups']);
                         if ($groups[0] === "") {
                             unset($groups);
                         }
                         // if a code has no groups associated with it, then kill the null value that will be in position 0 in the groups array.
                         $groups[] = XOOPS_GROUP_USERS;
                         $groups[] = XOOPS_GROUP_ANONYMOUS;
                     } else {
                         global $xoopsUser;
                         $groups = $xoopsUser ? $xoopsUser->getGroups() : array(0 => XOOPS_GROUP_ANONYMOUS);
                     }
                 }
                 $pgroups = array();
                 if ($ele_value[3]) {
                     $scopegroups = explode(",", $ele_value[3]);
                     if (!in_array("all", $scopegroups)) {
                         if ($ele_value[4]) {
                             // limit by users's groups
                             foreach ($groups as $gid) {
                                 // want to loop so we can get rid of reg users group simply
                                 if ($gid == XOOPS_GROUP_USERS) {
                                     continue;
                                 }
                                 if (in_array($gid, $scopegroups)) {
                                     $pgroups[] = $gid;
                                 }
                             }
                             if (count($pgroups) > 0) {
                                 unset($groups);
                                 $groups = $pgroups;
                             } else {
                                 $groups = array();
                             }
                         } else {
                             // don't limit by user's groups
                             $groups = $scopegroups;
                         }
                     } else {
                         // use all
                         if (!$ele_value[4]) {
                             // really use all (otherwise, we're just going with all user's groups, so existing value of $groups will be okay
                             unset($groups);
                             global $xoopsDB;
                             $allgroupsq = q("SELECT groupid FROM " . $xoopsDB->prefix("groups"));
                             //  . " WHERE groupid != " . XOOPS_GROUP_USERS); // removed exclusion of registered users group March 18 2009, since it doesn't make sense in this situation.  All groups should mean everyone, period.
                             foreach ($allgroupsq as $thisgid) {
                                 $groups[] = $thisgid['groupid'];
                             }
                         }
                     }
                 }
                 $namelist = gatherNames($groups, $nametype, $ele_value[6], $ele_value[5]);
                 foreach ($namelist as $auid => $aname) {
                     $options[$auid] = $aname;
                 }
             } elseif ($i['key'] === "{SELECTEDNAMES}") {
                 // loadValue in formDisplay will create a second option with this key that contains an array of the selected values
                 $selected = $i['value'];
             } elseif ($i['key'] === "{OWNERGROUPS}") {
                 // do nothing with this piece of metadata that gets set in loadValue, since it's used above
             } else {
                 // regular selection list....
                 $options[$opt_count] = $myts->stripSlashesGPC($i['key']);
                 if (strstr($i['key'], _formulize_OUTOFRANGE_DATA)) {
                     $hiddenOutOfRangeValuesToWrite[$opt_count] = str_replace(_formulize_OUTOFRANGE_DATA, "", $i['key']);
                     // if this is an out of range value, grab the actual value so we can stick it in a hidden element later
                 }
                 if ($i['value'] > 0) {
                     $selected[] = $opt_count;
                 }
                 $opt_count++;
             }
         }
         $count = count($options);
         $size = $ele_value[0];
         $final_size = $count < $size ? $count : $size;
         $form_ele1 = new XoopsFormSelect($caption, $markupName, $selected, $final_size, $ele_value[1]);
         $form_ele1->setExtra("onchange=\"javascript:formulizechanged=1;\" jquerytag='{$markupName}'");
         // must check the options for uitext before adding to the element -- aug 25, 2007
         foreach ($options as $okey => $ovalue) {
             $options[$okey] = formulize_swapUIText($ovalue, $element->getVar('ele_uitext'));
         }
         $form_ele1->addOptionArray($options);
         if ($selected) {
             if (is_array($selected)) {
                 $hiddenElementName = $ele_value[1] ? $form_ele1->getName() . "[]" : $form_ele1->getName();
                 foreach ($selected as $thisSelected) {
                     $disabledOutputText[] = $options[$thisSelected];
                     $disabledHiddenValue[] = "<input type=hidden name=\"{$hiddenElementName}\" value=\"{$thisSelected}\">";
                 }
             } elseif ($ele_value[1]) {
                 // need to keep [] in the hidden element name if multiple values are expected, even if only one is chosen
                 $disabledOutputText[] = $options[$selected];
                 $disabledHiddenValue[] = "<input type=hidden name=\"" . $form_ele1->getName() . "[]\" value=\"{$selected}\">";
             } else {
                 $disabledOutputText[] = $options[$selected];
                 $disabledHiddenValue[] = "<input type=hidden name=\"" . $form_ele1->getName() . "\" value=\"{$selected}\">";
             }
         }
         $renderedHoorvs = "";
         if (count($hiddenOutOfRangeValuesToWrite) > 0) {
             foreach ($hiddenOutOfRangeValuesToWrite as $hoorKey => $hoorValue) {
                 $thisHoorv = new xoopsFormHidden('formulize_hoorv_' . $true_ele_id . '_' . $hoorKey, $hoorValue);
                 $renderedHoorvs .= $thisHoorv->render() . "\n";
                 unset($thisHoorv);
             }
         }
         if ($isDisabled) {
             $disabledHiddenValues = implode("\n", $disabledHiddenValue);
             // glue the individual value elements together into a set of values
             $renderedElement = implode(", ", $disabledOutputText);
         } elseif ($ele_value[8] == 1) {
             // autocomplete construction: make sure that $renderedElement is the final output of this chunk of code
             // write the possible values to a cached file so we can look them up easily when we need them, don't want to actually send them to the browser, since it could be huge, but don't want to replicate all the logic that has already gathered the values for us, each time there's an ajax request
             $cachedOptionsFileName = "formulize_Options_" . str_replace(".", "", microtime(true));
             formulize_scandirAndClean(XOOPS_ROOT_PATH . "/cache/", "formulize_Options_");
             $cachedOptions = fopen(XOOPS_ROOT_PATH . "/cache/{$cachedOptionsFileName}", "w");
             fwrite($cachedOptions, "<?php\n\r");
             $maxLength = 0;
             foreach ($options as $id => $text) {
                 $thisTextLength = strlen($text);
                 $maxLength = $thisTextLength > $maxLength ? $thisTextLength : $maxLength;
                 //$quotedText = "\"".str_replace("\"", "\\\"", trim($text))."\"";
                 $quotedText = "\"" . str_replace("\"", "\\\"", $text) . "\"";
                 fwrite($cachedOptions, "if(stristr({$quotedText}, \$term)){ \$found[]='[{$quotedText},{$id}]'; }\n\r");
             }
             fwrite($cachedOptions, "?>");
             fclose($cachedOptions);
             //print_r($selected); print_r($options);
             $defaultSelected = is_array($selected) ? $selected[0] : $selected;
             $renderedComboBox = $renderer->formulize_renderQuickSelect($markupName, $cachedOptionsFileName, $defaultSelected, $options[$defaultSelected], $maxLength);
             $form_ele2 = new xoopsFormLabel($caption, $renderedComboBox);
             $renderedElement = $form_ele2->render();
         } else {
             // normal element
             $renderedElement = $form_ele1->render();
         }
         $form_ele = new XoopsFormLabel($caption, "<nobr>{$renderedElement}</nobr>\n{$renderedHoorvs}\n{$disabledHiddenValues}\n");
         $form_ele->setDescription(html_entity_decode($ele_desc, ENT_QUOTES));
     }
     // end of if we have a link on our hands. -- jwe 7/29/04
     return $form_ele;
 }
function convertRawValuestoRealValues($value, $handle, $returnFlat = false)
{
    if (!is_array($value)) {
        $value = array(0 => $value);
        $arrayWasPassedIn = false;
    } else {
        $arrayWasPassedIn = true;
    }
    $element_handler = xoops_getmodulehandler('elements', 'formulize');
    $thisElement = $element_handler->get($handle);
    if (!is_object($thisElement)) {
        if ($arrayWasPassedIn) {
            return $value;
        } else {
            return $value[0];
        }
    }
    $ele_value = $thisElement->getVar('ele_value');
    $isLinkedSelectBox = false;
    $isNamesList = false;
    if (is_array($ele_value)) {
        if (isset($ele_value[2])) {
            if (strstr($ele_value[2], "#*=:*")) {
                $isLinkedSelectBox = true;
                $linkedMetaData = formulize_isLinkedSelectBox($thisElement->getVar('ele_id'));
            } elseif (isset($ele_value[2]["{FULLNAMES}"]) or isset($ele_value[2]["{USERNAMES}"])) {
                $isNamesList = isset($ele_value[2]["{FULLNAMES}"]) ? 'name' : 'uname';
            }
        }
    }
    $allRealValuesNames = array();
    foreach ($value as $thisValue) {
        if ($isLinkedSelectBox) {
            // convert the pointers for the linked selectbox values, to their source values
            $sourceMeta = explode("#*=:*", $linkedMetaData[2]);
            $data_handler = new formulizeDataHandler($sourceMeta[0]);
            $realValues = $data_handler->findAllValuesForEntries($sourceMeta[1], explode(",", trim($thisValue, ",")));
            // trip opening and closing commas and split by comma into an array
            // findAllValuesForEntries method returns an array, so convert to a single value
            if (is_array($realValues) and $returnFlat) {
                $realValues = implode(", ", $realValues);
            }
            $allRealValues[] = $realValues;
        } elseif (strstr($thisValue, "*=+*:")) {
            $allRealValues[] = str_replace("*=+*:", ", ", ltrim($thisValue, "*=+*:"));
            // replace the separator with commas between values
        } elseif ($isNamesList) {
            $allRealValuesNames[] = $thisValue;
        } else {
            $allRealValues[] = $thisValue;
        }
    }
    if (count($allRealValuesNames) > 0) {
        // convert all uids found into names with only one query
        $user_handler = xoops_gethandler('user');
        $criteria = new CriteriaCompo();
        foreach ($allRealValuesNames as $thisUid) {
            if (is_numeric($thisUid)) {
                $criteria->add(new Criteria('uid', $thisUid), 'OR');
            }
        }
        $users = $user_handler->getObjects($criteria, true);
        // true causes key of returned array to be uids
        foreach ($allRealValuesNames as $thisUid) {
            if (is_numeric($thisUid) and isset($users[$thisUid])) {
                $allRealValues[] = $users[$thisUid]->getVar($isNamesList);
            } else {
                $allRealValues[] = _formulize_BLANK_KEYWORD;
            }
        }
    }
    if ($arrayWasPassedIn) {
        return $allRealValues;
    } else {
        return $allRealValues[0];
    }
}
 function adminSave($element, $ele_value)
 {
     $changed = false;
     list($indexId, $ele_uitext) = formulize_extractUIText($_POST['ele_value']);
     foreach ($indexId as $id => $text) {
         if ($text !== "") {
             $ele_value[$text] = isset($_POST['defaultoption'][$id]) ? 1 : 0;
         }
     }
     $element->setVar('ele_value', $ele_value);
     if ($_POST['element_delimit']) {
         if ($_POST['element_delimit'] == "custom") {
             $element->setVar('ele_delim', $_POST['element_delim_custom']);
         } else {
             $element->setVar('ele_delim', $_POST['element_delimit']);
         }
     }
     if (isset($_POST['changeuservalues']) and $_POST['changeuservalues'] == 1) {
         include_once XOOPS_ROOT_PATH . "/modules/formulize/class/data.php";
         $fid = $element->getVar('id_form');
         $data_handler = new formulizeDataHandler($fid);
         $newValues = $element->getVar('ele_value');
         $ele_id = $element->getVar('ele_id');
         if (!($changeResult = $data_handler->changeUserSubmittedValues($ele_id, $newValues))) {
             print "Error updating user submitted values for the options in element {$ele_id}";
         }
     }
     return $changed;
 }
 private static function user_can_modify_entry($action, $form_id, $user_id, $entry_id)
 {
     if (!in_array($action, array("update", "delete"))) {
         throw new Exception("Error: specify either update or delete when calling user_can_modify_entry();");
     }
     $cache_key = "{$action} {$form_id} {$user_id} {$entry_id}";
     if (!isset(self::$cached_permissions[$cache_key])) {
         self::$cached_permissions[$cache_key] = false;
         if (null == self::$formulize_module_id) {
             self::$formulize_module_id = getFormulizeModId();
         }
         $gperm_handler =& xoops_gethandler('groupperm');
         $member_handler =& xoops_gethandler('member');
         $groups = $member_handler->getGroupsByUser($user_id);
         if ("new" == $entry_id or "" == $entry_id) {
             if ("update" == $action) {
                 // user has permission to add new entries
                 self::$cached_permissions[$cache_key] = $gperm_handler->checkRight("add_own_entry", $form_id, $groups, self::$formulize_module_id);
                 if (!self::$cached_permissions[$cache_key]) {
                     self::$cached_permissions[$cache_key] = $gperm_handler->checkRight("add_proxy_entries", $form_id, $groups, self::$formulize_module_id);
                 }
             } else {
                 self::$cached_permissions[$cache_key] = false;
                 // cannot delete an entry which has not been saved
             }
         } else {
             // first check if this an entry by current user and they can edit their own entries
             if (getEntryOwner($entry_id, $form_id) == $user_id) {
                 // user can update entry because it is their own and they have permission to update their own entries
                 self::$cached_permissions[$cache_key] = $gperm_handler->checkRight("{$action}_own_entry", $form_id, $groups, self::$formulize_module_id);
             }
             // next, check group and other permissions, even for own entries
             if (!self::$cached_permissions[$cache_key]) {
                 // user can update entry because they have permission to update entries by others
                 self::$cached_permissions[$cache_key] = $gperm_handler->checkRight("{$action}_other_entries", $form_id, $groups, self::$formulize_module_id);
                 if (!self::$cached_permissions[$cache_key]) {
                     // check if the user belongs to a group with group-edit permission
                     if ($gperm_handler->checkRight("{$action}_group_entries", $form_id, $groups, self::$formulize_module_id)) {
                         // sometimes users can have a special group scope set, so use that if available
                         $formulize_permHandler = new formulizePermHandler($form_id);
                         $view_form_groups = $formulize_permHandler->getGroupScopeGroupIds($groups);
                         if ($view_form_groups === false) {
                             // no special group scope, so use normal view-form permissions
                             $view_form_groups = $gperm_handler->getGroupIds("view_form", $form_id, self::$formulize_module_id);
                             // need the groups the user is a member of, that have view form permission
                             $view_form_groups = array_intersect($view_form_groups, $groups);
                         }
                         // get the owner groups for the entry
                         $data_handler = new formulizeDataHandler($form_id);
                         $owner_groups = $data_handler->getEntryOwnerGroups($entry_id);
                         // check if the entry belongs to a group that is part of the scope that the user is permitted to interact with
                         self::$cached_permissions[$cache_key] = count(array_intersect($owner_groups, $view_form_groups));
                     }
                 }
             }
         }
         //Second update to include custom edit check code
         if ("update" == $action && $entry_id > 0) {
             $formHandler = xoops_getmodulehandler('forms', 'formulize');
             $formObject = $formHandler->get($form_id);
             self::$cached_permissions[$cache_key] = $formObject->customEditCheck($form_id, $entry_id, $user_id, self::$cached_permissions[$cache_key]);
         }
     }
     return self::$cached_permissions[$cache_key];
 }
Example #18
0
         $options['listValue'] = $listValue->render();
         // list of elements to display when showing this element as an html form element (in form or list screens)
         list($displayElements, $selectedListValue) = createFieldList($ele_value[EV_MULTIPLE_FORM_COLUMNS], false, $linkedSourceFid, "elements-ele_value[" . EV_MULTIPLE_FORM_COLUMNS . "]", _AM_ELE_LINKSELECTEDABOVE, true);
         $displayElements->setValue($ele_value[EV_MULTIPLE_FORM_COLUMNS]);
         // mark the current selections in the form element
         $options['displayElements'] = $displayElements->render();
         // list of elements to export to spreadsheet
         list($exportValue, $selectedExportValue) = createFieldList($ele_value[EV_MULTIPLE_SPREADSHEET_COLUMNS], false, $linkedSourceFid, "elements-ele_value[" . EV_MULTIPLE_SPREADSHEET_COLUMNS . "]", _AM_ELE_VALUEINLIST, true);
         $exportValue->setValue($ele_value[EV_MULTIPLE_SPREADSHEET_COLUMNS]);
         // mark the current selections in the form element
         $options['exportValue'] = $exportValue->render();
         // sort order
         list($optionSortOrder, $selectedOptionsSortOrder) = createFieldList($ele_value[12], false, $linkedSourceFid, "elements-ele_value[12]", _AM_ELE_LINKFIELD_ITSELF);
         $options['optionSortOrder'] = $optionSortOrder->render();
         include_once XOOPS_ROOT_PATH . "/modules/formulize/class/data.php";
         $linkedDataHandler = new formulizeDataHandler($linkedSourceFid);
         $allLinkedValues = $linkedDataHandler->findAllValuesForField($linkedMetaDataParts[1], "ASC");
         if (!is_array($ele_value[13])) {
             $ele_value[13] = array($ele_value[13]);
         }
         $options['optionDefaultSelectionDefaults'] = $ele_value[13];
         $options['optionDefaultSelection'] = $allLinkedValues;
         // array with keys as entry ids and values as text
     }
 }
 if (!$options['islinked'] or !$linkedSourceFid) {
     $options['exportValue'] = "";
     $options['listValue'] = "";
     $options['optionSortOrder'] = "";
     $options['optionDefaultSelectionDefaults'] = array();
     $options['optionDefaultSelection'] = "";
function displayFormPages($formframe, $entry = "", $mainform = "", $pages, $conditions = "", $introtext = "", $thankstext = "", $done_dest = "", $button_text = "", $settings = "", $overrideValue = "", $printall = 0, $screen = null, $saveAndContinueButtonText = null)
{
    // nmc 2007.03.24 - added 'printall'
    formulize_benchmark("Start of displayFormPages.");
    // extract the optional page titles from the $pages array for use in the jump to box
    // NOTE: pageTitles array must start with key 1, not 0.  Page 1 is the first page of the form
    $pageTitles = array();
    if (isset($pages['titles'])) {
        $pageTitles = $pages['titles'];
        unset($pages['titles']);
    }
    if (!$saveAndContinueButtonText and isset($_POST['formulize_saveAndContinueButtonText'])) {
        $saveAndContinueButtonText = unserialize($_POST['formulize_saveAndContinueButtonText']);
    }
    if (!$done_dest and $_POST['formulize_doneDest']) {
        $done_dest = $_POST['formulize_doneDest'];
    }
    if (!$button_text and $_POST['formulize_buttonText']) {
        $button_text = $_POST['formulize_buttonText'];
    }
    list($fid, $frid) = getFormFramework($formframe, $mainform);
    $thankstext = $thankstext ? $thankstext : _formulize_DMULTI_THANKS;
    $introtext = $introtext ? $introtext : "";
    global $xoopsUser;
    $mid = getFormulizeModId();
    $groups = $xoopsUser ? $xoopsUser->getGroups() : array(0 => XOOPS_GROUP_ANONYMOUS);
    $uid = $xoopsUser ? $xoopsUser->getVar('uid') : 0;
    $gperm_handler =& xoops_gethandler('groupperm');
    $member_handler =& xoops_gethandler('member');
    $single_result = getSingle($fid, $uid, $groups, $member_handler, $gperm_handler, $mid);
    // if this function was called without an entry specified, then assume the identity of the entry we're editing (unless this is a new save, in which case no entry has been made yet)
    // no handling of cookies here, so anonymous multi-page surveys will not benefit from that feature
    // this emphasizes how we need to standardize a lot of these interfaces with a real class system
    if (!$entry and $_POST['entry' . $fid]) {
        $entry = $_POST['entry' . $fid];
    } elseif (!$entry) {
        // or check getSingle to see what the real entry is
        $entry = $single_result['flag'] ? $single_result['entry'] : 0;
    }
    // formulize_newEntryIds is set when saving data
    if (!$entry and isset($GLOBALS['formulize_newEntryIds'][$fid])) {
        $entry = $GLOBALS['formulize_newEntryIds'][$fid][0];
    }
    $owner = getEntryOwner($entry, $fid);
    $prevPage = isset($_POST['formulize_prevPage']) ? $_POST['formulize_prevPage'] : 1;
    // last page that the user was on, not necessarily the previous page numerically
    $currentPage = isset($_POST['formulize_currentPage']) ? $_POST['formulize_currentPage'] : 1;
    $thanksPage = count($pages) + 1;
    // debug control:
    $currentPage = (isset($_GET['debugpage']) and is_numeric($_GET['debugpage'])) ? $_GET['debugpage'] : $currentPage;
    $usersCanSave = formulizePermHandler::user_can_edit_entry($fid, $uid, $entry);
    if ($pages[$prevPage][0] !== "HTML" and $pages[$prevPage][0] !== "PHP") {
        // remember prevPage is the last page the user was on, not the previous page numerically
        if (isset($_POST['form_submitted']) and $usersCanSave) {
            include_once XOOPS_ROOT_PATH . "/modules/formulize/include/formread.php";
            include_once XOOPS_ROOT_PATH . "/modules/formulize/include/functions.php";
            include_once XOOPS_ROOT_PATH . "/modules/formulize/class/data.php";
            //$owner_groups =& $member_handler->getGroupsByUser($owner, FALSE);
            $data_handler = new formulizeDataHandler($fid);
            $owner_groups = $data_handler->getEntryOwnerGroups($entry);
            $entries[$fid][0] = $entry;
            if ($frid) {
                $linkResults = checkForLinks($frid, array(0 => $fid), $fid, $entries, $gperm_handler, $owner_groups, $mid, $member_handler, $owner);
                unset($entries);
                $entries = $linkResults['entries'];
            }
            $entries = $GLOBALS['formulize_allWrittenEntryIds'];
            // set in readelements.php
            // if there has been no specific entry specified yet, then assume the identity of the entry that was just saved -- assumption is it will be a new save
            // from this point forward in time, this is the only entry that should be involved, since the 'entry'.$fid condition above will put this value into $entry even if this function was called with a blank entry value
            if (!$entry) {
                $entry = $entries[$fid][0];
            }
            synchSubformBlankDefaults($fid, $entry);
        }
    }
    // there are several points above where $entry is set, and now that we have a final value, store in ventry
    if ($entry > 0) {
        $settings['ventry'] = $entry;
    }
    // check to see if there are conditions on this page, and if so are they met
    // if the conditions are not met, move on to the next page and repeat the condition check
    // conditions only checked once there is an entry!
    $pagesSkipped = false;
    if (is_array($conditions) and $entry) {
        $conditionsMet = false;
        while (!$conditionsMet) {
            if (isset($conditions[$currentPage]) and count($conditions[$currentPage][0]) > 0) {
                // conditions on the current page
                $thesecons = $conditions[$currentPage];
                $elements = $thesecons[0];
                $ops = $thesecons[1];
                $terms = $thesecons[2];
                $types = $thesecons[3];
                // indicates if the term is part of a must or may set, ie: boolean and or or
                $filter = "";
                $oomfilter = "";
                $blankORSearch = "";
                foreach ($elements as $i => $thisElement) {
                    if ($ops[$i] == "NOT") {
                        $ops[$i] = "!=";
                    }
                    if ($terms[$i] == "{BLANK}") {
                        // NOTE...USE OF BLANKS WON'T WORK CLEANLY IN ALL CASES DEPENDING WHAT OTHER TERMS HAVE BEEN SPECIFIED!!
                        if ($ops[$i] == "!=" or $ops[$i] == "NOT LIKE") {
                            if ($types[$i] != "oom") {
                                // add to the main filter, ie: entry id = 1 AND x=5 AND y IS NOT "" AND y IS NOT NULL
                                if (!$filter) {
                                    $filter = $entry . "][" . $elements[$i] . "/**//**/!=][" . $elements[$i] . "/**//**/IS NOT NULL";
                                } else {
                                    $filter .= "][" . $elements[$i] . "/**//**/!=][" . $elements[$i] . "/**//**/IS NOT NULL";
                                }
                            } else {
                                // Add to the OOM filter, ie: entry id = 1 AND (x=5 OR y IS NOT "" OR y IS NOT NULL)
                                if (!$oomfilter) {
                                    $oomfilter = $elements[$i] . "/**//**/=][" . $elements[$i] . "/**//**/IS NULL";
                                } else {
                                    $oomfilter .= "][" . $elements[$i] . "/**//**/=][" . $elements[$i] . "/**//**/IS NULL";
                                }
                            }
                        } else {
                            if ($types[$i] != "oom") {
                                // add to its own OR filter, since we MUST match this condition, but we don't care if it's "" OR NULL
                                // ie: entry id = 1 AND (x=5 OR y=10) AND (z = "" OR z IS NULL)
                                if (!$blankORSearch) {
                                    $blankORSearch = $elements[$i] . "/**//**/=][" . $elements[$i] . "/**//**/IS NULL";
                                } else {
                                    $blankORSearch .= "][" . $elements[$i] . "/**//**/=][" . $elements[$i] . "/**//**/IS NULL";
                                }
                            } else {
                                // it's part of the oom filters anyway, so we put it there, because we don't care if it's null or "" or neither
                                if (!$oomfilter) {
                                    $oomfilter = $elements[$i] . "/**//**/=][" . $elements[$i] . "/**//**/IS NULL";
                                } else {
                                    $oomfilter .= "][" . $elements[$i] . "/**//**/=][" . $elements[$i] . "/**//**/IS NULL";
                                }
                            }
                        }
                    } elseif ($types[$i] == "oom") {
                        if (!$oomfilter) {
                            $oomfilter = $elements[$i] . "/**/" . trans($terms[$i]) . "/**/" . $ops[$i];
                        } else {
                            $oomfilter .= "][" . $elements[$i] . "/**/" . trans($terms[$i]) . "/**/" . $ops[$i];
                        }
                    } else {
                        if (!$filter) {
                            $filter = $entry . "][" . $elements[$i] . "/**/" . trans($terms[$i]) . "/**/" . $ops[$i];
                        } else {
                            $filter .= "][" . $elements[$i] . "/**/" . trans($terms[$i]) . "/**/" . $ops[$i];
                        }
                    }
                }
                if ($oomfilter and $filter) {
                    $finalFilter = array();
                    $finalFilter[0][0] = "AND";
                    $finalFilter[0][1] = $filter;
                    $finalFilter[1][0] = "OR";
                    $finalFilter[1][1] = $oomfilter;
                    if ($blankORSearch) {
                        $finalFilter[2][0] = "OR";
                        $finalFilter[2][1] = $blankORSearch;
                    }
                } elseif ($oomfilter) {
                    // need to add the $entry as a separate filter from the oom, so the entry and oom get an AND in between them
                    $finalFilter = array();
                    $finalFilter[0][0] = "AND";
                    $finalFilter[0][1] = $entry;
                    $finalFilter[1][0] = "OR";
                    $finalFilter[1][1] = $oomfilter;
                    if ($blankORSearch) {
                        $finalFilter[2][0] = "OR";
                        $finalFilter[2][1] = $blankORSearch;
                    }
                } else {
                    if ($blankORSearch) {
                        $finalFilter[0][0] = "AND";
                        $finalFilter[0][1] = $filter ? $filter : $entry;
                        $finalFilter[1][0] = "OR";
                        $finalFilter[1][1] = $blankORSearch;
                    } else {
                        $finalFilter = $filter;
                    }
                }
                $masterBoolean = "AND";
                include_once XOOPS_ROOT_PATH . "/modules/formulize/include/extract.php";
                $data = getData($frid, $fid, $finalFilter, $masterBoolean, "", "", "", "", "", false, 0, false, "", false, true);
                if (!$data) {
                    if ($prevPage <= $currentPage) {
                        $currentPage++;
                    } else {
                        $currentPage--;
                    }
                    $pagesSkipped = true;
                } else {
                    $conditionsMet = true;
                }
            } else {
                // no conditions on the current page
                $conditionsMet = true;
            }
        }
    }
    if ($currentPage > 1) {
        $previousPage = $currentPage - 1;
        // previous page numerically
    } else {
        $previousPage = "none";
    }
    $nextPage = $currentPage + 1;
    $done_dest = $done_dest ? $done_dest : getCurrentURL();
    $done_dest = substr($done_dest, 0, 4) == "http" ? $done_dest : "http://" . $done_dest;
    // Set up the javascript that we need for the form-submit functionality to work
    // note that validateAndSubmit calls the form validation function again, but obviously it will pass if it passed here.  The validation needs to be called prior to setting the pages, or else you can end up on the wrong page after clicking an ADD button in a subform when you've missed a required field.
    // savedPage and savedPrevPage are used to pick up the page and prevpage only when a two step validation, such as checking for uniqueness, returns and calls validateAndSubmit again
    ?>
	
	<script type='text/javascript'>
	var savedPage;
	var savedPrevPage;
	function submitForm(page, prevpage) {
		var validate = xoopsFormValidate_formulize();
		if(validate) {
			savedPage = 0;
			savedPrevPage = 0;
			multipageSetHiddenFields(page, prevpage);
			if (formulizechanged) {
        validateAndSubmit();
      } else {
        jQuery("#formulizeform").animate({opacity:0.4}, 200, "linear");
        jQuery("input[name^='decue_']").remove();
        // 'rewritePage' will trigger the page to change after the locks have been removed
        removeEntryLocks('rewritePage');
      }
    } else {
			savedPage = page;
			savedPrevPage = prevpage;
		}
  }

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

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