示例#1
0
 /**
  * Load saved list.
  * @param mixed $iSurveyId Survey id
  */
 private function _showSavedList($iSurveyId)
 {
     $clang = $this->getController()->lang;
     $aResults = Saved_control::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());
     }
 }
示例#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 (hasSurveyPermission($surveyid, 'responses', 'update')) {
            $surveytable = "{{survey_" . $surveyid . '}}';
            $aData['clang'] = $clang = $this->getController()->lang;
            $aData['display']['menu_bars']['browse'] = $clang->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 Answers if exist)
            $fnames['completed'] = array('fieldname' => "completed", 'question' => $clang->gT("Completed"), 'type' => 'completed');
            $fnames = array_merge($fnames, createFieldMap($surveyid, 'full', false, false, $sDataEntryLanguage));
            $nfncount = count($fnames) - 1;
            //SHOW INDIVIDUAL RECORD
            if ($subaction == "edit" && 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" && 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 = Saved_control::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 = Saved_control::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', 'clang' => $clang);
            $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'], $fname['type']);
                    }
                    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:s", mktime(0, 0, 0, 1, 1, 1980));
                            } else {
                                $mysubmitdate = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", Yii::app()->getConfig('timeadjust'));
                            }
                            $completedate = empty($idrow['submitdate']) ? $mysubmitdate : $idrow['submitdate'];
                            $selected = empty($idrow['submitdate']) ? 'N' : $completedate;
                            $select_options = array('N' => $clang->gT('No'), $completedate => $clang->gT('Yes'));
                            $aDataentryoutput .= CHtml::dropDownList('completed', $selected, $select_options);
                            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 .= CHtml::radioButton($fname['fieldname'], $checked, array('class' => 'radiobtn', 'value' => $i));
                                $aDataentryoutput .= $i;
                            }
                            break;
                        case "D":
                            //DATE
                            $thisdate = '';
                            $dateformatdetails = getDateFormatDataForQID($qidattributes, $surveyid);
                            if ($idrow[$fname['fieldname']] != '') {
                                $thisdate = DateTime::createFromFormat("Y-m-d H:i:s", $idrow[$fname['fieldname']])->format($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('' => $clang->gT("Please choose") . '...', 'F' => $clang->gT("Female"), 'G' => $clang->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']}'>\n" . "<option value=''";
                                if ($idrow[$fname['fieldname']] == "") {
                                    $aDataentryoutput .= " selected='selected'";
                                }
                                $aDataentryoutput .= ">" . $clang->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 .= ">" . $clang->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']}'>\n" . "<option value=''";
                            if ($idrow[$fname['fieldname']] == "") {
                                $aDataentryoutput .= " selected='selected'";
                            }
                            $aDataentryoutput .= ">" . $clang->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'];
                            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 = dbExecuteAssoc($ansquery);
                            $anscount = 0;
                            $aDataentryoutput .= "\t<script type='text/javascript'>\n" . "\t<!--\n" . "function rankthis_{$thisqid}(\$code, \$value)\n" . "\t{\n" . "\t\$index=document.editresponse.CHOICES_{$thisqid}.selectedIndex;\n" . "\tfor (i=1; i<={$anscount}; i++)\n" . "{\n" . "\$b=i;\n" . "\$b += '';\n" . "\$inputname=\"RANK_{$thisqid}\"+\$b;\n" . "\$hiddenname=\"d{$myfname}\"+\$b;\n" . "\$cutname=\"cut_{$thisqid}\"+i;\n" . "document.getElementById(\$cutname).style.display='none';\n" . "if (!document.getElementById(\$inputname).value)\n" . "\t{\n" . "\tdocument.getElementById(\$inputname).value=\$value;\n" . "\tdocument.getElementById(\$hiddenname).value=\$code;\n" . "\tdocument.getElementById(\$cutname).style.display='';\n" . "\tfor (var b=document.getElementById('CHOICES_{$thisqid}').options.length-1; b>=0; b--)\n" . "{\n" . "if (document.getElementById('CHOICES_{$thisqid}').options[b].value == \$code)\n" . "\t{\n" . "\tdocument.getElementById('CHOICES_{$thisqid}').options[b] = null;\n" . "\t}\n" . "}\n" . "\ti={$anscount};\n" . "\t}\n" . "}\n" . "\tif (document.getElementById('CHOICES_{$thisqid}').options.length == 0)\n" . "{\n" . "document.getElementById('CHOICES_{$thisqid}').disabled=true;\n" . "}\n" . "\tdocument.editresponse.CHOICES_{$thisqid}.selectedIndex=-1;\n" . "\t}\n" . "function deletethis_{$thisqid}(\$text, \$value, \$name, \$thisname)\n" . "\t{\n" . "\tvar qid='{$thisqid}';\n" . "\tvar lngth=qid.length+4;\n" . "\tvar cutindex=\$thisname.substring(lngth, \$thisname.length);\n" . "\tcutindex=parseFloat(cutindex);\n" . "\tdocument.getElementById(\$name).value='';\n" . "\tdocument.getElementById(\$thisname).style.display='none';\n" . "\tif (cutindex > 1)\n" . "{\n" . "\$cut1name=\"cut_{$thisqid}\"+(cutindex-1);\n" . "\$cut2name=\"d{$myfname}\"+(cutindex);\n" . "document.getElementById(\$cut1name).style.display='';\n" . "document.getElementById(\$cut2name).value='';\n" . "}\n" . "\telse\n" . "{\n" . "\$cut2name=\"d{$myfname}\"+(cutindex);\n" . "document.getElementById(\$cut2name).value='';\n" . "}\n" . "\tvar i=document.getElementById('CHOICES_{$thisqid}').options.length;\n" . "\tdocument.getElementById('CHOICES_{$thisqid}').options[i] = new Option(\$text, \$value);\n" . "\tif (document.getElementById('CHOICES_{$thisqid}').options.length > 0)\n" . "{\n" . "document.getElementById('CHOICES_{$thisqid}').disabled=false;\n" . "}\n" . "\t}\n" . "\t//-->\n" . "\t</script>\n";
                            foreach ($ansresult->readAll() as $ansrow) {
                                $answers[] = array($ansrow['code'], $ansrow['answer']);
                                $anscount++;
                            }
                            //now find out how many existing values there are
                            $chosen[] = "";
                            //create array
                            if (!isset($ranklist)) {
                                $ranklist = "";
                            }
                            if (isset($currentvalues)) {
                                $existing = count($currentvalues);
                            } else {
                                $existing = 0;
                            }
                            for ($j = 1; $j <= $anscount; $j++) {
                                $k = $j - 1;
                                if (isset($currentvalues) && isset($currentvalues[$k]) && $currentvalues[$k]) {
                                    foreach ($answers as $ans) {
                                        if ($ans[0] == $currentvalues[$k]) {
                                            $thiscode = $ans[0];
                                            $thistext = $ans[1];
                                        }
                                    }
                                }
                                $ranklist .= "{$j}:&nbsp;<input class='ranklist' id='RANK_{$thisqid}{$j}'";
                                if (isset($currentvalues) && isset($currentvalues[$k]) && $currentvalues[$k]) {
                                    $ranklist .= " value='" . $thistext . "'";
                                }
                                $ranklist .= " onFocus=\"this.blur()\"  />\n" . "<input type='hidden' id='d{$myfname}{$j}' name='{$myfname}{$j}' value='";
                                if (isset($currentvalues) && isset($currentvalues[$k]) && $currentvalues[$k]) {
                                    $ranklist .= $thiscode;
                                    $chosen[] = array($thiscode, $thistext);
                                }
                                $ranklist .= "' />\n" . "<img src='" . Yii::app()->getConfig('imageurl') . "/cut.gif' alt='" . $clang->gT("Remove this item") . "' title='" . $clang->gT("Remove this item") . "' ";
                                if ($j != $existing) {
                                    $ranklist .= "style='display:none'";
                                }
                                $ranklist .= " id='cut_{$thisqid}{$j}' onclick=\"deletethis_{$thisqid}(document.editresponse.RANK_{$thisqid}{$j}.value, document.editresponse.d{$myfname}{$j}.value, document.editresponse.RANK_{$thisqid}{$j}.id, this.id)\" /><br />\n\n";
                            }
                            if (!isset($choicelist)) {
                                $choicelist = "";
                            }
                            $choicelist .= "<select class='choicelist' size='{$anscount}' name='CHOICES' id='CHOICES_{$thisqid}' onclick=\"rankthis_{$thisqid}(this.options[this.selectedIndex].value, this.options[this.selectedIndex].text)\" >\n";
                            foreach ($answers as $ans) {
                                if (!in_array($ans, $chosen)) {
                                    $choicelist .= "\t<option value='{$ans[0]}'>{$ans[1]}</option>\n";
                                }
                            }
                            $choicelist .= "</select>\n";
                            $aDataentryoutput .= "\t<table>\n" . "<tr>\n" . "\t<td>\n" . "<strong>" . $clang->gT("Your Choices") . ":</strong><br />\n" . $choicelist . "\t</td>\n" . "\t<td align='left'>\n" . "<strong>" . $clang->gT("Your Ranking") . ":</strong><br />\n" . $ranklist . "\t</td>\n" . "</tr>\n" . "\t</table>\n" . "\t<input type='hidden' name='multi' value='{$anscount}' />\n" . "\t<input type='hidden' name='lastfield' value='";
                            if (isset($multifields)) {
                                $aDataentryoutput .= $multifields;
                            }
                            $aDataentryoutput .= "' />\n";
                            $choicelist = "";
                            $ranklist = "";
                            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 .= "\t<input type='checkbox' class='checkboxbtn' name='{$fname['fieldname']}' value='Y'";
                                    if ($idrow[$fname['fieldname']] == "Y") {
                                        $aDataentryoutput .= " checked";
                                    }
                                    $aDataentryoutput .= " />{$fname['subquestion']}<br />\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']}'>\n";
                            $aDataentryoutput .= "<option value=''";
                            if ($idrow[$fname['fieldname']] == "") {
                                $aDataentryoutput .= " selected='selected'";
                            }
                            $aDataentryoutput .= ">" . $clang->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><input type='checkbox' class='checkboxbtn' name=\"{$fname['fieldname']}\" value='Y'";
                                    if ($idrow[$fname['fieldname']] == "Y") {
                                        $aDataentryoutput .= " checked";
                                    }
                                    $aDataentryoutput .= " />{$fname['subquestion']}</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']}'>\n" . "<option value=''";
                            if ($idrow[$fname['fieldname']] == "") {
                                $aDataentryoutput .= " selected='selected'";
                            }
                            $aDataentryoutput .= ">" . $clang->gT("Please choose") . "..</option>\n" . "<option value='Y'";
                            if ($idrow[$fname['fieldname']] == "Y") {
                                $aDataentryoutput .= " selected='selected'";
                            }
                            $aDataentryoutput .= ">" . $clang->gT("Yes") . "</option>\n" . "<option value='N'";
                            if ($idrow[$fname['fieldname']] == "N") {
                                $aDataentryoutput .= " selected='selected'";
                            }
                            $aDataentryoutput .= ">" . $clang->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 .= "\t<input type='radio' class='radiobtn' name='{$fname['fieldname']}' value='{$j}'";
                                    if ($idrow[$fname['fieldname']] == $j) {
                                        $aDataentryoutput .= " checked";
                                    }
                                    $aDataentryoutput .= " />{$j}&nbsp;\n";
                                }
                                $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 .= "\t<input type='radio' class='radiobtn' name='{$fname['fieldname']}' value='{$j}'";
                                    if ($idrow[$fname['fieldname']] == $j) {
                                        $aDataentryoutput .= " checked";
                                    }
                                    $aDataentryoutput .= " />{$j}&nbsp;\n";
                                }
                                $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='radiobtn' name='{$fname['fieldname']}' value='Y'";
                                if ($idrow[$fname['fieldname']] == "Y") {
                                    $aDataentryoutput .= " checked";
                                }
                                $aDataentryoutput .= " />" . $clang->gT("Yes") . "&nbsp;\n" . "\t<input type='radio' class='radiobtn' name='{$fname['fieldname']}' value='U'";
                                if ($idrow[$fname['fieldname']] == "U") {
                                    $aDataentryoutput .= " checked";
                                }
                                $aDataentryoutput .= " />" . $clang->gT("Uncertain") . "&nbsp;\n" . "\t<input type='radio' class='radiobtn' name='{$fname['fieldname']}' value='N'";
                                if ($idrow[$fname['fieldname']] == "N") {
                                    $aDataentryoutput .= " checked";
                                }
                                $aDataentryoutput .= " />" . $clang->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='radiobtn' name='{$fname['fieldname']}' value='I'";
                                if ($idrow[$fname['fieldname']] == "I") {
                                    $aDataentryoutput .= " checked";
                                }
                                $aDataentryoutput .= " />Increase&nbsp;\n" . "\t<input type='radio' class='radiobtn' name='{$fname['fieldname']}' value='S'";
                                if ($idrow[$fname['fieldname']] == "I") {
                                    $aDataentryoutput .= " checked";
                                }
                                $aDataentryoutput .= " />Same&nbsp;\n" . "\t<input type='radio' class='radiobtn' 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='radiobtn' 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='radiobtn' name='{$fname['fieldname']}' value=''";
                                if ($idrow[$fname['fieldname']] == '') {
                                    $aDataentryoutput .= " checked";
                                }
                                $aDataentryoutput .= " />" . $clang->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']}'>\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;
                        default:
                            //This really only applies to tokens for non-private surveys
                            $aDataentryoutput .= "\t<input type='text' name='{$fname['fieldname']}' value='" . $idrow[$fname['fieldname']] . "' />\n";
                            break;
                    }
                    $aDataentryoutput .= "\t\t</td>\n                    </tr>\n";
                } while ($fname = next($fnames));
            }
            $aDataentryoutput .= "</table>\n" . "<p>\n";
            $aData['sDataEntryLanguage'] = $sDataEntryLanguage;
            if (!hasSurveyPermission($surveyid, 'responses', 'update')) {
                // if you are not survey owner or super admin you cannot modify responses
                $aDataentryoutput .= "<p><input type='button' value='" . $clang->gT("Save") . "' disabled='disabled'/></p>\n";
            } elseif ($subaction == "edit" && hasSurveyPermission($surveyid, 'responses', 'update')) {
                $aData['part'] = 'edit';
                $aDataentryoutput .= $this->getController()->render('/admin/dataentry/edit', $aData, TRUE);
            } elseif ($subaction == "editsaved" && hasSurveyPermission($surveyid, 'responses', 'update')) {
                $aData['part'] = 'editsaved';
                $aDataentryoutput .= $this->getController()->render('/admin/dataentry/edit', $aData, TRUE);
            }
            $aDataentryoutput .= "</form>\n";
            $aViewUrls['output'] = $aDataentryoutput;
            $this->_renderWrappedTemplate('dataentry', $aViewUrls, $aData);
        }
    }
示例#3
0
/**
* 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 Saved_control::getCountOfAll($surveyid);
}
示例#4
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) . "}}");
         }
         $oResult = Questions::model()->findAllByAttributes(array('sid' => $iSurveyID));
         foreach ($oResult as $aRow) {
             Answers::model()->deleteAllByAttributes(array('qid' => $aRow['qid']));
             Conditions::model()->deleteAllByAttributes(array('qid' => $aRow['qid']));
             Question_attributes::model()->deleteAllByAttributes(array('qid' => $aRow['qid']));
             Defaultvalues::model()->deleteAllByAttributes(array('qid' => $aRow['qid']));
         }
         Questions::model()->deleteAllByAttributes(array('sid' => $iSurveyID));
         Assessment::model()->deleteAllByAttributes(array('sid' => $iSurveyID));
         Groups::model()->deleteAllByAttributes(array('sid' => $iSurveyID));
         Surveys_languagesettings::model()->deleteAllByAttributes(array('surveyls_survey_id' => $iSurveyID));
         Survey_permissions::model()->deleteAllByAttributes(array('sid' => $iSurveyID));
         Saved_control::model()->deleteAllByAttributes(array('sid' => $iSurveyID));
         Survey_url_parameters::model()->deleteAllByAttributes(array('sid' => $iSurveyID));
         Quota::model()->deleteQuota(array('sid' => $iSurveyID), true);
     }
 }
 /**
  * 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);
     $clang = $this->getController()->lang;
     $date = date('YmdHis');
     //'His' adds 24hours+minutes to name to allow multiple deactiviations in a day
     if (empty($_POST['ok'])) {
         $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}}}")) {
             if (Yii::app()->db->getDriverName() == 'postgre') {
                 $deactivateresult = Yii::app()->db->createCommand()->renameTable($toldtable . '_tid_seq', $tnewtable . '_tid_seq');
                 $setsequence = "ALTER TABLE " . Yii::app()->db->quoteTableName($tnewtable) . " ALTER COLUMN tid SET DEFAULT nextval('{{{$tnewtable}}}_tid_seq'::regclass);";
                 $deactivateresult = Yii::app()->db->createCommand($setsequence)->query();
                 $setidx = "ALTER INDEX {{{$toldtable}}}_idx RENAME TO {{{$tnewtable}}}_idx;";
                 $deactivateresult = Yii::app()->db->createCommand($setidx)->query();
             }
             $toldtable = "{{tokens_{$iSurveyID}}}";
             $tnewtable = "{{old_tokens_{$iSurveyID}_{$date}}}";
             $tdeactivateresult = Yii::app()->db->createCommand()->renameTable($toldtable, $tnewtable);
             $aData['tnewtable'] = $tnewtable;
             $aData['toldtable'] = $toldtable;
         }
         //Remove any survey_links to the CPDB
         Survey_links::model()->deleteLinksBySurvey($iSurveyID);
         // IF there are any records in the saved_control table related to this survey, they have to be deleted
         $result = Saved_control::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 auto_increment value from the table before renaming
         $new_autonumber_start = 0;
         $query = "SELECT id FROM " . Yii::app()->db->quoteTableName($sOldSurveyTableName) . " ORDER BY id desc";
         $result = Yii::app()->db->createCommand($query)->limit(1)->query();
         foreach ($result->readAll() as $row) {
             if (strlen($row['id']) > 12) {
                 $part1 = substr($row['id'], 0, 12);
                 $part2len = strlen($row['id']) - 12;
                 $part2 = sprintf("%0{$part2len}d", substr($row['id'], 12, strlen($row['id']) - 12) + 1);
                 $new_autonumber_start = "{$part1}{$part2}";
             } else {
                 $new_autonumber_start = $row['id'] + 1;
             }
         }
         $condn = array('sid' => $iSurveyID);
         $insertdata = array('autonumber_start' => $new_autonumber_start);
         $survey = Survey::model()->findByAttributes($condn);
         $survey->autonumber_start = $new_autonumber_start;
         $survey->save();
         if (Yii::app()->db->getDrivername() == 'postgre') {
             $deactivateresult = Yii::app()->db->createCommand()->renameTable($sOldSurveyTableName . '_id_seq', $sNewSurveyTableName . '_id_seq');
             $setsequence = "ALTER TABLE {$newtable} ALTER COLUMN id SET DEFAULT nextval('{$sNewSurveyTableName}_id_seq'::regclass);";
             $deactivateresult = Yii::app()->db->createCommand($setsequence)->execute();
         }
         $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;
     }
     $this->_renderWrappedTemplate('survey', 'deactivateSurvey_view', $aData);
 }
 /**
  * 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 = '';
     $_SESSION[$this->sessid]['datestamp'] = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $this->surveyOptions['timeadjust']);
     if ($this->surveyOptions['active'] && !isset($_SESSION[$this->sessid]['srid'])) {
         // 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 = array_merge($sdata, array("token" => $this->surveyOptions['token']));
         }
         if ($this->surveyOptions['datestamp'] == true) {
             $sdata = array_merge($sdata, array("datestamp" => $this->surveyOptions['datestamp'] ? $_SESSION[$this->sessid]['datestamp'] : NULL, "startdate" => $this->surveyOptions['datestamp'] ? $_SESSION[$this->sessid]['datestamp'] : date("Y-m-d H:i:s", 0)));
         }
         if ($this->surveyOptions['ipaddr'] == true) {
             $sdata = array_merge($sdata, array("ipaddr" => getIPAddress()));
         }
         if ($this->surveyOptions['refurl'] == true) {
             $sdata = array_merge($sdata, array("refurl" => $this->surveyOptions['refurl'] ? getenv("HTTP_REFERER") : NULL));
         }
         $sdata = array_filter($sdata);
         Survey_dynamic::sid($this->sid);
         $oSurvey = new Survey_dynamic();
         $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?
         }
         //Insert Row for Timings, if needed
         if ($this->surveyOptions['savetimings']) {
             Survey_timings::sid($this->sid);
             $oSurveyTimings = new Survey_timings();
             $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'])) {
             $setter[] = dbQuoteID('datestamp') . "=" . dbQuoteAll($_SESSION[$this->sessid]['datestamp']);
         }
         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 = 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'])) {
                     Saved_control::model()->updateByPk($_SESSION[$this->sessid]['scid'], array('saved_thisstep' => $thisstep));
                 }
             }
             // Check Quotas
             $bQuotaMatched = false;
             $aQuotas = checkQuota('return', $this->sid);
             if ($aQuotas !== false) {
                 if ($aQuotas != false) {
                     foreach ($aQuotas as $aQuota) {
                         if (isset($aQuota['status']) && $aQuota['status'] == 'matched') {
                             $bQuotaMatched = true;
                         }
                     }
                 }
             }
             if ($bQuotaMatched) {
                 checkQuota('enforce', $this->sid);
                 // will create a page and quit.
             } 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($_SESSION[$this->sessid]['datestamp']);
                     } 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;
 }
示例#7
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, $timeadjust, $clang, $clienttoken, $thisstep;
     //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 = Saved_control::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 (Survey_dynamic::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 Saved_control();
         $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/" . urlencode($_POST['savename']) . "/loadpass/" . urlencode($_POST['savepass']) . "/lang/" . urlencode($clang->langcode));
             if ($clienttoken) {
                 $message .= "/token/{$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.');
     }
 }