Beispiel #1
0
 /**
  * Loads a survey from the database that has the given ID.  If no matching
  * survey is found then null is returned.  Note that no results are loaded
  * from this function call, only survey structure/definition.
  *
  * In the future it would be nice to load all languages from the db at
  * once and have the infrastructure be able to return responses based
  * on language codes.
  *
  * @param int $id
  * @return SurveyObj
  */
 public function loadSurveyById($id, $lang = null)
 {
     $survey = new SurveyObj();
     $clang = Yii::app()->lang;
     $intId = sanitize_int($id);
     $survey->id = $intId;
     $survey->info = getSurveyInfo($survey->id);
     $availableLanguages = Survey::model()->findByPk($intId)->getAllLanguages();
     if (is_null($lang) || in_array($lang, $availableLanguages) === false) {
         // use base language when requested language is not found or no specific language is requested
         $lang = Survey::model()->findByPk($intId)->language;
     }
     $clang = new limesurvey_lang($lang);
     $survey->fieldMap = createFieldMap($intId, 'full', true, false, $lang);
     // Check to see if timings are present and add to fieldmap if needed
     if ($survey->info['savetimings'] == "Y") {
         $survey->fieldMap = $survey->fieldMap + createTimingsFieldMap($intId, 'full', true, false, $lang);
     }
     if (empty($intId)) {
         //The id given to us is not an integer, croak.
         safeDie("An invalid survey ID was encountered: {$sid}");
     }
     //Load groups
     $sQuery = 'SELECT g.* FROM {{groups}} AS g ' . 'WHERE g.sid = ' . $intId . ' AND g.language = \'' . $lang . '\' ' . 'ORDER BY g.group_order;';
     $recordSet = Yii::app()->db->createCommand($sQuery)->query()->readAll();
     $survey->groups = $recordSet;
     //Load questions
     $sQuery = 'SELECT q.* FROM {{questions}} AS q ' . 'JOIN {{groups}} AS g ON (q.gid = g.gid and q.language = g.language) ' . 'WHERE q.sid = ' . $intId . ' AND q.language = \'' . $lang . '\' ' . 'ORDER BY g.group_order, q.question_order;';
     $survey->questions = Yii::app()->db->createCommand($sQuery)->query()->readAll();
     //Load answers
     $sQuery = 'SELECT DISTINCT a.* FROM {{answers}} AS a ' . 'JOIN {{questions}} AS q ON a.qid = q.qid ' . 'WHERE q.sid = ' . $intId . ' AND a.language = \'' . $lang . '\' ' . 'ORDER BY a.qid, a.sortorder;';
     //$survey->answers = Yii::app()->db->createCommand($sQuery)->queryAll();
     $aAnswers = Yii::app()->db->createCommand($sQuery)->queryAll();
     foreach ($aAnswers as $aAnswer) {
         if (Yii::app()->controller->action->id != 'remotecontrol') {
             $aAnswer['answer'] = stripTagsFull($aAnswer['answer']);
         }
         $survey->answers[$aAnswer['qid']][$aAnswer['scale_id']][$aAnswer['code']] = $aAnswer;
     }
     //Load language settings for requested language
     $sQuery = 'SELECT * FROM {{surveys_languagesettings}} WHERE surveyls_survey_id = ' . $intId . ' AND surveyls_language = \'' . $lang . '\';';
     $recordSet = Yii::app()->db->createCommand($sQuery)->query();
     $survey->languageSettings = $recordSet->read();
     $recordSet->close();
     if (tableExists('tokens_' . $survey->id) && array_key_exists('token', SurveyDynamic::model($survey->id)->attributes) && Permission::model()->hasSurveyPermission($survey->id, 'tokens', 'read')) {
         // Now add the tokenFields
         $survey->tokenFields = getTokenFieldsAndNames($survey->id);
         unset($survey->tokenFields['token']);
     }
     return $survey;
 }
/**
* Function to activate a survey
* @param int $iSurveyID The Survey ID
* @param bool $simulate
* @return string
*/
function activateSurvey($iSurveyID, $simulate = false)
{
    $createsurvey = '';
    $activateoutput = '';
    $createsurveytimings = '';
    $fieldstiming = array();
    $createsurveydirectory = false;
    //Check for any additional fields for this survey and create necessary fields (token and datestamp)
    $prow = Survey::model()->findByAttributes(array('sid' => $iSurveyID));
    //Get list of questions for the base language
    $fieldmap = createFieldMap($iSurveyID, 'full', true, false, getBaseLanguageFromSurveyID($iSurveyID));
    $createsurvey = array();
    foreach ($fieldmap as $j => $arow) {
        switch ($arow['type']) {
            case 'startlanguage':
                $createsurvey[$arow['fieldname']] = "string(20) NOT NULL";
                break;
            case 'id':
                $createsurvey[$arow['fieldname']] = "pk";
                break;
            case "startdate":
            case "datestamp":
                $createsurvey[$arow['fieldname']] = "datetime NOT NULL";
                break;
            case "submitdate":
                $createsurvey[$arow['fieldname']] = "datetime";
                break;
            case "lastpage":
                $createsurvey[$arow['fieldname']] = "integer";
                break;
            case "N":
                //Numerical
            //Numerical
            case "K":
                //Multiple Numerical
                $createsurvey[$arow['fieldname']] = "decimal (30,10)";
                break;
            case "S":
                //SHORT TEXT
                $createsurvey[$arow['fieldname']] = "text";
                break;
            case "L":
                //LIST (RADIO)
            //LIST (RADIO)
            case "!":
                //LIST (DROPDOWN)
            //LIST (DROPDOWN)
            case "M":
                //Multiple choice
            //Multiple choice
            case "P":
                //Multiple choice with comment
            //Multiple choice with comment
            case "O":
                //DROPDOWN LIST WITH COMMENT
                if ($arow['aid'] != 'other' && strpos($arow['aid'], 'comment') === false && strpos($arow['aid'], 'othercomment') === false) {
                    $createsurvey[$arow['fieldname']] = "string(5)";
                } else {
                    $createsurvey[$arow['fieldname']] = "text";
                }
                break;
            case "U":
                //Huge text
            //Huge text
            case "Q":
                //Multiple short text
            //Multiple short text
            case "T":
                //LONG TEXT
            //LONG TEXT
            case ";":
                //Multi Flexi
            //Multi Flexi
            case ":":
                //Multi Flexi
                $createsurvey[$arow['fieldname']] = "text";
                break;
            case "D":
                //DATE
                $createsurvey[$arow['fieldname']] = "datetime";
                break;
            case "5":
                //5 Point Choice
            //5 Point Choice
            case "G":
                //Gender
            //Gender
            case "Y":
                //YesNo
            //YesNo
            case "X":
                //Boilerplate
                $createsurvey[$arow['fieldname']] = "string(1)";
                break;
            case "I":
                //Language switch
                $createsurvey[$arow['fieldname']] = "string(20)";
                break;
            case "|":
                $createsurveydirectory = true;
                if (strpos($arow['fieldname'], "_")) {
                    $createsurvey[$arow['fieldname']] = "integer";
                } else {
                    $createsurvey[$arow['fieldname']] = "text";
                }
                break;
            case "ipaddress":
                if ($prow->ipaddr == "Y") {
                    $createsurvey[$arow['fieldname']] = "string";
                }
                break;
            case "url":
                if ($prow->refurl == "Y") {
                    $createsurvey[$arow['fieldname']] = "string";
                }
                break;
            case "token":
                // Specify case sensitive collations for the token
                $sCollation = '';
                if (Yii::app()->db->driverName == 'mysqli' | Yii::app()->db->driverName == 'mysqli') {
                    $sCollation = " COLLATE 'utf8_bin'";
                }
                if (Yii::app()->db->driverName == 'sqlsrv' | Yii::app()->db->driverName == 'dblib' | Yii::app()->db->driverName == 'mssql') {
                    $sCollation = " COLLATE SQL_Latin1_General_CP1_CS_AS";
                }
                $createsurvey[$arow['fieldname']] = 'string(35)' . $sCollation;
                break;
            case '*':
                // Equation
                $createsurvey[$arow['fieldname']] = "text";
                break;
            default:
                $createsurvey[$arow['fieldname']] = "string(5)";
        }
        if ($prow->anonymized == 'N' && !array_key_exists('token', $createsurvey)) {
            $createsurvey['token'] = "string(36)";
        }
        if ($simulate) {
            $tempTrim = trim($createsurvey);
            $brackets = strpos($tempTrim, "(");
            if ($brackets === false) {
                $type = substr($tempTrim, 0, 2);
            } else {
                $type = substr($tempTrim, 0, 2);
            }
            $arrSim[] = array($type);
        }
    }
    if ($simulate) {
        return array('dbengine' => $CI->db->databasetabletype, 'dbtype' => Yii::app()->db->driverName, 'fields' => $arrSim);
    }
    // If last question is of type MCABCEFHP^QKJR let's get rid of the ending coma in createsurvey
    //$createsurvey = rtrim($createsurvey, ",\n")."\n"; // Does nothing if not ending with a comma
    $tabname = "{{survey_{$iSurveyID}}}";
    Yii::app()->loadHelper("database");
    try {
        $execresult = Yii::app()->db->createCommand()->createTable($tabname, $createsurvey);
        Yii::app()->db->schema->getTable($tabname, true);
        // Refresh schema cache just in case the table existed in the past
    } catch (CDbException $e) {
        return array('error' => 'surveytablecreation');
    }
    try {
        if (isset($createsurvey['token'])) {
            Yii::app()->db->createCommand()->createIndex("idx_survey_token_{$iSurveyID}_" . rand(1, 50000), $tabname, 'token');
        }
    } catch (CDbException $e) {
    }
    $anquery = "SELECT autonumber_start FROM {{surveys}} WHERE sid={$iSurveyID}";
    $iAutoNumberStart = Yii::app()->db->createCommand($anquery)->queryScalar();
    //if there is an autonumber_start field, start auto numbering here
    if ($iAutoNumberStart !== false && $iAutoNumberStart > 0) {
        if (Yii::app()->db->driverName == 'mssql' || Yii::app()->db->driverName == 'sqlsrv' || Yii::app()->db->driverName == 'dblib') {
            mssql_drop_primary_index('survey_' . $iSurveyID);
            mssql_drop_constraint('id', 'survey_' . $iSurveyID);
            $sQuery = "ALTER TABLE {{survey_{$iSurveyID}}} drop column id ";
            Yii::app()->db->createCommand($sQuery)->execute();
            $sQuery = "ALTER TABLE {{survey_{$iSurveyID}}} ADD [id] int identity({$iAutoNumberStart},1)";
            Yii::app()->db->createCommand($sQuery)->execute();
            // Add back the primaryKey
            Yii::app()->db->createCommand()->addPrimaryKey('PRIMARY', '{{survey_' . $iSurveyID . '}}', 'id');
        } elseif (Yii::app()->db->driverName == 'pgsql') {
            $sQuery = "SELECT setval(pg_get_serial_sequence('{{survey_{$iSurveyID}}}', 'id'),{$iAutoNumberStart},false);";
            $result = @Yii::app()->db->createCommand($sQuery)->execute();
        } else {
            $sQuery = "ALTER TABLE {{survey_{$iSurveyID}}} AUTO_INCREMENT = {$iAutoNumberStart}";
            $result = @Yii::app()->db->createCommand($sQuery)->execute();
        }
    }
    if ($prow->savetimings == "Y") {
        $timingsfieldmap = createTimingsFieldMap($iSurveyID, "full", false, false, getBaseLanguageFromSurveyID($iSurveyID));
        $column = array();
        $column['id'] = $createsurvey['id'];
        foreach ($timingsfieldmap as $field => $fielddata) {
            $column[$field] = 'FLOAT';
        }
        $tabname = "{{survey_{$iSurveyID}_timings}}";
        try {
            $execresult = Yii::app()->db->createCommand()->createTable($tabname, $column);
            Yii::app()->db->schema->getTable($tabname, true);
            // Refresh schema cache just in case the table existed in the past
        } catch (CDbException $e) {
            return array('error' => 'timingstablecreation');
        }
    }
    $aResult = array('status' => 'OK');
    // create the survey directory where the uploaded files can be saved
    if ($createsurveydirectory) {
        if (!file_exists(Yii::app()->getConfig('uploaddir') . "/surveys/" . $iSurveyID . "/files")) {
            if (!mkdir(Yii::app()->getConfig('uploaddir') . "/surveys/" . $iSurveyID . "/files", 0777, true)) {
                $aResult['warning'] = 'nouploadsurveydir';
            } else {
                file_put_contents(Yii::app()->getConfig('uploaddir') . "/surveys/" . $iSurveyID . "/files/index.html", '<html><head></head><body></body></html>');
            }
        }
    }
    $acquery = "UPDATE {{surveys}} SET active='Y' WHERE sid=" . $iSurveyID;
    $acresult = Yii::app()->db->createCommand($acquery)->query();
    return $aResult;
}
Beispiel #3
0
 public function exportresults()
 {
     $iSurveyID = sanitize_int(Yii::app()->request->getParam('surveyid'));
     if (!isset($imageurl)) {
         $imageurl = "./images";
     }
     if (!isset($iSurveyID)) {
         $iSurveyID = returnGlobal('sid');
     }
     if (!isset($exportstyle)) {
         $exportstyle = returnGlobal('exportstyle');
     }
     if (!isset($answers)) {
         $answers = returnGlobal('answers');
     }
     if (!isset($type)) {
         $type = returnGlobal('type');
     }
     if (!isset($convertyto1)) {
         $convertyto1 = returnGlobal('convertyto1');
     }
     if (!isset($convertnto2)) {
         $convertnto2 = returnGlobal('convertnto2');
     }
     if (!isset($convertyto)) {
         $convertyto = returnGlobal('convertyto');
     }
     if (!isset($convertnto)) {
         $convertnto = returnGlobal('convertnto');
     }
     if (!isset($convertspacetous)) {
         $convertspacetous = returnGlobal('convertspacetous');
     }
     $clang = Yii::app()->lang;
     if (!hasSurveyPermission($iSurveyID, 'responses', 'export')) {
         exit;
     }
     Yii::app()->loadHelper("admin/exportresults");
     $surveybaselang = Survey::model()->findByPk($iSurveyID)->language;
     $exportoutput = "";
     // Get info about the survey
     $thissurvey = getSurveyInfo($iSurveyID);
     if (!$exportstyle) {
         //FIND OUT HOW MANY FIELDS WILL BE NEEDED - FOR 255 COLUMN LIMIT
         $aFieldMap = createFieldMap($iSurveyID, 'full', false, false, getBaseLanguageFromSurveyID($iSurveyID));
         if ($thissurvey['savetimings'] === "Y") {
             //Append survey timings to the fieldmap array
             $aFieldMap = $aFieldMap + createTimingsFieldMap($iSurveyID, 'full', false, false, getBaseLanguageFromSurveyID($iSurveyID));
         }
         $iFieldCount = count($aFieldMap);
         $selecthide = "";
         $selectshow = "";
         $selectinc = "";
         if (incompleteAnsFilterState() == "complete") {
             $selecthide = "selected='selected'";
         } elseif (incompleteAnsFilterState() == "incomplete") {
             $selectinc = "selected='selected'";
         } else {
             $selectshow = "selected='selected'";
         }
         $data['SingleResponse'] = (int) returnGlobal('id');
         $data['selecthide'] = $selecthide;
         $data['selectshow'] = $selectshow;
         $data['selectinc'] = $selectinc;
         $data['afieldcount'] = $iFieldCount;
         $data['excesscols'] = $aFieldMap;
         //get max number of datasets
         $iMaximum = Yii::app()->db->createCommand("SELECT count(id) FROM {{survey_" . intval($iSurveyID) . "}}")->queryScalar();
         $data['max_datasets'] = $iMaximum;
         $data['surveyid'] = $iSurveyID;
         $data['imageurl'] = Yii::app()->getConfig('imageurl');
         $data['thissurvey'] = $thissurvey;
         $data['display']['menu_bars']['browse'] = $clang->gT("Export results");
         $this->_renderWrappedTemplate('export', 'exportresults_view', $data);
         return;
     }
     // Export Language is set by default to surveybaselang
     // * the explang language code is used in SQL queries
     // * the alang object is used to translate headers and hardcoded answers
     // In the future it might be possible to 'post' the 'export language' from
     // the exportresults form
     $explang = $surveybaselang;
     $elang = new limesurvey_lang($explang);
     //Get together our FormattingOptions and then call into the exportSurvey
     //function.
     $options = new FormattingOptions();
     $options->selectedColumns = Yii::app()->request->getPost('colselect');
     $options->responseMinRecord = sanitize_int(Yii::app()->request->getPost('export_from'));
     $options->responseMaxRecord = sanitize_int(Yii::app()->request->getPost('export_to'));
     $options->answerFormat = $answers;
     $options->convertN = $convertnto2;
     $options->output = 'display';
     if ($options->convertN) {
         $options->nValue = $convertnto;
     }
     $options->convertY = $convertyto1;
     if ($options->convertY) {
         $options->yValue = $convertyto;
     }
     $options->headerSpacesToUnderscores = $convertspacetous;
     $options->headingFormat = $exportstyle;
     $options->responseCompletionState = incompleteAnsFilterState();
     // Replace token information by the column name
     if (in_array('first_name', Yii::app()->request->getPost('attribute_select', array()))) {
         $options->selectedColumns[] = "firstname";
     }
     if (in_array('last_name', Yii::app()->request->getPost('attribute_select', array()))) {
         $options->selectedColumns[] = "lastname";
     }
     if (in_array('email_address', Yii::app()->request->getPost('attribute_select', array()))) {
         $options->selectedColumns[] = "email";
     }
     $attributeFields = array_keys(getTokenFieldsAndNames($iSurveyID, TRUE));
     foreach ($attributeFields as $attr_name) {
         if (in_array($attr_name, Yii::app()->request->getPost('attribute_select', array()))) {
             $options->selectedColumns[] = $attr_name;
         }
     }
     if (Yii::app()->request->getPost('response_id')) {
         $sFilter = 'id=' . (int) Yii::app()->request->getPost('response_id');
     } else {
         $sFilter = '';
     }
     $resultsService = new ExportSurveyResultsService();
     $resultsService->exportSurvey($iSurveyID, $explang, $type, $options, $sFilter);
     exit;
 }
/**
* Function to activate a survey
* @param int $iSurveyID The Survey ID
* @param bool $simulate
* @return string
*/
function activateSurvey($iSurveyID, $simulate = false)
{
    $createsurvey = '';
    $activateoutput = '';
    $createsurveytimings = '';
    $fieldstiming = array();
    $createsurveydirectory = false;
    //Check for any additional fields for this survey and create necessary fields (token and datestamp)
    $prow = Survey::model()->findByAttributes(array('sid' => $iSurveyID));
    //Get list of questions for the base language
    $fieldmap = createFieldMap($iSurveyID, 'full', true, false, getBaseLanguageFromSurveyID($iSurveyID));
    $createsurvey = array();
    foreach ($fieldmap as $j => $arow) {
        switch ($arow['type']) {
            case 'startlanguage':
                $createsurvey[$arow['fieldname']] = "VARCHAR(20) NOT NULL";
                break;
            case 'id':
                $createsurvey[$arow['fieldname']] = "pk";
                break;
            case "startdate":
            case "datestamp":
                $createsurvey[$arow['fieldname']] = "datetime NOT NULL";
                break;
            case "submitdate":
                $createsurvey[$arow['fieldname']] = "datetime";
                break;
            case "lastpage":
                $createsurvey[$arow['fieldname']] = "integer";
                break;
            case "N":
                //NUMERICAL
                $createsurvey[$arow['fieldname']] = "decimal (30,10)";
                break;
            case "S":
                //SHORT TEXT
                if (Yii::app()->db->driverName == 'mysql' || Yii::app()->db->driverName == 'mysqli') {
                    $createsurvey[$arow['fieldname']] = "text";
                } else {
                    $createsurvey[$arow['fieldname']] = "string";
                }
                break;
            case "L":
                //LIST (RADIO)
            //LIST (RADIO)
            case "!":
                //LIST (DROPDOWN)
            //LIST (DROPDOWN)
            case "M":
                //Multiple choice
            //Multiple choice
            case "P":
                //Multiple choice with comment
            //Multiple choice with comment
            case "O":
                //DROPDOWN LIST WITH COMMENT
                if ($arow['aid'] != 'other' && strpos($arow['aid'], 'comment') === false && strpos($arow['aid'], 'othercomment') === false) {
                    $createsurvey[$arow['fieldname']] = "VARCHAR(5)";
                } else {
                    $createsurvey[$arow['fieldname']] = "text";
                }
                break;
            case "K":
                // Multiple Numerical
                $createsurvey[$arow['fieldname']] = "float";
                break;
            case "U":
                //Huge text
            //Huge text
            case "Q":
                //Multiple short text
            //Multiple short text
            case "T":
                //LONG TEXT
            //LONG TEXT
            case ";":
                //Multi Flexi
            //Multi Flexi
            case ":":
                //Multi Flexi
                $createsurvey[$arow['fieldname']] = "text";
                break;
            case "D":
                //DATE
                $createsurvey[$arow['fieldname']] = "datetime";
                break;
            case "5":
                //5 Point Choice
            //5 Point Choice
            case "G":
                //Gender
            //Gender
            case "Y":
                //YesNo
            //YesNo
            case "X":
                //Boilerplate
                $createsurvey[$arow['fieldname']] = "VARCHAR(1)";
                break;
            case "I":
                //Language switch
                $createsurvey[$arow['fieldname']] = "VARCHAR(20)";
                break;
            case "|":
                $createsurveydirectory = true;
                if (strpos($arow['fieldname'], "_")) {
                    $createsurvey[$arow['fieldname']] = "integer";
                } else {
                    $createsurvey[$arow['fieldname']] = "text";
                }
                break;
            case "ipaddress":
                if ($prow->ipaddr == "Y") {
                    $createsurvey[$arow['fieldname']] = "text";
                }
                break;
            case "url":
                if ($prow->refurl == "Y") {
                    $createsurvey[$arow['fieldname']] = "text";
                }
                break;
            case "token":
                if ($prow->anonymized == "N") {
                    $createsurvey[$arow['fieldname']] = "VARCHAR(36)";
                }
                break;
            case '*':
                // Equation
                $createsurvey[$arow['fieldname']] = "text";
                break;
            default:
                $createsurvey[$arow['fieldname']] = "VARCHAR(5)";
        }
        if ($simulate) {
            $tempTrim = trim($createsurvey);
            $brackets = strpos($tempTrim, "(");
            if ($brackets === false) {
                $type = substr($tempTrim, 0, 2);
            } else {
                $type = substr($tempTrim, 0, 2);
            }
            $arrSim[] = array($type);
        }
    }
    if ($simulate) {
        return array('dbengine' => $CI->db->databasetabletype, 'dbtype' => Yii::app()->db->driverName, 'fields' => $arrSim);
    }
    // If last question is of type MCABCEFHP^QKJR let's get rid of the ending coma in createsurvey
    //$createsurvey = rtrim($createsurvey, ",\n")."\n"; // Does nothing if not ending with a comma
    $tabname = "{{survey_{$iSurveyID}}}";
    $command = new CDbCommand(Yii::app()->db);
    try {
        $execresult = $command->createTable($tabname, $createsurvey);
    } catch (CDbException $e) {
        return array('error' => 'surveytablecreation');
    }
    $anquery = "SELECT autonumber_start FROM {{surveys}} WHERE sid={$iSurveyID}";
    if ($anresult = Yii::app()->db->createCommand($anquery)->query()->readAll()) {
        //if there is an autonumber_start field, start auto numbering here
        foreach ($anresult as $row) {
            if ($row['autonumber_start'] > 0) {
                if (Yii::app()->db->driverName == 'mssql' || Yii::app()->db->driverName == 'sqlsrv') {
                    mssql_drop_primary_index('survey_' . $iSurveyID);
                    mssql_drop_constraint('id', 'survey_' . $iSurveyID);
                    $autonumberquery = "alter table {{survey_{$iSurveyID}}} drop column id ";
                    Yii::app()->db->createCommand($autonumberquery)->execute();
                    $autonumberquery = "alter table {{survey_{$iSurveyID}}} add [id] int identity({$row['autonumber_start']},1)";
                    Yii::app()->db->createCommand($autonumberquery)->execute();
                } elseif (Yii::app()->db->driverName == 'pgsql') {
                } else {
                    $autonumberquery = "ALTER TABLE {{survey_{$iSurveyID}}} AUTO_INCREMENT = " . $row['autonumber_start'];
                    $result = @Yii::app()->db->createCommand($autonumberquery)->execute();
                }
            }
        }
    }
    if ($prow->savetimings == "Y") {
        $timingsfieldmap = createTimingsFieldMap($iSurveyID, "full", false, false, getBaseLanguageFromSurveyID($iSurveyID));
        $column = array();
        $column['id'] = $createsurvey['id'];
        foreach ($timingsfieldmap as $field => $fielddata) {
            $column[$field] = 'FLOAT';
        }
        $command = new CDbCommand(Yii::app()->db);
        $tabname = "{{survey_{$iSurveyID}}}_timings";
        try {
            $execresult = $command->createTable($tabname, $column);
        } catch (CDbException $e) {
            return array('error' => 'timingstablecreation');
        }
    }
    $aResult = array('status' => 'OK');
    // create the survey directory where the uploaded files can be saved
    if ($createsurveydirectory) {
        if (!file_exists(Yii::app()->getConfig('uploaddir') . "/surveys/" . $iSurveyID . "/files")) {
            if (!mkdir(Yii::app()->getConfig('uploaddir') . "/surveys/" . $iSurveyID . "/files", 0777, true)) {
                $aResult['warning'] = 'nouploadsurveydir';
            } else {
                file_put_contents(Yii::app()->getConfig('uploaddir') . "/surveys/" . $iSurveyID . "/files/index.html", '<html><head></head><body></body></html>');
            }
        }
    }
    $acquery = "UPDATE {{surveys}} SET active='Y' WHERE sid=" . $iSurveyID;
    $acresult = Yii::app()->db->createCommand($acquery)->query();
    return $aResult;
}
     $_POST['deleteanswer'] = (int) $_POST['deleteanswer'];
     // sanitize the value
     $query = "delete FROM {$surveytable} where id={$_POST['deleteanswer']}";
     $connect->execute($query) or safe_die("Could not delete response<br />{$dtquery}<br />" . $connect->ErrorMsg());
     // checked
 }
 if (isset($_POST['markedresponses']) && count($_POST['markedresponses']) > 0) {
     foreach ($_POST['markedresponses'] as $iResponseID) {
         $iResponseID = (int) $iResponseID;
         // sanitize the value
         $query = "delete FROM {$surveytable} where id={$iResponseID}";
         $connect->execute($query) or safe_die("Could not delete response<br />{$dtquery}<br />" . $connect->ErrorMsg());
         // checked
     }
 }
 $fields = createTimingsFieldMap($surveyid, 'full');
 foreach ($fields as $fielddetails) {
     // headers for answer id and time data
     if ($fielddetails['type'] == 'id') {
         $fnames[] = array($fielddetails['fieldname'], $fielddetails['question']);
     }
     if ($fielddetails['type'] == 'interview_time') {
         $fnames[] = array($fielddetails['fieldname'], $clang->gT('Total time'));
     }
     if ($fielddetails['type'] == 'page_time') {
         $fnames[] = array($fielddetails['fieldname'], $clang->gT('Group') . ": " . $fielddetails['group_name']);
     }
     if ($fielddetails['type'] == 'answer_time') {
         $fnames[] = array($fielddetails['fieldname'], $clang->gT('Question') . ": " . $fielddetails['title']);
     }
 }
Beispiel #6
0
 public function time($iSurveyID)
 {
     $aData = $this->_getData(array('iSurveyId' => $iSurveyID));
     extract($aData);
     $aViewUrls = array();
     if ($aData['surveyinfo']['savetimings'] != "Y") {
         die;
     }
     if (Yii::app()->request->getPost('deleteanswer') && Yii::app()->request->getPost('deleteanswer') != '' && Yii::app()->request->getPost('deleteanswer') != 'marked' && Permission::model()->hasSurveyPermission($iSurveyID, 'responses', 'delete')) {
         $iResponseID = (int) Yii::app()->request->getPost('deleteanswer');
         SurveyDynamic::model($iSurveyID)->deleteByPk($iResponseID);
         SurveyTimingDynamic::model($iSurveyID)->deleteByPk($iResponseID);
     }
     if (Yii::app()->request->getPost('markedresponses') && count(Yii::app()->request->getPost('markedresponses')) > 0) {
         if (Yii::app()->request->getPost('deleteanswer') && Yii::app()->request->getPost('deleteanswer') === 'marked' && Permission::model()->hasSurveyPermission($iSurveyID, 'responses', 'delete')) {
             foreach (Yii::app()->request->getPost('markedresponses') as $iResponseID) {
                 $iResponseID = (int) $iResponseID;
                 SurveyDynamic::model($iSurveyID)->deleteByPk($iResponseID);
                 SurveyTimingDynamic::model($iSurveyID)->deleteByPk($iResponseID);
             }
         }
     }
     $fields = createTimingsFieldMap($iSurveyID, 'full', true, false, $aData['language']);
     foreach ($fields as $fielddetails) {
         // headers for answer id and time data
         if ($fielddetails['type'] == 'id') {
             $fnames[] = array($fielddetails['fieldname'], $fielddetails['question']);
         }
         if ($fielddetails['type'] == 'interview_time') {
             $fnames[] = array($fielddetails['fieldname'], gT('Total time'));
         }
         if ($fielddetails['type'] == 'page_time') {
             $fnames[] = array($fielddetails['fieldname'], gT('Group') . ": " . $fielddetails['group_name']);
         }
         if ($fielddetails['type'] == 'answer_time') {
             $fnames[] = array($fielddetails['fieldname'], gT('Question') . ": " . $fielddetails['title']);
         }
     }
     $fncount = count($fnames);
     //NOW LETS CREATE A TABLE WITH THOSE HEADINGS
     foreach ($fnames as $fn) {
         if (!isset($currentgroup)) {
             $currentgroup = $fn[1];
             $gbc = "oddrow";
         }
         if ($currentgroup != $fn[1]) {
             $currentgroup = $fn[1];
             if ($gbc == "oddrow") {
                 $gbc = "evenrow";
             } else {
                 $gbc = "oddrow";
             }
         }
     }
     $aData['fnames'] = $fnames;
     $start = Yii::app()->request->getParam('start', 0);
     $limit = Yii::app()->request->getParam('limit', 50);
     if (!$limit) {
         $limit = 50;
     }
     //LETS COUNT THE DATA
     $oCriteria = new CdbCriteria();
     $oCriteria->select = 'tid';
     $oCriteria->join = "INNER JOIN {{survey_{$iSurveyID}}} s ON t.id=s.id";
     $oCriteria->condition = 'submitdate IS NOT NULL';
     $dtcount = SurveyTimingDynamic::model($iSurveyID)->count($oCriteria);
     // or die("Couldn't get response data");
     if ($limit > $dtcount) {
         $limit = $dtcount;
     }
     //NOW LETS SHOW THE DATA
     $oCriteria = new CdbCriteria();
     $oCriteria->join = "INNER JOIN {{survey_{$iSurveyID}}} s ON t.id=s.id";
     $oCriteria->condition = 'submitdate IS NOT NULL';
     $oCriteria->order = "s.id " . (Yii::app()->request->getParam('order') == 'desc' ? 'desc' : 'asc');
     $oCriteria->offset = $start;
     $oCriteria->limit = $limit;
     $dtresult = SurveyTimingDynamic::model($iSurveyID)->findAllAsArray($oCriteria);
     $dtcount2 = count($dtresult);
     $cells = $fncount + 1;
     //CONTROL MENUBAR
     $last = $start - $limit;
     $next = $start + $limit;
     $end = $dtcount - $limit;
     if ($end < 0) {
         $end = 0;
     }
     if ($last < 0) {
         $last = 0;
     }
     if ($next >= $dtcount) {
         $next = $dtcount - $limit;
     }
     if ($end < 0) {
         $end = 0;
     }
     $aData['sCompletionStateValue'] = incompleteAnsFilterState();
     $aData['start'] = $start;
     $aData['limit'] = $limit;
     $aData['last'] = $last;
     $aData['next'] = $next;
     $aData['end'] = $end;
     $aViewUrls[] = 'browsetimeheader_view';
     $aData['fncount'] = $fncount;
     $bgcc = 'oddrow';
     foreach ($dtresult as $dtrow) {
         if ($bgcc == "evenrow") {
             $bgcc = "oddrow";
         } else {
             $bgcc = "evenrow";
         }
         $browsedatafield = array();
         for ($i = 0; $i < $fncount; $i++) {
             $browsedatafield[$i] = $dtrow[$fnames[$i][0]];
             // seconds -> minutes & seconds
             if (strtolower(substr($fnames[$i][0], -4)) == "time") {
                 $minutes = (int) ($browsedatafield[$i] / 60);
                 $seconds = $browsedatafield[$i] % 60;
                 $browsedatafield[$i] = '';
                 if ($minutes > 0) {
                     $browsedatafield[$i] .= "{$minutes} min ";
                 }
                 $browsedatafield[$i] .= "{$seconds} s";
             }
         }
         $aData['browsedatafield'] = $browsedatafield;
         $aData['bgcc'] = $bgcc;
         $aData['dtrow'] = $dtrow;
         $aViewUrls['browsetimerow_view'][] = $aData;
     }
     //interview Time statistics
     $aData['statistics'] = SurveyTimingDynamic::model($iSurveyId)->statistics();
     $aData['num_total_answers'] = SurveyDynamic::model($iSurveyID)->count();
     $aData['num_completed_answers'] = SurveyDynamic::model($iSurveyID)->count('submitdate IS NOT NULL');
     $aViewUrls[] = 'browsetimefooter_view';
     $this->_renderWrappedTemplate('', $aViewUrls, $aData);
 }
 /**
  * Loads a survey from the database that has the given ID.  If no matching
  * survey is found then null is returned.  Note that no results are loaded
  * from this function call, only survey structure/definition.
  *
  * In the future it would be nice to load all languages from the db at
  * once and have the infrastructure be able to return responses based
  * on language codes.
  *
  * @param int $id
  * @return Survey
  */
 public function loadSurveyById($id)
 {
     $survey = new SurveyObj();
     $clang = Yii::app()->lang;
     $intId = sanitize_int($id);
     $survey->id = $intId;
     $survey->info = getSurveyInfo($survey->id);
     $lang = Survey::model()->findByPk($intId)->language;
     $clang = new limesurvey_lang($lang);
     $survey->fieldMap = createFieldMap($intId, 'full', false, false, getBaseLanguageFromSurveyID($intId));
     // Check to see if timings are present and add to fieldmap if needed
     if ($survey->info['savetimings'] == "Y") {
         $survey->fieldMap = $survey->fieldMap + createTimingsFieldMap($intId, 'full', false, false, getBaseLanguageFromSurveyID($intId));
     }
     if (empty($intId)) {
         //The id given to us is not an integer, croak.
         safeDie("An invalid survey ID was encountered: {$sid}");
     }
     //Load groups
     $sQuery = 'SELECT g.* FROM {{groups}} AS g ' . 'WHERE g.sid = ' . $intId . ' ' . 'ORDER BY g.group_order;';
     $recordSet = Yii::app()->db->createCommand($sQuery)->query()->readAll();
     $survey->groups = $recordSet;
     //Load questions
     $sQuery = 'SELECT q.* FROM {{questions}} AS q ' . 'JOIN {{groups}} AS g ON q.gid = g.gid ' . 'WHERE q.sid = ' . $intId . ' AND q.language = \'' . $lang . '\' ' . 'ORDER BY g.group_order, q.question_order;';
     $survey->questions = Yii::app()->db->createCommand($sQuery)->query()->readAll();
     //Load answers
     $sQuery = 'SELECT DISTINCT a.* FROM {{answers}} AS a ' . 'JOIN {{questions}} AS q ON a.qid = q.qid ' . 'WHERE q.sid = ' . $intId . ' AND a.language = \'' . $lang . '\' ' . 'ORDER BY a.qid, a.sortorder;';
     //$survey->answers = Yii::app()->db->createCommand($sQuery)->queryAll();
     $aAnswers = Yii::app()->db->createCommand($sQuery)->queryAll();
     foreach ($aAnswers as $aAnswer) {
         $aAnswer['answer'] = stripTagsFull($aAnswer['answer']);
         $survey->answers[$aAnswer['qid']][$aAnswer['scale_id']][$aAnswer['code']] = $aAnswer;
     }
     //Load tokens
     if (tableExists('{{tokens_' . $intId . '}}')) {
         $sQuery = 'SELECT t.* FROM {{tokens_' . $intId . '}} AS t;';
         $recordSet = Yii::app()->db->createCommand($sQuery)->query()->readAll();
         $survey->tokens = $recordSet;
     } else {
         $survey->tokens = array();
     }
     //Load language settings
     $sQuery = 'SELECT * FROM {{surveys_languagesettings}} WHERE surveyls_survey_id = ' . $intId . ';';
     $recordSet = Yii::app()->db->createCommand($sQuery)->query()->readAll();
     $survey->languageSettings = $recordSet;
     return $survey;
 }
Beispiel #8
0
 public function exportresults()
 {
     $iSurveyID = sanitize_int(Yii::app()->request->getParam('surveyid'));
     if (!isset($imageurl)) {
         $imageurl = "./images";
     }
     if (!isset($iSurveyID)) {
         $iSurveyID = returnGlobal('sid');
     }
     if (!isset($convertyto1)) {
         $convertyto1 = returnGlobal('convertyto1');
     }
     if (!isset($convertnto2)) {
         $convertnto2 = returnGlobal('convertnto2');
     }
     if (!isset($convertyto)) {
         $convertyto = returnGlobal('convertyto');
     }
     if (!isset($convertnto)) {
         $convertnto = returnGlobal('convertnto');
     }
     if (!Permission::model()->hasSurveyPermission($iSurveyID, 'responses', 'export')) {
         $this->getController()->error('Access denied!');
     }
     Yii::app()->loadHelper("admin/exportresults");
     App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('generalscripts') . "expressions/em_javascript.js");
     App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('adminscripts') . '/exportresults.js');
     $sExportType = Yii::app()->request->getPost('type');
     $sHeadingFormat = Yii::app()->request->getPost('headstyle');
     $sAnswerFormat = Yii::app()->request->getPost('answers');
     $bHeaderSpacesToUnderscores = Yii::app()->request->getPost('headspacetounderscores');
     $bConvertY = Yii::app()->request->getPost('converty');
     $bConvertN = Yii::app()->request->getPost('convertn');
     $sYValue = Yii::app()->request->getPost('convertyto');
     $sNValue = Yii::app()->request->getPost('convertnto');
     $surveybaselang = Survey::model()->findByPk($iSurveyID)->language;
     $exportoutput = "";
     // Get info about the survey
     $thissurvey = getSurveyInfo($iSurveyID);
     // Load ExportSurveyResultsService so we know what exports are available
     $resultsService = new ExportSurveyResultsService();
     $exports = $resultsService->getExports();
     if (!$sExportType) {
         //FIND OUT HOW MANY FIELDS WILL BE NEEDED - FOR 255 COLUMN LIMIT
         $aFieldMap = createFieldMap($iSurveyID, 'full', false, false, getBaseLanguageFromSurveyID($iSurveyID));
         if ($thissurvey['savetimings'] === "Y") {
             //Append survey timings to the fieldmap array
             $aFieldMap = $aFieldMap + createTimingsFieldMap($iSurveyID, 'full', false, false, getBaseLanguageFromSurveyID($iSurveyID));
         }
         $iFieldCount = count($aFieldMap);
         $selecthide = "";
         $selectshow = "";
         $selectinc = "";
         if (incompleteAnsFilterState() == "complete") {
             $selecthide = "selected='selected'";
         } elseif (incompleteAnsFilterState() == "incomplete") {
             $selectinc = "selected='selected'";
         } else {
             $selectshow = "selected='selected'";
         }
         $aFields = array();
         foreach ($aFieldMap as $sFieldName => $fieldinfo) {
             $sCode = viewHelper::getFieldCode($fieldinfo);
             $aFields[$sFieldName] = $sCode . ' - ' . htmlspecialchars(ellipsize(html_entity_decode(viewHelper::getFieldText($fieldinfo)), 30, 0.6, '...'));
             $aFieldsOptions[$sFieldName] = array('title' => viewHelper::getFieldText($fieldinfo), 'data-fieldname' => $fieldinfo['fieldname'], 'data-emcode' => viewHelper::getFieldCode($fieldinfo, array('LEMcompat' => true)));
             // No need to filter title : Yii do it (remove all tag)
         }
         $data['SingleResponse'] = (int) returnGlobal('id');
         $data['selecthide'] = $selecthide;
         $data['selectshow'] = $selectshow;
         $data['selectinc'] = $selectinc;
         $data['afieldcount'] = $iFieldCount;
         $data['aFields'] = $aFields;
         $data['aFieldsOptions'] = $aFieldsOptions;
         //get max number of datasets
         $iMaximum = SurveyDynamic::model($iSurveyID)->getMaxId();
         $data['max_datasets'] = $iMaximum;
         $data['surveyid'] = $iSurveyID;
         $data['imageurl'] = Yii::app()->getConfig('imageurl');
         $data['thissurvey'] = $thissurvey;
         $data['display']['menu_bars']['browse'] = gT("Export results");
         // Export plugins, leave out all entries that are not plugin
         $exports = array_filter($exports);
         $exportData = array();
         foreach ($exports as $key => $plugin) {
             $event = new PluginEvent('listExportOptions');
             $event->set('type', $key);
             $oPluginManager = App()->getPluginManager();
             $oPluginManager->dispatchEvent($event, $plugin);
             $exportData[$key] = array('onclick' => $event->get('onclick'), 'label' => $event->get('label'), 'checked' => $event->get('default', false), 'tooltip' => $event->get('tooltip', null));
         }
         $data['exports'] = $exportData;
         // Pass available exports
         $data['headexports'] = array('code' => array('label' => gT("Question code"), 'help' => null, 'checked' => false), 'abbreviated' => array('label' => gT("Abbreviated question text"), 'help' => null, 'checked' => false), 'full' => array('label' => gT("Full question text"), 'help' => null, 'checked' => true), 'codetext' => array('label' => gT("Question code and question text"), 'help' => null, 'checked' => false));
         // Add a plugin for adding headexports : a public function getRegistereddPlugins($event) can help here.
         $aLanguagesCode = Survey::model()->findByPk($iSurveyID)->getAllLanguages();
         $aLanguages = array();
         foreach ($aLanguagesCode as $sLanguage) {
             $aLanguages[$sLanguage] = getLanguageNameFromCode($sLanguage, false);
         }
         $data['aLanguages'] = $aLanguages;
         // Pass available exports
         $this->_renderWrappedTemplate('export', 'exportresults_view', $data);
         return;
     }
     // Export Language is set by default to surveybaselang
     // * the explang language code is used in SQL queries
     // * the alang object is used to translate headers and hardcoded answers
     // In the future it might be possible to 'post' the 'export language' from
     // the exportresults form
     $explang = Yii::app()->request->getPost('exportlang', $surveybaselang);
     //Get together our FormattingOptions and then call into the exportSurvey
     //function.
     $options = new FormattingOptions();
     $options->selectedColumns = Yii::app()->request->getPost('colselect');
     $options->responseMinRecord = sanitize_int(Yii::app()->request->getPost('export_from'));
     $options->responseMaxRecord = sanitize_int(Yii::app()->request->getPost('export_to'));
     $options->answerFormat = $sAnswerFormat;
     $options->convertY = $bConvertY;
     $options->yValue = $bConvertY ? $sYValue : null;
     $options->convertN = $bConvertN;
     $options->nValue = $bConvertN ? $sNValue : null;
     $options->headingTextLength = Yii::app()->request->getPost('abbreviatedtext') ? (int) Yii::app()->request->getPost('abbreviatedtextto') : null;
     $options->useEMCode = Yii::app()->request->getPost('emcode');
     $options->headCodeTextSeparator = Yii::app()->request->getPost('codetextseparator');
     $options->headerSpacesToUnderscores = $bHeaderSpacesToUnderscores;
     $options->headingFormat = $sHeadingFormat;
     $options->responseCompletionState = incompleteAnsFilterState();
     $options->output = 'display';
     // Replace token information by the column name
     if (in_array('first_name', Yii::app()->request->getPost('attribute_select', array()))) {
         $options->selectedColumns[] = "firstname";
     }
     if (in_array('last_name', Yii::app()->request->getPost('attribute_select', array()))) {
         $options->selectedColumns[] = "lastname";
     }
     if (in_array('email_address', Yii::app()->request->getPost('attribute_select', array()))) {
         $options->selectedColumns[] = "email";
     }
     $attributeFields = array_keys(getTokenFieldsAndNames($iSurveyID, TRUE));
     foreach ($attributeFields as $attr_name) {
         if (in_array($attr_name, Yii::app()->request->getPost('attribute_select', array()))) {
             $options->selectedColumns[] = $attr_name;
         }
     }
     if (Yii::app()->request->getPost('response_id')) {
         $sFilter = "{{survey_{$iSurveyID}}}.id=" . (int) Yii::app()->request->getPost('response_id');
     } else {
         $sFilter = '';
     }
     viewHelper::disableHtmlLogging();
     $resultsService->exportSurvey($iSurveyID, $explang, $sExportType, $options, $sFilter);
     exit;
 }
/**
 * Function to activate a survey
 * @global $dbprefix $dbprefix
 * @global $connect $connect
 * @global $clang $clang
 * @param int $postsid
 * @param int $surveyid
 * @return string
 */
function activateSurvey($postsid, $surveyid, $scriptname = 'admin.php')
{
    global $dbprefix, $connect, $clang, $databasetype, $databasetabletype, $uploaddir;
    $createsurvey = '';
    $activateoutput = '';
    $createsurveytimings = '';
    $createsurveydirectory = false;
    //Check for any additional fields for this survey and create necessary fields (token and datestamp)
    $pquery = "SELECT anonymized, allowregister, datestamp, ipaddr, refurl, savetimings FROM {$dbprefix}surveys WHERE sid={$postsid}";
    $presult = db_execute_assoc($pquery);
    $prow = $presult->FetchRow();
    if ($prow['allowregister'] == "Y") {
        $surveyallowsregistration = "TRUE";
    }
    if ($prow['savetimings'] == "Y") {
        $savetimings = "TRUE";
    }
    //strip trailing comma and new line feed (if any)
    $createsurvey = rtrim($createsurvey, ",\n");
    //strip trailing comma and new line feed (if any)
    $createsurvey = rtrim($createsurvey, ",\n");
    //Get list of questions for the base language
    $fieldmap = createFieldMap($surveyid);
    foreach ($fieldmap as $arow) {
        if ($createsurvey != '') {
            $createsurvey .= ",\n";
        }
        $createsurvey .= ' `' . $arow['fieldname'] . '`';
        switch ($arow['type']) {
            case 'startlanguage':
                $createsurvey .= " C(20) NOTNULL";
                break;
            case 'id':
                $createsurvey .= " I NOTNULL AUTO PRIMARY";
                $createsurveytimings .= " `{$arow['fieldname']}` I NOTNULL PRIMARY,\n";
                break;
            case "startdate":
            case "datestamp":
                $createsurvey .= " T NOTNULL";
                break;
            case "submitdate":
                $createsurvey .= " T";
                break;
            case "lastpage":
                $createsurvey .= " I";
                break;
            case "N":
                //NUMERICAL
                $createsurvey .= " F";
                break;
            case "S":
                //SHORT TEXT
                if ($databasetype == 'mysql' || $databasetype == 'mysqli') {
                    $createsurvey .= " X";
                } else {
                    $createsurvey .= " C(255)";
                }
                break;
            case "L":
                //LIST (RADIO)
            //LIST (RADIO)
            case "!":
                //LIST (DROPDOWN)
            //LIST (DROPDOWN)
            case "M":
                //Multiple choice
            //Multiple choice
            case "P":
                //Multiple choice with comment
            //Multiple choice with comment
            case "O":
                //DROPDOWN LIST WITH COMMENT
                if ($arow['aid'] != 'other' && strpos($arow['aid'], 'comment') === false && strpos($arow['aid'], 'othercomment') === false) {
                    $createsurvey .= " C(5)";
                } else {
                    $createsurvey .= " X";
                }
                break;
            case "K":
                // Multiple Numerical
                $createsurvey .= " F";
                break;
            case "U":
                //Huge text
            //Huge text
            case "Q":
                //Multiple short text
            //Multiple short text
            case "T":
                //LONG TEXT
            //LONG TEXT
            case ";":
                //Multi Flexi
            //Multi Flexi
            case ":":
                //Multi Flexi
                $createsurvey .= " X";
                break;
            case "D":
                //DATE
                $createsurvey .= " D";
                break;
            case "5":
                //5 Point Choice
            //5 Point Choice
            case "G":
                //Gender
            //Gender
            case "Y":
                //YesNo
            //YesNo
            case "X":
                //Boilerplate
                $createsurvey .= " C(1)";
                break;
            case "I":
                //Language switch
                $createsurvey .= " C(20)";
                break;
            case "|":
                $createsurveydirectory = true;
                if (strpos($arow['fieldname'], "_")) {
                    $createsurvey .= " I1";
                } else {
                    $createsurvey .= " X";
                }
                break;
            case "ipaddress":
                if ($prow['ipaddr'] == "Y") {
                    $createsurvey .= " X";
                }
                break;
            case "url":
                if ($prow['refurl'] == "Y") {
                    $createsurvey .= " X";
                }
                break;
            case "token":
                if ($prow['anonymized'] == "N") {
                    $createsurvey .= " C(36)";
                }
                break;
            default:
                $createsurvey .= " C(5)";
        }
    }
    $timingsfieldmap = createTimingsFieldMap($surveyid);
    $createsurveytimings .= '`' . implode("` F DEFAULT '0',\n`", array_keys($timingsfieldmap)) . "` F DEFAULT '0'";
    // If last question is of type MCABCEFHP^QKJR let's get rid of the ending coma in createsurvey
    $createsurvey = rtrim($createsurvey, ",\n") . "\n";
    // Does nothing if not ending with a comma
    $tabname = "{$dbprefix}survey_{$postsid}";
    # not using db_table_name as it quotes the table name (as does CreateTableSQL)
    $taboptarray = array('mysql' => 'ENGINE=' . $databasetabletype . '  CHARACTER SET utf8 COLLATE utf8_unicode_ci', 'mysqli' => 'ENGINE=' . $databasetabletype . '  CHARACTER SET utf8 COLLATE utf8_unicode_ci');
    $dict = NewDataDictionary($connect);
    $sqlarray = $dict->CreateTableSQL($tabname, $createsurvey, $taboptarray);
    if (isset($savetimings) && $savetimings == "TRUE") {
        $tabnametimings = $tabname . '_timings';
        $sqlarraytimings = $dict->CreateTableSQL($tabnametimings, $createsurveytimings, $taboptarray);
    }
    $execresult = $dict->ExecuteSQLArray($sqlarray, 1);
    if ($execresult == 0 || $execresult == 1) {
        $activateoutput .= "<br />\n<div class='messagebox ui-corner-all'>\n" . "<div class='header ui-widget-header'>" . $clang->gT("Activate Survey") . " ({$surveyid})</div>\n" . "<div class='warningheader'>" . $clang->gT("Survey could not be actived.") . "</div>\n" . "<p>" . $clang->gT("Database error:") . "\n <font color='red'>" . $connect->ErrorMsg() . "</font>\n" . "<pre>{$createsurvey}</pre>\n\n        <a href='{$scriptname}?sid={$postsid}'>" . $clang->gT("Main Admin Screen") . "</a>\n</div>";
    }
    if ($execresult != 0 && $execresult != 1) {
        $anquery = "SELECT autonumber_start FROM {$dbprefix}surveys WHERE sid={$postsid}";
        if ($anresult = db_execute_assoc($anquery)) {
            //if there is an autonumber_start field, start auto numbering here
            while ($row = $anresult->FetchRow()) {
                if ($row['autonumber_start'] > 0) {
                    if ($databasetype == 'odbc_mssql' || $databasetype == 'odbtp' || $databasetype == 'mssql_n' || $databasetype == 'mssqlnative') {
                        mssql_drop_primary_index('survey_' . $postsid);
                        mssql_drop_constraint('id', 'survey_' . $postsid);
                        $autonumberquery = "alter table {$dbprefix}survey_{$postsid} drop column id ";
                        $connect->Execute($autonumberquery);
                        $autonumberquery = "alter table {$dbprefix}survey_{$postsid} add [id] int identity({$row['autonumber_start']},1)";
                        $connect->Execute($autonumberquery);
                    } else {
                        $autonumberquery = "ALTER TABLE {$dbprefix}survey_{$postsid} AUTO_INCREMENT = " . $row['autonumber_start'];
                        $result = @$connect->Execute($autonumberquery);
                    }
                }
            }
            if (isset($savetimings) && $savetimings == "TRUE") {
                $dict->ExecuteSQLArray($sqlarraytimings, 1);
                // create a timings table for this survey
            }
        }
        $activateoutput .= "<br />\n<div class='messagebox ui-corner-all'>\n";
        $activateoutput .= "<div class='header ui-widget-header'>" . $clang->gT("Activate Survey") . " ({$surveyid})</div>\n";
        $activateoutput .= "<div class='successheader'>" . $clang->gT("Survey has been activated. Results table has been successfully created.") . "</div><br /><br />\n";
        // create the survey directory where the uploaded files can be saved
        if ($createsurveydirectory) {
            if (!file_exists($uploaddir . "/surveys/" . $postsid . "/files")) {
                if (!mkdir($uploaddir . "/surveys/" . $postsid . "/files", 0777, true)) {
                    $activateoutput .= "<div class='warningheader'>" . $clang->gT("The required directory for saving the uploaded files couldn't be created. Please check file premissions on the limesurvey/upload/surveys directory.") . "</div>";
                } else {
                    file_put_contents($uploaddir . "/surveys/" . $postsid . "/files/index.html", '<html><head></head><body></body></html>');
                }
            }
        }
        $acquery = "UPDATE {$dbprefix}surveys SET active='Y' WHERE sid=" . $surveyid;
        $acresult = $connect->Execute($acquery);
        if (isset($surveyallowsregistration) && $surveyallowsregistration == "TRUE") {
            $activateoutput .= $clang->gT("This survey allows public registration. A token table must also be created.") . "<br /><br />\n";
            $activateoutput .= "<input type='submit' value='" . $clang->gT("Initialise tokens") . "' onclick=\"" . get2post("{$scriptname}?action=tokens&amp;sid={$postsid}&amp;createtable=Y") . "\" />\n";
        } else {
            $activateoutput .= $clang->gT("This survey is now active, and responses can be recorded.") . "<br /><br />\n";
            $activateoutput .= "<strong>" . $clang->gT("Open-access mode") . ":</strong> " . $clang->gT("No invitation code is needed to complete the survey.") . "<br />" . $clang->gT("You can switch to the closed-access mode by initialising a token table with the button below.") . "<br /><br />\n";
            $activateoutput .= "<input type='submit' value='" . $clang->gT("Switch to closed-access mode") . "' onclick=\"" . get2post("{$scriptname}?action=tokens&amp;sid={$postsid}&amp;createtable=Y") . "\" />\n";
            $activateoutput .= "<input type='submit' value='" . $clang->gT("No, thanks.") . "' onclick=\"" . get2post("{$scriptname}?sid={$postsid}") . "\" />\n";
        }
        $activateoutput .= "</div><br />&nbsp;\n";
        $lsrcOutput = true;
    }
    if ($scriptname == 'lsrc') {
        if ($lsrcOutput == true) {
            return true;
        } else {
            return $activateoutput;
        }
    } else {
        return $activateoutput;
    }
}
Beispiel #10
0
        break;
}
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Pragma: public");
// Export Language is set by default to surveybaselang
// * the explang language code is used in SQL queries
// * the alang object is used to translate headers and hardcoded answers
// In the future it might be possible to 'post' the 'export language' from
// the exportresults form
$explang = $surveybaselang;
$elang = new limesurvey_lang($explang);
//STEP 1: First line is column headings
$fieldmap = createFieldMap($surveyid, 'full');
if ($thissurvey['savetimings'] === "Y") {
    //Append survey timings to the fieldmap array
    $fieldmap = $fieldmap + createTimingsFieldMap($surveyid, 'full');
}
//Get the fieldnames from the survey table for column headings
$surveytable = "{$dbprefix}survey_{$surveyid}";
if (isset($_POST['colselect'])) {
    $selectfields = "";
    foreach ($_POST['colselect'] as $cs) {
        if (!isset($fieldmap[$cs]) && !isset($aTokenFieldNames[$cs]) && $cs != 'completed') {
            continue;
        }
        // skip invalid field names to prevent SQL injection
        if ($tokenTableExists && $cs == 'token') {
            // We shouldnt include the token field when we are joining with the token field
        } elseif ($cs === 'id') {
            $selectfields .= db_quote_id($surveytable) . '.' . db_quote_id($cs) . ", ";
        } elseif ($cs != 'completed') {