Example #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;
 }
Example #2
0
 public function exportr()
 {
     global $length_vallabel;
     $iSurveyID = sanitize_int(Yii::app()->request->getParam('sid'));
     $subaction = Yii::app()->request->getParam('subaction');
     $clang = $this->getController()->lang;
     //for scale 1=nominal, 2=ordinal, 3=scale
     //$typeMap = $this->_getTypeMap();
     //        $length_vallabel = '120'; // Set the max text length of Value Labels
     $iLength = '25500';
     // Set the max text length of Text Data
     $length_varlabel = '25500';
     // Set the max text length of Variable Labels
     $headerComment = '';
     //        $tempFile = '';
     if (!isset($iSurveyID)) {
         $iSurveyID = returnGlobal('sid');
     }
     $filterstate = incompleteAnsFilterState();
     $headerComment = '#$Rev: 10193 $' . " {$filterstate}.\n";
     if (isset($_POST['dldata'])) {
         $subaction = "dldata";
     }
     if (isset($_POST['dlstructure'])) {
         $subaction = "dlstructure";
     }
     if (!isset($subaction)) {
         $selecthide = "";
         $selectshow = "";
         $selectinc = "";
         switch ($filterstate) {
             case "incomplete":
                 $selectinc = "selected='selected'";
                 break;
             case "complete":
                 $selecthide = "selected='selected'";
                 break;
             default:
                 $selectshow = "selected='selected'";
         }
         $data['selectinc'] = $selectinc;
         $data['selecthide'] = $selecthide;
         $data['selectshow'] = $selectshow;
         $data['filename'] = "survey_" . $iSurveyID . "_R_syntax_file.R";
         $data['surveyid'] = $iSurveyID;
         $data['display']['menu_bars']['browse'] = $clang->gT("Export results");
         $this->_renderWrappedTemplate('export', 'r_view', $data);
     } else {
         Yii::app()->loadHelper("admin/exportresults");
     }
     if ($subaction == 'dldata') {
         header("Content-Disposition: attachment; filename=survey_" . $iSurveyID . "_R_data_file.csv");
         header("Content-type: text/comma-separated-values; charset=UTF-8");
         header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
         header("Pragma: public");
         $na = "";
         //change to empty string instead of two double quotes to fix warnings on NA
         SPSSExportData($iSurveyID, $iLength, $na = '', $q = '"', $header = TRUE);
         exit;
     }
     if ($subaction == 'dlstructure') {
         header("Content-Disposition: attachment; filename=survey_" . $iSurveyID . "_R_syntax_file.R");
         header("Content-type: application/download; charset=UTF-8");
         header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
         header("Pragma: public");
         echo $headerComment;
         echo 'data <- read.csv("survey_' . $iSurveyID . '_R_data_file.csv", na.strings=c(",", "\\"\\""), stringsAsFactors=FALSE)';
         echo "\n\n";
         // Build array that has to be returned
         $fields = SPSSFieldMap($iSurveyID, "V");
         //Now get the query string with all fields to export
         $query = SPSSGetQuery($iSurveyID);
         $result = Yii::app()->db->createCommand($query)->query();
         //Checked
         $num_fields = 0;
         //Now we check if we need to adjust the size of the field or the type of the field
         foreach ($result as $row) {
             if ($num_fields == 0) {
                 $num_fields = count($row);
             }
             $row = array_values($row);
             $fieldno = 0;
             while ($fieldno < $num_fields) {
                 //Performance improvement, don't recheck fields that have valuelabels
                 if (!isset($fields[$fieldno]['answers'])) {
                     $strTmp = mb_substr(stripTagsFull($row[$fieldno]), 0, $iLength);
                     $len = mb_strlen($strTmp);
                     if ($len > $fields[$fieldno]['size']) {
                         $fields[$fieldno]['size'] = $len;
                     }
                     if (trim($strTmp) != '') {
                         if ($fields[$fieldno]['SPSStype'] == 'F' && (isNumericExtended($strTmp) === FALSE || $fields[$fieldno]['size'] > 16)) {
                             $fields[$fieldno]['SPSStype'] = 'A';
                         }
                     }
                 }
                 $fieldno++;
             }
         }
         $result->close();
         $errors = "";
         $i = 1;
         foreach ($fields as $field) {
             if ($field['SPSStype'] == 'DATETIME23.2') {
                 $field['size'] = '';
             }
             if ($field['LStype'] == 'N' || $field['LStype'] == 'K') {
                 $field['size'] .= '.' . ($field['size'] - 1);
             }
             switch ($field['SPSStype']) {
                 case 'F':
                     $type = "numeric";
                     break;
                 case 'A':
                     $type = "character";
                     break;
                 case 'DATETIME23.2':
                 case 'SDATE':
                     $type = "character";
                     //@TODO set $type to format for date
                     break;
             }
             if (!$field['hide']) {
                 echo "data[, " . $i . "] <- " . "as.{$type}(data[, " . $i . "])\n";
                 echo 'attributes(data)$variable.labels[' . $i . '] <- "' . addslashes(htmlspecialchars_decode(mb_substr(stripTagsFull($field['VariableLabel']), 0, $length_varlabel))) . '"' . "\n";
                 // Create the value Labels!
                 if (isset($field['answers'])) {
                     $answers = $field['answers'];
                     //print out the value labels!
                     echo 'data[, ' . $i . '] <- factor(data[, ' . $i . '], levels=c(';
                     $str = "";
                     foreach ($answers as $answer) {
                         if ($field['SPSStype'] == "F" && isNumericExtended($answer['code'])) {
                             $str .= ",{$answer['code']}";
                         } else {
                             $str .= ",\"{$answer['code']}\"";
                         }
                     }
                     $str = mb_substr($str, 1);
                     echo $str . '),labels=c(';
                     $str = "";
                     foreach ($answers as $answer) {
                         $str .= ",\"{$answer['value']}\"";
                     }
                     $str = mb_substr($str, 1);
                     if ($field['scale'] !== '' && $field['scale'] == 2) {
                         $scale = ",ordered=TRUE";
                     } else {
                         $scale = "";
                     }
                     echo "{$str}){$scale})\n";
                 }
                 //Rename the Variables (in case somethings goes wrong, we still have the OLD values
                 if (isset($field['sql_name'])) {
                     $ftitle = $field['title'];
                     if (!preg_match("/^([a-z]|[A-Z])+.*\$/", $ftitle)) {
                         $ftitle = "q_" . $ftitle;
                     }
                     $ftitle = str_replace(array("-", ":", ";", "!"), array("_hyph_", "_dd_", "_dc_", "_excl_"), $ftitle);
                     if (!$field['hide']) {
                         if ($ftitle != $field['title']) {
                             $errors .= "# Variable name was incorrect and was changed from {$field['title']} to {$ftitle} .\n";
                         }
                         echo "names(data)[" . $i . "] <- " . "\"" . $ftitle . "\"\n";
                         // <AdV> added \n
                     }
                     $i++;
                 } else {
                     echo "#sql_name not set\n";
                 }
             } else {
                 echo "#Field hidden\n";
             }
             echo "\n";
         }
         // end foreach
         echo $errors;
         exit;
     }
 }
Example #3
0
/**
* Check it the gives field has a labelset and return it as an array if true
*
* @param $field array field from SPSSFieldMap
* @return array or false
*/
function SPSSGetValues($field = array(), $qidattributes = null, $language)
{
    $length_vallabel = 120;
    if (!isset($field['LStype']) || empty($field['LStype'])) {
        return false;
    }
    $answers = array();
    if (strpos("!LORFWZWH1", $field['LStype']) !== false) {
        if (substr($field['code'], -5) == 'other' || substr($field['code'], -7) == 'comment') {
            //We have a comment field, so free text
        } else {
            $query = "SELECT {{answers}}.code, {{answers}}.answer,\n            {{questions}}.type FROM {{answers}}, {{questions}} WHERE";
            if (isset($field['scale_id'])) {
                $query .= " {{answers}}.scale_id = " . (int) $field['scale_id'] . " AND";
            }
            $query .= " {{answers}}.qid = '" . $field["qid"] . "' and {{questions}}.language='" . $language . "' and  {{answers}}.language='" . $language . "'\n            and {{questions}}.qid='" . $field['qid'] . "' ORDER BY sortorder ASC";
            $result = Yii::app()->db->createCommand($query)->query()->readAll();
            //Checked
            $num_results = count($result);
            if ($num_results > 0) {
                $displayvaluelabel = 0;
                # Build array that has to be returned
                foreach ($result as $row) {
                    $answers[] = array('code' => $row['code'], 'value' => mb_substr(stripTagsFull($row["answer"]), 0, $length_vallabel));
                }
            }
        }
    } elseif ($field['LStype'] == ':') {
        $displayvaluelabel = 0;
        //Get the labels that could apply!
        if (is_null($qidattributes)) {
            $qidattributes = getQuestionAttributeValues($field["qid"]);
        }
        if (trim($qidattributes['multiflexible_max']) != '') {
            $maxvalue = $qidattributes['multiflexible_max'];
        } else {
            $maxvalue = 10;
        }
        if (trim($qidattributes['multiflexible_min']) != '') {
            $minvalue = $qidattributes['multiflexible_min'];
        } else {
            $minvalue = 1;
        }
        if (trim($qidattributes['multiflexible_step']) != '') {
            $stepvalue = $qidattributes['multiflexible_step'];
        } else {
            $stepvalue = 1;
        }
        if ($qidattributes['multiflexible_checkbox'] != 0) {
            $minvalue = 0;
            $maxvalue = 1;
            $stepvalue = 1;
        }
        for ($i = $minvalue; $i <= $maxvalue; $i += $stepvalue) {
            $answers[] = array('code' => $i, 'value' => $i);
        }
    } elseif ($field['LStype'] == 'M' && substr($field['code'], -5) != 'other' && $field['size'] > 0) {
        $answers[] = array('code' => 1, 'value' => gT('Yes'));
        $answers[] = array('code' => 0, 'value' => gT('Not Selected'));
    } elseif ($field['LStype'] == "P" && substr($field['code'], -5) != 'other' && substr($field['code'], -7) != 'comment') {
        $answers[] = array('code' => 1, 'value' => gT('Yes'));
        $answers[] = array('code' => 0, 'value' => gT('Not Selected'));
    } elseif ($field['LStype'] == "G" && $field['size'] > 0) {
        $answers[] = array('code' => 1, 'value' => gT('Female'));
        $answers[] = array('code' => 2, 'value' => gT('Male'));
    } elseif ($field['LStype'] == "Y" && $field['size'] > 0) {
        $answers[] = array('code' => 1, 'value' => gT('Yes'));
        $answers[] = array('code' => 2, 'value' => gT('No'));
    } elseif ($field['LStype'] == "C" && $field['size'] > 0) {
        $answers[] = array('code' => 1, 'value' => gT('Yes'));
        $answers[] = array('code' => 2, 'value' => gT('No'));
        $answers[] = array('code' => 3, 'value' => gT('Uncertain'));
    } elseif ($field['LStype'] == "E" && $field['size'] > 0) {
        $answers[] = array('code' => 1, 'value' => gT('Increase'));
        $answers[] = array('code' => 2, 'value' => gT('Same'));
        $answers[] = array('code' => 3, 'value' => gT('Decrease'));
    }
    if (count($answers) > 0) {
        //check the max width of the answers
        $size = 0;
        $spsstype = $field['SPSStype'];
        foreach ($answers as $answer) {
            $len = mb_strlen($answer['code']);
            if ($len > $size) {
                $size = $len;
            }
            if ($spsstype == 'F' && (isNumericExtended($answer['code']) === false || $size > 16)) {
                $spsstype = 'A';
            }
        }
        $answers['SPSStype'] = $spsstype;
        $answers['size'] = $size;
        return $answers;
    } else {
        return false;
    }
}
 /**
  * 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;
 }
Example #5
0
 public function exportspss()
 {
     global $length_vallabel;
     $iSurveyID = sanitize_int(Yii::app()->request->getParam('sid'));
     //for scale 1=nominal, 2=ordinal, 3=scale
     //		$typeMap = $this->_getTypeMap();
     $filterstate = incompleteAnsFilterState();
     $spssver = returnGlobal('spssver');
     if (is_null($spssver)) {
         if (!Yii::app()->session['spssversion']) {
             Yii::app()->session['spssversion'] = 2;
             //Set default to 2, version 16 or up
         }
         $spssver = Yii::app()->session['spssversion'];
     } else {
         Yii::app()->session['spssversion'] = $spssver;
     }
     $length_varlabel = '231';
     // Set the max text length of Variable Labels
     $length_vallabel = '120';
     // Set the max text length of Value Labels
     switch ($spssver) {
         case 1:
             //<16
             $iLength = '255';
             // Set the max text length of the Value
             break;
         case 2:
             //>=16
             $iLength = '16384';
             // Set the max text length of the Value
             break;
         default:
             $iLength = '16384';
             // Set the max text length of the Value
     }
     $headerComment = '*$Rev: 121017 $' . " {$filterstate} {$spssver}.\n";
     if (isset($_POST['dldata'])) {
         $subaction = "dldata";
     }
     if (isset($_POST['dlstructure'])) {
         $subaction = "dlstructure";
     }
     if (!isset($subaction)) {
         $selecthide = "";
         $selectshow = "";
         $selectinc = "";
         switch ($filterstate) {
             case "incomplete":
                 $selectinc = "selected='selected'";
                 break;
             case "complete":
                 $selecthide = "selected='selected'";
                 break;
             default:
                 $selectshow = "selected='selected'";
         }
         $data['selectinc'] = $selectinc;
         $data['selecthide'] = $selecthide;
         $data['selectshow'] = $selectshow;
         $data['spssver'] = $spssver;
         $data['surveyid'] = $iSurveyID;
         $data['display']['menu_bars']['browse'] = gT('Export results');
         $this->_renderWrappedTemplate('export', 'spss_view', $data);
         return;
     }
     // Get Base language:
     $language = Survey::model()->findByPk($iSurveyID)->language;
     App()->setLanguage($language);
     Yii::app()->loadHelper("admin/exportresults");
     viewHelper::disableHtmlLogging();
     if ($subaction == 'dldata') {
         header("Content-Disposition: attachment; filename=survey_" . $iSurveyID . "_SPSS_data_file.dat");
         header("Content-type: text/comma-separated-values; charset=UTF-8");
         header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
         header("Pragma: public");
         if ($spssver == 2) {
             echo "";
         }
         SPSSExportData($iSurveyID, $iLength);
         exit;
     }
     if ($subaction == 'dlstructure') {
         header("Content-Disposition: attachment; filename=survey_" . $iSurveyID . "_SPSS_syntax_file.sps");
         header("Content-type: application/download; charset=UTF-8");
         header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
         header("Pragma: public");
         // Build array that has to be returned
         $fields = SPSSFieldMap($iSurveyID);
         //Now get the query string with all fields to export
         $query = SPSSGetQuery($iSurveyID, 500, 0);
         // Sample first 500 responses for adjusting fieldmap
         $result = $query->queryAll();
         $num_fields = 0;
         //Now we check if we need to adjust the size of the field or the type of the field
         foreach ($result as $row) {
             foreach ($fields as $iIndex => $aField) {
                 //Performance improvement, don't recheck fields that have valuelabels
                 if (!isset($aField['answers'])) {
                     $strTmp = mb_substr(stripTagsFull($row[$aField['sql_name']]), 0, $iLength);
                     $len = mb_strlen($strTmp);
                     if ($len > $fields[$iIndex]['size']) {
                         $fields[$iIndex]['size'] = $len;
                     }
                     if (trim($strTmp) != '') {
                         if ($fields[$iIndex]['SPSStype'] == 'F' && (isNumericExtended($strTmp) === FALSE || $fields[$iIndex]['size'] > 16)) {
                             $fields[$iIndex]['SPSStype'] = 'A';
                         }
                     }
                 }
             }
         }
         /**
          * End of DATA print out
          *
          * Now $fields contains accurate length data, and the DATA LIST can be rendered -- then the contents of the temp file can
          * be sent to the client.
          */
         if ($spssver == 2) {
             echo "";
         }
         echo $headerComment;
         if ($spssver == 2) {
             echo "SET UNICODE=ON.\n";
         }
         echo "SHOW LOCALE.\n";
         echo "PRESERVE LOCALE.\n";
         echo "SET LOCALE='en_UK'.\n";
         echo "GET DATA\n" . " /TYPE=TXT\n" . " /FILE='survey_" . $iSurveyID . "_SPSS_data_file.dat'\n" . " /DELCASE=LINE\n" . " /DELIMITERS=\",\"\n" . " /QUALIFIER=\"'\"\n" . " /ARRANGEMENT=DELIMITED\n" . " /FIRSTCASE=1\n" . " /IMPORTCASE=ALL\n" . " /VARIABLES=";
         foreach ($fields as $field) {
             if ($field['SPSStype'] == 'DATETIME23.2') {
                 $field['size'] = '';
             }
             if ($field['SPSStype'] == 'F' && ($field['LStype'] == 'N' || $field['LStype'] == 'K')) {
                 $field['size'] .= '.' . ($field['size'] - 1);
             }
             if (!$field['hide']) {
                 echo "\n {$field['id']} {$field['SPSStype']}{$field['size']}";
             }
         }
         echo ".\nCACHE.\n" . "EXECUTE.\n";
         //Create the variable labels:
         echo "*Define Variable Properties.\n";
         foreach ($fields as $field) {
             if (!$field['hide']) {
                 $label_parts = strSplitUnicode(str_replace('"', '""', stripTagsFull($field['VariableLabel'])), $length_varlabel - strlen($field['id']));
                 //if replaced quotes are splitted by, we need to mve the first quote to the next row
                 foreach ($label_parts as $idx => $label_part) {
                     if ($idx != count($label_parts) && substr($label_part, -1) == '"' && substr($label_part, -2) != '"') {
                         $label_parts[$idx] = rtrim($label_part, '"');
                         $label_parts[$idx + 1] = '"' . $label_parts[$idx + 1];
                     }
                 }
                 echo "VARIABLE LABELS " . $field['id'] . " \"" . implode("\"+\n\"", $label_parts) . "\".\n";
             }
         }
         // Create our Value Labels!
         echo "*Define Value labels.\n";
         foreach ($fields as $field) {
             if (isset($field['answers'])) {
                 $answers = $field['answers'];
                 //print out the value labels!
                 echo "VALUE LABELS  {$field['id']}\n";
                 $i = 0;
                 foreach ($answers as $answer) {
                     $i++;
                     if ($field['SPSStype'] == "F" && isNumericExtended($answer['code'])) {
                         $str = "{$answer['code']}";
                     } else {
                         $str = "\"{$answer['code']}\"";
                     }
                     if ($i < count($answers)) {
                         echo " {$str} \"{$answer['value']}\"\n";
                     } else {
                         echo " {$str} \"{$answer['value']}\".\n";
                     }
                 }
             }
         }
         foreach ($fields as $field) {
             if ($field['scale'] !== '') {
                 switch ($field['scale']) {
                     case 2:
                         echo "VARIABLE LEVEL {$field['id']}(ORDINAL).\n";
                         break;
                     case 3:
                         echo "VARIABLE LEVEL {$field['id']}(SCALE).\n";
                 }
             }
         }
         //Rename the Variables (in case somethings goes wrong, we still have the OLD values
         foreach ($fields as $field) {
             if (isset($field['sql_name']) && $field['hide'] === 0) {
                 $ftitle = $field['title'];
                 if (!preg_match("/^([a-z]|[A-Z])+.*\$/", $ftitle)) {
                     $ftitle = "q_" . $ftitle;
                 }
                 $ftitle = str_replace(array(" ", "-", ":", ";", "!", "/", "\\", "'"), array("_", "_hyph_", "_dd_", "_dc_", "_excl_", "_fs_", "_bs_", '_qu_'), $ftitle);
                 if ($ftitle != $field['title']) {
                     echo "* Variable name was incorrect and was changed from {$field['title']} to {$ftitle} .\n";
                 }
                 echo "RENAME VARIABLE ( " . $field['id'] . ' = ' . $ftitle . " ).\n";
             }
         }
         echo "RESTORE LOCALE.\n";
         exit;
     }
 }
 function clean(&$item)
 {
     $item = trim(htmlspecialchars_decode(stripTagsFull($item)));
 }
 public function close()
 {
     $errors = '';
     foreach ($this->headers as $id => $title) {
         $field = $this->customFieldmap[$title];
         $i = $id + 1;
         if ($field['SPSStype'] == 'DATETIME23.2') {
             $field['size'] = '';
         }
         if ($field['LStype'] == 'N' || $field['LStype'] == 'K') {
             $field['size'] .= '.' . ($field['size'] - 1);
         }
         switch ($field['SPSStype']) {
             case 'F':
                 $type = "numeric";
                 break;
             case 'A':
                 $type = "character";
                 break;
             case 'DATETIME23.2':
             case 'SDATE':
                 $type = "character";
                 //@TODO set $type to format for date
                 break;
         }
         $this->out("# LimeSurvey Field type: {$field['SPSStype']}");
         $this->out("data[, " . $i . "] <- " . "as.{$type}(data[, " . $i . "])");
         $this->out('attributes(data)$variable.labels[' . $i . '] <- "' . addslashes(htmlspecialchars_decode(mb_substr(stripTagsFull($field['VariableLabel']), 0, $this->maxLength))) . '"');
         // Create the value Labels!
         if (isset($field['answers'])) {
             $answers = $field['answers'];
             //print out the value labels!
             $str = 'data[, ' . $i . '] <- factor(data[, ' . $i . '], levels=c(';
             foreach ($answers as $answer) {
                 if ($field['SPSStype'] == "F" && isNumericExtended($answer['code'])) {
                     $str .= "{$answer['code']},";
                 } else {
                     $str .= "\"{$answer['code']}\",";
                 }
             }
             $str = mb_substr($str, 0, -1);
             $str .= '),labels=c(';
             foreach ($answers as $answer) {
                 $str .= "\"{$answer['value']}\", ";
             }
             $str = mb_substr($str, 0, -2);
             if ($field['scale'] !== '' && $field['scale'] == 2) {
                 $scale = ", ordered=TRUE";
             } else {
                 $scale = "";
             }
             $this->out("{$str}){$scale})");
         }
         //Rename the Variables (in case somethings goes wrong, we still have the OLD values
         if (isset($field['sql_name'])) {
             $ftitle = $field['title'];
             if (!preg_match("/^([a-z]|[A-Z])+.*\$/", $ftitle)) {
                 $ftitle = "q_" . $ftitle;
             }
             $ftitle = str_replace(array("-", ":", ";", "!"), array("_hyph_", "_dd_", "_dc_", "_excl_"), $ftitle);
             if ($ftitle != $field['title']) {
                 $errors .= "# Variable name was incorrect and was changed from {$field['title']} to {$ftitle} .\n";
             }
             $this->out("names(data)[" . $i . "] <- " . "\"" . $ftitle . "\"");
             // <AdV> added \n
         } else {
             $this->out("#sql_name not set");
         }
     }
     // end foreach
     if (!empty($errors)) {
         $this->out($errors);
     }
     fclose($this->handle);
 }
Example #8
0
 /**
  * Return the question text part without any subquestion
  * 
  * @param Survey $oSurvey
  * @param FormattingOptions $oOptions
  * @param string $fieldName
  * @return string
  */
 public function getFullQuestionHeading(SurveyObj $oSurvey, FormattingOptions $oOptions, $fieldName)
 {
     if (isset($oSurvey->fieldMap[$fieldName])) {
         $aField = $oSurvey->fieldMap[$fieldName];
         $aField['question'] = stripTagsFull($aField['question']);
         if ($oOptions->headingTextLength) {
             $aField['question'] = ellipsize($aField['question'], $oOptions->headingTextLength, 1, ".. ");
         }
         return $aField['question'];
     }
     return false;
 }