Beispiel #1
0
 /**
  * Load saved list.
  * @param mixed $iSurveyId Survey id
  */
 private function _showSavedList($iSurveyId)
 {
     $aResults = SavedControl::model()->findAll(array('select' => array('scid', 'srid', 'identifier', 'ip', 'saved_date', 'email', 'access_code'), 'condition' => 'sid=:sid', 'order' => 'saved_date desc', 'params' => array(':sid' => $iSurveyId)));
     if (!empty($aResults)) {
         return compact('aResults');
     } else {
         return array('aResults' => array());
     }
 }
Beispiel #2
0
    /**
     * dataentry::editdata()
     * Edit dataentry.
     * @param mixed $subaction
     * @param mixed $id
     * @param mixed $surveyid
     * @param mixed $language
     * @return
     */
    public function editdata($subaction, $id, $surveyid, $language = '')
    {
        if ($language == '') {
            $language = Survey::model()->findByPk($surveyid)->language;
        }
        $surveyid = sanitize_int($surveyid);
        $id = sanitize_int($id);
        $aViewUrls = array();
        if (!isset($sDataEntryLanguage)) {
            $sDataEntryLanguage = Survey::model()->findByPk($surveyid)->language;
        }
        $surveyinfo = getSurveyInfo($surveyid);
        if (Permission::model()->hasSurveyPermission($surveyid, 'responses', 'update')) {
            $surveytable = "{{survey_" . $surveyid . '}}';
            $aData['display']['menu_bars']['browse'] = gT("Data entry");
            Yii::app()->loadHelper('database');
            //FIRST LETS GET THE NAMES OF THE QUESTIONS AND MATCH THEM TO THE FIELD NAMES FOR THE DATABASE
            $fnquery = "SELECT * FROM {{questions}}, {{groups}} g, {{surveys}} WHERE\n            {{questions}}.gid=g.gid AND\n            {{questions}}.language = '{$sDataEntryLanguage}' AND g.language = '{$sDataEntryLanguage}' AND\n            {{questions}}.sid={{surveys}}.sid AND {{questions}}.sid='{$surveyid}'\n            order by group_order, question_order";
            $fnresult = dbExecuteAssoc($fnquery);
            $fnresult = $fnresult->readAll();
            $fncount = count($fnresult);
            $fnrows = array();
            //Create an empty array in case FetchRow does not return any rows
            foreach ($fnresult as $fnrow) {
                $fnrows[] = $fnrow;
                $private = $fnrow['anonymized'];
                $datestamp = $fnrow['datestamp'];
                $ipaddr = $fnrow['ipaddr'];
            }
            // Get table output into array
            // Perform a case insensitive natural sort on group name then question title of a multidimensional array
            // $fnames = (Field Name in Survey Table, Short Title of Question, Question Type, Field Name, Question Code, Predetermined Answer if exist)
            $fnames['completed'] = array('fieldname' => "completed", 'question' => gT("Completed"), 'type' => 'completed');
            $fnames = array_merge($fnames, createFieldMap($surveyid, 'full', false, false, $sDataEntryLanguage));
            // Fix private if disallowed to view token
            if (!Permission::model()->hasSurveyPermission($surveyid, 'tokens', 'read')) {
                unset($fnames['token']);
            }
            $nfncount = count($fnames) - 1;
            //SHOW INDIVIDUAL RECORD
            if ($subaction == "edit" && Permission::model()->hasSurveyPermission($surveyid, 'responses', 'update')) {
                $idquery = "SELECT * FROM {$surveytable} WHERE id={$id}";
                $idresult = dbExecuteAssoc($idquery) or safeDie("Couldn't get individual record<br />{$idquery}<br />");
                foreach ($idresult->readAll() as $idrow) {
                    $results[] = $idrow;
                }
            } elseif ($subaction == "editsaved" && Permission::model()->hasSurveyPermission($surveyid, 'responses', 'update')) {
                if (isset($_GET['public']) && $_GET['public'] == "true") {
                    $password = md5(Yii::app()->request->getParam('accesscode'));
                } else {
                    $password = Yii::app()->request->getParam('accesscode');
                }
                $svresult = SavedControl::model()->findAllByAttributes(array('sid' => $surveyid, 'identifier' => Yii::app()->request->getParam('identifier'), 'access_code' => $password));
                foreach ($svresult as $svrow) {
                    $saver['email'] = $svrow['email'];
                    $saver['scid'] = $svrow['scid'];
                    $saver['ip'] = $svrow['ip'];
                }
                $svresult = SavedControl::model()->findAllByAttributes(array('scid' => $saver['scid']));
                foreach ($svresult as $svrow) {
                    $responses[$svrow['fieldname']] = $svrow['value'];
                }
                // while
                $fieldmap = createFieldMap($surveyid, 'full', false, false, getBaseLanguageFromSurveyID($surveyid));
                foreach ($fieldmap as $fm) {
                    if (isset($responses[$fm['fieldname']])) {
                        $results1[$fm['fieldname']] = $responses[$fm['fieldname']];
                    } else {
                        $results1[$fm['fieldname']] = "";
                    }
                }
                $results1['id'] = "";
                $results1['datestamp'] = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", Yii::app()->getConfig('timeadjust'));
                $results1['ipaddr'] = $saver['ip'];
                $results[] = $results1;
            }
            $aData = array('id' => $id, 'surveyid' => $surveyid, 'subaction' => $subaction, 'part' => 'header');
            $aViewUrls[] = 'dataentry_header_view';
            $aViewUrls[] = 'edit';
            $highlight = FALSE;
            unset($fnames['lastpage']);
            // unset timings
            foreach ($fnames as $fname) {
                if ($fname['type'] == "interview_time" || $fname['type'] == "page_time" || $fname['type'] == "answer_time") {
                    unset($fnames[$fname['fieldname']]);
                    $nfncount--;
                }
            }
            $aDataentryoutput = '';
            foreach ($results as $idrow) {
                $fname = reset($fnames);
                do {
                    if (isset($idrow[$fname['fieldname']])) {
                        $answer = $idrow[$fname['fieldname']];
                    }
                    $question = $fname['question'];
                    $aDataentryoutput .= "\t<tr";
                    if ($highlight) {
                        $aDataentryoutput .= " class='odd'";
                    } else {
                        $aDataentryoutput .= " class='even'";
                    }
                    $highlight = !$highlight;
                    $aDataentryoutput .= ">\n" . "<td>" . "\n";
                    $aDataentryoutput .= stripJavaScript($question);
                    $aDataentryoutput .= "</td>\n" . "<td>\n";
                    //$aDataentryoutput .= "\t-={$fname[3]}=-"; //Debugging info
                    if (isset($fname['qid']) && isset($fname['type'])) {
                        $qidattributes = getQuestionAttributeValues($fname['qid']);
                    }
                    switch ($fname['type']) {
                        case "completed":
                            // First compute the submitdate
                            if ($private == "Y") {
                                // In case of anonymized responses survey with no datestamp
                                // then the the answer submitdate gets a conventional timestamp
                                // 1st Jan 1980
                                $mysubmitdate = date("Y-m-d H:i", mktime(0, 0, 0, 1, 1, 1980));
                                // Note that the completed field only supports 17 chars (so no seconds!)
                            } else {
                                $mysubmitdate = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i", Yii::app()->getConfig('timeadjust'));
                                // Note that the completed field only supports 17 chars (so no seconds!)
                            }
                            $completedate = empty($idrow['submitdate']) ? $mysubmitdate : $idrow['submitdate'];
                            $selected = empty($idrow['submitdate']) ? 'N' : $completedate;
                            $select_options = array('N' => gT('No', 'unescaped'), $completedate => gT('Yes', 'unescaped'));
                            $aDataentryoutput .= CHtml::dropDownList('completed', $selected, $select_options, array('class' => 'form-control'));
                            break;
                        case "X":
                            //Boilerplate question
                            $aDataentryoutput .= "";
                            break;
                        case "Q":
                        case "K":
                            $aDataentryoutput .= $fname['subquestion'] . '&nbsp;';
                            $aDataentryoutput .= CHtml::textField($fname['fieldname'], $idrow[$fname['fieldname']]);
                            break;
                        case "id":
                            $aDataentryoutput .= CHtml::tag('span', array('style' => 'font-weight: bold;'), '&nbsp;' . $idrow[$fname['fieldname']]);
                            break;
                        case "5":
                            //5 POINT CHOICE radio-buttons
                            for ($i = 1; $i <= 5; $i++) {
                                $checked = FALSE;
                                if ($idrow[$fname['fieldname']] == $i) {
                                    $checked = TRUE;
                                }
                                $aDataentryoutput .= '<span class="five-point">';
                                $aDataentryoutput .= CHtml::radioButton($fname['fieldname'], $checked, array('class' => '', 'value' => $i, 'id' => '5-point-choice-' . $i));
                                $aDataentryoutput .= '<label for="5-point-choice-' . $i . '">' . $i . '</label>';
                                $aDataentryoutput .= '</span>   ';
                            }
                            break;
                        case "D":
                            //DATE
                            $thisdate = '';
                            $dateformatdetails = getDateFormatDataForQID($qidattributes, $surveyid);
                            if ($idrow[$fname['fieldname']] != '') {
                                $datetimeobj = new Date_Time_Converter($idrow[$fname['fieldname']], "Y-m-d H:i:s");
                                $thisdate = $datetimeobj->convert($dateformatdetails['phpdate']);
                            } else {
                                $thisdate = '';
                            }
                            if (canShowDatePicker($dateformatdetails)) {
                                $goodchars = str_replace(array("m", "d", "y", "H", "M"), "", $dateformatdetails['dateformat']);
                                $goodchars = "0123456789" . $goodchars[0];
                                $aDataentryoutput .= CHtml::textField($fname['fieldname'], $thisdate, array('class' => 'popupdate', 'size' => '12', 'onkeypress' => 'return goodchars(event,\'' . $goodchars . '\')'));
                                $aDataentryoutput .= CHtml::hiddenField('dateformat' . $fname['fieldname'], $dateformatdetails['jsdate'], array('id' => "dateformat{$fname['fieldname']}"));
                                // $aDataentryoutput .= "\t<input type='text' class='popupdate' size='12' name='{$fname['fieldname']}' value='{$thisdate}' onkeypress=\"return goodchars(event,'".$goodchars."')\"/>\n";
                                // $aDataentryoutput .= "\t<input type='hidden' name='dateformat{$fname['fieldname']}' id='dateformat{$fname['fieldname']}' value='{$dateformatdetails['jsdate']}'  />\n";
                            } else {
                                $aDataentryoutput .= CHtml::textField($fname['fieldname'], $thisdate);
                            }
                            break;
                        case "G":
                            //GENDER drop-down list
                            $select_options = array('' => gT("Please choose") . '...', 'F' => gT("Female"), 'M' => gT("Male"));
                            $aDataentryoutput .= CHtml::listBox($fname['fieldname'], $idrow[$fname['fieldname']], $select_options);
                            break;
                        case "L":
                            //LIST drop-down
                        //LIST drop-down
                        case "!":
                            //List (Radio)
                            $qidattributes = getQuestionAttributeValues($fname['qid']);
                            if (isset($qidattributes['category_separator']) && trim($qidattributes['category_separator']) != '') {
                                $optCategorySeparator = $qidattributes['category_separator'];
                            } else {
                                unset($optCategorySeparator);
                            }
                            if (substr($fname['fieldname'], -5) == "other") {
                                $aDataentryoutput .= "\t<input type='text' name='{$fname['fieldname']}' value='" . htmlspecialchars($idrow[$fname['fieldname']], ENT_QUOTES) . "' />\n";
                            } else {
                                $lquery = "SELECT * FROM {{answers}} WHERE qid={$fname['qid']} AND language = '{$sDataEntryLanguage}' ORDER BY sortorder, answer";
                                $lresult = dbExecuteAssoc($lquery);
                                $aDataentryoutput .= "\t<select name='{$fname['fieldname']}' class='form-control'>\n" . "<option value=''";
                                if ($idrow[$fname['fieldname']] == "") {
                                    $aDataentryoutput .= " selected='selected'";
                                }
                                $aDataentryoutput .= ">" . gT("Please choose") . "..</option>\n";
                                if (!isset($optCategorySeparator)) {
                                    foreach ($lresult->readAll() as $llrow) {
                                        $aDataentryoutput .= "<option value='{$llrow['code']}'";
                                        if ($idrow[$fname['fieldname']] == $llrow['code']) {
                                            $aDataentryoutput .= " selected='selected'";
                                        }
                                        $aDataentryoutput .= ">{$llrow['answer']}</option>\n";
                                    }
                                } else {
                                    $defaultopts = array();
                                    $optgroups = array();
                                    foreach ($lresult->readAll() as $llrow) {
                                        list($categorytext, $answertext) = explode($optCategorySeparator, $llrow['answer']);
                                        if ($categorytext == '') {
                                            $defaultopts[] = array('code' => $llrow['code'], 'answer' => $answertext);
                                        } else {
                                            $optgroups[$categorytext][] = array('code' => $llrow['code'], 'answer' => $answertext);
                                        }
                                    }
                                    foreach ($optgroups as $categoryname => $optionlistarray) {
                                        $aDataentryoutput .= "<optgroup class=\"dropdowncategory\" label=\"" . $categoryname . "\">\n";
                                        foreach ($optionlistarray as $optionarray) {
                                            $aDataentryoutput .= "\t<option value='{$optionarray['code']}'";
                                            if ($idrow[$fname['fieldname']] == $optionarray['code']) {
                                                $aDataentryoutput .= " selected='selected'";
                                            }
                                            $aDataentryoutput .= ">{$optionarray['answer']}</option>\n";
                                        }
                                        $aDataentryoutput .= "</optgroup>\n";
                                    }
                                    foreach ($defaultopts as $optionarray) {
                                        $aDataentryoutput .= "<option value='{$optionarray['code']}'";
                                        if ($idrow[$fname['fieldname']] == $optionarray['code']) {
                                            $aDataentryoutput .= " selected='selected'";
                                        }
                                        $aDataentryoutput .= ">{$optionarray['answer']}</option>\n";
                                    }
                                }
                                $oquery = "SELECT other FROM {{questions}} WHERE qid={$fname['qid']} AND {{questions}}.language = '{$sDataEntryLanguage}'";
                                $oresult = dbExecuteAssoc($oquery) or safeDie("Couldn't get other for list question<br />" . $oquery . "<br />");
                                foreach ($oresult->readAll() as $orow) {
                                    $fother = $orow['other'];
                                }
                                if ($fother == "Y") {
                                    $aDataentryoutput .= "<option value='-oth-'";
                                    if ($idrow[$fname['fieldname']] == "-oth-") {
                                        $aDataentryoutput .= " selected='selected'";
                                    }
                                    $aDataentryoutput .= ">" . gT("Other") . "</option>\n";
                                }
                                $aDataentryoutput .= "\t</select>\n";
                            }
                            break;
                        case "O":
                            //LIST WITH COMMENT drop-down/radio-button list + textarea
                            $lquery = "SELECT * FROM {{answers}} WHERE qid={$fname['qid']} AND language = '{$sDataEntryLanguage}' ORDER BY sortorder, answer";
                            $lresult = dbExecuteAssoc($lquery);
                            $aDataentryoutput .= "\t<select name='{$fname['fieldname']}' class='form-control'>\n" . "<option value=''";
                            if ($idrow[$fname['fieldname']] == "") {
                                $aDataentryoutput .= " selected='selected'";
                            }
                            $aDataentryoutput .= ">" . gT("Please choose") . "..</option>\n";
                            foreach ($lresult->readAll() as $llrow) {
                                $aDataentryoutput .= "<option value='{$llrow['code']}'";
                                if ($idrow[$fname['fieldname']] == $llrow['code']) {
                                    $aDataentryoutput .= " selected='selected'";
                                }
                                $aDataentryoutput .= ">{$llrow['answer']}</option>\n";
                            }
                            $fname = next($fnames);
                            $aDataentryoutput .= "\t</select>\n" . "\t<br />\n" . "\t<textarea cols='45' rows='5' name='{$fname['fieldname']}'>" . htmlspecialchars($idrow[$fname['fieldname']]) . "</textarea>\n";
                            break;
                        case "R":
                            //RANKING TYPE QUESTION
                            $thisqid = $fname['qid'];
                            $currentvalues = array();
                            $myfname = $fname['sid'] . 'X' . $fname['gid'] . 'X' . $fname['qid'];
                            $aDataentryoutput .= '<div id="question' . $thisqid . '" class="ranking-answers"><ul class="answers-list">';
                            while (isset($fname['type']) && $fname['type'] == "R" && $fname['qid'] == $thisqid) {
                                //Let's get all the existing values into an array
                                if ($idrow[$fname['fieldname']]) {
                                    $currentvalues[] = $idrow[$fname['fieldname']];
                                }
                                $fname = next($fnames);
                            }
                            $ansquery = "SELECT * FROM {{answers}} WHERE language = '{$sDataEntryLanguage}' AND qid={$thisqid} ORDER BY sortorder, answer";
                            $ansresult = Yii::app()->db->createCommand($ansquery)->query()->readAll();
                            //Checked
                            $anscount = count($ansresult);
                            $answers = array();
                            foreach ($ansresult as $ansrow) {
                                $answers[] = $ansrow;
                            }
                            for ($i = 1; $i <= $anscount; $i++) {
                                $aDataentryoutput .= "\n<li class=\"select-item\">";
                                $aDataentryoutput .= "<label for=\"answer{$myfname}{$i}\">";
                                if ($i == 1) {
                                    $aDataentryoutput .= gT('First choice');
                                } else {
                                    $aDataentryoutput .= gT('Next choice');
                                }
                                $aDataentryoutput .= "</label>";
                                $aDataentryoutput .= "<select name=\"{$myfname}{$i}\" id=\"answer{$myfname}{$i}\" class='form-control'>\n";
                                !isset($currentvalues[$i - 1]) ? $selected = " selected=\"selected\"" : ($selected = "");
                                $aDataentryoutput .= "\t<option value=\"\" {$selected}>" . gT('None') . "</option>\n";
                                foreach ($answers as $ansrow) {
                                    isset($currentvalues[$i - 1]) && $currentvalues[$i - 1] == $ansrow['code'] ? $selected = " selected=\"selected\"" : ($selected = "");
                                    $aDataentryoutput .= "\t<option value=\"" . $ansrow['code'] . "\" {$selected}>" . flattenText($ansrow['answer']) . "</option>\n";
                                }
                                $aDataentryoutput .= "</select\n";
                                $aDataentryoutput .= "</li>";
                            }
                            $aDataentryoutput .= '</ul>';
                            $aDataentryoutput .= "<div style='display:none' id='ranking-{$thisqid}-maxans'>{$anscount}</div>" . "<div style='display:none' id='ranking-{$thisqid}-minans'>0</div>" . "<div style='display:none' id='ranking-{$thisqid}-name'>javatbd{$myfname}</div>";
                            $aDataentryoutput .= "<div style=\"display:none\">";
                            foreach ($answers as $ansrow) {
                                $aDataentryoutput .= "<div id=\"htmlblock-{$thisqid}-{$ansrow['code']}\">{$ansrow['answer']}</div>";
                            }
                            $aDataentryoutput .= "</div>";
                            $aDataentryoutput .= '</div>';
                            App()->getClientScript()->registerPackage('jquery-actual');
                            App()->getClientScript()->registerScriptFile(App()->getAssetManager()->publish(SCRIPT_PATH . 'ranking.js'));
                            App()->getClientScript()->registerCssFile(App()->getAssetManager()->publish(dirname(Yii::app()->request->scriptFile) . '/styles-public/ranking.css'));
                            $aDataentryoutput .= "<script type='text/javascript'>\n" . "  <!--\n" . "var aRankingTranslations = {\n                                         choicetitle: '" . gT("Your Choices", 'js') . "',\n                                         ranktitle: '" . gT("Your Ranking", 'js') . "'\n                                        };\n" . "function checkconditions(){};" . "\$(function() {" . " doDragDropRank({$thisqid},0,true,true);\n" . "});\n" . " -->\n" . "</script>\n";
                            unset($answers);
                            $fname = prev($fnames);
                            break;
                        case "M":
                            //Multiple choice checkbox
                            $qidattributes = getQuestionAttributeValues($fname['qid']);
                            if (trim($qidattributes['display_columns']) != '') {
                                $dcols = $qidattributes['display_columns'];
                            } else {
                                $dcols = 0;
                            }
                            //                    while ($fname[3] == "M" && $question != "" && $question == $fname['type'])
                            $thisqid = $fname['qid'];
                            while ($fname['qid'] == $thisqid) {
                                $fieldn = substr($fname['fieldname'], 0, strlen($fname['fieldname']));
                                //$aDataentryoutput .= substr($fname['fieldname'], strlen($fname['fieldname'])-5, 5)."<br />\n";
                                if (substr($fname['fieldname'], -5) == "other") {
                                    $aDataentryoutput .= "\t<input type='text' name='{$fname['fieldname']}' value='" . htmlspecialchars($idrow[$fname['fieldname']], ENT_QUOTES) . "' />\n";
                                } else {
                                    $aDataentryoutput .= "<div class='checkbox'>\t<input type='checkbox' class='checkboxbtn' name='{$fname['fieldname']}' id='{$fname['fieldname']}' value='Y'";
                                    if ($idrow[$fname['fieldname']] == "Y") {
                                        $aDataentryoutput .= " checked";
                                    }
                                    $aDataentryoutput .= " /><label for='{$fname['fieldname']}'>{$fname['subquestion']}</label></div>\n";
                                }
                                $fname = next($fnames);
                            }
                            $fname = prev($fnames);
                            break;
                        case "I":
                            //Language Switch
                            $lquery = "SELECT * FROM {{answers}} WHERE qid={$fname['qid']} AND language = '{$sDataEntryLanguage}' ORDER BY sortorder, answer";
                            $lresult = dbExecuteAssoc($lquery);
                            $slangs = Survey::model()->findByPk($surveyid)->additionalLanguages;
                            $baselang = Survey::model()->findByPk($surveyid)->language;
                            array_unshift($slangs, $baselang);
                            $aDataentryoutput .= "<select name='{$fname['fieldname']}' class='form-control'>\n";
                            $aDataentryoutput .= "<option value=''";
                            if ($idrow[$fname['fieldname']] == "") {
                                $aDataentryoutput .= " selected='selected'";
                            }
                            $aDataentryoutput .= ">" . gT("Please choose") . "..</option>\n";
                            foreach ($slangs as $lang) {
                                $aDataentryoutput .= "<option value='{$lang}'";
                                if ($lang == $idrow[$fname['fieldname']]) {
                                    $aDataentryoutput .= " selected='selected'";
                                }
                                $aDataentryoutput .= ">" . getLanguageNameFromCode($lang, false) . "</option>\n";
                            }
                            $aDataentryoutput .= "</select>";
                            break;
                        case "P":
                            //Multiple choice with comments checkbox + text
                            $aDataentryoutput .= "<table>\n";
                            while (isset($fname) && $fname['type'] == "P") {
                                $thefieldname = $fname['fieldname'];
                                if (substr($thefieldname, -7) == "comment") {
                                    $aDataentryoutput .= "<td><input type='text' name='{$fname['fieldname']}' size='50' value='" . htmlspecialchars($idrow[$fname['fieldname']], ENT_QUOTES) . "' /></td>\n" . "\t</tr>\n";
                                } elseif (substr($fname['fieldname'], -5) == "other") {
                                    $aDataentryoutput .= "\t<tr>\n" . "<td>\n" . "\t<input type='text' name='{$fname['fieldname']}' size='30' value='" . htmlspecialchars($idrow[$fname['fieldname']], ENT_QUOTES) . "' />\n" . "</td>\n" . "<td>\n";
                                    $fname = next($fnames);
                                    $aDataentryoutput .= "\t<input type='text' name='{$fname['fieldname']}' size='50' value='" . htmlspecialchars($idrow[$fname['fieldname']], ENT_QUOTES) . "' />\n" . "</td>\n" . "\t</tr>\n";
                                } else {
                                    $aDataentryoutput .= "\t<tr>\n" . "<td><div class='checkbox'><input type='checkbox' class='checkboxbtn' name=\"{$fname['fieldname']}\" id=\"{$fname['fieldname']}\" value='Y'";
                                    if ($idrow[$fname['fieldname']] == "Y") {
                                        $aDataentryoutput .= " checked";
                                    }
                                    $aDataentryoutput .= " /><label for=\"{$fname['fieldname']}\">{$fname['subquestion']}</label></div></td>\n";
                                }
                                $fname = next($fnames);
                            }
                            $aDataentryoutput .= "</table>\n";
                            $fname = prev($fnames);
                            break;
                        case "|":
                            //FILE UPLOAD
                            $aDataentryoutput .= "<table>\n";
                            if ($fname['aid'] !== 'filecount' && isset($idrow[$fname['fieldname'] . '_filecount']) && $idrow[$fname['fieldname'] . '_filecount'] > 0) {
                                //file metadata
                                $metadata = json_decode($idrow[$fname['fieldname']], true);
                                $qAttributes = getQuestionAttributeValues($fname['qid']);
                                for ($i = 0; $i < $qAttributes['max_num_of_files'] && isset($metadata[$i]); $i++) {
                                    if ($qAttributes['show_title']) {
                                        $aDataentryoutput .= '<tr><td>Title    </td><td><input type="text" class="' . $fname['fieldname'] . '" id="' . $fname['fieldname'] . '_title_' . $i . '" name="title"    size=50 value="' . htmlspecialchars($metadata[$i]["title"]) . '" /></td></tr>';
                                    }
                                    if ($qAttributes['show_comment']) {
                                        $aDataentryoutput .= '<tr><td >Comment  </td><td><input type="text" class="' . $fname['fieldname'] . '" id="' . $fname['fieldname'] . '_comment_' . $i . '" name="comment"  size=50 value="' . htmlspecialchars($metadata[$i]["comment"]) . '" /></td></tr>';
                                    }
                                    $aDataentryoutput .= '<tr><td>        File name</td><td><input   class="' . $fname['fieldname'] . '" id="' . $fname['fieldname'] . '_name_' . $i . '" name="name" size=50 value="' . htmlspecialchars(rawurldecode($metadata[$i]["name"])) . '" /></td></tr>' . '<tr><td></td><td><input type="hidden" class="' . $fname['fieldname'] . '" id="' . $fname['fieldname'] . '_size_' . $i . '" name="size" size=50 value="' . htmlspecialchars($metadata[$i]["size"]) . '" /></td></tr>' . '<tr><td></td><td><input type="hidden" class="' . $fname['fieldname'] . '" id="' . $fname['fieldname'] . '_ext_' . $i . '" name="ext" size=50 value="' . htmlspecialchars($metadata[$i]["ext"]) . '" /></td></tr>' . '<tr><td></td><td><input type="hidden"  class="' . $fname['fieldname'] . '" id="' . $fname['fieldname'] . '_filename_' . $i . '" name="filename" size=50 value="' . htmlspecialchars(rawurldecode($metadata[$i]["filename"])) . '" /></td></tr>';
                                }
                                $aDataentryoutput .= '<tr><td></td><td><input type="hidden" id="' . $fname['fieldname'] . '" name="' . $fname['fieldname'] . '" size=50 value="' . htmlspecialchars($idrow[$fname['fieldname']]) . '" /></td></tr>';
                                $aDataentryoutput .= '</table>';
                                $aDataentryoutput .= '<script type="text/javascript">
                                $(function() {
                                $(".' . $fname['fieldname'] . '").keyup(function() {
                                var filecount = $("#' . $fname['fieldname'] . '_filecount").val();
                                var jsonstr = "[";
                                var i;
                                for (i = 0; i < filecount; i++)
                                {
                                if (i != 0)
                                jsonstr += ",";
                                jsonstr += \'{"title":"\'+$("#' . $fname['fieldname'] . '_title_"+i).val()+\'",\';
                                jsonstr += \'"comment":"\'+$("#' . $fname['fieldname'] . '_comment_"+i).val()+\'",\';
                                jsonstr += \'"size":"\'+$("#' . $fname['fieldname'] . '_size_"+i).val()+\'",\';
                                jsonstr += \'"ext":"\'+$("#' . $fname['fieldname'] . '_ext_"+i).val()+\'",\';
                                jsonstr += \'"filename":"\'+$("#' . $fname['fieldname'] . '_filename_"+i).val()+\'",\';
                                jsonstr += \'"name":"\'+encodeURIComponent($("#' . $fname['fieldname'] . '_name_"+i).val())+\'"}\';
                                }
                                jsonstr += "]";
                                $("#' . $fname['fieldname'] . '").val(jsonstr);

                                });
                                });
                                </script>';
                            } else {
                                //file count
                                $aDataentryoutput .= '<input readonly id="' . $fname['fieldname'] . '" name="' . $fname['fieldname'] . '" value ="' . htmlspecialchars($idrow[$fname['fieldname']]) . '" /></td></table>';
                            }
                            break;
                        case "N":
                            //NUMERICAL TEXT
                            $aDataentryoutput .= "\t<input type='text' name='{$fname['fieldname']}' value='{$idrow[$fname['fieldname']]}' " . "onkeypress=\"return goodchars(event,'0123456789.,')\" />\n";
                            break;
                        case "S":
                            //SHORT FREE TEXT
                            $aDataentryoutput .= "\t<input type='text' name='{$fname['fieldname']}' value='" . htmlspecialchars($idrow[$fname['fieldname']], ENT_QUOTES) . "' />\n";
                            break;
                        case "T":
                            //LONG FREE TEXT
                            $aDataentryoutput .= "\t<textarea rows='5' cols='45' name='{$fname['fieldname']}'>" . htmlspecialchars($idrow[$fname['fieldname']], ENT_QUOTES) . "</textarea>\n";
                            break;
                        case "U":
                            //HUGE FREE TEXT
                            $aDataentryoutput .= "\t<textarea rows='50' cols='70' name='{$fname['fieldname']}'>" . htmlspecialchars($idrow[$fname['fieldname']], ENT_QUOTES) . "</textarea>\n";
                            break;
                        case "Y":
                            //YES/NO radio-buttons
                            $aDataentryoutput .= "\t<select name='{$fname['fieldname']}' class='form-control'>\n" . "<option value=''";
                            if ($idrow[$fname['fieldname']] == "") {
                                $aDataentryoutput .= " selected='selected'";
                            }
                            $aDataentryoutput .= ">" . gT("Please choose") . "..</option>\n" . "<option value='Y'";
                            if ($idrow[$fname['fieldname']] == "Y") {
                                $aDataentryoutput .= " selected='selected'";
                            }
                            $aDataentryoutput .= ">" . gT("Yes") . "</option>\n" . "<option value='N'";
                            if ($idrow[$fname['fieldname']] == "N") {
                                $aDataentryoutput .= " selected='selected'";
                            }
                            $aDataentryoutput .= ">" . gT("No") . "</option>\n" . "\t</select>\n";
                            break;
                        case "A":
                            //ARRAY (5 POINT CHOICE) radio-buttons
                            $aDataentryoutput .= "<table>\n";
                            $thisqid = $fname['qid'];
                            while ($fname['qid'] == $thisqid) {
                                $aDataentryoutput .= "\t<tr>\n" . "<td align='right'>{$fname['subquestion']}</td>\n" . "<td>\n";
                                for ($j = 1; $j <= 5; $j++) {
                                    $aDataentryoutput .= '<span class="five-point">';
                                    $aDataentryoutput .= "\t<input type='radio' class='' name='{$fname['fieldname']}' id='5-point-radio-{$fname['fieldname']}' value='{$j}'";
                                    if ($idrow[$fname['fieldname']] == $j) {
                                        $aDataentryoutput .= " checked";
                                    }
                                    $aDataentryoutput .= " /><label for='5-point-radio-{$fname['fieldname']}'>{$j}</label>&nbsp;\n";
                                    $aDataentryoutput .= '</span>';
                                }
                                $aDataentryoutput .= "</td>\n" . "\t</tr>\n";
                                $fname = next($fnames);
                            }
                            $aDataentryoutput .= "</table>\n";
                            $fname = prev($fnames);
                            break;
                        case "B":
                            //ARRAY (10 POINT CHOICE) radio-buttons
                            $aDataentryoutput .= "<table>\n";
                            $thisqid = $fname['qid'];
                            while ($fname['qid'] == $thisqid) {
                                $fieldn = substr($fname['fieldname'], 0, strlen($fname['fieldname']));
                                $aDataentryoutput .= "\t<tr>\n" . "<td align='right'>{$fname['subquestion']}</td>\n" . "<td>\n";
                                for ($j = 1; $j <= 10; $j++) {
                                    $aDataentryoutput .= '<span class="ten-point">';
                                    $aDataentryoutput .= "\t<input type='radio' class='' name='{$fname['fieldname']}' id='ten-point-{$fname['fieldname']}-{$j}' value='{$j}'";
                                    if ($idrow[$fname['fieldname']] == $j) {
                                        $aDataentryoutput .= " checked";
                                    }
                                    $aDataentryoutput .= " /><label for='ten-point-{$fname['fieldname']}-{$j}'>{$j}</label>&nbsp;\n";
                                    $aDataentryoutput .= '</span>';
                                }
                                $aDataentryoutput .= "</td>\n" . "\t</tr>\n";
                                $fname = next($fnames);
                            }
                            $fname = prev($fnames);
                            $aDataentryoutput .= "</table>\n";
                            break;
                        case "C":
                            //ARRAY (YES/UNCERTAIN/NO) radio-buttons
                            $aDataentryoutput .= "<table>\n";
                            $thisqid = $fname['qid'];
                            while ($fname['qid'] == $thisqid) {
                                $fieldn = substr($fname['fieldname'], 0, strlen($fname['fieldname']));
                                $aDataentryoutput .= "\t<tr>\n" . "<td align='right'>{$fname['subquestion']}</td>\n" . "<td>\n" . "\t<input type='radio' class='' name='{$fname['fieldname']}' value='Y'";
                                if ($idrow[$fname['fieldname']] == "Y") {
                                    $aDataentryoutput .= " checked";
                                }
                                $aDataentryoutput .= " />" . gT("Yes") . "&nbsp;\n" . "\t<input type='radio' class='' name='{$fname['fieldname']}' value='U'";
                                if ($idrow[$fname['fieldname']] == "U") {
                                    $aDataentryoutput .= " checked";
                                }
                                $aDataentryoutput .= " />" . gT("Uncertain") . "&nbsp;\n" . "\t<input type='radio' class='' name='{$fname['fieldname']}' value='N'";
                                if ($idrow[$fname['fieldname']] == "N") {
                                    $aDataentryoutput .= " checked";
                                }
                                $aDataentryoutput .= " />" . gT("No") . "&nbsp;\n" . "</td>\n" . "\t</tr>\n";
                                $fname = next($fnames);
                            }
                            $fname = prev($fnames);
                            $aDataentryoutput .= "</table>\n";
                            break;
                        case "E":
                            //ARRAY (Increase/Same/Decrease) radio-buttons
                            $aDataentryoutput .= "<table>\n";
                            $thisqid = $fname['qid'];
                            while ($fname['qid'] == $thisqid) {
                                $fieldn = substr($fname['fieldname'], 0, strlen($fname['fieldname']));
                                $aDataentryoutput .= "\t<tr>\n" . "<td align='right'>{$fname['subquestion']}</td>\n" . "<td>\n" . "\t<input type='radio' class='' name='{$fname['fieldname']}' value='I'";
                                if ($idrow[$fname['fieldname']] == "I") {
                                    $aDataentryoutput .= " checked";
                                }
                                $aDataentryoutput .= " />Increase&nbsp;\n" . "\t<input type='radio' class='' name='{$fname['fieldname']}' value='S'";
                                if ($idrow[$fname['fieldname']] == "I") {
                                    $aDataentryoutput .= " checked";
                                }
                                $aDataentryoutput .= " />Same&nbsp;\n" . "\t<input type='radio' class='' name='{$fname['fieldname']}' value='D'";
                                if ($idrow[$fname['fieldname']] == "D") {
                                    $aDataentryoutput .= " checked";
                                }
                                $aDataentryoutput .= " />Decrease&nbsp;\n" . "</td>\n" . "\t</tr>\n";
                                $fname = next($fnames);
                            }
                            $fname = prev($fnames);
                            $aDataentryoutput .= "</table>\n";
                            break;
                        case "F":
                            //ARRAY (Flexible Labels)
                        //ARRAY (Flexible Labels)
                        case "H":
                        case "1":
                            $aDataentryoutput .= "<table>\n";
                            $thisqid = $fname['qid'];
                            while (isset($fname['qid']) && $fname['qid'] == $thisqid) {
                                $fieldn = substr($fname['fieldname'], 0, strlen($fname['fieldname']));
                                $aDataentryoutput .= "\t<tr>\n" . "<td>{$fname['subquestion']}";
                                if (isset($fname['scale'])) {
                                    $aDataentryoutput .= " (" . $fname['scale'] . ')';
                                }
                                $aDataentryoutput .= "</td>\n";
                                $scale_id = 0;
                                if (isset($fname['scale_id'])) {
                                    $scale_id = $fname['scale_id'];
                                }
                                $fquery = "SELECT * FROM {{answers}} WHERE qid='{$fname['qid']}' and scale_id={$scale_id} and language='{$sDataEntryLanguage}' order by sortorder, answer";
                                $fresult = dbExecuteAssoc($fquery);
                                $aDataentryoutput .= "<td>\n";
                                foreach ($fresult->readAll() as $frow) {
                                    $aDataentryoutput .= "\t<input type='radio' class='' name='{$fname['fieldname']}' value='{$frow['code']}'";
                                    if ($idrow[$fname['fieldname']] == $frow['code']) {
                                        $aDataentryoutput .= " checked";
                                    }
                                    $aDataentryoutput .= " />" . $frow['answer'] . "&nbsp;\n";
                                }
                                //Add 'No Answer'
                                $aDataentryoutput .= "\t<input type='radio' class='' name='{$fname['fieldname']}' value=''";
                                if ($idrow[$fname['fieldname']] == '') {
                                    $aDataentryoutput .= " checked";
                                }
                                $aDataentryoutput .= " />" . gT("No answer") . "&nbsp;\n";
                                $aDataentryoutput .= "</td>\n" . "\t</tr>\n";
                                $fname = next($fnames);
                            }
                            $fname = prev($fnames);
                            $aDataentryoutput .= "</table>\n";
                            break;
                        case ":":
                            //ARRAY (Multi Flexi) (Numbers)
                            $qidattributes = getQuestionAttributeValues($fname['qid']);
                            if (trim($qidattributes['multiflexible_max']) != '' && trim($qidattributes['multiflexible_min']) == '') {
                                $maxvalue = $qidattributes['multiflexible_max'];
                                $minvalue = 1;
                            }
                            if (trim($qidattributes['multiflexible_min']) != '' && trim($qidattributes['multiflexible_max']) == '') {
                                $minvalue = $qidattributes['multiflexible_min'];
                                $maxvalue = $qidattributes['multiflexible_min'] + 10;
                            }
                            if (trim($qidattributes['multiflexible_min']) == '' && trim($qidattributes['multiflexible_max']) == '') {
                                $minvalue = 1;
                                $maxvalue = 10;
                            }
                            if (trim($qidattributes['multiflexible_min']) != '' && trim($qidattributes['multiflexible_max']) != '') {
                                if ($qidattributes['multiflexible_min'] < $qidattributes['multiflexible_max']) {
                                    $minvalue = $qidattributes['multiflexible_min'];
                                    $maxvalue = $qidattributes['multiflexible_max'];
                                }
                            }
                            if (trim($qidattributes['multiflexible_step']) != '') {
                                $stepvalue = $qidattributes['multiflexible_step'];
                            } else {
                                $stepvalue = 1;
                            }
                            if ($qidattributes['multiflexible_checkbox'] != 0) {
                                $minvalue = 0;
                                $maxvalue = 1;
                                $stepvalue = 1;
                            }
                            $aDataentryoutput .= "<table>\n";
                            $thisqid = $fname['qid'];
                            while (isset($fname['qid']) && $fname['qid'] == $thisqid) {
                                $fieldn = substr($fname['fieldname'], 0, strlen($fname['fieldname']));
                                $aDataentryoutput .= "\t<tr>\n" . "<td>{$fname['subquestion1']}:{$fname['subquestion2']}</td>\n";
                                $aDataentryoutput .= "<td>\n";
                                if ($qidattributes['input_boxes'] != 0) {
                                    $aDataentryoutput .= "\t<input type='text' name='{$fname['fieldname']}' value='";
                                    if (!empty($idrow[$fname['fieldname']])) {
                                        $aDataentryoutput .= $idrow[$fname['fieldname']];
                                    }
                                    $aDataentryoutput .= "' size=4 />";
                                } else {
                                    $aDataentryoutput .= "\t<select name='{$fname['fieldname']}' class='form-control'>\n";
                                    $aDataentryoutput .= "<option value=''>...</option>\n";
                                    for ($ii = $minvalue; $ii <= $maxvalue; $ii += $stepvalue) {
                                        $aDataentryoutput .= "<option value='{$ii}'";
                                        if ($idrow[$fname['fieldname']] == $ii) {
                                            $aDataentryoutput .= " selected";
                                        }
                                        $aDataentryoutput .= ">{$ii}</option>\n";
                                    }
                                }
                                $aDataentryoutput .= "</td>\n" . "\t</tr>\n";
                                $fname = next($fnames);
                            }
                            $fname = prev($fnames);
                            $aDataentryoutput .= "</table>\n";
                            break;
                        case ";":
                            //ARRAY (Multi Flexi)
                            $aDataentryoutput .= "<table>\n";
                            $thisqid = $fname['qid'];
                            while (isset($fname['qid']) && $fname['qid'] == $thisqid) {
                                $fieldn = substr($fname['fieldname'], 0, strlen($fname['fieldname']));
                                $aDataentryoutput .= "\t<tr>\n" . "<td>{$fname['subquestion1']}:{$fname['subquestion2']}</td>\n";
                                $aDataentryoutput .= "<td>\n";
                                $aDataentryoutput .= "\t<input type='text' name='{$fname['fieldname']}' value='";
                                if (!empty($idrow[$fname['fieldname']])) {
                                    $aDataentryoutput .= $idrow[$fname['fieldname']];
                                }
                                $aDataentryoutput .= "' /></td>\n" . "\t</tr>\n";
                                $fname = next($fnames);
                            }
                            $fname = prev($fnames);
                            $aDataentryoutput .= "</table>\n";
                            break;
                        case "token":
                            if (Permission::model()->hasSurveyPermission($surveyid, 'tokens', 'update')) {
                                $aDataentryoutput .= CHtml::textField($fname['fieldname'], $idrow[$fname['fieldname']]);
                            } else {
                                $aDataentryoutput .= CHtml::textField($fname['fieldname'], $idrow[$fname['fieldname']], array('disabled' => 'disabled'));
                            }
                            break;
                        case "submitdate":
                        case "startlanguage":
                        default:
                            $aDataentryoutput .= "\t<input type='text' name='{$fname['fieldname']}' value='" . $idrow[$fname['fieldname']] . "' />\n";
                            break;
                    }
                    $aDataentryoutput .= "        </td>\n                    </tr>\n";
                } while ($fname = next($fnames));
            }
            $aDataentryoutput .= "</table>\n" . "<p>\n";
            $aData['sDataEntryLanguage'] = $sDataEntryLanguage;
            if (!Permission::model()->hasSurveyPermission($surveyid, 'responses', 'update')) {
                // if you are not survey owner or super admin you cannot modify responses
                $aDataentryoutput .= "<p><input type='button' value='" . gT("Save") . "' disabled='disabled'/></p>\n";
            } elseif ($subaction == "edit" && Permission::model()->hasSurveyPermission($surveyid, 'responses', 'update')) {
                $aData['part'] = 'edit';
                $aDataentryoutput .= $this->getController()->renderPartial('/admin/dataentry/edit', $aData, TRUE);
            } elseif ($subaction == "editsaved" && Permission::model()->hasSurveyPermission($surveyid, 'responses', 'update')) {
                $aData['part'] = 'editsaved';
                $aDataentryoutput .= $this->getController()->renderPartial('/admin/dataentry/edit', $aData, TRUE);
            }
            $aDataentryoutput .= "</form>\n";
            $aViewUrls['output'] = $aDataentryoutput;
            $aData['sidemenu']['state'] = false;
            $aData['menu']['edition'] = true;
            $aData['menu']['save'] = true;
            $aData['menu']['close'] = true;
            //$aData['menu']['savebutton'] = 'frmeditgroup';
            $this->_renderWrappedTemplate('dataentry', $aViewUrls, $aData);
        }
    }
/**
* This function returns a count of the number of saved responses to a survey
*
* @param mixed $surveyid Survey ID
*/
function getSavedCount($surveyid)
{
    $surveyid = (int) $surveyid;
    return SavedControl::model()->getCountOfAll($surveyid);
}
Beispiel #4
0
 /**
  * Function responsible to deactivate a survey.
  *
  * @access public
  * @param int $iSurveyID
  * @return void
  */
 public function deactivate($iSurveyID = null)
 {
     $iSurveyID = Yii::app()->request->getPost('sid', $iSurveyID);
     $iSurveyID = sanitize_int($iSurveyID);
     $date = date('YmdHis');
     //'His' adds 24hours+minutes to name to allow multiple deactiviations in a day
     if (empty($_POST['ok'])) {
         if (!tableExists('survey_' . $iSurveyID)) {
             $_SESSION['flashmessage'] = gT("Error: Response table does not exist. Survey cannot be deactivated.");
             $this->getController()->redirect($this->getController()->createUrl("admin/survey/sa/view/surveyid/{$iSurveyID}"));
         }
         $aData['surveyid'] = $iSurveyID;
         $aData['date'] = $date;
         $aData['dbprefix'] = Yii::app()->db->tablePrefix;
         $aData['step1'] = true;
     } else {
         //See if there is a tokens table for this survey
         if (tableExists("{{tokens_{$iSurveyID}}}")) {
             $toldtable = Yii::app()->db->tablePrefix . "tokens_{$iSurveyID}";
             $tnewtable = Yii::app()->db->tablePrefix . "old_tokens_{$iSurveyID}_{$date}";
             if (Yii::app()->db->getDriverName() == 'pgsql') {
                 $tidDefault = Yii::app()->db->createCommand("SELECT pg_attrdef.adsrc FROM pg_attribute JOIN pg_class ON (pg_attribute.attrelid=pg_class.oid) JOIN pg_attrdef ON(pg_attribute.attrelid=pg_attrdef.adrelid AND pg_attribute.attnum=pg_attrdef.adnum) WHERE pg_class.relname='{$toldtable}' and pg_attribute.attname='tid'")->queryScalar();
                 if (preg_match("/nextval\\('(tokens_\\d+_tid_seq\\d*)'::regclass\\)/", $tidDefault, $matches)) {
                     $oldSeq = $matches[1];
                     $deactivateresult = Yii::app()->db->createCommand()->renameTable($oldSeq, $tnewtable . '_tid_seq');
                     $setsequence = "ALTER TABLE " . Yii::app()->db->quoteTableName($toldtable) . " ALTER COLUMN tid SET DEFAULT nextval('{$tnewtable}_tid_seq'::regclass);";
                     $deactivateresult = Yii::app()->db->createCommand($setsequence)->query();
                 }
             }
             $tdeactivateresult = Yii::app()->db->createCommand()->renameTable($toldtable, $tnewtable);
             $aData['tnewtable'] = $tnewtable;
             $aData['toldtable'] = $toldtable;
         }
         //Remove any survey_links to the CPDB
         SurveyLink::model()->deleteLinksBySurvey($iSurveyID);
         // IF there are any records in the saved_control table related to this survey, they have to be deleted
         $result = SavedControl::model()->deleteSomeRecords(array('sid' => $iSurveyID));
         //Yii::app()->db->createCommand($query)->query();
         $sOldSurveyTableName = Yii::app()->db->tablePrefix . "survey_{$iSurveyID}";
         $sNewSurveyTableName = Yii::app()->db->tablePrefix . "old_survey_{$iSurveyID}_{$date}";
         $aData['sNewSurveyTableName'] = $sNewSurveyTableName;
         //Update the autonumber_start in the survey properties
         $new_autonumber_start = 0;
         $query = "SELECT id FROM " . Yii::app()->db->quoteTableName($sOldSurveyTableName) . " ORDER BY id desc";
         $sLastID = Yii::app()->db->createCommand($query)->limit(1)->queryScalar();
         $new_autonumber_start = $sLastID + 1;
         $insertdata = array('autonumber_start' => $new_autonumber_start);
         $survey = Survey::model()->findByAttributes(array('sid' => $iSurveyID));
         $survey->autonumber_start = $new_autonumber_start;
         $survey->save();
         if (Yii::app()->db->getDriverName() == 'pgsql') {
             $idDefault = Yii::app()->db->createCommand("SELECT pg_attrdef.adsrc FROM pg_attribute JOIN pg_class ON (pg_attribute.attrelid=pg_class.oid) JOIN pg_attrdef ON(pg_attribute.attrelid=pg_attrdef.adrelid AND pg_attribute.attnum=pg_attrdef.adnum) WHERE pg_class.relname='{$sOldSurveyTableName}' and pg_attribute.attname='id'")->queryScalar();
             if (preg_match("/nextval\\('(survey_\\d+_id_seq\\d*)'::regclass\\)/", $idDefault, $matches)) {
                 $oldSeq = $matches[1];
                 $deactivateresult = Yii::app()->db->createCommand()->renameTable($oldSeq, $sNewSurveyTableName . '_id_seq');
                 $setsequence = "ALTER TABLE " . Yii::app()->db->quoteTableName($sOldSurveyTableName) . " ALTER COLUMN id SET DEFAULT nextval('{{{$sNewSurveyTableName}}}_id_seq'::regclass);";
                 $deactivateresult = Yii::app()->db->createCommand($setsequence)->query();
             }
         }
         $deactivateresult = Yii::app()->db->createCommand()->renameTable($sOldSurveyTableName, $sNewSurveyTableName);
         $insertdata = array('active' => 'N');
         $survey->active = 'N';
         $survey->save();
         $prow = Survey::model()->find('sid = :sid', array(':sid' => $iSurveyID));
         if ($prow->savetimings == "Y") {
             $sOldTimingsTableName = Yii::app()->db->tablePrefix . "survey_{$iSurveyID}_timings";
             $sNewTimingsTableName = Yii::app()->db->tablePrefix . "old_survey_{$iSurveyID}_timings_{$date}";
             $deactivateresult2 = Yii::app()->db->createCommand()->renameTable($sOldTimingsTableName, $sNewTimingsTableName);
             $deactivateresult = $deactivateresult && $deactivateresult2;
             $aData['sNewTimingsTableName'] = $sNewTimingsTableName;
         }
         $aData['surveyid'] = $iSurveyID;
         Yii::app()->db->schema->refresh();
     }
     $this->_renderWrappedTemplate('survey', 'deactivateSurvey_view', $aData);
 }
function loadanswers()
{
    Yii::trace('start', 'survey.loadanswers');
    global $surveyid;
    global $thissurvey, $thisstep;
    global $clienttoken;
    $clang = Yii::app()->lang;
    $scid = Yii::app()->request->getQuery('scid');
    if (Yii::app()->request->getParam('loadall') == "reload") {
        $sLoadName = Yii::app()->request->getParam('loadname');
        $sLoadPass = Yii::app()->request->getParam('loadpass');
        $oCriteria = new CDbCriteria();
        $oCriteria->join = "LEFT JOIN {{saved_control}} ON t.id={{saved_control}}.srid";
        $oCriteria->condition = "{{saved_control}}.sid=:sid";
        $aParams = array(':sid' => $surveyid);
        if (isset($scid)) {
            $oCriteria->addCondition("{{saved_control}}.scid=:scid");
            $aParams[':scid'] = $scid;
        }
        $oCriteria->addCondition("{{saved_control}}.identifier=:identifier");
        $aParams[':identifier'] = $sLoadName;
        if (in_array(Yii::app()->db->getDriverName(), array('mssql', 'sqlsrv', 'dblib'))) {
            // To be validated with mssql, think it's not needed
            $oCriteria->addCondition(" CAST({{saved_control}}.access_code as varchar(32))=:access_code");
        } else {
            $oCriteria->addCondition("{{saved_control}}.access_code=:access_code");
        }
        $aParams[':access_code'] = md5($sLoadPass);
    } elseif (isset($_SESSION['survey_' . $surveyid]['srid'])) {
        $oCriteria = new CDbCriteria();
        $oCriteria->condition = "id=:id";
        $aParams = array(':id' => $_SESSION['survey_' . $surveyid]['srid']);
    } else {
        return;
    }
    $oCriteria->params = $aParams;
    $oResponses = SurveyDynamic::model($surveyid)->find($oCriteria);
    if (!$oResponses) {
        return false;
    } else {
        //A match has been found. Let's load the values!
        //If this is from an email, build surveysession first
        $_SESSION['survey_' . $surveyid]['LEMtokenResume'] = true;
        // If survey come from reload (GET or POST); some value need to be found on saved_control, not on survey
        if (Yii::app()->request->getParam('loadall') == "reload") {
            $oSavedSurvey = SavedControl::model()->find("identifier=:identifier AND access_code=:access_code", array(":identifier" => $sLoadName, ":access_code" => md5($sLoadPass)));
            // We don't need to control if we have one, because we do the test before
            $_SESSION['survey_' . $surveyid]['scid'] = $oSavedSurvey->scid;
            $_SESSION['survey_' . $surveyid]['step'] = $oSavedSurvey->saved_thisstep > 1 ? $oSavedSurvey->saved_thisstep : 1;
            $thisstep = $_SESSION['survey_' . $surveyid]['step'] - 1;
            // deprecated ?
            $_SESSION['survey_' . $surveyid]['srid'] = $oSavedSurvey->srid;
            // Seems OK without
            $_SESSION['survey_' . $surveyid]['refurl'] = $oSavedSurvey->refurl;
        }
        // Get if survey is been answered
        $submitdate = $oResponses->submitdate;
        $aRow = $oResponses->attributes;
        foreach ($aRow as $column => $value) {
            if ($column == "token") {
                $clienttoken = $value;
                $token = $value;
            } elseif ($column == 'lastpage' && !isset($_SESSION['survey_' . $surveyid]['step'])) {
                if (is_null($submitdate) || $submitdate == "N") {
                    $_SESSION['survey_' . $surveyid]['step'] = $value > 1 ? $value : 1;
                    $thisstep = $_SESSION['survey_' . $surveyid]['step'] - 1;
                } else {
                    $_SESSION['survey_' . $surveyid]['maxstep'] = $value > 1 ? $value : 1;
                }
            } elseif ($column == "datestamp") {
                $_SESSION['survey_' . $surveyid]['datestamp'] = $value;
            }
            if ($column == "startdate") {
                $_SESSION['survey_' . $surveyid]['startdate'] = $value;
            } else {
                //Only make session variables for those in insertarray[]
                if (in_array($column, $_SESSION['survey_' . $surveyid]['insertarray']) && isset($_SESSION['survey_' . $surveyid]['fieldmap'][$column])) {
                    if (($_SESSION['survey_' . $surveyid]['fieldmap'][$column]['type'] == 'N' || $_SESSION['survey_' . $surveyid]['fieldmap'][$column]['type'] == 'K' || $_SESSION['survey_' . $surveyid]['fieldmap'][$column]['type'] == 'D') && $value == null) {
                        // For type N,K,D NULL in DB is to be considered as NoAnswer in any case.
                        // We need to set the _SESSION[field] value to '' in order to evaluate conditions.
                        // This is especially important for the deletenonvalue feature,
                        // otherwise we would erase any answer with condition such as EQUALS-NO-ANSWER on such
                        // question types (NKD)
                        $_SESSION['survey_' . $surveyid][$column] = '';
                    } else {
                        $_SESSION['survey_' . $surveyid][$column] = $value;
                    }
                }
                // if (in_array(
            }
            // else
        }
        // foreach
        return true;
    }
}
 /**
  * Write values to database.
  * @param <type> $updatedValues
  * @param <boolean> $finished - true if the survey needs to be finalized
  */
 private function _UpdateValuesInDatabase($updatedValues, $finished = false)
 {
     //  TODO - now that using $this->updatedValues, may be able to remove local copies of it (unless needed by other sub-systems)
     $updatedValues = $this->updatedValues;
     $message = '';
     if (!$this->surveyOptions['active'] || $this->sPreviewMode) {
         return $message;
     }
     if (!isset($_SESSION[$this->sessid]['srid'])) {
         $_SESSION[$this->sessid]['datestamp'] = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $this->surveyOptions['timeadjust']);
         // Create initial insert row for this record
         $today = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $this->surveyOptions['timeadjust']);
         $sdata = array("startlanguage" => $this->surveyOptions['startlanguage']);
         if ($this->surveyOptions['anonymized'] == false) {
             $sdata['token'] = $this->surveyOptions['token'];
         }
         if ($this->surveyOptions['datestamp'] == true) {
             $sdata['datestamp'] = $_SESSION[$this->sessid]['datestamp'];
             $sdata['startdate'] = $_SESSION[$this->sessid]['datestamp'];
         }
         if ($this->surveyOptions['ipaddr'] == true) {
             $sdata['ipaddr'] = getIPAddress();
         }
         if ($this->surveyOptions['refurl'] == true) {
             if (isset($_SESSION[$this->sessid]['refurl'])) {
                 $sdata['refurl'] = $_SESSION[$this->sessid]['refurl'];
             } else {
                 $sdata['refurl'] = getenv("HTTP_REFERER");
             }
         }
         $sdata = array_filter($sdata);
         SurveyDynamic::sid($this->sid);
         $oSurvey = new SurveyDynamic();
         $iNewID = $oSurvey->insertRecords($sdata);
         if ($iNewID) {
             $srid = $iNewID;
             $_SESSION[$this->sessid]['srid'] = $iNewID;
         } else {
             $message .= $this->gT("Unable to insert record into survey table");
             // TODO - add SQL error?
             echo submitfailed('');
             // TODO - report SQL error?
         }
         //Insert Row for Timings, if needed
         if ($this->surveyOptions['savetimings']) {
             SurveyTimingDynamic::sid($this->sid);
             $oSurveyTimings = new SurveyTimingDynamic();
             $tdata = array('id' => $srid, 'interviewtime' => 0);
             switchMSSQLIdentityInsert("survey_{$this->sid}_timings", true);
             $iNewID = $oSurveyTimings->insertRecords($tdata);
             switchMSSQLIdentityInsert("survey_{$this->sid}_timings", false);
         }
     }
     if (count($updatedValues) > 0 || $finished) {
         $query = 'UPDATE ' . $this->surveyOptions['tablename'] . ' SET ';
         $setter = array();
         switch ($this->surveyMode) {
             case 'question':
                 $thisstep = $this->currentQuestionSeq;
                 break;
             case 'group':
                 $thisstep = $this->currentGroupSeq;
                 break;
             case 'survey':
                 $thisstep = 1;
                 break;
         }
         $setter[] = dbQuoteID('lastpage') . "=" . dbQuoteAll($thisstep);
         if ($this->surveyOptions['datestamp'] && isset($_SESSION[$this->sessid]['datestamp'])) {
             $_SESSION[$this->sessid]['datestamp'] = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $this->surveyOptions['timeadjust']);
             $setter[] = dbQuoteID('datestamp') . "=" . dbQuoteAll(dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $this->surveyOptions['timeadjust']));
         }
         if ($this->surveyOptions['ipaddr']) {
             $setter[] = dbQuoteID('ipaddr') . "=" . dbQuoteAll(getIPAddress());
         }
         foreach ($updatedValues as $key => $value) {
             $val = is_null($value) ? NULL : $value['value'];
             $type = is_null($value) ? NULL : $value['type'];
             // Clean up the values to cope with database storage requirements
             switch ($type) {
                 case 'D':
                     //DATE
                     if (trim($val) == '' || $val == "INVALID") {
                         $val = NULL;
                         // since some databases can't store blanks in date fields
                     }
                     // otherwise will already be in yyyy-mm-dd format after ProcessCurrentResponses()
                     break;
                 case '|':
                     //File upload
                     // This block can be removed once we require 5.3 or later
                     if (function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc()) {
                         $val = addslashes($val);
                     }
                     break;
                 case 'N':
                     //NUMERICAL QUESTION TYPE
                 //NUMERICAL QUESTION TYPE
                 case 'K':
                     //MULTIPLE NUMERICAL QUESTION
                     if (trim($val) == '') {
                         $val = NULL;
                         // since some databases can't store blanks in numerical inputs
                     }
                     break;
                 default:
                     break;
             }
             if (is_null($val)) {
                 $setter[] = dbQuoteID($key) . "=NULL";
             } else {
                 $setter[] = dbQuoteID($key) . "=" . dbQuoteAll($val);
             }
         }
         $query .= implode(', ', $setter);
         $query .= " WHERE ID=";
         if (isset($_SESSION[$this->sessid]['srid']) && $this->surveyOptions['active']) {
             $query .= $_SESSION[$this->sessid]['srid'];
             if (!dbExecuteAssoc($query)) {
                 echo submitfailed('');
                 // TODO - report SQL error?
                 if (($this->debugLevel & LEM_DEBUG_VALIDATION_SUMMARY) == LEM_DEBUG_VALIDATION_SUMMARY) {
                     $message .= $this->gT('Error in SQL update');
                     // TODO - add  SQL error?
                 }
             } elseif ($this->surveyOptions['savetimings']) {
                 Yii::import("application.libraries.Save");
                 $cSave = new Save();
                 $cSave->set_answer_time();
             }
             if ($finished) {
                 // Delete the save control record if successfully finalize the submission
                 $query = "DELETE FROM {{saved_control}} where srid=" . $_SESSION[$this->sessid]['srid'] . ' and sid=' . $this->sid;
                 Yii::app()->db->createCommand($query)->execute();
                 if (($this->debugLevel & LEM_DEBUG_VALIDATION_SUMMARY) == LEM_DEBUG_VALIDATION_SUMMARY) {
                     $message .= ';<br />' . $query;
                 }
             } else {
                 if ($this->surveyOptions['allowsave'] && isset($_SESSION[$this->sessid]['scid'])) {
                     SavedControl::model()->updateByPk($_SESSION[$this->sessid]['scid'], array('saved_thisstep' => $thisstep));
                 }
             }
             // Check Quotas
             $aQuotas = checkCompletedQuota($this->sid, 'return');
             if ($aQuotas && !empty($aQuotas)) {
                 checkCompletedQuota($this->sid);
                 // will create a page and quit: why not use it directly ?
             } else {
                 if ($finished) {
                     $sQuery = 'UPDATE ' . $this->surveyOptions['tablename'] . " SET ";
                     if ($this->surveyOptions['datestamp']) {
                         // Replace with date("Y-m-d H:i:s") ? See timeadjust
                         $sQuery .= dbQuoteID('submitdate') . "=" . dbQuoteAll(dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $this->surveyOptions['timeadjust']));
                     } else {
                         $sQuery .= dbQuoteID('submitdate') . "=" . dbQuoteAll(date("Y-m-d H:i:s", mktime(0, 0, 0, 1, 1, 1980)));
                     }
                     $sQuery .= " WHERE ID=" . $_SESSION[$this->sessid]['srid'];
                     dbExecuteAssoc($sQuery);
                     // Checked
                 }
             }
         }
         if (($this->debugLevel & LEM_DEBUG_VALIDATION_SUMMARY) == LEM_DEBUG_VALIDATION_SUMMARY) {
             $message .= $query;
         }
     }
     return $message;
 }
 /**
  * Deletes a survey and all its data
  *
  * @access public
  * @param int $iSurveyID
  * @param bool @recursive
  * @return void
  */
 public function deleteSurvey($iSurveyID, $recursive = true)
 {
     Survey::model()->deleteByPk($iSurveyID);
     if ($recursive == true) {
         if (tableExists("{{survey_" . intval($iSurveyID) . "}}")) {
             Yii::app()->db->createCommand()->dropTable("{{survey_" . intval($iSurveyID) . "}}");
         }
         if (tableExists("{{survey_" . intval($iSurveyID) . "_timings}}")) {
             Yii::app()->db->createCommand()->dropTable("{{survey_" . intval($iSurveyID) . "_timings}}");
         }
         if (tableExists("{{tokens_" . intval($iSurveyID) . "}}")) {
             Yii::app()->db->createCommand()->dropTable("{{tokens_" . intval($iSurveyID) . "}}");
         }
         $oResult = Question::model()->findAllByAttributes(array('sid' => $iSurveyID));
         foreach ($oResult as $aRow) {
             Answer::model()->deleteAllByAttributes(array('qid' => $aRow['qid']));
             Condition::model()->deleteAllByAttributes(array('qid' => $aRow['qid']));
             QuestionAttribute::model()->deleteAllByAttributes(array('qid' => $aRow['qid']));
             DefaultValue::model()->deleteAllByAttributes(array('qid' => $aRow['qid']));
         }
         Question::model()->deleteAllByAttributes(array('sid' => $iSurveyID));
         Assessment::model()->deleteAllByAttributes(array('sid' => $iSurveyID));
         QuestionGroup::model()->deleteAllByAttributes(array('sid' => $iSurveyID));
         SurveyLanguageSetting::model()->deleteAllByAttributes(array('surveyls_survey_id' => $iSurveyID));
         Permission::model()->deleteAllByAttributes(array('entity_id' => $iSurveyID, 'entity' => 'survey'));
         SavedControl::model()->deleteAllByAttributes(array('sid' => $iSurveyID));
         SurveyURLParameter::model()->deleteAllByAttributes(array('sid' => $iSurveyID));
         //Remove any survey_links to the CPDB
         SurveyLink::model()->deleteLinksBySurvey($iSurveyID);
         Quota::model()->deleteQuota(array('sid' => $iSurveyID), true);
     }
 }
Beispiel #8
0
 function savedcontrol()
 {
     //This data will be saved to the "saved_control" table with one row per response.
     // - a unique "saved_id" value (autoincremented)
     // - the "sid" for this survey
     // - the "srid" for the survey_x row id
     // - "saved_thisstep" which is the step the user is up to in this survey
     // - "saved_ip" which is the ip address of the submitter
     // - "saved_date" which is the date ofthe saved response
     // - an "identifier" which is like a username
     // - a "password"
     // - "fieldname" which is the fieldname of the saved response
     // - "value" which is the value of the response
     //We start by generating the first 5 values which are consistent for all rows.
     global $surveyid, $thissurvey, $errormsg, $publicurl, $sitename, $clang, $clienttoken, $thisstep;
     $timeadjust = getGlobalSetting('timeadjust');
     //Check that the required fields have been completed.
     $errormsg = '';
     if (empty($_POST['savename'])) {
         $errormsg .= $clang->gT("You must supply a name for this saved session.") . "<br />\n";
     }
     if (empty($_POST['savepass'])) {
         $errormsg .= $clang->gT("You must supply a password for this saved session.") . "<br />\n";
     }
     if (empty($_POST['savepass']) || empty($_POST['savepass2']) || $_POST['savepass'] != $_POST['savepass2']) {
         $errormsg .= $clang->gT("Your passwords do not match.") . "<br />\n";
     }
     // if security question asnwer is incorrect
     if (function_exists("ImageCreate") && isCaptchaEnabled('saveandloadscreen', $thissurvey['usecaptcha'])) {
         if (empty($_POST['loadsecurity']) || !isset($_SESSION['survey_' . $surveyid]['secanswer']) || $_POST['loadsecurity'] != $_SESSION['survey_' . $surveyid]['secanswer']) {
             $errormsg .= $clang->gT("The answer to the security question is incorrect.") . "<br />\n";
         }
     }
     if (!empty($errormsg)) {
         return;
     }
     $duplicate = SavedControl::model()->findByAttributes(array('sid' => $surveyid, 'identifier' => $_POST['savename']));
     if (!empty($duplicate) && $duplicate->count() > 0) {
         $errormsg .= $clang->gT("This name has already been used for this survey. You must use a unique save name.") . "<br />\n";
         return;
     } else {
         //INSERT BLANK RECORD INTO "survey_x" if one doesn't already exist
         if (!isset($_SESSION['survey_' . $surveyid]['srid'])) {
             $today = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust);
             $sdata = array("datestamp" => $today, "ipaddr" => getIPAddress(), "startlanguage" => $_SESSION['survey_' . $surveyid]['s_lang'], "refurl" => getenv("HTTP_REFERER"));
             if (SurveyDynamic::model($thissurvey['sid'])->insert($sdata)) {
                 $srid = getLastInsertID('{{survey_' . $surveyid . '}}');
                 $_SESSION['survey_' . $surveyid]['srid'] = $srid;
             } else {
                 safeDie("Unable to insert record into survey table.<br /><br />");
             }
         }
         //CREATE ENTRY INTO "saved_control"
         $today = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust);
         $saved_control = new SavedControl();
         $saved_control->sid = $surveyid;
         $saved_control->srid = $_SESSION['survey_' . $surveyid]['srid'];
         $saved_control->identifier = $_POST['savename'];
         // Binding does escape, so no quoting/escaping necessary
         $saved_control->access_code = md5($_POST['savepass']);
         $saved_control->email = $_POST['saveemail'];
         $saved_control->ip = getIPAddress();
         $saved_control->saved_thisstep = $thisstep;
         $saved_control->status = 'S';
         $saved_control->saved_date = $today;
         $saved_control->refurl = getenv('HTTP_REFERER');
         if ($saved_control->save()) {
             $scid = getLastInsertID('{{saved_control}}');
             $_SESSION['survey_' . $surveyid]['scid'] = $scid;
         } else {
             safeDie("Unable to insert record into saved_control table.<br /><br />");
         }
         $_SESSION['survey_' . $surveyid]['holdname'] = $_POST['savename'];
         //Session variable used to load answers every page. Unsafe - so it has to be taken care of on output
         $_SESSION['survey_' . $surveyid]['holdpass'] = $_POST['savepass'];
         //Session variable used to load answers every page. Unsafe - so it has to be taken care of on output
         //Email if needed
         if (isset($_POST['saveemail']) && validateEmailAddress($_POST['saveemail'])) {
             $subject = $clang->gT("Saved Survey Details") . " - " . $thissurvey['name'];
             $message = $clang->gT("Thank you for saving your survey in progress.  The following details can be used to return to this survey and continue where you left off.  Please keep this e-mail for your reference - we cannot retrieve the password for you.");
             $message .= "\n\n" . $thissurvey['name'] . "\n\n";
             $message .= $clang->gT("Name") . ": " . $_POST['savename'] . "\n";
             $message .= $clang->gT("Password") . ": " . $_POST['savepass'] . "\n\n";
             $message .= $clang->gT("Reload your survey by clicking on the following link (or pasting it into your browser):") . "\n";
             $message .= Yii::app()->getController()->createAbsoluteUrl("/survey/index/sid/{$surveyid}/loadall/reload/scid/{$scid}/loadname/" . rawurlencode($_POST['savename']) . "/loadpass/" . rawurlencode($_POST['savepass']) . "/lang/" . rawurlencode($clang->langcode));
             if ($clienttoken) {
                 $message .= "/token/" . rawurlencode($clienttoken);
             }
             $from = "{$thissurvey['adminname']} <{$thissurvey['adminemail']}>";
             if (SendEmailMessage($message, $subject, $_POST['saveemail'], $from, $sitename, false, getBounceEmail($surveyid))) {
                 $emailsent = "Y";
             } else {
                 $errormsg .= $clang->gT('Error: Email failed, this may indicate a PHP Mail Setup problem on the server. Your survey details have still been saved, however you will not get an email with the details. You should note the "name" and "password" you just used for future reference.');
                 if (trim($thissurvey['adminemail']) == '') {
                     $errormsg .= $clang->gT('(Reason: Admin email address empty)');
                 }
             }
         }
         return $clang->gT('Your survey was successfully saved.');
     }
 }
Beispiel #9
0
 /**
  * Deletes a survey and all its data
  *
  * @access public
  * @param int $iSurveyID
  * @param bool @recursive
  * @return void
  */
 public function deleteSurvey($iSurveyID, $recursive = true)
 {
     Survey::model()->deleteByPk($iSurveyID);
     if ($recursive == true) {
         if (tableExists("{{survey_" . intval($iSurveyID) . "}}")) {
             Yii::app()->db->createCommand()->dropTable("{{survey_" . intval($iSurveyID) . "}}");
         }
         if (tableExists("{{survey_" . intval($iSurveyID) . "_timings}}")) {
             Yii::app()->db->createCommand()->dropTable("{{survey_" . intval($iSurveyID) . "_timings}}");
         }
         if (tableExists("{{tokens_" . intval($iSurveyID) . "}}")) {
             Yii::app()->db->createCommand()->dropTable("{{tokens_" . intval($iSurveyID) . "}}");
         }
         /* Remove User/global settings part : need Question and QuestionGroup*/
         // Settings specific for this survey
         $oCriteria = new CDbCriteria();
         $oCriteria->compare('stg_name', 'last_%', true, 'AND', false);
         $oCriteria->compare('stg_value', $iSurveyID, false, 'AND');
         SettingGlobal::model()->deleteAll($oCriteria);
         // Settings specific for this survey, 2nd part
         $oCriteria = new CDbCriteria();
         $oCriteria->compare('stg_name', 'last_%' . $iSurveyID . '%', true, 'AND', false);
         SettingGlobal::model()->deleteAll($oCriteria);
         // All Group id from this survey for ALL users
         $aGroupId = CHtml::listData(QuestionGroup::model()->findAll(array('select' => 'gid', 'condition' => 'sid=:sid', 'params' => array(':sid' => $iSurveyID))), 'gid', 'gid');
         $oCriteria = new CDbCriteria();
         $oCriteria->compare('stg_name', 'last_question_gid_%', true, 'AND', false);
         if (Yii::app()->db->getDriverName() == 'pgsql') {
             $oCriteria->addInCondition('CAST(stg_value as ' . App()->db->schema->getColumnType("integer") . ')', $aGroupId);
         } else {
             $oCriteria->addInCondition('stg_value', $aGroupId);
         }
         SettingGlobal::model()->deleteAll($oCriteria);
         // All Question id from this survey for ALL users
         $aQuestionId = CHtml::listData(Question::model()->findAll(array('select' => 'qid', 'condition' => 'sid=:sid', 'params' => array(':sid' => $iSurveyID))), 'qid', 'qid');
         $oCriteria = new CDbCriteria();
         $oCriteria->compare('stg_name', 'last_question_%', true, 'OR', false);
         if (Yii::app()->db->getDriverName() == 'pgsql') {
             $oCriteria->addInCondition('CAST(stg_value as ' . App()->db->schema->getColumnType("integer") . ')', $aQuestionId);
         } else {
             $oCriteria->addInCondition('stg_value', $aQuestionId);
         }
         SettingGlobal::model()->deleteAll($oCriteria);
         $oResult = Question::model()->findAllByAttributes(array('sid' => $iSurveyID));
         foreach ($oResult as $aRow) {
             Answer::model()->deleteAllByAttributes(array('qid' => $aRow['qid']));
             Condition::model()->deleteAllByAttributes(array('qid' => $aRow['qid']));
             QuestionAttribute::model()->deleteAllByAttributes(array('qid' => $aRow['qid']));
             DefaultValue::model()->deleteAllByAttributes(array('qid' => $aRow['qid']));
         }
         Question::model()->deleteAllByAttributes(array('sid' => $iSurveyID));
         Assessment::model()->deleteAllByAttributes(array('sid' => $iSurveyID));
         QuestionGroup::model()->deleteAllByAttributes(array('sid' => $iSurveyID));
         SurveyLanguageSetting::model()->deleteAllByAttributes(array('surveyls_survey_id' => $iSurveyID));
         Permission::model()->deleteAllByAttributes(array('entity_id' => $iSurveyID, 'entity' => 'survey'));
         SavedControl::model()->deleteAllByAttributes(array('sid' => $iSurveyID));
         SurveyURLParameter::model()->deleteAllByAttributes(array('sid' => $iSurveyID));
         //Remove any survey_links to the CPDB
         SurveyLink::model()->deleteLinksBySurvey($iSurveyID);
         Quota::model()->deleteQuota(array('sid' => $iSurveyID), true);
     }
 }