Exemple #1
0
function single_edit($tbl, $col, $id)
{
    $result = getSingle($tbl, $col, $id);
    $getResult = mysqli_fetch_array($result);
    echo "<form action=\"edit.php\" method=\"POST\">";
    echo "<input type=\"hidden\" name=\"tbl\" value=\"{$tbl}\">";
    echo "<input type=\"hidden\" name=\"col\" value=\"{$col}\">";
    echo "<input type=\"hidden\" name=\"id\" value=\"{$id}\">";
    for ($i = 0; $i < mysqli_num_fields($result); $i++) {
        $dataType = mysqli_fetch_field_direct($result, $i);
        //expects two arguments
        $fieldName = $dataType->name;
        //like an associative array - allows you to dig into the object and look for "name" (seen as the label in the object with the ->)
        //$title = explode('_', $fieldName);
        $fieldType = $dataType->type;
        //returns a number that can be used
        if ($fieldName != $col) {
            echo "<label>{$fieldName}</label><br>";
            if ($fieldType != 252) {
                echo "<input type=\"text\" name=\"{$fieldName}\" value=\"{$getResult[$i]}\">";
            } else {
                echo "<textarea name=\"{$fieldName}\">{$getResult[$i]}</textarea>";
            }
        }
    }
    echo "<input type=\"submit\" value=\"Save Content\">";
    echo "</form>";
}
 function formulize_setupPreviousEntryUI($screen, $element_id, $type, $owner, $de = false, $entryId = "", $ele_handle, $fid)
 {
     // 1. need to get and cache the values of the entry for this screen
     // 2. need to put the values into a dropdown list with an onchange event that populates the actual form element
     // this should be cached in some other way, since every instance of the renderer will need to cache this.  If it were a GLOBAL or this whole thing were in some other function, that would work.
     static $cachedEntries = array();
     if (!isset($cachedEntries[$screen->getVar('sid')])) {
         // identify the entry belonging to this user's group(s) in the other form.  Currently only group correspondence is supported.
         global $xoopsUser;
         $groups = $xoopsUser ? $xoopsUser->getGroups() : array(0 => XOOPS_GROUP_ANONYMOUS);
         $member_handler =& xoops_gethandler('member');
         $gperm_handler =& xoops_gethandler('groupperm');
         $mid = getFormulizeModId();
         $owner_groups =& $member_handler->getGroupsByUser($owner, FALSE);
         // in this particular case, it's okay to make the owner_groups based on the users's memberships, since we want to present the single entry that belongs to whichever groups the user is a member of...I think.  :-)
         $singleData = getSingle($screen->getVar('paraentryform'), $owner, $owner_groups, $member_handler, $gperm_handler, $mid);
         if ($singleData['flag'] == "group" and $singleData['entry'] > 0) {
             // only proceed if there is a one-entry-per-group situation in the target form
             formulize_benchmark("Ready to do previous entry query.");
             $cachedEntries[$screen->getVar('sid')] = getData("", $screen->getVar('paraentryform'), $singleData['entry']);
             formulize_benchmark("Done query.");
         } else {
             return "";
         }
     }
     $entries = $cachedEntries[$screen->getVar('sid')];
     // big assumption below is corresponding captions.  In future there will be more ad hoc ways of describing which elements align to which other ones.
     // 1. figure out the corresponding element ID based on matching captions
     // 2. grab the previous value from the $entry/entries
     // 3. create the dropdown list with these values, including javascript
     $formHandler =& xoops_getmodulehandler('forms', 'formulize');
     $currentForm = $formHandler->get($screen->getVar('fid'));
     $previousForm = $formHandler->get($screen->getVar('paraentryform'));
     $currentCaptions = $currentForm->getVar('elementCaptions');
     $captionToMatch = $currentCaptions[$ele_handle];
     $previousCaptions = $previousForm->getVar('elementCaptions');
     $previousElementHandle = array_search($captionToMatch, $previousCaptions);
     if (!$previousElementHandle) {
         return "";
     }
     $elementName = $de ? "de_" . $fid . "_" . $entryId . "_" . $element_id : "ele_" . $element_id;
     // displayElement elements have different names from regular elements
     $previousElementId = formulize_getIdFromElementHandle($previousElementHandle);
     // function is in extract.php
     // setup the javascript based on the type of question, and setup other data that is required
     switch ($type) {
         case "text":
         case "date":
             $javascript = "onchange='javascript:this.form." . $elementName . ".value=this.form.prev_" . $element_id . ".value;'";
             break;
         case "radio":
             // need to get the options of the question so we know what to match
             $prevElementMetaData = formulize_getElementMetaData($previousElementId);
             // use this function in extract instead of the get element method in handler, since this is guaranteed to be already be cached in memory
             $prevElement_ele_value = unserialize($prevElementMetaData['ele_value']);
             $prevElementOptions = array_keys($prevElement_ele_value);
             $javascript = "onchange='javascript:if(this.form.prev_" . $element_id . ".value !== \"\") { this.form." . $elementName . "[this.form.prev_" . $element_id . ".value].checked=true; }'";
             break;
         case "yn":
             $javascript = "onchange='javascript:if(this.form.prev_" . $element_id . ".value !== \"\") { this.form." . $elementName . "[this.form.prev_" . $element_id . ".value].checked=true; }'";
             break;
     }
     $previousOptions = array();
     $prevOptionsExist = false;
     foreach ($entries as $id => $entry) {
         $value = htmlspecialchars(strip_tags(display($entry, $previousElementHandle)));
         if (is_array($value)) {
             $value = printSmart(implode(", ", $value));
         }
         if (trim($value) === "" or trim($value) == "0000-00-00") {
             continue;
         }
         $prevOptionsExist = true;
         switch ($type) {
             case "text":
             case "date":
                 $previousOptions[$value] = $value;
                 break;
             case "radio":
                 $prevElementPosition = array_search($value, $prevElementOptions);
                 // need to figure out which option matches the text of the value
                 if ($prevElementPosition !== false) {
                     $previousOptions[$prevElementPosition] = $value;
                     // for radio buttons, we need to pass the position of the option
                 }
                 break;
             case "yn":
                 if ($value == _formulize_TEMP_QYES) {
                     $previousOptions[0] = $value;
                 } elseif ($value == _formulize_TEMP_QNO) {
                     $previousOptions[1] = $value;
                 }
                 break;
         }
     }
     if (!$prevOptionsExist) {
         return "";
     }
     $prevUI = new xoopsFormSelect('', 'prev_' . $element_id, '123qweasdzxc', 1, false);
     // 123qweasdzxc is meant to be a unique value that will never be selected, since we don't ever want a previous selection showing by default
     $prevUI->addOption('', _AM_FORMULIZE_PREVIOUS_OPTION);
     $prevUI->addOptionArray($previousOptions);
     $prevUI->setExtra($javascript);
     return $prevUI;
 }
function drawSubLinks($subform_id, $sub_entries, $uid, $groups, $frid, $mid, $fid, $entry, $customCaption = "", $customElements = "", $defaultblanks = 0, $showViewButtons = 1, $captionsForHeadings = 0, $overrideOwnerOfNewEntries = "", $mainFormOwner = 0, $hideaddentries = "", $subformConditions = null, $subformElementId = 0, $rowsOrForms = 'row', $addEntriesText = _formulize_ADD_ENTRIES, $subform_element_object = null)
{
    $nestedSubform = false;
    if (isset($GLOBALS['formulize_inlineSubformFrid'])) {
        $frid = $GLOBALS['formulize_inlineSubformFrid'];
        $nestedSubform = true;
    }
    $member_handler = xoops_gethandler('member');
    $gperm_handler = xoops_gethandler('groupperm');
    $addEntriesText = $addEntriesText ? $addEntriesText : _formulize_ADD_ENTRIES;
    global $xoopsDB, $nosubforms;
    $GLOBALS['framework'] = $frid;
    $form_handler = xoops_getmodulehandler('forms', 'formulize');
    // limit the sub_entries array to just the entries that match the conditions, if any
    if (is_array($subformConditions) and is_array($sub_entries[$subform_id])) {
        list($conditionsFilter, $conditionsFilterOOM, $curlyBracketFormFrom) = buildConditionsFilterSQL($subformConditions, $subform_id, $entry, $mainFormOwner, $fid);
        // pass in mainFormOwner as the comparison ID for evaluating {USER} so that the included entries are consistent when an admin looks at a set of entries made by someone else.
        $subformObject = $form_handler->get($subform_id);
        $sql = "SELECT entry_id FROM " . $xoopsDB->prefix("formulize_" . $subformObject->getVar('form_handle')) . "{$curlyBracketFormFrom} WHERE entry_id IN (" . implode(", ", $sub_entries[$subform_id]) . ") {$conditionsFilter} {$conditionsFilterOOM}";
        $sub_entries[$subform_id] = array();
        if ($res = $xoopsDB->query($sql)) {
            while ($array = $xoopsDB->fetchArray($res)) {
                $sub_entries[$subform_id][] = $array['entry_id'];
            }
        }
    }
    include_once XOOPS_ROOT_PATH . "/modules/formulize/include/extract.php";
    $target_sub_to_use = (isset($_POST['target_sub']) and $_POST['target_sub'] != 0) ? $_POST['target_sub'] : $subform_id;
    $elementq = q("SELECT fl_key1, fl_key2, fl_common_value, fl_form2_id FROM " . $xoopsDB->prefix("formulize_framework_links") . " WHERE fl_frame_id=" . intval($frid) . " AND fl_form2_id=" . intval($fid) . " AND fl_form1_id=" . intval($target_sub_to_use));
    // element_to_write is used below in writing results of "add x entries" clicks, plus it is used for defaultblanks on first drawing blank entries, so we need to get this outside of the saving routine
    if (count($elementq) > 0) {
        $element_to_write = $elementq[0]['fl_key1'];
        $value_source = $elementq[0]['fl_key2'];
        $value_source_form = $elementq[0]['fl_form2_id'];
    } else {
        $elementq = q("SELECT fl_key2, fl_key1, fl_common_value, fl_form1_id FROM " . $xoopsDB->prefix("formulize_framework_links") . " WHERE fl_frame_id=" . intval($frid) . " AND fl_form1_id=" . intval($fid) . " AND fl_form2_id=" . intval($target_sub_to_use));
        $element_to_write = $elementq[0]['fl_key2'];
        $value_source = $elementq[0]['fl_key1'];
        $value_source_form = $elementq[0]['fl_form1_id'];
    }
    if (0 == strlen($element_to_write)) {
        error_log("Relationship {$frid} for subform {$subform_id} on form {$fid} is invalid.");
        $to_return = array("c1" => "", "c2" => "", "sigle" => "");
        global $xoopsUser;
        if (is_object($xoopsUser) and in_array(XOOPS_GROUP_ADMIN, $xoopsUser->getGroups())) {
            if (0 == $frid) {
                $to_return['single'] = "This subform cannot be shown because no relationship is active.";
            } else {
                $to_return['single'] = "This subform cannot be shown because relationship {$frid} for subform " . "{$subform_id} on form {$fid} is invalid.";
            }
        }
        return $to_return;
    }
    // check for adding of a sub entry, and handle accordingly -- added September 4 2006
    static $subformInstance;
    $subformInstance = !isset($subformInstance) ? 100 : $subformInstance;
    $subformInstance++;
    if ($_POST['target_sub'] and $_POST['target_sub'] == $subform_id and $_POST['target_sub_instance'] == $subformElementId . $subformInstance) {
        // important we only do this on the run through for that particular sub form (hence target_sub == sfid), and also only for the specific instance of this subform on the page too, since not all entries may apply to all subform instances any longer with conditions in effect now
        // need to handle things differently depending on whether it's a common value or a linked selectbox type of link
        // uid links need to result in a "new" value in the displayElement boxes -- odd things will happen if people start adding linked values to entries that aren't theirs!
        if ($element_to_write != 0) {
            if ($elementq[0]['fl_common_value']) {
                // grab the value from the parent element -- assume that it is a textbox of some kind!
                if (isset($_POST['de_' . $value_source_form . '_' . $entry . '_' . $value_source])) {
                    $value_to_write = $_POST['de_' . $value_source_form . '_' . $entry . '_' . $value_source];
                } else {
                    // get this entry and see what the source value is
                    $data_handler = new formulizeDataHandler($value_source_form);
                    $value_to_write = $data_handler->getElementValueInEntry($entry, $value_source);
                }
            } else {
                $value_to_write = $entry;
            }
            $sub_entry_new = "";
            for ($i = 0; $i < $_POST['numsubents']; $i++) {
                // actually goahead and create the requested number of new sub entries...start with the key field, and then do all textboxes with defaults too...
                //$subEntWritten = writeElementValue($_POST['target_sub'], $element_to_write, "new", $value_to_write, "", "", true); // Last param is override that allows direct writing to linked selectboxes if we have prepped the value first!
                if ($overrideOwnerOfNewEntries) {
                    $creation_user_touse = $mainFormOwner;
                } else {
                    $creation_user_touse = "";
                }
                $subEntWritten = writeElementValue($_POST['target_sub'], $element_to_write, "new", $value_to_write, $creation_user_touse, "", true);
                // Last param is override that allows direct writing to linked selectboxes if we have prepped the value first!
                $element_handler = xoops_getmodulehandler('elements', 'formulize');
                if (!isset($elementsForDefaults)) {
                    $criteria = new CriteriaCompo();
                    $criteria->add(new Criteria('ele_type', 'text'), 'OR');
                    $criteria->add(new Criteria('ele_type', 'textarea'), 'OR');
                    $criteria->add(new Criteria('ele_type', 'date'), 'OR');
                    $criteria->add(new Criteria('ele_type', 'radio'), 'OR');
                    $elementsForDefaults = $element_handler->getObjects($criteria, $_POST['target_sub']);
                    // get all the text or textarea elements in the form
                }
                foreach ($elementsForDefaults as $thisDefaultEle) {
                    // need to write in any default values for any text boxes or text areas that are in the subform.  Perhaps other elements could be included too, but that would take too much work right now. (March 9 2009)
                    $defaultTextToWrite = "";
                    $ele_value_for_default = $thisDefaultEle->getVar('ele_value');
                    switch ($thisDefaultEle->getVar('ele_type')) {
                        case "text":
                            $defaultTextToWrite = getTextboxDefault($ele_value_for_default[2], $_POST['target_sub'], $subEntWritten);
                            // position 2 is default value for text boxes
                            break;
                        case "textarea":
                            $defaultTextToWrite = getTextboxDefault($ele_value_for_default[0], $_POST['target_sub'], $subEntWritten);
                            // position 0 is default value for text boxes
                            break;
                        case "date":
                            $defaultTextToWrite = getDateElementDefault($ele_value_for_default[0]);
                            if (false === $defaultTextToWrite) {
                                $defaultTextToWrite = "";
                            } else {
                                $defaultTextToWrite = date("c", $defaultTextToWrite);
                            }
                            break;
                        case "radio":
                            $thisDefaultEleValue = $thisDefaultEle->getVar('ele_value');
                            $defaultTextToWrite = array_search(1, $thisDefaultEleValue);
                    }
                    if ($defaultTextToWrite) {
                        writeElementValue($_POST['target_sub'], $thisDefaultEle->getVar('ele_id'), $subEntWritten, $defaultTextToWrite);
                    }
                }
                $sub_entry_written[] = $subEntWritten;
            }
        } else {
            $sub_entry_new = "new";
            // this happens in uid-link situations?
            $sub_entry_written = "";
        }
        // need to also enforce any equals conditions that are on the subform element, if any, and assign those values to the entries that were just added
        if (is_array($subformConditions)) {
            $filterValues = array();
            foreach ($subformConditions[1] as $i => $thisOp) {
                if ($thisOp == "=" and $subformConditions[3][$i] != "oom" and $subformConditions[2][$i] != "{BLANK}") {
                    $conditionElementObject = $element_handler->get($subformConditions[0][$i]);
                    $filterValues[$subformConditions[0][$i]] = prepareLiteralTextForDB($conditionElementObject, $subformConditions[2][$i]);
                }
            }
            if (count($filterValues) > 0) {
                foreach ($sub_entry_written as $thisSubEntry) {
                    formulize_writeEntry($filterValues, $thisSubEntry);
                }
            }
        }
    }
    // need to do a number of checks here, including looking for single status on subform, and not drawing in add another if there is an entry for a single
    $sub_single_result = getSingle($subform_id, $uid, $groups, $member_handler, $gperm_handler, $mid);
    $sub_single = $sub_single_result['flag'];
    if ($sub_single) {
        unset($sub_entries);
        $sub_entries[$subform_id][0] = $sub_single_result['entry'];
    }
    if (!is_array($sub_entries[$subform_id])) {
        $sub_entries[$subform_id] = array();
    }
    if ($sub_entry_new and !$sub_single and $_POST['target_sub'] == $subform_id) {
        for ($i = 0; $i < $_POST['numsubents']; $i++) {
            array_unshift($sub_entries[$subform_id], $sub_entry_new);
        }
    }
    if (is_array($sub_entry_written) and !$sub_single and $_POST['target_sub'] == $subform_id) {
        foreach ($sub_entry_written as $sew) {
            array_unshift($sub_entries[$subform_id], $sew);
        }
    }
    if (!$customCaption) {
        // get the title of this subform
        // help text removed for F4.0 RC2, this is an experiment
        $subtitle = q("SELECT desc_form FROM " . $xoopsDB->prefix("formulize_id") . " WHERE id_form = {$subform_id}");
        $col_one = "<p id=\"subform-caption-f{$fid}-sf{$subform_id}\" class=\"subform-caption\"><b>" . trans($subtitle[0]['desc_form']) . "</b></p>";
        // <p style=\"font-weight: normal;\">" . _formulize_ADD_HELP;
    } else {
        $col_one = "<p id=\"subform-caption-f{$fid}-sf{$subform_id}\" class=\"subform-caption\"><b>" . trans($customCaption) . "</b></p>";
        // <p style=\"font-weight: normal;\">" . _formulize_ADD_HELP;
    }
    /*if(intval($sub_entries[$subform_id][0]) != 0 OR $sub_entry_new OR is_array($sub_entry_written)) {
    		if(!$nosubforms) { $col_one .= "<br>" . _formulize_ADD_HELP2; }
    		$col_one .= "<br>" . _formulize_ADD_HELP3;
    	} */
    // list the entries, including links to them and delete checkboxes
    // get the headerlist for the subform and convert it into handles
    // note big assumption/restriction that we are only using the first header found (ie: only specify one header for a sub form!)
    // setup the array of elements to draw
    if (is_array($customElements)) {
        $headingDescriptions = array();
        $headerq = q("SELECT ele_caption, ele_colhead, ele_desc, ele_id FROM " . $xoopsDB->prefix("formulize") . " WHERE ele_id IN (" . implode(", ", $customElements) . ") ORDER BY ele_order");
        foreach ($headerq as $thisHeaderResult) {
            $elementsToDraw[] = $thisHeaderResult['ele_id'];
            $headingDescriptions[] = $thisHeaderResult['ele_desc'] ? $thisHeaderResult['ele_desc'] : "";
            if ($captionsForHeadings) {
                $headersToDraw[] = $thisHeaderResult['ele_caption'];
            } else {
                $headersToDraw[] = $thisHeaderResult['ele_colhead'] ? $thisHeaderResult['ele_colhead'] : $thisHeaderResult['ele_caption'];
            }
        }
    } else {
        $subHeaderList = getHeaderList($subform_id);
        $subHeaderList1 = getHeaderList($subform_id, true);
        if (isset($subHeaderList[0])) {
            $headersToDraw[] = trans($subHeaderList[0]);
        }
        if (isset($subHeaderList[1])) {
            $headersToDraw[] = trans($subHeaderList[1]);
        }
        if (isset($subHeaderList[2])) {
            $headersToDraw[] = trans($subHeaderList[2]);
        }
        $elementsToDraw = array_slice($subHeaderList1, 0, 3);
    }
    $need_delete = 0;
    $drawnHeadersOnce = false;
    if ($rowsOrForms == "row" or $rowsOrForms == '') {
        $col_two = "<table id=\"formulize-subform-table-{$subform_id}\" class=\"formulize-subform-table\">";
    } else {
        $col_two = "";
        if (!strstr($_SERVER['PHP_SELF'], "formulize/printview.php")) {
            $col_two .= "<div id=\"subform-{$subformElementId}\" class=\"subform-accordion-container\" subelementid=\"{$subformElementId}\" style=\"display: none;\">";
        }
        $col_two .= "<input type='hidden' name='subform_entry_" . $subformElementId . "_active' id='subform_entry_" . $subformElementId . "_active' value='' />";
        include_once XOOPS_ROOT_PATH . "/modules/formulize/class/data.php";
        $data_handler = new formulizeDataHandler($subform_id);
    }
    $deFrid = $frid ? $frid : "";
    // need to set this up so we can pass it as part of the displayElement function, necessary to establish the framework in case this is a framework and no subform element is being used, just the default draw-in-the-one-to-many behaviour
    // if there's been no form submission, and there's no sub_entries, and there are default blanks to show, then do everything differently -- sept 8 2007
    if (!$_POST['form_submitted'] and count($sub_entries[$subform_id]) == 0 and $defaultblanks > 0 and ($rowsOrForms == "row" or $rowsOrForms == '')) {
        for ($i = 0; $i < $defaultblanks; $i++) {
            // nearly same header drawing code as in the 'else' for drawing regular entries
            if (!$drawnHeadersOnce) {
                $col_two .= "<tr><td>\n";
                $col_two .= "<input type=\"hidden\" name=\"formulize_subformValueSource_{$subform_id}\" value=\"{$value_source}\">\n";
                $col_two .= "<input type=\"hidden\" name=\"formulize_subformValueSourceForm_{$subform_id}\" value=\"{$value_source_form}\">\n";
                $col_two .= "<input type=\"hidden\" name=\"formulize_subformValueSourceEntry_{$subform_id}\" value=\"{$entry}\">\n";
                $col_two .= "<input type=\"hidden\" name=\"formulize_subformElementToWrite_{$subform_id}\" value=\"{$element_to_write}\">\n";
                $col_two .= "<input type=\"hidden\" name=\"formulize_subformSourceType_{$subform_id}\" value=\"" . $elementq[0]['fl_common_value'] . "\">\n";
                $col_two .= "<input type=\"hidden\" name=\"formulize_subformId_{$subform_id}\" value=\"{$subform_id}\">\n";
                // this is probably redundant now that we're tracking sfid in the names of the other elements
                $col_two .= "</td>\n";
                foreach ($headersToDraw as $x => $thishead) {
                    if ($thishead) {
                        $headerHelpLinkPart1 = $headingDescriptions[$i] ? "<a href=\"#\" onclick=\"return false;\" alt=\"" . $headingDescriptions[$x] . "\" title=\"" . $headingDescriptions[$x] . "\">" : "";
                        $headerHelpLinkPart2 = $headerHelpLinkPart1 ? "</a>" : "";
                        $col_two .= "<th><p>{$headerHelpLinkPart1}<b>{$thishead}</b>{$headerHelpLinkPart2}</p></th>\n";
                    }
                }
                $col_two .= "</tr>\n";
                $drawnHeadersOnce = true;
            }
            $col_two .= "<tr>\n<td>";
            $col_two .= "</td>\n";
            include_once XOOPS_ROOT_PATH . "/modules/formulize/include/elementdisplay.php";
            foreach ($elementsToDraw as $thisele) {
                if ($thisele) {
                    ob_start();
                    // critical that we *don't* ask for displayElement to return the element object, since this way the validation logic is passed back through the global space also (ugh).  Otherwise, no validation logic possible for subforms.
                    $renderResult = displayElement($deFrid, $thisele, "subformCreateEntry_" . $i . "_" . $subformElementId);
                    $col_two_temp = ob_get_contents();
                    ob_end_clean();
                    if ($col_two_temp or $renderResult == "rendered") {
                        // only draw in a cell if there actually is an element rendered (some elements might be rendered as nothing (such as derived values)
                        $col_two .= "<td>{$col_two_temp}</td>\n";
                    } else {
                        $col_two .= "<td>******</td>";
                    }
                }
            }
            $col_two .= "</tr>\n";
        }
    } elseif (count($sub_entries[$subform_id]) > 0) {
        // need to figure out the proper order for the sub entries based on the properties set for this form
        // for now, hard code to the word number field to suit the map site only
        // if it's the word subform, then sort the entries differently
        /*if($subform_id == 281) {
        			$sortClause = " fas_281, block_281, word_number ";
        		} 
        		elseif ($subform_id == 283) {
        			$sortClause = " fas_283 ";
        		}
        		else {*/
        $sortClause = " entry_id ";
        //}
        $sformObject = $form_handler->get($subform_id);
        $subEntriesOrderSQL = "SELECT entry_id FROM " . $xoopsDB->prefix("formulize_" . $sformObject->getVar('form_handle')) . " WHERE entry_id IN (" . implode(",", $sub_entries[$subform_id]) . ") ORDER BY {$sortClause}";
        if ($subEntriesOrderRes = $xoopsDB->query($subEntriesOrderSQL)) {
            $sub_entries[$subform_id] = array();
            while ($subEntriesOrderArray = $xoopsDB->fetchArray($subEntriesOrderRes)) {
                $sub_entries[$subform_id][] = $subEntriesOrderArray['entry_id'];
            }
        }
        $currentSubformInstance = $subformInstance;
        foreach ($sub_entries[$subform_id] as $sub_ent) {
            if ($sub_ent != "") {
                if ($rowsOrForms == 'row' or $rowsOrForms == '') {
                    if (!$drawnHeadersOnce) {
                        $col_two .= "<tr><th></th>\n";
                        foreach ($headersToDraw as $i => $thishead) {
                            if ($thishead) {
                                $headerHelpLinkPart1 = $headingDescriptions[$i] ? "<a href=\"#\" onclick=\"return false;\" alt=\"" . $headingDescriptions[$i] . "\" title=\"" . $headingDescriptions[$i] . "\">" : "";
                                $headerHelpLinkPart2 = $headerHelpLinkPart1 ? "</a>" : "";
                                $col_two .= "<th><p>{$headerHelpLinkPart1}<b>{$thishead}</b>{$headerHelpLinkPart2}</p></th>\n";
                            }
                        }
                        $col_two .= "</tr>\n";
                        $drawnHeadersOnce = true;
                    }
                    $col_two .= "<tr>\n<td>";
                    // check to see if we draw a delete box or not
                    if ($sub_ent !== "new" and "hideaddentries" != $hideaddentries and formulizePermHandler::user_can_delete_entry($subform_id, $uid, $sub_ent) and !strstr($_SERVER['PHP_SELF'], "formulize/printview.php")) {
                        // note: if the add/delete entry buttons are hidden, then these delete checkboxes are hidden as well
                        $need_delete = 1;
                        $col_two .= "<input type=checkbox name=delbox{$sub_ent} value={$sub_ent}></input>";
                    }
                    $col_two .= "</td>\n";
                    include_once XOOPS_ROOT_PATH . "/modules/formulize/include/elementdisplay.php";
                    foreach ($elementsToDraw as $thisele) {
                        if ($thisele) {
                            ob_start();
                            // critical that we *don't* ask for displayElement to return the element object, since this way the validation logic is passed back through the global space also (ugh).  Otherwise, no validation logic possible for subforms.
                            $renderResult = displayElement($deFrid, $thisele, $sub_ent);
                            $col_two_temp = ob_get_contents();
                            ob_end_clean();
                            if ($col_two_temp or $renderResult == "rendered") {
                                // only draw in a cell if there actually is an element rendered (some elements might be rendered as nothing (such as derived values)
                                $col_two .= "<td>{$col_two_temp}</td>\n";
                            } else {
                                $col_two .= "<td>******</td>";
                            }
                        }
                    }
                    if (!$nosubforms and $showViewButtons and !strstr($_SERVER['PHP_SELF'], "formulize/printview.php")) {
                        $col_two .= "<td><input type=button name=view" . $sub_ent . " value='" . _formulize_SUBFORM_VIEW . "' onclick=\"javascript:goSub('{$sub_ent}', '{$subform_id}');return false;\"></input></td>\n";
                    }
                    $col_two .= "</tr>\n";
                } else {
                    // display the full form
                    $headerValues = array();
                    foreach ($elementsToDraw as $thisele) {
                        $value = $data_handler->getElementValueInEntry($sub_ent, $thisele);
                        $element_object = _getElementObject($thisele);
                        $value = prepvalues($value, $element_object->getVar("ele_handle"), $sub_ent);
                        if (is_array($value)) {
                            $value = implode(" - ", $value);
                        }
                        // may be an array if the element allows multiple selections (checkboxes, multiselect list boxes, etc)
                        $headerValues[] = $value;
                    }
                    $headerToWrite = implode(" &mdash; ", $headerValues);
                    if (str_replace(" &mdash; ", "", $headerToWrite) == "") {
                        $headerToWrite = _AM_ELE_SUBFORM_NEWENTRY_LABEL;
                    }
                    // check to see if we draw a delete box or not
                    $deleteBox = "";
                    if ($sub_ent !== "new" and formulizePermHandler::user_can_delete_entry($subform_id, $uid, $sub_ent) and !strstr($_SERVER['PHP_SELF'], "formulize/printview.php")) {
                        $need_delete = 1;
                        $deleteBox = "<input type=checkbox name=delbox{$sub_ent} value={$sub_ent}></input>&nbsp;&nbsp;";
                    }
                    if (!strstr($_SERVER['PHP_SELF'], "formulize/printview.php")) {
                        $col_two .= "<div class=\"subform-deletebox\">{$deleteBox}</div><div class=\"subform-entry-container\" id=\"subform-" . $subform_id . "-" . "{$sub_ent}\">\r\n\t<p class=\"subform-header\"><a href=\"#\"><span class=\"accordion-name\">" . $headerToWrite . "</span></a></p>\r\n\t<div class=\"accordion-content content\">";
                    }
                    ob_start();
                    $GLOBALS['formulize_inlineSubformFrid'] = $frid;
                    if ($display_screen = get_display_screen_for_subform($subform_element_object)) {
                        $subScreen_handler = xoops_getmodulehandler('formScreen', 'formulize');
                        $subScreenObject = $subScreen_handler->get($display_screen);
                        $subScreen_handler->render($subScreenObject, $sub_ent, null, true);
                    } else {
                        // SHOULD CHANGE THIS TO USE THE DEFAULT SCREEN FOR THE FORM!!!!!!????
                        $renderResult = displayForm($subform_id, $sub_ent, "", "", "", "", "formElementsOnly");
                    }
                    if (!$nestedSubform) {
                        unset($GLOBALS['formulize_inlineSubformFrid']);
                    }
                    $col_two_temp = ob_get_contents();
                    ob_end_clean();
                    $col_two .= $col_two_temp;
                    if (!strstr($_SERVER['PHP_SELF'], "formulize/printview.php")) {
                        $col_two .= "</div>\n</div>\n";
                    }
                }
            }
        }
        $subformInstance = $currentSubformInstance;
        // instance counter might have changed because the form could include other subforms
    }
    if ($rowsOrForms == 'row' or $rowsOrForms == '') {
        // complete the table if we're drawing rows
        $col_two .= "</table>";
    } else {
        if (!strstr($_SERVER['PHP_SELF'], "formulize/printview.php")) {
            $col_two .= "</div>";
            // close of the subform-accordion-container
        }
        static $jqueryUILoaded = false;
        if (!$jqueryUILoaded) {
            $col_two .= "<script type=\"text/javascript\" src=\"" . XOOPS_URL . "/modules/formulize/libraries/jquery/jquery-ui-1.8.2.custom.min.js\"></script>\n";
            $col_two .= "<link rel=\"stylesheet\" type=\"text/css\" href=\"" . XOOPS_URL . "/modules/formulize/libraries/jquery/css/start/jquery-ui-1.8.2.custom.css\">\n";
            $jqueryUILoaded = true;
        }
        $col_two .= "\n\r\n<script type=\"text/javascript\">\r\n\tjQuery(document).ready(function() {\r\n\t\tjQuery(\"#subform-{$subformElementId}\").accordion({\r\n\t\t\tautoHeight: false, // no fixed height for sections\r\n\t\t\tcollapsible: true, // sections can be collapsed\r\n\t\t\tactive: ";
        if ($_POST['target_sub_instance'] == $subformElementId . $subformInstance and $_POST['target_sub'] == $subform_id) {
            $col_two .= count($sub_entries[$subform_id]) - $_POST['numsubents'];
        } elseif (is_numeric($_POST['subform_entry_' . $subformElementId . '_active'])) {
            $col_two .= $_POST['subform_entry_' . $subformElementId . '_active'];
        } else {
            $col_two .= 'false';
        }
        $col_two .= ",\r\n\t\t\theader: \"> div > p.subform-header\"\r\n\t\t});\r\n\t\tjQuery(\"#subform-{$subformElementId}\").fadeIn();\r\n\t});\r\n</script>";
    }
    // end of if we're closing the subform inferface where entries are supposed to be collapsable forms
    $deleteButton = "";
    if ((count($sub_entries[$subform_id]) > 0 and $sub_entries[$subform_id][0] != "" or $sub_entry_new or is_array($sub_entry_written)) and $need_delete) {
        $deleteButton = "&nbsp;&nbsp;&nbsp;<input type=button name=deletesubs value='" . _formulize_DELETE_CHECKED . "' onclick=\"javascript:sub_del('{$subform_id}');\">";
        static $deletesubsflagIncluded = false;
        if (!$deletesubsflagIncluded) {
            $col_one .= "\n<input type=hidden name=deletesubsflag value=''>\n";
            $deletesubsflagIncluded = true;
        }
    }
    // if the 'add x entries button' should be hidden or visible
    if ("hideaddentries" != $hideaddentries) {
        $allowed_to_add_entries = false;
        if ("subform" == $hideaddentries or 1 == $hideaddentries) {
            // for compatability, accept '1' which is the old value which corresponds to the new use-subform-permissions (saved as "subform")
            // user can add entries if they have permission on the sub form
            $allowed_to_add_entries = $gperm_handler->checkRight("add_own_entry", $subform_id, $groups, $mid);
        } else {
            // user can add entries if they have permission on the main form
            // the user should only be able to add subform entries if they can *edit* the main form entry, since adding a subform entry
            //  is like editing the main form entry. otherwise they could add subform entries on main form entries owned by other users
            $allowed_to_add_entries = formulizePermHandler::user_can_edit_entry($fid, $uid, $entry);
        }
        if ($allowed_to_add_entries and !strstr($_SERVER['PHP_SELF'], "formulize/printview.php")) {
            if (count($sub_entries[$subform_id]) == 1 and $sub_entries[$subform_id][0] === "" and $sub_single) {
                $col_two .= "<p><input type=button name=addsub value='" . _formulize_ADD_ONE . "' onclick=\"javascript:add_sub('{$subform_id}', 1, " . $subformElementId . $subformInstance . ");\"></p>";
            } elseif (!$sub_single) {
                $use_simple_add_one_button = isset($subform_element_object->ele_value["simple_add_one_button"]) ? 1 == $subform_element_object->ele_value["simple_add_one_button"] : false;
                $col_two .= "<p><input type=button name=addsub value='" . ($use_simple_add_one_button ? trans($subform_element_object->ele_value['simple_add_one_button_text']) : _formulize_ADD) . "' onclick=\"javascript:add_sub('{$subform_id}', window.document.formulize.addsubentries{$subform_id}{$subformElementId}{$subformInstance}.value, " . $subformElementId . $subformInstance . ");\">";
                if ($use_simple_add_one_button) {
                    $col_two .= "<input type=\"hidden\" name=addsubentries{$subform_id}{$subformElementId}{$subformInstance} id=addsubentries{$subform_id}{$subformElementId}{$subformInstance} value=\"1\">";
                } else {
                    $col_two .= "<input type=text name=addsubentries{$subform_id}{$subformElementId}{$subformInstance} id=addsubentries{$subform_id}{$subformElementId}{$subformInstance} value=1 size=2 maxlength=2>";
                    $col_two .= $addEntriesText;
                }
                $col_two .= $deleteButton . "</p>";
            }
        }
    }
    $to_return['c1'] = $col_one;
    $to_return['c2'] = $col_two;
    $to_return['single'] = $col_one . $col_two;
    if (is_object($subform_element_object)) {
        global $xoopsUser;
        $show_element_edit_link = (is_object($xoopsUser) and in_array(XOOPS_GROUP_ADMIN, $xoopsUser->getGroups()));
        $edit_link = "";
        if ($show_element_edit_link) {
            $edit_link = "<a class=\"formulize-element-edit-link\" tabindex=\"-1\" href=\"" . XOOPS_URL . "/modules/formulize/admin/ui.php?page=element&aid=0&ele_id=" . $subform_element_object->getVar("ele_id") . "\" target=\"_blank\">edit element</a>";
        }
        $to_return['single'] = "<div class=\"formulize-subform-" . $subform_element_object->getVar("ele_handle") . "\">{$edit_link} {$col_one} {$col_two}</div>";
    }
    return $to_return;
}
Exemple #4
0
function existsInCache($type, $key)
{
    $q = getSingle("SELECT cache.id FROM cache WHERE cache.type = '{$type}' AND cache.key = '{$key}'");
    if ($q == null) {
        return false;
    } else {
        return true;
    }
}
Exemple #5
0
confirm_logged_in();
$tbl = "tbl_homeslides";
$tblNews = "tbl_news";
$tblEvents = "tbl_events";
$col = "homeslides_id";
$colNews = "news_id";
$colEvents = "events_id";
if ($_GET['id']) {
    $id = $_GET['id'];
    $_SESSION['savedCurrentId'] = $id;
}
if (!empty($_SESSION['message'])) {
    $message = $_SESSION['message'];
}
$savedId = $_SESSION['savedCurrentId'];
$result = getSingle($tbl, $col, $savedId);
$resultNews = getAll($tblNews);
$resultEvents = getAll($tblEvents);
$getResult = mysqli_fetch_array($result);
$savedPage = explode("_", $getResult['homeslides_link']);
$page = $savedPage[0];
$savedDetailsPost = explode("=", $getResult['homeslides_link']);
if ($page == 'news' || $page == 'events') {
    if ($savedDetailsPost[1]) {
        $returnTitle = getTitle($savedPage, $savedDetailsPost);
        $getTitleResult = mysqli_fetch_array($returnTitle);
    }
}
$errors = array();
if (isset($_POST['submit'])) {
    $text = trim($_POST['homeslides_text']);
Exemple #6
0
<?php

require_once 'admin/includes/init.php';
if (isset($_GET['id'])) {
    $tbl = "tbl_news";
    $col = "news_id";
    $id = $_GET['id'];
    $getSingle = getSingle($tbl, $col, $id);
}
?>
<!doctype html>
<html class="no-js" lang="en">
<head>
  <meta charset="utf-8" />
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Eating Disorders Foundation of Canada | Events</title>
  <link rel="stylesheet" href="css/normalize.css"/>
  <link rel="stylesheet" href="css/foundation.css" />
  <link rel="stylesheet" href="css/app.css" />
  <link href='https://fonts.googleapis.com/css?family=Montserrat:400,700' rel='stylesheet' type='text/css'>
  <link rel="stylesheet" href="css/main.css"/>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/1.18.2/TweenMax.min.js"></script>
  <link rel="icon" href="images/icon.png" type="image/x-icon"/>
</head>
<body>

  <div id="cover"></div>

  <div class="container-navigation small-12 medium-12 large-3 columns">
    <div class="logo">
                            case "http://vancouver.24hrs.ca/rss.xml":
                                $publisher = "<a href='http://vancouver.24hrs.ca/'>24 Hours Vancouver</a>";
                                $linkContent = "<a href='{$link}' target='_blank'>Read full story at 24 Hours Vancouver</a>";
                                break;
                            default:
                                $publisher = "<a href=''>Unknown</a>";
                                $linkContent = "<a href='{$link}' target='_blank'>Read full story here</a>";
                                break;
                        }
                        file_put_contents($publisherFile, $publisher);
                        file_put_contents($linkFile, $linkContent);
                        //add a count to the $articlesAdded var
                        $articlesAdded++;
                    } else {
                        echo "file put contents FAILED for {$image}<br/>";
                    }
                } else {
                    echo " file get contents FAILED for {$image} <br/>";
                }
            } else {
                echo "No image was found <br/>";
            }
        }
        $i++;
    }
}
foreach ($custom1 as $single) {
    echo "<a href='{$single}'>{$single}</a><br/>";
    getSingle($single, 1);
    echo "<br/>";
}
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];
    }
}
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 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.");
}