Ejemplo n.º 1
0
/**
 * Checks for duplicate column names and fixes them
 * Returns true if a correction has been made and false if not
 *
 * @param $surveyid - The Survey Identifier
 * @return bool
 */
function surveyFixDuplicateColumns($surveyid)
{
    list($duplicates, $fieldmap) = surveyCheckUniqueColumns($surveyid);
    if (!empty($duplicates)) {
        foreach ($duplicates as $dup) {
            $badquestion = arraySearchByKey($dup, $fieldmap, "fieldname", 1);
            surveyFixQuestionNumbering($badquestion['qid']);
        }
        return true;
    }
    return false;
}
Ejemplo n.º 2
0
 public function vvexport()
 {
     $iSurveyID = sanitize_int(Yii::app()->request->getParam('surveyid'));
     $subaction = Yii::app()->request->getParam('subaction');
     //Exports all responses to a survey in special "Verified Voting" format.
     $clang = $this->getController()->lang;
     if (!hasSurveyPermission($iSurveyID, 'responses', 'export')) {
         return;
     }
     if ($subaction != "export") {
         $selecthide = "";
         $selectshow = "";
         $selectinc = "";
         if (incompleteAnsFilterState() == "incomplete") {
             $selectinc = "selected='selected'";
         } elseif (incompleteAnsFilterState() == "complete") {
             $selecthide = "selected='selected'";
         } else {
             $selectshow = "selected='selected'";
         }
         $data['selectinc'] = $selectinc;
         $data['selecthide'] = $selecthide;
         $data['selectshow'] = $selectshow;
         $data['surveyid'] = $iSurveyID;
         $data['display']['menu_bars']['browse'] = $clang->gT("Export VV file");
         $this->_renderWrappedTemplate('export', 'vv_view', $data);
     } elseif (isset($iSurveyID) && $iSurveyID) {
         //Export is happening
         $extension = sanitize_paranoid_string(returnGlobal('extension'));
         $fn = "vvexport_{$iSurveyID}." . $extension;
         $this->_addHeaders($fn, "text/comma-separated-values", 0, "cache");
         $s = "\t";
         $fieldmap = createFieldMap($iSurveyID, 'full', false, false, getBaseLanguageFromSurveyID($iSurveyID));
         $surveytable = "{{survey_{$iSurveyID}}}";
         Survey::model()->findByPk($iSurveyID)->language;
         $fieldnames = Yii::app()->db->schema->getTable($surveytable)->getColumnNames();
         //Create the human friendly first line
         $firstline = "";
         $secondline = "";
         foreach ($fieldnames as $field) {
             $fielddata = arraySearchByKey($field, $fieldmap, "fieldname", 1);
             if (count($fielddata) < 1) {
                 $firstline .= $field;
             } else {
                 $firstline .= preg_replace('/\\s+/', ' ', strip_tags($fielddata['question']));
             }
             $firstline .= $s;
             $secondline .= $field . $s;
         }
         $vvoutput = $firstline . "\n";
         $vvoutput .= $secondline . "\n";
         $query = "SELECT * FROM " . Yii::app()->db->quoteTableName($surveytable);
         if (incompleteAnsFilterState() == "incomplete") {
             $query .= " WHERE submitdate IS NULL ";
         } elseif (incompleteAnsFilterState() == "complete") {
             $query .= " WHERE submitdate >= '01/01/1980' ";
         }
         $result = Yii::app()->db->createCommand($query)->query();
         foreach ($result->readAll() as $row) {
             foreach ($fieldnames as $field) {
                 if (is_null($row[$field])) {
                     $value = '{question_not_shown}';
                 } else {
                     $value = trim($row[$field]);
                     // sunscreen for the value. necessary for the beach.
                     // careful about the order of these arrays:
                     // lbrace has to be substituted *first*
                     $value = str_replace(array("{", "\n", "\r", "\t"), array("{lbrace}", "{newline}", "{cr}", "{tab}"), $value);
                 }
                 // one last tweak: excel likes to quote values when it
                 // exports as tab-delimited (esp if value contains a comma,
                 // oddly enough).  So we're going to encode a leading quote,
                 // if it occurs, so that we can tell the difference between
                 // strings that "really are" quoted, and those that excel quotes
                 // for us.
                 $value = preg_replace('/^"/', '{quote}', $value);
                 // yay!  that nasty soab won't hurt us now!
                 if ($field == "submitdate" && !$value) {
                     $value = "NULL";
                 }
                 $sun[] = $value;
             }
             $beach = implode($s, $sun);
             $vvoutput .= $beach;
             unset($sun);
             $vvoutput .= "\n";
         }
         echo $vvoutput;
         exit;
     }
 }
Ejemplo n.º 3
0
/**
* getArrayFilterExcludesCascadesForGroup() queries the database and produces a list of array_filter_exclude questions and targets with in the same group
* @return returns a keyed nested array, keyed by the qid of the question, containing cascade information
*/
function getArrayFilterExcludesCascadesForGroup($surveyid, $gid = "", $output = "qid")
{
    $surveyid = sanitize_int($surveyid);
    $gid = sanitize_int($gid);
    $cascaded = array();
    $sources = array();
    $qidtotitle = array();
    $fieldmap = createFieldMap($surveyid, 'full', false, false, getBaseLanguageFromSurveyID($surveyid));
    if ($gid != "") {
        $qrows = arraySearchByKey($gid, $fieldmap, 'gid');
    } else {
        $qrows = $fieldmap;
    }
    $grows = array();
    //Create an empty array in case query not return any rows
    // Store each result as an array with in the $grows array
    foreach ($qrows as $qrow) {
        if (isset($qrow['gid']) && !empty($qrow['gid'])) {
            $grows[$qrow['qid']] = array('qid' => $qrow['qid'], 'type' => $qrow['type'], 'mandatory' => $qrow['mandatory'], 'title' => $qrow['title'], 'gid' => $qrow['gid']);
        }
    }
    $attrmach = array();
    // Stores Matches of filters that have their values as questions within current group
    foreach ($grows as $qrow) {
        $qidtotitle[$qrow['qid']] = $qrow['title'];
        $qresult = getQuestionAttributeValues($qrow['qid']);
        if (isset($qresult['array_filter_exclude'])) {
            $val = $qresult['array_filter_exclude'];
            // Get the Value of the Attribute ( should be a previous question's title in same group )
            foreach ($grows as $avalue) {
                if ($avalue['title'] == $val) {
                    /* This question ($avalue) is the question that provides the source information we use
                     * to determine which answers show up in the question we're looking at, which is $qrow['qid']
                     * So, in other words, we're currently working on question $qrow['qid'], trying to find out more
                     * information about question $avalue['qid'], because that's the source */
                    $sources[$qrow['qid']] = $avalue['qid'];
                    /* This question ($qrow['qid']) relies on answers in $avalue['qid'] */
                    if (isset($cascades)) {
                        unset($cascades);
                    }
                    $cascades = array();
                    /* Create an empty array */
                    /* At this stage, we know for sure that this question relies on one other question for the filter */
                    /* But this function wants to send back information about questions that rely on multiple other questions for the filter */
                    /* So we don't want to do anything yet */
                    /* What we need to do now, is check whether the question this one relies on, also relies on another */
                    /* The question we are now checking is $avalue['qid'] */
                    $keepgoing = 1;
                    $questiontocheck = $avalue['qid'];
                    /* If there is a key in the $sources array that is equal to $avalue['qid'] then we want to add that
                     * to the $cascades array */
                    while ($keepgoing > 0) {
                        if (!empty($sources[$questiontocheck])) {
                            $cascades[] = $sources[$questiontocheck];
                            /* Now we need to move down the chain */
                            /* We want to check the $sources[$questiontocheck] question */
                            $questiontocheck = $sources[$questiontocheck];
                        } else {
                            /* Since it was empty, there must not be any more questions down the cascade */
                            $keepgoing = 0;
                        }
                    }
                    /* Now add all that info */
                    if (count($cascades) > 0) {
                        $cascaded[$qrow['qid']] = $cascades;
                    }
                }
            }
        }
    }
    $cascade2 = array();
    if ($output == "title") {
        foreach ($cascaded as $key => $cascade) {
            foreach ($cascade as $item) {
                $cascade2[$key][] = $qidtotitle[$item];
            }
        }
        $cascaded = $cascade2;
    }
    return $cascaded;
}
Ejemplo n.º 4
0
/**
* checks questions in a survey for consistency
* @param <type> $postsid
* @param <type> $iSurveyID
* @return array $faildcheck
*/
function checkQuestions($postsid, $iSurveyID, $qtypes)
{
    $clang = Yii::app()->lang;
    //CHECK TO MAKE SURE ALL QUESTION TYPES THAT REQUIRE ANSWERS HAVE ACTUALLY GOT ANSWERS
    //THESE QUESTION TYPES ARE:
    //	# "L" -> LIST
    //  # "O" -> LIST WITH COMMENT
    //  # "M" -> Multiple choice
    //	# "P" -> Multiple choice with comments
    //	# "A", "B", "C", "E", "F", "H", "^" -> Various Array Types
    //  # "R" -> RANKING
    //  # "U" -> FILE CSV MORE
    //  # "I" -> LANGUAGE SWITCH
    //  # ":" -> Array Multi Flexi Numbers
    //  # ";" -> Array Multi Flexi Text
    //  # "1" -> MULTI SCALE
    $chkquery = "SELECT qid, question, gid, type FROM {{questions}} WHERE sid={$iSurveyID} and parent_qid=0";
    $chkresult = Yii::app()->db->createCommand($chkquery)->query()->readAll();
    foreach ($chkresult as $chkrow) {
        if ($qtypes[$chkrow['type']]['subquestions'] > 0) {
            $chaquery = "SELECT * FROM {{questions}} WHERE parent_qid = {$chkrow['qid']} ORDER BY question_order";
            $charesult = Yii::app()->db->createCommand($chaquery)->query()->readAll();
            $chacount = count($charesult);
            if ($chacount == 0) {
                $failedcheck[] = array($chkrow['qid'], $chkrow['question'], ": " . $clang->gT("This question has no subquestions."), $chkrow['gid']);
            }
        }
        if ($qtypes[$chkrow['type']]['answerscales'] > 0) {
            $chaquery = "SELECT * FROM {{answers}} WHERE qid = {$chkrow['qid']} ORDER BY sortorder, answer";
            $charesult = Yii::app()->db->createCommand($chaquery)->query()->readAll();
            $chacount = count($charesult);
            if ($chacount == 0) {
                $failedcheck[] = array($chkrow['qid'], $chkrow['question'], ": " . $clang->gT("This question has no answers."), $chkrow['gid']);
            }
        }
    }
    //NOW CHECK THAT ALL QUESTIONS HAVE A 'QUESTION TYPE' FIELD SET
    $chkquery = "SELECT qid, question, gid FROM {{questions}} WHERE sid={$iSurveyID} AND type = ''";
    $chkresult = Yii::app()->db->createCommand($chkquery)->query()->readAll();
    foreach ($chkresult as $chkrow) {
        $failedcheck[] = array($chkrow['qid'], $chkrow['question'], ": " . $clang->gT("This question does not have a question 'type' set."), $chkrow['gid']);
    }
    //Check that certain array question types have answers set
    $chkquery = "SELECT q.qid, question, gid FROM {{questions}} as q WHERE (select count(*) from {{answers}} as a where a.qid=q.qid and scale_id=0)=0 and sid={$iSurveyID} AND type IN ('F', 'H', 'W', 'Z', '1') and q.parent_qid=0";
    $chkresult = Yii::app()->db->createCommand($chkquery)->query()->readAll();
    foreach ($chkresult as $chkrow) {
        $failedcheck[] = array($chkrow['qid'], $chkrow['question'], ": " . $clang->gT("This question requires answers, but none are set."), $chkrow['gid']);
    }
    // while
    //CHECK THAT DUAL Array has answers set
    $chkquery = "SELECT q.qid, question, gid FROM {{questions}} as q WHERE (select count(*) from {{answers}} as a where a.qid=q.qid and scale_id=1)=0 and sid={$iSurveyID} AND type='1' and q.parent_qid=0";
    $chkresult = Yii::app()->db->createCommand($chkquery)->query()->readAll();
    foreach ($chkresult as $chkrow) {
        $failedcheck[] = array($chkrow['qid'], $chkrow['question'], ": " . $clang->gT("This question requires a second answer set but none is set."), $chkrow['gid']);
    }
    // while
    //TO AVOID NATURAL SORT ORDER ISSUES, FIRST GET ALL QUESTIONS IN NATURAL SORT ORDER, AND FIND OUT WHICH NUMBER IN THAT ORDER THIS QUESTION IS
    $qorderquery = "SELECT * FROM {{questions}} WHERE sid={$iSurveyID} AND type not in ('S', 'D', 'T', 'Q')";
    $qorderresult = Yii::app()->db->createCommand($qorderquery)->query()->readAll();
    $qrows = array();
    //Create an empty array in case FetchRow does not return any rows
    foreach ($qorderresult as $qrow) {
        $qrows[] = $qrow;
    }
    // Get table output into array
    usort($qrows, 'groupOrderThenQuestionOrder');
    // Perform a case insensitive natural sort on group name then question title of a multidimensional array
    $c = 0;
    foreach ($qrows as $qr) {
        $qidorder[] = array($c, $qrow['qid']);
        $c++;
    }
    $qordercount = "";
    //1: Get each condition's question id
    $conquery = "SELECT {{conditions}}.qid, cqid, {{questions}}.question, " . "{{questions}}.gid " . "FROM {{conditions}}, {{questions}}, {{groups}} " . "WHERE {{conditions}}.qid={{questions}}.qid " . "AND {{questions}}.gid={{groups}}.gid ORDER BY {{conditions}}.qid";
    $conresult = Yii::app()->db->createCommand($conquery)->query()->readAll();
    //2: Check each conditions cqid that it occurs later than the cqid
    foreach ($conresult as $conrow) {
        $cqidfound = 0;
        $qidfound = 0;
        $b = 0;
        while ($b < $qordercount) {
            if ($conrow['cqid'] == $qidorder[$b][1]) {
                $cqidfound = 1;
                $b = $qordercount;
            }
            if ($conrow['qid'] == $qidorder[$b][1]) {
                $qidfound = 1;
                $b = $qordercount;
            }
            if ($qidfound == 1) {
                $failedcheck[] = array($conrow['qid'], $conrow['question'], ": " . $clang->gT("This question has a condition set, however the condition is based on a question that appears after it."), $conrow['gid']);
            }
            $b++;
        }
    }
    //CHECK THAT ALL THE CREATED FIELDS WILL BE UNIQUE
    $fieldmap = createFieldMap($iSurveyID, 'full', false, false, getBaseLanguageFromSurveyID($iSurveyID));
    if (isset($fieldmap)) {
        foreach ($fieldmap as $fielddata) {
            $fieldlist[] = $fielddata['fieldname'];
        }
        $fieldlist = array_reverse($fieldlist);
        //let's always change the later duplicate, not the earlier one
    }
    $checkKeysUniqueComparison = create_function('$value', 'if ($value > 1) return true;');
    @($duplicates = array_keys(array_filter(array_count_values($fieldlist), $checkKeysUniqueComparison)));
    if (isset($duplicates)) {
        foreach ($duplicates as $dup) {
            $badquestion = arraySearchByKey($dup, $fieldmap, "fieldname", 1);
            $fix = "[<a href='{$scriptname}?action=activate&amp;sid={$iSurveyID}&amp;fixnumbering=" . $badquestion['qid'] . "'>Click Here to Fix</a>]";
            $failedcheck[] = array($badquestion['qid'], $badquestion['question'], ": Bad duplicate fieldname {$fix}", $badquestion['gid']);
        }
    }
    if (isset($failedcheck)) {
        return $failedcheck;
    } else {
        return false;
    }
}
Ejemplo n.º 5
0
 //Export is happening
 $extension = sanitize_paranoid_string(returnglobal('extension'));
 header("Content-Disposition: attachment; filename=vvexport_{$surveyid}." . $extension);
 header("Content-type: text/comma-separated-values; charset=UTF-8");
 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
 header("Pragma: cache");
 $s = "\t";
 $fieldmap = createFieldMap($surveyid, "full");
 $surveytable = "{$dbprefix}survey_{$surveyid}";
 GetBaseLanguageFromSurveyID($surveyid);
 $fieldnames = array_values($connect->MetaColumnNames($surveytable, true));
 //Create the human friendly first line
 $firstline = "";
 $secondline = "";
 foreach ($fieldnames as $field) {
     $fielddata = arraySearchByKey($field, $fieldmap, "fieldname", 1);
     //$vvoutput .= "<pre>";print_r($fielddata);$vvoutput .= "</pre>";
     if (count($fielddata) < 1) {
         $firstline .= $field;
     } else {
         $firstline .= preg_replace('/\\s+/', ' ', strip_tags($fielddata['question']));
     }
     $firstline .= $s;
     $secondline .= $field . $s;
 }
 $vvoutput = $firstline . "\n";
 $vvoutput .= $secondline . "\n";
 $query = "SELECT * FROM {$surveytable}";
 if (incompleteAnsFilterstate() == "inc") {
     $query .= " WHERE submitdate IS NULL ";
 } elseif (incompleteAnsFilterstate() == "filter") {
Ejemplo n.º 6
0
 public function vvexport()
 {
     $iSurveyId = sanitize_int(Yii::app()->request->getParam('surveyid'));
     $subaction = Yii::app()->request->getParam('subaction');
     //Exports all responses to a survey in special "Verified Voting" format.
     if (!Permission::model()->hasSurveyPermission($iSurveyId, 'responses', 'export')) {
         Yii::app()->session['flashmessage'] = gT("You do not have sufficient rights to access this page.");
         $this->getController()->redirect($this->getController()->createUrl("/admin/survey/sa/view/surveyid/{$iSurveyId}"));
     }
     if ($subaction != "export") {
         $aData['selectincansstate'] = incompleteAnsFilterState();
         $aData['surveyid'] = $iSurveyId;
         $aData['display']['menu_bars']['browse'] = gT("Export VV file");
         $fieldmap = createFieldMap($iSurveyId, 'full', false, false, getBaseLanguageFromSurveyID($iSurveyId));
         Survey::model()->findByPk($iSurveyId)->language;
         $surveytable = "{{survey_{$iSurveyId}}}";
         // Control if fieldcode are unique
         $fieldnames = Yii::app()->db->schema->getTable($surveytable)->getColumnNames();
         foreach ($fieldnames as $field) {
             $fielddata = arraySearchByKey($field, $fieldmap, "fieldname", 1);
             $fieldcode[] = viewHelper::getFieldCode($fielddata, array("LEMcompat" => true));
         }
         $aData['uniquefieldcode'] = count(array_unique($fieldcode)) == count($fieldcode);
         // Did we need more control ?
         $aData['vvversionseleted'] = $aData['uniquefieldcode'] ? 2 : 1;
         $this->_renderWrappedTemplate('export', 'vv_view', $aData);
     } elseif (isset($iSurveyId) && $iSurveyId) {
         //Export is happening
         $extension = sanitize_paranoid_string(returnGlobal('extension'));
         $vvVersion = (int) Yii::app()->request->getPost('vvversion');
         $vvVersion = in_array($vvVersion, array(1, 2)) ? $vvVersion : 2;
         // Only 2 version actually, default to 2
         $fn = "vvexport_{$iSurveyId}." . $extension;
         $this->_addHeaders($fn, "text/comma-separated-values", 0, "cache");
         $s = "\t";
         $fieldmap = createFieldMap($iSurveyId, 'full', false, false, getBaseLanguageFromSurveyID($iSurveyId));
         $surveytable = "{{survey_{$iSurveyId}}}";
         Survey::model()->findByPk($iSurveyId)->language;
         $fieldnames = Yii::app()->db->schema->getTable($surveytable)->getColumnNames();
         //Create the human friendly first line
         $firstline = "";
         $secondline = "";
         foreach ($fieldnames as $field) {
             $fielddata = arraySearchByKey($field, $fieldmap, "fieldname", 1);
             if (count($fielddata) < 1) {
                 $firstline .= $field;
             } else {
                 $firstline .= preg_replace('/\\s+/', ' ', strip_tags($fielddata['question']));
             }
             $firstline .= $s;
             if ($vvVersion == 2) {
                 $fieldcode = viewHelper::getFieldCode($fielddata, array("LEMcompat" => true));
                 $fieldcode = $fieldcode ? $fieldcode : $field;
                 // $fieldcode is empty for token if there are no token table
             } else {
                 $fieldcode = $field;
             }
             $secondline .= $fieldcode . $s;
         }
         $vvoutput = $firstline . "\n";
         $vvoutput .= $secondline . "\n";
         $query = "SELECT * FROM " . Yii::app()->db->quoteTableName($surveytable);
         if (incompleteAnsFilterState() == "incomplete") {
             $query .= " WHERE submitdate IS NULL ";
         } elseif (incompleteAnsFilterState() == "complete") {
             $query .= " WHERE submitdate >= '01/01/1980' ";
         }
         $result = Yii::app()->db->createCommand($query)->query();
         echo $vvoutput;
         foreach ($result as $row) {
             foreach ($fieldnames as $field) {
                 if (is_null($row[$field])) {
                     $value = '{question_not_shown}';
                 } else {
                     $value = trim($row[$field]);
                     // sunscreen for the value. necessary for the beach.
                     // careful about the order of these arrays:
                     // lbrace has to be substituted *first*
                     $value = str_replace(array("{", "\n", "\r", "\t"), array("{lbrace}", "{newline}", "{cr}", "{tab}"), $value);
                 }
                 // one last tweak: excel likes to quote values when it
                 // exports as tab-delimited (esp if value contains a comma,
                 // oddly enough).  So we're going to encode a leading quote,
                 // if it occurs, so that we can tell the difference between
                 // strings that "really are" quoted, and those that excel quotes
                 // for us.
                 $value = preg_replace('/^"/', '{quote}', $value);
                 // yay!  that nasty soab won't hurt us now!
                 if ($field == "submitdate" && !$value) {
                     $value = "NULL";
                 }
                 $sun[] = $value;
             }
             /* it is important here to stream output data, line by line
              * in order to avoid huge memory consumption when exporting large
              * quantities of answers */
             echo implode($s, $sun) . "\n";
             unset($sun);
         }
         exit;
     }
 }
 //Get the questions for this group
 $baselang = GetBaseLanguageFromSurveyID($surveyid);
 $oqquery = "SELECT * FROM " . db_table_name('questions') . " WHERE sid={$surveyid} AND gid={$gid} AND language='" . $baselang . "' and parent_qid=0 order by question_order";
 $oqresult = db_execute_assoc($oqquery);
 $orderquestions = "<div class='header ui-widget-header'>" . $clang->gT("Change Question Order") . "</div>";
 $questioncount = $oqresult->RecordCount();
 $oqarray = $oqresult->GetArray();
 $minioqarray = $oqarray;
 // Get the condition dependecy array for all questions in this array and group
 $questdepsarray = GetQuestDepsForConditions($surveyid, $gid);
 if (!is_null($questdepsarray)) {
     $orderquestions .= "<br/><div class='movableNode' style='margin:0 auto;'><strong><font color='orange'>" . $clang->gT("Warning") . ":</font> " . $clang->gT("Current group is using conditional questions") . "</strong><br /><br /><i>" . $clang->gT("Re-ordering questions in this group is restricted to ensure that questions on which conditions are based aren't reordered after questions having the conditions set") . "</i></strong><br /><br/>" . $clang->gT("See the conditions marked on the following questions") . ":<ul>\n";
     foreach ($questdepsarray as $depqid => $depquestrow) {
         foreach ($depquestrow as $targqid => $targcid) {
             $listcid = implode("-", $targcid);
             $question = arraySearchByKey($depqid, $oqarray, "qid", 1);
             $orderquestions .= "<li><a href='#' onclick=\"window.open('admin.php?sid=" . $surveyid . "&amp;gid=" . $gid . "&amp;qid=" . $depqid . "&amp;action=conditions&amp;markcid=" . $listcid . "','_top')\">" . $question['title'] . ": " . FlattenText($question['question']) . " [QID: " . $depqid . "] </a> ";
         }
         $orderquestions .= "</li>\n";
     }
     $orderquestions .= "</ul></div>";
 }
 $orderquestions .= "<form method='post' action=''><ul class='movableList'>";
 for ($i = 0; $i < $questioncount; $i++) {
     $downdisabled = "";
     $updisabled = "";
     //Check if question is relied on as a condition dependency by the next question, and if so, don't allow moving down
     if (!is_null($questdepsarray) && $i < $questioncount - 1 && array_key_exists($oqarray[$i + 1]['qid'], $questdepsarray) && array_key_exists($oqarray[$i]['qid'], $questdepsarray[$oqarray[$i + 1]['qid']])) {
         $downdisabled = "disabled=\"true\" class=\"disabledUpDnBtn\"";
     }
     //Check if question has a condition dependency on the preceding question, and if so, don't allow moving up
Ejemplo n.º 8
0
function returnQuestionResults($surveyid, $questionfields, $sql = null)
{
    global $connect;
    //Returns uninterpreted raw results from survey table for question(s)
    //$table = survcey table name (ie: "survey_1")
    //$questionfields should contain an array of the question fields that are being returned
    //$sql is any additional "filtering" sql code
    $details = array();
    $output = array();
    foreach ($questionfields as $questionfield) {
        $detailsarray = arraySearchByKey($questionfield, createFieldMap($surveyid), "fieldname");
        foreach ($detailsarray as $dt) {
            $details[] = $dt;
        }
    }
    $table = "survey_" . $surveyid;
    if (count($questionfields) > 1) {
        $selects = "`" . implode("`, `", $questionfields) . "`";
    } else {
        $selects = "`" . $questionfields[0] . "`";
    }
    $query = "SELECT {$selects}\n\t\t\t  FROM {$table}";
    if (!empty($sql)) {
        $query .= "\nWHERE {$sql}";
    }
    $result = db_execute_assoc($query) or safe_diee("error getting results in returnQuestionResults<br />{$query}<br />" . $connect->ErrorMsg());
    while ($row = $result->FetchRow()) {
        $output[] = $row;
    }
    // while
    return array($details, $output);
}
Ejemplo n.º 9
0
 /**
  * function to activate surveys based on new activate.php 5771 2008-10-13 02:28:40Z jcleeland $
  *
  * @param unknown_type $surveyid
  * @return boolean
  */
 function activateSurvey($surveyid)
 {
     global $connect;
     global $dbprefix;
     $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
     include "lsrc.config.php";
     $_GET['sid'] = $surveyid;
     $_POST['sid'] = $surveyid;
     //$postsid = $surveyid;
     //$activateoutput='';
     $this->debugLsrc("wir sind in " . __FILE__ . " - " . __FUNCTION__ . " Line " . __LINE__ . ", OK ");
     if (!isset($_POST['ok']) || !$_POST['ok']) {
         $this->debugLsrc("wir sind in " . __FUNCTION__ . " Line " . __LINE__ . ", OK ");
         if (isset($_GET['fixnumbering']) && $_GET['fixnumbering']) {
             $this->debugLsrc("wir sind in " . __FUNCTION__ . " Line " . __LINE__ . ", OK ");
             //Fix a question id - requires renumbering a question
             $oldqid = $_GET['fixnumbering'];
             $query = "SELECT qid FROM {$dbprefix}questions ORDER BY qid DESC";
             $result = db_select_limit_assoc($query, 1) or $this->debugLsrc($query . "" . $connect->ErrorMsg());
             while ($row = $result->FetchRow()) {
                 $lastqid = $row['qid'];
             }
             $newqid = $lastqid + 1;
             $query = "UPDATE {$dbprefix}questions SET qid={$newqid} WHERE qid={$oldqid}";
             $result = $connect->Execute($query) or $this->debugLsrc($query . "" . $connect->ErrorMsg());
             //Update conditions.. firstly conditions FOR this question
             $query = "UPDATE {$dbprefix}conditions SET qid={$newqid} WHERE qid={$oldqid}";
             $result = $connect->Execute($query) or $this->debugLsrc($query . "" . $connect->ErrorMsg());
             //Now conditions based upon this question
             $query = "SELECT cqid, cfieldname FROM {$dbprefix}conditions WHERE cqid={$oldqid}";
             $result = db_execute_assoc($query) or $this->debugLsrc($query . "" . $connect->ErrorMsg());
             $this->debugLsrc("wir sind in " . __FUNCTION__ . " Line " . __LINE__ . ", OK ");
             while ($row = $result->FetchRow()) {
                 $switcher[] = array("cqid" => $row['cqid'], "cfieldname" => $row['cfieldname']);
             }
             if (isset($switcher)) {
                 foreach ($switcher as $switch) {
                     $query = "UPDATE {$dbprefix}conditions\r\n\t\t\t\t\t\t\t\t  SET cqid={$newqid},\r\n\t\t\t\t\t\t\t\t  cfieldname='" . str_replace("X" . $oldqid, "X" . $newqid, $switch['cfieldname']) . "'\r\n\t\t\t\t\t\t\t\t  WHERE cqid={$oldqid}";
                     $result = $connect->Execute($query) or $this->debugLsrc($query . "" . $connect->ErrorMsg());
                 }
             }
             $this->debugLsrc("wir sind in " . __FUNCTION__ . " Line " . __LINE__ . ", OK ");
             //Now question_attributes
             $query = "UPDATE {$dbprefix}question_attributes SET qid={$newqid} WHERE qid={$oldqid}";
             $result = $connect->Execute($query) or $this->debugLsrc($query . "" . $connect->ErrorMsg());
             //Now answers
             $query = "UPDATE {$dbprefix}answers SET qid={$newqid} WHERE qid={$oldqid}";
             $result = $connect->Execute($query) or $this->debugLsrc($query . "" . $connect->ErrorMsg());
         }
         //CHECK TO MAKE SURE ALL QUESTION TYPES THAT REQUIRE ANSWERS HAVE ACTUALLY GOT ANSWERS
         //THESE QUESTION TYPES ARE:
         //	# "L" -> LIST
         //  # "O" -> LIST WITH COMMENT
         //  # "M" -> MULTIPLE OPTIONS
         //	# "P" -> MULTIPLE OPTIONS WITH COMMENTS
         //	# "A", "B", "C", "E", "F", "H", "^" -> Various Array Types
         //  # "R" -> RANKING
         //  # "U" -> FILE CSV MORE
         //  # "I" -> FILE CSV ONE
         //  # ":" -> Array Multi Flexi Numbers
         //  # ";" -> Array Multi Flexi Text
         //  # "1" -> MULTI SCALE
         $this->debugLsrc("wir sind in " . __FUNCTION__ . " Line " . __LINE__ . ", OK ");
         $chkquery = "SELECT qid, question, gid FROM {$dbprefix}questions WHERE sid={$surveyid} AND type IN ('L', 'O', 'M', 'P', 'A', 'B', 'C', 'E', 'F', 'R', 'J', '!', '^', ':', '1')";
         $chkresult = db_execute_assoc($chkquery) or $this->debugLsrc("Couldn't get list of questions{$chkquery}" . $connect->ErrorMsg());
         while ($chkrow = $chkresult->FetchRow()) {
             $chaquery = "SELECT * FROM {$dbprefix}answers WHERE qid = {$chkrow['qid']} ORDER BY sortorder, answer";
             $charesult = $connect->Execute($chaquery);
             $chacount = $charesult->RecordCount();
             if (!$chacount > 0) {
                 //$failedcheck[]=array($chkrow['qid'], $chkrow['question'], ": ".("This question is a multiple answer type question but has no answers."), $chkrow['gid']);
             }
         }
         //NOW CHECK THAT ALL QUESTIONS HAVE A 'QUESTION TYPE' FIELD
         $chkquery = "SELECT qid, question, gid FROM {$dbprefix}questions WHERE sid={$surveyid} AND type = ''";
         $chkresult = db_execute_assoc($chkquery) or $this->debugLsrc("Couldn't check questions for missing types{$chkquery}" . $connect->ErrorMsg());
         while ($chkrow = $chkresult->FetchRow()) {
             //$failedcheck[]=array($chkrow['qid'], $chkrow['question'], ": ".("This question does not have a question 'type' set."), $chkrow['gid']);
         }
         $this->debugLsrc("wir sind in " . __FUNCTION__ . " Line " . __LINE__ . ", OK ");
         //CHECK THAT FLEXIBLE LABEL TYPE QUESTIONS HAVE AN "LID" SET
         $chkquery = "SELECT qid, question, gid FROM {$dbprefix}questions WHERE sid={$surveyid} AND type IN ('F', 'H', 'W', 'Z', ':', '1') AND (lid = 0 OR lid is null)";
         //$chkresult = db_execute_assoc($chkquery) or $this->debugLsrc ("Couldn't check questions for missing LIDs$chkquery".$connect->ErrorMsg());
         while ($chkrow = $chkresult->FetchRow()) {
             //	$failedcheck[]=array($chkrow['qid'], $chkrow['question'], ": ".("This question requires a Labelset, but none is set."), $chkrow['gid']);
         }
         // while
         //CHECK THAT FLEXIBLE LABEL TYPE QUESTIONS HAVE AN "LID1" SET FOR MULTI SCALE
         $chkquery = "SELECT qid, question, gid FROM {$dbprefix}questions WHERE sid={$surveyid} AND (type ='1') AND (lid1 = 0 OR lid1 is null)";
         $chkresult = db_execute_assoc($chkquery) or $this->debugLsrc("Couldn't check questions for missing LIDs{$chkquery}" . $connect->ErrorMsg());
         while ($chkrow = $chkresult->FetchRow()) {
             //	$failedcheck[]=array($chkrow['qid'], $chkrow['question'], ": ".("This question requires a second Labelset, but none is set."), $chkrow['gid']);
         }
         // while
         $this->debugLsrc("wir sind in " . __FUNCTION__ . " Line " . __LINE__ . ", OK ");
         // XXX rakete Changed: This was making errors, for we dont have additional languages and this script throws an error when there are none.
         //NOW check that all used labelsets have all necessary languages
         $chkquery = "SELECT qid, question, gid, lid FROM {$dbprefix}questions WHERE sid={$surveyid} AND type IN ('F', 'H', 'W', 'Z', ':', '1') AND (lid > 0) AND (lid is not null)";
         $this->debugLsrc("wir sind in " . __FUNCTION__ . " Line " . __LINE__ . ", {$chkquery} ");
         $chkresult = db_execute_assoc($chkquery) or $this->debugLsrc("Couldn't check questions for missing LID languages{$chkquery}" . $connect->ErrorMsg());
         $slangs = GetAdditionalLanguagesFromSurveyID($surveyid);
         $baselang = GetBaseLanguageFromSurveyID($surveyid);
         array_unshift($slangs, $baselang);
         while ($chkrow = $chkresult->FetchRow()) {
             foreach ($slangs as $surveylanguage) {
                 $chkquery2 = "SELECT lid FROM {$dbprefix}labels WHERE language='{$surveylanguage}' AND (lid = {$chkrow['lid']}) ";
                 $chkresult2 = db_execute_assoc($chkquery2);
                 if ($chkresult2->RecordCount() == 0) {
                     $failedcheck[] = array($chkrow['qid'], $chkrow['question'], ": The labelset used in this question does not exists or is missing a translation.", $chkrow['gid']);
                 }
             }
             //foreach
         }
         //while
         $this->debugLsrc("wir sind in " . __FUNCTION__ . " Line " . __LINE__ . ", OK ");
         //CHECK THAT ALL CONDITIONS SET ARE FOR QUESTIONS THAT PRECEED THE QUESTION CONDITION
         //A: Make an array of all the qids in order of appearance
         //	$qorderquery="SELECT * FROM {$dbprefix}questions, {$dbprefix}groups WHERE {$dbprefix}questions.gid={$dbprefix}groups.gid AND {$dbprefix}questions.sid={$surveyid} ORDER BY {$dbprefix}groups.sortorder, {$dbprefix}questions.title";
         //	$qorderresult=$connect->Execute($qorderquery) or $this->debugLsrc("Couldn't generate a list of questions in order$qorderquery".$connect->ErrorMsg());
         //	$qordercount=$qorderresult->RecordCount();
         //	$c=0;
         //	while ($qorderrow=$qorderresult->FetchRow())
         //		{
         //		$qidorder[]=array($c, $qorderrow['qid']);
         //		$c++;
         //		}
         //TO AVOID NATURAL SORT ORDER ISSUES, FIRST GET ALL QUESTIONS IN NATURAL SORT ORDER, AND FIND OUT WHICH NUMBER IN THAT ORDER THIS QUESTION IS
         $qorderquery = "SELECT * FROM {$dbprefix}questions WHERE sid={$surveyid} AND type not in ('S', 'D', 'T', 'Q')";
         $qorderresult = db_execute_assoc($qorderquery) or $this->debugLsrc("{$qorderquery}" . $connect->ErrorMsg());
         $qrows = array();
         //Create an empty array in case FetchRow does not return any rows
         while ($qrow = $qorderresult->FetchRow()) {
             $qrows[] = $qrow;
         }
         // Get table output into array
         usort($qrows, 'GroupOrderThenQuestionOrder');
         // Perform a case insensitive natural sort on group name then question title of a multidimensional array
         $c = 0;
         foreach ($qrows as $qr) {
             $qidorder[] = array($c, $qrow['qid']);
             $c++;
         }
         $qordercount = "";
         //1: Get each condition's question id
         $conquery = "SELECT {$dbprefix}conditions.qid, cqid, {$dbprefix}questions.question, " . "{$dbprefix}questions.gid " . "FROM {$dbprefix}conditions, {$dbprefix}questions, {$dbprefix}groups " . "WHERE {$dbprefix}conditions.qid={$dbprefix}questions.qid " . "AND {$dbprefix}questions.gid={$dbprefix}groups.gid ORDER BY {$dbprefix}conditions.qid";
         $conresult = db_execute_assoc($conquery) or $this->debugLsrc("Couldn't check conditions for relative consistency{$conquery}" . $connect->ErrorMsg());
         //2: Check each conditions cqid that it occurs later than the cqid
         while ($conrow = $conresult->FetchRow()) {
             $cqidfound = 0;
             $qidfound = 0;
             $b = 0;
             while ($b < $qordercount) {
                 if ($conrow['cqid'] == $qidorder[$b][1]) {
                     $cqidfound = 1;
                     $b = $qordercount;
                 }
                 if ($conrow['qid'] == $qidorder[$b][1]) {
                     $qidfound = 1;
                     $b = $qordercount;
                 }
                 if ($qidfound == 1) {
                     //$failedcheck[]=array($conrow['qid'], $conrow['question'], ": ".("This question has a condition set, however the condition is based on a question that appears after it."), $conrow['gid']);
                 }
                 $b++;
             }
         }
         //CHECK THAT ALL THE CREATED FIELDS WILL BE UNIQUE
         $fieldmap = createFieldMap($surveyid, "full");
         if (isset($fieldmap)) {
             foreach ($fieldmap as $fielddata) {
                 $fieldlist[] = $fielddata['fieldname'];
             }
             $fieldlist = array_reverse($fieldlist);
             //let's always change the later duplicate, not the earlier one
         }
         $checkKeysUniqueComparison = create_function('$value', 'if ($value > 1) return true;');
         @($duplicates = array_keys(array_filter(array_count_values($fieldlist), $checkKeysUniqueComparison)));
         if (isset($duplicates)) {
             foreach ($duplicates as $dup) {
                 $badquestion = arraySearchByKey($dup, $fieldmap, "fieldname", 1);
                 $fix = "[<a href='{$scriptname}?action=activate&amp;sid={$surveyid}&amp;fixnumbering=" . $badquestion['qid'] . "'>Click Here to Fix</a>]";
                 //$failedcheck[]=array($badquestion['qid'], $badquestion['question'], ": Bad duplicate fieldname $fix", $badquestion['gid']);
             }
         }
         //IF ANY OF THE CHECKS FAILED, PRESENT THIS SCREEN
         if (isset($failedcheck) && $failedcheck) {
             //$activateoutput .= "\n<table bgcolor='#FFFFFF' width='500' align='center' style='border: 1px solid #555555' cellpadding='6' cellspacing='0'>\n";
             //$activateoutput .= "\t\t\t\t<tr bgcolor='#555555'><td height='4'><font size='1' face='verdana' color='white'><strong>".("Activate Survey")." ($surveyid)</strong></font></td></tr>\n";
             //$activateoutput .= "\t<tr>\n";
             //$activateoutput .= "\t\t<td align='center' bgcolor='#ffeeee'>\n";
             //$activateoutput .= "\t\t\t<font color='red'><strong>".("Error")."</strong>\n";
             //$activateoutput .= "\t\t\t".("Survey does not pass consistency check")."</font>\n";
             //$activateoutput .= "\t\t</td>\n";
             //$activateoutput .= "\t</tr>\n";
             //$activateoutput .= "\t<tr>\n";
             //$activateoutput .= "\t\t<td>\n";
             //$activateoutput .= "\t\t\t<strong>".("The following problems have been found:")."</strong>\n";
             //$activateoutput .= "\t\t\t<ul>\n";
             foreach ($failedcheck as $fc) {
                 //$activateoutput .= "\t\t\t\t<li> Question qid-{$fc[0]} (\"<a href='$scriptname?sid=$surveyid&amp;gid=$fc[3]&amp;qid=$fc[0]'>{$fc[1]}</a>\"){$fc[2]}</li>\n";
             }
             //$activateoutput .= "\t\t\t</ul>\n";
             //$activateoutput .= "\t\t\t".("The survey cannot be activated until these problems have been resolved.")."\n";
             //$activateoutput .= "\t\t</td>\n";
             //$activateoutput .= "\t</tr>\n";
             //$activateoutput .= "</table>&nbsp;\n";
             $this->debugLsrc("wir sind in " . __FUNCTION__ . " Line " . __LINE__ . ", NICHT ERWARTET ");
             return false;
         }
         $this->debugLsrc("wir sind in " . __FUNCTION__ . " Line " . __LINE__ . ", OK ");
         //$activateoutput .= "\n<table class='alertbox'>\n";
         //$activateoutput .= "\t\t\t\t<tr><td height='4'><strong>".("Activate Survey")." ($surveyid)</strong></td></tr>\n";
         //$activateoutput .= "\t<tr>\n";
         //$activateoutput .= "\t\t<td align='center' bgcolor='#ffeeee'>\n";
         //$activateoutput .= "\t\t\t<font color='red'><strong>".("Warning")."</strong>\n";
         //$activateoutput .= "\t\t\t".("READ THIS CAREFULLY BEFORE PROCEEDING")."\n";
         //$activateoutput .= "\t\t\t</font>\n";
         //$activateoutput .= "\t\t</td>\n";
         //$activateoutput .= "\t</tr>\n";
         //$activateoutput .= "\t<tr>\n";
         //$activateoutput .= "\t\t<td>\n";
         //$activateoutput .= ("You should only activate a survey when you are absolutely certain that your survey setup is finished and will not need changing.")."\n";
         //$activateoutput .= ("Once a survey is activated you can no longer:")."<ul><li>".("Add or delete groups")."</li><li>".("Add or remove answers to Multiple Answer questions")."</li><li>".("Add or delete questions")."</li></ul>\n";
         //$activateoutput .= ("However you can still:")."<ul><li>".("Edit (change) your questions code, text or type")."</li><li>".("Edit (change) your group names")."</li><li>".("Add, Remove or Edit pre-defined question answers (except for Multi-answer questions)")."</li><li>".("Change survey name or description")."</li></ul>\n";
         //$activateoutput .= ("Once data has been entered into this survey, if you want to add or remove groups or questions, you will need to deactivate this survey, which will move all data that has already been entered into a separate archived table.")."\n";
         //$activateoutput .= "\t\t</td>\n";
         //$activateoutput .= "\t</tr>\n";
         //$activateoutput .= "\t<tr>\n";
         //$activateoutput .= "\t\t<td align='center'>\n";
         //$activateoutput .= "\t\t\t<input type='submit' value=\"".("Activate Survey")."\" onclick=\"window.open('$scriptname?action=activate&amp;ok=Y&amp;sid={$surveyid}', '_top')\" />\n";
         //$activateoutput .= "\t\t\t<input type='submit' value=\"".("Activate Survey")."\" onclick=\"".get2post("$scriptname?action=activate&amp;ok=Y&amp;sid={$surveyid}")."\" />\n";
         //$activateoutput .= "\t\t&nbsp;</td>\n";
         //$activateoutput .= "\t</tr>\n";
         //$activateoutput .= "</table>&nbsp;\n";
         //XXX Changed rakete, set Post var for lsrc, no else
         $_POST['ok'] = "Y";
         $this->debugLsrc("wir sind in " . __FUNCTION__ . " Line " . __LINE__ . ", OK ");
     }
     if (isset($_POST['ok']) || $_POST['ok']) {
         $this->debugLsrc("wir sind in " . __FUNCTION__ . " Line " . __LINE__ . ", OK ");
         //Create the survey responses table
         $createsurvey = "id I NOTNULL AUTO PRIMARY,\n";
         $createsurvey .= " submitdate T,\n";
         $createsurvey .= " lastpage I,\n";
         $createsurvey .= " startlanguage C(20) NOTNULL ,\n";
         //Check for any additional fields for this survey and create necessary fields (token and datestamp)
         $pquery = "SELECT private, allowregister, datestamp, ipaddr, refurl FROM {$dbprefix}surveys WHERE sid={$surveyid}";
         $presult = db_execute_assoc($pquery);
         while ($prow = $presult->FetchRow()) {
             if ($prow['private'] == "N") {
                 $createsurvey .= "  token C(36),\n";
                 $surveynotprivate = "TRUE";
             }
             if ($prow['allowregister'] == "Y") {
                 $surveyallowsregistration = "TRUE";
             }
             if ($prow['datestamp'] == "Y") {
                 $createsurvey .= " datestamp T NOTNULL,\n";
                 $createsurvey .= " startdate T NOTNULL,\n";
             }
             if ($prow['ipaddr'] == "Y") {
                 $createsurvey .= " ipaddr X,\n";
             }
             //Check to see if 'refurl' field is required.
             if ($prow['refurl'] == "Y") {
                 $createsurvey .= " refurl X,\n";
             }
         }
         //Get list of questions for the base language
         $aquery = " SELECT * FROM " . db_table_name('questions') . ", " . db_table_name('groups') . " WHERE " . db_table_name('questions') . ".gid=" . db_table_name('groups') . ".gid " . " AND " . db_table_name('questions') . ".sid={$surveyid} " . " AND " . db_table_name('groups') . ".language='" . GetbaseLanguageFromSurveyid($surveyid) . "' " . " AND " . db_table_name('questions') . ".language='" . GetbaseLanguageFromSurveyid($surveyid) . "' " . " ORDER BY group_order, question_order";
         $aresult = db_execute_assoc($aquery);
         while ($arow = $aresult->FetchRow()) {
             if (substr($createsurvey, strlen($createsurvey) - 2, 2) != ",\n") {
                 $createsurvey .= ",\n";
             }
             if ($arow['type'] != "M" && $arow['type'] != "A" && $arow['type'] != "B" && $arow['type'] != "C" && $arow['type'] != "E" && $arow['type'] != "F" && $arow['type'] != "H" && $arow['type'] != "P" && $arow['type'] != "R" && $arow['type'] != "Q" && $arow['type'] != "^" && $arow['type'] != "J" && $arow['type'] != "K" && $arow['type'] != ":" && $arow['type'] != ";" && $arow['type'] != "1") {
                 $createsurvey .= "  `{$arow['sid']}X{$arow['gid']}X{$arow['qid']}`";
                 switch ($arow['type']) {
                     case "N":
                         //NUMERICAL
                         $createsurvey .= " F";
                         break;
                     case "S":
                         //SHORT TEXT
                         if ($databasetype == 'mysql' || $databasetype == 'mysqli') {
                             $createsurvey .= " X";
                         } else {
                             $createsurvey .= " C(255)";
                         }
                         break;
                     case "L":
                         //LIST (RADIO)
                     //LIST (RADIO)
                     case "!":
                         //LIST (DROPDOWN)
                     //LIST (DROPDOWN)
                     case "W":
                     case "Z":
                         $createsurvey .= " C(5)";
                         if ($arow['other'] == "Y") {
                             $createsurvey .= ",\n`{$arow['sid']}X{$arow['gid']}X{$arow['qid']}other` X";
                         }
                         break;
                     case "I":
                         // CSV ONE
                         $createsurvey .= " C(5)";
                         break;
                     case "O":
                         //DROPDOWN LIST WITH COMMENT
                         $createsurvey .= " C(5),\n `{$arow['sid']}X{$arow['gid']}X{$arow['qid']}comment` X";
                         break;
                     case "T":
                         //LONG TEXT
                         $createsurvey .= " X";
                         break;
                     case "U":
                         //HUGE TEXT
                         $createsurvey .= " X";
                         break;
                     case "D":
                         //DATE
                         $createsurvey .= " D";
                         break;
                     case "5":
                         //5 Point Choice
                     //5 Point Choice
                     case "G":
                         //Gender
                     //Gender
                     case "Y":
                         //YesNo
                     //YesNo
                     case "X":
                         //Boilerplate
                         $createsurvey .= " C(1)";
                         break;
                 }
             } elseif ($arow['type'] == "M" || $arow['type'] == "A" || $arow['type'] == "B" || $arow['type'] == "C" || $arow['type'] == "E" || $arow['type'] == "F" || $arow['type'] == "H" || $arow['type'] == "P" || $arow['type'] == "^") {
                 //MULTI ENTRY
                 $abquery = "SELECT a.*, q.other FROM {$dbprefix}answers as a, {$dbprefix}questions as q" . " WHERE a.qid=q.qid AND sid={$surveyid} AND q.qid={$arow['qid']} " . " AND a.language='" . GetbaseLanguageFromSurveyid($surveyid) . "' " . " AND q.language='" . GetbaseLanguageFromSurveyid($surveyid) . "' " . " ORDER BY a.sortorder, a.answer";
                 $abresult = db_execute_assoc($abquery) or $this->debugLsrc("Couldn't get perform answers query{$abquery}" . $connect->ErrorMsg());
                 while ($abrow = $abresult->FetchRow()) {
                     $createsurvey .= "  `{$arow['sid']}X{$arow['gid']}X{$arow['qid']}{$abrow['code']}` C(5),\n";
                     if ($abrow['other'] == "Y") {
                         $alsoother = "Y";
                     }
                     if ($arow['type'] == "P") {
                         $createsurvey .= "  `{$arow['sid']}X{$arow['gid']}X{$arow['qid']}{$abrow['code']}comment` X,\n";
                     }
                 }
                 if (isset($alsoother) && $alsoother == "Y" && ($arow['type'] == "M" || $arow['type'] == "P" || $arow['type'] == "1")) {
                     $createsurvey .= " `{$arow['sid']}X{$arow['gid']}X{$arow['qid']}other` X,\n";
                     if ($arow['type'] == "P") {
                         $createsurvey .= " `{$arow['sid']}X{$arow['gid']}X{$arow['qid']}othercomment` X,\n";
                     }
                 }
             } elseif ($arow['type'] == ":" || $arow['type'] == ";") {
                 //MULTI ENTRY
                 $abquery = "SELECT a.*, q.other FROM {$dbprefix}answers as a, {$dbprefix}questions as q" . " WHERE a.qid=q.qid AND sid={$surveyid} AND q.qid={$arow['qid']} " . " AND a.language='" . GetbaseLanguageFromSurveyid($surveyid) . "' " . " AND q.language='" . GetbaseLanguageFromSurveyid($surveyid) . "' " . " ORDER BY a.sortorder, a.answer";
                 $abresult = db_execute_assoc($abquery) or die("Couldn't get perform answers query{$abquery}" . $connect->ErrorMsg());
                 $ab2query = "SELECT " . db_table_name('labels') . ".*\r\n\t\t\t\t\t             FROM " . db_table_name('questions') . ", " . db_table_name('labels') . "\r\n\t\t\t\t\t             WHERE sid={$surveyid} \r\n\t\t\t\t\t\t\t\t AND " . db_table_name('labels') . ".lid=" . db_table_name('questions') . ".lid\r\n\t\t\t\t\t\t\t\t AND " . db_table_name('labels') . ".language='" . GetbaseLanguageFromSurveyid($surveyid) . "' \r\n\t\t\t\t\t             AND " . db_table_name('questions') . ".qid=" . $arow['qid'] . "\r\n\t\t\t\t\t             ORDER BY " . db_table_name('labels') . ".sortorder, " . db_table_name('labels') . ".title";
                 $ab2result = db_execute_assoc($ab2query) or die("Couldn't get list of labels in createFieldMap function (case :){$ab2query}" . htmlspecialchars($connection->ErrorMsg()));
                 while ($ab2row = $ab2result->FetchRow()) {
                     $lset[] = $ab2row;
                 }
                 while ($abrow = $abresult->FetchRow()) {
                     foreach ($lset as $ls) {
                         $createsurvey .= "  `{$arow['sid']}X{$arow['gid']}X{$arow['qid']}{$abrow['code']}_{$ls['code']}` X,\n";
                     }
                 }
                 unset($lset);
             } elseif ($arow['type'] == "Q") {
                 $abquery = "SELECT a.*, q.other FROM {$dbprefix}answers as a, {$dbprefix}questions as q WHERE a.qid=q.qid AND sid={$surveyid} AND q.qid={$arow['qid']} " . " AND a.language='" . GetbaseLanguageFromSurveyid($surveyid) . "' " . " AND q.language='" . GetbaseLanguageFromSurveyid($surveyid) . "' " . " ORDER BY a.sortorder, a.answer";
                 $abresult = db_execute_assoc($abquery) or $this->debugLsrc("Couldn't get perform answers query{$abquery}" . $connect->ErrorMsg());
                 while ($abrow = $abresult->FetchRow()) {
                     $createsurvey .= "  `{$arow['sid']}X{$arow['gid']}X{$arow['qid']}{$abrow['code']}`";
                     if ($databasetype == 'mysql' || $databasetype == 'mysqli') {
                         $createsurvey .= " X";
                     } else {
                         $createsurvey .= " C(255)";
                     }
                     $createsurvey .= ",\n";
                 }
             } elseif ($arow['type'] == "K") {
                 $abquery = "SELECT a.*, q.other FROM {$dbprefix}answers as a, {$dbprefix}questions as q WHERE a.qid=q.qid AND sid={$surveyid} AND q.qid={$arow['qid']} " . " AND a.language='" . GetbaseLanguageFromSurveyid($surveyid) . "' " . " AND q.language='" . GetbaseLanguageFromSurveyid($surveyid) . "' " . " ORDER BY a.sortorder, a.answer";
                 $abresult = db_execute_assoc($abquery) or $this->debugLsrc("Couldn't get perform answers query{$abquery}" . $connect->ErrorMsg());
                 while ($abrow = $abresult->FetchRow()) {
                     $createsurvey .= "  `{$arow['sid']}X{$arow['gid']}X{$arow['qid']}{$abrow['code']}` F,\n";
                 }
             } elseif ($arow['type'] == "R") {
                 //MULTI ENTRY
                 $abquery = "SELECT a.*, q.other FROM {$dbprefix}answers as a, {$dbprefix}questions as q" . " WHERE a.qid=q.qid AND sid={$surveyid} AND q.qid={$arow['qid']} " . " AND a.language='" . GetbaseLanguageFromSurveyid($surveyid) . "' " . " AND q.language='" . GetbaseLanguageFromSurveyid($surveyid) . "' " . " ORDER BY a.sortorder, a.answer";
                 $abresult = $connect->Execute($abquery) or $this->debugLsrc("Couldn't get perform answers query{$abquery}" . $connect->ErrorMsg());
                 $abcount = $abresult->RecordCount();
                 for ($i = 1; $i <= $abcount; $i++) {
                     $createsurvey .= "  `{$arow['sid']}X{$arow['gid']}X{$arow['qid']}{$i}` C(5),\n";
                 }
             } elseif ($arow['type'] == "1") {
                 $abquery = "SELECT a.*, q.other FROM {$dbprefix}answers as a, {$dbprefix}questions as q" . " WHERE a.qid=q.qid AND sid={$surveyid} AND q.qid={$arow['qid']} " . " AND a.language='" . GetbaseLanguageFromSurveyid($surveyid) . "' " . " AND q.language='" . GetbaseLanguageFromSurveyid($surveyid) . "' " . " ORDER BY a.sortorder, a.answer";
                 $abresult = db_execute_assoc($abquery) or $this->debugLsrc("Couldn't get perform answers query{$abquery}" . $connect->ErrorMsg());
                 $abcount = $abresult->RecordCount();
                 while ($abrow = $abresult->FetchRow()) {
                     $abmultiscalequery = "SELECT a.*, q.other FROM {$dbprefix}answers as a, {$dbprefix}questions as q, {$dbprefix}labels as l" . " WHERE a.qid=q.qid AND sid={$surveyid} AND q.qid={$arow['qid']} " . " AND l.lid=q.lid AND sid={$surveyid} AND q.qid={$arow['qid']} AND l.title = '' " . " AND l.language='" . GetbaseLanguageFromSurveyid($surveyid) . "' " . " AND q.language='" . GetbaseLanguageFromSurveyid($surveyid) . "' ";
                     $abmultiscaleresult = $connect->Execute($abmultiscalequery) or $this->debugLsrc("Couldn't get perform answers query{$abmultiscalequery}" . $connect->ErrorMsg());
                     $abmultiscaleresultcount = $abmultiscaleresult->RecordCount();
                     $abmultiscaleresultcount = 1;
                     for ($j = 0; $j <= $abmultiscaleresultcount; $j++) {
                         $createsurvey .= "  `{$arow['sid']}X{$arow['gid']}X{$arow['qid']}{$abrow['code']}#{$j}` C(5),\n";
                     }
                 }
             }
         }
         // If last question is of type MCABCEFHP^QKJR let's get rid of the ending coma in createsurvey
         $createsurvey = rtrim($createsurvey, ",\n") . "\n";
         // Does nothing if not ending with a comma
         $tabname = "{$dbprefix}survey_{$surveyid}";
         # not using db_table_name as it quotes the table name (as does CreateTableSQL)
         $taboptarray = array('mysql' => 'ENGINE=' . $databasetabletype . '  CHARACTER SET utf8 COLLATE utf8_unicode_ci', 'mysqli' => 'ENGINE=' . $databasetabletype . '  CHARACTER SET utf8 COLLATE utf8_unicode_ci');
         $dict = NewDataDictionary($connect);
         $sqlarray = $dict->CreateTableSQL($tabname, $createsurvey, $taboptarray);
         $execresult = $dict->ExecuteSQLArray($sqlarray, 1);
         if ($execresult == 0 || $execresult == 1) {
             //		$activateoutput .= "\n<table width='350' align='center' style='border: 1px solid #555555' cellpadding='1' cellspacing='0'>\n" .
             //		"<tr bgcolor='#555555'><td height='4'><font size='1' face='verdana' color='white'><strong>".("Activate Survey")." ($surveyid)</strong></font></td></tr>\n" .
             //		"<tr><td>\n" .
             //		"<font color='red'>".("Survey could not be actived.")."</font>\n" .
             //		"<center><a href='$scriptname?sid={$surveyid}'>".("Main Admin Screen")."</a></center>\n" .
             //		"DB ".("Error").":\n<font color='red'>" . $connect->ErrorMsg() . "</font>\n" .
             //		"<pre>$createsurvey</pre>\n" .
             //		"</td></tr></table></br>&nbsp;\n" .
             //		"</body>\n</html>";
         }
         if ($execresult != 0 && $execresult != 1) {
             $anquery = "SELECT autonumber_start FROM {$dbprefix}surveys WHERE sid={$surveyid}";
             if ($anresult = db_execute_assoc($anquery)) {
                 //if there is an autonumber_start field, start auto numbering here
                 while ($row = $anresult->FetchRow()) {
                     if ($row['autonumber_start'] > 0) {
                         $autonumberquery = "ALTER TABLE {$dbprefix}survey_{$surveyid} AUTO_INCREMENT = " . $row['autonumber_start'];
                         if ($result = $connect->Execute($autonumberquery)) {
                             //We're happy it worked!
                         } else {
                             //Continue regardless - it's not the end of the world
                         }
                     }
                 }
             }
             //$activateoutput .= "\n<table class='alertbox'>\n";
             //$activateoutput .= "\t\t\t\t<tr><td height='4'><strong>".("Activate Survey")." ($surveyid)</td></tr>\n";
             //$activateoutput .= "\t\t\t\t<tr><td align='center'><font class='successtitle'>".("Survey has been activated. Results table has been successfully created.")."</font>\n";
             $this->debugLsrc("wir sind in " . __FILE__ . " - " . __FUNCTION__ . " Line " . __LINE__ . ", OK ");
             $acquery = "UPDATE {$dbprefix}surveys SET active='Y' WHERE sid=" . $surveyid;
             $acresult = $connect->Execute($acquery);
             $this->debugLsrc("wir sind in " . __FILE__ . " - " . __FUNCTION__ . " Line " . __LINE__ . ", FERTIG ");
         }
     }
     return true;
 }
/**
 * checks questions in a survey for consistency
 * @global <type> $dbprefix
 * @global <type> $connect
 * @global <type> $clang
 * @param <type> $postsid
 * @param <type> $surveyid
 * @return array $faildcheck
 */
function checkQuestions($postsid, $surveyid, $qtypes)
{
    global $dbprefix, $connect, $clang;
    //CHECK TO MAKE SURE ALL QUESTION TYPES THAT REQUIRE ANSWERS HAVE ACTUALLY GOT ANSWERS
    //THESE QUESTION TYPES ARE:
    //	# "L" -> LIST
    //  # "O" -> LIST WITH COMMENT
    //  # "M" -> Multiple choice
    //	# "P" -> Multiple choice with comments
    //	# "A", "B", "C", "E", "F", "H", "^" -> Various Array Types
    //  # "R" -> RANKING
    //  # "U" -> FILE CSV MORE
    //  # "I" -> LANGUAGE SWITCH
    //  # ":" -> Array Multi Flexi Numbers
    //  # ";" -> Array Multi Flexi Text
    //  # "1" -> MULTI SCALE
    $chkquery = "SELECT qid, question, gid, type FROM {$dbprefix}questions WHERE sid={$surveyid} and parent_qid=0";
    $chkresult = db_execute_assoc($chkquery) or safe_die("Couldn't get list of questions<br />{$chkquery}<br />" . $connect->ErrorMsg());
    while ($chkrow = $chkresult->FetchRow()) {
        if ($qtypes[$chkrow['type']]['subquestions'] > 0) {
            $chaquery = "SELECT * FROM {$dbprefix}questions WHERE parent_qid = {$chkrow['qid']} ORDER BY question_order";
            $charesult = $connect->Execute($chaquery);
            $chacount = $charesult->RecordCount();
            if ($chacount == 0) {
                $failedcheck[] = array($chkrow['qid'], $chkrow['question'], ": " . $clang->gT("This question is a subquestion type question but has no configured subquestions."), $chkrow['gid']);
            }
        }
        if ($qtypes[$chkrow['type']]['answerscales'] > 0) {
            $chaquery = "SELECT * FROM {$dbprefix}answers WHERE qid = {$chkrow['qid']} ORDER BY sortorder, answer";
            $charesult = $connect->Execute($chaquery);
            $chacount = $charesult->RecordCount();
            if ($chacount == 0) {
                $failedcheck[] = array($chkrow['qid'], $chkrow['question'], ": " . $clang->gT("This question is a multiple answer type question but has no answers."), $chkrow['gid']);
            }
        }
    }
    //NOW CHECK THAT ALL QUESTIONS HAVE A 'QUESTION TYPE' FIELD SET
    $chkquery = "SELECT qid, question, gid FROM {$dbprefix}questions WHERE sid={$_GET['sid']} AND type = ''";
    $chkresult = db_execute_assoc($chkquery) or safe_die("Couldn't check questions for missing types<br />{$chkquery}<br />" . $connect->ErrorMsg());
    while ($chkrow = $chkresult->FetchRow()) {
        $failedcheck[] = array($chkrow['qid'], $chkrow['question'], ": " . $clang->gT("This question does not have a question 'type' set."), $chkrow['gid']);
    }
    //ChECK THAT certain array question types have answers set
    $chkquery = "SELECT q.qid, question, gid FROM {$dbprefix}questions as q WHERE (select count(*) from {$dbprefix}answers as a where a.qid=q.qid and scale_id=0)=0 and sid={$_GET['sid']} AND type IN ('F', 'H', 'W', 'Z', '1') and q.parent_qid=0";
    $chkresult = db_execute_assoc($chkquery) or safe_die("Couldn't check questions for missing answers<br />{$chkquery}<br />" . $connect->ErrorMsg());
    while ($chkrow = $chkresult->FetchRow()) {
        $failedcheck[] = array($chkrow['qid'], $chkrow['question'], ": " . $clang->gT("This question requires answers, but none are set."), $chkrow['gid']);
    }
    // while
    //CHECK THAT DUAL Array has answers set
    $chkquery = "SELECT q.qid, question, gid FROM {$dbprefix}questions as q WHERE (select count(*) from {$dbprefix}answers as a where a.qid=q.qid and scale_id=1)=0 and sid={$_GET['sid']} AND type='1' and q.parent_qid=0";
    $chkresult = db_execute_assoc($chkquery) or safe_die("Couldn't check questions for missing 2nd answer set<br />{$chkquery}<br />" . $connect->ErrorMsg());
    while ($chkrow = $chkresult->FetchRow()) {
        $failedcheck[] = array($chkrow['qid'], $chkrow['question'], ": " . $clang->gT("This question requires a second answer set but none is set."), $chkrow['gid']);
    }
    // while
    //CHECK THAT ALL CONDITIONS SET ARE FOR QUESTIONS THAT PRECEED THE QUESTION CONDITION
    //A: Make an array of all the qids in order of appearance
    //	$qorderquery="SELECT * FROM {$dbprefix}questions, {$dbprefix}groups WHERE {$dbprefix}questions.gid={$dbprefix}groups.gid AND {$dbprefix}questions.sid={$_GET['sid']} ORDER BY {$dbprefix}groups.sortorder, {$dbprefix}questions.title";
    //	$qorderresult=$connect->Execute($qorderquery) or safe_die("Couldn't generate a list of questions in order<br />$qorderquery<br />".$connect->ErrorMsg());
    //	$qordercount=$qorderresult->RecordCount();
    //	$c=0;
    //	while ($qorderrow=$qorderresult->FetchRow())
    //		{
    //		$qidorder[]=array($c, $qorderrow['qid']);
    //		$c++;
    //		}
    //TO AVOID NATURAL SORT ORDER ISSUES, FIRST GET ALL QUESTIONS IN NATURAL SORT ORDER, AND FIND OUT WHICH NUMBER IN THAT ORDER THIS QUESTION IS
    $qorderquery = "SELECT * FROM {$dbprefix}questions WHERE sid={$surveyid} AND type not in ('S', 'D', 'T', 'Q')";
    $qorderresult = db_execute_assoc($qorderquery) or safe_die("{$qorderquery}<br />" . $connect->ErrorMsg());
    $qrows = array();
    //Create an empty array in case FetchRow does not return any rows
    while ($qrow = $qorderresult->FetchRow()) {
        $qrows[] = $qrow;
    }
    // Get table output into array
    usort($qrows, 'GroupOrderThenQuestionOrder');
    // Perform a case insensitive natural sort on group name then question title of a multidimensional array
    $c = 0;
    foreach ($qrows as $qr) {
        $qidorder[] = array($c, $qrow['qid']);
        $c++;
    }
    $qordercount = "";
    //1: Get each condition's question id
    $conquery = "SELECT {$dbprefix}conditions.qid, cqid, {$dbprefix}questions.question, " . "{$dbprefix}questions.gid " . "FROM {$dbprefix}conditions, {$dbprefix}questions, {$dbprefix}groups " . "WHERE {$dbprefix}conditions.qid={$dbprefix}questions.qid " . "AND {$dbprefix}questions.gid={$dbprefix}groups.gid ORDER BY {$dbprefix}conditions.qid";
    $conresult = db_execute_assoc($conquery) or safe_die("Couldn't check conditions for relative consistency<br />{$conquery}<br />" . $connect->ErrorMsg());
    //2: Check each conditions cqid that it occurs later than the cqid
    while ($conrow = $conresult->FetchRow()) {
        $cqidfound = 0;
        $qidfound = 0;
        $b = 0;
        while ($b < $qordercount) {
            if ($conrow['cqid'] == $qidorder[$b][1]) {
                $cqidfound = 1;
                $b = $qordercount;
            }
            if ($conrow['qid'] == $qidorder[$b][1]) {
                $qidfound = 1;
                $b = $qordercount;
            }
            if ($qidfound == 1) {
                $failedcheck[] = array($conrow['qid'], $conrow['question'], ": " . $clang->gT("This question has a condition set, however the condition is based on a question that appears after it."), $conrow['gid']);
            }
            $b++;
        }
    }
    //CHECK THAT ALL THE CREATED FIELDS WILL BE UNIQUE
    $fieldmap = createFieldMap($surveyid, "full");
    if (isset($fieldmap)) {
        foreach ($fieldmap as $fielddata) {
            $fieldlist[] = $fielddata['fieldname'];
        }
        $fieldlist = array_reverse($fieldlist);
        //let's always change the later duplicate, not the earlier one
    }
    $checkKeysUniqueComparison = create_function('$value', 'if ($value > 1) return true;');
    @($duplicates = array_keys(array_filter(array_count_values($fieldlist), $checkKeysUniqueComparison)));
    if (isset($duplicates)) {
        foreach ($duplicates as $dup) {
            $badquestion = arraySearchByKey($dup, $fieldmap, "fieldname", 1);
            $fix = "[<a href='{$scriptname}?action=activate&amp;sid={$surveyid}&amp;fixnumbering=" . $badquestion['qid'] . "'>Click Here to Fix</a>]";
            $failedcheck[] = array($badquestion['qid'], $badquestion['question'], ": Bad duplicate fieldname {$fix}", $badquestion['gid']);
        }
    }
    if (isset($failedcheck)) {
        return $failedcheck;
    } else {
        return false;
    }
}
/**
 * getArrayFiltersExcludesOutGroup($qid) finds out if a question is in the current group or not for array filter exclude
 * @global string $qid
 * @return returns true if its not in currect group and false if it is..
 */
function getArrayFiltersExcludesOutGroup($qid)
{
    // TODO: Check list_filter values to make sure questions are previous?
    global $surveyid, $dbprefix, $gid;
    $qid = sanitize_int($qid);
    $attributes = getQuestionAttributes($qid);
    if (isset($attributes['array_filter_exclude'])) {
        $val = $attributes['array_filter_exclude'];
        // Get the Value of the Attribute ( should be a previous question's title in same group )
        // we found the target question, now we need to know what the answers where, we know its a multi!
        $surveyid = returnglobal('sid');
        $fieldmap = createFieldMap($surveyid, 'full');
        $val2 = arraySearchByKey($val, $fieldmap, 'title', 1);
        if ($val2['gid'] != $gid) {
            return true;
        }
        if ($val2['gid'] == $gid) {
            return false;
        }
    }
    return false;
}
Ejemplo n.º 12
0
function getsidgidqidaidtype($fieldcode)
{
    // use simple parsing to get {sid}, {gid}
    // and what may be {qid} or {qid}{aid} combination
    list($fsid, $fgid, $fqid) = explode('X', $fieldcode);
    $fsid = sanitize_int($fsid);
    $fgid = sanitize_int($fgid);
    if (!$fqid) {
        $fqid = 0;
    }
    $fqid = sanitize_int($fqid);
    // try a true parsing of fieldcode (can separate qid from aid)
    // but fails for type M and type P multiple choice
    // questions because the SESSION fieldcode is combined
    // and we want here to pass only the sidXgidXqid for type M and P
    $fields = arraySearchByKey($fieldcode, createFieldMap($fsid), "fieldname", 1);
    if (count($fields) != 0) {
        $aRef['sid'] = $fields['sid'];
        $aRef['gid'] = $fields['gid'];
        $aRef['qid'] = $fields['qid'];
        $aRef['aid'] = $fields['aid'];
        $aRef['type'] = $fields['type'];
    } else {
        // either the fielcode doesn't match a question
        // or it is a type M or P question
        $aRef['sid'] = $fsid;
        $aRef['gid'] = $fgid;
        $aRef['qid'] = sanitize_int($fqid);
        $s_lang = GetBaseLanguageFromSurveyID($fsid);
        $query = "SELECT type FROM " . db_table_name('questions') . " WHERE qid=" . $fqid . " AND language='" . $s_lang . "'";
        $result = db_execute_assoc($query) or safe_die("Couldn't get question type - getsidgidqidaidtype() in common.php<br />" . $connect->ErrorMsg());
        //Checked
        if ($result->RecordCount() == 0) {
            // question doesn't exist
            return array();
        } else {
            // certainly is type M or P
            while ($row = $result->FetchRow()) {
                $aRef['type'] = $row['type'];
            }
        }
    }
    //return array('sid'=>$fsid, "gid"=>$fgid, "qid"=>$fqid);
    return $aRef;
}