loadHelper('surveytranslator'); } /** * Function responsible for importing responses from file (.csv) * * @param mixed $surveyid * @return void */ function vvimport() { $aData = array(); $iSurveyId = sanitize_int(Yii::app()->request->getParam('surveyid')); $aData['iSurveyId'] = $aData['surveyid'] = $iSurveyId; $aData['clang'] = $this->getController()->lang; if( Permission::model()->hasSurveyPermission($iSurveyId,'responses','create') ) { if(tableExists("{{survey_$iSurveyId}}")) { // First load the database helper Yii::app()->loadHelper('database'); // Really needed ? $subAction = Yii::app()->request->getPost('subaction'); if ($subAction != "upload") { $this->_showUploadForm($this->_getEncodingsArray(), $iSurveyId, $aData); } else { $this->_handleFileUpload($iSurveyId, $aData); } } else { Yii::app()->session['flashmessage'] = $clang->gT("This survey is not active. You must activate the survey before attempting to import a VVexport file."); $this->getController()->redirect($this->getController()->createUrl("/admin/survey/sa/view/surveyid/{$iSurveyId}")); } } else { Yii::app()->session['flashmessage'] = $clang->gT("You do not have sufficient rights to access this page."); $this->getController()->redirect($this->getController()->createUrl("/admin/survey/sa/view/surveyid/{$iSurveyId}")); } } function iteratesurvey($surveyid) { $aData = array(); $surveyid = sanitize_int($surveyid); $aData['surveyid'] = $surveyid; $aData['clang'] = $this->getController()->lang; $aData['success'] = false; if (Permission::model()->hasSurveyPermission($surveyid,'surveyactivation','update')) { if (Yii::app()->request->getParam('unfinalizeanswers') == 'true') { SurveyDynamic::sid($surveyid); Yii::app()->db->createCommand("DELETE from {{survey_$surveyid}} WHERE submitdate IS NULL AND token in (SELECT * FROM ( SELECT answ2.token from {{survey_$surveyid}} AS answ2 WHERE answ2.submitdate IS NOT NULL) tmp )")->execute(); // Then set all remaining answers to incomplete state Yii::app()->db->createCommand("UPDATE {{survey_$surveyid}} SET submitdate=NULL, lastpage=NULL")->execute(); // Finally, reset the token completed and sent status Yii::app()->db->createCommand("UPDATE {{tokens_$surveyid}} SET sent='N', remindersent='N', remindercount=0, completed='N', usesleft=1 where usesleft=0")->execute(); $aData['success']=true; } $this->_renderWrappedTemplate('dataentry', 'iteratesurvey', $aData); } } private function _handleFileUpload($iSurveyId, $aData) { $vvoutput = ''; $donotimport = array(); $clang = $this->getController()->lang; $filePath = $this->_moveUploadedFile($aData); //$aFileContents = $this->_readFile($filePath); Yii::app()->loadHelper('admin/import'); // Fill option $aOptions=array(); $aOptions['bDeleteFistLine']=(Yii::app()->request->getPost('dontdeletefirstline') == "dontdeletefirstline")?false:true;// Force, maybe function change ;) if(Yii::app()->request->getPost('noid')==="noid"){ $aOptions['sExistingId']='ignore'; }else{ $aOptions['sExistingId']=Yii::app()->request->getPost('insertmethod'); } $aOptions['bNotFinalized']=(Yii::app()->request->getPost('notfinalized') == "notfinalized"); $aOptions['bForceImport']=(Yii::app()->request->getPost('forceimport') == "forceimport"); $aOptions['sCharset']=Yii::app()->request->getPost('vvcharset'); $aOptions['sSeparator']="\t"; $aResult=CSVImportResponses($filePath,$iSurveyId,$aOptions); unlink($filePath); //delete the uploaded file $aData['class']=""; $aData['title']=$clang->gT("Import a VV response data file"); $aData['aResult']['success'][]=$clang->gT("File upload succeeded."); if(isset($aResult['success'])){ $aData['aResult']['success']=array_merge($aData['aResult']['success'],$aResult['success']); } $aData['aResult']['errors']=(isset($aResult['errors'])) ? $aResult['errors'] : false; $aData['aResult']['warnings']=(isset($aResult['warnings'])) ? $aResult['warnings'] : false; $this->_renderWrappedTemplate('dataentry', 'vvimport_result', $aData); } private function _getFieldInfo($aFileContents) { $aFieldnames = explode("\t", trim($aFileContents[1])); $nbOfFields = count($aFieldnames) - 1; while (trim($aFieldnames[$nbOfFields]) == "" && $nbOfFields > -1) // get rid of blank entries { unset($aFieldnames[$nbOfFields]); $nbOfFields--; } return array($aFieldnames, $nbOfFields); } private function _readFile($filePath) { // Open the file for reading $handle = fopen($filePath, "r"); // Read the file while (!feof($handle)) { $buffer = fgets($handle); //To allow for very long lines $bigarray[] = @mb_convert_encoding($buffer, "UTF-8", $this->_getUploadCharset($this->_getEncodingsArray())); } // Close the file fclose($handle); return $bigarray; } private function _moveUploadedFile($aData) { $clang = $this->getController()->lang; $sFullFilePath = Yii::app()->getConfig('tempdir') . "/" . randomChars(20); $fileVV = CUploadedFile::getInstanceByName('csv_vv_file'); if($fileVV){ if(!$fileVV->SaveAs($sFullFilePath)) { $aData['class']='error warningheader'; $aData['title']=$clang->gT("Error"); $aData['aResult']['errors'][] = sprintf( $clang->gT("An error occurred uploading your file. This may be caused by incorrect permissions in your %s folder."), Yii::app()->getConfig('tempdir') ); $aData['aResult']['errors'][] = "
".
                $aData['aUrls'][] = array(
                    'link'=>$this->getController()->createUrl('admin/dataentry/sa/vvimport/surveyid/'.$aData['surveyid']),
                    'text'=>$aData['aUrlText'][] = $clang->gT("Back to Response Import"),
                    );
                $this->_renderWrappedTemplate('dataentry', 'vvimport_result', $aData);
                die;
            }
            else
            {
                return $sFullFilePath;
            }
        }else{
            Yii::app()->session['flashmessage'] = gT("You have to select a file.");
            $this->getController()->redirect($this->getController()->createUrl("admin/dataentry/sa/vvimport/surveyid/{$aData['surveyid']}"));
        }
    }

    private function _showUploadForm($aEncodings, $surveyid, $aData)
    {
        unset($aEncodings['auto']);
        asort($aEncodings);
        $aData['aEncodings']=$aEncodings;
        $aData['tableExists'] = tableExists("{{survey_$surveyid}}");

        $aData['display']['menu_bars']['browse'] = $this->getController()->lang->gT("Import VV file");

        $this->_renderWrappedTemplate('dataentry', 'vvimport', $aData);
    }

    /**
    * dataentry::import()
    * Function responsible to import responses from old survey table(s).
    * @param int $iSurveyId
    * @return void
    */
    public function import($surveyid)
    {
        $iSurveyId = sanitize_int($surveyid);

        if(Permission::model()->hasSurveyPermission($iSurveyId,'responses','create'))
        {
            if (!App()->getRequest()->isPostRequest || App()->getRequest()->getPost('table') == 'none')
            {
                
                // Schema that serves as the base for compatibility checks.
                $baseSchema = SurveyDynamic::model($iSurveyId)->getTableSchema();
                $tables = App()->getApi()->getOldResponseTables($iSurveyId);
                $compatible = array();
				$coercible = array();
                foreach ($tables as $table)
                {
                    $schema = PluginDynamic::model($table)->getTableSchema();
                    if (PluginDynamic::model($table)->count() > 0)
                    {
						if ($this->isCompatible($baseSchema, $schema))
						{
							$compatible[] = $table;
						}
						elseif ($this->isCompatible($baseSchema, $schema, false))
						{
							$coercible[] = $table;
						}
                    }
                }
                
                $aData = array();
                $aData['surveyid'] = $iSurveyId;
                $aData['settings']['table'] = array(
                    'label' => gT('Source table'),
                    'type' => 'select',
                    'options' => array(
						gT('Compatible') => $this->tableList($compatible),
						gT('Compatible with type coercion') => $this->tableList($coercible)
					)
                );


                $aData['settings']['timings'] = array(
                    'type' => 'checkbox',
                    'label' => gT('Import timings (if exist)')
                );

                //Get the menubar
                $aData['display']['menu_bars']['browse'] = gT("Quick statistics");

                $this->_renderWrappedTemplate('dataentry', 'import', $aData);
            }
            else
            {
                $targetSchema = SurveyDynamic::model($iSurveyId)->getTableSchema();
                $sourceTable = PluginDynamic::model($_POST['table']);
                $sourceSchema = $sourceTable->getTableSchema();
             
                $fieldMap = array();
                $pattern = '/([\d]+)X([\d]+)X([\d]+.*)/';
                foreach ($sourceSchema->getColumnNames() as $name)
                {
                    // Skip id field.
                    if ($name == 'id')
                    {
                        continue;
                    }

                    $sourceColumn = $sourceSchema->getColumn($name);
                    $matches = array();
                    // Exact match.
                    if ($targetSchema->getColumn($name))
                    {
                        $fieldMap[$name] = $name;
                    }
                    elseif(preg_match($pattern, $name, $matches)) // Column name is SIDXGIDXQID
                    {
                        $qid = $matches[3];
                        $targetColumn = $this->getQidColumn($targetSchema, $qid);
                        if (isset($targetColumn))
                        {
                            $fieldMap[$name] = $targetColumn->name;
                        }
                    }
                }
                $imported = 0;
				$sourceResponses = new CDataProviderIterator(new CActiveDataProvider($sourceTable), 500);
                foreach ($sourceResponses as $sourceResponse)
                {
                    
                    // Using plugindynamic model because I dont trust surveydynamic.
                   $targetResponse = new PluginDynamic("{{survey_$iSurveyId}}");

                   foreach($fieldMap as $sourceField => $targetField)
                   {
                       $targetResponse[$targetField] = $sourceResponse[$sourceField];
                   }
                   $imported++;
                   $targetResponse->save();
                   unset($targetResponse);
                }


                
                Yii::app()->session['flashmessage'] = sprintf(gT("%s old response(s) were successfully imported."), $imported);
                $sOldTimingsTable=substr($sourceTable->tableName(),0,strrpos($sourceTable->tableName(),'_')).'_timings'.substr($sourceTable->tableName(),strrpos($sourceTable->tableName(),'_'));
                $sNewTimingsTable = "{{{$surveyid}_timings}}";

                if (isset($_POST['timings']) && $_POST['timings'] == 1 && tableExists($sOldTimingsTable) && tableExists($sNewTimingsTable))
                {
                    // Import timings
                    $aFieldsOldTimingTable=array_values($schema->getTable($sOldTimingsTable)->columnNames);
                    $aFieldsNewTimingTable=array_values($schema->getTable($sNewTimingsTable)->columnNames);

                    $aValidTimingFields=array_intersect($aFieldsOldTimingTable,$aFieldsNewTimingTable);

                    $queryOldValues = "SELECT ".implode(", ",$aValidTimingFields)." FROM {$sOldTimingsTable} ";
                    $resultOldValues = dbExecuteAssoc($queryOldValues) or show_error("Error:
$queryOldValues
"); $iRecordCountT=0; $aSRIDConversions=array(); foreach ($resultOldValues->readAll() as $sTable) { if (isset($aSRIDConversions[$sTable['id']])) { $sTable['id']=$aSRIDConversions[$sTable['id']]; } else continue; //$sInsertSQL=Yii::app()->db->GetInsertSQL($sNewTimingsTable,$row); $sInsertSQL="INSERT into {$sNewTimingsTable} (".implode(",", array_map("dbQuoteID", array_keys($sTable))).") VALUES (".implode(",", array_map("dbQuoteAll", array_values($sTable))).")"; $aTables = dbExecuteAssoc($sInsertSQL) or show_error("Error:
$sInsertSQL
"); $iRecordCountT++; } Yii::app()->session['flashmessage'] = sprintf(gT("%s old response(s) and according timings were successfully imported."),$imported,$iRecordCountT); } $this->getController()->redirect(array("/admin/responses/sa/index/", 'surveyid' => $surveyid)); } } } /** * Takes a list of tablenames and creates a nice key value array. * @param type $list */ protected function tableList($tables) { $list = array(); if (empty($tables)) { $list['none'] = gT('No old responses found.'); } foreach ($tables as $table) { $count = PluginDynamic::model($table)->count(); $timestamp = date_format(new DateTime(substr($table, -14)), 'Y-m-d H:i:s'); $list[$table] = "$timestamp ($count responses)"; } return $list; } /** * Takes a table schema and finds the field for some question id. * @param CDbTableSchema $schema * @param type $qid * @return CDbColumnSchema */ protected function getQidColumn(CDbTableSchema $schema, $qid) { foreach ($schema->columns as $name => $column) { $pattern = '/([\d]+)X([\d]+)X([\d]+.*)/'; $matches = array(); if (preg_match($pattern, $name, $matches)) { if ($matches[3] == $qid) { return $column; } } } } /** * Compares 2 table schema to see if they are compatible. */ protected function isCompatible(CDbTableSchema $base, CDbTableSchema $old, $checkColumnTypes = true) { $pattern = '/([\d]+)X([\d]+)X([\d]+.*)/'; foreach($old->columns as $name => $column) { // The following columns are always compatible. if (in_array($name, array('id', 'token', 'submitdate', 'lastpage', 'startlanguage'))) { continue; } $matches = array(); if (preg_match($pattern, $name, $matches)) { $qid = $matches[3]; $baseColumn = $this->getQidColumn($base, $qid); if ($baseColumn) { if ($baseColumn && $checkColumnTypes && ($baseColumn->dbType != $column->dbType)) { return false; } } } } return true; } /** * 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['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 {{questions}}.gid=g.gid AND {{questions}}.language = '{$sDataEntryLanguage}' AND g.language = '{$sDataEntryLanguage}' AND {{questions}}.sid={{surveys}}.sid AND {{questions}}.sid='$surveyid' 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'=>$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" && Permission::model()->hasSurveyPermission($surveyid,'responses','update')) { $idquery = "SELECT * FROM $surveytable WHERE id=$id"; $idresult = dbExecuteAssoc($idquery) or safeDie ("Couldn't get individual record
$idquery
"); 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', '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" ."\n"; $aDataentryoutput .= stripJavaScript($question); $aDataentryoutput .= "\n" ."\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",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' => $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'].' '; $aDataentryoutput .= CHtml::textField($fname['fieldname'], $idrow[$fname['fieldname']]); break; case "id": $aDataentryoutput .= CHtml::tag('span', array('style' => 'font-weight: bold;'), ' '.$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']]!='') { $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\n"; // $aDataentryoutput .= "\t\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"), 'M' => $clang->gT("Male") ); $aDataentryoutput .= CHtml::listBox($fname['fieldname'], $idrow[$fname['fieldname']], $select_options); break; case "L": //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\n"; } else { $lquery = "SELECT * FROM {{answers}} WHERE qid={$fname['qid']} AND language = '{$sDataEntryLanguage}' ORDER BY sortorder, answer"; $lresult = dbExecuteAssoc($lquery); $aDataentryoutput .= "\t\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\n"; break; case "R": //RANKING TYPE QUESTION $thisqid=$fname['qid']; $currentvalues=array(); $myfname=$fname['sid'].'X'.$fname['gid'].'X'.$fname['qid']; $aDataentryoutput .= '
    '; 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
  • "; $aDataentryoutput .=""; $aDataentryoutput .= "\n"; } else { $aDataentryoutput .= "\tfindByPk($surveyid)->additionalLanguages; $baselang = Survey::model()->findByPk($surveyid)->language; array_unshift($slangs,$baselang); $aDataentryoutput.= ""; break; case "P": //Multiple choice with comments checkbox + text $aDataentryoutput .= "\n"; while (isset($fname) && $fname['type'] == "P") { $thefieldname=$fname['fieldname']; if (substr($thefieldname, -7) == "comment") { $aDataentryoutput .= "\n" ."\t\n"; } elseif (substr($fname['fieldname'], -5) == "other") { $aDataentryoutput .= "\t\n" ."\n" ."\n" ."\t\n"; } else { $aDataentryoutput .= "\t\n" ."'; if ($qAttributes['show_comment']) $aDataentryoutput .= ''; $aDataentryoutput .= '' .'' .'' .''; } $aDataentryoutput .= ''; $aDataentryoutput .= '
    \n" ."\t\n" ."\n"; $fname=next($fnames); $aDataentryoutput .= "\t\n" ."
    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 .= '
    Title
    Comment
    File name
    '; $aDataentryoutput .= ''; } else {//file count $aDataentryoutput .= ''; } break; case "N": //NUMERICAL TEXT $aDataentryoutput .= "\t\n"; break; case "S": //SHORT FREE TEXT $aDataentryoutput .= "\t\n"; break; case "T": //LONG FREE TEXT $aDataentryoutput .= "\t\n"; break; case "U": //HUGE FREE TEXT $aDataentryoutput .= "\t\n"; break; case "Y": //YES/NO radio-buttons $aDataentryoutput .= "\t\n"; break; case "A": //ARRAY (5 POINT CHOICE) radio-buttons $aDataentryoutput .= "\n"; $thisqid=$fname['qid']; while ($fname['qid'] == $thisqid) { $aDataentryoutput .= "\t\n" ."\n" ."
    {$fname['subquestion']}\n"; for ($j=1; $j<=5; $j++) { $aDataentryoutput .= "\t\n"; $fname=next($fnames); } $aDataentryoutput .= "
    \n"; $fname=prev($fnames); break; case "B": //ARRAY (10 POINT CHOICE) radio-buttons $aDataentryoutput .= "\n"; $thisqid=$fname['qid']; while ($fname['qid'] == $thisqid) { $fieldn = substr($fname['fieldname'], 0, strlen($fname['fieldname'])); $aDataentryoutput .= "\t\n" ."\n" ."
    {$fname['subquestion']}\n"; for ($j=1; $j<=10; $j++) { $aDataentryoutput .= "\t\n"; $fname=next($fnames); } $fname=prev($fnames); $aDataentryoutput .= "
    \n"; break; case "C": //ARRAY (YES/UNCERTAIN/NO) radio-buttons $aDataentryoutput .= "\n"; $thisqid=$fname['qid']; while ($fname['qid'] == $thisqid) { $fieldn = substr($fname['fieldname'], 0, strlen($fname['fieldname'])); $aDataentryoutput .= "\t\n" ."\n" ."\n" ."\t\n"; $fname=next($fnames); } $fname=prev($fnames); $aDataentryoutput .= "
    {$fname['subquestion']}\n" ."\tgT("Yes")." \n" ."\tgT("Uncertain")." \n" ."\tgT("No")." \n" ."
    \n"; break; case "E": //ARRAY (Increase/Same/Decrease) radio-buttons $aDataentryoutput .= "\n"; $thisqid=$fname['qid']; while ($fname['qid'] == $thisqid) { $fieldn = substr($fname['fieldname'], 0, strlen($fname['fieldname'])); $aDataentryoutput .= "\t\n" ."\n" ."\n"; $fname=next($fnames); } $fname=prev($fnames); $aDataentryoutput .= "
    {$fname['subquestion']}\n" ."\t\n" ."\t
    \n"; break; case "F": //ARRAY (Flexible Labels) case "H": case "1": $aDataentryoutput .= "\n"; $thisqid=$fname['qid']; while (isset($fname['qid']) && $fname['qid'] == $thisqid) { $fieldn = substr($fname['fieldname'], 0, strlen($fname['fieldname'])); $aDataentryoutput .= "\t\n" ."\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 .= "\n" ."\t\n"; $fname=next($fnames); } $fname=prev($fnames); $aDataentryoutput .= "
    {$fname['subquestion']}"; if (isset($fname['scale'])) { $aDataentryoutput .= " (".$fname['scale'].')'; } $aDataentryoutput .="\n"; foreach ($fresult->readAll() as $frow) { $aDataentryoutput .= "\tgT("No answer")." \n"; $aDataentryoutput .= "
    \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 .= "\n"; $thisqid=$fname['qid']; while (isset($fname['qid']) && $fname['qid'] == $thisqid) { $fieldn = substr($fname['fieldname'], 0, strlen($fname['fieldname'])); $aDataentryoutput .= "\t\n" . "\n"; $aDataentryoutput .= "
    {$fname['subquestion1']}:{$fname['subquestion2']}\n"; if ($qidattributes['input_boxes']!=0) { $aDataentryoutput .= "\t\n"; $fname=next($fnames); } $fname=prev($fnames); $aDataentryoutput .= "
    \n"; break; case ";": //ARRAY (Multi Flexi) $aDataentryoutput .= "\n"; $thisqid=$fname['qid']; while (isset($fname['qid']) && $fname['qid'] == $thisqid) { $fieldn = substr($fname['fieldname'], 0, strlen($fname['fieldname'])); $aDataentryoutput .= "\t\n" . "\n"; $aDataentryoutput .= "
    {$fname['subquestion1']}:{$fname['subquestion2']}\n"; $aDataentryoutput .= "\t\n"; $fname=next($fnames); } $fname=prev($fnames); $aDataentryoutput .= "
    \n"; break; default: //This really only applies to tokens for non-private surveys $aDataentryoutput .= "\t\n"; break; } $aDataentryoutput .= " \n"; } while ($fname=next($fnames)); } $aDataentryoutput .= "\n" ."

    \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 .= "

    \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 .= "\n"; $aViewUrls['output'] = $aDataentryoutput; $this->_renderWrappedTemplate('dataentry', $aViewUrls, $aData); } } /** * dataentry::delete() * delete dataentry * @return */ public function delete() { if (isset($_REQUEST['surveyid']) && !empty($_REQUEST['surveyid'])) { $surveyid = $_REQUEST['surveyid']; } if (!empty($_REQUEST['sid'])) $surveyid = (int)$_REQUEST['sid']; $surveyid = sanitize_int($surveyid); $id = $_REQUEST['id']; $aData = array( 'surveyid' => $surveyid, 'id' => $id ); if (Permission::model()->hasSurveyPermission($surveyid, 'responses','read') && Permission::model()->hasSurveyPermission($surveyid, 'responses', 'delete')) { $surveytable = "{{survey_".$surveyid.'}}'; $aData['thissurvey'] = getSurveyInfo($surveyid); $delquery = "DELETE FROM $surveytable WHERE id=$id"; Yii::app()->loadHelper('database'); $delresult = dbExecuteAssoc($delquery) or safeDie ("Couldn't delete record $id
    \n"); $this->_renderWrappedTemplate('dataentry', 'delete', $aData); } } /** * dataentry::update() * update dataentry * @return */ public function update() { $aData=array(); $subaction = Yii::app()->request->getPost('subaction'); if (isset($_REQUEST['surveyid'])) $surveyid = $_REQUEST['surveyid']; if (!empty($_REQUEST['sid'])) $surveyid = (int)$_REQUEST['sid']; $surveyid = sanitize_int($surveyid); $id = Yii::app()->request->getPost('id'); $lang = Yii::app()->request->getPost('lang'); if ($subaction == "update" && Permission::model()->hasSurveyPermission($surveyid, 'responses', 'update')) { $baselang = Survey::model()->findByPk($surveyid)->language; Yii::app()->loadHelper("database"); $clang = $this->getController()->lang; $surveytable = "{{survey_".$surveyid.'}}'; $aDataentryoutput = "
    ".$clang->gT("Data entry")."
    \n"; $fieldmap = createFieldMap($surveyid,'full',false,false,getBaseLanguageFromSurveyID($surveyid)); // unset timings foreach ($fieldmap as $fname) { if ($fname['type'] == "interview_time" || $fname['type'] == "page_time" || $fname['type'] == "answer_time") { unset($fieldmap[$fname['fieldname']]); } } $thissurvey = getSurveyInfo($surveyid); $updateqr = "UPDATE $surveytable SET \n"; foreach ($fieldmap as $irow) { $fieldname=$irow['fieldname']; if ($fieldname=='id') continue; if (isset($_POST[$fieldname])) { $thisvalue=$_POST[$fieldname]; } else { $thisvalue=""; } if ($irow['type'] == 'lastpage') { $thisvalue=0; } elseif ($irow['type'] == 'D') { if ($thisvalue == "") { $updateqr .= dbQuoteID($fieldname)." = NULL, \n"; } else { $qidattributes = getQuestionAttributeValues($irow['qid'], $irow['type']); $dateformatdetails = getDateFormatDataForQID($qidattributes, $thissurvey); $this->getController()->loadLibrary('Date_Time_Converter'); $datetimeobj = new date_time_converter($thisvalue,$dateformatdetails['phpdate']) ; //need to check if library get initialized with new value of constructor or not. //$datetimeobj = new Date_Time_Converter($thisvalue,$dateformatdetails['phpdate']); $updateqr .= dbQuoteID($fieldname)." = '{$datetimeobj->convert("Y-m-d H:i:s")}', \n"; } } elseif (($irow['type'] == 'N' || $irow['type'] == 'K') && $thisvalue == "") { $updateqr .= dbQuoteID($fieldname)." = NULL, \n"; } elseif ($irow['type'] == '|' && strpos($irow['fieldname'], '_filecount') && $thisvalue == "") { $updateqr .= dbQuoteID($fieldname)." = NULL, \n"; } elseif ($irow['type'] == 'submitdate') { if (isset($_POST['completed']) && ($_POST['completed']== "N")) { $updateqr .= dbQuoteID($fieldname)." = NULL, \n"; } elseif (isset($_POST['completed']) && $thisvalue=="") { $updateqr .= dbQuoteID($fieldname)." = " . dbQuoteAll($_POST['completed']) . ", \n"; } else { $updateqr .= dbQuoteID($fieldname)." = " . dbQuoteAll($thisvalue) . ", \n"; } } else { $updateqr .= dbQuoteID($fieldname)." = " . dbQuoteAll($thisvalue) . ", \n"; } } $updateqr = substr($updateqr, 0, -3); $updateqr .= " WHERE id=$id"; $updateres = dbExecuteAssoc($updateqr) or safeDie("Update failed:
    \n
    $updateqr"); $onerecord_link = $this->getController()->createUrl('/admin/responses/sa/view/surveyid/'.$surveyid.'/id/'.$id); $allrecords_link = $this->getController()->createUrl('/admin/responses/sa/index/surveyid/'.$surveyid); $aDataentryoutput .= "
    ".$clang->gT("Success")."
    \n" .$clang->gT("Record has been updated.")."

    \n" ."

    \n" ."\n" ."
    \n"; $aViewUrls['output'] = $aDataentryoutput; $this->_renderWrappedTemplate('dataentry', $aViewUrls, $aData); } } /** * dataentry::insert() * insert new dataentry * @return */ public function insert() { $clang = Yii::app()->lang; $subaction = Yii::app()->request->getPost('subaction'); $surveyid = Yii::app()->request->getPost('sid'); $lang = isset($_POST['lang']) ? Yii::app()->request->getPost('lang') : NULL; $aData = array( 'surveyid' => $surveyid, 'lang' => $lang, 'clang' => $clang ); if (Permission::model()->hasSurveyPermission($surveyid, 'responses','create')) { if ($subaction == "insert" && Permission::model()->hasSurveyPermission($surveyid,'responses','create')) { $surveytable = "{{survey_{$surveyid}}}"; $thissurvey = getSurveyInfo($surveyid); $errormsg = ""; Yii::app()->loadHelper("database"); $aViewUrls['display']['menu_bars']['browse'] = $clang->gT("Data entry"); $aDataentryoutput = ''; $aDataentrymsgs = array(); $hiddenfields = ''; $lastanswfortoken = ''; // check if a previous answer has been submitted or saved $rlanguage = ''; if (isset($_POST['token'])) { $tokencompleted = ""; $tcquery = "SELECT completed from {{tokens_{$surveyid}}} WHERE token=".dbQuoteAll($_POST['token']); $tcresult = dbExecuteAssoc($tcquery); $tcresult = $tcresult->readAll(); $tccount = count($tcresult); foreach ($tcresult as $tcrow) { $tokencompleted = $tcrow['completed']; } if ($tccount < 1) { // token doesn't exist in token table $lastanswfortoken = 'UnknownToken'; } elseif ($thissurvey['anonymized'] == "Y") { // token exist but survey is anonymous, check completed state if ($tokencompleted != "" && $tokencompleted != "N") { // token is completed $lastanswfortoken='PrivacyProtected'; } } else { // token is valid, survey not anonymous, try to get last recorded response id $aquery = "SELECT id,startlanguage FROM $surveytable WHERE token=".dbQuoteAll($_POST['token']); $aresult = dbExecuteAssoc($aquery); foreach ($aresult->readAll() as $arow) { if ($tokencompleted != "N") { $lastanswfortoken=$arow['id']; } $rlanguage=$arow['startlanguage']; } } } // First Check if the survey uses tokens and if a token has been provided if (tableExists('{{tokens_'.$thissurvey['sid'].'}}') && (!$_POST['token'])) { $errormsg = CHtml::tag('div', array('class'=>'warningheader'), $clang->gT("Error")); $errormsg .= CHtml::tag('p', array(), $clang->gT("This is a closed-access survey, so you must supply a valid token. Please contact the administrator for assistance.")); } elseif (tableExists('{{tokens_'.$thissurvey['sid'].'}}') && $lastanswfortoken == 'UnknownToken') { $errormsg = CHtml::tag('div', array('class'=>'warningheader'), $clang->gT("Error")); $errormsg .= CHtml::tag('p', array(), $clang->gT("The token you have provided is not valid or has already been used.")); } elseif (tableExists('{{tokens_'.$thissurvey['sid'].'}}') && $lastanswfortoken != '') { $errormsg = CHtml::tag('div', array('class'=>'warningheader'), $clang->gT("Error")); $errormsg .= CHtml::tag('p', array(), $clang->gT("There is already a recorded answer for this token")); if ($lastanswfortoken != 'PrivacyProtected') { $errormsg .= "

    ".$clang->gT("Follow the following link to update it").":\n"; $errormsg .= CHtml::link("[id:$lastanswfortoken]", $this->getController()->createUrl('/admin/dataentry/sa/editdata/subaction/edit/id/'.$lastanswfortoken.'/surveyid/'.$surveyid.'/lang/'.$rlanguage), array('title' => $clang->gT("Edit this entry"))); $errormsg .= "

    "; } else { $errormsg .= "

    ".$clang->gT("This surveys uses anonymized responses, so you can't update your response.")."\n"; } } else { $last_db_id = 0; if (isset($_POST['save']) && $_POST['save'] == "on") { $aData['save'] = TRUE; $saver['identifier']=$_POST['save_identifier']; $saver['language']=$_POST['save_language']; $saver['password']=$_POST['save_password']; $saver['passwordconfirm']=$_POST['save_confirmpassword']; $saver['email']=$_POST['save_email']; if (!returnGlobal('redo')) { $password = md5($saver['password']); } else { $password=$saver['password']; } $errormsg=""; if (!$saver['identifier']) { $errormsg .= $clang->gT("Error").": ".$clang->gT("You must supply a name for this saved session.");} if (!$saver['password']) { $errormsg .= $clang->gT("Error").": ".$clang->gT("You must supply a password for this saved session.");} if ($saver['password'] != $saver['passwordconfirm']) { $errormsg .= $clang->gT("Error").": ".$clang->gT("Your passwords do not match.");} $aData['errormsg'] = $errormsg; if ($errormsg) { foreach ($_POST as $key=>$val) { if (substr($key, 0, 4) != "save" && $key != "action" && $key !="sid" && $key != "datestamp" && $key !="ipaddr") { $hiddenfields .= CHtml::hiddenField($key, $val); //$aDataentryoutput .= "\n"; } } } } //BUILD THE SQL TO INSERT RESPONSES $baselang = Survey::model()->findByPk($surveyid)->language; $fieldmap = createFieldMap($surveyid,'full',false,false,getBaseLanguageFromSurveyID($surveyid)); $insert_data = array(); $_POST['startlanguage'] = $baselang; if ($thissurvey['datestamp'] == "Y") { $_POST['startdate'] = $_POST['datestamp']; } if (isset($_POST['closerecord'])) { if ($thissurvey['datestamp'] == "Y") { $_POST['submitdate'] = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", Yii::app()->getConfig('timeadjust')); } else { $_POST['submitdate'] = date("Y-m-d H:i:s",mktime(0,0,0,1,1,1980)); } } foreach ($fieldmap as $irow) { $fieldname = $irow['fieldname']; if (isset($_POST[$fieldname])) { if ($_POST[$fieldname] == "" && ($irow['type'] == 'D' || $irow['type'] == 'N' || $irow['type'] == 'K')) { // can't add '' in Date column // Do nothing } else if ($irow['type'] == '|') { if (!strpos($irow['fieldname'], "_filecount")) { $json = $_POST[$fieldname]; $phparray = json_decode(stripslashes($json)); $filecount = 0; for ($i = 0; $filecount < count($phparray); $i++) { if ($_FILES[$fieldname."_file_".$i]['error'] != 4) { $target = Yii::app()->getConfig('uploaddir')."/surveys/". $thissurvey['sid'] ."/files/".randomChars(20); $size = 0.001 * $_FILES[$fieldname."_file_".$i]['size']; $name = rawurlencode($_FILES[$fieldname."_file_".$i]['name']); if (move_uploaded_file($_FILES[$fieldname."_file_".$i]['tmp_name'], $target)) { $phparray[$filecount]->filename = basename($target); $phparray[$filecount]->name = $name; $phparray[$filecount]->size = $size; $pathinfo = pathinfo($_FILES[$fieldname."_file_".$i]['name']); $phparray[$filecount]->ext = $pathinfo['extension']; $filecount++; } } } $insert_data[$fieldname] = ls_json_encode($phparray); } else { $insert_data[$fieldname] = count($phparray); } } elseif ($irow['type'] == 'D') { Yii::app()->loadLibrary('Date_Time_Converter'); $qidattributes = getQuestionAttributeValues($irow['qid'], $irow['type']); $dateformatdetails = getDateFormatDataForQID($qidattributes, $thissurvey); $datetimeobj = new Date_Time_Converter($_POST[$fieldname],$dateformatdetails['phpdate']); $insert_data[$fieldname] = $datetimeobj->convert("Y-m-d H:i:s"); } else { $insert_data[$fieldname] = $_POST[$fieldname]; } } } SurveyDynamic::sid($surveyid); $new_response = new SurveyDynamic; foreach($insert_data as $column => $value) { $new_response->$column = $value; } $new_response->save(); $last_db_id = $new_response->getPrimaryKey(); if (isset($_POST['closerecord']) && isset($_POST['token']) && $_POST['token'] != '') // submittoken { // get submit date if (isset($_POST['closedate'])) { $submitdate = $_POST['closedate']; } else { $submitdate = dateShift(date("Y-m-d H:i:s"), "Y-m-d", $timeadjust); } // check how many uses the token has left $usesquery = "SELECT usesleft FROM {{tokens_}}$surveyid WHERE token=".dbQuoteAll($_POST['token']); $usesresult = dbExecuteAssoc($usesquery); $usesrow = $usesresult->readAll(); //$usesresult->row_array() if (isset($usesrow)) { $usesleft = $usesrow[0]['usesleft']; } // query for updating tokens $utquery = "UPDATE {{tokens_$surveyid}}\n"; if (isTokenCompletedDatestamped($thissurvey)) { if (isset($usesleft) && $usesleft<=1) { $utquery .= "SET usesleft=usesleft-1, completed='$submitdate'\n"; } else { $utquery .= "SET usesleft=usesleft-1\n"; } } else { if (isset($usesleft) && $usesleft<=1) { $utquery .= "SET usesleft=usesleft-1, completed='Y'\n"; } else { $utquery .= "SET usesleft=usesleft-1\n"; } } $utquery .= "WHERE token=".dbQuoteAll($_POST['token']); $utresult = dbExecuteAssoc($utquery); //Yii::app()->db->Execute($utquery) or safeDie ("Couldn't update tokens table!
    \n$utquery
    \n".Yii::app()->db->ErrorMsg()); // save submitdate into survey table $sdquery = "UPDATE {{survey_$surveyid}} SET submitdate='".$submitdate."' WHERE id={$last_db_id}\n"; $sdresult = dbExecuteAssoc($sdquery) or safeDie ("Couldn't set submitdate response in survey table!
    \n$sdquery
    \n"); $last_db_id = getLastInsertID("{{survey_$surveyid}}"); } if (isset($_POST['save']) && $_POST['save'] == "on") { $srid = $last_db_id; $aUserData=Yii::app()->session; //CREATE ENTRY INTO "saved_control" $saved_control_table = '{{saved_control}}'; $columns = array("sid", "srid", "identifier", "access_code", "email", "ip", "refurl", 'saved_thisstep', "status", "saved_date"); $values = array("'".$surveyid."'", "'".$srid."'", "'".$saver['identifier']."'", "'".$password."'", "'".$saver['email']."'", "'".$aUserData['ip_address']."'", "'".getenv("HTTP_REFERER")."'", 0, "'"."S"."'", "'".dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", "'".Yii::app()->getConfig('timeadjust'))."'"); $SQL = "INSERT INTO $saved_control_table (".implode(',',$columns).") VALUES (".implode(',',$values).")"; /*$scdata = array("sid"=>$surveyid, "srid"=>$srid, "identifier"=>$saver['identifier'], "access_code"=>$password, "email"=>$saver['email'], "ip"=>$aUserData['ip_address'], "refurl"=>getenv("HTTP_REFERER"), 'saved_thisstep' => 0, "status"=>"S", "saved_date"=>dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", Yii::app()->getConfig('timeadjust'))); $this->load->model('saved_control_model');*/ if (dbExecuteAssoc($SQL)) { $scid = getLastInsertID('{{saved_control}}'); $aDataentrymsgs[] = CHtml::tag('font', array('class'=>'successtitle'), $clang->gT("Your survey responses have been saved successfully. You will be sent a confirmation e-mail. Please make sure to save your password, since we will not be able to retrieve it for you.")); //$aDataentryoutput .= "
    \n"; $tokens_table = "{{tokens_$surveyid}}"; if (tableExists($tokens_table)) //If the query fails, assume no tokens table exists { $tkquery = "SELECT * FROM {$tokens_table}"; $tkresult = dbExecuteAssoc($tkquery); /*$tokendata = array ( "firstname"=> $saver['identifier'], "lastname"=> $saver['identifier'], "email"=>$saver['email'], "token"=>randomChars(15), "language"=>$saver['language'], "sent"=>dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i", $timeadjust), "completed"=>"N");*/ $columns = array("firstname", "lastname", "email", "token", "language", "sent", "completed"); $values = array("'".$saver['identifier']."'", "'".$saver['identifier']."'", "'".$saver['email']."'", "'".$password."'", "'".randomChars(15)."'", "'".$saver['language']."'", "'"."N"."'"); $SQL = "INSERT INTO $token_table (".implode(',',$columns).") VALUES (".implode(',',$values).")"; dbExecuteAssoc($SQL); $aDataentrymsgs[] = CHtml::tag('font', array('class'=>'successtitle'), $clang->gT("A token entry for the saved survey has been created too.")); //$aDataentryoutput .= "
    \n"; } if ($saver['email']) { //Send email if (validateEmailAddress($saver['email']) && !returnGlobal('redo')) { $subject = $clang->gT("Saved Survey Details"); $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").": ".$saver['identifier']."\n"; $message .= $clang->gT("Password").": ".$saver['password']."\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/{$iSurveyID}/loadall/reload/scid/{$scid}/loadname/".rawurlencode ($saver['identifier'])."/loadpass/".rawurlencode ($saver['password'])."/lang/".rawurlencode($saver['language'])); if (isset($tokendata['token'])) { $message .= "/token/".rawurlencode($tokendata['token']); } $from = $thissurvey['adminemail']; if (SendEmailMessage($message, $subject, $saver['email'], $from, $sitename, false, getBounceEmail($surveyid))) { $emailsent="Y"; $aDataentrymsgs[] = CHtml::tag('font', array('class'=>'successtitle'), $clang->gT("An email has been sent with details about your saved survey")); } } } } else { safeDie("Unable to insert record into saved_control table.

    "); } } $aData['thisid'] = $last_db_id; } $aData['errormsg'] = $errormsg; $aData['dataentrymsgs'] = $aDataentrymsgs; $this->_renderWrappedTemplate('dataentry', 'insert', $aData); } } } /** * dataentry::view() * view a dataentry * @param mixed $surveyid * @param mixed $lang * @return */ public function view($surveyid, $lang=NULL) { $surveyid = sanitize_int($surveyid); $lang = isset($_GET['lang']) ? $_GET['lang'] : NULL; if(isset($lang)) $lang=sanitize_languagecode($lang); $aViewUrls = array(); if (Permission::model()->hasSurveyPermission($surveyid, 'responses', 'create')) { $clang = Yii::app()->lang; $sDataEntryLanguage = Survey::model()->findByPk($surveyid)->language; $surveyinfo=getSurveyInfo($surveyid); $slangs = Survey::model()->findByPk($surveyid)->additionalLanguages; $baselang = Survey::model()->findByPk($surveyid)->language; array_unshift($slangs,$baselang); if(is_null($lang) || !in_array($lang,$slangs)) { $sDataEntryLanguage = $baselang; $blang = $clang; } else { Yii::app()->loadLibrary('Limesurvey_lang',array($lang)); $blang = new Limesurvey_lang($lang); $sDataEntryLanguage = $lang; } $langlistbox = languageDropdown($surveyid,$sDataEntryLanguage); $thissurvey=getSurveyInfo($surveyid); //This is the default, presenting a blank dataentry form LimeExpressionManager::StartSurvey($surveyid, 'survey', NULL, false, LEM_PRETTY_PRINT_ALL_SYNTAX); $moveResult = LimeExpressionManager::NavigateForwards(); $aData['thissurvey'] = $thissurvey; $aData['langlistbox'] = $langlistbox; $aData['surveyid'] = $surveyid; $aData['blang'] = $blang; $aData['site_url'] = Yii::app()->homeUrl; LimeExpressionManager::StartProcessingPage(true, Yii::app()->baseUrl); // means that all variables are on the same page $aViewUrls[] = 'caption_view'; Yii::app()->loadHelper('database'); // SURVEY NAME AND DESCRIPTION TO GO HERE $degquery = "SELECT * FROM {{groups}} WHERE sid=$surveyid AND language='{$sDataEntryLanguage}' ORDER BY {{groups}}.group_order"; $degresult = dbExecuteAssoc($degquery); // GROUP NAME $aDataentryoutput = ''; foreach ($degresult->readAll() as $degrow) { LimeExpressionManager::StartProcessingGroup($degrow['gid'], ($thissurvey['anonymized']!="N"),$surveyid); $deqquery = "SELECT * FROM {{questions}} WHERE sid=$surveyid AND parent_qid=0 AND gid={$degrow['gid']} AND language='{$sDataEntryLanguage}'"; $deqrows = (array) dbExecuteAssoc($deqquery)->readAll(); $aDataentryoutput .= "\t\n" ."".flattenText($degrow['group_name'],true)."\n" ."\t\n"; $gid = $degrow['gid']; $aDataentryoutput .= "\t\n"; // Perform a case insensitive natural sort on group name then question title of a multidimensional array usort($deqrows, 'groupOrderThenQuestionOrder'); $bgc = 'odd'; foreach ($deqrows as $deqrow) { $cdata = array(); $qidattributes = getQuestionAttributeValues($deqrow['qid'], $deqrow['type']); $cdata['qidattributes'] = $qidattributes; $hidden = (isset($qidattributes['hidden']) ? $qidattributes['hidden'] : 0); // TODO - can questions be hidden? Are JavaScript variables names used? Consistently with everywhere else? // LimeExpressionManager::ProcessRelevance($qidattributes['relevance'],$deqrow['qid'],NULL,$deqrow['type'],$hidden); // TMSW Condition->Relevance: Show relevance equation instead of conditions here - better yet, have data entry use survey-at-a-time but with different view $qinfo = LimeExpressionManager::GetQuestionStatus($deqrow['qid']); $relevance = trim($qinfo['info']['relevance']); $explanation = trim($qinfo['relEqn']); $validation = trim($qinfo['prettyValidTip']); $qidattributes=getQuestionAttributeValues($deqrow['qid']); $array_filter_help = flattenText($this->_array_filter_help($qidattributes, $sDataEntryLanguage, $surveyid)); if (($relevance != '' && $relevance != '1') || ($validation != '') || ($array_filter_help != '')) { $showme = ''; if ($bgc == "even") {$bgc = "odd";} else {$bgc = "even";} //Do no alternate on explanation row if ($relevance != '' && $relevance != '1') { $showme = "[".$blang->gT("Only answer this if the following conditions are met:")."]
    $explanation\n"; } if ($showme != '' && $validation != '') { $showme .= '
    '; } if ($validation != '') { $showme .= "[".$blang->gT("The answer(s) must meet these validation criteria:")."]
    $validation\n"; } if ($showme != '' && $array_filter_help != '') { $showme .= '
    '; } if ($array_filter_help != '') { $showme .= "[".$blang->gT("The answer(s) must meet these array_filter criteria:")."]
    $array_filter_help\n"; } $cdata['explanation'] = "$showme\n"; } //END OF GETTING CONDITIONS //Alternate bgcolor for different groups if (!isset($bgc)) {$bgc = "even";} if ($bgc == "even") {$bgc = "odd";} else {$bgc = "even";} $qid = $deqrow['qid']; $fieldname = "$surveyid"."X"."$gid"."X"."$qid"; $cdata['bgc'] = $bgc; $cdata['fieldname'] = $fieldname; $cdata['deqrow'] = $deqrow; $cdata['clang'] = $clang; //DIFFERENT TYPES OF DATA FIELD HERE $cdata['blang'] = $blang; $cdata['thissurvey'] = $thissurvey; if ($deqrow['help']) { $hh = addcslashes($deqrow['help'], "\0..\37'\""); //Escape ASCII decimal 0-32 plus single and double quotes to make JavaScript happy. $hh = htmlspecialchars($hh, ENT_QUOTES); //Change & " ' < > to HTML entities to make HTML happy. $cdata['hh'] = $hh; //$aDataentryoutput .= "\t".$blang->gT("Help about this question")."\n"; } switch($deqrow['type']) { case "Q": //MULTIPLE SHORT TEXT case "K": $deaquery = "SELECT question,title FROM {{questions}} WHERE parent_qid={$deqrow['qid']} AND language='{$sDataEntryLanguage}' ORDER BY question_order"; $dearesult = dbExecuteAssoc($deaquery); $cdata['dearesult'] = $dearesult->readAll(); break; case "1": // multi scale^ $deaquery = "SELECT * FROM {{questions}} WHERE parent_qid={$deqrow['qid']} AND language='{$baselang}' ORDER BY question_order"; $dearesult = dbExecuteAssoc($deaquery); $cdata['dearesult'] = $dearesult->readAll(); $oquery="SELECT other FROM {{questions}} WHERE qid={$deqrow['qid']} AND language='{$baselang}'"; $oresult=dbExecuteAssoc($oquery) or safeDie("Couldn't get other for list question
    ".$oquery); foreach($oresult->readAll() as $orow) { $cdata['fother']=$orow['other']; } break; case "L": //LIST drop-down/radio-button list case "!": // $qidattributes=getQuestionAttributeValues($deqrow['qid']); if ($deqrow['type']=='!' && trim($qidattributes['category_separator'])!='') { $optCategorySeparator = $qidattributes['category_separator']; } else { unset($optCategorySeparator); } $defexists=""; $deaquery = "SELECT * FROM {{answers}} WHERE qid={$deqrow['qid']} AND language='{$sDataEntryLanguage}' ORDER BY sortorder, answer"; $dearesult = dbExecuteAssoc($deaquery); //$aDataentryoutput .= "\t\n"; $aDatatemp=''; foreach ($dearesult->readAll() as $dearow) // while ($dearow = $dearesult->FetchRow()) { $aDatatemp .= "