public function index()
 {
     $surveyid = intval(App()->request->getQuery('surveyid'));
     $gid = intval(App()->request->getQuery('gid'));
     $qid = intval(App()->request->getQuery('qid'));
     $fieldtype = sanitize_xss_string(App()->request->getQuery('fieldtype'));
     $action = sanitize_xss_string(App()->request->getQuery('action'));
     if (!Yii::app()->session['loginID']) {
         throw new CHttpException(401);
     }
     list($replacementFields, $isInstertAnswerEnabled) = $this->_getReplacementFields($fieldtype, $surveyid);
     if ($isInstertAnswerEnabled === true) {
         //2: Get all other questions that occur before this question that are pre-determined answer types
         $fieldmap = createFieldMap($surveyid, 'full', false, false, getBaseLanguageFromSurveyID($surveyid));
         $surveyInfo = getSurveyInfo($surveyid);
         $surveyformat = $surveyInfo['format'];
         // S, G, A
         //Go through each question until we reach the current one
         //error_log(print_r($qrows,true));
         $questionlist = $this->_getQuestionList($action, $gid, $qid, $fieldmap, $fieldtype, $surveyformat);
         $childQuestions = $this->_getChildQuestions($questionlist);
     }
     $data['countfields'] = count($replacementFields);
     $data['replFields'] = $replacementFields;
     if (isset($childQuestions)) {
         $data['cquestions'] = $childQuestions;
     }
     if (isset($surveyformat)) {
         $data['surveyformat'] = $surveyformat;
     }
     $this->getController()->render('/admin/limeReplacementFields_view', $data);
 }
Exemplo n.º 2
0
 /**
  * Delete all files related to this repsonse.
  */
 public function getFiles()
 {
     $questions = Question::model()->findAllByAttributes(array('sid' => $this->dynamicId, 'type' => '|', 'language' => getBaseLanguageFromSurveyID($this->dynamicId)));
     $files = array();
     foreach ($questions as $question) {
         $field = "{$question->sid}X{$question->gid}X{$question->qid}";
         $data = json_decode(stripslashes($this->getAttribute($field)), true);
         if (is_array($data)) {
             $files = array_merge($files, $data);
         }
     }
     return $files;
 }
 public function index()
 {
     if (isset($_GET['surveyid'])) {
         $surveyid = sanitize_int($_GET['surveyid']);
     }
     if (isset($_GET['gid'])) {
         $gid = sanitize_int($_GET['gid']);
     }
     if (isset($_GET['qid'])) {
         $qid = sanitize_int($_GET['qid']);
     }
     if (isset($_GET['fieldtype'])) {
         $fieldtype = $_GET['fieldtype'];
     }
     if (isset($_GET['action'])) {
         $action = $_GET['action'];
     }
     $clang = Yii::app()->lang;
     if (!Yii::app()->session['loginID']) {
         die("Unauthenticated Access Forbiden");
     }
     list($replacementFields, $isInstertAnswerEnabled) = $this->_getReplacementFields($fieldtype, $surveyid);
     if ($isInstertAnswerEnabled === true) {
         if (empty($surveyid)) {
             safeDie("No SID provided.");
         }
         //2: Get all other questions that occur before this question that are pre-determined answer types
         $fieldmap = createFieldMap($surveyid, 'full', false, false, getBaseLanguageFromSurveyID($surveyid));
         $surveyInfo = getSurveyInfo($surveyid);
         $surveyformat = $surveyInfo['format'];
         // S, G, A
         //Go through each question until we reach the current one
         //error_log(print_r($qrows,true));
         $questionlist = $this->_getQuestionList($action, $gid, $qid, $fieldmap, $fieldtype, $surveyformat);
         $childQuestions = $this->_getChildQuestions($questionlist);
     }
     $data['countfields'] = count($replacementFields);
     $data['replFields'] = $replacementFields;
     $data['clang'] = $clang;
     if (isset($childQuestions)) {
         $data['cquestions'] = $childQuestions;
     }
     if (isset($surveyformat)) {
         $data['surveyformat'] = $surveyformat;
     }
     $this->getController()->render('/admin/limeReplacementFields_view', $data);
 }
Exemplo n.º 4
0
/**
* 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;
}
Exemplo n.º 5
0
 /**
  * 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 (hasSurveyPermission($surveyid, 'responses', 'read')) {
         if ($subaction == "insert" && 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='{$_POST['token']}'";
                 //dbQuoteAll($_POST['token'],true);
                 $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='" . $_POST['token'] . "'";
                     //dbQuoteAll($_POST['token'],true);
                     $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 .= "<br /><br />" . $clang->gT("Follow the following link to update it") . ":\n";
                     $errormsg .= CHtml::link("[id:{$lastanswfortoken}]", Yii::app()->baseUrl . ('/admin/dataentry/editdata/subaction/edit/id/' . $lastanswfortoken . '/surveyid/' . $surveyid . '/lang/' . $rlanguage), array('title' => $clang->gT("Edit this entry")));
                 } else {
                     $errormsg .= "<br /><br />" . $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 .= "<input type='hidden' name='$key' value='$val' />\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];
                             }
                         }
                     }
                 }
                 Survey_dynamic::sid($surveyid);
                 $new_response = new Survey_dynamic();
                 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'] != '') {
                     // 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='" . $_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='" . $_POST['token'] . "'";
                     $utresult = dbExecuteAssoc($utquery);
                     //Yii::app()->db->Execute($utquery) or safeDie ("Couldn't update tokens table!<br />\n$utquery<br />\n".Yii::app()->db->ErrorMsg());
                     // save submitdate into survey table
                     $srid = Yii::app()->db->getLastInsertID();
                     // Yii::app()->db->getLastInsertID();
                     $sdquery = "UPDATE {{survey_{$surveyid}}} SET submitdate='" . $submitdate . "' WHERE id={$srid}\n";
                     $sdresult = dbExecuteAssoc($sdquery) or safeDie("Couldn't set submitdate response in survey table!<br />\n{$sdquery}<br />\n");
                     $last_db_id = Yii::app()->db->getLastInsertID();
                 }
                 if (isset($_POST['save']) && $_POST['save'] == "on") {
                     $srid = Yii::app()->db->getLastInsertID();
                     //Yii::app()->db->getLastInsertID();
                     $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}\n                        (" . implode(',', $columns) . ")\n                        VALUES\n                        (" . 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 = Yii::app()->db->getLastInsertID();
                         // Yii::app()->db->getLastInsertID("{{saved_control}}","scid");
                         $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 .= "<font class='successtitle'></font><br />\n";
                         $tokens_table = "{{tokens_{$surveyid}}}";
                         $last_db_id = Yii::app()->db->getLastInsertID();
                         if (tableExists($tokens_table)) {
                             $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}\n                                (" . implode(',', $columns) . ")\n                                VALUES\n                                (" . implode(',', $values) . ")";
                             //$this->tokens_dynamic_model->insertToken($surveyid,$tokendata);
                             dbExecuteAssoc($SQL);
                             //Yii::app()->db->AutoExecute(db_table_name("tokens_".$surveyid), $tokendata,'INSERT');
                             $aDataentrymsgs[] = CHtml::tag('font', array('class' => 'successtitle'), $clang->gT("A token entry for the saved survey has been created too."));
                             //$aDataentryoutput .= "<font class='successtitle'></font><br />\n";
                             $last_db_id = Yii::app()->db->getLastInsertID();
                         }
                         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()->getConfig('publicurl') . "/index.php?sid={$surveyid}&loadall=reload&scid=" . $scid . "&lang=" . urlencode($saver['language']) . "&loadname=" . urlencode($saver['identifier']) . "&loadpass="******"&token=" . $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.<br /><br />");
                     }
                 }
                 $aData['thisid'] = $last_db_id;
             }
             $aData['errormsg'] = $errormsg;
             $aData['dataentrymsgs'] = $aDataentrymsgs;
             $this->_renderWrappedTemplate('dataentry', 'insert', $aData);
         }
     }
 }
Exemplo n.º 6
0
 public function vvexport()
 {
     $iSurveyID = sanitize_int(Yii::app()->request->getParam('surveyid'));
     $subaction = Yii::app()->request->getParam('subaction');
     //Exports all responses to a survey in special "Verified Voting" format.
     $clang = $this->getController()->lang;
     if (!hasSurveyPermission($iSurveyID, 'responses', 'export')) {
         return;
     }
     if ($subaction != "export") {
         $selecthide = "";
         $selectshow = "";
         $selectinc = "";
         if (incompleteAnsFilterState() == "incomplete") {
             $selectinc = "selected='selected'";
         } elseif (incompleteAnsFilterState() == "complete") {
             $selecthide = "selected='selected'";
         } else {
             $selectshow = "selected='selected'";
         }
         $data['selectinc'] = $selectinc;
         $data['selecthide'] = $selecthide;
         $data['selectshow'] = $selectshow;
         $data['surveyid'] = $iSurveyID;
         $data['display']['menu_bars']['browse'] = $clang->gT("Export VV file");
         $this->_renderWrappedTemplate('export', 'vv_view', $data);
     } elseif (isset($iSurveyID) && $iSurveyID) {
         //Export is happening
         $extension = sanitize_paranoid_string(returnGlobal('extension'));
         $fn = "vvexport_{$iSurveyID}." . $extension;
         $this->_addHeaders($fn, "text/comma-separated-values", 0, "cache");
         $s = "\t";
         $fieldmap = createFieldMap($iSurveyID, 'full', false, false, getBaseLanguageFromSurveyID($iSurveyID));
         $surveytable = "{{survey_{$iSurveyID}}}";
         Survey::model()->findByPk($iSurveyID)->language;
         $fieldnames = Yii::app()->db->schema->getTable($surveytable)->getColumnNames();
         //Create the human friendly first line
         $firstline = "";
         $secondline = "";
         foreach ($fieldnames as $field) {
             $fielddata = arraySearchByKey($field, $fieldmap, "fieldname", 1);
             if (count($fielddata) < 1) {
                 $firstline .= $field;
             } else {
                 $firstline .= preg_replace('/\\s+/', ' ', strip_tags($fielddata['question']));
             }
             $firstline .= $s;
             $secondline .= $field . $s;
         }
         $vvoutput = $firstline . "\n";
         $vvoutput .= $secondline . "\n";
         $query = "SELECT * FROM " . Yii::app()->db->quoteTableName($surveytable);
         if (incompleteAnsFilterState() == "incomplete") {
             $query .= " WHERE submitdate IS NULL ";
         } elseif (incompleteAnsFilterState() == "complete") {
             $query .= " WHERE submitdate >= '01/01/1980' ";
         }
         $result = Yii::app()->db->createCommand($query)->query();
         foreach ($result->readAll() as $row) {
             foreach ($fieldnames as $field) {
                 if (is_null($row[$field])) {
                     $value = '{question_not_shown}';
                 } else {
                     $value = trim($row[$field]);
                     // sunscreen for the value. necessary for the beach.
                     // careful about the order of these arrays:
                     // lbrace has to be substituted *first*
                     $value = str_replace(array("{", "\n", "\r", "\t"), array("{lbrace}", "{newline}", "{cr}", "{tab}"), $value);
                 }
                 // one last tweak: excel likes to quote values when it
                 // exports as tab-delimited (esp if value contains a comma,
                 // oddly enough).  So we're going to encode a leading quote,
                 // if it occurs, so that we can tell the difference between
                 // strings that "really are" quoted, and those that excel quotes
                 // for us.
                 $value = preg_replace('/^"/', '{quote}', $value);
                 // yay!  that nasty soab won't hurt us now!
                 if ($field == "submitdate" && !$value) {
                     $value = "NULL";
                 }
                 $sun[] = $value;
             }
             $beach = implode($s, $sun);
             $vvoutput .= $beach;
             unset($sun);
             $vvoutput .= "\n";
         }
         echo $vvoutput;
         exit;
     }
 }
Exemplo n.º 7
0
/**
* This function creates the old fieldnames for survey import
*
* @param mixed $iOldSID  The old survey id
* @param mixed $iNewSID  The new survey id
* @param array $aGIDReplacements An array with group ids (oldgid=>newgid)
* @param array $aQIDReplacements An array with question ids (oldqid=>newqid)
*/
function reverseTranslateFieldNames($iOldSID, $iNewSID, $aGIDReplacements, $aQIDReplacements)
{
    $aGIDReplacements = array_flip($aGIDReplacements);
    $aQIDReplacements = array_flip($aQIDReplacements);
    if ($iOldSID == $iNewSID) {
        $forceRefresh = true;
        // otherwise grabs the cached copy and throws undefined index exceptions
    } else {
        $forceRefresh = false;
    }
    $aFieldMap = createFieldMap($iNewSID, 'short', $forceRefresh, false, getBaseLanguageFromSurveyID($iNewSID));
    $aFieldMappings = array();
    foreach ($aFieldMap as $sFieldname => $aFieldinfo) {
        if ($aFieldinfo['qid'] != null) {
            $aFieldMappings[$sFieldname] = $iOldSID . 'X' . $aGIDReplacements[$aFieldinfo['gid']] . 'X' . $aQIDReplacements[$aFieldinfo['qid']] . $aFieldinfo['aid'];
            if ($aFieldinfo['type'] == '1') {
                $aFieldMappings[$sFieldname] = $aFieldMappings[$sFieldname] . '#' . $aFieldinfo['scale_id'];
            }
            // now also add a shortened field mapping which is needed for certain kind of condition mappings
            $aFieldMappings[$iNewSID . 'X' . $aFieldinfo['gid'] . 'X' . $aFieldinfo['qid']] = $iOldSID . 'X' . $aGIDReplacements[$aFieldinfo['gid']] . 'X' . $aQIDReplacements[$aFieldinfo['qid']];
            // Shortened field mapping for timings table
            $aFieldMappings[$iNewSID . 'X' . $aFieldinfo['gid']] = $iOldSID . 'X' . $aGIDReplacements[$aFieldinfo['gid']];
        }
    }
    return array_flip($aFieldMappings);
}
Exemplo n.º 8
0
 /**
  * RPC Routine to export token response in a survey.
  * Returns the requested file as base64 encoded string
  *
  * @access public
  * @param string $sSessionKey Auth credentials
  * @param int $iSurveyID Id of the Survey
  * @param string $sDocumentType pdf,csv,xls,doc,json
  * @param string $sToken The token for which responses needed
  * @param string $sLanguageCode The language to be used
  * @param string $sCompletionStatus Optional 'complete','incomplete' or 'all' - defaults to 'all'
  * @param string $sHeadingType 'code','full' or 'abbreviated' Optional defaults to 'code'
  * @param string $sResponseType 'short' or 'long' Optional defaults to 'short'
  * @param array $aFields Optional Selected fields
  * @return array|string On success: Requested file as base 64-encoded string. On failure array with error information
  *
  */
 public function export_responses_by_token($sSessionKey, $iSurveyID, $sDocumentType, $sToken, $sLanguageCode = null, $sCompletionStatus = 'all', $sHeadingType = 'code', $sResponseType = 'short', $aFields = null)
 {
     if (!$this->_checkSessionKey($sSessionKey)) {
         return array('status' => 'Invalid session key');
     }
     Yii::app()->loadHelper('admin/exportresults');
     if (!tableExists('{{survey_' . $iSurveyID . '}}')) {
         return array('status' => 'No Data, survey table does not exist.');
     }
     if (!($maxId = SurveyDynamic::model($iSurveyID)->getMaxId())) {
         return array('status' => 'No Data, could not get max id.');
     }
     if (!empty($sLanguageCode) && !in_array($sLanguageCode, Survey::model()->findByPk($iSurveyID)->getAllLanguages())) {
         return array('status' => 'Language code not found for this survey.');
     }
     if (!SurveyDynamic::model($iSurveyID)->findByAttributes(array('token' => $sToken))) {
         return array('status' => 'No Response found for Token');
     }
     if (!Permission::model()->hasSurveyPermission($iSurveyID, 'responses', 'export')) {
         return array('status' => 'No permission');
     }
     if (empty($sLanguageCode)) {
         $sLanguageCode = getBaseLanguageFromSurveyID($iSurveyID);
     }
     if (is_null($aFields)) {
         $aFields = array_keys(createFieldMap($iSurveyID, 'full', true, false, $sLanguageCode));
     }
     if ($sDocumentType == 'xls') {
         // Cut down to the first 255 fields
         $aFields = array_slice($aFields, 0, 255);
     }
     $oFormattingOptions = new FormattingOptions();
     $oFormattingOptions->responseMinRecord = 1;
     $oFormattingOptions->responseMaxRecord = $maxId;
     $oFormattingOptions->selectedColumns = $aFields;
     $oFormattingOptions->responseCompletionState = $sCompletionStatus;
     $oFormattingOptions->headingFormat = $sHeadingType;
     $oFormattingOptions->answerFormat = $sResponseType;
     $oFormattingOptions->output = 'file';
     $oExport = new ExportSurveyResultsService();
     $sTableName = Yii::app()->db->tablePrefix . 'survey_' . $iSurveyID;
     $sTempFile = $oExport->exportSurvey($iSurveyID, $sLanguageCode, $sDocumentType, $oFormattingOptions, "{$sTableName}.token='{$sToken}'");
     return new BigFile($sTempFile, true, 'base64');
 }
Exemplo n.º 9
0
/**
* 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;
}
Exemplo n.º 10
0
 /**
  * RPC Routine to export responses.
  * Returns the requested file as base64 encoded string
  *
  * @access public
  * @param string $sSessionKey Auth credentials 
  * @param int $iSurveyID Id of the Survey
  * @param string $sDocumentType pdf,csv,xls,doc
  * @param string $sLanguageCode The language to be used
  * @param string $sCompletionStatus Optional 'complete','incomplete' or 'all' - defaults to complete
  * @param string $sHeadingType 'code','full' or 'abbreviated' Optional defaults to 'code'
  * @param string $sResponseType 'short' or 'long' Optional defaults to 'short'
  * @param integer $iFromResponseID Optional
  * @param integer $iToResponseID Optional
  * @param array $aFields Optional Selected fields
  * @return array|string On success: Requested file as base 64-encoded string. On failure array with error information
  **/
 public function export_responses($sSessionKey, $iSurveyID, $sDocumentType, $sLanguageCode = null, $sCompletionStatus = 'all', $sHeadingType = 'code', $sResponseType = 'short', $iFromResponseID = null, $iToResponseID = null, $aFields = null)
 {
     if (!$this->_checkSessionKey($sSessionKey)) {
         return array('status' => 'Invalid session key');
     }
     Yii::app()->loadHelper('admin/exportresults');
     if (!hasSurveyPermission($iSurveyID, 'responses', 'export')) {
         return array('status' => 'No permission');
     }
     if (is_null($sLanguageCode)) {
         $sLanguageCode = getBaseLanguageFromSurveyID($iSurveyID);
     }
     if (is_null($aFields)) {
         $aFields = array_keys(createFieldMap($iSurveyID, 'full', true, false, $sLanguageCode));
     }
     if ($sDocumentType == 'xls') {
         // Cut down to the first 255 fields
         $aFields = array_slice($aFields, 0, 255);
     }
     $oFomattingOptions = new FormattingOptions();
     $oFomattingOptions->format = $sDocumentType;
     $oFomattingOptions->responseMinRecord = $iFromResponseID;
     $oFomattingOptions->responseMaxRecord = $iToResponseID;
     $oFomattingOptions->selectedColumns = $aFields;
     $oFomattingOptions->responseCompletionState = $sCompletionStatus;
     $oFomattingOptions->headingFormat = $sHeadingType;
     $oFomattingOptions->answerFormat = $sResponseType;
     $oExport = new ExportSurveyResultsService();
     $sFileData = $oExport->exportSurvey($iSurveyID, $sLanguageCode, $oFomattingOptions, 'return');
     return base64_encode($sFileData);
 }
Exemplo n.º 11
0
/**
* Creates a fieldmap with all information necessary to output the fields
*
* @param $prefix string prefix for the variable ID
* @return array
*/
function SPSSFieldMap($iSurveyID, $prefix = 'V')
{
    $typeMap = array('5' => array('name' => '5 Point Choice', 'size' => 1, 'SPSStype' => 'F', 'Scale' => 3), 'B' => array('name' => 'Array (10 Point Choice)', 'size' => 1, 'SPSStype' => 'F', 'Scale' => 3), 'A' => array('name' => 'Array (5 Point Choice)', 'size' => 1, 'SPSStype' => 'F', 'Scale' => 3), 'F' => array('name' => 'Array (Flexible Labels)', 'size' => 1, 'SPSStype' => 'F'), '1' => array('name' => 'Array (Flexible Labels) Dual Scale', 'size' => 1, 'SPSStype' => 'F'), 'H' => array('name' => 'Array (Flexible Labels) by Column', 'size' => 1, 'SPSStype' => 'F'), 'E' => array('name' => 'Array (Increase, Same, Decrease)', 'size' => 1, 'SPSStype' => 'F', 'Scale' => 2), 'C' => array('name' => 'Array (Yes/No/Uncertain)', 'size' => 1, 'SPSStype' => 'F'), 'X' => array('name' => 'Boilerplate Question', 'size' => 1, 'SPSStype' => 'A', 'hide' => 1), 'D' => array('name' => 'Date', 'size' => 20, 'SPSStype' => 'DATETIME23.2'), 'G' => array('name' => 'Gender', 'size' => 1, 'SPSStype' => 'F'), 'U' => array('name' => 'Huge Free Text', 'size' => 1, 'SPSStype' => 'A'), 'I' => array('name' => 'Language Switch', 'size' => 1, 'SPSStype' => 'A'), '!' => array('name' => 'List (Dropdown)', 'size' => 1, 'SPSStype' => 'F'), 'W' => array('name' => 'List (Flexible Labels) (Dropdown)', 'size' => 1, 'SPSStype' => 'F'), 'Z' => array('name' => 'List (Flexible Labels) (Radio)', 'size' => 1, 'SPSStype' => 'F'), 'L' => array('name' => 'List (Radio)', 'size' => 1, 'SPSStype' => 'F'), 'O' => array('name' => 'List With Comment', 'size' => 1, 'SPSStype' => 'F'), 'T' => array('name' => 'Long free text', 'size' => 1, 'SPSStype' => 'A'), 'K' => array('name' => 'Multiple Numerical Input', 'size' => 1, 'SPSStype' => 'F'), 'M' => array('name' => 'Multiple choice', 'size' => 1, 'SPSStype' => 'F'), 'P' => array('name' => 'Multiple choice with comments', 'size' => 1, 'SPSStype' => 'F'), 'Q' => array('name' => 'Multiple Short Text', 'size' => 1, 'SPSStype' => 'F'), 'N' => array('name' => 'Numerical Input', 'size' => 3, 'SPSStype' => 'F', 'Scale' => 3), 'R' => array('name' => 'Ranking', 'size' => 1, 'SPSStype' => 'F'), 'S' => array('name' => 'Short free text', 'size' => 1, 'SPSStype' => 'F'), 'Y' => array('name' => 'Yes/No', 'size' => 1, 'SPSStype' => 'F'), ':' => array('name' => 'Multi flexi numbers', 'size' => 1, 'SPSStype' => 'F', 'Scale' => 3), ';' => array('name' => 'Multi flexi text', 'size' => 1, 'SPSStype' => 'A'), '|' => array('name' => 'File upload', 'size' => 1, 'SPSStype' => 'A'), '*' => array('name' => 'Equation', 'size' => 1, 'SPSStype' => 'A'));
    $fieldmap = createFieldMap($iSurveyID, 'full', false, false, getBaseLanguageFromSurveyID($iSurveyID));
    #See if tokens are being used
    $bTokenTableExists = tableExists('tokens_' . $iSurveyID);
    #Lookup the names of the attributes
    $query = "SELECT sid, anonymized, language FROM {{surveys}} WHERE sid={$iSurveyID}";
    $aRow = Yii::app()->db->createCommand($query)->queryRow();
    //Checked
    $surveyprivate = $aRow['anonymized'];
    $language = $aRow['language'];
    $fieldno = 0;
    $fields = array();
    if ($bTokenTableExists && $surveyprivate == 'N' && Permission::model()->hasSurveyPermission($iSurveyID, 'tokens', 'read')) {
        $tokenattributes = getTokenFieldsAndNames($iSurveyID, false);
        foreach ($tokenattributes as $attributefield => $attributedescription) {
            //Drop the token field, since it is in the survey too
            if ($attributefield != 'token') {
                $fieldno++;
                $fields[] = array('id' => "{$prefix}{$fieldno}", 'name' => mb_substr($attributefield, 0, 8), 'qid' => 0, 'code' => '', 'SPSStype' => 'A', 'LStype' => 'Undef', 'VariableLabel' => $attributedescription['description'], 'sql_name' => $attributefield, 'size' => '100', 'title' => $attributefield, 'hide' => 0, 'scale' => '');
            }
        }
    }
    $tempArray = array();
    $fieldnames = Yii::app()->db->schema->getTable("{{survey_{$iSurveyID}}}")->getColumnNames();
    $num_results = count($fieldnames);
    $num_fields = $num_results;
    $diff = 0;
    $noQID = array('id', 'token', 'datestamp', 'submitdate', 'startdate', 'startlanguage', 'ipaddr', 'refurl', 'lastpage');
    # Build array that has to be returned
    for ($i = 0; $i < $num_results; $i++) {
        #Condition for SPSS fields:
        # - Length may not be longer than 8 characters
        # - Name may not begin with a digit
        $fieldname = $fieldnames[$i];
        $fieldtype = '';
        $ftype = '';
        $val_size = 1;
        $hide = 0;
        $export_scale = '';
        $code = '';
        $scale_id = null;
        $aQuestionAttribs = array();
        #Determine field type
        if ($fieldname == 'submitdate' || $fieldname == 'startdate' || $fieldname == 'datestamp') {
            $fieldtype = 'DATETIME23.2';
        } elseif ($fieldname == 'startlanguage') {
            $fieldtype = 'A';
            $val_size = 19;
        } elseif ($fieldname == 'token') {
            $fieldtype = 'A';
            $val_size = 16;
        } elseif ($fieldname == 'id') {
            $fieldtype = 'F';
            $val_size = 7;
            //Arbitrarilty restrict to 9,999,999 (7 digits) responses/survey
        } elseif ($fieldname == 'ipaddr') {
            $fieldtype = 'A';
            $val_size = 15;
        } elseif ($fieldname == 'refurl') {
            $fieldtype = 'A';
            $val_size = 255;
        } elseif ($fieldname == 'lastpage') {
            $fieldtype = 'F';
            $val_size = 7;
            //Arbitrarilty restrict to 9,999,999 (7 digits) pages
        }
        #Get qid (question id)
        if (in_array($fieldname, $noQID) || substr($fieldname, 0, 10) == 'attribute_') {
            $qid = 0;
            $varlabel = $fieldname;
            $ftitle = $fieldname;
        } else {
            //GET FIELD DATA
            if (!isset($fieldmap[$fieldname])) {
                //Field in database but no longer in survey... how is this possible?
                //@TODO: think of a fix.
                $fielddata = array();
                $qid = 0;
                $varlabel = $fieldname;
                $ftitle = $fieldname;
                $fieldtype = "F";
                $val_size = 1;
            } else {
                $fielddata = $fieldmap[$fieldname];
                $qid = $fielddata['qid'];
                $ftype = $fielddata['type'];
                $fsid = $fielddata['sid'];
                $fgid = $fielddata['gid'];
                $code = mb_substr($fielddata['fieldname'], strlen($fsid . "X" . $fgid . "X" . $qid));
                $varlabel = $fielddata['question'];
                if (isset($fielddata['scale'])) {
                    $varlabel = "[{$fielddata['scale']}] " . $varlabel;
                }
                if (isset($fielddata['subquestion'])) {
                    $varlabel = "[{$fielddata['subquestion']}] " . $varlabel;
                }
                if (isset($fielddata['subquestion2'])) {
                    $varlabel = "[{$fielddata['subquestion2']}] " . $varlabel;
                }
                if (isset($fielddata['subquestion1'])) {
                    $varlabel = "[{$fielddata['subquestion1']}] " . $varlabel;
                }
                $ftitle = $fielddata['title'];
                if (!is_null($code) && $code != "") {
                    $ftitle .= "_{$code}";
                }
                if (isset($typeMap[$ftype]['size'])) {
                    $val_size = $typeMap[$ftype]['size'];
                }
                if (isset($fielddata['scale_id'])) {
                    $scale_id = $fielddata['scale_id'];
                }
                if ($fieldtype == '') {
                    $fieldtype = $typeMap[$ftype]['SPSStype'];
                }
                if (isset($typeMap[$ftype]['hide'])) {
                    $hide = $typeMap[$ftype]['hide'];
                    $diff++;
                }
                //Get default scale for this type
                if (isset($typeMap[$ftype]['Scale'])) {
                    $export_scale = $typeMap[$ftype]['Scale'];
                }
                //But allow override
                $aQuestionAttribs = getQuestionAttributeValues($qid);
                if (isset($aQuestionAttribs['scale_export'])) {
                    $export_scale = $aQuestionAttribs['scale_export'];
                }
            }
        }
        $fieldno++;
        $fid = $fieldno - $diff;
        $lsLong = isset($typeMap[$ftype]["name"]) ? $typeMap[$ftype]["name"] : $ftype;
        $tempArray = array('id' => "{$prefix}{$fid}", 'name' => mb_substr($fieldname, 0, 8), 'qid' => $qid, 'code' => $code, 'SPSStype' => $fieldtype, 'LStype' => $ftype, "LSlong" => $lsLong, 'ValueLabels' => '', 'VariableLabel' => $varlabel, "sql_name" => $fieldname, "size" => $val_size, 'title' => $ftitle, 'hide' => $hide, 'scale' => $export_scale, 'scale_id' => $scale_id);
        //Now check if we have to retrieve value labels
        $answers = SPSSGetValues($tempArray, $aQuestionAttribs, $language);
        if (is_array($answers)) {
            //Ok we have answers
            if (isset($answers['size'])) {
                $tempArray['size'] = $answers['size'];
                unset($answers['size']);
            }
            if (isset($answers['SPSStype'])) {
                $tempArray['SPSStype'] = $answers['SPSStype'];
                unset($answers['SPSStype']);
            }
            $tempArray['answers'] = $answers;
        }
        $fields[] = $tempArray;
    }
    return $fields;
}
Exemplo n.º 12
0
 /**
  * Generates statistics
  *
  * @param int $surveyid The survey id
  * @param mixed $allfields
  * @param mixed $q2show
  * @param mixed $usegraph
  * @param string $outputType Optional - Can be xls, html or pdf - Defaults to pdf
  * @param string $pdfOutput Sets the target for the PDF output: DD=File download , F=Save file to local disk
  * @param string $statlangcode Lamguage for statistics
  * @param mixed $browse  Show browse buttons
  * @return buffer
  */
 public function generate_statistics($surveyid, $allfields, $q2show = 'all', $usegraph = 0, $outputType = 'pdf', $pdfOutput = 'I', $sLanguageCode = null, $browse = true)
 {
     $aStatisticsData = array();
     //astatdata generates data for the output page's javascript so it can rebuild graphs on the fly
     //load surveytranslator helper
     Yii::import('application.helpers.surveytranslator_helper', true);
     Yii::import('application.third_party.ar-php.Arabic', true);
     $sOutputHTML = "";
     //This string carries all the actual HTML code to print.
     $sTempDir = Yii::app()->getConfig("tempdir");
     $this->pdf = array();
     //Make sure $this->pdf exists - it will be replaced with an object if a $this->pdf is actually being created
     //pick the best font file if font setting is 'auto'
     if (is_null($sLanguageCode)) {
         $sLanguageCode = getBaseLanguageFromSurveyID($surveyid);
     }
     Yii::app()->setLanguage($sLanguageCode);
     /*
      * this variable is used in the function shortencode() which cuts off a question/answer title
      * after $maxchars and shows the rest as tooltip (in html mode)
      */
     $maxchars = 13;
     //we collect all the html-output within this variable
     $sOutputHTML = '';
     /**
      * $outputType: html || pdf ||
      */
     /**
      * get/set Survey Details
      */
     //no survey ID? -> come and get one
     if (!isset($surveyid)) {
         $surveyid = returnGlobal('sid');
     }
     //Get an array of codes of all available languages in this survey
     $surveylanguagecodes = Survey::model()->findByPk($surveyid)->additionalLanguages;
     $surveylanguagecodes[] = Survey::model()->findByPk($surveyid)->language;
     $fieldmap = createFieldMap($surveyid, "full", false, false, $sLanguageCode);
     // Set language for questions and answers to base language of this survey
     $language = $sLanguageCode;
     if ($q2show == 'all') {
         $summarySql = " SELECT gid, parent_qid, qid, type " . " FROM {{questions}} WHERE parent_qid=0" . " AND sid={$surveyid} ";
         $summaryRs = Yii::app()->db->createCommand($summarySql)->query()->readAll();
         foreach ($summaryRs as $field) {
             $myField = $surveyid . "X" . $field['gid'] . "X" . $field['qid'];
             // Multiple choice get special treatment
             if ($field['type'] == "M") {
                 $myField = "M{$myField}";
             }
             if ($field['type'] == "P") {
                 $myField = "P{$myField}";
             }
             //numerical input will get special treatment (arihtmetic mean, standard derivation, ...)
             if ($field['type'] == "N") {
                 $myField = "N{$myField}";
             }
             if ($field['type'] == "|") {
                 $myField = "|{$myField}";
             }
             if ($field['type'] == "Q") {
                 $myField = "Q{$myField}";
             }
             // textfields get special treatment
             if ($field['type'] == "S" || $field['type'] == "T" || $field['type'] == "U") {
                 $myField = "T{$myField}";
             }
             //statistics for Date questions are not implemented yet.
             if ($field['type'] == "D") {
                 $myField = "D{$myField}";
             }
             if ($field['type'] == "F" || $field['type'] == "H") {
                 //Get answers. We always use the answer code because the label might be too long elsewise
                 $query = "SELECT code, answer FROM {{answers}} WHERE qid='" . $field['qid'] . "' AND scale_id=0 AND language='{$language}' ORDER BY sortorder, answer";
                 $result = Yii::app()->db->createCommand($query)->query();
                 $counter2 = 0;
                 //check all the answers
                 foreach ($result->readAll() as $row) {
                     $row = array_values($row);
                     $myField = "{$myField}{$row[0]}";
                 }
                 //$myField = "{$surveyid}X{$flt[1]}X{$flt[0]}{$row[0]}[]";
             }
             if ($q2show == 'all') {
                 $summary[] = $myField;
             }
             //$allfields[]=$myField;
         }
     } else {
         // This gets all the 'to be shown questions' from the POST and puts these into an array
         if (!is_array($q2show)) {
             $summary = returnGlobal('summary');
         } else {
             $summary = $q2show;
         }
         //print_r($_POST);
         //if $summary isn't an array we create one
         if (isset($summary) && !is_array($summary)) {
             $summary = explode("+", $summary);
         }
     }
     /**
      * pdf Config
      */
     if ($outputType == 'pdf') {
         //require_once('classes/tcpdf/mypdf.php');
         Yii::import('application.libraries.admin.pdf', true);
         Yii::import('application.helpers.pdfHelper');
         $aPdfLanguageSettings = pdfHelper::getPdfLanguageSettings($language);
         // create new PDF document
         $this->pdf = new pdf();
         $surveyInfo = getSurveyInfo($surveyid, $language);
         // set document information
         $this->pdf->SetCreator(PDF_CREATOR);
         $this->pdf->SetAuthor('LimeSurvey');
         $this->pdf->SetTitle(sprintf(gT("Statistics survey %s"), $surveyid));
         $this->pdf->SetSubject($surveyInfo['surveyls_title']);
         $this->pdf->SetKeywords('LimeSurvey,' . gT("Statistics") . ', ' . sprintf(gT("Survey %s"), $surveyid));
         $this->pdf->SetDisplayMode('fullpage', 'two');
         $this->pdf->setLanguageArray($aPdfLanguageSettings['lg']);
         // set header and footer fonts
         $this->pdf->setHeaderFont(array($aPdfLanguageSettings['pdffont'], '', PDF_FONT_SIZE_MAIN));
         $this->pdf->setFooterFont(array($aPdfLanguageSettings['pdffont'], '', PDF_FONT_SIZE_DATA));
         // set default header data
         // Since png crashes some servers (and we can not try/catch that) we use .gif (or .jpg) instead
         $headerlogo = 'statistics.gif';
         $this->pdf->SetHeaderData($headerlogo, 10, gT("Quick statistics", 'unescaped'), gT("Survey") . " " . $surveyid . " '" . flattenText($surveyInfo['surveyls_title'], false, true, 'UTF-8') . "'");
         $this->pdf->SetFont($aPdfLanguageSettings['pdffont'], '', $aPdfLanguageSettings['pdffontsize']);
         // set default monospaced font
         $this->pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
     }
     if ($outputType == 'xls') {
         /**
          * Initiate the Spreadsheet_Excel_Writer
          */
         require_once APPPATH . '/third_party/pear/Spreadsheet/Excel/Xlswriter.php';
         if ($pdfOutput == 'F') {
             $sFileName = $sTempDir . '/statistic-survey' . $surveyid . '.xls';
             $this->workbook = new Xlswriter($sFileName);
         } else {
             $this->workbook = new Xlswriter();
         }
         $this->workbook->setVersion(8);
         // Inform the module that our data will arrive as UTF-8.
         // Set the temporary directory to avoid PHP error messages due to open_basedir restrictions and calls to tempnam("", ...)
         $this->workbook->setTempDir($sTempDir);
         // Inform the module that our data will arrive as UTF-8.
         // Set the temporary directory to avoid PHP error messages due to open_basedir restrictions and calls to tempnam("", ...)
         if (!empty($sTempDir)) {
             $this->workbook->setTempDir($sTempDir);
         }
         if ($pdfOutput != 'F') {
             $this->workbook->send('statistic-survey' . $surveyid . '.xls');
         }
         // Creating the first worksheet
         $this->sheet = $this->workbook->addWorksheet(utf8_decode('results-survey' . $surveyid));
         $this->xlsPercents =& $this->workbook->addFormat();
         $this->xlsPercents->setNumFormat('0.00%');
         $this->formatBold =& $this->workbook->addFormat(array('Bold' => 1));
         $this->sheet->setInputEncoding('utf-8');
         $this->sheet->setColumn(0, 20, 20);
         $separator = "~|";
         /**XXX*/
     }
     /**
      * Start generating
      */
     $selects = buildSelects($allfields, $surveyid, $language);
     //count number of answers
     $query = "SELECT count(*) FROM {{survey_{$surveyid}}}";
     //if incompleted answers should be filtert submitdate has to be not null
     if (incompleteAnsFilterState() == "incomplete") {
         $query .= " WHERE submitdate is null";
     } elseif (incompleteAnsFilterState() == "complete") {
         $query .= " WHERE submitdate is not null";
     }
     $total = Yii::app()->db->createCommand($query)->queryScalar();
     //are there any filters that have to be taken care of?
     if (isset($selects) && $selects) {
         //Save the filters to session for use in browsing text & other features (statistics.php function listcolumn())
         Yii::app()->session['statistics_selects_' . $surveyid] = $selects;
         //filter incomplete answers?
         if (incompleteAnsFilterState() == "complete" || incompleteAnsFilterState() == "incomplete") {
             $query .= " AND ";
         } else {
             $query .= " WHERE ";
         }
         //add filter criteria to SQL
         $query .= implode(" AND ", $selects);
     }
     //get me some data Scotty
     $results = Yii::app()->db->createCommand($query)->queryScalar();
     if ($total) {
         $percent = sprintf("%01.2f", $results / $total * 100);
     }
     switch ($outputType) {
         case "xls":
             $this->xlsRow = 0;
             $this->sheet->write($this->xlsRow, 0, gT("Number of records in this query:", 'unescaped'));
             $this->sheet->writeNumber($this->xlsRow, 1, $results);
             $this->xlsRow++;
             $this->sheet->write($this->xlsRow, 0, gT("Total records in survey:", 'unescaped'));
             $this->sheet->writeNumber($this->xlsRow, 1, $total);
             if ($total) {
                 $this->xlsRow++;
                 $this->sheet->write($this->xlsRow, 0, gT("Percentage of total:", 'unescaped'));
                 $this->sheet->writeNumber($this->xlsRow, 1, $results / $total, $this->xlsPercents);
             }
             break;
         case 'pdf':
             // add summary to pdf
             $array = array(array(gT("Number of records in this query:", 'unescaped'), $results), array(gT("Total records in survey:", 'unescaped'), $total));
             if ($total) {
                 $array[] = array(gT("Percentage of total:", 'unescaped'), $percent . "%");
             }
             $this->pdf->AddPage('P', ' A4');
             $this->pdf->Bookmark(gT("Results", 'unescaped'), 0, 0);
             $this->pdf->titleintopdf(gT("Results", 'unescaped'), gT("Survey", 'unescaped') . " " . $surveyid);
             $this->pdf->tableintopdf($array);
             break;
         case 'html':
             $sOutputHTML .= "<br />\n<table class='statisticssummary' >\n" . "\t<thead><tr><th colspan='2'>" . gT("Results") . "</th></tr></thead>\n" . "\t<tr><th >" . gT("Number of records in this query:") . '</th>' . "<td>{$results}</td></tr>\n" . "\t<tr><th>" . gT("Total records in survey:") . '</th>' . "<td>{$total}</td></tr>\n";
             //only calculate percentage if $total is set
             if ($total) {
                 $percent = sprintf("%01.2f", $results / $total * 100);
                 $sOutputHTML .= "\t<tr><th align='right'>" . gT("Percentage of total:") . '</th>' . "<td>{$percent}%</td></tr>\n";
             }
             $sOutputHTML .= "</table>\n";
             break;
         default:
             break;
     }
     //put everything from $selects array into a string connected by AND
     //This string ($sql) can then be passed on to other functions so you can
     //browse these results
     if (isset($selects) && $selects) {
         $sql = implode(" AND ", $selects);
     } elseif (!empty($newsql)) {
         $sql = $newsql;
     }
     if (!isset($sql) || !$sql) {
         $sql = null;
     }
     //only continue if we have something to output
     if ($results > 0) {
         if ($outputType == 'html' && $browse === true && Permission::model()->hasSurveyPermission($surveyid, 'responses', 'read')) {
             //add a buttons to browse results
             $sOutputHTML .= CHtml::form(array("admin/responses/sa/browse/surveyid/{$surveyid}"), 'post', array('target' => '_blank')) . "\n" . "\t\t<p>" . "\t\t\t<input type='submit' value='" . gT("Browse") . "'  />\n" . "\t\t\t<input type='hidden' name='sid' value='{$surveyid}' />\n" . "\t\t\t<input type='hidden' name='sql' value=\"{$sql}\" />\n" . "\t\t\t<input type='hidden' name='subaction' value='all' />\n" . "\t\t</p>" . "\t\t</form>\n";
         }
     }
     //end if (results > 0)
     /* Show Summary results
      * The $summary array contains each fieldname that we want to display statistics for
      *
      * */
     if (isset($summary) && $summary) {
         //let's run through the survey
         $runthrough = $summary;
         //START Chop up fieldname and find matching questions
         //loop through all selected questions
         foreach ($runthrough as $rt) {
             //Step 1: Get information about this response field (SGQA) for the summary
             $outputs = $this->buildOutputList($rt, $language, $surveyid, $outputType, $sql, $sLanguageCode);
             $sOutputHTML .= $outputs['statisticsoutput'];
             //2. Collect and Display results #######################################################################
             if (isset($outputs['alist']) && $outputs['alist']) {
                 $display = $this->displayResults($outputs, $results, $rt, $outputType, $surveyid, $sql, $usegraph, $browse, $sLanguageCode);
                 $sOutputHTML .= $display['statisticsoutput'];
                 $aStatisticsData = array_merge($aStatisticsData, $display['astatdata']);
             }
             //end if -> collect and display results
             //Delete Build Outputs data
             unset($outputs);
             unset($display);
         }
         // end foreach -> loop through all questions
         //output
         if ($outputType == 'html') {
             $sOutputHTML .= "<br />&nbsp;\n";
         }
     }
     //end if -> show summary results
     switch ($outputType) {
         case 'xls':
             $this->workbook->close();
             if ($pdfOutput == 'F') {
                 return $sFileName;
             } else {
                 return;
             }
             break;
         case 'pdf':
             $this->pdf->lastPage();
             if ($pdfOutput == 'F') {
                 // This is only used by lsrc to send an E-Mail attachment, so it gives back the filename to send and delete afterwards
                 $tempfilename = $sTempDir . "/Survey_" . $surveyid . ".pdf";
                 $this->pdf->Output($tempfilename, $pdfOutput);
                 return $tempfilename;
             } else {
                 return $this->pdf->Output(gT('Survey') . '_' . $surveyid . "_" . $surveyInfo['surveyls_title'] . '.pdf', $pdfOutput);
             }
             break;
         case 'html':
             $sGoogleMapsAPIKey = trim(Yii::app()->getConfig("googleMapsAPIKey"));
             if ($sGoogleMapsAPIKey != '') {
                 $sGoogleMapsAPIKey = '&key=' . $sGoogleMapsAPIKey;
             }
             $sSSL = '';
             if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != "off") {
                 $sSSL = 's';
             }
             $sOutputHTML .= "<script type=\"text/javascript\" src=\"http{$sSSL}://maps.googleapis.com/maps/api/js?sensor=false{$sGoogleMapsAPIKey}\"></script>\n" . "<script type=\"text/javascript\">var site_url='" . Yii::app()->baseUrl . "';var temppath='" . Yii::app()->getConfig("tempurl") . "';var imgpath='" . Yii::app()->getConfig('adminimageurl') . "';var aStatData=" . ls_json_encode($aStatisticsData) . "</script>";
             return $sOutputHTML;
             break;
         default:
             return $sOutputHTML;
             break;
     }
 }
Exemplo n.º 13
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 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;
 }
Exemplo n.º 14
0
 public function vvexport()
 {
     $iSurveyId = sanitize_int(Yii::app()->request->getParam('surveyid'));
     $subaction = Yii::app()->request->getParam('subaction');
     //Exports all responses to a survey in special "Verified Voting" format.
     if (!Permission::model()->hasSurveyPermission($iSurveyId, 'responses', 'export')) {
         Yii::app()->session['flashmessage'] = gT("You do not have sufficient rights to access this page.");
         $this->getController()->redirect($this->getController()->createUrl("/admin/survey/sa/view/surveyid/{$iSurveyId}"));
     }
     if ($subaction != "export") {
         $aData['selectincansstate'] = incompleteAnsFilterState();
         $aData['surveyid'] = $iSurveyId;
         $aData['display']['menu_bars']['browse'] = gT("Export VV file");
         $fieldmap = createFieldMap($iSurveyId, 'full', false, false, getBaseLanguageFromSurveyID($iSurveyId));
         Survey::model()->findByPk($iSurveyId)->language;
         $surveytable = "{{survey_{$iSurveyId}}}";
         // Control if fieldcode are unique
         $fieldnames = Yii::app()->db->schema->getTable($surveytable)->getColumnNames();
         foreach ($fieldnames as $field) {
             $fielddata = arraySearchByKey($field, $fieldmap, "fieldname", 1);
             $fieldcode[] = viewHelper::getFieldCode($fielddata, array("LEMcompat" => true));
         }
         $aData['uniquefieldcode'] = count(array_unique($fieldcode)) == count($fieldcode);
         // Did we need more control ?
         $aData['vvversionseleted'] = $aData['uniquefieldcode'] ? 2 : 1;
         $this->_renderWrappedTemplate('export', 'vv_view', $aData);
     } elseif (isset($iSurveyId) && $iSurveyId) {
         //Export is happening
         $extension = sanitize_paranoid_string(returnGlobal('extension'));
         $vvVersion = (int) Yii::app()->request->getPost('vvversion');
         $vvVersion = in_array($vvVersion, array(1, 2)) ? $vvVersion : 2;
         // Only 2 version actually, default to 2
         $fn = "vvexport_{$iSurveyId}." . $extension;
         $this->_addHeaders($fn, "text/comma-separated-values", 0, "cache");
         $s = "\t";
         $fieldmap = createFieldMap($iSurveyId, 'full', false, false, getBaseLanguageFromSurveyID($iSurveyId));
         $surveytable = "{{survey_{$iSurveyId}}}";
         Survey::model()->findByPk($iSurveyId)->language;
         $fieldnames = Yii::app()->db->schema->getTable($surveytable)->getColumnNames();
         //Create the human friendly first line
         $firstline = "";
         $secondline = "";
         foreach ($fieldnames as $field) {
             $fielddata = arraySearchByKey($field, $fieldmap, "fieldname", 1);
             if (count($fielddata) < 1) {
                 $firstline .= $field;
             } else {
                 $firstline .= preg_replace('/\\s+/', ' ', strip_tags($fielddata['question']));
             }
             $firstline .= $s;
             if ($vvVersion == 2) {
                 $fieldcode = viewHelper::getFieldCode($fielddata, array("LEMcompat" => true));
                 $fieldcode = $fieldcode ? $fieldcode : $field;
                 // $fieldcode is empty for token if there are no token table
             } else {
                 $fieldcode = $field;
             }
             $secondline .= $fieldcode . $s;
         }
         $vvoutput = $firstline . "\n";
         $vvoutput .= $secondline . "\n";
         $query = "SELECT * FROM " . Yii::app()->db->quoteTableName($surveytable);
         if (incompleteAnsFilterState() == "incomplete") {
             $query .= " WHERE submitdate IS NULL ";
         } elseif (incompleteAnsFilterState() == "complete") {
             $query .= " WHERE submitdate >= '01/01/1980' ";
         }
         $result = Yii::app()->db->createCommand($query)->query();
         echo $vvoutput;
         foreach ($result as $row) {
             foreach ($fieldnames as $field) {
                 if (is_null($row[$field])) {
                     $value = '{question_not_shown}';
                 } else {
                     $value = trim($row[$field]);
                     // sunscreen for the value. necessary for the beach.
                     // careful about the order of these arrays:
                     // lbrace has to be substituted *first*
                     $value = str_replace(array("{", "\n", "\r", "\t"), array("{lbrace}", "{newline}", "{cr}", "{tab}"), $value);
                 }
                 // one last tweak: excel likes to quote values when it
                 // exports as tab-delimited (esp if value contains a comma,
                 // oddly enough).  So we're going to encode a leading quote,
                 // if it occurs, so that we can tell the difference between
                 // strings that "really are" quoted, and those that excel quotes
                 // for us.
                 $value = preg_replace('/^"/', '{quote}', $value);
                 // yay!  that nasty soab won't hurt us now!
                 if ($field == "submitdate" && !$value) {
                     $value = "NULL";
                 }
                 $sun[] = $value;
             }
             /* it is important here to stream output data, line by line
              * in order to avoid huge memory consumption when exporting large
              * quantities of answers */
             echo implode($s, $sun) . "\n";
             unset($sun);
         }
         exit;
     }
 }
 /**
  * RPC Routine to export responses.
  * Returns the requested file as base64 encoded string
  *
  * @access public
  * @param string $sSessionKey Auth credentials
  * @param int $iSurveyID Id of the Survey
  * @param string $sDocumentType pdf,csv,xls,doc,json
  * @param string $sLanguageCode The language to be used
  * @param string $sCompletionStatus Optional 'complete','incomplete' or 'all' - defaults to 'all'
  * @param string $sHeadingType 'code','full' or 'abbreviated' Optional defaults to 'code'
  * @param string $sResponseType 'short' or 'long' Optional defaults to 'short'
  * @param integer $iFromResponseID Optional
  * @param integer $iToResponseID Optional
  * @param array $aFields Optional Selected fields
  * @return array|string On success: Requested file as base 64-encoded string. On failure array with error information
  * */
 public function export_responses($sSessionKey, $iSurveyID, $sDocumentType, $sLanguageCode = null, $sCompletionStatus = 'all', $sHeadingType = 'code', $sResponseType = 'short', $iFromResponseID = null, $iToResponseID = null, $aFields = null)
 {
     if (!$this->_checkSessionKey($sSessionKey)) {
         return array('status' => 'Invalid session key');
     }
     Yii::app()->loadHelper('admin/exportresults');
     if (!tableExists('{{survey_' . $iSurveyID . '}}')) {
         return array('status' => 'No Data, survey table does not exist.');
     }
     if (!($maxId = SurveyDynamic::model($iSurveyID)->getMaxId())) {
         return array('status' => 'No Data, could not get max id.');
     }
     if (!Permission::model()->hasSurveyPermission($iSurveyID, 'responses', 'export')) {
         return array('status' => 'No permission');
     }
     if (is_null($sLanguageCode)) {
         $sLanguageCode = getBaseLanguageFromSurveyID($iSurveyID);
     }
     if (is_null($aFields)) {
         $aFields = array_keys(createFieldMap($iSurveyID, 'full', true, false, $sLanguageCode));
     }
     if ($sDocumentType == 'xls') {
         // Cut down to the first 255 fields
         $aFields = array_slice($aFields, 0, 255);
     }
     $oFomattingOptions = new FormattingOptions();
     if ($iFromResponseID != null) {
         $oFomattingOptions->responseMinRecord = $iFromResponseID;
     } else {
         $oFomattingOptions->responseMinRecord = 1;
     }
     if ($iToResponseID != null) {
         $oFomattingOptions->responseMaxRecord = $iToResponseID;
     } else {
         $oFomattingOptions->responseMaxRecord = $maxId;
     }
     $oFomattingOptions->selectedColumns = $aFields;
     $oFomattingOptions->responseCompletionState = $sCompletionStatus;
     $oFomattingOptions->headingFormat = $sHeadingType;
     $oFomattingOptions->answerFormat = $sResponseType;
     $oFomattingOptions->output = 'file';
     $oExport = new ExportSurveyResultsService();
     $sTempFile = $oExport->exportSurvey($iSurveyID, $sLanguageCode, $sDocumentType, $oFomattingOptions, '');
     return new BigFile($sTempFile, true, 'base64');
 }
Exemplo n.º 16
0
 /**
  * Show printable survey
  */
 function index($surveyid, $lang = null)
 {
     $surveyid = sanitize_int($surveyid);
     //echo '<pre>'.print_r($_SESSION,true).'</pre>';
     // PRESENT SURVEY DATAENTRY SCREEN
     if (isset($_POST['printableexport'])) {
         Yii::import("application.libraries.admin.pdf");
         $pdf = new PDF($pdforientation, 'mm', 'A4');
         $pdf->SetFont($pdfdefaultfont, '', $pdffontsize);
         $pdf->AddPage();
     }
     // Set the language of the survey, either from GET parameter of session var
     if (isset($lang)) {
         $lang = preg_replace("/[^a-zA-Z0-9-]/", "", $lang);
         if ($lang) {
             $surveyprintlang = $lang;
         }
     } else {
         $surveyprintlang = getBaseLanguageFromSurveyID((int) $surveyid);
     }
     $_POST['surveyprintlang'] = $surveyprintlang;
     // Setting the selected language for printout
     $clang = new limesurvey_lang($surveyprintlang);
     $desrow = Survey::model()->with(array('languagesettings' => array('condition' => 'surveyls_language=:language', 'params' => array(':language' => $surveyprintlang))))->findByAttributes(array('sid' => $surveyid));
     if (is_null($desrow)) {
         $this->getController()->error('Invalid survey ID');
     }
     $desrow = array_merge($desrow->attributes, $desrow->languagesettings[0]->attributes);
     //echo '<pre>'.print_r($desrow,true).'</pre>';
     $template = $desrow['template'];
     $welcome = $desrow['surveyls_welcometext'];
     $end = $desrow['surveyls_endtext'];
     $surveyname = $desrow['surveyls_title'];
     $surveydesc = $desrow['surveyls_description'];
     $surveyactive = $desrow['active'];
     $surveytable = "{{survey_" . $desrow['sid'] . "}}";
     $surveyexpirydate = $desrow['expires'];
     $surveystartdate = $desrow['startdate'];
     $surveyfaxto = $desrow['faxto'];
     $dateformattype = $desrow['surveyls_dateformat'];
     if (isset($_POST['printableexport'])) {
         $pdf->titleintopdf($surveyname, $surveydesc);
     }
     Yii::app()->loadHelper('surveytranslator');
     $dformat = getDateFormatData($dateformattype);
     $dformat = $dformat['phpdate'];
     $expirytimestamp = strtotime($surveyexpirydate);
     $expirytimeofday_h = date('H', $expirytimestamp);
     $expirytimeofday_m = date('i', $expirytimestamp);
     $surveyexpirydate = date($dformat, $expirytimestamp);
     if (!empty($expirytimeofday_h) || !empty($expirytimeofday_m)) {
         $surveyexpirydate .= ' &ndash; ' . $expirytimeofday_h . ':' . $expirytimeofday_m;
     }
     //define('PRINT_TEMPLATE' , '/templates/print/' , true);
     if (is_file(Yii::app()->getConfig('usertemplaterootdir') . DIRECTORY_SEPARATOR . $template . DIRECTORY_SEPARATOR . 'print_survey.pstpl')) {
         define('PRINT_TEMPLATE_DIR', Yii::app()->getConfig('usertemplaterootdir') . DIRECTORY_SEPARATOR . $template . DIRECTORY_SEPARATOR, true);
         define('PRINT_TEMPLATE_URL', Yii::app()->getConfig('usertemplaterooturl') . '/' . $template . '/', true);
     } elseif (is_file(Yii::app()->getConfig('usertemplaterootdir') . '/' . $template . '/print_survey.pstpl')) {
         define('PRINT_TEMPLATE_DIR', Yii::app()->getConfig('standardtemplaterootdir') . DIRECTORY_SEPARATOR . $template . DIRECTORY_SEPARATOR, true);
         define('PRINT_TEMPLATE_URL', Yii::app()->getConfig('standardtemplaterooturl') . '/' . $template . '/', true);
     } else {
         define('PRINT_TEMPLATE_DIR', Yii::app()->getConfig('standardtemplaterootdir') . DIRECTORY_SEPARATOR . 'default' . DIRECTORY_SEPARATOR, true);
         define('PRINT_TEMPLATE_URL', Yii::app()->getConfig('standardtemplaterooturl') . '/default/', true);
     }
     LimeExpressionManager::StartSurvey($surveyid, 'survey', NULL, false, LEM_PRETTY_PRINT_ALL_SYNTAX);
     $moveResult = LimeExpressionManager::NavigateForwards();
     $condition = "sid = '{$surveyid}' AND language = '{$surveyprintlang}'";
     $degresult = Groups::model()->getAllGroups($condition, array('group_order'));
     //xiao,
     if (!isset($surveyfaxto) || !$surveyfaxto and isset($surveyfaxnumber)) {
         $surveyfaxto = $surveyfaxnumber;
         //Use system fax number if none is set in survey.
     }
     $headelements = getPrintableHeader();
     //if $showsgqacode is enabled at config.php show table name for reference
     $showsgqacode = Yii::app()->getConfig("showsgqacode");
     if (isset($showsgqacode) && $showsgqacode == true) {
         $surveyname = $surveyname . "<br />[" . $clang->gT('Database') . " " . $clang->gT('table') . ": {$surveytable}]";
     } else {
         $surveyname = $surveyname;
     }
     $survey_output = array('SITENAME' => Yii::app()->getConfig("sitename"), 'SURVEYNAME' => $surveyname, 'SURVEYDESCRIPTION' => $surveydesc, 'WELCOME' => $welcome, 'END' => $end, 'THEREAREXQUESTIONS' => 0, 'SUBMIT_TEXT' => $clang->gT("Submit Your Survey."), 'SUBMIT_BY' => $surveyexpirydate, 'THANKS' => $clang->gT("Thank you for completing this survey."), 'HEADELEMENTS' => $headelements, 'TEMPLATEURL' => PRINT_TEMPLATE_URL, 'FAXTO' => $surveyfaxto, 'PRIVACY' => '', 'GROUPS' => '');
     $survey_output['FAX_TO'] = '';
     if (!empty($surveyfaxto) && $surveyfaxto != '000-00000000') {
         $survey_output['FAX_TO'] = $clang->gT("Please fax your completed survey to:") . " {$surveyfaxto}";
     }
     if ($surveystartdate != '') {
         $survey_output['SUBMIT_BY'] = sprintf($clang->gT("Please submit by %s"), $surveyexpirydate);
     }
     /**
      * Output arrays:
      *    $survey_output  =       final vaiables for whole survey
      *        $survey_output['SITENAME'] =
      *        $survey_output['SURVEYNAME'] =
      *        $survey_output['SURVEY_DESCRIPTION'] =
      *        $survey_output['WELCOME'] =
      *        $survey_output['THEREAREXQUESTIONS'] =
      *        $survey_output['PDF_FORM'] =
      *        $survey_output['HEADELEMENTS'] =
      *        $survey_output['TEMPLATEURL'] =
      *        $survey_output['SUBMIT_TEXT'] =
      *        $survey_output['SUBMIT_BY'] =
      *        $survey_output['THANKS'] =
      *        $survey_output['FAX_TO'] =
      *        $survey_output['SURVEY'] =     contains an array of all the group arrays
      *
      *    $groups[]       =       an array of all the groups output
      *        $group['GROUPNAME'] =
      *        $group['GROUPDESCRIPTION'] =
      *        $group['QUESTIONS'] =     templated formatted content if $question is appended to this at the end of processing each question.
      *        $group['ODD_EVEN'] =     class to differentiate alternate groups
      *        $group['SCENARIO'] =
      *
      *    $questions[]    =       contains an array of all the questions within a group
      *        $question['QUESTION_CODE'] =         content of the question code field
      *        $question['QUESTION_TEXT'] =         content of the question field
      *        $question['QUESTION_SCENARIO'] =         if there are conditions on a question, list the conditions.
      *        $question['QUESTION_MANDATORY'] =     translated 'mandatory' identifier
      *        $question['QUESTION_CLASS'] =         classes to be added to wrapping question div
      *        $question['QUESTION_TYPE_HELP'] =         instructions on how to complete the question
      *        $question['QUESTION_MAN_MESSAGE'] =     (not sure if this is used) mandatory error
      *        $question['QUESTION_VALID_MESSAGE'] =     (not sure if this is used) validation error
      *        $question['ANSWER'] =                contains formatted HTML answer
      *        $question['QUESTIONHELP'] =         content of the question help field.
      *
      */
     $total_questions = 0;
     $mapquestionsNumbers = array();
     $answertext = '';
     // otherwise can throw an error on line 1617
     // =========================================================
     // START doin the business:
     $pdfoutput = '';
     foreach ($degresult->readAll() as $degrow) {
         // ---------------------------------------------------
         // START doing groups
         $deqresult = Questions::model()->getQuestions($surveyid, $degrow['gid'], $surveyprintlang, 0, '"I"');
         $deqrows = array();
         //Create an empty array in case FetchRow does not return any rows
         foreach ($deqresult->readAll() as $deqrow) {
             $deqrows[] = $deqrow;
         }
         // Get table output into array
         // Perform a case insensitive natural sort on group name then question title of a multidimensional array
         usort($deqrows, 'groupOrderThenQuestionOrder');
         if ($degrow['description']) {
             $group_desc = $degrow['description'];
         } else {
             $group_desc = '';
         }
         $group = array('GROUPNAME' => $degrow['group_name'], 'GROUPDESCRIPTION' => $group_desc, 'QUESTIONS' => '');
         // A group can have only hidden questions. In that case you don't want to see the group's header/description either.
         $bGroupHasVisibleQuestions = false;
         if (isset($_POST['printableexport'])) {
             $pdf->titleintopdf($degrow['group_name'], $degrow['description']);
         }
         $gid = $degrow['gid'];
         //Alternate bgcolor for different groups
         if (!isset($group['ODD_EVEN']) || $group['ODD_EVEN'] == ' g-row-even') {
             $group['ODD_EVEN'] = ' g-row-odd';
         } else {
             $group['ODD_EVEN'] = ' g-row-even';
         }
         //Loop through questions
         foreach ($deqrows as $deqrow) {
             // - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
             // START doing questions
             $qidattributes = getQuestionAttributeValues($deqrow['qid'], $deqrow['type']);
             if ($qidattributes['hidden'] == 1 && $deqrow['type'] != '*') {
                 continue;
             }
             $bGroupHasVisibleQuestions = true;
             //GET ANY CONDITIONS THAT APPLY TO THIS QUESTION
             $printablesurveyoutput = '';
             $explanation = '';
             //reset conditions explanation
             $s = 0;
             //                    // TMSW Conditions->Relevance:  show relevance instead of this whole section to create $explanation
             //
             //
             //                            $scenarioresult=Conditions::model()->getScenarios($deqrow['qid']);
             //                            $scenarioresult = $scenarioresult->readAll();
             //                    //Loop through distinct scenarios, thus grouping them together.
             //                    foreach ($scenarioresult as $scenariorow)
             //                    {
             //                        if( $s == 0 && count($scenarioresult) > 1)
             //                        {
             //                            $explanation .= '<p class="scenario">'.self::_try_debug(__LINE__)." -------- Scenario {$scenariorow['scenario']} --------</p>\n\n";
             //                        }
             //                        if($s > 0)
             //                        {
             //                            $explanation .= '<p class="scenario">'.self::_try_debug(__LINE__).' -------- '.$clang->gT("or")." Scenario {$scenariorow['scenario']} --------</p>\n\n";
             //                        }
             //
             //                        $x=0;
             //
             //                        $conditions1="qid={$deqrow['qid']} AND scenario={$scenariorow['scenario']}";
             //                        $distinctresult=Conditions::model()->getSomeConditions(array('cqid','method', 'cfieldname', 'value'), $conditions1, array('cqid'),array('cqid', 'method'));
             //
             //                        //Loop through each condition for a particular scenario.
             //                        foreach ($distinctresult->readAll() as $distinctrow)
             //                        {
             //                              $condition = "qid = '{$distinctrow['cqid']}' AND parent_qid = 0 AND language = '{$surveyprintlang}'";
             //                              $subresult=Questions::model()->find($condition);
             //
             //                            if($x > 0)
             //                            {
             //                                $explanation .= ' <em class="scenario-and-seperator">'.$clang->gT('and').'</em> ';
             //                            }
             //                            if(trim($distinctrow['method'])=='') //If there is no method chosen assume "equals"
             //                            {
             //                                $distinctrow['method']='==';
             //                            }
             //
             //                            if($distinctrow['cqid']){ // cqid != 0  ==> previous answer match
             //                                if($distinctrow['method']=='==')
             //                                {
             //                                    $explanation .= $clang->gT("Answer was")." ";
             //                                }
             //                                elseif($distinctrow['method']=='!=')
             //                                {
             //                                    $explanation .= $clang->gT("Answer was NOT")." ";
             //                                }
             //                                elseif($distinctrow['method']=='<')
             //                                {
             //                                    $explanation .= $clang->gT("Answer was less than")." ";
             //                                }
             //                                elseif($distinctrow['method']=='<=')
             //                                {
             //                                    $explanation .= $clang->gT("Answer was less than or equal to")." ";
             //                                }
             //                                elseif($distinctrow['method']=='>=')
             //                                {
             //                                    $explanation .= $clang->gT("Answer was greater than or equal to")." ";
             //                                }
             //                                elseif($distinctrow['method']=='>')
             //                                {
             //                                    $explanation .= $clang->gT("Answer was greater than")." ";
             //                                }
             //                                elseif($distinctrow['method']=='RX')
             //                                {
             //                                    $explanation .= $clang->gT("Answer matched (regexp)")." ";
             //                                }
             //                                else
             //                                {
             //                                    $explanation .= $clang->gT("Answer was")." ";
             //                                }
             //                                if($distinctrow['value'] == '') {
             //                                    $explanation .= ' '.$clang->gT("Not selected").' ';
             //                                }
             //                                //If question type is numerical or multi-numerical, show the actual value - otherwise, don't.
             //                                if($subresult['type'] == 'N' || $subresult['type'] == 'K') {
             //                                    $explanation .= ' '.$distinctrow['value']. ' ';
             //                                }
             //                            }
             //                            if(!$distinctrow['cqid']) { // cqid == 0  ==> token attribute match
             //                                $tokenData = getTokenFieldsAndNames($surveyid);
             //                                preg_match('/^{TOKEN:([^}]*)}$/',$distinctrow['cfieldname'],$extractedTokenAttr);
             //                                $explanation .= "Your ".$tokenData[strtolower($extractedTokenAttr[1])]." ";
             //                                if($distinctrow['method']=='==')
             //                                {
             //                                    $explanation .= $clang->gT("is")." ";
             //                                }
             //                                elseif($distinctrow['method']=='!=')
             //                                {
             //                                    $explanation .= $clang->gT("is NOT")." ";
             //                                }
             //                                elseif($distinctrow['method']=='<')
             //                                {
             //                                    $explanation .= $clang->gT("is less than")." ";
             //                                }
             //                                elseif($distinctrow['method']=='<=')
             //                                {
             //                                    $explanation .= $clang->gT("is less than or equal to")." ";
             //                                }
             //                                elseif($distinctrow['method']=='>=')
             //                                {
             //                                    $explanation .= $clang->gT("is greater than or equal to")." ";
             //                                }
             //                                elseif($distinctrow['method']=='>')
             //                                {
             //                                    $explanation .= $clang->gT("is greater than")." ";
             //                                }
             //                                elseif($distinctrow['method']=='RX')
             //                                {
             //                                    $explanation .= $clang->gT("is matched (regexp)")." ";
             //                                }
             //                                else
             //                                {
             //                                    $explanation .= $clang->gT("is")." ";
             //                                }
             //                                $answer_section = ' '.$distinctrow['value'].' ';
             //                            }
             //
             //                            $conresult=Conditions::model()->getConditionsQuestions($distinctrow['cqid'],$deqrow['qid'],$scenariorow['scenario'],$surveyprintlang);
             //
             //                            $conditions=array();
             //                            foreach ($conresult->readAll() as $conrow)
             //                            {
             //
             //                                $postans="";
             //                                $value=$conrow['value'];
             //                                switch($conrow['type'])
             //                                {
             //                                    case "Y":
             //                                        switch ($conrow['value'])
             //                                        {
             //                                            case "Y": $conditions[]=$clang->gT("Yes"); break;
             //                                            case "N": $conditions[]=$clang->gT("No"); break;
             //                                        }
             //                                        break;
             //                                    case "G":
             //                                        switch($conrow['value'])
             //                                        {
             //                                            case "M": $conditions[]=$clang->gT("Male"); break;
             //                                            case "F": $conditions[]=$clang->gT("Female"); break;
             //                                        } // switch
             //                                        break;
             //                                    case "A":
             //                                    case "B":
             //                                    case ":":
             //                                    case ";":
             //                                        $conditions[]=$conrow['value'];
             //                                        break;
             //                                    case "C":
             //                                        switch($conrow['value'])
             //                                        {
             //                                            case "Y": $conditions[]=$clang->gT("Yes"); break;
             //                                            case "U": $conditions[]=$clang->gT("Uncertain"); break;
             //                                            case "N": $conditions[]=$clang->gT("No"); break;
             //                                        } // switch
             //                                        break;
             //                                    case "E":
             //                                        switch($conrow['value'])
             //                                        {
             //                                            case "I": $conditions[]=$clang->gT("Increase"); break;
             //                                            case "D": $conditions[]=$clang->gT("Decrease"); break;
             //                                            case "S": $conditions[]=$clang->gT("Same"); break;
             //                                        }
             //                                    case "1":
             //                                        $labelIndex=preg_match("/^[^#]+#([01]{1})$/",$conrow['cfieldname']);
             //                                        if ($labelIndex == 0)
             //                                        { // TIBO
             //
             //                                        $condition="qid='{$conrow['cqid']}' AND code='{$conrow['value']}' AND scale_id=0 AND language='{$surveyprintlang}'";
             //                                        $fresult=Answers::model()->getAllRecords($condition);
             //
             //                                            foreach($fresult->readAll() as $frow)
             //                                            {
             //                                                $postans=$frow['answer'];
             //                                                $conditions[]=$frow['answer'];
             //                                            } // while
             //                                        }
             //                                        elseif ($labelIndex == 1)
             //                                        {
             //
             //                                        $condition="qid='{$conrow['cqid']}' AND code='{$conrow['value']}' AND scale_id=1 AND language='{$surveyprintlang}'";
             //                                        $fresult=Answers::model()->getAllRecords($condition);
             //                                            foreach($fresult->readAll() as $frow)
             //                                            {
             //                                                $postans=$frow['answer'];
             //                                                $conditions[]=$frow['answer'];
             //                                            } // while
             //                                        }
             //                                        break;
             //                                    case "L":
             //                                    case "!":
             //                                    case "O":
             //                                    case "R":
             //                                        $condition="qid='{$conrow['cqid']}' AND code='{$conrow['value']}' AND language='{$surveyprintlang}'";
             //                                        $ansresult=Answers::model()->findAll($condition);
             //
             //                                        foreach ($ansresult as $ansrow)
             //                                        {
             //                                            $conditions[]=$ansrow['answer'];
             //                                        }
             //                                        if($conrow['value'] == "-oth-") {
             //                                            $conditions[]=$clang->gT("Other");
             //                                        }
             //                                        $conditions = array_unique($conditions);
             //                                        break;
             //                                    case "M":
             //                                    case "P":
             //                                        $condition=" parent_qid='{$conrow['cqid']}' AND title='{$conrow['value']}' AND language='{$surveyprintlang}'";
             //                                        $ansresult=Questions::model()->findAll($condition);
             //                                        foreach ($ansresult as $ansrow)
             //                                        {
             //                                            $conditions[]=$ansrow['question'];
             //                                        }
             //                                        $conditions = array_unique($conditions);
             //                                        break;
             //                                    case "N":
             //                                        $conditions[]=$value;
             //                                        break;
             //                                    case "F":
             //                                    case "H":
             //                                    default:
             //                                        $value=substr($conrow['cfieldname'], strpos($conrow['cfieldname'], "X".$conrow['cqid'])+strlen("X".$conrow['cqid']), strlen($conrow['cfieldname']));
             //
             //                                        $condition=" qid='{$conrow['cqid']}' AND code='{$conrow['value']}' AND language='{$surveyprintlang}'";
             //
             //                                        $fresult=Answers::model()->getAllRecords($condition);
             //                                        foreach ($fresult->readAll() as $frow)
             //                                        {
             //                                            $postans=$frow['answer'];
             //                                            $conditions[]=$frow['answer'];
             //                                        } // while
             //                                        break;
             //                                } // switch
             //
             //                                // Now let's complete the answer text with the answer_section
             //                                $answer_section="";
             //                                switch($conrow['type'])
             //                                {
             //                                    case "A":
             //                                    case "B":
             //                                    case "C":
             //                                    case "E":
             //                                    case "F":
             //                                    case "H":
             //                                    case "K":
             //                                        $thiscquestion=$fieldmap[$conrow['cfieldname']];
             //                                        $condition="parent_qid='{$conrow['cqid']}' AND title='{$thiscquestion['aid']}' AND language='{$surveyprintlang}'";
             //                                          $ansresult= Questions::model()->findAll($condition);
             //
             //                                        foreach ($ansresult as $ansrow)
             //                                        {
             //                                            $answer_section=" (".$ansrow['question'].")";
             //                                        }
             //                                        break;
             //
             //                                    case "1": // dual: (Label 1), (Label 2)
             //                                        $labelIndex=substr($conrow['cfieldname'],-1);
             //                                        $thiscquestion=$fieldmap[$conrow['cfieldname']];
             //                                         $condition="parent_qid='{$conrow['cqid']}' AND title='{$thiscquestion['aid']}' AND language='{$surveyprintlang}'";
             //                                         $ansresult= Questions::model()->findAll($condition);
             //                                        $cqidattributes = getQuestionAttributeValues($conrow['cqid'], $conrow['type']);
             //                                        if ($labelIndex == 0)
             //                                        {
             //                                            if (trim($cqidattributes['dualscale_headerA']) != '') {
             //                                                $header = $clang->gT($cqidattributes['dualscale_headerA']);
             //                                            } else {
             //                                                $header = '1';
             //                                            }
             //                                        }
             //                                        elseif ($labelIndex == 1)
             //                                        {
             //                                            if (trim($cqidattributes['dualscale_headerB']) != '') {
             //                                                $header = $clang->gT($cqidattributes['dualscale_headerB']);
             //                                            } else {
             //                                                $header = '2';
             //                                            }
             //                                        }
             //                                        foreach ($ansresult->readAll() as $ansrow)
             //                                        {
             //                                            $answer_section=" (".$ansrow['question']." ".sprintf($clang->gT("Label %s"),$header).")";
             //                                        }
             //                                        break;
             //                                    case ":":
             //                                    case ";": //multi flexi: ( answer [label] )
             //                                        $thiscquestion=$fieldmap[$conrow['cfieldname']];
             //                                        $condition="parent_qid='{$conrow['cqid']}' AND title='{$thiscquestion['aid']}' AND language='{$surveyprintlang}'";
             //                                         $ansresult= Questions::model()->findAll($condition);
             //                                        foreach ($ansresult as $ansrow)
             //                                        {
             //
             //                                        $condition = "qid = '{$conrow['cqid']}' AND code = '{$conrow['value']}' AND language= '{$surveyprintlang}'";
             //                                        $fresult= Answers::model()->findAll($condition);
             //                                            foreach ($fresult as $frow)
             //                                            {
             //                                                //$conditions[]=$frow['title'];
             //                                                $answer_section=" (".$ansrow['question']."[".$frow['answer']."])";
             //                                            } // while
             //                                        }
             //                                        break;
             //                                    case "R": // (Rank 1), (Rank 2)... TIBO
             //                                        $thiscquestion=$fieldmap[$conrow['cfieldname']];
             //                                        $rankid=$thiscquestion['aid'];
             //                                        $answer_section=" (".$clang->gT("RANK")." $rankid)";
             //                                        break;
             //                                    default: // nothing to add
             //                                        break;
             //                                }
             //                            }
             //
             //                            if (count($conditions) > 1)
             //                            {
             //                                $explanation .=  "'".implode("' <em class='scenario-or-seperator'>".$clang->gT("or")."</em> '", $conditions)."'";
             //                            }
             //                            elseif (count($conditions) == 1)
             //                            {
             //                                $explanation .= "'".$conditions[0]."'";
             //                            }
             //                            unset($conditions);
             //                            // Following line commented out because answer_section  was lost, but is required for some question types
             //                            //$explanation .= " ".$clang->gT("to question")." '".$mapquestionsNumbers[$distinctrow['cqid']]."' $answer_section ";
             //                            if($distinctrow['cqid']){
             //                                $explanation .= " <span class='scenario-at-seperator'>".$clang->gT("at question")."</span> '".$mapquestionsNumbers[$distinctrow['cqid']]." [".$subresult['title']."]' (".strip_tags($subresult['question'])."$answer_section)" ;
             //                            }
             //                            else{
             //                                $explanation .= " ".$distinctrow['value'] ;
             //                            }
             //                            //$distinctrow
             //                            $x++;
             //                        }
             //                        $s++;
             //                    }
             $qinfo = LimeExpressionManager::GetQuestionStatus($deqrow['qid']);
             $relevance = trim($qinfo['info']['relevance']);
             $explanation = $qinfo['relEqn'];
             if (trim($relevance) != '' && trim($relevance) != '1') {
                 $explanation = "<b>" . $clang->gT('Only answer this question if the following conditions are met:') . "</b>" . "<br/> ° " . $explanation;
             } else {
                 $explanation = '';
             }
             ++$total_questions;
             //TIBO map question qid to their q number
             $mapquestionsNumbers[$deqrow['qid']] = $total_questions;
             //END OF GETTING CONDITIONS
             $qid = $deqrow['qid'];
             $fieldname = "{$surveyid}" . "X" . "{$gid}" . "X" . "{$qid}";
             if (isset($showsgqacode) && $showsgqacode == true) {
                 $deqrow['question'] = $deqrow['question'] . "<br />" . $clang->gT("ID:") . " {$fieldname} <br />" . $clang->gT("Question code:") . " " . $deqrow['title'];
             }
             $question = array('QUESTION_NUMBER' => $total_questions, 'QUESTION_CODE' => $deqrow['title'], 'QUESTION_TEXT' => preg_replace('/(?:<br ?\\/?>|<\\/(?:p|h[1-6])>)$/is', '', $deqrow['question']), 'QUESTION_SCENARIO' => $explanation, 'QUESTION_MANDATORY' => '', 'QUESTION_ID' => $deqrow['qid'], 'QUESTION_CLASS' => getQuestionClass($deqrow['type']), 'QUESTION_TYPE_HELP' => $qinfo['validTip'], 'QUESTION_MAN_MESSAGE' => '', 'QUESTION_VALID_MESSAGE' => '', 'QUESTION_FILE_VALID_MESSAGE' => '', 'QUESTIONHELP' => '', 'ANSWER' => '');
             if ($question['QUESTION_TYPE_HELP'] != "") {
                 $question['QUESTION_TYPE_HELP'] .= "<br />\n";
             }
             if ($deqrow['mandatory'] == 'Y') {
                 $question['QUESTION_MANDATORY'] = $clang->gT('*');
                 $question['QUESTION_CLASS'] .= ' mandatory';
                 $pdfoutput .= $clang->gT("*");
             }
             $pdfoutput = '';
             //DIFFERENT TYPES OF DATA FIELD HERE
             if (isset($_POST['printableexport'])) {
                 $pdf->intopdf($deqrow['title'] . " " . $deqrow['question']);
             }
             if ($deqrow['help']) {
                 $hh = $deqrow['help'];
                 $question['QUESTIONHELP'] = $hh;
                 if (isset($_POST['printableexport'])) {
                     $pdf->helptextintopdf($hh);
                 }
             }
             if (!empty($qidattributes['page_break'])) {
                 $question['QUESTION_CLASS'] .= ' breakbefore ';
             }
             if (isset($qidattributes['maximum_chars']) && $qidattributes['maximum_chars'] != '') {
                 $question['QUESTION_CLASS'] = "max-chars-{$qidattributes['maximum_chars']} " . $question['QUESTION_CLASS'];
             }
             switch ($deqrow['type']) {
                 // ==================================================================
                 case "5":
                     //5 POINT CHOICE
                     $question['QUESTION_TYPE_HELP'] .= $clang->gT('Please choose *only one* of the following:');
                     if (isset($_POST['printableexport'])) {
                         $pdf->intopdf($clang->gT("Please choose *only one* of the following:"), "U");
                     }
                     $pdfoutput = '';
                     $question['ANSWER'] .= "\n\t<ul>\n";
                     for ($i = 1; $i <= 5; $i++) {
                         $pdfoutput .= " o " . $i . " ";
                         //                        $printablesurveyoutput .="\t\t\t<input type='checkbox' name='$fieldname' value='$i' readonly='readonly' />$i \n";
                         $question['ANSWER'] .= "\t\t<li>\n\t\t\t" . self::_input_type_image('radio', $i) . "\n\t\t\t{$i} " . self::_addsgqacode("({$i})") . "\n\t\t</li>\n";
                     }
                     if (isset($_POST['printableexport'])) {
                         $pdf->intopdf($pdfoutput);
                     }
                     $question['ANSWER'] .= "\t</ul>\n";
                     break;
                     // ==================================================================
                 // ==================================================================
                 case "D":
                     //DATE
                     $question['QUESTION_TYPE_HELP'] .= $clang->gT('Please enter a date:');
                     $question['ANSWER'] .= "\t" . self::_input_type_image('text', $question['QUESTION_TYPE_HELP'], 30, 1);
                     if (isset($_POST['printableexport'])) {
                         $pdf->intopdf($clang->gT("Please enter a date:") . " ___________");
                     }
                     break;
                     // ==================================================================
                 // ==================================================================
                 case "G":
                     //GENDER
                     $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please choose *only one* of the following:");
                     $question['ANSWER'] .= "\n\t<ul>\n";
                     $question['ANSWER'] .= "\t\t<li>\n\t\t\t" . self::_input_type_image('radio', $clang->gT("Female")) . "\n\t\t\t" . $clang->gT("Female") . " " . self::_addsgqacode("(F)") . "\n\t\t</li>\n";
                     $question['ANSWER'] .= "\t\t<li>\n\t\t\t" . self::_input_type_image('radio', $clang->gT("Male")) . "\n\t\t\t" . $clang->gT("Male") . " " . self::_addsgqacode("(M)") . "\n\t\t</li>\n";
                     $question['ANSWER'] .= "\t</ul>\n";
                     if (isset($_POST['printableexport'])) {
                         $pdf->intopdf($clang->gT("Please choose *only one* of the following:"));
                     }
                     if (isset($_POST['printableexport'])) {
                         $pdf->intopdf(" o " . $clang->gT("Female") . " | o " . $clang->gT("Male"));
                     }
                     break;
                     // ==================================================================
                 // ==================================================================
                 case "L":
                     //LIST drop-down/radio-button list
                     // ==================================================================
                 //LIST drop-down/radio-button list
                 // ==================================================================
                 case "!":
                     //List - dropdown
                     if (isset($qidattributes['display_columns']) && trim($qidattributes['display_columns']) != '') {
                         $dcols = $qidattributes['display_columns'];
                     } else {
                         $dcols = 0;
                     }
                     if (isset($qidattributes['category_separator']) && trim($qidattributes['category_separator']) != '') {
                         $optCategorySeparator = $qidattributes['category_separator'];
                     } else {
                         unset($optCategorySeparator);
                     }
                     $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please choose *only one* of the following:");
                     $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $surveyprintlang, $surveyid);
                     if (isset($_POST['printableexport'])) {
                         $pdf->intopdf($clang->gT("Please choose *only one* of the following:"));
                     }
                     $dearesult = Answers::model()->getAllRecords(" qid='{$deqrow['qid']}' AND language='{$surveyprintlang}' ", array('sortorder', 'answer'));
                     $dearesult = $dearesult->readAll();
                     $deacount = count($dearesult);
                     if ($deqrow['other'] == "Y") {
                         $deacount++;
                     }
                     $wrapper = setupColumns(0, $deacount);
                     $question['ANSWER'] = $wrapper['whole-start'];
                     $rowcounter = 0;
                     $colcounter = 1;
                     foreach ($dearesult as $dearow) {
                         if (isset($optCategorySeparator)) {
                             list($category, $answer) = explode($optCategorySeparator, $dearow['answer']);
                             if ($category != '') {
                                 $dearow['answer'] = "({$category}) {$answer} " . self::_addsgqacode("(" . $dearow['code'] . ")");
                             } else {
                                 $dearow['answer'] = $answer . self::_addsgqacode(" (" . $dearow['code'] . ")");
                             }
                             $question['ANSWER'] .= "\t" . $wrapper['item-start'] . "\t\t" . self::_input_type_image('radio', $dearow['answer']) . "\n\t\t\t" . $dearow['answer'] . "\n" . $wrapper['item-end'];
                         } else {
                             $question['ANSWER'] .= "\t" . $wrapper['item-start'] . "\t\t" . self::_input_type_image('radio', $dearow['answer']) . "\n\t\t\t" . $dearow['answer'] . self::_addsgqacode(" (" . $dearow['code'] . ")") . "\n" . $wrapper['item-end'];
                         }
                         if (isset($_POST['printableexport'])) {
                             $pdf->intopdf(" o " . $dearow['answer']);
                         }
                         ++$rowcounter;
                         if ($rowcounter == $wrapper['maxrows'] && $colcounter < $wrapper['cols']) {
                             if ($colcounter == $wrapper['cols'] - 1) {
                                 $question['ANSWER'] .= $wrapper['col-devide-last'];
                             } else {
                                 $question['ANSWER'] .= $wrapper['col-devide'];
                             }
                             $rowcounter = 0;
                             ++$colcounter;
                         }
                     }
                     if ($deqrow['other'] == 'Y') {
                         if (trim($qidattributes["other_replace_text"][$surveyprintlang]) == '') {
                             $qidattributes["other_replace_text"][$surveyprintlang] = "Other";
                         }
                         //                    $printablesurveyoutput .="\t".$wrapper['item-start']."\t\t".self::_input_type_image('radio' , $clang->gT("Other"))."\n\t\t\t".$clang->gT("Other")."\n\t\t\t<input type='text' size='30' readonly='readonly' />\n".$wrapper['item-end'];
                         $question['ANSWER'] .= $wrapper['item-start-other'] . self::_input_type_image('radio', $clang->gT($qidattributes["other_replace_text"][$surveyprintlang])) . ' ' . $clang->gT($qidattributes["other_replace_text"][$surveyprintlang]) . self::_addsgqacode(" (-oth-)") . "\n\t\t\t" . self::_input_type_image('other') . self::_addsgqacode(" (" . $deqrow['sid'] . "X" . $deqrow['gid'] . "X" . $deqrow['qid'] . "other)") . "\n" . $wrapper['item-end'];
                         if (isset($_POST['printableexport'])) {
                             $pdf->intopdf(" o " . $clang->gT($qidattributes["other_replace_text"][$surveyprintlang]) . ": ________");
                         }
                     }
                     $question['ANSWER'] .= $wrapper['whole-end'];
                     //Let's break the presentation into columns.
                     break;
                     // ==================================================================
                 // ==================================================================
                 case "O":
                     //LIST WITH COMMENT
                     $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please choose *only one* of the following:");
                     if (isset($_POST['printableexport'])) {
                         $pdf->intopdf($clang->gT("Please choose *only one* of the following:"), "U");
                     }
                     $dearesult = Answers::model()->getAllRecords(" qid='{$deqrow['qid']}' AND language='{$surveyprintlang}'", array('sortorder', 'answer'));
                     $question['ANSWER'] = "\t<ul>\n";
                     foreach ($dearesult->readAll() as $dearow) {
                         $question['ANSWER'] .= "\t\t<li>\n\t\t\t" . self::_input_type_image('radio', $dearow['answer']) . "\n\t\t\t" . $dearow['answer'] . self::_addsgqacode(" (" . $dearow['code'] . ")") . "\n\t\t</li>\n";
                         if (isset($_POST['printableexport'])) {
                             $pdf->intopdf($dearow['answer']);
                         }
                     }
                     $question['ANSWER'] .= "\t</ul>\n";
                     $question['ANSWER'] .= "\t<p class=\"comment\">\n\t\t" . $clang->gT("Make a comment on your choice here:") . "\n";
                     if (isset($_POST['printableexport'])) {
                         $pdf->intopdf("Make a comment on your choice here:");
                     }
                     $question['ANSWER'] .= "\t\t" . self::_input_type_image('textarea', $clang->gT("Make a comment on your choice here:"), 50, 8) . self::_addsgqacode(" (" . $deqrow['sid'] . "X" . $deqrow['gid'] . "X" . $deqrow['qid'] . "comment)") . "\n\t</p>\n";
                     for ($i = 0; $i < 9; $i++) {
                         if (isset($_POST['printableexport'])) {
                             $pdf->intopdf("____________________");
                         }
                     }
                     break;
                     // ==================================================================
                 // ==================================================================
                 case "R":
                     //RANKING Type Question
                     $rearesult = Answers::model()->getAllRecords(" qid='{$deqrow['qid']}' AND language='{$surveyprintlang}'", array('sortorder', 'answer'));
                     $rearesult = $rearesult->readAll();
                     $reacount = count($rearesult);
                     $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please number each box in order of preference from 1 to") . " {$reacount}";
                     $question['QUESTION_TYPE_HELP'] .= self::_min_max_answers_help($qidattributes, $surveyprintlang, $surveyid);
                     if (isset($_POST['printableexport'])) {
                         $pdf->intopdf($clang->gT("Please number each box in order of preference from 1 to ") . $reacount, "U");
                     }
                     $question['ANSWER'] = "\n<ul>\n";
                     foreach ($rearesult as $rearow) {
                         $question['ANSWER'] .= "\t<li>\n\t" . self::_input_type_image('rank', '', 4, 1) . "\n\t\t&nbsp;" . $rearow['answer'] . self::_addsgqacode(" (" . $fieldname . $rearow['code'] . ")") . "\n\t</li>\n";
                         if (isset($_POST['printableexport'])) {
                             $pdf->intopdf("__ " . $rearow['answer']);
                         }
                     }
                     $question['ANSWER'] .= "\n</ul>\n";
                     break;
                     // ==================================================================
                 // ==================================================================
                 case "M":
                     //Multiple choice (Quite tricky really!)
                     if (trim($qidattributes['display_columns']) != '') {
                         $dcols = $qidattributes['display_columns'];
                     } else {
                         $dcols = 0;
                     }
                     $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please choose *all* that apply:");
                     if (isset($_POST['printableexport'])) {
                         $pdf->intopdf($clang->gT("Please choose *all* that apply:"), "U");
                     }
                     $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $surveyprintlang, $surveyid);
                     $mearesult = Questions::model()->getAllRecords(" parent_qid='{$deqrow['qid']}' AND language='{$surveyprintlang}' ", array('question_order'));
                     $mearesult = $mearesult->readAll();
                     $meacount = count($mearesult);
                     if ($deqrow['other'] == 'Y') {
                         $meacount++;
                     }
                     $wrapper = setupColumns($dcols, $meacount);
                     $question['ANSWER'] = $wrapper['whole-start'];
                     $rowcounter = 0;
                     $colcounter = 1;
                     foreach ($mearesult as $mearow) {
                         $question['ANSWER'] .= $wrapper['item-start'] . self::_input_type_image('checkbox', $mearow['question']) . "\n\t\t" . $mearow['question'] . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ") ") . $wrapper['item-end'];
                         if (isset($_POST['printableexport'])) {
                             $pdf->intopdf(" o " . $mearow['answer']);
                         }
                         //                        $upto++;
                         ++$rowcounter;
                         if ($rowcounter == $wrapper['maxrows'] && $colcounter < $wrapper['cols']) {
                             if ($colcounter == $wrapper['cols'] - 1) {
                                 $question['ANSWER'] .= $wrapper['col-devide-last'];
                             } else {
                                 $question['ANSWER'] .= $wrapper['col-devide'];
                             }
                             $rowcounter = 0;
                             ++$colcounter;
                         }
                     }
                     if ($deqrow['other'] == "Y") {
                         if (trim($qidattributes['other_replace_text'][$surveyprintlang]) == '') {
                             $qidattributes["other_replace_text"][$surveyprintlang] = "Other";
                         }
                         if (!isset($mearow['answer'])) {
                             $mearow['answer'] = "";
                         }
                         $question['ANSWER'] .= $wrapper['item-start-other'] . self::_input_type_image('checkbox', $mearow['answer']) . $clang->gT($qidattributes["other_replace_text"][$surveyprintlang]) . ":\n\t\t" . self::_input_type_image('other') . self::_addsgqacode(" (" . $fieldname . "other) ") . $wrapper['item-end'];
                         if (isset($_POST['printableexport'])) {
                             $pdf->intopdf(" o " . $clang->gT($qidattributes["other_replace_text"][$surveyprintlang]) . ": ________");
                         }
                     }
                     $question['ANSWER'] .= $wrapper['whole-end'];
                     //                }
                     break;
                     // ==================================================================
                 // ==================================================================
                 case "P":
                     //Multiple choice with comments
                     $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please choose all that apply and provide a comment:");
                     if (isset($_POST['printableexport'])) {
                         $pdf->intopdf($clang->gT("Please choose all that apply and provide a comment:"), "U");
                     }
                     $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $surveyprintlang, $surveyid);
                     $mearesult = Questions::model()->getAllRecords("parent_qid='{$deqrow['qid']}'  AND language='{$surveyprintlang}'", array('question_order'));
                     //                $printablesurveyoutput .="\t\t\t<u>".$clang->gT("Please choose all that apply and provide a comment:")."</u><br />\n";
                     $pdfoutput = array();
                     $j = 0;
                     $longest_string = 0;
                     foreach ($mearesult->readAll() as $mearow) {
                         $longest_string = longestString($mearow['question'], $longest_string);
                         $question['ANSWER'] .= "\t<li><span>\n\t\t" . self::_input_type_image('checkbox', $mearow['question']) . $mearow['question'] . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ") ") . "</span>\n\t\t" . self::_input_type_image('text', 'comment box', 60) . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . "comment) ") . "\n\t</li>\n";
                         $pdfoutput[$j] = array(" o " . $mearow['title'], " __________");
                         $j++;
                     }
                     if ($deqrow['other'] == "Y") {
                         $question['ANSWER'] .= "\t<li class=\"other\">\n\t\t<div class=\"other-replacetext\">" . $clang->gT('Other:') . self::_input_type_image('other', '', 1) . "</div>" . self::_input_type_image('othercomment', 'comment box', 50) . self::_addsgqacode(" (" . $fieldname . "other) ") . "\n\t</li>\n";
                         // lemeur: PDFOUTPUT HAS NOT BEEN IMPLEMENTED for these fields
                         // not sure who did implement this.
                         $pdfoutput[$j][0] = array(" o " . "Other", " __________");
                         $pdfoutput[$j][1] = array(" o " . "OtherComment", " __________");
                         $j++;
                     }
                     $question['ANSWER'] = "\n<ul>\n" . $question['ANSWER'] . "</ul>\n";
                     if (isset($_POST['printableexport'])) {
                         $pdf->tableintopdf($pdfoutput);
                     }
                     break;
                     // ==================================================================
                 // ==================================================================
                 case "Q":
                     //MULTIPLE SHORT TEXT
                     $width = 60;
                     // ==================================================================
                 // ==================================================================
                 case "K":
                     //MULTIPLE NUMERICAL
                     $question['QUESTION_TYPE_HELP'] = "";
                     $width = isset($width) ? $width : 16;
                     if (isset($_POST['printableexport'])) {
                         $pdf->intopdf($clang->gT("Please write your answer(s) here:"), "U");
                     }
                     //                            if (!empty($qidattributes['equals_num_value']))
                     //                            {
                     //                                $question['QUESTION_TYPE_HELP'] .= "* ".sprintf($clang->gT('Total of all entries must equal %d'),$qidattributes['equals_num_value'])."<br />\n";
                     //                            }
                     //                            if (!empty($qidattributes['max_num_value']))
                     //                            {
                     //                                $question['QUESTION_TYPE_HELP'] .= sprintf($clang->gT('Total of all entries must not exceed %d'), $qidattributes['max_num_value'])."<br />\n";
                     //                            }
                     //                            if (!empty($qidattributes['min_num_value']))
                     //                            {
                     //                                $question['QUESTION_TYPE_HELP'] .= sprintf($clang->gT('Total of all entries must be at least %s'),$qidattributes['min_num_value'])."<br />\n";
                     //                            }
                     $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please write your answer(s) here:");
                     $mearesult = Questions::model()->getAllRecords("parent_qid='{$deqrow['qid']}' AND language='{$surveyprintlang}'", array('question_order'));
                     $longest_string = 0;
                     foreach ($mearesult->readAll() as $mearow) {
                         $longest_string = longestString($mearow['question'], $longest_string);
                         if (isset($qidattributes['slider_layout']) && $qidattributes['slider_layout'] == 1) {
                             $mearow['question'] = explode(':', $mearow['question']);
                             $mearow['question'] = $mearow['question'][0];
                         }
                         $question['ANSWER'] .= "\t<li>\n\t\t<span>" . $mearow['question'] . "</span>\n\t\t" . self::_input_type_image('text', $mearow['question'], $width) . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ") ") . "\n\t</li>\n";
                         if (isset($_POST['printableexport'])) {
                             $pdf->intopdf($mearow['question'] . ": ____________________");
                         }
                     }
                     $question['ANSWER'] = "\n<ul>\n" . $question['ANSWER'] . "</ul>\n";
                     break;
                     // ==================================================================
                 // ==================================================================
                 case "S":
                     //SHORT TEXT
                     $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please write your answer here:");
                     $question['ANSWER'] = self::_input_type_image('text', $question['QUESTION_TYPE_HELP'], 50);
                     if (isset($_POST['printableexport'])) {
                         $pdf->intopdf($clang->gT("Please write your answer here:"), "U");
                     }
                     if (isset($_POST['printableexport'])) {
                         $pdf->intopdf("____________________");
                     }
                     break;
                     // ==================================================================
                 // ==================================================================
                 case "T":
                     //LONG TEXT
                     $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please write your answer here:");
                     $question['ANSWER'] = self::_input_type_image('textarea', $question['QUESTION_TYPE_HELP'], '100%', 8);
                     if (isset($_POST['printableexport'])) {
                         $pdf->intopdf($clang->gT("Please write your answer here:"), "U");
                     }
                     for ($i = 0; $i < 9; $i++) {
                         if (isset($_POST['printableexport'])) {
                             $pdf->intopdf("____________________");
                         }
                     }
                     break;
                     // ==================================================================
                 // ==================================================================
                 case "U":
                     //HUGE TEXT
                     $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please write your answer here:");
                     $question['ANSWER'] = self::_input_type_image('textarea', $question['QUESTION_TYPE_HELP'], '100%', 30);
                     if (isset($_POST['printableexport'])) {
                         $pdf->intopdf($clang->gT("Please write your answer here:"), "U");
                     }
                     for ($i = 0; $i < 20; $i++) {
                         if (isset($_POST['printableexport'])) {
                             $pdf->intopdf("____________________");
                         }
                     }
                     break;
                     // ==================================================================
                 // ==================================================================
                 case "N":
                     //NUMERICAL
                     $prefix = "";
                     $suffix = "";
                     if ($qidattributes['prefix'][$surveyprintlang] != "") {
                         $prefix = $qidattributes['prefix'][$surveyprintlang];
                         print_r($prefix);
                     }
                     if ($qidattributes['suffix'][$surveyprintlang] != "") {
                         $suffix = $qidattributes['suffix'][$surveyprintlang];
                     }
                     $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please write your answer here:");
                     $question['ANSWER'] = "<ul>\n\t<li>\n\t\t<span>{$prefix}</span>\n\t\t" . self::_input_type_image('text', $question['QUESTION_TYPE_HELP'], 20) . "\n\t\t<span>{$suffix}</span>\n\t\t</li>\n\t</ul>";
                     if (isset($_POST['printableexport'])) {
                         $pdf->intopdf($clang->gT("Please write your answer here:"), "U");
                     }
                     if (isset($_POST['printableexport'])) {
                         $pdf->intopdf("____________________");
                     }
                     break;
                     // ==================================================================
                 // ==================================================================
                 case "Y":
                     //YES/NO
                     $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please choose *only one* of the following:");
                     $question['ANSWER'] = "\n<ul>\n\t<li>\n\t\t" . self::_input_type_image('radio', $clang->gT('Yes')) . "\n\t\t" . $clang->gT('Yes') . self::_addsgqacode(" (Y)") . "\n\t</li>\n";
                     $question['ANSWER'] .= "\n\t<li>\n\t\t" . self::_input_type_image('radio', $clang->gT('No')) . "\n\t\t" . $clang->gT('No') . self::_addsgqacode(" (N)") . "\n\t</li>\n</ul>\n";
                     if (isset($_POST['printableexport'])) {
                         $pdf->intopdf($clang->gT("Please choose *only one* of the following:"), "U");
                     }
                     if (isset($_POST['printableexport'])) {
                         $pdf->intopdf(" o " . $clang->gT("Yes"));
                     }
                     if (isset($_POST['printableexport'])) {
                         $pdf->intopdf(" o " . $clang->gT("No"));
                     }
                     break;
                     // ==================================================================
                 // ==================================================================
                 case "A":
                     //ARRAY (5 POINT CHOICE)
                     $condition = "parent_qid = '{$deqrow['qid']}'  AND language= '{$surveyprintlang}'";
                     $mearesult = Questions::model()->getAllRecords($condition, array('question_order'));
                     $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please choose the appropriate response for each item:");
                     $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $surveyprintlang, $surveyid);
                     $question['ANSWER'] = "\n        <table>\n            <thead>\n                <tr>\n                    <td>&nbsp;</td>\n                    <th style='font-family:Arial,helvetica,sans-serif;font-weight:normal;'>1&nbsp;&nbsp;&nbsp;&nbsp;" . self::_addsgqacode(" (1)") . "</th>\n                    <th style='font-family:Arial,helvetica,sans-serif;font-weight:normal;'>2&nbsp;&nbsp;&nbsp;&nbsp;" . self::_addsgqacode(" (2)") . "</th>\n                    <th style='font-family:Arial,helvetica,sans-serif;font-weight:normal;'>3&nbsp;&nbsp;&nbsp;&nbsp;" . self::_addsgqacode(" (3)") . "</th>\n                    <th style='font-family:Arial,helvetica,sans-serif;font-weight:normal;'>4&nbsp;&nbsp;&nbsp;&nbsp;" . self::_addsgqacode(" (4)") . "</th>\n                    <th style='font-family:Arial,helvetica,sans-serif;font-weight:normal;'>5" . self::_addsgqacode(" (5)") . "</th>\n                </tr>\n            </thead>\n            <tbody>";
                     if (isset($_POST['printableexport'])) {
                         $pdf->intopdf($clang->gT("Please choose the appropriate response for each item:"), "U");
                     }
                     $pdfoutput = array();
                     $j = 0;
                     $rowclass = 'array1';
                     foreach ($mearesult->readAll() as $mearow) {
                         $question['ANSWER'] .= "\t\t<tr class=\"{$rowclass}\">\n";
                         $rowclass = alternation($rowclass, 'row');
                         //semantic differential question type?
                         if (strpos($mearow['question'], '|')) {
                             $answertext = substr($mearow['question'], 0, strpos($mearow['question'], '|')) . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ")") . " ";
                         } else {
                             $answertext = $mearow['question'] . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ")");
                         }
                         $question['ANSWER'] .= "\t\t\t<th class=\"answertext\">{$answertext}</th>\n";
                         $pdfoutput[$j][0] = $answertext;
                         for ($i = 1; $i <= 5; $i++) {
                             $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', $i) . "</td>\n";
                             $pdfoutput[$j][$i] = " o " . $i;
                         }
                         $answertext .= $mearow['question'];
                         //semantic differential question type?
                         if (strpos($mearow['question'], '|')) {
                             $answertext2 = substr($mearow['question'], strpos($mearow['question'], '|') + 1);
                             $question['ANSWER'] .= "\t\t\t<th class=\"answertextright\">{$answertext2}</td>\n";
                         }
                         $question['ANSWER'] .= "\t\t</tr>\n";
                         $j++;
                     }
                     $question['ANSWER'] .= "\t</tbody>\n</table>\n";
                     if (isset($_POST['printableexport'])) {
                         $pdf->tableintopdf($pdfoutput);
                     }
                     break;
                     // ==================================================================
                 // ==================================================================
                 case "B":
                     //ARRAY (10 POINT CHOICE)
                     $mearesult = Questions::model()->getAllRecords(" parent_qid='{$deqrow['qid']}' AND language='{$surveyprintlang}' ", array('question_order'));
                     $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please choose the appropriate response for each item:");
                     $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $surveyprintlang, $surveyid);
                     $question['ANSWER'] .= "\n<table>\n\t<thead>\n\t\t<tr>\n\t\t\t<td>&nbsp;</td>\n";
                     for ($i = 1; $i <= 10; $i++) {
                         $question['ANSWER'] .= "\t\t\t<th>{$i}" . self::_addsgqacode(" ({$i})") . "</th>\n";
                     }
                     $question['ANSWER'] .= "\t</thead>\n\n\t<tbody>\n";
                     if (isset($_POST['printableexport'])) {
                         $pdf->intopdf($clang->gT("Please choose the appropriate response for each item:"), "U");
                     }
                     $pdfoutput = array();
                     $j = 0;
                     $rowclass = 'array1';
                     foreach ($mearesult->readAll() as $mearow) {
                         $question['ANSWER'] .= "\t\t<tr class=\"{$rowclass}\">\n\t\t\t<th class=\"answertext\">{$mearow['question']}" . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ")") . "</th>\n";
                         $rowclass = alternation($rowclass, 'row');
                         $pdfoutput[$j][0] = $mearow['question'];
                         for ($i = 1; $i <= 10; $i++) {
                             $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', $i) . "</td>\n";
                             $pdfoutput[$j][$i] = " o " . $i;
                         }
                         $question['ANSWER'] .= "\t\t</tr>\n";
                         $j++;
                     }
                     $question['ANSWER'] .= "\t</tbody>\n</table>\n";
                     if (isset($_POST['printableexport'])) {
                         $pdf->tableintopdf($pdfoutput);
                     }
                     break;
                     // ==================================================================
                 // ==================================================================
                 case "C":
                     //ARRAY (YES/UNCERTAIN/NO)
                     $mearesult = Questions::model()->getAllRecords(" parent_qid='{$deqrow['qid']}'  AND language='{$surveyprintlang}' ", array('question_order'));
                     $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please choose the appropriate response for each item:");
                     $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $surveyprintlang, $surveyid);
                     $question['ANSWER'] = '
     <table>
         <thead>
             <tr>
                 <td>&nbsp;</td>
                 <th>' . $clang->gT("Yes") . self::_addsgqacode(" (Y)") . '</th>
                 <th>' . $clang->gT("Uncertain") . self::_addsgqacode(" (U)") . '</th>
                 <th>' . $clang->gT("No") . self::_addsgqacode(" (N)") . '</th>
             </tr>
         </thead>
         <tbody>
     ';
                     if (isset($_POST['printableexport'])) {
                         $pdf->intopdf($clang->gT("Please choose the appropriate response for each item:"), "U");
                     }
                     $pdfoutput = array();
                     $j = 0;
                     $rowclass = 'array1';
                     foreach ($mearesult->readAll() as $mearow) {
                         $question['ANSWER'] .= "\t\t<tr class=\"{$rowclass}\">\n";
                         $question['ANSWER'] .= "\t\t\t<th class=\"answertext\">{$mearow['question']}" . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ")") . "</th>\n";
                         $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', $clang->gT("Yes")) . "</td>\n";
                         $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', $clang->gT("Uncertain")) . "</td>\n";
                         $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', $clang->gT("No")) . "</td>\n";
                         $question['ANSWER'] .= "\t\t</tr>\n";
                         $pdfoutput[$j] = array($mearow['question'], " o " . $clang->gT("Yes"), " o " . $clang->gT("Uncertain"), " o " . $clang->gT("No"));
                         $j++;
                         $rowclass = alternation($rowclass, 'row');
                     }
                     $question['ANSWER'] .= "\t</tbody>\n</table>\n";
                     if (isset($_POST['printableexport'])) {
                         $pdf->tableintopdf($pdfoutput);
                     }
                     break;
                 case "E":
                     //ARRAY (Increase/Same/Decrease)
                     $mearesult = Questions::model()->getAllRecords(" parent_qid='{$deqrow['qid']}'  AND language='{$surveyprintlang}' ", array('question_order'));
                     $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please choose the appropriate response for each item:");
                     $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $surveyprintlang, $surveyid);
                     $question['ANSWER'] = '
     <table>
         <thead>
             <tr>
                 <td>&nbsp;</td>
                 <th>' . $clang->gT("Increase") . self::_addsgqacode(" (I)") . '</th>
                 <th>' . $clang->gT("Same") . self::_addsgqacode(" (S)") . '</th>
                 <th>' . $clang->gT("Decrease") . self::_addsgqacode(" (D)") . '</th>
             </tr>
         </thead>
         <tbody>
     ';
                     if (isset($_POST['printableexport'])) {
                         $pdf->intopdf($clang->gT("Please choose the appropriate response for each item:"), "U");
                     }
                     $pdfoutput = array();
                     $j = 0;
                     $rowclass = 'array1';
                     foreach ($mearesult->readAll() as $mearow) {
                         $question['ANSWER'] .= "\t\t<tr class=\"{$rowclass}\">\n";
                         $question['ANSWER'] .= "\t\t\t<th class=\"answertext\">{$mearow['question']}" . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ")") . "</th>\n";
                         $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', $clang->gT("Increase")) . "</td>\n";
                         $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', $clang->gT("Same")) . "</td>\n";
                         $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', $clang->gT("Decrease")) . "</td>\n";
                         $question['ANSWER'] .= "\t\t</tr>\n";
                         $pdfoutput[$j] = array($mearow['question'] . ":", " o " . $clang->gT("Increase"), " o " . $clang->gT("Same"), " o " . $clang->gT("Decrease"));
                         $j++;
                         $rowclass = alternation($rowclass, 'row');
                     }
                     $question['ANSWER'] .= "\t</tbody>\n</table>\n";
                     if (isset($_POST['printableexport'])) {
                         $pdf->tableintopdf($pdfoutput);
                     }
                     break;
                     // ==================================================================
                 // ==================================================================
                 case ":":
                     //ARRAY (Multi Flexible) (Numbers)
                     $headstyle = "style='padding-left: 20px; padding-right: 7px'";
                     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) {
                         $checkboxlayout = true;
                     } else {
                         $checkboxlayout = false;
                     }
                     $mearesult = Questions::model()->getAllRecords(" parent_qid='{$deqrow['qid']}' and scale_id=0 AND language='{$surveyprintlang}' ", array('question_order'));
                     //                            if ($checkboxlayout === false)
                     //                            {
                     //                                if ($stepvalue > 1)
                     //                                {
                     //                                    $question['QUESTION_TYPE_HELP'] = sprintf($clang->gT("Please write a multiple of %d between (%s) and (%s) for each item:"),$stepvalue,$minvalue,$maxvalue);
                     //                                    if(isset($_POST['printableexport'])){$pdf->intopdf(sprintf($clang->gT("Please write a multiple of %d between (%s) and (%s) for each item:"),$stepvalue,$minvalue,$maxvalue),"U");}
                     //                                }
                     //                                else {
                     //                                    $question['QUESTION_TYPE_HELP'] = sprintf($clang->gT("Please enter a number between (%s) and (%s) for each item:"),$minvalue,$maxvalue);
                     //                                    if(isset($_POST['printableexport'])){$pdf->intopdf(sprintf($clang->gT("Please enter a number between (%s) and (%s) for each item:"),$minvalue,$maxvalue),"U");}
                     //                                }
                     //                            }
                     //                            else
                     //                            {
                     //                                $question['QUESTION_TYPE_HELP'] .= $clang->gT("Check any that apply").":";
                     //                                if(isset($_POST['printableexport'])){$pdf->intopdf($clang->gT("Check any that apply"),"U");}
                     //                            }
                     $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $surveyprintlang, $surveyid);
                     $question['ANSWER'] .= "\n<table>\n\t<thead>\n\t\t<tr>\n\t\t\t<td>&nbsp;</td>\n";
                     $fresult = Questions::model()->getAllRecords(" parent_qid='{$deqrow['qid']}' and scale_id=1 AND language='{$surveyprintlang}' ", array('question_order'));
                     $fresult = $fresult->readAll();
                     $fcount = count($fresult);
                     $fwidth = "120";
                     $i = 0;
                     $pdfoutput = array();
                     $pdfoutput[0][0] = ' ';
                     //array to temporary store X axis question codes
                     $xaxisarray = array();
                     foreach ($fresult as $frow) {
                         $question['ANSWER'] .= "\t\t\t<th>{$frow['question']}</th>\n";
                         $i++;
                         $pdfoutput[0][$i] = $frow['question'];
                         //add current question code
                         $xaxisarray[$i] = $frow['title'];
                     }
                     $question['ANSWER'] .= "\t\t</tr>\n\t</thead>\n\n\t<tbody>\n";
                     $a = 1;
                     //Counter for pdfoutput
                     $rowclass = 'array1';
                     $result = $mearesult->readAll();
                     foreach ($result as $frow) {
                         $question['ANSWER'] .= "\t<tr class=\"{$rowclass}\">\n";
                         $rowclass = alternation($rowclass, 'row');
                         $answertext = $frow['question'];
                         if (strpos($answertext, '|')) {
                             $answertext = substr($answertext, 0, strpos($answertext, '|'));
                         }
                         $question['ANSWER'] .= "\t\t\t\t\t<th class=\"answertext\">{$answertext}</th>\n";
                         //$printablesurveyoutput .="\t\t\t\t\t<td>";
                         $pdfoutput[$a][0] = $answertext;
                         for ($i = 1; $i <= $fcount; $i++) {
                             $question['ANSWER'] .= "\t\t\t<td>\n";
                             if ($checkboxlayout === false) {
                                 $question['ANSWER'] .= "\t\t\t\t" . self::_input_type_image('text', '', 4) . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . "_" . $xaxisarray[$i] . ") ") . "\n";
                                 $pdfoutput[$a][$i] = "__";
                             } else {
                                 $question['ANSWER'] .= "\t\t\t\t" . self::_input_type_image('checkbox') . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . "_" . $xaxisarray[$i] . ") ") . "\n";
                                 $pdfoutput[$a][$i] = "o";
                             }
                             $question['ANSWER'] .= "\t\t\t</td>\n";
                         }
                         $answertext = $mearow['question'];
                         if (strpos($answertext, '|')) {
                             $answertext = substr($answertext, strpos($answertext, '|') + 1);
                             $question['ANSWER'] .= "\t\t\t<th class=\"answertextright\">{$answertext}</th>\n";
                             //$pdfoutput[$a][$i]=$answertext;
                         }
                         $question['ANSWER'] .= "\t\t</tr>\n";
                         $a++;
                     }
                     $question['ANSWER'] .= "\t</tbody>\n</table>\n";
                     if (isset($_POST['printableexport'])) {
                         $pdf->tableintopdf($pdfoutput);
                     }
                     break;
                     // ==================================================================
                 // ==================================================================
                 case ";":
                     //ARRAY (Multi Flexible) (text)
                     $headstyle = "style='padding-left: 20px; padding-right: 7px'";
                     $mearesult = Questions::model()->getAllRecords(" parent_qid='{$deqrow['qid']}' AND scale_id=0 AND language='{$surveyprintlang}' ", array('question_order'));
                     $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $surveyprintlang, $surveyid);
                     $question['ANSWER'] .= "\n<table>\n\t<thead>\n\t\t<tr>\n\t\t\t<td>&nbsp;</td>\n";
                     $fresult = Questions::model()->getAllRecords(" parent_qid='{$deqrow['qid']}'  AND scale_id=1 AND language='{$surveyprintlang}' ", array('question_order'));
                     $fresult = $fresult->readAll();
                     $fcount = count($fresult);
                     $fwidth = "120";
                     $i = 0;
                     $pdfoutput = array();
                     $pdfoutput[0][0] = '';
                     //array to temporary store X axis question codes
                     $xaxisarray = array();
                     foreach ($fresult as $frow) {
                         $question['ANSWER'] .= "\t\t\t<th>{$frow['question']}</th>\n";
                         $i++;
                         $pdfoutput[0][$i] = $frow['question'];
                         //add current question code
                         $xaxisarray[$i] = $frow['title'];
                     }
                     $question['ANSWER'] .= "\t\t</tr>\n\t</thead>\n\n<tbody>\n";
                     $a = 1;
                     $rowclass = 'array1';
                     foreach ($mearesult->readAll() as $mearow) {
                         $question['ANSWER'] .= "\t\t<tr class=\"{$rowclass}\">\n";
                         $rowclass = alternation($rowclass, 'row');
                         $answertext = $mearow['question'];
                         if (strpos($answertext, '|')) {
                             $answertext = substr($answertext, 0, strpos($answertext, '|'));
                         }
                         $question['ANSWER'] .= "\t\t\t<th class=\"answertext\">{$answertext}</th>\n";
                         $pdfoutput[$a][0] = $answertext;
                         //$printablesurveyoutput .="\t\t\t\t\t<td>";
                         for ($i = 1; $i <= $fcount; $i++) {
                             $question['ANSWER'] .= "\t\t\t<td>\n";
                             $question['ANSWER'] .= "\t\t\t\t" . self::_input_type_image('text', '', 23) . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . "_" . $xaxisarray[$i] . ") ") . "\n";
                             $question['ANSWER'] .= "\t\t\t</td>\n";
                             $pdfoutput[$a][$i] = "_____________";
                         }
                         $answertext = $mearow['question'];
                         if (strpos($answertext, '|')) {
                             $answertext = substr($answertext, strpos($answertext, '|') + 1);
                             $question['ANSWER'] .= "\t\t\t\t<th class=\"answertextright\">{$answertext}</th>\n";
                         }
                         $question['ANSWER'] .= "\t\t</tr>\n";
                         $a++;
                     }
                     $question['ANSWER'] .= "\t</tbody>\n</table>\n";
                     if (isset($_POST['printableexport'])) {
                         $pdf->tableintopdf($pdfoutput);
                     }
                     break;
                     // ==================================================================
                 // ==================================================================
                 case "F":
                     //ARRAY (Flexible Labels)
                     $mearesult = Questions::model()->getAllRecords(" parent_qid='{$deqrow['qid']}'  AND language='{$surveyprintlang}' ", array('question_order'));
                     $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please choose the appropriate response for each item:");
                     $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $surveyprintlang, $surveyid);
                     $fresult = Answers::model()->getAllRecords(" scale_id=0 AND qid='{$deqrow['qid']}'  AND language='{$surveyprintlang}'", array('sortorder', 'code'));
                     $fresult = $fresult->readAll();
                     $fcount = count($fresult);
                     $fwidth = "120";
                     $i = 1;
                     $pdfoutput = array();
                     $pdfoutput[0][0] = '';
                     if (isset($_POST['printableexport'])) {
                         $pdf->intopdf($clang->gT("Please choose the appropriate response for each item:"), "U");
                     }
                     $column_headings = array();
                     foreach ($fresult as $frow) {
                         $column_headings[] = $frow['answer'] . self::_addsgqacode(" (" . $frow['code'] . ")");
                     }
                     if (trim($qidattributes['answer_width']) != '') {
                         $iAnswerWidth = 100 - $qidattributes['answer_width'];
                     } else {
                         $iAnswerWidth = 80;
                     }
                     if (count($column_headings) > 0) {
                         $col_width = round($iAnswerWidth / count($column_headings));
                     } else {
                         $heading = '';
                     }
                     $question['ANSWER'] .= "\n<table>\n\t<thead>\n\t\t<tr>\n";
                     $question['ANSWER'] .= "\t\t\t<td>&nbsp;</td>\n";
                     foreach ($column_headings as $heading) {
                         $question['ANSWER'] .= "\t\t\t<th style=\"width:{$col_width}%;\">{$heading}</th>\n";
                     }
                     $pdfoutput[0][$i] = $heading;
                     $i++;
                     $question['ANSWER'] .= "\t\t</tr>\n\t</thead>\n\n\t<tbody>\n";
                     $counter = 1;
                     $rowclass = 'array1';
                     foreach ($mearesult->readAll() as $mearow) {
                         $question['ANSWER'] .= "\t\t<tr class=\"{$rowclass}\">\n";
                         $rowclass = alternation($rowclass, 'row');
                         if (trim($answertext) == '') {
                             $answertext = '&nbsp;';
                         }
                         //semantic differential question type?
                         if (strpos($mearow['question'], '|')) {
                             $answertext = substr($mearow['question'], 0, strpos($mearow['question'], '|')) . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ")") . " ";
                         } else {
                             $answertext = $mearow['question'] . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ")");
                         }
                         if (trim($qidattributes['answer_width']) != '') {
                             $sInsertStyle = ' style="width:' . $qidattributes['answer_width'] . '%" ';
                         } else {
                             $sInsertStyle = '';
                         }
                         $question['ANSWER'] .= "\t\t\t<th {$sInsertStyle} class=\"answertext\">{$answertext}</th>\n";
                         $pdfoutput[$counter][0] = $answertext;
                         for ($i = 1; $i <= $fcount; $i++) {
                             $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio') . "</td>\n";
                             $pdfoutput[$counter][$i] = "o";
                         }
                         $counter++;
                         $answertext = $mearow['question'];
                         //semantic differential question type?
                         if (strpos($mearow['question'], '|')) {
                             $answertext2 = substr($mearow['question'], strpos($mearow['question'], '|') + 1);
                             $question['ANSWER'] .= "\t\t\t<th class=\"answertextright\">{$answertext2}</th>\n";
                         }
                         $question['ANSWER'] .= "\t\t</tr>\n";
                     }
                     $question['ANSWER'] .= "\t</tbody>\n</table>\n";
                     if (isset($_POST['printableexport'])) {
                         $pdf->tableintopdf($pdfoutput);
                     }
                     break;
                     // ==================================================================
                 // ==================================================================
                 case "1":
                     //ARRAY (Flexible Labels) multi scale
                     $leftheader = $qidattributes['dualscale_headerA'][$surveyprintlang];
                     $rightheader = $qidattributes['dualscale_headerB'][$surveyprintlang];
                     $headstyle = 'style="padding-left: 20px; padding-right: 7px"';
                     //$meaquery = "SELECT * FROM {{questions}} WHERE parent_qid={$deqrow['qid']}  AND language='{$surveyprintlang}' ORDER BY question_order";
                     //$mearesult = Yii::app()->db->createCommand($meaquery)->query();
                     $mearesult = Questions::model()->getAllRecords(" parent_qid={$deqrow['qid']}  AND language='{$surveyprintlang}' ", array('question_order'));
                     $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please choose the appropriate response for each item:");
                     $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $surveyprintlang, $surveyid);
                     if (isset($_POST['printableexport'])) {
                         $pdf->intopdf($clang->gT("Please choose the appropriate response for each item:"), "U");
                     }
                     $question['ANSWER'] .= "\n<table>\n\t<thead>\n";
                     $condition = "qid= '{$deqrow['qid']}'  AND language= '{$surveyprintlang}' AND scale_id=0";
                     $fresult = Answers::model()->getAllRecords($condition, array('sortorder', 'code'));
                     $fresult = $fresult->readAll();
                     $fcount = count($fresult);
                     $fwidth = "120";
                     $l1 = 0;
                     $printablesurveyoutput2 = "\t\t\t<td>&nbsp;</td>\n";
                     $myheader2 = '';
                     $pdfoutput = array();
                     $pdfoutput[0][0] = '';
                     foreach ($fresult as $frow) {
                         $printablesurveyoutput2 .= "\t\t\t<th>{$frow['answer']}" . self::_addsgqacode(" (" . $frow['code'] . ")") . "</th>\n";
                         $myheader2 .= "<td></td>";
                         $pdfoutput[0][$l1 + 1] = $frow['answer'];
                         $l1++;
                     }
                     // second scale
                     $printablesurveyoutput2 .= "\t\t\t<td>&nbsp;</td>\n";
                     //$fquery1 = "SELECT * FROM {{answers}} WHERE qid='{$deqrow['qid']}'  AND language='{$surveyprintlang}' AND scale_id=1 ORDER BY sortorder, code";
                     // $fresult1 = Yii::app()->db->createCommand($fquery1)->query();
                     $fresult1 = Answers::model()->getAllRecords(" qid='{$deqrow['qid']}'  AND language='{$surveyprintlang}' AND scale_id=1 ", array('sortorder', 'code'));
                     $fresult1 = $fresult1->readAll();
                     $fcount1 = count($fresult1);
                     $fwidth = "120";
                     $l2 = 0;
                     //array to temporary store second scale question codes
                     $scale2array = array();
                     foreach ($fresult1 as $frow1) {
                         $printablesurveyoutput2 .= "\t\t\t<th>{$frow1['answer']}" . self::_addsgqacode(" (" . $frow1['code'] . ")") . "</th>\n";
                         $pdfoutput[1][$l2] = $frow['answer'];
                         //add current question code
                         $scale2array[$l2] = $frow1['code'];
                         $l2++;
                     }
                     // build header if needed
                     if ($leftheader != '' || $rightheader != '') {
                         $myheader = "\t\t\t<td>&nbsp;</td>";
                         $myheader .= "\t\t\t<th colspan=\"" . $l1 . "\">{$leftheader}</th>\n";
                         if ($rightheader != '') {
                             // $myheader .= "\t\t\t\t\t" .$myheader2;
                             $myheader .= "\t\t\t<td>&nbsp;</td>";
                             $myheader .= "\t\t\t<th colspan=\"" . $l2 . "\">{$rightheader}</td>\n";
                         }
                         $myheader .= "\t\t\t\t</tr>\n";
                     } else {
                         $myheader = '';
                     }
                     $question['ANSWER'] .= $myheader . "\t\t</tr>\n\n\t\t<tr>\n";
                     $question['ANSWER'] .= $printablesurveyoutput2;
                     $question['ANSWER'] .= "\t\t</tr>\n\t</thead>\n\n\t<tbody>\n";
                     $rowclass = 'array1';
                     //counter for each subquestion
                     $sqcounter = 0;
                     foreach ($mearesult->readAll() as $mearow) {
                         $question['ANSWER'] .= "\t\t<tr class=\"{$rowclass}\">\n";
                         $rowclass = alternation($rowclass, 'row');
                         $answertext = $mearow['question'] . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . "#0) / (" . $fieldname . $mearow['title'] . "#1)");
                         if (strpos($answertext, '|')) {
                             $answertext = substr($answertext, 0, strpos($answertext, '|'));
                         }
                         $question['ANSWER'] .= "\t\t\t<th class=\"answertext\">{$answertext}</th>\n";
                         for ($i = 1; $i <= $fcount; $i++) {
                             $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio') . "</td>\n";
                         }
                         $question['ANSWER'] .= "\t\t\t<td>&nbsp;</td>\n";
                         for ($i = 1; $i <= $fcount1; $i++) {
                             $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio') . "</td>\n";
                         }
                         $answertext = $mearow['question'];
                         if (strpos($answertext, '|')) {
                             $answertext = substr($answertext, strpos($answertext, '|') + 1);
                             $question['ANSWER'] .= "\t\t\t<th class=\"answertextright\">{$answertext}</th>\n";
                         }
                         $question['ANSWER'] .= "\t\t</tr>\n";
                         //increase subquestion counter
                         $sqcounter++;
                     }
                     $question['ANSWER'] .= "\t</tbody>\n</table>\n";
                     if (isset($_POST['printableexport'])) {
                         $pdf->tableintopdf($pdfoutput);
                     }
                     break;
                     // ==================================================================
                 // ==================================================================
                 case "H":
                     //ARRAY (Flexible Labels) by Column
                     //$headstyle="style='border-left-style: solid; border-left-width: 1px; border-left-color: #AAAAAA'";
                     $headstyle = "style='padding-left: 20px; padding-right: 7px'";
                     $condition = "parent_qid= '{$deqrow['qid']}'  AND language= '{$surveyprintlang}'";
                     $fresult = Questions::model()->getAllRecords($condition, array('question_order', 'title'));
                     $fresult = $fresult->readAll();
                     $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please choose the appropriate response for each item:");
                     if (isset($_POST['printableexport'])) {
                         $pdf->intopdf($clang->gT("Please choose the appropriate response for each item:"), "U");
                     }
                     $question['ANSWER'] .= "\n<table>\n\t<thead>\n\t\t<tr>\n\t\t\t<td>&nbsp;</td>\n";
                     $mearesult = Answers::model()->getAllRecords(" qid='{$deqrow['qid']}' AND scale_id=0 AND language='{$surveyprintlang}' ", array('sortorder', 'code'));
                     $fcount = count($fresult);
                     $fwidth = "120";
                     $i = 0;
                     $pdfoutput = array();
                     $pdfoutput[0][0] = '';
                     foreach ($fresult as $frow) {
                         $question['ANSWER'] .= "\t\t\t<th>{$frow['question']}" . self::_addsgqacode(" (" . $fieldname . $frow['title'] . ")") . "</th>\n";
                         $i++;
                         $pdfoutput[0][$i] = $frow['question'];
                     }
                     $question['ANSWER'] .= "\t\t</tr>\n\t</thead>\n\n\t<tbody>\n";
                     $a = 1;
                     $rowclass = 'array1';
                     foreach ($mearesult->readAll() as $mearow) {
                         //$_POST['type']=$type;
                         $question['ANSWER'] .= "\t\t<tr class=\"{$rowclass}\">\n";
                         $rowclass = alternation($rowclass, 'row');
                         $question['ANSWER'] .= "\t\t\t<th class=\"answertext\">{$mearow['answer']}" . self::_addsgqacode(" (" . $mearow['code'] . ")") . "</th>\n";
                         //$printablesurveyoutput .="\t\t\t\t\t<td>";
                         $pdfoutput[$a][0] = $mearow['answer'];
                         for ($i = 1; $i <= $fcount; $i++) {
                             $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio') . "</td>\n";
                             $pdfoutput[$a][$i] = "o";
                         }
                         //$printablesurveyoutput .="\t\t\t\t\t</tr></table></td>\n";
                         $question['ANSWER'] .= "\t\t</tr>\n";
                         $a++;
                     }
                     $question['ANSWER'] .= "\t</tbody>\n</table>\n";
                     if (isset($_POST['printableexport'])) {
                         $pdf->tableintopdf($pdfoutput);
                     }
                     break;
                 case "|":
                     // File Upload
                     $question['QUESTION_TYPE_HELP'] .= "Kindly attach the aforementioned documents along with the survey";
                     break;
                     // === END SWITCH ===================================================
             }
             if (isset($_POST['printableexport'])) {
                 $pdf->ln(5);
             }
             $question['QUESTION_TYPE_HELP'] = self::_star_replace($question['QUESTION_TYPE_HELP']);
             $group['QUESTIONS'] .= self::_populate_template('question', $question);
         }
         if ($bGroupHasVisibleQuestions) {
             $survey_output['GROUPS'] .= self::_populate_template('group', $group);
         }
     }
     $survey_output['THEREAREXQUESTIONS'] = str_replace('{NUMBEROFQUESTIONS}', $total_questions, $clang->gT('There are {NUMBEROFQUESTIONS} questions in this survey'));
     // START recursive tag stripping.
     // PHP 5.1.0 introduced the count parameter for preg_replace() and thus allows this procedure to run with only one regular expression.
     // Previous version of PHP needs two regular expressions to do the same thing and thus will run a bit slower.
     $server_is_newer = version_compare(PHP_VERSION, '5.1.0', '>');
     $rounds = 0;
     while ($rounds < 1) {
         $replace_count = 0;
         if ($server_is_newer) {
             $survey_output['GROUPS'] = preg_replace(array('/<td>(?:&nbsp;|&#160;| )?<\\/td>/isU', '/<th[^>]*>(?:&nbsp;|&#160;| )?<\\/th>/isU', '/<([^ >]+)[^>]*>(?:&nbsp;|&#160;|\\r\\n|\\n\\r|\\n|\\r|\\t| )*<\\/\\1>/isU'), array('[[EMPTY-TABLE-CELL]]', '[[EMPTY-TABLE-CELL-HEADER]]', ''), $survey_output['GROUPS'], -1, $replace_count);
         } else {
             $survey_output['GROUPS'] = preg_replace(array('/<td>(?:&nbsp;|&#160;| )?<\\/td>/isU', '/<th[^>]*>(?:&nbsp;|&#160;| )?<\\/th>/isU', '/<([^ >]+)[^>]*>(?:&nbsp;|&#160;|\\r\\n|\\n\\r|\\n|\\r|\\t| )*<\\/\\1>/isU'), array('[[EMPTY-TABLE-CELL]]', '[[EMPTY-TABLE-CELL-HEADER]]', ''), $survey_output['GROUPS']);
             $replace_count = preg_match('/<([^ >]+)[^>]*>(?:&nbsp;|&#160;|\\r\\n|\\n\\r|\\n|\\r|\\t| )*<\\/\\1>/isU', $survey_output['GROUPS']);
         }
         if ($replace_count == 0) {
             ++$rounds;
             $survey_output['GROUPS'] = preg_replace(array('/\\[\\[EMPTY-TABLE-CELL\\]\\]/', '/\\[\\[EMPTY-TABLE-CELL-HEADER\\]\\]/', '/\\n(?:\\t*\\n)+/'), array('<td>&nbsp;</td>', '<th>&nbsp;</th>', "\n"), $survey_output['GROUPS']);
         }
     }
     $survey_output['GROUPS'] = preg_replace('/(<div[^>]*>){NOTEMPTY}(<\\/div>)/', '\\1&nbsp;\\2', $survey_output['GROUPS']);
     // END recursive empty tag stripping.
     if (isset($_POST['printableexport'])) {
         if ($surveystartdate != '') {
             if (isset($_POST['printableexport'])) {
                 $pdf->intopdf(sprintf($clang->gT("Please submit by %s"), $surveyexpirydate));
             }
         }
         if (!empty($surveyfaxto) && $surveyfaxto != '000-00000000') {
             if (isset($_POST['printableexport'])) {
                 $pdf->intopdf(sprintf($clang->gT("Please fax your completed survey to: %s"), $surveyfaxto), 'B');
             }
         }
         $pdf->titleintopdf($clang->gT("Submit Your Survey."), $clang->gT("Thank you for completing this survey."));
         $pdf->write_out($clang->gT($surveyname) . " " . $surveyid . ".pdf");
     } else {
         echo self::_populate_template('survey', $survey_output);
     }
 }