コード例 #1
0
 function actionAction($surveyid, $language = null)
 {
     $sLanguage = $language;
     ob_start(function ($buffer, $phase) {
         App()->getClientScript()->render($buffer);
         App()->getClientScript()->reset();
         return $buffer;
     });
     ob_implicit_flush(false);
     $iSurveyID = (int) $surveyid;
     //$postlang = returnglobal('lang');
     Yii::import('application.libraries.admin.progressbar', true);
     Yii::app()->loadHelper("admin/statistics");
     Yii::app()->loadHelper('database');
     Yii::app()->loadHelper('surveytranslator');
     App()->getClientScript()->registerPackage('jqueryui');
     App()->getClientScript()->registerPackage('jquery-touch-punch');
     App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('generalscripts') . "survey_runtime.js");
     $data = array();
     if (!isset($iSurveyID)) {
         $iSurveyID = returnGlobal('sid');
     } else {
         $iSurveyID = (int) $iSurveyID;
     }
     if (!$iSurveyID) {
         //This next line ensures that the $iSurveyID value is never anything but a number.
         safeDie('You have to provide a valid survey ID.');
     }
     if ($iSurveyID) {
         $actresult = Survey::model()->findAll('sid = :sid AND active = :active', array(':sid' => $iSurveyID, ':active' => 'Y'));
         //Checked
         if (count($actresult) == 0) {
             safeDie('You have to provide a valid survey ID.');
         } else {
             $surveyinfo = getSurveyInfo($iSurveyID);
             // CHANGE JSW_NZ - let's get the survey title for display
             $thisSurveyTitle = $surveyinfo["name"];
             // CHANGE JSW_NZ - let's get css from individual template.css - so define path
             $thisSurveyCssPath = getTemplateURL($surveyinfo["template"]);
             if ($surveyinfo['publicstatistics'] != 'Y') {
                 safeDie('The public statistics for this survey are deactivated.');
             }
             //check if graphs should be shown for this survey
             if ($surveyinfo['publicgraphs'] == 'Y') {
                 $publicgraphs = 1;
             } else {
                 $publicgraphs = 0;
             }
         }
     }
     //we collect all the output within this variable
     $statisticsoutput = '';
     //for creating graphs we need some more scripts which are included here
     //True -> include
     //False -> forget about charts
     if (isset($publicgraphs) && $publicgraphs == 1) {
         require_once APPPATH . 'third_party/pchart/pchart/pChart.class';
         require_once APPPATH . 'third_party/pchart/pchart/pData.class';
         require_once APPPATH . 'third_party/pchart/pchart/pCache.class';
         $MyCache = new pCache(Yii::app()->getConfig("tempdir") . DIRECTORY_SEPARATOR);
         //$currentuser is created as prefix for pchart files
         if (isset($_SERVER['REDIRECT_REMOTE_USER'])) {
             $currentuser = $_SERVER['REDIRECT_REMOTE_USER'];
         } else {
             if (session_id()) {
                 $currentuser = substr(session_id(), 0, 15);
             } else {
                 $currentuser = "******";
             }
         }
     }
     // Set language for questions and labels to base language of this survey
     if ($sLanguage == null || !in_array($sLanguage, Survey::model()->findByPk($iSurveyID)->getAllLanguages())) {
         $sLanguage = Survey::model()->findByPk($iSurveyID)->language;
     } else {
         $sLanguage = sanitize_languagecode($sLanguage);
     }
     //set survey language for translations
     SetSurveyLanguage($iSurveyID, $sLanguage);
     //Create header
     sendCacheHeaders();
     $condition = false;
     $sitename = Yii::app()->getConfig("sitename");
     $data['surveylanguage'] = $sLanguage;
     $data['sitename'] = $sitename;
     $data['condition'] = $condition;
     $data['thisSurveyCssPath'] = $thisSurveyCssPath;
     /*
      * only show questions where question attribute "public_statistics" is set to "1"
      */
     $query = "SELECT q.* , group_name, group_order FROM {{questions}} q, {{groups}} g, {{question_attributes}} qa\n                    WHERE g.gid = q.gid AND g.language = :lang1 AND q.language = :lang2 AND q.sid = :surveyid AND q.qid = qa.qid AND q.parent_qid = 0 AND qa.attribute = 'public_statistics'";
     $databasetype = Yii::app()->db->getDriverName();
     if ($databasetype == 'mssql' || $databasetype == "sqlsrv" || $databasetype == "dblib") {
         $query .= " AND CAST(CAST(qa.value as varchar) as int)='1'\n";
     } else {
         $query .= " AND qa.value='1'\n";
     }
     //execute query
     $result = Yii::app()->db->createCommand($query)->bindParam(":lang1", $sLanguage, PDO::PARAM_STR)->bindParam(":lang2", $sLanguage, PDO::PARAM_STR)->bindParam(":surveyid", $iSurveyID, PDO::PARAM_INT)->queryAll();
     //store all the data in $rows
     $rows = $result;
     //SORT IN NATURAL ORDER!
     usort($rows, 'groupOrderThenQuestionOrder');
     //put the question information into the filter array
     foreach ($rows as $row) {
         //store some column names in $filters array
         $filters[] = array($row['qid'], $row['gid'], $row['type'], $row['title'], $row['group_name'], flattenText($row['question']));
     }
     //number of records for this survey
     $totalrecords = 0;
     //count number of answers
     $query = "SELECT count(*) FROM {{survey_" . intval($iSurveyID) . "}}";
     //if incompleted answers should be filtert submitdate has to be not null
     //this setting is taken from config-defaults.php
     if (Yii::app()->getConfig("filterout_incomplete_answers") == true) {
         $query .= " WHERE {{survey_" . intval($iSurveyID) . "}}.submitdate is not null";
     }
     $result = Yii::app()->db->createCommand($query)->queryAll();
     //$totalrecords = total number of answers
     foreach ($result as $row) {
         $totalrecords = reset($row);
     }
     //this is the array which we need later...
     $summary = array();
     //...while this is the array from copy/paste which we don't want to replace because this is a nasty source of error
     $allfields = array();
     //---------- CREATE SGQA OF ALL QUESTIONS WHICH USE "PUBLIC_STATISTICS" ----------
     /*
              * let's go through the filter array which contains
              *     ['qid'],
              ['gid'],
              ['type'],
              ['title'],
              ['group_name'],
              ['question'];
     */
     $currentgroup = '';
     // use to check if there are any question with public statistics
     if (isset($filters)) {
         foreach ($filters as $flt) {
             //SGQ identifier
             $myfield = "{$iSurveyID}X{$flt[1]}X{$flt[0]}";
             //let's switch through the question type for each question
             switch ($flt[2]) {
                 case "K":
                     // Multiple Numerical
                 // Multiple Numerical
                 case "Q":
                     // Multiple Short Text
                     //get answers
                     $query = "SELECT title as code, question as answer FROM {{questions}} WHERE parent_qid=:flt_0 AND language = :lang ORDER BY question_order";
                     $result = Yii::app()->db->createCommand($query)->bindParam(":flt_0", $flt[0], PDO::PARAM_INT)->bindParam(":lang", $sLanguage, PDO::PARAM_STR)->queryAll();
                     //go through all the (multiple) answers
                     foreach ($result as $row) {
                         $myfield2 = $flt[2] . $myfield . reset($row);
                         $allfields[] = $myfield2;
                     }
                     break;
                 case "A":
                     // ARRAY OF 5 POINT CHOICE QUESTIONS
                 // ARRAY OF 5 POINT CHOICE QUESTIONS
                 case "B":
                     // ARRAY OF 10 POINT CHOICE QUESTIONS
                 // ARRAY OF 10 POINT CHOICE QUESTIONS
                 case "C":
                     // ARRAY OF YES\No\gT("Uncertain") QUESTIONS
                 // ARRAY OF YES\No\gT("Uncertain") QUESTIONS
                 case "E":
                     // ARRAY OF Increase/Same/Decrease QUESTIONS
                 // ARRAY OF Increase/Same/Decrease QUESTIONS
                 case "F":
                     // FlEXIBLE ARRAY
                 // FlEXIBLE ARRAY
                 case "H":
                     // ARRAY (By Column)
                     //get answers
                     $query = "SELECT title as code, question as answer FROM {{questions}} WHERE parent_qid=:flt_0 AND language = :lang ORDER BY question_order";
                     $result = Yii::app()->db->createCommand($query)->bindParam(":flt_0", $flt[0], PDO::PARAM_INT)->bindParam(":lang", $sLanguage, PDO::PARAM_STR)->queryAll();
                     //go through all the (multiple) answers
                     foreach ($result as $row) {
                         $myfield2 = $myfield . reset($row);
                         $allfields[] = $myfield2;
                     }
                     break;
                     // all "free text" types (T, U, S)  get the same prefix ("T")
                 // all "free text" types (T, U, S)  get the same prefix ("T")
                 case "T":
                     // Long free text
                 // Long free text
                 case "U":
                     // Huge free text
                 // Huge free text
                 case "S":
                     // Short free text
                     $myfield = "T{$myfield}";
                     $allfields[] = $myfield;
                     break;
                 case ";":
                     //ARRAY (Multi Flex) (Text)
                 //ARRAY (Multi Flex) (Text)
                 case ":":
                     //ARRAY (Multi Flex) (Numbers)
                     $query = "SELECT title, question FROM {{questions}} WHERE parent_qid=:flt_0 AND language=:lang AND scale_id = 0 ORDER BY question_order";
                     $result = Yii::app()->db->createCommand($query)->bindParam(":flt_0", $flt[0], PDO::PARAM_INT)->bindParam(":lang", $sLanguage, PDO::PARAM_STR)->queryAll();
                     foreach ($result as $row) {
                         $fquery = "SELECT * FROM {{questions}} WHERE parent_qid = :flt_0 AND language = :lang AND scale_id = 1 ORDER BY question_order, title";
                         $fresult = Yii::app()->db->createCommand($query)->bindParam(":flt_0", $flt[0], PDO::PARAM_INT)->bindParam(":lang", $sLanguage, PDO::PARAM_STR)->queryAll();
                         foreach ($fresult as $frow) {
                             $myfield2 = $myfield . reset($row) . "_" . $frow['title'];
                             $allfields[] = $myfield2;
                         }
                     }
                     break;
                 case "R":
                     //RANKING
                     //get some answers
                     $query = "SELECT code, answer FROM {{answers}} WHERE qid = :flt_0 AND language = :lang ORDER BY sortorder, answer";
                     $result = Yii::app()->db->createCommand($query)->bindParam(":flt_0", $flt[0], PDO::PARAM_INT)->bindParam(":lang", $sLanguage, PDO::PARAM_STR)->queryAll();
                     //get number of answers
                     $count = count($result);
                     //loop through all answers. if there are 3 items to rate there will be 3 statistics
                     for ($i = 1; $i <= $count; $i++) {
                         $myfield2 = "R" . $myfield . $i . "-" . strlen($i);
                         $allfields[] = $myfield2;
                     }
                     break;
                     //Boilerplate questions are only used to put some text between other questions -> no analysis needed
                 //Boilerplate questions are only used to put some text between other questions -> no analysis needed
                 case "X":
                     //This is a boilerplate question and it has no business in this script
                     break;
                 case "1":
                     // MULTI SCALE
                     //get answers
                     $query = "SELECT title, question FROM {{questions}} WHERE parent_qid = :flt_0 AND language = :lang ORDER BY question_order";
                     $result = Yii::app()->db->createCommand($query)->bindParam(":flt_0", $flt[0], PDO::PARAM_INT)->bindParam(":lang", $sLanguage, PDO::PARAM_STR)->queryAll();
                     //loop through answers
                     foreach ($result as $row) {
                         //----------------- LABEL 1 ---------------------
                         $myfield2 = $myfield . $row['title'] . "#0";
                         $allfields[] = $myfield2;
                         //----------------- LABEL 2 ---------------------
                         $myfield2 = $myfield . $row['title'] . "#1";
                         $allfields[] = $myfield2;
                     }
                     //end WHILE -> loop through all answers
                     break;
                 case "P":
                     //P - Multiple choice with comments
                 //P - Multiple choice with comments
                 case "M":
                     //M - Multiple choice
                 //M - Multiple choice
                 case "N":
                     //N - Numerical input
                 //N - Numerical input
                 case "D":
                     //D - Date
                     $myfield2 = $flt[2] . $myfield;
                     $allfields[] = $myfield2;
                     break;
                 default:
                     //Default settings
                     $allfields[] = $myfield;
                     break;
             }
             //end switch -> check question types and create filter forms
         }
         //end foreach -> loop through all questions with "public_statistics" enabled
     }
     // end if -> for removing the error message in case there are no filters
     $summary = $allfields;
     // Get the survey inforamtion
     $thissurvey = getSurveyInfo($surveyid, $sLanguage);
     //SET THE TEMPLATE DIRECTORY
     $data['sTemplatePath'] = $surveyinfo['template'];
     // surveyinfo=getSurveyInfo and if survey don't exist : stop before.
     //---------- CREATE STATISTICS ----------
     $redata = compact(array_keys(get_defined_vars()));
     doHeader();
     echo templatereplace(file_get_contents(getTemplatePath($data['sTemplatePath']) . DIRECTORY_SEPARATOR . "startpage.pstpl"), array(), $redata);
     //some progress bar stuff
     // Create progress bar which is shown while creating the results
     $prb = new ProgressBar();
     $prb->pedding = 2;
     // Bar Pedding
     $prb->brd_color = "#404040 #dfdfdf #dfdfdf #404040";
     // Bar Border Color
     $prb->setFrame();
     // set ProgressBar Frame
     $prb->frame['left'] = 50;
     // Frame position from left
     $prb->frame['top'] = 80;
     // Frame position from top
     $prb->addLabel('text', 'txt1', gT("Please wait ..."));
     // add Text as Label 'txt1' and value 'Please wait'
     $prb->addLabel('percent', 'pct1');
     // add Percent as Label 'pct1'
     $prb->addButton('btn1', gT('Go back'), '?action=statistics&amp;sid=' . $iSurveyID);
     // add Button as Label 'btn1' and action '?restart=1'
     //progress bar starts with 35%
     $process_status = 35;
     $prb->show();
     // show the ProgressBar
     // 1: Get list of questions with answers chosen
     //"Getting Questions and Answer ..." is shown above the bar
     $prb->setLabelValue('txt1', gT('Getting questions and answers ...'));
     $prb->moveStep(5);
     // creates array of post variable names
     for (reset($_POST); $key = key($_POST); next($_POST)) {
         $postvars[] = $key;
     }
     $data['thisSurveyTitle'] = $thisSurveyTitle;
     $data['totalrecords'] = $totalrecords;
     $data['summary'] = $summary;
     //show some main data at the beginnung
     // CHANGE JSW_NZ - let's allow html formatted questions to show
     //push progress bar from 35 to 40
     $process_status = 40;
     //Show Summary results
     if (isset($summary) && $summary) {
         //"Generating Summaries ..." is shown above the progress bar
         $prb->setLabelValue('txt1', gT('Generating summaries ...'));
         $prb->moveStep($process_status);
         //let's run through the survey // Fixed bug 3053 with array_unique
         $runthrough = array_unique($summary);
         //loop through all selected questions
         foreach ($runthrough as $rt) {
             //update progress bar
             if ($process_status < 100) {
                 $process_status++;
             }
             $prb->moveStep($process_status);
         }
         // end foreach -> loop through all questions
         $helper = new statistics_helper();
         $statisticsoutput .= $helper->generate_statistics($iSurveyID, $summary, $summary, $publicgraphs, 'html', null, $sLanguage, false);
     }
     //end if -> show summary results
     $data['statisticsoutput'] = $statisticsoutput;
     //done! set progress bar to 100%
     if (isset($prb)) {
         $prb->setLabelValue('txt1', gT('Completed'));
         $prb->moveStep(100);
         $prb->hide();
     }
     $redata = compact(array_keys(get_defined_vars()));
     $data['redata'] = $redata;
     Yii::app()->getClientScript()->registerScriptFile(Yii::app()->getConfig('generalscripts') . 'statistics_user.js');
     $this->renderPartial('/statistics_user_view', $data);
     //output footer
     echo getFooter();
     //Delete all Session Data
     Yii::app()->session['finished'] = true;
 }
コード例 #2
0
ファイル: index.php プロジェクト: kochichi/LimeSurvey
 function action()
 {
     global $surveyid;
     global $thissurvey, $thisstep;
     global $clienttoken, $tokensexist, $token;
     // only attempt to change session lifetime if using a DB backend
     // with file based sessions, it's up to the admin to configure maxlifetime
     if (isset(Yii::app()->session->connectionID)) {
         @ini_set('session.gc_maxlifetime', Yii::app()->getConfig('iSessionExpirationTime'));
     }
     $this->_loadRequiredHelpersAndLibraries();
     $param = $this->_getParameters(func_get_args(), $_POST);
     $surveyid = $param['sid'];
     Yii::app()->setConfig('surveyID', $surveyid);
     $thisstep = $param['thisstep'];
     $move = getMove();
     Yii::app()->setConfig('move', $move);
     $clienttoken = trim($param['token']);
     $standardtemplaterootdir = Yii::app()->getConfig('standardtemplaterootdir');
     if (is_null($thissurvey) && !is_null($surveyid)) {
         $thissurvey = getSurveyInfo($surveyid);
     }
     // unused vars in this method (used in methods using compacted method vars)
     @($loadname = $param['loadname']);
     @($loadpass = $param['loadpass']);
     $sitename = Yii::app()->getConfig('sitename');
     if (isset($param['newtest']) && $param['newtest'] == "Y") {
         killSurveySession($surveyid);
     }
     $surveyExists = $surveyid && Survey::model()->findByPk($surveyid);
     $isSurveyActive = $surveyExists && Survey::model()->findByPk($surveyid)->active == "Y";
     // collect all data in this method to pass on later
     $redata = compact(array_keys(get_defined_vars()));
     $this->_loadLimesurveyLang($surveyid);
     if ($this->_isClientTokenDifferentFromSessionToken($clienttoken, $surveyid)) {
         $sReloadUrl = $this->getController()->createUrl("/survey/index/sid/{$surveyid}", array('token' => $clienttoken, 'lang' => App()->language, 'newtest' => 'Y'));
         $asMessage = array(gT('Token mismatch'), gT('The token you provided doesn\'t match the one in your session.'), "<a class='reloadlink newsurvey' href={$sReloadUrl}>" . gT("Click here to start the survey.") . "</a>");
         $this->_createNewUserSessionAndRedirect($surveyid, $redata, __LINE__, $asMessage);
     }
     if ($this->_isSurveyFinished($surveyid) && ($thissurvey['alloweditaftercompletion'] != 'Y' || $thissurvey['tokenanswerspersistence'] != 'Y')) {
         $aReloadUrlParam = array('lang' => App()->language, 'newtest' => 'Y');
         if ($clienttoken) {
             $aReloadUrlParam['token'] = $clienttoken;
         }
         $sReloadUrl = $this->getController()->createUrl("/survey/index/sid/{$surveyid}", $aReloadUrlParam);
         $asMessage = array(gT('Previous session is set to be finished.'), gT('Your browser reports that it was used previously to answer this survey. We are resetting the session so that you can start from the beginning.'), "<a class='reloadlink newsurvey' href={$sReloadUrl}>" . gT("Click here to start the survey.") . "</a>");
         $this->_createNewUserSessionAndRedirect($surveyid, $redata, __LINE__, $asMessage);
     }
     $previewmode = false;
     if (isset($param['action']) && in_array($param['action'], array('previewgroup', 'previewquestion'))) {
         if (!$this->_canUserPreviewSurvey($surveyid)) {
             $asMessage = array(gT('Error'), gT("We are sorry but you don't have permissions to do this."));
             $this->_niceExit($redata, __LINE__, null, $asMessage);
         } else {
             if (intval($param['qid']) && $param['action'] == 'previewquestion') {
                 $previewmode = 'question';
             }
             if (intval($param['gid']) && $param['action'] == 'previewgroup') {
                 $previewmode = 'group';
             }
         }
     }
     Yii::app()->setConfig('previewmode', $previewmode);
     if ($this->_surveyCantBeViewedWithCurrentPreviewAccess($surveyid, $isSurveyActive, $surveyExists)) {
         $bPreviewRight = $this->_userHasPreviewAccessSession($surveyid);
         if ($bPreviewRight === false) {
             $asMessage = array(gT("Error"), gT("We are sorry but you don't have permissions to do this."), sprintf(gT("Please contact %s ( %s ) for further assistance."), $thissurvey['adminname'], $thissurvey['adminemail']));
             $this->_niceExit($redata, __LINE__, null, $asMessage);
         }
     }
     // TODO can this be moved to the top?
     // (Used to be global, used in ExpressionManager, merged into amVars. If not filled in === '')
     // can this be added in the first computation of $redata?
     if (isset($_SESSION['survey_' . $surveyid]['srid'])) {
         $saved_id = $_SESSION['survey_' . $surveyid]['srid'];
     }
     // recompute $redata since $saved_id used to be a global
     $redata = compact(array_keys(get_defined_vars()));
     if ($this->_didSessionTimeOut($surveyid)) {
         // @TODO is this still required ?
         $asMessage = array(gT("Error"), gT("We are sorry but your session has expired."), gT("Either you have been inactive for too long, you have cookies disabled for your browser, or there were problems with your connection."), sprintf(gT("Please contact %s ( %s ) for further assistance."), $thissurvey['adminname'], $thissurvey['adminemail']));
         $this->_niceExit($redata, __LINE__, null, $asMessage);
     }
     // Set the language of the survey, either from POST, GET parameter of session var
     // Keep the old value, because SetSurveyLanguage update $_SESSION
     $sOldLang = isset($_SESSION['survey_' . $surveyid]['s_lang']) ? $_SESSION['survey_' . $surveyid]['s_lang'] : "";
     // Keep the old value, because SetSurveyLanguage update $_SESSION
     if (!empty($param['lang'])) {
         $sDisplayLanguage = $param['lang'];
         // $param take lang from returnGlobal and returnGlobal sanitize langagecode
     } elseif (isset($_SESSION['survey_' . $surveyid]['s_lang'])) {
         $sDisplayLanguage = $_SESSION['survey_' . $surveyid]['s_lang'];
     } elseif (Survey::model()->findByPk($surveyid)) {
         $sDisplayLanguage = Survey::model()->findByPk($surveyid)->language;
     } else {
         $sDisplayLanguage = Yii::app()->getConfig('defaultlang');
     }
     //CHECK FOR REQUIRED INFORMATION (sid)
     if ($surveyid && $surveyExists) {
         LimeExpressionManager::SetSurveyId($surveyid);
         // must be called early - it clears internal cache if a new survey is being used
         SetSurveyLanguage($surveyid, $sDisplayLanguage);
         if ($previewmode) {
             LimeExpressionManager::SetPreviewMode($previewmode);
         }
         if (App()->language != $sOldLang) {
             UpdateGroupList($surveyid, App()->language);
             // to refresh the language strings in the group list session variable
             UpdateFieldArray();
             // to refresh question titles and question text
         }
     } else {
         throw new CHttpException(404, "The survey in which you are trying to participate does not seem to exist. It may have been deleted or the link you were given is outdated or incorrect.");
     }
     // Get token
     if (!isset($token)) {
         $token = $clienttoken;
     }
     //GET BASIC INFORMATION ABOUT THIS SURVEY
     $thissurvey = getSurveyInfo($surveyid, $_SESSION['survey_' . $surveyid]['s_lang']);
     $event = new PluginEvent('beforeSurveyPage');
     $event->set('surveyId', $surveyid);
     App()->getPluginManager()->dispatchEvent($event);
     if (!is_null($event->get('template'))) {
         $thissurvey['templatedir'] = $event->get('template');
     }
     //SEE IF SURVEY USES TOKENS
     if ($surveyExists == 1 && tableExists('{{tokens_' . $thissurvey['sid'] . '}}')) {
         $tokensexist = 1;
     } else {
         $tokensexist = 0;
         unset($_POST['token']);
         unset($param['token']);
         unset($token);
         unset($clienttoken);
     }
     //SET THE TEMPLATE DIRECTORY
     global $oTemplate;
     $thistpl = $oTemplate->viewPath;
     $timeadjust = Yii::app()->getConfig("timeadjust");
     //MAKE SURE SURVEY HASN'T EXPIRED
     if ($thissurvey['expiry'] != '' and dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust) > $thissurvey['expiry'] && $thissurvey['active'] != 'N' && !$previewmode) {
         $redata = compact(array_keys(get_defined_vars()));
         $asMessage = array(gT("Error"), gT("This survey is no longer available."), sprintf(gT("Please contact %s ( %s ) for further assistance."), $thissurvey['adminname'], $thissurvey['adminemail']));
         $this->_niceExit($redata, __LINE__, $thissurvey['templatedir'], $asMessage);
     }
     //MAKE SURE SURVEY IS ALREADY VALID
     if ($thissurvey['startdate'] != '' and dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust) < $thissurvey['startdate'] && $thissurvey['active'] != 'N' && !$previewmode) {
         $redata = compact(array_keys(get_defined_vars()));
         $asMessage = array(gT("Error"), gT("This survey is not yet started."), sprintf(gT("Please contact %s ( %s ) for further assistance."), $thissurvey['adminname'], $thissurvey['adminemail']));
         $this->_niceExit($redata, __LINE__, $thissurvey['templatedir'], $asMessage);
     }
     //CHECK FOR PREVIOUSLY COMPLETED COOKIE
     //If cookies are being used, and this survey has been completed, a cookie called "PHPSID[sid]STATUS" will exist (ie: SID6STATUS) and will have a value of "COMPLETE"
     $sCookieName = "LS_" . $surveyid . "_STATUS";
     if (isset($_COOKIE[$sCookieName]) && $_COOKIE[$sCookieName] == "COMPLETE" && $thissurvey['usecookie'] == "Y" && $tokensexist != 1 && (!isset($param['newtest']) || $param['newtest'] != "Y")) {
         $redata = compact(array_keys(get_defined_vars()));
         $asMessage = array(gT("Error"), gT("You have already completed this survey."), sprintf(gT("Please contact %s ( %s ) for further assistance."), $thissurvey['adminname'], $thissurvey['adminemail']));
         $this->_niceExit($redata, __LINE__, $thissurvey['templatedir'], $asMessage);
     }
     //LOAD SAVED SURVEY
     if (Yii::app()->request->getParam('loadall') == "reload") {
         $errormsg = "";
         $sLoadName = Yii::app()->request->getParam('loadname');
         $sLoadPass = Yii::app()->request->getParam('loadpass');
         if (isset($sLoadName) && !$sLoadName) {
             $errormsg .= gT("You did not provide a name") . "<br />\n";
         }
         if (isset($sLoadPass) && !$sLoadPass) {
             $errormsg .= gT("You did not provide a password") . "<br />\n";
         }
         // if security question answer is incorrect
         // Not called if scid is set in GET params (when using email save/reload reminder URL)
         if (function_exists("ImageCreate") && isCaptchaEnabled('saveandloadscreen', $thissurvey['usecaptcha']) && is_null(Yii::app()->request->getQuery('scid'))) {
             $sLoadSecurity = Yii::app()->request->getPost('loadsecurity');
             if (empty($sLoadSecurity)) {
                 $errormsg .= gT("You did not answer to the security question.") . "<br />\n";
             } elseif (!isset($_SESSION['survey_' . $surveyid]['secanswer']) || $sLoadSecurity != $_SESSION['survey_' . $surveyid]['secanswer']) {
                 $errormsg .= gT("The answer to the security question is incorrect.") . "<br />\n";
             }
         }
         if ($errormsg == "") {
             LimeExpressionManager::SetDirtyFlag();
             buildsurveysession($surveyid);
             if (loadanswers()) {
                 Yii::app()->setConfig('move', 'reload');
                 $move = "reload";
                 // veyRunTimeHelper use $move in $arg
             } else {
                 $errormsg .= gT("There is no matching saved survey");
             }
         }
         if ($errormsg) {
             Yii::app()->setConfig('move', "loadall");
             // Show loading form
         }
     }
     //Allow loading of saved survey
     if (Yii::app()->getConfig('move') == "loadall") {
         $redata = compact(array_keys(get_defined_vars()));
         Yii::import("application.libraries.Load_answers");
         $tmp = new Load_answers();
         $tmp->run($redata);
     }
     //Check if TOKEN is used for EVERY PAGE
     //This function fixes a bug where users able to submit two surveys/votes
     //by checking that the token has not been used at each page displayed.
     // bypass only this check at first page (Step=0) because
     // this check is done in buildsurveysession and error message
     // could be more interresting there (takes into accound captcha if used)
     if ($tokensexist == 1 && isset($token) && $token != "" && isset($_SESSION['survey_' . $surveyid]['step']) && $_SESSION['survey_' . $surveyid]['step'] > 0 && tableExists("tokens_{$surveyid}}}")) {
         // check also if it is allowed to change survey after completion
         if ($thissurvey['alloweditaftercompletion'] == 'Y') {
             $tokenInstance = Token::model($surveyid)->findByAttributes(array('token' => $token));
         } else {
             $tokenInstance = Token::model($surveyid)->usable()->incomplete()->findByAttributes(array('token' => $token));
         }
         if (!isset($tokenInstance) && !$previewmode) {
             //TOKEN DOESN'T EXIST OR HAS ALREADY BEEN USED. EXPLAIN PROBLEM AND EXIT
             $asMessage = array(null, gT("This is a controlled survey. You need a valid token to participate."), sprintf(gT("For further information please contact %s"), $thissurvey['adminname'] . " (<a href='mailto:{$thissurvey['adminemail']}'>" . "{$thissurvey['adminemail']}</a>)"));
             $this->_niceExit($redata, __LINE__, $thistpl, $asMessage, true);
         }
     }
     if ($tokensexist == 1 && isset($token) && $token != "" && tableExists("{{tokens_" . $surveyid . "}}") && !$previewmode) {
         // check also if it is allowed to change survey after completion
         if ($thissurvey['alloweditaftercompletion'] == 'Y') {
             $tokenInstance = Token::model($surveyid)->editable()->findByAttributes(array('token' => $token));
         } else {
             $tokenInstance = Token::model($surveyid)->usable()->incomplete()->findByAttributes(array('token' => $token));
         }
         if (!isset($tokenInstance)) {
             $oToken = Token::model($surveyid)->findByAttributes(array('token' => $token));
             if ($oToken) {
                 $now = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", Yii::app()->getConfig("timeadjust"));
                 if ($oToken->completed != 'N' && !empty($oToken->completed)) {
                     $sError = gT("This invitation has already been used.");
                 } elseif (strtotime($now) < strtotime($oToken->validfrom)) {
                     $sError = gT("This invitation is not valid yet.");
                 } elseif (strtotime($now) > strtotime($oToken->validuntil)) {
                     $sError = gT("This invitation is not valid anymore.");
                 } else {
                     $sError = gT("This is a controlled survey. You need a valid token to participate.");
                 }
             } else {
                 $sError = gT("This is a controlled survey. You need a valid token to participate.");
             }
             $asMessage = array($sError, gT("We are sorry but you are not allowed to enter this survey."), sprintf(gT("For further information please contact %s"), $thissurvey['adminname'] . " (<a href='mailto:{$thissurvey['adminemail']}'>" . "{$thissurvey['adminemail']}</a>)"));
             $this->_niceExit($redata, __LINE__, $thistpl, $asMessage, true);
         }
     }
     //Clear session and remove the incomplete response if requested.
     if (isset($move) && $move == "clearall") {
         // delete the response but only if not already completed
         $s_lang = $_SESSION['survey_' . $surveyid]['s_lang'];
         if (isset($_SESSION['survey_' . $surveyid]['srid']) && !SurveyDynamic::model($surveyid)->isCompleted($_SESSION['survey_' . $surveyid]['srid'])) {
             // delete the response but only if not already completed
             $result = dbExecuteAssoc('DELETE FROM {{survey_' . $surveyid . '}} WHERE id=' . $_SESSION['survey_' . $surveyid]['srid'] . " AND submitdate IS NULL");
             if ($result->count() > 0) {
                 // Using count() here *should* be okay for MSSQL because it is a delete statement
                 // find out if there are any fuqt questions - checked
                 $fieldmap = createFieldMap($surveyid, 'short', false, false, $s_lang);
                 foreach ($fieldmap as $field) {
                     if ($field['type'] == "|" && !strpos($field['fieldname'], "_filecount")) {
                         if (!isset($qid)) {
                             $qid = array();
                         }
                         $qid[] = $field['fieldname'];
                     }
                 }
                 // if yes, extract the response json to those questions
                 if (isset($qid)) {
                     $query = "SELECT * FROM {{survey_" . $surveyid . "}} WHERE id=" . $_SESSION['survey_' . $surveyid]['srid'];
                     $result = dbExecuteAssoc($query);
                     foreach ($result->readAll() as $row) {
                         foreach ($qid as $question) {
                             $json = $row[$question];
                             if ($json == "" || $json == NULL) {
                                 continue;
                             }
                             // decode them
                             $phparray = json_decode($json);
                             foreach ($phparray as $metadata) {
                                 $target = Yii::app()->getConfig("uploaddir") . "/surveys/" . $surveyid . "/files/";
                                 // delete those files
                                 unlink($target . $metadata->filename);
                             }
                         }
                     }
                 }
                 // done deleting uploaded files
             }
             // also delete a record from saved_control when there is one
             dbExecuteAssoc('DELETE FROM {{saved_control}} WHERE srid=' . $_SESSION['survey_' . $surveyid]['srid'] . ' AND sid=' . $surveyid);
         }
         killSurveySession($surveyid);
         sendCacheHeaders();
         doHeader();
         $redata = compact(array_keys(get_defined_vars()));
         $this->_printTemplateContent($thistpl . '/startpage.pstpl', $redata, __LINE__);
         echo "\n\n<!-- JAVASCRIPT FOR CONDITIONAL QUESTIONS -->\n" . "\t<script type='text/javascript'>\n" . "\t<!--\n" . "function checkconditions(value, name, type, evt_type)\n" . "\t{\n" . "\t}\n" . "\t//-->\n" . "\t</script>\n\n";
         //Present the clear all page using clearall.pstpl template
         $this->_printTemplateContent($thistpl . '/clearall.pstpl', $redata, __LINE__);
         $this->_printTemplateContent($thistpl . '/endpage.pstpl', $redata, __LINE__);
         doFooter();
         exit;
     }
     //Check to see if a refering URL has been captured.
     if (!isset($_SESSION['survey_' . $surveyid]['refurl'])) {
         $_SESSION['survey_' . $surveyid]['refurl'] = GetReferringUrl();
         // do not overwrite refurl
     }
     // Let's do this only if
     //  - a saved answer record hasn't been loaded through the saved feature
     //  - the survey is not anonymous
     //  - the survey is active
     //  - a token information has been provided
     //  - the survey is setup to allow token-response-persistence
     if (!isset($_SESSION['survey_' . $surveyid]['srid']) && $thissurvey['anonymized'] == "N" && $thissurvey['active'] == "Y" && isset($token) && $token != '') {
         // load previous answers if any (dataentry with nosubmit)
         $oResponses = Response::model($surveyid)->findAllByAttributes(array('token' => $token), array('order' => 'id DESC'));
         if (!empty($oResponses)) {
             /**
              * We fire the response selection event when at least 1 response was found.
              * If there is just 1 response the plugin still has to option to choose
              * NOT to use it.
              */
             $event = new PluginEvent('beforeLoadResponse');
             $event->set('responses', $oResponses);
             $event->set('surveyId', $surveyid);
             App()->pluginManager->dispatchEvent($event);
             $oResponse = $event->get('response');
             // If $oResponse is false we act as if no response was found.
             // This allows a plugin to deny continuing a response.
             if ($oResponse !== false) {
                 // If plugin does not set a response we use the first one found, (this replicates pre-plugin behavior)
                 if (!isset($oResponse) && (!isset($oResponses[0]->submitdate) || $thissurvey['alloweditaftercompletion'] == 'Y') && $thissurvey['tokenanswerspersistence'] == 'Y') {
                     $oResponse = $oResponses[0];
                 }
                 if (isset($oResponse)) {
                     $_SESSION['survey_' . $surveyid]['srid'] = $oResponse->id;
                     if (!empty($oResponse->lastpage)) {
                         $_SESSION['survey_' . $surveyid]['LEMtokenResume'] = true;
                         // If the response was completed and user is allowed to edit after completion start at the beginning and not at the last page - just makes more sense
                         if (!($oResponse->submitdate && $thissurvey['alloweditaftercompletion'] == 'Y')) {
                             $_SESSION['survey_' . $surveyid]['step'] = $oResponse->lastpage;
                         }
                     }
                     buildsurveysession($surveyid);
                     if (!empty($oResponse->submitdate)) {
                         $_SESSION['survey_' . $surveyid]['maxstep'] = $_SESSION['survey_' . $surveyid]['totalsteps'];
                     }
                     loadanswers();
                 }
             }
         }
     }
     // Preview action : Preview right already tested before
     if ($previewmode) {
         // Unset all SESSION: be sure to have the last version
         unset($_SESSION['fieldmap-' . $surveyid . App()->language]);
         // Needed by createFieldMap: else fieldmap can be outdated
         unset($_SESSION['survey_' . $surveyid]);
         if ($param['action'] == 'previewgroup') {
             $thissurvey['format'] = 'G';
         } elseif ($param['action'] == 'previewquestion') {
             $thissurvey['format'] = 'S';
         }
         buildsurveysession($surveyid, true);
     }
     sendCacheHeaders();
     //Send local variables to the appropriate survey type
     unset($redata);
     $redata = compact(array_keys(get_defined_vars()));
     Yii::import('application.helpers.SurveyRuntimeHelper');
     $tmp = new SurveyRuntimeHelper();
     $tmp->run($surveyid, $redata);
     if (isset($_POST['saveall']) || isset($flashmessage)) {
         echo "<script type='text/javascript'> \$(document).ready( function() { alert('" . gT("Your responses were successfully saved.", "js") . "');}) </script>";
     }
 }
コード例 #3
0
/**
* This function builds all the required session variables when a survey is first started and
* it loads any answer defaults from command line or from the table defaultvalues
* It is called from the related format script (group.php, question.php, survey.php)
* if the survey has just started.
*/
function buildsurveysession($surveyid, $preview = false)
{
    Yii::trace('start', 'survey.buildsurveysession');
    global $secerror, $clienttoken;
    global $tokensexist;
    //global $surveyid;
    global $move, $rooturl;
    $clang = Yii::app()->lang;
    $sLangCode = $clang->langcode;
    $languagechanger = makeLanguageChangerSurvey($sLangCode);
    if (!$preview) {
        $preview = Yii::app()->getConfig('previewmode');
    }
    $thissurvey = getSurveyInfo($surveyid, $sLangCode);
    $_SESSION['survey_' . $surveyid]['templatename'] = validateTemplateDir($thissurvey['template']);
    $_SESSION['survey_' . $surveyid]['templatepath'] = getTemplatePath($_SESSION['survey_' . $surveyid]['templatename']) . DIRECTORY_SEPARATOR;
    $sTemplatePath = $_SESSION['survey_' . $surveyid]['templatepath'];
    $loadsecurity = returnGlobal('loadsecurity', true);
    // NO TOKEN REQUIRED BUT CAPTCHA ENABLED FOR SURVEY ACCESS
    if ($tokensexist == 0 && isCaptchaEnabled('surveyaccessscreen', $thissurvey['usecaptcha']) && !isset($_SESSION['survey_' . $surveyid]['captcha_surveyaccessscreen']) && !$preview) {
        // IF CAPTCHA ANSWER IS NOT CORRECT OR NOT SET
        if (!isset($loadsecurity) || !isset($_SESSION['survey_' . $surveyid]['secanswer']) || $loadsecurity != $_SESSION['survey_' . $surveyid]['secanswer']) {
            sendCacheHeaders();
            doHeader();
            // No or bad answer to required security question
            $redata = compact(array_keys(get_defined_vars()));
            echo templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata, 'frontend_helper[875]');
            //echo makedropdownlist();
            echo templatereplace(file_get_contents($sTemplatePath . "survey.pstpl"), array(), $redata, 'frontend_helper[877]');
            if (isset($loadsecurity)) {
                // was a bad answer
                echo "<font color='#FF0000'>" . $clang->gT("The answer to the security question is incorrect.") . "</font><br />";
            }
            echo "<p class='captcha'>" . $clang->gT("Please confirm access to survey by answering the security question below and click continue.") . "</p>" . CHtml::form(array("/survey/index/sid/{$surveyid}"), 'post', array('class' => 'captcha')) . "\n            <table align='center'>\n            <tr>\n            <td align='right' valign='middle'>\n            <input type='hidden' name='sid' value='" . $surveyid . "' id='sid' />\n            <input type='hidden' name='lang' value='" . $sLangCode . "' id='lang' />";
            // In case we this is a direct Reload previous answers URL, then add hidden fields
            if (isset($_GET['loadall']) && isset($_GET['scid']) && isset($_GET['loadname']) && isset($_GET['loadpass'])) {
                echo "\n                <input type='hidden' name='loadall' value='" . htmlspecialchars($_GET['loadall']) . "' id='loadall' />\n                <input type='hidden' name='scid' value='" . returnGlobal('scid', true) . "' id='scid' />\n                <input type='hidden' name='loadname' value='" . htmlspecialchars($_GET['loadname']) . "' id='loadname' />\n                <input type='hidden' name='loadpass' value='" . htmlspecialchars($_GET['loadpass']) . "' id='loadpass' />";
            }
            echo "\n            </td>\n            </tr>";
            if (function_exists("ImageCreate") && isCaptchaEnabled('surveyaccessscreen', $thissurvey['usecaptcha'])) {
                echo "<tr>\n                <td align='center' valign='middle'><label for='captcha'>" . $clang->gT("Security question:") . "</label></td><td align='left' valign='middle'><table><tr><td valign='middle'><img src='" . Yii::app()->getController()->createUrl('/verification/image/sid/' . $surveyid) . "' alt='captcha' /></td>\n                <td valign='middle'><input id='captcha' type='text' size='5' maxlength='3' name='loadsecurity' value='' /></td></tr></table>\n                </td>\n                </tr>";
            }
            echo "<tr><td colspan='2' align='center'><input class='submit' type='submit' value='" . $clang->gT("Continue") . "' /></td></tr>\n            </table>\n            </form>";
            echo templatereplace(file_get_contents($sTemplatePath . "endpage.pstpl"), array(), $redata, 'frontend_helper[1567]');
            doFooter();
            exit;
        } else {
            $_SESSION['survey_' . $surveyid]['captcha_surveyaccessscreen'] = true;
        }
    }
    //BEFORE BUILDING A NEW SESSION FOR THIS SURVEY, LET'S CHECK TO MAKE SURE THE SURVEY SHOULD PROCEED!
    // TOKEN REQUIRED BUT NO TOKEN PROVIDED
    if ($tokensexist == 1 && !$clienttoken && !$preview) {
        if ($thissurvey['nokeyboard'] == 'Y') {
            includeKeypad();
            $kpclass = "text-keypad";
        } else {
            $kpclass = "";
        }
        // DISPLAY REGISTER-PAGE if needed
        // DISPLAY CAPTCHA if needed
        sendCacheHeaders();
        doHeader();
        $redata = compact(array_keys(get_defined_vars()));
        echo templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata, 'frontend_helper[1594]');
        //echo makedropdownlist();
        echo templatereplace(file_get_contents($sTemplatePath . "survey.pstpl"), array(), $redata, 'frontend_helper[1596]');
        if (isset($thissurvey) && $thissurvey['allowregister'] == "Y") {
            echo templatereplace(file_get_contents($sTemplatePath . "register.pstpl"), array(), $redata, 'frontend_helper[1599]');
        } else {
            // ->renderPartial('entertoken_view');
            if (isset($secerror)) {
                echo "<span class='error'>" . $secerror . "</span><br />";
            }
            echo '<div id="wrapper"><p id="tokenmessage">' . $clang->gT("This is a controlled survey. You need a valid token to participate.") . "<br />";
            echo $clang->gT("If you have been issued a token, please enter it in the box below and click continue.") . "</p>\n            <script type='text/javascript'>var focus_element='#token';</script>" . CHtml::form(array("/survey/index/sid/{$surveyid}"), 'post', array('id' => 'tokenform', 'autocomplete' => 'off')) . "\n            <ul>\n            <li>";
            ?>
            <label for='token'><?php 
            $clang->eT("Token:");
            ?>
</label><input class='text <?php 
            echo $kpclass;
            ?>
' id='token' type='password' name='token' value='' />
            <?php 
            echo "<input type='hidden' name='sid' value='" . $surveyid . "' id='sid' />\n            <input type='hidden' name='lang' value='" . $sLangCode . "' id='lang' />";
            if (isset($_GET['newtest']) && $_GET['newtest'] == "Y") {
                echo "  <input type='hidden' name='newtest' value='Y' id='newtest' />";
            }
            // If this is a direct Reload previous answers URL, then add hidden fields
            if (isset($_GET['loadall']) && isset($_GET['scid']) && isset($_GET['loadname']) && isset($_GET['loadpass'])) {
                echo "\n                <input type='hidden' name='loadall' value='" . htmlspecialchars($_GET['loadall']) . "' id='loadall' />\n                <input type='hidden' name='scid' value='" . returnGlobal('scid', true) . "' id='scid' />\n                <input type='hidden' name='loadname' value='" . htmlspecialchars($_GET['loadname']) . "' id='loadname' />\n                <input type='hidden' name='loadpass' value='" . htmlspecialchars($_GET['loadpass']) . "' id='loadpass' />";
            }
            echo "</li>";
            if (function_exists("ImageCreate") && isCaptchaEnabled('surveyaccessscreen', $thissurvey['usecaptcha'])) {
                echo "<li>\n                <label for='captchaimage'>" . $clang->gT("Security Question") . "</label><img id='captchaimage' src='" . Yii::app()->getController()->createUrl('/verification/image/sid/' . $surveyid) . "' alt='captcha' /><input type='text' size='5' maxlength='3' name='loadsecurity' value='' />\n                </li>";
            }
            echo "<li>\n            <input class='submit button' type='submit' value='" . $clang->gT("Continue") . "' />\n            </li>\n            </ul>\n            </form></div>";
        }
        echo templatereplace(file_get_contents($sTemplatePath . "endpage.pstpl"), array(), $redata, 'frontend_helper[1645]');
        doFooter();
        exit;
    } elseif ($tokensexist == 1 && $clienttoken && !isCaptchaEnabled('surveyaccessscreen', $thissurvey['usecaptcha'])) {
        //check if token actually does exist
        // check also if it is allowed to change survey after completion
        if ($thissurvey['alloweditaftercompletion'] == 'Y') {
            $oTokenEntry = Token::model($surveyid)->findByAttributes(array('token' => $clienttoken));
        } else {
            $oTokenEntry = Token::model($surveyid)->usable()->incomplete()->findByAttributes(array('token' => $clienttoken));
        }
        if (!isset($oTokenEntry)) {
            //TOKEN DOESN'T EXIST OR HAS ALREADY BEEN USED. EXPLAIN PROBLEM AND EXIT
            killSurveySession($surveyid);
            sendCacheHeaders();
            doHeader();
            $redata = compact(array_keys(get_defined_vars()));
            echo templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata, 'frontend_helper[1676]');
            echo templatereplace(file_get_contents($sTemplatePath . "survey.pstpl"), array(), $redata, 'frontend_helper[1677]');
            echo '<div id="wrapper"><p id="tokenmessage">' . $clang->gT("This is a controlled survey. You need a valid token to participate.") . "<br /><br />\n" . "\t" . $clang->gT("The token you have provided is either not valid, or has already been used.") . "<br /><br />\n" . "\t" . sprintf($clang->gT("For further information please contact %s"), $thissurvey['adminname']) . " (<a href='mailto:{$thissurvey['adminemail']}'>" . "{$thissurvey['adminemail']}</a>)</p></div>\n";
            echo templatereplace(file_get_contents($sTemplatePath . "endpage.pstpl"), array(), $redata, 'frontend_helper[1684]');
            doFooter();
            exit;
        }
    } elseif ($tokensexist == 1 && $clienttoken && isCaptchaEnabled('surveyaccessscreen', $thissurvey['usecaptcha'])) {
        // IF CAPTCHA ANSWER IS CORRECT
        if (isset($loadsecurity) && isset($_SESSION['survey_' . $surveyid]['secanswer']) && $loadsecurity == $_SESSION['survey_' . $surveyid]['secanswer']) {
            if ($thissurvey['alloweditaftercompletion'] == 'Y') {
                $oTokenEntry = Token::model($surveyid)->findByAttributes(array('token' => $clienttoken));
            } else {
                $oTokenEntry = Token::model($surveyid)->incomplete()->findByAttributes(array('token' => $clienttoken));
            }
            if (!isset($oTokenEntry)) {
                sendCacheHeaders();
                doHeader();
                //TOKEN DOESN'T EXIST OR HAS ALREADY BEEN USED. EXPLAIN PROBLEM AND EXIT
                $redata = compact(array_keys(get_defined_vars()));
                echo templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata, 'frontend_helper[1719]');
                echo templatereplace(file_get_contents($sTemplatePath . "survey.pstpl"), array(), $redata, 'frontend_helper[1720]');
                echo "\t<div id='wrapper'>\n" . "\t<p id='tokenmessage'>\n" . "\t" . $clang->gT("This is a controlled survey. You need a valid token to participate.") . "<br /><br />\n" . "\t" . $clang->gT("The token you have provided is either not valid, or has already been used.") . "<br/><br />\n" . "\t" . sprintf($clang->gT("For further information please contact %s"), $thissurvey['adminname']) . " (<a href='mailto:{$thissurvey['adminemail']}'>" . "{$thissurvey['adminemail']}</a>)\n" . "\t</p>\n" . "\t</div>\n";
                echo templatereplace(file_get_contents($sTemplatePath . "endpage.pstpl"), array(), $redata, 'frontend_helper[1731]');
                doFooter();
                exit;
            }
        } else {
            if (!isset($move) || is_null($move)) {
                unset($_SESSION['survey_' . $surveyid]['srid']);
                $gettoken = $clienttoken;
                sendCacheHeaders();
                doHeader();
                // No or bad answer to required security question
                $redata = compact(array_keys(get_defined_vars()));
                echo templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata, 'frontend_helper[1745]');
                echo templatereplace(file_get_contents($sTemplatePath . "survey.pstpl"), array(), $redata, 'frontend_helper[1746]');
                // If token wasn't provided and public registration
                // is enabled then show registration form
                if (!isset($gettoken) && isset($thissurvey) && $thissurvey['allowregister'] == "Y") {
                    echo templatereplace(file_get_contents($sTemplatePath . "register.pstpl"), array(), $redata, 'frontend_helper[1751]');
                } else {
                    // only show CAPTCHA
                    echo '<div id="wrapper"><p id="tokenmessage">';
                    if (isset($loadsecurity)) {
                        // was a bad answer
                        echo "<span class='error'>" . $clang->gT("The answer to the security question is incorrect.") . "</span><br />";
                    }
                    echo $clang->gT("This is a controlled survey. You need a valid token to participate.") . "<br /><br />";
                    // IF TOKEN HAS BEEN GIVEN THEN AUTOFILL IT
                    // AND HIDE ENTRY FIELD
                    if (!isset($gettoken)) {
                        echo $clang->gT("If you have been issued a token, please enter it in the box below and click continue.") . "</p>\n                        <form id='tokenform' method='get' action='" . Yii::app()->getController()->createUrl("/survey/index") . "'>\n                        <ul>\n                        <li>\n                        <input type='hidden' name='sid' value='" . $surveyid . "' id='sid' />\n                        <input type='hidden' name='lang' value='" . $sLangCode . "' id='lang' />";
                        if (isset($_GET['loadall']) && isset($_GET['scid']) && isset($_GET['loadname']) && isset($_GET['loadpass'])) {
                            echo "<input type='hidden' name='loadall' value='" . htmlspecialchars($_GET['loadall']) . "' id='loadall' />\n                            <input type='hidden' name='scid' value='" . returnGlobal('scid', true) . "' id='scid' />\n                            <input type='hidden' name='loadname' value='" . htmlspecialchars($_GET['loadname']) . "' id='loadname' />\n                            <input type='hidden' name='loadpass' value='" . htmlspecialchars($_GET['loadpass']) . "' id='loadpass' />";
                        }
                        echo '<label for="token">' . $clang->gT("Token") . "</label><input class='text' type='password' id='token' name='token'></li>";
                    } else {
                        echo $clang->gT("Please confirm the token by answering the security question below and click continue.") . "</p>\n                    <form id='tokenform' method='get' action='" . Yii::app()->getController()->createUrl("/survey/index") . "'>\n                    <ul>\n                    <li>\n                    <input type='hidden' name='sid' value='" . $surveyid . "' id='sid' />\n                    <input type='hidden' name='lang' value='" . $sLangCode . "' id='lang' />";
                        if (isset($_GET['loadall']) && isset($_GET['scid']) && isset($_GET['loadname']) && isset($_GET['loadpass'])) {
                            echo "<input type='hidden' name='loadall' value='" . htmlspecialchars($_GET['loadall']) . "' id='loadall' />\n                        <input type='hidden' name='scid' value='" . returnGlobal('scid', true) . "' id='scid' />\n                        <input type='hidden' name='loadname' value='" . htmlspecialchars($_GET['loadname']) . "' id='loadname' />\n                        <input type='hidden' name='loadpass' value='" . htmlspecialchars($_GET['loadpass']) . "' id='loadpass' />";
                        }
                        echo '<label for="token">' . $clang->gT("Token:") . "</label><span id='token'>{$gettoken}</span>" . "<input type='hidden' name='token' value='{$gettoken}'></li>";
                    }
                    if (function_exists("ImageCreate") && isCaptchaEnabled('surveyaccessscreen', $thissurvey['usecaptcha'])) {
                        echo "<li>\n                    <label for='captchaimage'>" . $clang->gT("Security Question") . "</label><img id='captchaimage' src='" . Yii::app()->getController()->createUrl('/verification/image/sid/' . $surveyid) . "' alt='captcha' /><input type='text' size='5' maxlength='3' name='loadsecurity' value='' />\n                    </li>";
                    }
                    echo "<li><input class='submit' type='submit' value='" . $clang->gT("Continue") . "' /></li>\n                </ul>\n                </form>\n                </id>";
                }
                echo '</div>' . templatereplace(file_get_contents($sTemplatePath . "endpage.pstpl"), array(), $redata, 'frontend_helper[1817]');
                doFooter();
                exit;
            }
        }
    }
    //RESET ALL THE SESSION VARIABLES AND START AGAIN
    unset($_SESSION['survey_' . $surveyid]['grouplist']);
    unset($_SESSION['survey_' . $surveyid]['fieldarray']);
    unset($_SESSION['survey_' . $surveyid]['insertarray']);
    unset($_SESSION['survey_' . $surveyid]['fieldnamesInfo']);
    unset($_SESSION['survey_' . $surveyid]['fieldmap-' . $surveyid . '-randMaster']);
    unset($_SESSION['survey_' . $surveyid]['groupReMap']);
    $_SESSION['survey_' . $surveyid]['fieldnamesInfo'] = array();
    // Multi lingual support order : by REQUEST, if not by Token->language else by survey default language
    if (returnGlobal('lang', true)) {
        $language_to_set = returnGlobal('lang', true);
    } elseif (isset($oTokenEntry) && $oTokenEntry) {
        // If survey have token : we have a $oTokenEntry
        // Can use $oTokenEntry = Token::model($surveyid)->findByAttributes(array('token'=>$clienttoken)); if we move on another function : this par don't validate the token validity
        $language_to_set = $oTokenEntry->language;
    } else {
        $language_to_set = $thissurvey['language'];
    }
    if (!isset($_SESSION['survey_' . $surveyid]['s_lang'])) {
        SetSurveyLanguage($surveyid, $language_to_set);
    }
    UpdateGroupList($surveyid, $_SESSION['survey_' . $surveyid]['s_lang']);
    $sQuery = "SELECT count(*)\n" . " FROM {{groups}} INNER JOIN {{questions}} ON {{groups}}.gid = {{questions}}.gid\n" . " WHERE {{questions}}.sid=" . $surveyid . "\n" . " AND {{groups}}.language='" . $_SESSION['survey_' . $surveyid]['s_lang'] . "'\n" . " AND {{questions}}.language='" . $_SESSION['survey_' . $surveyid]['s_lang'] . "'\n" . " AND {{questions}}.parent_qid=0\n";
    $totalquestions = Yii::app()->db->createCommand($sQuery)->queryScalar();
    // Fix totalquestions by substracting Test Display questions
    $iNumberofQuestions = dbExecuteAssoc("SELECT count(*)\n" . " FROM {{questions}}" . " WHERE type in ('X','*')\n" . " AND sid={$surveyid}" . " AND language='" . $_SESSION['survey_' . $surveyid]['s_lang'] . "'" . " AND parent_qid=0")->read();
    $_SESSION['survey_' . $surveyid]['totalquestions'] = $totalquestions - (int) reset($iNumberofQuestions);
    //2. SESSION VARIABLE: totalsteps
    //The number of "pages" that will be presented in this survey
    //The number of pages to be presented will differ depending on the survey format
    switch ($thissurvey['format']) {
        case "A":
            $_SESSION['survey_' . $surveyid]['totalsteps'] = 1;
            break;
        case "G":
            if (isset($_SESSION['survey_' . $surveyid]['grouplist'])) {
                $_SESSION['survey_' . $surveyid]['totalsteps'] = count($_SESSION['survey_' . $surveyid]['grouplist']);
            }
            break;
        case "S":
            $_SESSION['survey_' . $surveyid]['totalsteps'] = $totalquestions;
    }
    if ($totalquestions == 0) {
        sendCacheHeaders();
        doHeader();
        $redata = compact(array_keys(get_defined_vars()));
        echo templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata, 'frontend_helper[1914]');
        echo templatereplace(file_get_contents($sTemplatePath . "survey.pstpl"), array(), $redata, 'frontend_helper[1915]');
        echo "\t<div id='wrapper'>\n" . "\t<p id='tokenmessage'>\n" . "\t" . $clang->gT("This survey does not yet have any questions and cannot be tested or completed.") . "<br /><br />\n" . "\t" . sprintf($clang->gT("For further information please contact %s"), $thissurvey['adminname']) . " (<a href='mailto:{$thissurvey['adminemail']}'>" . "{$thissurvey['adminemail']}</a>)<br /><br />\n" . "\t</p>\n" . "\t</div>\n";
        echo templatereplace(file_get_contents($sTemplatePath . "endpage.pstpl"), array(), $redata, 'frontend_helper[1925]');
        doFooter();
        exit;
    }
    //Perform a case insensitive natural sort on group name then question title of a multidimensional array
    //    usort($arows, 'groupOrderThenQuestionOrder');
    //3. SESSION VARIABLE - insertarray
    //An array containing information about used to insert the data into the db at the submit stage
    //4. SESSION VARIABLE - fieldarray
    //See rem at end..
    if ($tokensexist == 1 && $clienttoken) {
        $_SESSION['survey_' . $surveyid]['token'] = $clienttoken;
    }
    if ($thissurvey['anonymized'] == "N") {
        $_SESSION['survey_' . $surveyid]['insertarray'][] = "token";
    }
    $qtypes = getQuestionTypeList('', 'array');
    $fieldmap = createFieldMap($surveyid, 'full', true, false, $_SESSION['survey_' . $surveyid]['s_lang']);
    // Randomization groups for groups
    $aRandomGroups = array();
    $aGIDCompleteMap = array();
    // first find all groups and their groups IDS
    $criteria = new CDbCriteria();
    $criteria->addColumnCondition(array('sid' => $surveyid, 'language' => $_SESSION['survey_' . $surveyid]['s_lang']));
    $criteria->addCondition("randomization_group != ''");
    $oData = QuestionGroup::model()->findAll($criteria);
    foreach ($oData as $aGroup) {
        $aRandomGroups[$aGroup['randomization_group']][] = $aGroup['gid'];
    }
    // Shuffle each group and create a map for old GID => new GID
    foreach ($aRandomGroups as $sGroupName => $aGIDs) {
        $aShuffledIDs = $aGIDs;
        shuffle($aShuffledIDs);
        $aGIDCompleteMap = $aGIDCompleteMap + array_combine($aGIDs, $aShuffledIDs);
    }
    $_SESSION['survey_' . $surveyid]['groupReMap'] = $aGIDCompleteMap;
    $randomized = false;
    // So we can trigger reorder once for group and question randomization
    // Now adjust the grouplist
    if (count($aRandomGroups) > 0 && !$preview) {
        $randomized = true;
        // So we can trigger reorder once for group and question randomization
        // Now adjust the grouplist
        Yii::import('application.helpers.frontend_helper', true);
        // make sure frontend helper is loaded
        UpdateGroupList($surveyid, $_SESSION['survey_' . $surveyid]['s_lang']);
        // ... and the fieldmap
        // First create a fieldmap with GID as key
        foreach ($fieldmap as $aField) {
            if (isset($aField['gid'])) {
                $GroupFieldMap[$aField['gid']][] = $aField;
            } else {
                $GroupFieldMap['other'][] = $aField;
            }
        }
        // swap it
        foreach ($GroupFieldMap as $iOldGid => $fields) {
            $iNewGid = $iOldGid;
            if (isset($aGIDCompleteMap[$iOldGid])) {
                $iNewGid = $aGIDCompleteMap[$iOldGid];
            }
            $newGroupFieldMap[$iNewGid] = $GroupFieldMap[$iNewGid];
        }
        $GroupFieldMap = $newGroupFieldMap;
        // and convert it back to a fieldmap
        unset($fieldmap);
        foreach ($GroupFieldMap as $aGroupFields) {
            foreach ($aGroupFields as $aField) {
                if (isset($aField['fieldname'])) {
                    $fieldmap[$aField['fieldname']] = $aField;
                    // isset() because of the shuffled flag above
                }
            }
        }
        unset($GroupFieldMap);
    }
    // Randomization groups for questions
    // Find all defined randomization groups through question attribute values
    $randomGroups = array();
    if (in_array(Yii::app()->db->getDriverName(), array('mssql', 'sqlsrv', 'dblib'))) {
        $rgquery = "SELECT attr.qid, CAST(value as varchar(255)) as value FROM {{question_attributes}} as attr right join {{questions}} as quests on attr.qid=quests.qid WHERE attribute='random_group' and CAST(value as varchar(255)) <> '' and sid={$surveyid} GROUP BY attr.qid, CAST(value as varchar(255))";
    } else {
        $rgquery = "SELECT attr.qid, value FROM {{question_attributes}} as attr right join {{questions}} as quests on attr.qid=quests.qid WHERE attribute='random_group' and value <> '' and sid={$surveyid} GROUP BY attr.qid, value";
    }
    $rgresult = dbExecuteAssoc($rgquery);
    foreach ($rgresult->readAll() as $rgrow) {
        // Get the question IDs for each randomization group
        $randomGroups[$rgrow['value']][] = $rgrow['qid'];
    }
    // If we have randomization groups set, then lets cycle through each group and
    // replace questions in the group with a randomly chosen one from the same group
    if (count($randomGroups) > 0 && !$preview) {
        $randomized = true;
        // So we can trigger reorder once for group and question randomization
        $copyFieldMap = array();
        $oldQuestOrder = array();
        $newQuestOrder = array();
        $randGroupNames = array();
        foreach ($randomGroups as $key => $value) {
            $oldQuestOrder[$key] = $randomGroups[$key];
            $newQuestOrder[$key] = $oldQuestOrder[$key];
            // We shuffle the question list to get a random key->qid which will be used to swap from the old key
            shuffle($newQuestOrder[$key]);
            $randGroupNames[] = $key;
        }
        // Loop through the fieldmap and swap each question as they come up
        foreach ($fieldmap as $fieldkey => $fieldval) {
            $found = 0;
            foreach ($randomGroups as $gkey => $gval) {
                // We found a qid that is in the randomization group
                if (isset($fieldval['qid']) && in_array($fieldval['qid'], $oldQuestOrder[$gkey])) {
                    // Get the swapped question
                    $idx = array_search($fieldval['qid'], $oldQuestOrder[$gkey]);
                    foreach ($fieldmap as $key => $field) {
                        if (isset($field['qid']) && $field['qid'] == $newQuestOrder[$gkey][$idx]) {
                            $field['random_gid'] = $fieldval['gid'];
                            // It is possible to swap to another group
                            $copyFieldMap[$key] = $field;
                        }
                    }
                    $found = 1;
                    break;
                } else {
                    $found = 2;
                }
            }
            if ($found == 2) {
                $copyFieldMap[$fieldkey] = $fieldval;
            }
            reset($randomGroups);
        }
        $fieldmap = $copyFieldMap;
    }
    if ($randomized === true) {
        // reset the sequencing counts
        $gseq = -1;
        $_gid = -1;
        $qseq = -1;
        $_qid = -1;
        $copyFieldMap = array();
        foreach ($fieldmap as $key => $val) {
            if ($val['gid'] != '') {
                if (isset($val['random_gid'])) {
                    $gid = $val['random_gid'];
                } else {
                    $gid = $val['gid'];
                }
                if ($gid != $_gid) {
                    $_gid = $gid;
                    ++$gseq;
                }
            }
            if ($val['qid'] != '' && $val['qid'] != $_qid) {
                $_qid = $val['qid'];
                ++$qseq;
            }
            if ($val['gid'] != '' && $val['qid'] != '') {
                $val['groupSeq'] = $gseq;
                $val['questionSeq'] = $qseq;
            }
            $copyFieldMap[$key] = $val;
        }
        $fieldmap = $copyFieldMap;
        unset($copyFieldMap);
        $_SESSION['survey_' . $surveyid]['fieldmap-' . $surveyid . $_SESSION['survey_' . $surveyid]['s_lang']] = $fieldmap;
        $_SESSION['survey_' . $surveyid]['fieldmap-' . $surveyid . '-randMaster'] = 'fieldmap-' . $surveyid . $_SESSION['survey_' . $surveyid]['s_lang'];
    }
    // TMSW Condition->Relevance:  don't need hasconditions, or usedinconditions
    $_SESSION['survey_' . $surveyid]['fieldmap'] = $fieldmap;
    foreach ($fieldmap as $field) {
        if (isset($field['qid']) && $field['qid'] != '') {
            $_SESSION['survey_' . $surveyid]['fieldnamesInfo'][$field['fieldname']] = $field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid'];
            $_SESSION['survey_' . $surveyid]['insertarray'][] = $field['fieldname'];
            //fieldarray ARRAY CONTENTS -
            //            [0]=questions.qid,
            //            [1]=fieldname,
            //            [2]=questions.title,
            //            [3]=questions.question
            //                     [4]=questions.type,
            //            [5]=questions.gid,
            //            [6]=questions.mandatory,
            //            [7]=conditionsexist,
            //            [8]=usedinconditions
            //            [8]=usedinconditions
            //            [9]=used in group.php for question count
            //            [10]=new group id for question in randomization group (GroupbyGroup Mode)
            if (!isset($_SESSION['survey_' . $surveyid]['fieldarray'][$field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid']])) {
                //JUST IN CASE : PRECAUTION!
                //following variables are set only if $style=="full" in createFieldMap() in common_helper.
                //so, if $style = "short", set some default values here!
                if (isset($field['title'])) {
                    $title = $field['title'];
                } else {
                    $title = "";
                }
                if (isset($field['question'])) {
                    $question = $field['question'];
                } else {
                    $question = "";
                }
                if (isset($field['mandatory'])) {
                    $mandatory = $field['mandatory'];
                } else {
                    $mandatory = 'N';
                }
                if (isset($field['hasconditions'])) {
                    $hasconditions = $field['hasconditions'];
                } else {
                    $hasconditions = 'N';
                }
                if (isset($field['usedinconditions'])) {
                    $usedinconditions = $field['usedinconditions'];
                } else {
                    $usedinconditions = 'N';
                }
                $_SESSION['survey_' . $surveyid]['fieldarray'][$field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid']] = array($field['qid'], $field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid'], $title, $question, $field['type'], $field['gid'], $mandatory, $hasconditions, $usedinconditions);
            }
            if (isset($field['random_gid'])) {
                $_SESSION['survey_' . $surveyid]['fieldarray'][$field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid']][10] = $field['random_gid'];
            }
        }
    }
    // Prefill questions/answers from command line params
    $reservedGetValues = array('token', 'sid', 'gid', 'qid', 'lang', 'newtest', 'action');
    $startingValues = array();
    if (isset($_GET)) {
        foreach ($_GET as $k => $v) {
            if (!in_array($k, $reservedGetValues) && isset($_SESSION['survey_' . $surveyid]['fieldmap'][$k])) {
                $startingValues[$k] = $v;
            } else {
                // Search question codes to use those for prefilling.
                foreach ($_SESSION['survey_' . $surveyid]['fieldmap'] as $sgqa => $details) {
                    if ($details['title'] == $k) {
                        $startingValues[$sgqa] = $v;
                    }
                }
            }
        }
    }
    $_SESSION['survey_' . $surveyid]['startingValues'] = $startingValues;
    if (isset($_SESSION['survey_' . $surveyid]['fieldarray'])) {
        $_SESSION['survey_' . $surveyid]['fieldarray'] = array_values($_SESSION['survey_' . $surveyid]['fieldarray']);
    }
    //Check if a passthru label and value have been included in the query url
    $oResult = SurveyURLParameter::model()->getParametersForSurvey($surveyid);
    foreach ($oResult->readAll() as $aRow) {
        if (isset($_GET[$aRow['parameter']]) && !$preview) {
            $_SESSION['survey_' . $surveyid]['urlparams'][$aRow['parameter']] = $_GET[$aRow['parameter']];
            if ($aRow['targetqid'] != '') {
                foreach ($fieldmap as $sFieldname => $aField) {
                    if ($aRow['targetsqid'] != '') {
                        if ($aField['qid'] == $aRow['targetqid'] && $aField['sqid'] == $aRow['targetsqid']) {
                            $_SESSION['survey_' . $surveyid]['startingValues'][$sFieldname] = $_GET[$aRow['parameter']];
                            $_SESSION['survey_' . $surveyid]['startingValues'][$aRow['parameter']] = $_GET[$aRow['parameter']];
                        }
                    } else {
                        if ($aField['qid'] == $aRow['targetqid']) {
                            $_SESSION['survey_' . $surveyid]['startingValues'][$sFieldname] = $_GET[$aRow['parameter']];
                            $_SESSION['survey_' . $surveyid]['startingValues'][$aRow['parameter']] = $_GET[$aRow['parameter']];
                        }
                    }
                }
            }
        }
    }
    Yii::trace('end', 'survey.buildsurveysession');
}
コード例 #4
0
 /**
  * TSV survey definition in format readable by TSVSurveyImport
  * one line each per group, question, sub-question, and answer
  * does not use SGQA naming at all.
  * @param type $sid
  * @return type
  */
 public static function &TSVSurveyExport($sid)
 {
     $fields = array('class', 'type/scale', 'name', 'relevance', 'text', 'help', 'language', 'validation', 'mandatory', 'other', 'default', 'same_default', 'allowed_filetypes', 'alphasort', 'answer_width', 'array_filter', 'array_filter_exclude', 'array_filter_style', 'assessment_value', 'category_separator', 'choice_title', 'code_filter', 'commented_checkbox', 'commented_checkbox_auto', 'date_format', 'date_max', 'date_min', 'display_columns', 'display_rows', 'dropdown_dates', 'dropdown_dates_minute_step', 'dropdown_dates_month_style', 'dropdown_prefix', 'dropdown_prepostfix', 'dropdown_separators', 'dropdown_size', 'dualscale_headerA', 'dualscale_headerB', 'em_validation_q', 'em_validation_q_tip', 'em_validation_sq', 'em_validation_sq_tip', 'equals_num_value', 'exclude_all_others', 'exclude_all_others_auto', 'hidden', 'hide_tip', 'input_boxes', 'location_city', 'location_country', 'location_defaultcoordinates', 'location_mapheight', 'location_mapservice', 'location_mapwidth', 'location_mapzoom', 'location_nodefaultfromip', 'location_postal', 'location_state', 'max_answers', 'max_filesize', 'max_num_of_files', 'max_num_value', 'max_num_value_n', 'maximum_chars', 'min_answers', 'min_num_of_files', 'min_num_value', 'min_num_value_n', 'multiflexible_checkbox', 'multiflexible_max', 'multiflexible_min', 'multiflexible_step', 'num_value_int_only', 'numbers_only', 'other_comment_mandatory', 'other_numbers_only', 'other_replace_text', 'page_break', 'parent_order', 'prefix', 'printable_help', 'public_statistics', 'random_group', 'random_order', 'rank_title', 'repeat_headings', 'reverse', 'samechoiceheight', 'samelistheight', 'scale_export', 'show_comment', 'show_grand_total', 'show_title', 'show_totals', 'showpopups', 'slider_accuracy', 'slider_default', 'slider_layout', 'slider_max', 'slider_middlestart', 'slider_min', 'slider_rating', 'slider_reset', 'slider_separator', 'slider_showminmax', 'statistics_graphtype', 'statistics_showgraph', 'statistics_showmap', 'suffix', 'text_input_width', 'time_limit', 'time_limit_action', 'time_limit_countdown_message', 'time_limit_disable_next', 'time_limit_disable_prev', 'time_limit_message', 'time_limit_message_delay', 'time_limit_message_style', 'time_limit_timer_style', 'time_limit_warning', 'time_limit_warning_2', 'time_limit_warning_2_display_time', 'time_limit_warning_2_message', 'time_limit_warning_2_style', 'time_limit_warning_display_time', 'time_limit_warning_message', 'time_limit_warning_style', 'thousands_separator', 'use_dropdown');
     $rows = array();
     $primarylang = 'en';
     $otherlangs = '';
     $langs = array();
     // Export survey-level information
     $query = "select * from {{surveys}} where sid = " . $sid;
     $data = dbExecuteAssoc($query);
     foreach ($data->readAll() as $r) {
         foreach ($r as $key => $value) {
             if ($value != '') {
                 $row['class'] = 'S';
                 $row['name'] = $key;
                 $row['text'] = $value;
                 $rows[] = $row;
             }
             if ($key == 'language') {
                 $primarylang = $value;
             }
             if ($key == 'additional_languages') {
                 $otherlangs = $value;
             }
         }
     }
     $langs = explode(' ', $primarylang . ' ' . $otherlangs);
     $langs = array_unique($langs);
     // Export survey language settings
     $query = "select * from {{surveys_languagesettings}} where surveyls_survey_id = " . $sid;
     $data = dbExecuteAssoc($query);
     foreach ($data->readAll() as $r) {
         $_lang = $r['surveyls_language'];
         foreach ($r as $key => $value) {
             if ($value != '' && $key != 'surveyls_language' && $key != 'surveyls_survey_id') {
                 $row['class'] = 'SL';
                 $row['name'] = $key;
                 $row['text'] = $value;
                 $row['language'] = $_lang;
                 $rows[] = $row;
             }
         }
     }
     $surveyinfo = getSurveyInfo($sid);
     $assessments = false;
     if (isset($surveyinfo['assessments']) && $surveyinfo['assessments'] == 'Y') {
         $assessments = true;
     }
     foreach ($langs as $lang) {
         if (trim($lang) == '') {
             continue;
         }
         SetSurveyLanguage($sid, $lang);
         LimeExpressionManager::StartSurvey($sid, 'survey', array('sgqaNaming' => 'N', 'assessments' => $assessments), true);
         $moveResult = LimeExpressionManager::NavigateForwards();
         $LEM =& LimeExpressionManager::singleton();
         if (is_null($moveResult) || is_null($LEM->currentQset) || count($LEM->currentQset) == 0) {
             continue;
         }
         $_gseq = -1;
         foreach ($LEM->currentQset as $q) {
             $gseq = $q['info']['gseq'];
             $gid = $q['info']['gid'];
             $qid = $q['info']['qid'];
             //////
             // SHOW GROUP-LEVEL INFO
             //////
             if ($gseq != $_gseq) {
                 $_gseq = $gseq;
                 $ginfo = $LEM->gseq2info[$gseq];
                 // if relevance equation is using SGQA coding, convert to qcoding
                 $grelevance = $ginfo['grelevance'] == '' ? 1 : $ginfo['grelevance'];
                 $LEM->em->ProcessBooleanExpression($grelevance, $gseq, 0);
                 // $qseq
                 $grelevance = trim(strip_tags($LEM->em->GetPrettyPrintString()));
                 $gtext = trim($ginfo['description']) == '' ? '' : $ginfo['description'];
                 $row = array();
                 $row['class'] = 'G';
                 //create a group code to allow proper importing of multi-lang survey TSVs
                 $row['type/scale'] = 'G' . $gseq;
                 $row['name'] = $ginfo['group_name'];
                 $row['relevance'] = $grelevance;
                 $row['text'] = $gtext;
                 $row['language'] = $lang;
                 $row['random_group'] = $ginfo['randomization_group'];
                 $rows[] = $row;
             }
             //////
             // SHOW QUESTION-LEVEL INFO
             //////
             $row = array();
             $mandatory = $q['info']['mandatory'] == 'Y' ? 'Y' : '';
             $type = $q['info']['type'];
             $sgqas = explode('|', $q['sgqa']);
             if (count($sgqas) == 1 && !is_null($q['info']['default'])) {
                 $default = $q['info']['default'];
             } else {
                 $default = '';
             }
             $qtext = $q['info']['qtext'] != '' ? $q['info']['qtext'] : '';
             $help = $q['info']['help'] != '' ? $q['info']['help'] : '';
             //////
             // SHOW QUESTION ATTRIBUTES THAT ARE PROCESSED BY EM
             //////
             if (isset($LEM->qattr[$qid]) && count($LEM->qattr[$qid]) > 0) {
                 foreach ($LEM->qattr[$qid] as $key => $value) {
                     if (is_null($value) || trim($value) == '') {
                         continue;
                     }
                     switch ($key) {
                         default:
                         case 'exclude_all_others':
                         case 'exclude_all_others_auto':
                         case 'hidden':
                             if ($value == false || $value == '0') {
                                 $value = NULL;
                                 // so can skip this one - just using continue here doesn't work.
                             }
                             break;
                         case 'relevance':
                             $value = NULL;
                             // means an outdate database structure
                             break;
                     }
                     if (is_null($value) || trim($value) == '') {
                         continue;
                         // since continuing from within a switch statement doesn't work
                     }
                     $row[$key] = $value;
                 }
             }
             // if relevance equation is using SGQA coding, convert to qcoding
             $relevanceEqn = $q['info']['relevance'] == '' ? 1 : $q['info']['relevance'];
             $LEM->em->ProcessBooleanExpression($relevanceEqn, $gseq, $q['info']['qseq']);
             // $qseq
             $relevanceEqn = trim(strip_tags($LEM->em->GetPrettyPrintString()));
             $rootVarName = $q['info']['rootVarName'];
             $preg = '';
             if (isset($LEM->q2subqInfo[$q['info']['qid']]['preg'])) {
                 $preg = $LEM->q2subqInfo[$q['info']['qid']]['preg'];
                 if (is_null($preg)) {
                     $preg = '';
                 }
             }
             $row['class'] = 'Q';
             $row['type/scale'] = $type;
             $row['name'] = $rootVarName;
             $row['relevance'] = $relevanceEqn;
             $row['text'] = $qtext;
             $row['help'] = $help;
             $row['language'] = $lang;
             $row['validation'] = $preg;
             $row['mandatory'] = $mandatory;
             $row['other'] = $q['info']['other'];
             $row['default'] = $default;
             $row['same_default'] = 1;
             // TODO - need this: $q['info']['same_default'];
             $rows[] = $row;
             //////
             // SHOW ALL SUB-QUESTIONS
             //////
             $sawThis = array();
             // array of rowdivids already seen so only show them once
             foreach ($sgqas as $sgqa) {
                 if ($LEM->knownVars[$sgqa]['qcode'] == $rootVarName) {
                     continue;
                     // so don't show the main question as a sub-question too
                 }
                 $rowdivid = $sgqa;
                 $varName = $LEM->knownVars[$sgqa]['qcode'];
                 // if SQrelevance equation is using SGQA coding, convert to qcoding
                 $SQrelevance = $LEM->knownVars[$sgqa]['SQrelevance'] == '' ? 1 : $LEM->knownVars[$sgqa]['SQrelevance'];
                 $LEM->em->ProcessBooleanExpression($SQrelevance, $gseq, $q['info']['qseq']);
                 $SQrelevance = trim(strip_tags($LEM->em->GetPrettyPrintString()));
                 switch ($q['info']['type']) {
                     case '1':
                         if (preg_match('/#1$/', $sgqa)) {
                             $rowdivid = NULL;
                             // so that doesn't show same message for second scale
                         } else {
                             $rowdivid = substr($sgqa, 0, -2);
                             // strip suffix
                             $varName = substr($LEM->knownVars[$sgqa]['qcode'], 0, -2);
                         }
                         break;
                     case 'P':
                         if (preg_match('/comment$/', $sgqa)) {
                             $rowdivid = NULL;
                         }
                         break;
                     case ':':
                     case ';':
                         $_rowdivid = $LEM->knownVars[$sgqa]['rowdivid'];
                         if (isset($sawThis[$qid . '~' . $_rowdivid])) {
                             $rowdivid = NULL;
                             // so don't show again
                         } else {
                             $sawThis[$qid . '~' . $_rowdivid] = true;
                             $rowdivid = $_rowdivid;
                             $sgqa_len = strlen($sid . 'X' . $gid . 'X' . $qid);
                             $varName = $rootVarName . '_' . substr($_rowdivid, $sgqa_len);
                         }
                         break;
                 }
                 if (is_null($rowdivid)) {
                     continue;
                 }
                 $sgqaInfo = $LEM->knownVars[$sgqa];
                 $subqText = $sgqaInfo['subqtext'];
                 if (isset($sgqaInfo['default'])) {
                     $default = $sgqaInfo['default'];
                 } else {
                     $default = '';
                 }
                 $row = array();
                 $row['class'] = 'SQ';
                 $row['type/scale'] = 0;
                 $row['name'] = substr($varName, strlen($rootVarName) + 1);
                 $row['relevance'] = $SQrelevance;
                 $row['text'] = $subqText;
                 $row['language'] = $lang;
                 $row['default'] = $default;
                 $rows[] = $row;
             }
             //////
             // SHOW ANSWER OPTIONS FOR ENUMERATED LISTS, AND FOR MULTIFLEXI
             //////
             if (isset($LEM->qans[$qid]) || isset($LEM->multiflexiAnswers[$qid])) {
                 $_scale = -1;
                 if (isset($LEM->multiflexiAnswers[$qid])) {
                     $ansList = $LEM->multiflexiAnswers[$qid];
                 } else {
                     $ansList = $LEM->qans[$qid];
                 }
                 foreach ($ansList as $ans => $value) {
                     $ansInfo = explode('~', $ans);
                     $valParts = explode('|', $value);
                     $valInfo[0] = array_shift($valParts);
                     $valInfo[1] = implode('|', $valParts);
                     if ($_scale != $ansInfo[0]) {
                         $_scale = $ansInfo[0];
                     }
                     $row = array();
                     if ($type == ':' || $type == ';') {
                         $row['class'] = 'SQ';
                     } else {
                         $row['class'] = 'A';
                     }
                     $row['type/scale'] = $_scale;
                     $row['name'] = $ansInfo[1];
                     $row['relevance'] = $assessments == true ? $valInfo[0] : '';
                     $row['text'] = $valInfo[1];
                     $row['language'] = $lang;
                     $rows[] = $row;
                 }
             }
         }
     }
     // Now generate the array out output data
     $out = array();
     $out[] = $fields;
     foreach ($rows as $row) {
         $tsv = array();
         foreach ($fields as $field) {
             $val = isset($row[$field]) ? $row[$field] : '';
             $tsv[] = $val;
         }
         $out[] = $tsv;
     }
     return $out;
 }
コード例 #5
0
 /**
  * Show printable survey
  */
 function index($surveyid, $lang = null)
 {
     $surveyid = sanitize_int($surveyid);
     if (!Permission::model()->hasSurveyPermission($surveyid, 'surveycontent', 'read')) {
         $aData['surveyid'] = $surveyid;
         App()->getClientScript()->registerPackage('jquery-superfish');
         $message['title'] = gT('Access denied!');
         $message['message'] = gT('You do not have sufficient rights to access this page.');
         $message['class'] = "error";
         $this->_renderWrappedTemplate('survey', array("message" => $message), $aData);
     } else {
         $aSurveyInfo = getSurveyInfo($surveyid, $lang);
         if (!$aSurveyInfo) {
             $this->getController()->error('Invalid survey ID');
         }
         SetSurveyLanguage($surveyid, $lang);
         $sLanguageCode = App()->language;
         $templatename = $aSurveyInfo['template'];
         $welcome = $aSurveyInfo['surveyls_welcometext'];
         $end = $aSurveyInfo['surveyls_endtext'];
         $surveyname = $aSurveyInfo['surveyls_title'];
         $surveydesc = $aSurveyInfo['surveyls_description'];
         $surveyactive = $aSurveyInfo['active'];
         $surveytable = "{{survey_" . $aSurveyInfo['sid'] . "}}";
         $surveyexpirydate = $aSurveyInfo['expires'];
         $surveyfaxto = $aSurveyInfo['faxto'];
         $dateformattype = $aSurveyInfo['surveyls_dateformat'];
         Yii::app()->loadHelper('surveytranslator');
         if (!is_null($surveyexpirydate)) {
             $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;
             }
             sprintf(gT("Please submit by %s"), $surveyexpirydate);
         } else {
             $surveyexpirydate = '';
         }
         //Fix $templatename : control if print_survey.pstpl exist
         if (is_file(getTemplatePath($templatename) . DIRECTORY_SEPARATOR . 'print_survey.pstpl')) {
             $templatename = $templatename;
             // Change nothing
         } elseif (is_file(getTemplatePath(Yii::app()->getConfig("defaulttemplate")) . DIRECTORY_SEPARATOR . 'print_survey.pstpl')) {
             $templatename = Yii::app()->getConfig("defaulttemplate");
         } else {
             $templatename = "default";
         }
         $sFullTemplatePath = getTemplatePath($templatename) . DIRECTORY_SEPARATOR;
         $sFullTemplateUrl = getTemplateURL($templatename) . "/";
         define('PRINT_TEMPLATE_DIR', $sFullTemplatePath, true);
         define('PRINT_TEMPLATE_URL', $sFullTemplateUrl, true);
         LimeExpressionManager::StartSurvey($surveyid, 'survey', NULL, false, LEM_PRETTY_PRINT_ALL_SYNTAX);
         $moveResult = LimeExpressionManager::NavigateForwards();
         $condition = "sid = '{$surveyid}' AND language = '{$sLanguageCode}'";
         $degresult = QuestionGroup::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 />[" . gT('Database') . " " . 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' => gT("Submit Your Survey."), 'SUBMIT_BY' => $surveyexpirydate, 'THANKS' => 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'] = gT("Please fax your completed survey to:") . " {$surveyfaxto}";
         }
         $total_questions = 0;
         $mapquestionsNumbers = array();
         $answertext = '';
         // otherwise can throw an error on line 1617
         $fieldmap = createFieldMap($surveyid, 'full', false, false, $sLanguageCode);
         // =========================================================
         // START doin the business:
         foreach ($degresult->readAll() as $degrow) {
             // ---------------------------------------------------
             // START doing groups
             $deqresult = Question::model()->getQuestions($surveyid, $degrow['gid'], $sLanguageCode, 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;
             $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 = '';
                 $sExplanation = '';
                 //reset conditions explanation
                 $s = 0;
                 // TMSW Condition->Relevance:  show relevance instead of this whole section to create $explanation
                 $scenarioresult = Condition::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) {
                         $sExplanation .= '<p class="scenario">' . " -------- Scenario {$scenariorow['scenario']} --------</p>\n\n";
                     }
                     if ($s > 0) {
                         $sExplanation .= '<p class="scenario">' . ' -------- ' . gT("or") . " Scenario {$scenariorow['scenario']} --------</p>\n\n";
                     }
                     $x = 0;
                     $conditions1 = "qid={$deqrow['qid']} AND scenario={$scenariorow['scenario']}";
                     $distinctresult = Condition::model()->getSomeConditions(array('cqid', 'method', 'cfieldname'), $conditions1, array('cqid'), array('cqid', 'method', 'cfieldname'));
                     //Loop through each condition for a particular scenario.
                     foreach ($distinctresult->readAll() as $distinctrow) {
                         $condition = "qid = '{$distinctrow['cqid']}' AND parent_qid = 0 AND language = '{$sLanguageCode}'";
                         $subresult = Question::model()->find($condition);
                         if ($x > 0) {
                             $sExplanation .= ' <em class="scenario-and-separator">' . gT('and') . '</em> ';
                         }
                         if (trim($distinctrow['method']) == '') {
                             $distinctrow['method'] = '==';
                         }
                         if ($distinctrow['cqid']) {
                             // cqid != 0  ==> previous answer match
                             if ($distinctrow['method'] == '==') {
                                 $sExplanation .= gT("Answer was") . " ";
                             } elseif ($distinctrow['method'] == '!=') {
                                 $sExplanation .= gT("Answer was NOT") . " ";
                             } elseif ($distinctrow['method'] == '<') {
                                 $sExplanation .= gT("Answer was less than") . " ";
                             } elseif ($distinctrow['method'] == '<=') {
                                 $sExplanation .= gT("Answer was less than or equal to") . " ";
                             } elseif ($distinctrow['method'] == '>=') {
                                 $sExplanation .= gT("Answer was greater than or equal to") . " ";
                             } elseif ($distinctrow['method'] == '>') {
                                 $sExplanation .= gT("Answer was greater than") . " ";
                             } elseif ($distinctrow['method'] == 'RX') {
                                 $sExplanation .= gT("Answer matched (regexp)") . " ";
                             } else {
                                 $sExplanation .= gT("Answer was") . " ";
                             }
                         }
                         if (!$distinctrow['cqid']) {
                             // cqid == 0  ==> token attribute match
                             $tokenData = getTokenFieldsAndNames($surveyid);
                             preg_match('/^{TOKEN:([^}]*)}$/', $distinctrow['cfieldname'], $extractedTokenAttr);
                             $sExplanation .= "Your " . $tokenData[strtolower($extractedTokenAttr[1])]['description'] . " ";
                             if ($distinctrow['method'] == '==') {
                                 $sExplanation .= gT("is") . " ";
                             } elseif ($distinctrow['method'] == '!=') {
                                 $sExplanation .= gT("is NOT") . " ";
                             } elseif ($distinctrow['method'] == '<') {
                                 $sExplanation .= gT("is less than") . " ";
                             } elseif ($distinctrow['method'] == '<=') {
                                 $sExplanation .= gT("is less than or equal to") . " ";
                             } elseif ($distinctrow['method'] == '>=') {
                                 $sExplanation .= gT("is greater than or equal to") . " ";
                             } elseif ($distinctrow['method'] == '>') {
                                 $sExplanation .= gT("is greater than") . " ";
                             } elseif ($distinctrow['method'] == 'RX') {
                                 $sExplanation .= gT("is matched (regexp)") . " ";
                             } else {
                                 $sExplanation .= gT("is") . " ";
                             }
                             $answer_section = ' ' . $distinctrow['value'] . ' ';
                         }
                         $conresult = Condition::model()->getConditionsQuestions($distinctrow['cqid'], $deqrow['qid'], $scenariorow['scenario'], $sLanguageCode);
                         $conditions = array();
                         foreach ($conresult->readAll() as $conrow) {
                             $postans = "";
                             $value = $conrow['value'];
                             switch ($conrow['type']) {
                                 case "Y":
                                     switch ($conrow['value']) {
                                         case "Y":
                                             $conditions[] = gT("Yes");
                                             break;
                                         case "N":
                                             $conditions[] = gT("No");
                                             break;
                                     }
                                     break;
                                 case "G":
                                     switch ($conrow['value']) {
                                         case "M":
                                             $conditions[] = gT("Male");
                                             break;
                                         case "F":
                                             $conditions[] = gT("Female");
                                             break;
                                     }
                                     // switch
                                     break;
                                 case "A":
                                 case "B":
                                 case ":":
                                 case ";":
                                 case "5":
                                     $conditions[] = $conrow['value'];
                                     break;
                                 case "C":
                                     switch ($conrow['value']) {
                                         case "Y":
                                             $conditions[] = gT("Yes");
                                             break;
                                         case "U":
                                             $conditions[] = gT("Uncertain");
                                             break;
                                         case "N":
                                             $conditions[] = gT("No");
                                             break;
                                     }
                                     // switch
                                     break;
                                 case "E":
                                     switch ($conrow['value']) {
                                         case "I":
                                             $conditions[] = gT("Increase");
                                             break;
                                         case "D":
                                             $conditions[] = gT("Decrease");
                                             break;
                                         case "S":
                                             $conditions[] = 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='{$sLanguageCode}'";
                                         $fresult = Answer::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='{$sLanguageCode}'";
                                         $fresult = Answer::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='{$sLanguageCode}'";
                                     $ansresult = Answer::model()->findAll($condition);
                                     foreach ($ansresult as $ansrow) {
                                         $conditions[] = $ansrow['answer'];
                                     }
                                     if ($conrow['value'] == "-oth-") {
                                         $conditions[] = gT("Other");
                                     }
                                     $conditions = array_unique($conditions);
                                     break;
                                 case "M":
                                 case "P":
                                     $condition = " parent_qid='{$conrow['cqid']}' AND title='{$conrow['value']}' AND language='{$sLanguageCode}'";
                                     $ansresult = Question::model()->findAll($condition);
                                     foreach ($ansresult as $ansrow) {
                                         $conditions[] = $ansrow['question'];
                                     }
                                     $conditions = array_unique($conditions);
                                     break;
                                 case "N":
                                 case "K":
                                     $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='{$sLanguageCode}'";
                                     $fresult = Answer::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='{$sLanguageCode}'";
                                     $ansresult = Question::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='{$sLanguageCode}'";
                                     $ansresult = Question::model()->findAll($condition);
                                     $cqidattributes = getQuestionAttributeValues($conrow['cqid']);
                                     if ($labelIndex == 0) {
                                         if (trim($cqidattributes['dualscale_headerA'][$sLanguageCode]) != '') {
                                             $header = gT($cqidattributes['dualscale_headerA'][$sLanguageCode]);
                                         } else {
                                             $header = '1';
                                         }
                                     } elseif ($labelIndex == 1) {
                                         if (trim($cqidattributes['dualscale_headerB'][$sLanguageCode]) != '') {
                                             $header = gT($cqidattributes['dualscale_headerB'][$sLanguageCode]);
                                         } else {
                                             $header = '2';
                                         }
                                     }
                                     foreach ($ansresult as $ansrow) {
                                         $answer_section = " (" . $ansrow->question . " " . sprintf(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='{$sLanguageCode}'";
                                     $ansresult = Question::model()->findAll($condition);
                                     foreach ($ansresult as $ansrow) {
                                         $condition = "qid = '{$conrow['cqid']}' AND code = '{$conrow['value']}' AND language= '{$sLanguageCode}'";
                                         $fresult = Answer::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 = " (" . gT("RANK") . " {$rankid})";
                                     break;
                                 default:
                                     // nothing to add
                                     break;
                             }
                         }
                         if (count($conditions) > 1) {
                             $sExplanation .= "'" . implode("' <em class='scenario-or-separator'>" . gT("or") . "</em> '", $conditions) . "'";
                         } elseif (count($conditions) == 1) {
                             $sExplanation .= "'" . $conditions[0] . "'";
                         }
                         unset($conditions);
                         // Following line commented out because answer_section  was lost, but is required for some question types
                         //$explanation .= " ".gT("to question")." '".$mapquestionsNumbers[$distinctrow['cqid']]."' $answer_section ";
                         if ($distinctrow['cqid']) {
                             $sExplanation .= " <span class='scenario-at-separator'>" . gT("at question") . "</span> '" . $mapquestionsNumbers[$distinctrow['cqid']] . " [" . $subresult['title'] . "]' (" . strip_tags($subresult['question']) . "{$answer_section})";
                         } else {
                             $sExplanation .= " " . $distinctrow['value'];
                         }
                         //$distinctrow
                         $x++;
                     }
                     $s++;
                 }
                 $qinfo = LimeExpressionManager::GetQuestionStatus($deqrow['qid']);
                 $relevance = trim($qinfo['info']['relevance']);
                 $sEquation = $qinfo['relEqn'];
                 if (trim($relevance) != '' && trim($relevance) != '1') {
                     if (isset($qidattributes['printable_help'][$sLanguageCode]) && $qidattributes['printable_help'][$sLanguageCode] != '') {
                         $sExplanation = $qidattributes['printable_help'][$sLanguageCode];
                     } elseif ($sExplanation == '') {
                         $sExplanation = $sEquation;
                         $sEquation = '&nbsp;';
                         // No need to show it twice
                     }
                     $sExplanation = "<b>" . gT('Only answer this question if the following conditions are met:') . "</b><br/> " . $sExplanation;
                     if (Yii::app()->getConfig('showrelevance')) {
                         $sExplanation .= "<span class='printable_equation'><br>" . $sEquation . "</span>";
                     }
                 } else {
                     $sExplanation = '';
                 }
                 ++$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 />" . gT("ID:") . " {$fieldname} <br />" . 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' => $sExplanation, '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' => '');
                 $showqnumcode = Yii::app()->getConfig('showqnumcode');
                 if ($showqnumcode == 'choose' && ($aSurveyInfo['showqnumcode'] == 'N' || $aSurveyInfo['showqnumcode'] == 'X') || $showqnumcode == 'number' || $showqnumcode == 'none') {
                     $question['QUESTION_CODE'] = '';
                 }
                 if ($showqnumcode == 'choose' && ($aSurveyInfo['showqnumcode'] == 'C' || $aSurveyInfo['showqnumcode'] == 'X') || $showqnumcode == 'code' || $showqnumcode == 'none') {
                     $question['QUESTION_NUMBER'] = '';
                 }
                 if ($question['QUESTION_TYPE_HELP'] != "") {
                     $question['QUESTION_TYPE_HELP'] .= "<br />\n";
                 }
                 if ($deqrow['mandatory'] == 'Y') {
                     $question['QUESTION_MANDATORY'] = gT('*');
                     $question['QUESTION_CLASS'] .= ' mandatory';
                 }
                 //DIFFERENT TYPES OF DATA FIELD HERE
                 if ($deqrow['help']) {
                     $question['QUESTIONHELP'] = $deqrow['help'];
                 }
                 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'] .= gT('Please choose *only one* of the following:');
                         $question['ANSWER'] .= "\n\t<ul>\n";
                         for ($i = 1; $i <= 5; $i++) {
                             $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";
                         }
                         $question['ANSWER'] .= "\t</ul>\n";
                         break;
                         // ==================================================================
                     // ==================================================================
                     case "D":
                         //DATE
                         $question['QUESTION_TYPE_HELP'] .= gT('Please enter a date:');
                         $question['ANSWER'] .= "\t" . self::_input_type_image('text', $question['QUESTION_TYPE_HELP'], 30, 1);
                         break;
                         // ==================================================================
                     // ==================================================================
                     case "G":
                         //GENDER
                         $question['QUESTION_TYPE_HELP'] .= 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', gT("Female")) . "\n\t\t\t" . gT("Female") . " " . self::_addsgqacode("(F)") . "\n\t\t</li>\n";
                         $question['ANSWER'] .= "\t\t<li>\n\t\t\t" . self::_input_type_image('radio', gT("Male")) . "\n\t\t\t" . gT("Male") . " " . self::_addsgqacode("(M)") . "\n\t\t</li>\n";
                         $question['ANSWER'] .= "\t</ul>\n";
                         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'] .= gT("Please choose *only one* of the following:");
                         $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $sLanguageCode, $surveyid);
                         $dearesult = Answer::model()->getAllRecords(" qid='{$deqrow['qid']}' AND language='{$sLanguageCode}' ", 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'];
                             }
                             ++$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"][$sLanguageCode]) == '') {
                                 $qidattributes["other_replace_text"][$sLanguageCode] = gT("Other");
                             }
                             //                    $printablesurveyoutput .="\t".$wrapper['item-start']."\t\t".self::_input_type_image('radio' , gT("Other"))."\n\t\t\t".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', gT($qidattributes["other_replace_text"][$sLanguageCode])) . ' ' . gT($qidattributes["other_replace_text"][$sLanguageCode]) . 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'];
                         }
                         $question['ANSWER'] .= $wrapper['whole-end'];
                         //Let's break the presentation into columns.
                         break;
                         // ==================================================================
                     // ==================================================================
                     case "O":
                         //LIST WITH COMMENT
                         $question['QUESTION_TYPE_HELP'] .= gT("Please choose *only one* of the following:");
                         $dearesult = Answer::model()->getAllRecords(" qid='{$deqrow['qid']}' AND language='{$sLanguageCode}'", 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";
                         }
                         $question['ANSWER'] .= "\t</ul>\n";
                         $question['ANSWER'] .= "\t<p class=\"comment\">\n\t\t" . gT("Make a comment on your choice here:") . "\n";
                         $question['ANSWER'] .= "\t\t" . self::_input_type_image('textarea', 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";
                         break;
                         // ==================================================================
                     // ==================================================================
                     case "R":
                         //RANKING Type Question
                         $rearesult = Answer::model()->getAllRecords(" qid='{$deqrow['qid']}' AND language='{$sLanguageCode}'", array('sortorder', 'answer'));
                         $rearesult = $rearesult->readAll();
                         $reacount = count($rearesult);
                         $question['QUESTION_TYPE_HELP'] .= gT("Please number each box in order of preference from 1 to") . " {$reacount}";
                         $question['QUESTION_TYPE_HELP'] .= self::_min_max_answers_help($qidattributes, $sLanguageCode, $surveyid);
                         $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";
                         }
                         $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'] .= gT("Please choose *all* that apply:");
                         $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $sLanguageCode, $surveyid);
                         $mearesult = Question::model()->getAllRecords(" parent_qid='{$deqrow['qid']}' AND language='{$sLanguageCode}' ", 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'];
                             ++$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'][$sLanguageCode]) == '') {
                                 $qidattributes["other_replace_text"][$sLanguageCode] = "Other";
                             }
                             if (!isset($mearow['answer'])) {
                                 $mearow['answer'] = "";
                             }
                             $question['ANSWER'] .= $wrapper['item-start-other'] . self::_input_type_image('checkbox', $mearow['answer']) . gT($qidattributes["other_replace_text"][$sLanguageCode]) . ":\n\t\t" . self::_input_type_image('other') . self::_addsgqacode(" (" . $fieldname . "other) ") . $wrapper['item-end'];
                         }
                         $question['ANSWER'] .= $wrapper['whole-end'];
                         //                }
                         break;
                         // ==================================================================
                     // ==================================================================
                     case "P":
                         //Multiple choice with comments
                         $question['QUESTION_TYPE_HELP'] .= gT("Please choose all that apply and provide a comment:");
                         $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $sLanguageCode, $surveyid);
                         $mearesult = Question::model()->getAllRecords("parent_qid='{$deqrow['qid']}'  AND language='{$sLanguageCode}'", array('question_order'));
                         //                $printablesurveyoutput .="\t\t\t<u>".gT("Please choose all that apply and provide a comment:")."</u><br />\n";
                         $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";
                             $j++;
                         }
                         if ($deqrow['other'] == "Y") {
                             $question['ANSWER'] .= "\t<li class=\"other\">\n\t\t<div class=\"other-replacetext\">" . 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";
                             $j++;
                         }
                         $question['ANSWER'] = "\n<ul>\n" . $question['ANSWER'] . "</ul>\n";
                         break;
                         // ==================================================================
                     // ==================================================================
                     case "Q":
                         //MULTIPLE SHORT TEXT
                         $width = 60;
                         // ==================================================================
                     // ==================================================================
                     case "K":
                         //MULTIPLE NUMERICAL
                         $question['QUESTION_TYPE_HELP'] = "";
                         $width = isset($width) ? $width : 16;
                         //                            if (!empty($qidattributes['equals_num_value']))
                         //                            {
                         //                                $question['QUESTION_TYPE_HELP'] .= "* ".sprintf(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(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(gT('Total of all entries must be at least %s'),$qidattributes['min_num_value'])."<br />\n";
                         //                            }
                         $question['QUESTION_TYPE_HELP'] .= gT("Please write your answer(s) here:");
                         $longest_string = 0;
                         $mearesult = Question::model()->getAllRecords("parent_qid='{$deqrow['qid']}' AND language='{$sLanguageCode}'", array('question_order'));
                         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";
                         }
                         $question['ANSWER'] = "\n<ul>\n" . $question['ANSWER'] . "</ul>\n";
                         break;
                         // ==================================================================
                     // ==================================================================
                     case "S":
                         //SHORT TEXT
                         $question['QUESTION_TYPE_HELP'] .= gT("Please write your answer here:");
                         $question['ANSWER'] = self::_input_type_image('text', $question['QUESTION_TYPE_HELP'], 50);
                         break;
                         // ==================================================================
                     // ==================================================================
                     case "T":
                         //LONG TEXT
                         $question['QUESTION_TYPE_HELP'] .= gT("Please write your answer here:");
                         $question['ANSWER'] = self::_input_type_image('textarea', $question['QUESTION_TYPE_HELP'], '100%', 8);
                         break;
                         // ==================================================================
                     // ==================================================================
                     case "U":
                         //HUGE TEXT
                         $question['QUESTION_TYPE_HELP'] .= gT("Please write your answer here:");
                         $question['ANSWER'] = self::_input_type_image('textarea', $question['QUESTION_TYPE_HELP'], '100%', 30);
                         break;
                         // ==================================================================
                     // ==================================================================
                     case "N":
                         //NUMERICAL
                         $prefix = "";
                         $suffix = "";
                         if ($qidattributes['prefix'][$sLanguageCode] != "") {
                             $prefix = $qidattributes['prefix'][$sLanguageCode];
                         }
                         if ($qidattributes['suffix'][$sLanguageCode] != "") {
                             $suffix = $qidattributes['suffix'][$sLanguageCode];
                         }
                         $question['QUESTION_TYPE_HELP'] .= 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>";
                         break;
                         // ==================================================================
                     // ==================================================================
                     case "Y":
                         //YES/NO
                         $question['QUESTION_TYPE_HELP'] .= gT("Please choose *only one* of the following:");
                         $question['ANSWER'] = "\n<ul>\n\t<li>\n\t\t" . self::_input_type_image('radio', gT('Yes')) . "\n\t\t" . gT('Yes') . self::_addsgqacode(" (Y)") . "\n\t</li>\n";
                         $question['ANSWER'] .= "\n\t<li>\n\t\t" . self::_input_type_image('radio', gT('No')) . "\n\t\t" . gT('No') . self::_addsgqacode(" (N)") . "\n\t</li>\n</ul>\n";
                         break;
                         // ==================================================================
                     // ==================================================================
                     case "A":
                         //ARRAY (5 POINT CHOICE)
                         $condition = "parent_qid = '{$deqrow['qid']}'  AND language= '{$sLanguageCode}'";
                         $question['QUESTION_TYPE_HELP'] .= gT("Please choose the appropriate response for each item:");
                         $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $sLanguageCode, $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>";
                         $j = 0;
                         $rowclass = 'array1';
                         $mearesult = Question::model()->getAllRecords($condition, array('question_order'));
                         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";
                             for ($i = 1; $i <= 5; $i++) {
                                 $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', $i) . "</td>\n";
                             }
                             $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";
                         break;
                         // ==================================================================
                     // ==================================================================
                     case "B":
                         //ARRAY (10 POINT CHOICE)
                         $question['QUESTION_TYPE_HELP'] .= gT("Please choose the appropriate response for each item:");
                         $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $sLanguageCode, $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";
                         $j = 0;
                         $rowclass = 'array1';
                         $mearesult = Question::model()->getAllRecords(" parent_qid='{$deqrow['qid']}' AND language='{$sLanguageCode}' ", array('question_order'));
                         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');
                             for ($i = 1; $i <= 10; $i++) {
                                 $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', $i) . "</td>\n";
                             }
                             $question['ANSWER'] .= "\t\t</tr>\n";
                             $j++;
                         }
                         $question['ANSWER'] .= "\t</tbody>\n</table>\n";
                         break;
                         // ==================================================================
                     // ==================================================================
                     case "C":
                         //ARRAY (YES/UNCERTAIN/NO)
                         $question['QUESTION_TYPE_HELP'] .= gT("Please choose the appropriate response for each item:");
                         $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $sLanguageCode, $surveyid);
                         $question['ANSWER'] = '
         <table>
             <thead>
                 <tr>
                     <td>&nbsp;</td>
                     <th>' . gT("Yes") . self::_addsgqacode(" (Y)") . '</th>
                     <th>' . gT("Uncertain") . self::_addsgqacode(" (U)") . '</th>
                     <th>' . gT("No") . self::_addsgqacode(" (N)") . '</th>
                 </tr>
             </thead>
             <tbody>
         ';
                         $j = 0;
                         $rowclass = 'array1';
                         $mearesult = Question::model()->getAllRecords(" parent_qid='{$deqrow['qid']}'  AND language='{$sLanguageCode}' ", array('question_order'));
                         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', gT("Yes")) . "</td>\n";
                             $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', gT("Uncertain")) . "</td>\n";
                             $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', gT("No")) . "</td>\n";
                             $question['ANSWER'] .= "\t\t</tr>\n";
                             $j++;
                             $rowclass = alternation($rowclass, 'row');
                         }
                         $question['ANSWER'] .= "\t</tbody>\n</table>\n";
                         break;
                     case "E":
                         //ARRAY (Increase/Same/Decrease)
                         $question['QUESTION_TYPE_HELP'] .= gT("Please choose the appropriate response for each item:");
                         $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $sLanguageCode, $surveyid);
                         $question['ANSWER'] = '
         <table>
             <thead>
                 <tr>
                     <td>&nbsp;</td>
                     <th>' . gT("Increase") . self::_addsgqacode(" (I)") . '</th>
                     <th>' . gT("Same") . self::_addsgqacode(" (S)") . '</th>
                     <th>' . gT("Decrease") . self::_addsgqacode(" (D)") . '</th>
                 </tr>
             </thead>
             <tbody>
         ';
                         $j = 0;
                         $rowclass = 'array1';
                         $mearesult = Question::model()->getAllRecords(" parent_qid='{$deqrow['qid']}'  AND language='{$sLanguageCode}' ", array('question_order'));
                         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', gT("Increase")) . "</td>\n";
                             $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', gT("Same")) . "</td>\n";
                             $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', gT("Decrease")) . "</td>\n";
                             $question['ANSWER'] .= "\t\t</tr>\n";
                             $j++;
                             $rowclass = alternation($rowclass, 'row');
                         }
                         $question['ANSWER'] .= "\t</tbody>\n</table>\n";
                         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;
                         }
                         $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $sLanguageCode, $surveyid);
                         $question['ANSWER'] .= "\n<table>\n\t<thead>\n\t\t<tr>\n\t\t\t<td>&nbsp;</td>\n";
                         $fresult = Question::model()->getAllRecords(" parent_qid='{$deqrow['qid']}' and scale_id=1 AND language='{$sLanguageCode}' ", array('question_order'));
                         $fresult = $fresult->readAll();
                         $fcount = count($fresult);
                         $fwidth = "120";
                         $i = 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++;
                             //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';
                         $mearesult = Question::model()->getAllRecords(" parent_qid='{$deqrow['qid']}' and scale_id=0 AND language='{$sLanguageCode}' ", array('question_order'));
                         $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>";
                             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 . $frow['title'] . "_" . $xaxisarray[$i] . ") ") . "\n";
                                 } else {
                                     $question['ANSWER'] .= "\t\t\t\t" . self::_input_type_image('checkbox') . self::_addsgqacode(" (" . $fieldname . $frow['title'] . "_" . $xaxisarray[$i] . ") ") . "\n";
                                 }
                                 $question['ANSWER'] .= "\t\t\t</td>\n";
                             }
                             $answertext = $frow['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";
                             $a++;
                         }
                         $question['ANSWER'] .= "\t</tbody>\n</table>\n";
                         break;
                         // ==================================================================
                     // ==================================================================
                     case ";":
                         //ARRAY (Multi Flexible) (text)
                         $headstyle = "style='padding-left: 20px; padding-right: 7px'";
                         $mearesult = Question::model()->getAllRecords(" parent_qid='{$deqrow['qid']}' AND scale_id=0 AND language='{$sLanguageCode}' ", array('question_order'));
                         $mearesult = $mearesult->readAll();
                         $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $sLanguageCode, $surveyid);
                         $question['ANSWER'] .= "\n<table>\n\t<thead>\n\t\t<tr>\n\t\t\t<td>&nbsp;</td>\n";
                         $fresult = Question::model()->getAllRecords(" parent_qid='{$deqrow['qid']}'  AND scale_id=1 AND language='{$sLanguageCode}' ", array('question_order'));
                         $fresult = $fresult->readAll();
                         $fcount = count($fresult);
                         $fwidth = "120";
                         $i = 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++;
                             //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 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";
                             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";
                             }
                             $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";
                         break;
                         // ==================================================================
                     // ==================================================================
                     case "F":
                         //ARRAY (Flexible Labels)
                         $question['QUESTION_TYPE_HELP'] .= gT("Please choose the appropriate response for each item:");
                         $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $sLanguageCode, $surveyid);
                         $fresult = Answer::model()->getAllRecords(" scale_id=0 AND qid='{$deqrow['qid']}'  AND language='{$sLanguageCode}'", array('sortorder', 'code'));
                         $fresult = $fresult->readAll();
                         $fcount = count($fresult);
                         $fwidth = "120";
                         $i = 1;
                         $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";
                         }
                         $i++;
                         $question['ANSWER'] .= "\t\t</tr>\n\t</thead>\n\n\t<tbody>\n";
                         $counter = 1;
                         $rowclass = 'array1';
                         $mearesult = Question::model()->getAllRecords(" parent_qid='{$deqrow['qid']}'  AND language='{$sLanguageCode}' ", array('question_order'));
                         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";
                             for ($i = 1; $i <= $fcount; $i++) {
                                 $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio') . "</td>\n";
                             }
                             $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";
                         break;
                         // ==================================================================
                     // ==================================================================
                     case "1":
                         //ARRAY (Flexible Labels) multi scale
                         $leftheader = $qidattributes['dualscale_headerA'][$sLanguageCode];
                         $rightheader = $qidattributes['dualscale_headerB'][$sLanguageCode];
                         $headstyle = 'style="padding-left: 20px; padding-right: 7px"';
                         $question['QUESTION_TYPE_HELP'] .= gT("Please choose the appropriate response for each item:");
                         $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $sLanguageCode, $surveyid);
                         $question['ANSWER'] .= "\n<table>\n\t<thead>\n";
                         $condition = "qid= '{$deqrow['qid']}'  AND language= '{$sLanguageCode}' AND scale_id=0";
                         $fresult = Answer::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 = '';
                         foreach ($fresult as $frow) {
                             $printablesurveyoutput2 .= "\t\t\t<th>{$frow['answer']}" . self::_addsgqacode(" (" . $frow['code'] . ")") . "</th>\n";
                             $myheader2 .= "<td></td>";
                             $l1++;
                         }
                         // second scale
                         $printablesurveyoutput2 .= "\t\t\t<td>&nbsp;</td>\n";
                         //$fquery1 = "SELECT * FROM {{answers}} WHERE qid='{$deqrow['qid']}'  AND language='{$sLanguageCode}' AND scale_id=1 ORDER BY sortorder, code";
                         // $fresult1 = Yii::app()->db->createCommand($fquery1)->query();
                         $fresult1 = Answer::model()->getAllRecords(" qid='{$deqrow['qid']}'  AND language='{$sLanguageCode}' 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";
                             //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;
                         $mearesult = Question::model()->getAllRecords(" parent_qid={$deqrow['qid']}  AND language='{$sLanguageCode}' ", array('question_order'));
                         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";
                         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= '{$sLanguageCode}'";
                         $fresult = Question::model()->getAllRecords($condition, array('question_order', 'title'));
                         $fresult = $fresult->readAll();
                         $question['QUESTION_TYPE_HELP'] .= gT("Please choose the appropriate response for each item:");
                         $question['ANSWER'] .= "\n<table>\n\t<thead>\n\t\t<tr>\n\t\t\t<td>&nbsp;</td>\n";
                         $fcount = count($fresult);
                         $fwidth = "120";
                         $i = 0;
                         foreach ($fresult as $frow) {
                             $question['ANSWER'] .= "\t\t\t<th>{$frow['question']}" . self::_addsgqacode(" (" . $fieldname . $frow['title'] . ")") . "</th>\n";
                             $i++;
                         }
                         $question['ANSWER'] .= "\t\t</tr>\n\t</thead>\n\n\t<tbody>\n";
                         $a = 1;
                         $rowclass = 'array1';
                         $mearesult = Answer::model()->getAllRecords(" qid='{$deqrow['qid']}' AND scale_id=0 AND language='{$sLanguageCode}' ", array('sortorder', 'code'));
                         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>";
                             for ($i = 1; $i <= $fcount; $i++) {
                                 $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio') . "</td>\n";
                             }
                             //$printablesurveyoutput .="\t\t\t\t\t</tr></table></td>\n";
                             $question['ANSWER'] .= "\t\t</tr>\n";
                             $a++;
                         }
                         $question['ANSWER'] .= "\t</tbody>\n</table>\n";
                         break;
                     case "|":
                         // File Upload
                         $question['QUESTION_TYPE_HELP'] .= "Kindly attach the aforementioned documents along with the survey";
                         break;
                         // === END SWITCH ===================================================
                 }
                 $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, 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.
         echo self::_populate_template('survey', $survey_output);
     }
     // End print
 }
コード例 #6
0
 /**
  * @param int $surveyid
  * @param string $language
  */
 public function actionAction($surveyid, $language = null)
 {
     $sLanguage = $language;
     $this->sLanguage = $language;
     ob_start(function ($buffer) {
         App()->getClientScript()->render($buffer);
         App()->getClientScript()->reset();
         return $buffer;
     });
     ob_implicit_flush(false);
     $iSurveyID = (int) $surveyid;
     $this->iSurveyID = (int) $surveyid;
     //$postlang = returnglobal('lang');
     Yii::import('application.libraries.admin.progressbar', true);
     Yii::app()->loadHelper("userstatistics");
     Yii::app()->loadHelper('database');
     Yii::app()->loadHelper('surveytranslator');
     App()->getClientScript()->registerPackage('jqueryui');
     App()->getClientScript()->registerPackage('jquery-touch-punch');
     App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('generalscripts') . "survey_runtime.js");
     $data = array();
     if (!isset($iSurveyID)) {
         $iSurveyID = returnGlobal('sid');
     } else {
         $iSurveyID = (int) $iSurveyID;
     }
     if (!$iSurveyID) {
         //This next line ensures that the $iSurveyID value is never anything but a number.
         safeDie('You have to provide a valid survey ID.');
     }
     $actresult = Survey::model()->findAll('sid = :sid AND active = :active', array(':sid' => $iSurveyID, ':active' => 'Y'));
     //Checked
     if (count($actresult) == 0) {
         safeDie('You have to provide a valid survey ID.');
     } else {
         $surveyinfo = getSurveyInfo($iSurveyID);
         // CHANGE JSW_NZ - let's get the survey title for display
         $thisSurveyTitle = $surveyinfo["name"];
         // CHANGE JSW_NZ - let's get css from individual template.css - so define path
         $thisSurveyCssPath = getTemplateURL($surveyinfo["template"]);
         if ($surveyinfo['publicstatistics'] != 'Y') {
             safeDie('The public statistics for this survey are deactivated.');
         }
         //check if graphs should be shown for this survey
         if ($surveyinfo['publicgraphs'] == 'Y') {
             $publicgraphs = 1;
         } else {
             $publicgraphs = 0;
         }
     }
     //we collect all the output within this variable
     $statisticsoutput = '';
     //for creating graphs we need some more scripts which are included here
     //True -> include
     //False -> forget about charts
     if (isset($publicgraphs) && $publicgraphs == 1) {
         require_once APPPATH . 'third_party/pchart/pchart/pChart.class';
         require_once APPPATH . 'third_party/pchart/pchart/pData.class';
         require_once APPPATH . 'third_party/pchart/pchart/pCache.class';
         $MyCache = new pCache(Yii::app()->getConfig("tempdir") . DIRECTORY_SEPARATOR);
         //$currentuser is created as prefix for pchart files
         if (isset($_SERVER['REDIRECT_REMOTE_USER'])) {
             $currentuser = $_SERVER['REDIRECT_REMOTE_USER'];
         } else {
             if (session_id()) {
                 $currentuser = substr(session_id(), 0, 15);
             } else {
                 $currentuser = "******";
             }
         }
     }
     // Set language for questions and labels to base language of this survey
     if ($sLanguage == null || !in_array($sLanguage, Survey::model()->findByPk($iSurveyID)->getAllLanguages())) {
         $sLanguage = Survey::model()->findByPk($iSurveyID)->language;
     } else {
         $sLanguage = sanitize_languagecode($sLanguage);
     }
     //set survey language for translations
     SetSurveyLanguage($iSurveyID, $sLanguage);
     //Create header
     sendCacheHeaders();
     $condition = false;
     $sitename = Yii::app()->getConfig("sitename");
     $data['surveylanguage'] = $sLanguage;
     $data['sitename'] = $sitename;
     $data['condition'] = $condition;
     $data['thisSurveyCssPath'] = $thisSurveyCssPath;
     /*
      * only show questions where question attribute "public_statistics" is set to "1"
      */
     $query = "SELECT q.* , group_name, group_order FROM {{questions}} q, {{groups}} g, {{question_attributes}} qa\n                    WHERE g.gid = q.gid AND g.language = :lang1 AND q.language = :lang2 AND q.sid = :surveyid AND q.qid = qa.qid AND q.parent_qid = 0 AND qa.attribute = 'public_statistics'";
     $databasetype = Yii::app()->db->getDriverName();
     if ($databasetype == 'mssql' || $databasetype == "sqlsrv" || $databasetype == "dblib") {
         $query .= " AND CAST(CAST(qa.value as varchar) as int)='1'\n";
     } else {
         $query .= " AND qa.value='1'\n";
     }
     //execute query
     $result = Yii::app()->db->createCommand($query)->bindParam(":lang1", $sLanguage, PDO::PARAM_STR)->bindParam(":lang2", $sLanguage, PDO::PARAM_STR)->bindParam(":surveyid", $iSurveyID, PDO::PARAM_INT)->queryAll();
     //store all the data in $rows
     $rows = $result;
     //SORT IN NATURAL ORDER!
     usort($rows, 'groupOrderThenQuestionOrder');
     //put the question information into the filter array
     $filters = array();
     foreach ($rows as $row) {
         //store some column names in $filters array
         $filters[] = array($row['qid'], $row['gid'], $row['type'], $row['title'], $row['group_name'], flattenText($row['question']));
     }
     //number of records for this survey
     $totalrecords = 0;
     //count number of answers
     $query = "SELECT count(*) FROM {{survey_" . intval($iSurveyID) . "}}";
     //if incompleted answers should be filtert submitdate has to be not null
     //this setting is taken from config-defaults.php
     if (Yii::app()->getConfig("filterout_incomplete_answers") == true) {
         $query .= " WHERE {{survey_" . intval($iSurveyID) . "}}.submitdate is not null";
     }
     $result = Yii::app()->db->createCommand($query)->queryAll();
     //$totalrecords = total number of answers
     foreach ($result as $row) {
         $totalrecords = reset($row);
     }
     //...while this is the array from copy/paste which we don't want to replace because this is a nasty source of error
     $allfields = array();
     //---------- CREATE SGQA OF ALL QUESTIONS WHICH USE "PUBLIC_STATISTICS" ----------
     /*
              * let's go through the filter array which contains
              *     ['qid'],
              ['gid'],
              ['type'],
              ['title'],
              ['group_name'],
              ['question'];
     */
     $currentgroup = '';
     // use to check if there are any question with public statistics
     if (isset($filters)) {
         $allfields = $this->createSGQA($filters);
     }
     // end if -> for removing the error message in case there are no filters
     $summary = $allfields;
     // Get the survey inforamtion
     $thissurvey = getSurveyInfo($surveyid, $sLanguage);
     //SET THE TEMPLATE DIRECTORY
     $data['sTemplatePath'] = $surveyinfo['template'];
     // surveyinfo=getSurveyInfo and if survey don't exist : stop before.
     //---------- CREATE STATISTICS ----------
     $redata = compact(array_keys(get_defined_vars()));
     doHeader();
     /// $oTemplate is a global variable defined in controller/survey/index
     $oTemplate = Template::model()->getInstance(null, $surveyid);
     echo templatereplace(file_get_contents($oTemplate->viewPath . "startpage.pstpl"), array(), $redata);
     //some progress bar stuff
     // Create progress bar which is shown while creating the results
     $prb = new ProgressBar();
     $prb->pedding = 2;
     // Bar Pedding
     $prb->brd_color = "#404040 #dfdfdf #dfdfdf #404040";
     // Bar Border Color
     $prb->setFrame();
     // set ProgressBar Frame
     $prb->frame['left'] = 50;
     // Frame position from left
     $prb->frame['top'] = 80;
     // Frame position from top
     $prb->addLabel('text', 'txt1', gT("Please wait ..."));
     // add Text as Label 'txt1' and value 'Please wait'
     $prb->addLabel('percent', 'pct1');
     // add Percent as Label 'pct1'
     $prb->addButton('btn1', gT('Go back'), '?action=statistics&amp;sid=' . $iSurveyID);
     // add Button as Label 'btn1' and action '?restart=1'
     $prb->show();
     // show the ProgressBar
     // 1: Get list of questions with answers chosen
     //"Getting Questions and Answer ..." is shown above the bar
     $prb->setLabelValue('txt1', gT('Getting questions and answers ...'));
     $prb->moveStep(5);
     // creates array of post variable names
     $postvars = array();
     for (reset($_POST); $key = key($_POST); next($_POST)) {
         $postvars[] = $key;
     }
     $data['thisSurveyTitle'] = $thisSurveyTitle;
     $data['totalrecords'] = $totalrecords;
     $data['summary'] = $summary;
     //show some main data at the beginnung
     // CHANGE JSW_NZ - let's allow html formatted questions to show
     //push progress bar from 35 to 40
     $process_status = 40;
     //Show Summary results
     if (isset($summary) && !empty($summary)) {
         //"Generating Summaries ..." is shown above the progress bar
         $prb->setLabelValue('txt1', gT('Generating summaries ...'));
         $prb->moveStep($process_status);
         //let's run through the survey // Fixed bug 3053 with array_unique
         $runthrough = array_unique($summary);
         //loop through all selected questions
         foreach ($runthrough as $rt) {
             //update progress bar
             if ($process_status < 100) {
                 $process_status++;
             }
             $prb->moveStep($process_status);
         }
         // end foreach -> loop through all questions
         $helper = new userstatistics_helper();
         $statisticsoutput .= $helper->generate_statistics($iSurveyID, $summary, $summary, $publicgraphs, 'html', null, $sLanguage, false);
     }
     //end if -> show summary results
     $data['statisticsoutput'] = $statisticsoutput;
     //done! set progress bar to 100%
     if (isset($prb)) {
         $prb->setLabelValue('txt1', gT('Completed'));
         $prb->moveStep(100);
         $prb->hide();
     }
     $redata = compact(array_keys(get_defined_vars()));
     $data['redata'] = $redata;
     Yii::app()->getClientScript()->registerScriptFile(Yii::app()->getConfig('generalscripts') . 'statistics_user.js');
     $this->renderPartial('/statistics_user_view', $data);
     //output footer
     echo getFooter();
     //Delete all Session Data
     Yii::app()->session['finished'] = true;
 }
コード例 #7
0
 /**
  * printanswers::view()
  * View answers at the end of a survey in one place. To export as pdf, set 'usepdfexport' = 1 in lsconfig.php and $printableexport='pdf'.
  * @param mixed $surveyid
  * @param bool $printableexport
  * @return
  */
 function actionView($surveyid, $printableexport = FALSE)
 {
     global $siteadminname, $siteadminemail;
     Yii::app()->loadHelper("frontend");
     Yii::import('application.libraries.admin.pdf');
     $surveyid = (int) $surveyid;
     Yii::app()->loadHelper('database');
     if (isset($_SESSION['survey_' . $surveyid]['sid'])) {
         $surveyid = $_SESSION['survey_' . $surveyid]['sid'];
     } else {
         die('Invalid survey/session');
     }
     //Debut session time out
     if (!isset($_SESSION['survey_' . $surveyid]['finished']) || !isset($_SESSION['survey_' . $surveyid]['srid'])) {
         //require_once($rootdir.'/classes/core/language.php');
         $baselang = Survey::model()->findByPk($surveyid)->language;
         Yii::import('application.libraries.Limesurvey_lang', true);
         $clang = new Limesurvey_lang($baselang);
         //A nice exit
         sendCacheHeaders();
         doHeader();
         echo templatereplace(file_get_contents(getTemplatePath(validateTemplateDir("default")) . "/startpage.pstpl"), array(), array());
         echo "<center><br />\n" . "\t<font color='RED'><strong>" . $clang->gT("Error") . "</strong></font><br />\n" . "\t" . $clang->gT("We are sorry but your session has expired.") . "<br />" . $clang->gT("Either you have been inactive for too long, you have cookies disabled for your browser, or there were problems with your connection.") . "<br />\n" . "\t" . sprintf($clang->gT("Please contact %s ( %s ) for further assistance."), $siteadminname, $siteadminemail) . "\n" . "</center><br />\n";
         echo templatereplace(file_get_contents(getTemplatePath(validateTemplateDir("default")) . "/endpage.pstpl"), array(), array());
         doFooter();
         exit;
     }
     //Fin session time out
     $id = $_SESSION['survey_' . $surveyid]['srid'];
     //I want to see the answers with this id
     $clang = $_SESSION['survey_' . $surveyid]['s_lang'];
     //Ensure script is not run directly, avoid path disclosure
     //if (!isset($rootdir) || isset($_REQUEST['$rootdir'])) {die( "browse - Cannot run this script directly");}
     // Set the language for dispay
     //require_once($rootdir.'/classes/core/language.php');  // has been secured
     if (isset($_SESSION['survey_' . $surveyid]['s_lang'])) {
         $clang = SetSurveyLanguage($surveyid, $_SESSION['survey_' . $surveyid]['s_lang']);
         $language = $_SESSION['survey_' . $surveyid]['s_lang'];
     } else {
         $language = Survey::model()->findByPk($surveyid)->language;
         $clang = SetSurveyLanguage($surveyid, $language);
     }
     // Get the survey inforamtion
     $thissurvey = getSurveyInfo($surveyid, $language);
     //SET THE TEMPLATE DIRECTORY
     if (!isset($thissurvey['templatedir']) || !$thissurvey['templatedir']) {
         $thistpl = validateTemplateDir("default");
     } else {
         $thistpl = validateTemplateDir($thissurvey['templatedir']);
     }
     if ($thissurvey['printanswers'] == 'N') {
         die;
         //Die quietly if print answers is not permitted
     }
     //CHECK IF SURVEY IS ACTIVATED AND EXISTS
     $surveytable = "{{survey_{$surveyid}}}";
     $surveyname = $thissurvey['surveyls_title'];
     $anonymized = $thissurvey['anonymized'];
     //OK. IF WE GOT THIS FAR, THEN THE SURVEY EXISTS AND IT IS ACTIVE, SO LETS GET TO WORK.
     //SHOW HEADER
     $printoutput = '';
     $printoutput .= "<form action='" . Yii::app()->getController()->createUrl('printanswers/view/surveyid/' . $surveyid . '/printableexport/pdf') . "' method='post'>\n<center><input type='submit' value='" . $clang->gT("PDF export") . "'id=\"exportbutton\"/><input type='hidden' name='printableexport' /></center></form>";
     if ($printableexport == 'pdf') {
         require Yii::app()->getConfig('rootdir') . '/application/config/tcpdf.php';
         Yii::import('application.libraries.admin.pdf', true);
         $pdf = new pdf();
         $pdf->setConfig($tcpdf);
         //$pdf->SetFont($pdfdefaultfont,'',$pdffontsize);
         $pdf->AddPage();
         //$pdf->titleintopdf($clang->gT("Survey name (ID)",'unescaped').": {$surveyname} ({$surveyid})");
         $pdf->SetTitle($clang->gT("Survey name (ID)", 'unescaped') . ": {$surveyname} ({$surveyid})");
     }
     $printoutput .= "\t<div class='printouttitle'><strong>" . $clang->gT("Survey name (ID):") . "</strong> {$surveyname} ({$surveyid})</div><p>&nbsp;\n";
     LimeExpressionManager::StartProcessingPage(true);
     // means that all variables are on the same page
     // Since all data are loaded, and don't need JavaScript, pretend all from Group 1
     LimeExpressionManager::StartProcessingGroup(1, $thissurvey['anonymized'] != "N", $surveyid);
     $aFullResponseTable = getFullResponseTable($surveyid, $id, $language, true);
     //Get the fieldmap @TODO: do we need to filter out some fields?
     unset($aFullResponseTable['id']);
     unset($aFullResponseTable['token']);
     unset($aFullResponseTable['lastpage']);
     unset($aFullResponseTable['startlanguage']);
     unset($aFullResponseTable['datestamp']);
     unset($aFullResponseTable['startdate']);
     $printoutput .= "<table class='printouttable' >\n";
     if ($printableexport == 'pdf') {
         $pdf->intopdf($clang->gT("Question", 'unescaped') . ": " . $clang->gT("Your answer", 'unescaped'));
     }
     $oldgid = 0;
     $oldqid = 0;
     foreach ($aFullResponseTable as $sFieldname => $fname) {
         if (substr($sFieldname, 0, 4) == 'gid_') {
             if ($printableexport) {
                 $pdf->intopdf(flattenText($fname[0], false, true));
                 $pdf->ln(2);
             } else {
                 $printoutput .= "\t<tr class='printanswersgroup'><td colspan='2'>{$fname[0]}</td></tr>\n";
             }
         } elseif (substr($sFieldname, 0, 4) == 'qid_') {
             if ($printableexport == 'pdf') {
                 $pdf->intopdf(flattenText($fname[0] . $fname[1], false, true) . ": " . $fname[2]);
                 $pdf->ln(2);
             } else {
                 $printoutput .= "\t<tr class='printanswersquestionhead'><td  colspan='2'>{$fname[0]}</td></tr>\n";
             }
         } elseif ($sFieldname == 'submitdate') {
             if ($anonymized != 'Y') {
                 if ($printableexport == 'pdf') {
                     $pdf->intopdf(flattenText($fname[0] . $fname[1], false, true) . ": " . $fname[2]);
                     $pdf->ln(2);
                 } else {
                     $printoutput .= "\t<tr class='printanswersquestion'><td>{$fname[0]} {$fname[1]} {$sFieldname}</td><td class='printanswersanswertext'>{$fname[2]}</td></tr>";
                 }
             }
         } else {
             if ($printableexport == 'pdf') {
                 $pdf->intopdf(flattenText($fname[0] . $fname[1], false, true) . ": " . $fname[2]);
                 $pdf->ln(2);
             } else {
                 $printoutput .= "\t<tr class='printanswersquestion'><td>{$fname[0]} {$fname[1]}</td><td class='printanswersanswertext'>{$fname[2]}</td></tr>";
             }
         }
     }
     $printoutput .= "</table>\n";
     if ($printableexport == 'pdf') {
         header("Pragma: public");
         header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
         $sExportFileName = sanitize_filename($surveyname);
         $pdf->Output($sExportFileName . "-" . $surveyid . ".pdf", "D");
     }
     //Display the page with user answers
     if (!$printableexport) {
         sendCacheHeaders();
         doHeader();
         echo templatereplace(file_get_contents(getTemplatePath($thistpl) . '/startpage.pstpl'));
         echo templatereplace(file_get_contents(getTemplatePath($thistpl) . '/printanswers.pstpl'), array('ANSWERTABLE' => $printoutput));
         echo templatereplace(file_get_contents(getTemplatePath($thistpl) . '/endpage.pstpl'));
         echo "</body></html>";
     }
     LimeExpressionManager::FinishProcessingGroup();
     LimeExpressionManager::FinishProcessingPage();
 }
コード例 #8
0
 /**
  * printanswers::view()
  * View answers at the end of a survey in one place. To export as pdf, set 'usepdfexport' = 1 in lsconfig.php and $printableexport='pdf'.
  * @param mixed $surveyid
  * @param bool $printableexport
  * @return
  */
 function actionView($surveyid, $printableexport = FALSE)
 {
     Yii::app()->loadHelper("frontend");
     Yii::import('application.libraries.admin.pdf');
     $iSurveyID = (int) $surveyid;
     $sExportType = $printableexport;
     Yii::app()->loadHelper('database');
     if (isset($_SESSION['survey_' . $iSurveyID]['sid'])) {
         $iSurveyID = $_SESSION['survey_' . $iSurveyID]['sid'];
     } else {
         //die('Invalid survey/session');
     }
     // Get the survey inforamtion
     // Set the language for dispay
     if (isset($_SESSION['survey_' . $iSurveyID]['s_lang'])) {
         $sLanguage = $_SESSION['survey_' . $iSurveyID]['s_lang'];
     } elseif (Survey::model()->findByPk($iSurveyID)) {
         $sLanguage = Survey::model()->findByPk($iSurveyID)->language;
     } else {
         $iSurveyID = 0;
         $sLanguage = Yii::app()->getConfig("defaultlang");
     }
     SetSurveyLanguage($iSurveyID, $sLanguage);
     $aSurveyInfo = getSurveyInfo($iSurveyID, $sLanguage);
     $oTemplate = Template::model()->getInstance(null, $iSurveyID);
     //Survey is not finished or don't exist
     if (!isset($_SESSION['survey_' . $iSurveyID]['finished']) || !isset($_SESSION['survey_' . $iSurveyID]['srid'])) {
         sendCacheHeaders();
         doHeader();
         /// $oTemplate is a global variable defined in controller/survey/index
         echo templatereplace(file_get_contents($oTemplate->viewPath . '/startpage.pstpl'), array());
         echo "<center><br />\n" . "\t<font color='RED'><strong>" . gT("Error") . "</strong></font><br />\n" . "\t" . gT("We are sorry but your session has expired.") . "<br />" . gT("Either you have been inactive for too long, you have cookies disabled for your browser, or there were problems with your connection.") . "<br />\n" . "\t" . sprintf(gT("Please contact %s ( %s ) for further assistance."), Yii::app()->getConfig("siteadminname"), Yii::app()->getConfig("siteadminemail")) . "\n" . "</center><br />\n";
         echo templatereplace(file_get_contents($oTemplate->viewPath . '/endpage.pstpl'), array());
         doFooter();
         exit;
     }
     //Fin session time out
     $sSRID = $_SESSION['survey_' . $iSurveyID]['srid'];
     //I want to see the answers with this id
     //Ensure script is not run directly, avoid path disclosure
     //if (!isset($rootdir) || isset($_REQUEST['$rootdir'])) {die( "browse - Cannot run this script directly");}
     //Ensure Participants printAnswer setting is set to true or that the logged user have read permissions over the responses.
     if ($aSurveyInfo['printanswers'] == 'N' && !Permission::model()->hasSurveyPermission($iSurveyID, 'responses', 'read')) {
         throw new CHttpException(401, 'You are not allowed to print answers.');
     }
     //CHECK IF SURVEY IS ACTIVATED AND EXISTS
     $sSurveyName = $aSurveyInfo['surveyls_title'];
     $sAnonymized = $aSurveyInfo['anonymized'];
     //OK. IF WE GOT THIS FAR, THEN THE SURVEY EXISTS AND IT IS ACTIVE, SO LETS GET TO WORK.
     //SHOW HEADER
     if ($sExportType != 'pdf') {
         $sOutput = CHtml::form(array("printanswers/view/surveyid/{$iSurveyID}/printableexport/pdf"), 'post') . "<center><input class='btn btn-default' type='submit' value='" . gT("PDF export") . "'id=\"exportbutton\"/><input type='hidden' name='printableexport' /></center></form>";
         $sOutput .= "\t<div class='printouttitle'><strong>" . gT("Survey name (ID):") . "</strong> {$sSurveyName} ({$iSurveyID})</div><p>&nbsp;\n";
         LimeExpressionManager::StartProcessingPage(true);
         // means that all variables are on the same page
         // Since all data are loaded, and don't need JavaScript, pretend all from Group 1
         LimeExpressionManager::StartProcessingGroup(1, $aSurveyInfo['anonymized'] != "N", $iSurveyID);
         $printanswershonorsconditions = Yii::app()->getConfig('printanswershonorsconditions');
         $aFullResponseTable = getFullResponseTable($iSurveyID, $sSRID, $sLanguage, $printanswershonorsconditions);
         //Get the fieldmap @TODO: do we need to filter out some fields?
         if ($aSurveyInfo['datestamp'] != "Y" || $sAnonymized == 'Y') {
             unset($aFullResponseTable['submitdate']);
         } else {
             unset($aFullResponseTable['id']);
         }
         unset($aFullResponseTable['token']);
         unset($aFullResponseTable['lastpage']);
         unset($aFullResponseTable['startlanguage']);
         unset($aFullResponseTable['datestamp']);
         unset($aFullResponseTable['startdate']);
         $sOutput .= "<table class='printouttable' >\n";
         foreach ($aFullResponseTable as $sFieldname => $fname) {
             if (substr($sFieldname, 0, 4) == 'gid_') {
                 $sOutput .= "\t<tr class='printanswersgroup'><td colspan='2'>{$fname[0]}</td></tr>\n";
                 $sOutput .= "\t<tr class='printanswersgroupdesc'><td colspan='2'>{$fname[1]}</td></tr>\n";
             } elseif ($sFieldname == 'submitdate') {
                 if ($sAnonymized != 'Y') {
                     $sOutput .= "\t<tr class='printanswersquestion'><td>{$fname[0]} {$fname[1]} {$sFieldname}</td><td class='printanswersanswertext'>{$fname[2]}</td></tr>";
                 }
             } elseif (substr($sFieldname, 0, 4) != 'qid_') {
                 $sOutput .= "\t<tr class='printanswersquestion'><td>{$fname[0]} {$fname[1]}</td><td class='printanswersanswertext'>" . flattenText($fname[2]) . "</td></tr>";
             }
         }
         $sOutput .= "</table>\n";
         $sData['thissurvey'] = $aSurveyInfo;
         $sOutput = templatereplace($sOutput, array(), $sData, '', $aSurveyInfo['anonymized'] == "Y", NULL, array(), true);
         // Do a static replacement
         ob_start(function ($buffer, $phase) {
             App()->getClientScript()->render($buffer);
             App()->getClientScript()->reset();
             return $buffer;
         });
         ob_implicit_flush(false);
         sendCacheHeaders();
         doHeader();
         echo templatereplace(file_get_contents($oTemplate->viewPath . '/startpage.pstpl'), array(), $sData);
         echo templatereplace(file_get_contents($oTemplate->viewPath . '/printanswers.pstpl'), array('ANSWERTABLE' => $sOutput), $sData);
         echo templatereplace(file_get_contents($oTemplate->viewPath . '/endpage.pstpl'), array(), $sData);
         echo "</body></html>";
         ob_flush();
     }
     if ($sExportType == 'pdf') {
         // Get images for TCPDF from template directory
         define('K_PATH_IMAGES', getTemplatePath($aSurveyInfo['template']) . DIRECTORY_SEPARATOR);
         Yii::import('application.libraries.admin.pdf', true);
         Yii::import('application.helpers.pdfHelper');
         $aPdfLanguageSettings = pdfHelper::getPdfLanguageSettings(App()->language);
         $oPDF = new pdf();
         $sDefaultHeaderString = $sSurveyName . " (" . gT("ID", 'unescaped') . ":" . $iSurveyID . ")";
         $oPDF->initAnswerPDF($aSurveyInfo, $aPdfLanguageSettings, Yii::app()->getConfig('sitename'), $sSurveyName, $sDefaultHeaderString);
         LimeExpressionManager::StartProcessingPage(true);
         // means that all variables are on the same page
         // Since all data are loaded, and don't need JavaScript, pretend all from Group 1
         LimeExpressionManager::StartProcessingGroup(1, $aSurveyInfo['anonymized'] != "N", $iSurveyID);
         $printanswershonorsconditions = Yii::app()->getConfig('printanswershonorsconditions');
         $aFullResponseTable = getFullResponseTable($iSurveyID, $sSRID, $sLanguage, $printanswershonorsconditions);
         //Get the fieldmap @TODO: do we need to filter out some fields?
         if ($aSurveyInfo['datestamp'] != "Y" || $sAnonymized == 'Y') {
             unset($aFullResponseTable['submitdate']);
         } else {
             unset($aFullResponseTable['id']);
         }
         unset($aFullResponseTable['token']);
         unset($aFullResponseTable['lastpage']);
         unset($aFullResponseTable['startlanguage']);
         unset($aFullResponseTable['datestamp']);
         unset($aFullResponseTable['startdate']);
         foreach ($aFullResponseTable as $sFieldname => $fname) {
             if (substr($sFieldname, 0, 4) == 'gid_') {
                 $oPDF->addGidAnswer($fname[0], $fname[1]);
             } elseif ($sFieldname == 'submitdate') {
                 if ($sAnonymized != 'Y') {
                     $oPDF->addAnswer($fname[0] . " " . $fname[1], $fname[2]);
                 }
             } elseif (substr($sFieldname, 0, 4) != 'qid_') {
                 $oPDF->addAnswer($fname[0] . " " . $fname[1], $fname[2]);
             }
         }
         header("Pragma: public");
         header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
         $sExportFileName = sanitize_filename($sSurveyName);
         $oPDF->Output($sExportFileName . "-" . $iSurveyID . ".pdf", "D");
     }
     LimeExpressionManager::FinishProcessingGroup();
     LimeExpressionManager::FinishProcessingPage();
 }
コード例 #9
0
ファイル: index.php プロジェクト: rawaludin/LimeSurvey
    function action()
    {
        global $surveyid;
        global $thissurvey, $thisstep;
        global $clienttoken, $tokensexist, $token;
        global $clang;
        $clang = Yii::app()->lang;
        @ini_set('session.gc_maxlifetime', Yii::app()->getConfig('iSessionExpirationTime'));
        $this->_loadRequiredHelpersAndLibraries();
        $param = $this->_getParameters(func_get_args(), $_POST);
        $surveyid = $param['sid'];
        Yii::app()->setConfig('surveyID', $surveyid);
        $thisstep = $param['thisstep'];
        $move = $param['move'];
        $clienttoken = $param['token'];
        $standardtemplaterootdir = Yii::app()->getConfig('standardtemplaterootdir');
        // unused vars in this method (used in methods using compacted method vars)
        @($loadname = $param['loadname']);
        @($loadpass = $param['loadpass']);
        $sitename = Yii::app()->getConfig('sitename');
        if (isset($param['newtest']) && $param['newtest'] == "Y") {
            killSurveySession($surveyid);
        }
        list($surveyExists, $isSurveyActive) = $this->_surveyExistsAndIsActive($surveyid);
        // collect all data in this method to pass on later
        $redata = compact(array_keys(get_defined_vars()));
        $clang = $this->_loadLimesurveyLang($surveyid);
        if ($this->_isClientTokenDifferentFromSessionToken($clienttoken, $surveyid)) {
            $asMessage = array($clang->gT('Token mismatch'), $clang->gT('The token you provided doesn\'t match the one in your session.'), $clang->gT('Please wait to begin with a new session.'));
            $this->_createNewUserSessionAndRedirect($surveyid, $redata, __LINE__, $asMessage);
        }
        if ($this->_isSurveyFinished($surveyid)) {
            $asMessage = array($clang->gT('Previous session is set to be finished.'), $clang->gT('Your browser reports that it was used previously to answer this survey. We are resetting the session so that you can start from the beginning.'), $clang->gT('Please wait to begin with a new session.'));
            $this->_createNewUserSessionAndRedirect($surveyid, $redata, __LINE__, $asMessage);
        }
        if ($this->_isPreviewAction($param) && !$this->_canUserPreviewSurvey($surveyid)) {
            $asMessage = array($clang->gT('Error'), $clang->gT('We are sorry but you don\'t have permissions to do this.'));
            $this->_niceExit($redata, __LINE__, null, $asMessage);
        }
        if ($this->_surveyCantBeViewedWithCurrentPreviewAccess($surveyid, $isSurveyActive, $surveyExists)) {
            $bPreviewRight = $this->_userHasPreviewAccessSession($surveyid);
            if ($bPreviewRight === false) {
                $asMessage = array($clang->gT("Error"), $clang->gT("We are sorry but you don't have permissions to do this."), sprintf($clang->gT("Please contact %s ( %s ) for further assistance."), $thissurvey['adminname'], $thissurvey['adminemail']));
                $this->_niceExit($redata, __LINE__, null, $asMessage);
            }
        }
        // TODO can this be moved to the top?
        // (Used to be global, used in ExpressionManager, merged into amVars. If not filled in === '')
        // can this be added in the first computation of $redata?
        if (isset($_SESSION['survey_' . $surveyid]['srid'])) {
            $saved_id = $_SESSION['survey_' . $surveyid]['srid'];
        }
        // recompute $redata since $saved_id used to be a global
        $redata = compact(array_keys(get_defined_vars()));
        /*if ( $this->_didSessionTimeOut() )
          {
          // @TODO is this still required ?
          $asMessage = array(
          $clang->gT("Error"),
          $clang->gT("We are sorry but your session has expired."),
          $clang->gT("Either you have been inactive for too long, you have cookies disabled for your browser, or there were problems with your connection."),
          sprintf($clang->gT("Please contact %s ( %s ) for further assistance."),$thissurvey['adminname'],$thissurvey['adminemail'])
          );
          $this->_niceExit($redata, __LINE__, null, $asMessage);
          };*/
        // Set the language of the survey, either from POST, GET parameter of session var
        if (!empty($_REQUEST['lang'])) {
            $sTempLanguage = sanitize_languagecode($_REQUEST['lang']);
        } elseif (!empty($param['lang'])) {
            $sTempLanguage = sanitize_languagecode($param['lang']);
        } elseif (isset($_SESSION['survey_' . $surveyid]['s_lang'])) {
            $sTempLanguage = $_SESSION['survey_' . $surveyid]['s_lang'];
        } else {
            $sTempLanguage = '';
        }
        //CHECK FOR REQUIRED INFORMATION (sid)
        if ($surveyid && $surveyExists) {
            LimeExpressionManager::SetSurveyId($surveyid);
            // must be called early - it clears internal cache if a new survey is being used
            $clang = SetSurveyLanguage($surveyid, $sTempLanguage);
            UpdateSessionGroupList($surveyid, $sTempLanguage);
            // to refresh the language strings in the group list session variable
            UpdateFieldArray();
            // to refresh question titles and question text
        } else {
            if (!is_null($param['lang'])) {
                $sDisplayLanguage = $param['lang'];
            } else {
                $sDisplayLanguage = Yii::app()->getConfig('defaultlang');
            }
            $clang = $this->_loadLimesurveyLang($sDisplayLanguage);
            $languagechanger = makeLanguageChanger($sDisplayLanguage);
            //Find out if there are any publicly available surveys
            $query = "SELECT sid, surveyls_title, publicstatistics, language\n            FROM {{surveys}}\n            INNER JOIN {{surveys_languagesettings}}\n            ON ( surveyls_survey_id = sid  )\n            AND (surveyls_language=language)\n            WHERE\n            active='Y'\n            AND listpublic='Y'\n            AND ((expires >= '" . date("Y-m-d H:i") . "') OR (expires is null))\n            AND ((startdate <= '" . date("Y-m-d H:i") . "') OR (startdate is null))\n            ORDER BY surveyls_title";
            $result = dbExecuteAssoc($query, false, true) or safeDie("Could not connect to database. If you try to install LimeSurvey please refer to the <a href='http://docs.limesurvey.org'>installation docs</a> and/or contact the system administrator of this webpage.");
            //Checked
            $list = array();
            foreach ($result->readAll() as $rows) {
                $querylang = "SELECT surveyls_title\n                FROM {{surveys_languagesettings}}\n                WHERE surveyls_survey_id={$rows['sid']}\n                AND surveyls_language='{$sDisplayLanguage}'";
                $resultlang = Yii::app()->db->createCommand($querylang)->queryRow();
                if ($resultlang['surveyls_title']) {
                    $rows['surveyls_title'] = $resultlang['surveyls_title'];
                    $langtag = "";
                } else {
                    $langtag = "lang=\"{$rows['language']}\"";
                }
                $link = "<li><a href='" . $this->getController()->createUrl('/survey/index/sid/' . $rows['sid']);
                if (isset($param['lang']) && $langtag == "") {
                    $link .= "/lang-" . sanitize_languagecode($param['lang']);
                }
                $link .= "' {$langtag} class='surveytitle'>" . $rows['surveyls_title'] . "</a>\n";
                if ($rows['publicstatistics'] == 'Y') {
                    $link .= "<a href='" . $this->getController()->createUrl("/statistics_user/action/surveyid/" . $rows['sid']) . "/language/" . $sDisplayLanguage . "'>(" . $clang->gT('View statistics') . ")</a>";
                }
                $link .= "</li>\n";
                $list[] = $link;
            }
            //Check for inactive surveys which allow public registration.
            // TODO add a new template replace {SURVEYREGISTERLIST} ?
            $squery = "SELECT sid, surveyls_title, publicstatistics, language\n            FROM {{surveys}}\n            INNER JOIN {{surveys_languagesettings}}\n            ON (surveyls_survey_id = sid)\n            AND (surveyls_language=language)\n            WHERE allowregister='Y'\n            AND active='Y'\n            AND listpublic='Y'\n            AND ((expires >= '" . date("Y-m-d H:i") . "') OR (expires is null))\n            AND (startdate >= '" . date("Y-m-d H:i") . "')\n            ORDER BY surveyls_title";
            $sresult = dbExecuteAssoc($squery) or safeDie("Couldn't execute {$squery}");
            $aRows = $sresult->readAll();
            if (count($aRows) > 0) {
                $list[] = "</ul>" . " <div class=\"survey-list-heading\">" . $clang->gT("Following survey(s) are not yet active but you can register for them.") . "</div>" . " <ul>";
                // TODO give it to template
                foreach ($aRows as $rows) {
                    $querylang = "SELECT surveyls_title\n                    FROM {{surveys_languagesettings}}\n                    WHERE surveyls_survey_id={$rows['sid']}\n                    AND surveyls_language='{$sDisplayLanguage}'";
                    $resultlang = Yii::app()->db->createCommand($querylang)->queryRow();
                    if ($resultlang['surveyls_title']) {
                        $rows['surveyls_title'] = $resultlang['surveyls_title'];
                        $langtag = "";
                    } else {
                        $langtag = "lang=\"{$rows['language']}\"";
                    }
                    $link = "<li><a href=\"#\" id='inactivesurvey' onclick = 'sendreq(" . $rows['sid'] . ");' ";
                    //$link = "<li><a href=\"#\" id='inactivesurvey' onclick = 'convertGETtoPOST(".$this->getController()->createUrl('survey/send/')."?sid={$rows['sid']}&amp;)sendreq(".$rows['sid'].",".$rows['startdate'].",".$rows['expires'].");' ";
                    $link .= " {$langtag} class='surveytitle'>" . $rows['surveyls_title'] . "</a>\n";
                    $link .= "</li><div id='regform'></div>\n";
                    $list[] = $link;
                }
            }
            if (count($list) < 1) {
                $list[] = "<li class='surveytitle'>" . $clang->gT("No available surveys") . "</li>";
            }
            if (!$surveyid) {
                $thissurvey['name'] = Yii::app()->getConfig("sitename");
                $nosid = $clang->gT("You have not provided a survey identification number");
            } else {
                $thissurvey['name'] = $clang->gT("The survey identification number is invalid");
                $nosid = $clang->gT("The survey identification number is invalid");
            }
            $surveylist = array("nosid" => $nosid, "contact" => sprintf($clang->gT("Please contact %s ( %s ) for further assistance."), Yii::app()->getConfig("siteadminname"), encodeEmail(Yii::app()->getConfig("siteadminemail"))), "listheading" => $clang->gT("The following surveys are available:"), "list" => implode("\n", $list));
            $data['thissurvey'] = $thissurvey;
            //$data['privacy'] = $privacy;
            $data['surveylist'] = $surveylist;
            $data['surveyid'] = $surveyid;
            $data['templatedir'] = getTemplatePath(Yii::app()->getConfig("defaulttemplate"));
            $data['templateurl'] = getTemplateURL(Yii::app()->getConfig("defaulttemplate")) . "/";
            $data['templatename'] = Yii::app()->getConfig("defaulttemplate");
            $data['sitename'] = Yii::app()->getConfig("sitename");
            $data['languagechanger'] = $languagechanger;
            //A nice exit
            sendCacheHeaders();
            doHeader();
            $this->_printTemplateContent(getTemplatePath(Yii::app()->getConfig("defaulttemplate")) . "/startpage.pstpl", $data, __LINE__);
            $this->_printTemplateContent(getTemplatePath(Yii::app()->getConfig("defaulttemplate")) . "/surveylist.pstpl", $data, __LINE__);
            echo '<script type="text/javascript" >
            function sendreq(surveyid)
            {

            $.ajax({
            type: "GET",
            url: "' . $this->getController()->createUrl("/register/ajaxregisterform/surveyid") . '/" + surveyid,
            }).done(function(msg) {
            document.getElementById("regform").innerHTML = msg;
            });
            }
            </script>';
            $this->_printTemplateContent(getTemplatePath(Yii::app()->getConfig("defaulttemplate")) . "/endpage.pstpl", $data, __LINE__);
            doFooter();
            exit;
        }
        // Get token
        if (!isset($token)) {
            $token = $clienttoken;
        }
        //GET BASIC INFORMATION ABOUT THIS SURVEY
        $thissurvey = getSurveyInfo($surveyid, $_SESSION['survey_' . $surveyid]['s_lang']);
        //SEE IF SURVEY USES TOKENS
        if ($surveyExists == 1 && tableExists('{{tokens_' . $thissurvey['sid'] . '}}')) {
            $tokensexist = 1;
        } else {
            $tokensexist = 0;
            unset($_POST['token']);
            unset($param['token']);
            unset($token);
            unset($clienttoken);
        }
        //SET THE TEMPLATE DIRECTORY
        $thistpl = getTemplatePath($thissurvey['templatedir']);
        $timeadjust = Yii::app()->getConfig("timeadjust");
        //MAKE SURE SURVEY HASN'T EXPIRED
        if ($thissurvey['expiry'] != '' and dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust) > $thissurvey['expiry'] && $thissurvey['active'] != 'N') {
            $redata = compact(array_keys(get_defined_vars()));
            $asMessage = array($clang->gT("Error"), $clang->gT("This survey is no longer available."), sprintf($clang->gT("Please contact %s ( %s ) for further assistance."), $thissurvey['adminname'], $thissurvey['adminemail']));
            $this->_niceExit($redata, __LINE__, $thistpl, $asMessage);
        }
        //MAKE SURE SURVEY IS ALREADY VALID
        if ($thissurvey['startdate'] != '' and dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust) < $thissurvey['startdate'] && $thissurvey['active'] != 'N') {
            $redata = compact(array_keys(get_defined_vars()));
            $asMessage = array($clang->gT("Error"), $clang->gT("This survey is not yet started."), sprintf($clang->gT("Please contact %s ( %s ) for further assistance."), $thissurvey['adminname'], $thissurvey['adminemail']));
            $this->_niceExit($redata, __LINE__, $thistpl, $asMessage);
        }
        //CHECK FOR PREVIOUSLY COMPLETED COOKIE
        //If cookies are being used, and this survey has been completed, a cookie called "PHPSID[sid]STATUS" will exist (ie: SID6STATUS) and will have a value of "COMPLETE"
        $sCookieName = "LS_" . $surveyid . "_STATUS";
        if (isset($_COOKIE[$sCookieName]) && $_COOKIE[$sCookieName] == "COMPLETE" && $thissurvey['usecookie'] == "Y" && $tokensexist != 1 && (!isset($param['newtest']) || $param['newtest'] != "Y")) {
            $redata = compact(array_keys(get_defined_vars()));
            $asMessage = array($clang->gT("Error"), $clang->gT("You have already completed this survey."), sprintf($clang->gT("Please contact %s ( %s ) for further assistance."), $thissurvey['adminname'], $thissurvey['adminemail']));
            $this->_niceExit($redata, __LINE__, $thistpl, $asMessage);
        }
        if (isset($_GET['loadall']) && $_GET['loadall'] == "reload") {
            if (returnGlobal('loadname') && returnGlobal('loadpass')) {
                $_POST['loadall'] = "reload";
            }
        }
        //LOAD SAVED SURVEY
        if (isset($_POST['loadall']) && $_POST['loadall'] == "reload") {
            $errormsg = "";
            if (!isset($param['loadname']) || $param['loadname'] == null) {
                $errormsg .= $clang->gT("You did not provide a name") . "<br />\n";
            }
            if (!isset($param['loadpass']) || $param['loadpass'] == null) {
                $errormsg .= $clang->gT("You did not provide a password") . "<br />\n";
            }
            // if security question answer is incorrect
            // Not called if scid is set in GET params (when using email save/reload reminder URL)
            if (function_exists("ImageCreate") && isCaptchaEnabled('saveandloadscreen', $thissurvey['usecaptcha'])) {
                if ((!isset($_POST['loadsecurity']) || !isset($_SESSION['survey_' . $surveyid]['secanswer']) || $_POST['loadsecurity'] != $_SESSION['survey_' . $surveyid]['secanswer']) && !isset($_GET['scid'])) {
                    $errormsg .= $clang->gT("The answer to the security question is incorrect.") . "<br />\n";
                }
            }
            // Load session before loading the values from the saved data
            if (isset($_GET['loadall'])) {
                buildsurveysession($surveyid);
            }
            $_SESSION['survey_' . $surveyid]['holdname'] = $param['loadname'];
            //Session variable used to load answers every page.
            $_SESSION['survey_' . $surveyid]['holdpass'] = $param['loadpass'];
            //Session variable used to load answers every page.
            if ($errormsg == "") {
                loadanswers();
            }
            $move = "movenext";
            if ($errormsg) {
                $_POST['loadall'] = $clang->gT("Load unfinished survey");
            }
        }
        //Allow loading of saved survey
        if (isset($_POST['loadall']) && $_POST['loadall'] == $clang->gT("Load unfinished survey")) {
            $redata = compact(array_keys(get_defined_vars()));
            Yii::import("application.libraries.Load_answers");
            $tmp = new Load_answers();
            $tmp->run($redata);
        }
        //Check if TOKEN is used for EVERY PAGE
        //This function fixes a bug where users able to submit two surveys/votes
        //by checking that the token has not been used at each page displayed.
        // bypass only this check at first page (Step=0) because
        // this check is done in buildsurveysession and error message
        // could be more interresting there (takes into accound captcha if used)
        if ($tokensexist == 1 && isset($token) && $token && isset($_SESSION['survey_' . $surveyid]['step']) && $_SESSION['survey_' . $surveyid]['step'] > 0 && tableExists("tokens_{$surveyid}}}")) {
            //check if tokens actually haven't been already used
            $areTokensUsed = usedTokens(trim(strip_tags(returnGlobal('token'))), $surveyid);
            // check if token actually does exist
            // check also if it is allowed to change survey after completion
            if ($thissurvey['alloweditaftercompletion'] == 'Y') {
                $sQuery = "SELECT * FROM {{tokens_" . $surveyid . "}} WHERE token='" . $token . "'";
            } else {
                $sQuery = "SELECT * FROM {{tokens_" . $surveyid . "}} WHERE token='" . $token . "' AND (completed = 'N' or completed='')";
            }
            $aRow = Yii::app()->db->createCommand($sQuery)->queryRow();
            $tokendata = $aRow;
            if (!$aRow || $areTokensUsed && $thissurvey['alloweditaftercompletion'] != 'Y') {
                sendCacheHeaders();
                doHeader();
                //TOKEN DOESN'T EXIST OR HAS ALREADY BEEN USED. EXPLAIN PROBLEM AND EXIT
                $redata = compact(array_keys(get_defined_vars()));
                $this->_printTemplateContent($thistpl . '/startpage.pstpl', $redata, __LINE__);
                $this->_printTemplateContent($thistpl . '/survey.pstpl', $redata, __LINE__);
                $asMessage = array(null, $clang->gT("This is a controlled survey. You need a valid token to participate."), sprintf($clang->gT("For further information please contact %s"), $thissurvey['adminname'] . " (<a href='mailto:{$thissurvey['adminemail']}'>" . "{$thissurvey['adminemail']}</a>)"));
                $this->_niceExit($redata, __LINE__, $thistpl, $asMessage, true);
            }
        }
        if ($tokensexist == 1 && isset($token) && $token && tableExists("{{tokens_" . $surveyid . "}}")) {
            // check also if it is allowed to change survey after completion
            if ($thissurvey['alloweditaftercompletion'] == 'Y') {
                $tkquery = "SELECT * FROM {{tokens_" . $surveyid . "}} WHERE token='" . $token . "'";
            } else {
                $tkquery = "SELECT * FROM {{tokens_" . $surveyid . "}} WHERE token='" . $token . "' AND (completed = 'N' or completed='')";
            }
            $tkresult = dbExecuteAssoc($tkquery);
            //Checked
            $tokendata = $tkresult->read();
            if (isset($tokendata['validfrom']) && (trim($tokendata['validfrom']) != '' && $tokendata['validfrom'] > dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust)) || isset($tokendata['validuntil']) && (trim($tokendata['validuntil']) != '' && $tokendata['validuntil'] < dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust))) {
                sendCacheHeaders();
                doHeader();
                //TOKEN DOESN'T EXIST OR HAS ALREADY BEEN USED. EXPLAIN PROBLEM AND EXIT
                $redata = compact(array_keys(get_defined_vars()));
                $this->_printTemplateContent($thistpl . '/startpage.pstpl', $redata, __LINE__);
                $this->_printTemplateContent($thistpl . '/survey.pstpl', $redata, __LINE__);
                $asMessage = array(null, $clang->gT("We are sorry but you are not allowed to enter this survey."), $clang->gT("Your token seems to be valid but can be used only during a certain time period."), sprintf($clang->gT("For further information please contact %s"), $thissurvey['adminname'] . " (<a href='mailto:{$thissurvey['adminemail']}'>" . "{$thissurvey['adminemail']}</a>)"));
                $this->_niceExit($redata, __LINE__, $thistpl, $asMessage, true);
            }
        }
        //Clear session and remove the incomplete response if requested.
        if (isset($move) && $move == "clearall") {
            // delete the response but only if not already completed
            $s_lang = $_SESSION['survey_' . $surveyid]['s_lang'];
            if (isset($_SESSION['survey_' . $surveyid]['srid']) && !Survey_dynamic::model($surveyid)->isCompleted($_SESSION['survey_' . $surveyid]['srid'])) {
                // delete the response but only if not already completed
                $result = dbExecuteAssoc('DELETE FROM {{survey_' . $surveyid . '}} WHERE id=' . $_SESSION['survey_' . $surveyid]['srid'] . " AND submitdate IS NULL");
                if ($result->count() > 0) {
                    // Using count() here *should* be okay for MSSQL because it is a delete statement
                    // find out if there are any fuqt questions - checked
                    $fieldmap = createFieldMap($surveyid, 'short', false, false, $s_lang);
                    foreach ($fieldmap as $field) {
                        if ($field['type'] == "|" && !strpos($field['fieldname'], "_filecount")) {
                            if (!isset($qid)) {
                                $qid = array();
                            }
                            $qid[] = $field['fieldname'];
                        }
                    }
                    // if yes, extract the response json to those questions
                    if (isset($qid)) {
                        $query = "SELECT * FROM {{survey_" . $surveyid . "}} WHERE id=" . $_SESSION['survey_' . $surveyid]['srid'];
                        $result = dbExecuteAssoc($query);
                        foreach ($result->readAll() as $row) {
                            foreach ($qid as $question) {
                                $json = $row[$question];
                                if ($json == "" || $json == NULL) {
                                    continue;
                                }
                                // decode them
                                $phparray = json_decode($json);
                                foreach ($phparray as $metadata) {
                                    $target = Yii::app()->getConfig("uploaddir") . "/surveys/" . $surveyid . "/files/";
                                    // delete those files
                                    unlink($target . $metadata->filename);
                                }
                            }
                        }
                    }
                    // done deleting uploaded files
                }
                // also delete a record from saved_control when there is one
                dbExecuteAssoc('DELETE FROM {{saved_control}} WHERE srid=' . $_SESSION['survey_' . $surveyid]['srid'] . ' AND sid=' . $surveyid);
            }
            killSurveySession($surveyid);
            sendCacheHeaders();
            doHeader();
            $redata = compact(array_keys(get_defined_vars()));
            $this->_printTemplateContent($thistpl . '/startpage.pstpl', $redata, __LINE__);
            echo "\n\n<!-- JAVASCRIPT FOR CONDITIONAL QUESTIONS -->\n" . "\t<script type='text/javascript'>\n" . "\t<!--\n" . "function checkconditions(value, name, type, evt_type)\n" . "\t{\n" . "\t}\n" . "\t//-->\n" . "\t</script>\n\n";
            //Present the clear all page using clearall.pstpl template
            $this->_printTemplateContent($thistpl . '/clearall.pstpl', $redata, __LINE__);
            $this->_printTemplateContent($thistpl . '/endpage.pstpl', $redata, __LINE__);
            doFooter();
            exit;
        }
        //Check to see if a refering URL has been captured.
        if (!isset($_SESSION['survey_' . $surveyid]['refurl'])) {
            $_SESSION['survey_' . $surveyid]['refurl'] = GetReferringUrl();
            // do not overwrite refurl
        }
        // Let's do this only if
        //  - a saved answer record hasn't been loaded through the saved feature
        //  - the survey is not anonymous
        //  - the survey is active
        //  - a token information has been provided
        //  - the survey is setup to allow token-response-persistence
        if (!isset($_SESSION['survey_' . $surveyid]['srid']) && $thissurvey['anonymized'] == "N" && $thissurvey['active'] == "Y" && isset($token) && $token != '') {
            // load previous answers if any (dataentry with nosubmit)
            $sQuery = "SELECT id,submitdate,lastpage FROM {$thissurvey['tablename']} WHERE {$thissurvey['tablename']}.token='{$token}' order by id desc";
            $aRow = Yii::app()->db->createCommand($sQuery)->queryRow();
            if ($aRow) {
                if ($aRow['submitdate'] == '' && $thissurvey['tokenanswerspersistence'] == 'Y' || $aRow['submitdate'] != '' && $thissurvey['alloweditaftercompletion'] == 'Y') {
                    $_SESSION['survey_' . $surveyid]['srid'] = $aRow['id'];
                    if (!is_null($aRow['lastpage']) && $aRow['submitdate'] == '') {
                        $_SESSION['survey_' . $surveyid]['LEMtokenResume'] = true;
                        $_SESSION['survey_' . $surveyid]['step'] = $aRow['lastpage'];
                    }
                }
                buildsurveysession($surveyid);
                loadanswers();
            }
        }
        //        // SAVE POSTED ANSWERS TO DATABASE IF MOVE (NEXT,PREV,LAST, or SUBMIT) or RETURNING FROM SAVE FORM
        //        if (isset($move) || isset($_POST['saveprompt']))
        //        {
        //            $redata = compact(array_keys(get_defined_vars()));
        //            //save.php
        //            Yii::import("application.libraries.Save");
        //            $tmp = new Save();
        //            $tmp->run($redata);
        //
        //            // RELOAD THE ANSWERS INCASE SOMEONE ELSE CHANGED THEM
        //            if ($thissurvey['active'] == "Y" &&
        //            ( $thissurvey['allowsave'] == "Y" || $thissurvey['tokenanswerspersistence'] == "Y") )
        //            {
        //                loadanswers();
        //            }
        //        }
        if (isset($param['action']) && $param['action'] == 'previewgroup') {
            $thissurvey['format'] = 'G';
            buildsurveysession($surveyid, true);
        }
        if (isset($param['action']) && $param['action'] == 'previewquestion') {
            $thissurvey['format'] = 'S';
            buildsurveysession($surveyid, true);
        }
        sendCacheHeaders();
        //Send local variables to the appropriate survey type
        unset($redata);
        $redata = compact(array_keys(get_defined_vars()));
        Yii::import('application.helpers.SurveyRuntimeHelper');
        $tmp = new SurveyRuntimeHelper();
        $tmp->run($surveyid, $redata);
        if (isset($_POST['saveall']) || isset($flashmessage)) {
            echo "<script type='text/javascript'> \$(document).ready( function() { alert('" . $clang->gT("Your responses were successfully saved.", "js") . "');}) </script>";
        }
    }
コード例 #10
0
ファイル: common_functions.php プロジェクト: ddrmoscow/queXS
/**
* This function generates an array containing the fieldcode, and matching data in the same order as the activate script
*
* @param string $surveyid The Survey ID
* @param mixed $style 'short' (default) or 'full' - full creates extra information like default values
* @param mixed $force_refresh - Forces to really refresh the array, not just take the session copy
* @param int $questionid Limit to a certain qid only (for question preview) - default is false
* @return array
*/
function createFieldMap($surveyid, $style = 'full', $force_refresh = false, $questionid = false, $sQuestionLanguage = null)
{
    global $dbprefix, $connect, $clang, $aDuplicateQIDs;
    $surveyid = sanitize_int($surveyid);
    //Get list of questions
    if (is_null($sQuestionLanguage)) {
        if (isset($_SESSION['s_lang']) && in_array($_SESSION['s_lang'], GetAdditionalLanguagesFromSurveyID($surveyid))) {
            $sQuestionLanguage = $_SESSION['s_lang'];
        } else {
            $sQuestionLanguage = GetBaseLanguageFromSurveyID($surveyid);
        }
    }
    $sQuestionLanguage = sanitize_languagecode($sQuestionLanguage);
    if ($clang->langcode != $sQuestionLanguage) {
        SetSurveyLanguage($surveyid, $sQuestionLanguage);
    }
    $s_lang = $clang->langcode;
    //checks to see if fieldmap has already been built for this page.
    if (isset($_SESSION['fieldmap-' . $surveyid . $s_lang]) && !$force_refresh && $questionid == false) {
        if (isset($_SESSION['adminlang']) && $clang->langcode != $_SESSION['adminlang']) {
            $clang = new limesurvey_lang($_SESSION['adminlang']);
        }
        return $_SESSION['fieldmap-' . $surveyid . $s_lang];
    }
    $fieldmap["id"] = array("fieldname" => "id", 'sid' => $surveyid, 'type' => "id", "gid" => "", "qid" => "", "aid" => "");
    if ($style == "full") {
        $fieldmap["id"]['title'] = "";
        $fieldmap["id"]['question'] = $clang->gT("Response ID");
        $fieldmap["id"]['group_name'] = "";
    }
    $fieldmap["submitdate"] = array("fieldname" => "submitdate", 'type' => "submitdate", 'sid' => $surveyid, "gid" => "", "qid" => "", "aid" => "");
    if ($style == "full") {
        $fieldmap["submitdate"]['title'] = "";
        $fieldmap["submitdate"]['question'] = $clang->gT("Date submitted");
        $fieldmap["submitdate"]['group_name'] = "";
    }
    $fieldmap["lastpage"] = array("fieldname" => "lastpage", 'sid' => $surveyid, 'type' => "lastpage", "gid" => "", "qid" => "", "aid" => "");
    if ($style == "full") {
        $fieldmap["lastpage"]['title'] = "";
        $fieldmap["lastpage"]['question'] = $clang->gT("Last page");
        $fieldmap["lastpage"]['group_name'] = "";
    }
    $fieldmap["startlanguage"] = array("fieldname" => "startlanguage", 'sid' => $surveyid, 'type' => "startlanguage", "gid" => "", "qid" => "", "aid" => "");
    if ($style == "full") {
        $fieldmap["startlanguage"]['title'] = "";
        $fieldmap["startlanguage"]['question'] = $clang->gT("Start language");
        $fieldmap["startlanguage"]['group_name'] = "";
    }
    //Check for any additional fields for this survey and create necessary fields (token and datestamp and ipaddr)
    $pquery = "SELECT anonymized, datestamp, ipaddr, refurl FROM " . db_table_name('surveys') . " WHERE sid={$surveyid}";
    $presult = db_execute_assoc($pquery);
    //Checked
    while ($prow = $presult->FetchRow()) {
        if ($prow['anonymized'] == "N") {
            $fieldmap["token"] = array("fieldname" => "token", 'sid' => $surveyid, 'type' => "token", "gid" => "", "qid" => "", "aid" => "");
            if ($style == "full") {
                $fieldmap["token"]['title'] = "";
                $fieldmap["token"]['question'] = $clang->gT("Token");
                $fieldmap["token"]['group_name'] = "";
            }
        }
        if ($prow['datestamp'] == "Y") {
            $fieldmap["datestamp"] = array("fieldname" => "datestamp", 'type' => "datestamp", 'sid' => $surveyid, "gid" => "", "qid" => "", "aid" => "");
            if ($style == "full") {
                $fieldmap["datestamp"]['title'] = "";
                $fieldmap["datestamp"]['question'] = $clang->gT("Date last action");
                $fieldmap["datestamp"]['group_name'] = "";
            }
            $fieldmap["startdate"] = array("fieldname" => "startdate", 'type' => "startdate", 'sid' => $surveyid, "gid" => "", "qid" => "", "aid" => "");
            if ($style == "full") {
                $fieldmap["startdate"]['title'] = "";
                $fieldmap["startdate"]['question'] = $clang->gT("Date started");
                $fieldmap["startdate"]['group_name'] = "";
            }
        }
        if ($prow['ipaddr'] == "Y") {
            $fieldmap["ipaddr"] = array("fieldname" => "ipaddr", 'type' => "ipaddress", 'sid' => $surveyid, "gid" => "", "qid" => "", "aid" => "");
            if ($style == "full") {
                $fieldmap["ipaddr"]['title'] = "";
                $fieldmap["ipaddr"]['question'] = $clang->gT("IP address");
                $fieldmap["ipaddr"]['group_name'] = "";
            }
        }
        // Add 'refurl' to fieldmap.
        if ($prow['refurl'] == "Y") {
            $fieldmap["refurl"] = array("fieldname" => "refurl", 'type' => "url", 'sid' => $surveyid, "gid" => "", "qid" => "", "aid" => "");
            if ($style == "full") {
                $fieldmap["refurl"]['title'] = "";
                $fieldmap["refurl"]['question'] = $clang->gT("Referrer URL");
                $fieldmap["refurl"]['group_name'] = "";
            }
        }
    }
    // Collect all default values once so don't need separate query for each question with defaults
    // First collect language specific defaults
    $defaultsQuery = "SELECT a.qid, a.sqid, a.scale_id, a.specialtype, a.defaultvalue" . " FROM " . db_table_name('defaultvalues') . " as a, " . db_table_name('questions') . " as b" . " WHERE a.qid = b.qid" . " AND a.language = b.language" . " AND a.language = '{$s_lang}'" . " AND b.same_default=0" . " AND b.sid = " . $surveyid;
    $defaultResults = db_execute_assoc($defaultsQuery) or safe_die("Couldn't get list of default values in createFieldMap.<br/>{$defaultsQuery}<br/>" . $conect->ErrorMsg());
    $defaultValues = array();
    // indexed by question then subquestion
    foreach ($defaultResults as $dv) {
        if ($dv['specialtype'] != '') {
            $sq = $dv['specialtype'];
        } else {
            $sq = $dv['sqid'];
        }
        $defaultValues[$dv['qid'] . '~' . $sq] = $dv['defaultvalue'];
    }
    // Now overwrite language-specific defaults (if any) base language values for each question that uses same_defaults=1
    $baseLanguage = GetBaseLanguageFromSurveyID($surveyid);
    $defaultsQuery = "SELECT a.qid, a.sqid, a.scale_id, a.specialtype, a.defaultvalue" . " FROM " . db_table_name('defaultvalues') . " as a, " . db_table_name('questions') . " as b" . " WHERE a.qid = b.qid" . " AND a.language = b.language" . " AND a.language = '{$baseLanguage}'" . " AND b.same_default=1" . " AND b.sid = " . $surveyid;
    $defaultResults = db_execute_assoc($defaultsQuery) or safe_die("Couldn't get list of default values in createFieldMap.<br/>{$defaultsQuery}<br/>" . $conect->ErrorMsg());
    foreach ($defaultResults as $dv) {
        if ($dv['specialtype'] != '') {
            $sq = $dv['specialtype'];
        } else {
            $sq = $dv['sqid'];
        }
        $defaultValues[$dv['qid'] . '~' . $sq] = $dv['defaultvalue'];
    }
    $qtypes = getqtypelist('', 'array');
    $aquery = "SELECT * " . " FROM " . db_table_name('questions') . " as questions, " . db_table_name('groups') . " as groups" . " WHERE questions.gid=groups.gid AND " . " questions.sid={$surveyid} AND " . " questions.language='{$s_lang}' AND " . " questions.parent_qid=0 AND " . " groups.language='{$s_lang}' ";
    if ($questionid !== false) {
        $aquery .= " and questions.qid={$questionid} ";
    }
    $aquery .= " ORDER BY group_order, question_order";
    $aresult = db_execute_assoc($aquery) or safe_die("Couldn't get list of questions in createFieldMap function.<br />{$query}<br />" . $connect->ErrorMsg());
    //Checked
    $questionSeq = -1;
    // this is incremental question sequence across all groups
    $groupSeq = -1;
    $_groupOrder = -1;
    while ($arow = $aresult->FetchRow()) {
        ++$questionSeq;
        // fix fact taht group_order may have gaps
        if ($_groupOrder != $arow['group_order']) {
            $_groupOrder = $arow['group_order'];
            ++$groupSeq;
        }
        // Conditions indicators are obsolete with EM.  However, they are so tightly coupled into LS code that easider to just set values to 'N' for now and refactor later.
        $conditions = 'N';
        $usedinconditions = 'N';
        // Field identifier
        // GXQXSXA
        // G=Group  Q=Question S=Subquestion A=Answer Option
        // If S or A don't exist then set it to 0
        // Implicit (subqestion intermal to a question type ) or explicit qubquestions/answer count starts at 1
        // Types "L", "!" , "O", "D", "G", "N", "X", "Y", "5","S","T","U","*"
        $fieldname = "{$arow['sid']}X{$arow['gid']}X{$arow['qid']}";
        if ($qtypes[$arow['type']]['subquestions'] == 0 && $arow['type'] != "R" && $arow['type'] != "|") {
            if (isset($fieldmap[$fieldname])) {
                $aDuplicateQIDs[$arow['qid']] = array('fieldname' => $fieldname, 'question' => $arow['question'], 'gid' => $arow['gid']);
            }
            $fieldmap[$fieldname] = array("fieldname" => $fieldname, 'type' => "{$arow['type']}", 'sid' => $surveyid, "gid" => $arow['gid'], "qid" => $arow['qid'], "aid" => "");
            if ($style == "full") {
                $fieldmap[$fieldname]['title'] = $arow['title'];
                $fieldmap[$fieldname]['question'] = $arow['question'];
                $fieldmap[$fieldname]['group_name'] = $arow['group_name'];
                $fieldmap[$fieldname]['mandatory'] = $arow['mandatory'];
                $fieldmap[$fieldname]['hasconditions'] = $conditions;
                $fieldmap[$fieldname]['usedinconditions'] = $usedinconditions;
                $fieldmap[$fieldname]['questionSeq'] = $questionSeq;
                $fieldmap[$fieldname]['groupSeq'] = $groupSeq;
                if (isset($defaultValues[$arow['qid'] . '~0'])) {
                    $fieldmap[$fieldname]['defaultvalue'] = $defaultValues[$arow['qid'] . '~0'];
                }
            }
            switch ($arow['type']) {
                case "L":
                    //RADIO LIST
                //RADIO LIST
                case "!":
                    //DROPDOWN LIST
                    $fieldmap[$fieldname]['other'] = $arow['other'];
                    // so that base variable knows whether has other value
                    if ($arow['other'] == "Y") {
                        $fieldname = "{$arow['sid']}X{$arow['gid']}X{$arow['qid']}other";
                        if (isset($fieldmap[$fieldname])) {
                            $aDuplicateQIDs[$arow['qid']] = array('fieldname' => $fieldname, 'question' => $arow['question'], 'gid' => $arow['gid']);
                        }
                        $fieldmap[$fieldname] = array("fieldname" => $fieldname, 'type' => $arow['type'], 'sid' => $surveyid, "gid" => $arow['gid'], "qid" => $arow['qid'], "aid" => "other");
                        // dgk bug fix line above. aid should be set to "other" for export to append to the field name in the header line.
                        if ($style == "full") {
                            $fieldmap[$fieldname]['title'] = $arow['title'];
                            $fieldmap[$fieldname]['question'] = $arow['question'];
                            $fieldmap[$fieldname]['subquestion'] = $clang->gT("Other");
                            $fieldmap[$fieldname]['group_name'] = $arow['group_name'];
                            $fieldmap[$fieldname]['mandatory'] = $arow['mandatory'];
                            $fieldmap[$fieldname]['hasconditions'] = $conditions;
                            $fieldmap[$fieldname]['usedinconditions'] = $usedinconditions;
                            $fieldmap[$fieldname]['questionSeq'] = $questionSeq;
                            $fieldmap[$fieldname]['groupSeq'] = $groupSeq;
                            $fieldmap[$fieldname]['other'] = $arow['other'];
                            if (isset($defaultValues[$arow['qid'] . '~other'])) {
                                $fieldmap[$fieldname]['defaultvalue'] = $defaultValues[$arow['qid'] . '~other'];
                            }
                        }
                    }
                    break;
                case "O":
                    //DROPDOWN LIST WITH COMMENT
                    $fieldname = "{$arow['sid']}X{$arow['gid']}X{$arow['qid']}comment";
                    if (isset($fieldmap[$fieldname])) {
                        $aDuplicateQIDs[$arow['qid']] = array('fieldname' => $fieldname, 'question' => $arow['question'], 'gid' => $arow['gid']);
                    }
                    $fieldmap[$fieldname] = array("fieldname" => $fieldname, 'type' => $arow['type'], 'sid' => $surveyid, "gid" => $arow['gid'], "qid" => $arow['qid'], "aid" => "comment");
                    // dgk bug fix line below. aid should be set to "comment" for export to append to the field name in the header line. Also needed set the type element correctly.
                    if ($style == "full") {
                        $fieldmap[$fieldname]['title'] = $arow['title'];
                        $fieldmap[$fieldname]['question'] = $arow['question'];
                        $fieldmap[$fieldname]['subquestion'] = $clang->gT("Comment");
                        $fieldmap[$fieldname]['group_name'] = $arow['group_name'];
                        $fieldmap[$fieldname]['mandatory'] = $arow['mandatory'];
                        $fieldmap[$fieldname]['hasconditions'] = $conditions;
                        $fieldmap[$fieldname]['usedinconditions'] = $usedinconditions;
                        $fieldmap[$fieldname]['questionSeq'] = $questionSeq;
                        $fieldmap[$fieldname]['groupSeq'] = $groupSeq;
                    }
                    break;
            }
        } elseif ($qtypes[$arow['type']]['subquestions'] == 2 && $qtypes[$arow['type']]['answerscales'] == 0) {
            //MULTI FLEXI
            $abrows = getSubQuestions($surveyid, $arow['qid'], $s_lang);
            //Now first process scale=1
            $answerset = array();
            $answerList = array();
            foreach ($abrows as $key => $abrow) {
                if ($abrow['scale_id'] == 1) {
                    $answerset[] = $abrow;
                    $answerList[] = array('code' => $abrow['title'], 'answer' => $abrow['question']);
                    unset($abrows[$key]);
                }
            }
            reset($abrows);
            foreach ($abrows as $abrow) {
                foreach ($answerset as $answer) {
                    $fieldname = "{$arow['sid']}X{$arow['gid']}X{$arow['qid']}{$abrow['title']}_{$answer['title']}";
                    if (isset($fieldmap[$fieldname])) {
                        $aDuplicateQIDs[$arow['qid']] = array('fieldname' => $fieldname, 'question' => $arow['question'], 'gid' => $arow['gid']);
                    }
                    $fieldmap[$fieldname] = array("fieldname" => $fieldname, 'type' => $arow['type'], 'sid' => $surveyid, "gid" => $arow['gid'], "qid" => $arow['qid'], "aid" => $abrow['title'] . "_" . $answer['title'], "sqid" => $abrow['qid']);
                    if ($abrow['other'] == "Y") {
                        $alsoother = "Y";
                    }
                    if ($style == "full") {
                        $fieldmap[$fieldname]['title'] = $arow['title'];
                        $fieldmap[$fieldname]['question'] = $arow['question'];
                        $fieldmap[$fieldname]['subquestion1'] = $abrow['question'];
                        $fieldmap[$fieldname]['subquestion2'] = $answer['question'];
                        $fieldmap[$fieldname]['group_name'] = $arow['group_name'];
                        $fieldmap[$fieldname]['mandatory'] = $arow['mandatory'];
                        $fieldmap[$fieldname]['hasconditions'] = $conditions;
                        $fieldmap[$fieldname]['usedinconditions'] = $usedinconditions;
                        $fieldmap[$fieldname]['questionSeq'] = $questionSeq;
                        $fieldmap[$fieldname]['groupSeq'] = $groupSeq;
                        $fieldmap[$fieldname]['preg'] = $arow['preg'];
                        $fieldmap[$fieldname]['answerList'] = $answerList;
                    }
                }
            }
            unset($answerset);
        } elseif ($arow['type'] == "1") {
            $abrows = getSubQuestions($surveyid, $arow['qid'], $s_lang);
            foreach ($abrows as $abrow) {
                $fieldname = "{$arow['sid']}X{$arow['gid']}X{$arow['qid']}{$abrow['title']}#0";
                if (isset($fieldmap[$fieldname])) {
                    $aDuplicateQIDs[$arow['qid']] = array('fieldname' => $fieldname, 'question' => $arow['question'], 'gid' => $arow['gid']);
                }
                $fieldmap[$fieldname] = array("fieldname" => $fieldname, 'type' => $arow['type'], 'sid' => $surveyid, "gid" => $arow['gid'], "qid" => $arow['qid'], "aid" => $abrow['title'], "scale_id" => 0);
                if ($style == "full") {
                    $fieldmap[$fieldname]['title'] = $arow['title'];
                    $fieldmap[$fieldname]['question'] = $arow['question'];
                    $fieldmap[$fieldname]['subquestion'] = $abrow['question'];
                    $fieldmap[$fieldname]['group_name'] = $arow['group_name'];
                    $fieldmap[$fieldname]['scale'] = $clang->gT('Scale 1');
                    $fieldmap[$fieldname]['mandatory'] = $arow['mandatory'];
                    $fieldmap[$fieldname]['hasconditions'] = $conditions;
                    $fieldmap[$fieldname]['usedinconditions'] = $usedinconditions;
                    $fieldmap[$fieldname]['questionSeq'] = $questionSeq;
                    $fieldmap[$fieldname]['groupSeq'] = $groupSeq;
                }
                $fieldname = "{$arow['sid']}X{$arow['gid']}X{$arow['qid']}{$abrow['title']}#1";
                if (isset($fieldmap[$fieldname])) {
                    $aDuplicateQIDs[$arow['qid']] = array('fieldname' => $fieldname, 'question' => $arow['question'], 'gid' => $arow['gid']);
                }
                $fieldmap[$fieldname] = array("fieldname" => $fieldname, 'type' => $arow['type'], 'sid' => $surveyid, "gid" => $arow['gid'], "qid" => $arow['qid'], "aid" => $abrow['title'], "scale_id" => 1);
                if ($style == "full") {
                    $fieldmap[$fieldname]['title'] = $arow['title'];
                    $fieldmap[$fieldname]['question'] = $arow['question'];
                    $fieldmap[$fieldname]['subquestion'] = $abrow['question'];
                    $fieldmap[$fieldname]['group_name'] = $arow['group_name'];
                    $fieldmap[$fieldname]['scale'] = $clang->gT('Scale 2');
                    $fieldmap[$fieldname]['mandatory'] = $arow['mandatory'];
                    $fieldmap[$fieldname]['hasconditions'] = $conditions;
                    $fieldmap[$fieldname]['usedinconditions'] = $usedinconditions;
                    $fieldmap[$fieldname]['questionSeq'] = $questionSeq;
                    $fieldmap[$fieldname]['groupSeq'] = $groupSeq;
                }
            }
        } elseif ($arow['type'] == "R") {
            //MULTI ENTRY
            $slots = $connect->GetOne("select count(code) from " . db_table_name('answers') . " where qid={$arow['qid']} and language='{$s_lang}'");
            for ($i = 1; $i <= $slots; $i++) {
                $fieldname = "{$arow['sid']}X{$arow['gid']}X{$arow['qid']}{$i}";
                if (isset($fieldmap[$fieldname])) {
                    $aDuplicateQIDs[$arow['qid']] = array('fieldname' => $fieldname, 'question' => $arow['question'], 'gid' => $arow['gid']);
                }
                $fieldmap[$fieldname] = array("fieldname" => $fieldname, 'type' => $arow['type'], 'sid' => $surveyid, "gid" => $arow['gid'], "qid" => $arow['qid'], "aid" => $i);
                if ($style == "full") {
                    $fieldmap[$fieldname]['title'] = $arow['title'];
                    $fieldmap[$fieldname]['question'] = $arow['question'];
                    $fieldmap[$fieldname]['subquestion'] = sprintf($clang->gT('Rank %s'), $i);
                    $fieldmap[$fieldname]['group_name'] = $arow['group_name'];
                    $fieldmap[$fieldname]['mandatory'] = $arow['mandatory'];
                    $fieldmap[$fieldname]['hasconditions'] = $conditions;
                    $fieldmap[$fieldname]['usedinconditions'] = $usedinconditions;
                    $fieldmap[$fieldname]['questionSeq'] = $questionSeq;
                    $fieldmap[$fieldname]['groupSeq'] = $groupSeq;
                }
            }
        } elseif ($arow['type'] == "|") {
            $abquery = "SELECT value FROM " . db_table_name('question_attributes') . " WHERE attribute='max_num_of_files' AND qid=" . $arow['qid'];
            $abresult = db_execute_assoc($abquery) or safe_die("Couldn't get maximum\n            number of files that can be uploaded <br />{$abquery}<br />" . $connect->ErrorMsg());
            $abrow = $abresult->FetchRow();
            $fieldname = "{$arow['sid']}X{$arow['gid']}X{$arow['qid']}";
            $fieldmap[$fieldname] = array("fieldname" => $fieldname, 'type' => $arow['type'], 'sid' => $surveyid, "gid" => $arow['gid'], "qid" => $arow['qid'], "aid" => '');
            if ($style == "full") {
                $fieldmap[$fieldname]['title'] = $arow['title'];
                $fieldmap[$fieldname]['question'] = $arow['question'];
                $fieldmap[$fieldname]['max_files'] = $abrow['value'];
                $fieldmap[$fieldname]['group_name'] = $arow['group_name'];
                $fieldmap[$fieldname]['mandatory'] = $arow['mandatory'];
                $fieldmap[$fieldname]['hasconditions'] = $conditions;
                $fieldmap[$fieldname]['usedinconditions'] = $usedinconditions;
                $fieldmap[$fieldname]['questionSeq'] = $questionSeq;
                $fieldmap[$fieldname]['groupSeq'] = $groupSeq;
            }
            $fieldname = "{$arow['sid']}X{$arow['gid']}X{$arow['qid']}" . "_filecount";
            $fieldmap[$fieldname] = array("fieldname" => $fieldname, 'type' => $arow['type'], 'sid' => $surveyid, "gid" => $arow['gid'], "qid" => $arow['qid'], "aid" => "filecount");
            if ($style == "full") {
                $fieldmap[$fieldname]['title'] = $arow['title'];
                $fieldmap[$fieldname]['question'] = "filecount - " . $arow['question'];
                //$fieldmap[$fieldname]['subquestion']=$clang->gT("Comment");
                $fieldmap[$fieldname]['group_name'] = $arow['group_name'];
                $fieldmap[$fieldname]['mandatory'] = $arow['mandatory'];
                $fieldmap[$fieldname]['hasconditions'] = $conditions;
                $fieldmap[$fieldname]['usedinconditions'] = $usedinconditions;
                $fieldmap[$fieldname]['questionSeq'] = $questionSeq;
                $fieldmap[$fieldname]['groupSeq'] = $groupSeq;
            }
        } else {
            //MULTI ENTRY
            $abrows = getSubQuestions($surveyid, $arow['qid'], $s_lang);
            foreach ($abrows as $abrow) {
                $fieldname = "{$arow['sid']}X{$arow['gid']}X{$arow['qid']}{$abrow['title']}";
                if (isset($fieldmap[$fieldname])) {
                    $aDuplicateQIDs[$arow['qid']] = array('fieldname' => $fieldname, 'question' => $arow['question'], 'gid' => $arow['gid']);
                }
                $fieldmap[$fieldname] = array("fieldname" => $fieldname, 'type' => $arow['type'], 'sid' => $surveyid, 'gid' => $arow['gid'], 'qid' => $arow['qid'], 'aid' => $abrow['title'], 'sqid' => $abrow['qid']);
                if ($style == "full") {
                    $fieldmap[$fieldname]['title'] = $arow['title'];
                    $fieldmap[$fieldname]['question'] = $arow['question'];
                    $fieldmap[$fieldname]['subquestion'] = $abrow['question'];
                    $fieldmap[$fieldname]['group_name'] = $arow['group_name'];
                    $fieldmap[$fieldname]['mandatory'] = $arow['mandatory'];
                    $fieldmap[$fieldname]['hasconditions'] = $conditions;
                    $fieldmap[$fieldname]['usedinconditions'] = $usedinconditions;
                    $fieldmap[$fieldname]['questionSeq'] = $questionSeq;
                    $fieldmap[$fieldname]['groupSeq'] = $groupSeq;
                    $fieldmap[$fieldname]['preg'] = $arow['preg'];
                    if (isset($defaultValues[$arow['qid'] . '~' . $abrow['qid']])) {
                        $fieldmap[$fieldname]['defaultvalue'] = $defaultValues[$arow['qid'] . '~' . $abrow['qid']];
                    }
                }
                if ($arow['type'] == "P") {
                    $fieldname = "{$arow['sid']}X{$arow['gid']}X{$arow['qid']}{$abrow['title']}comment";
                    if (isset($fieldmap[$fieldname])) {
                        $aDuplicateQIDs[$arow['qid']] = array('fieldname' => $fieldname, 'question' => $arow['question'], 'gid' => $arow['gid']);
                    }
                    $fieldmap[$fieldname] = array("fieldname" => $fieldname, 'type' => $arow['type'], 'sid' => $surveyid, "gid" => $arow['gid'], "qid" => $arow['qid'], "aid" => $abrow['title'] . "comment");
                    if ($style == "full") {
                        $fieldmap[$fieldname]['title'] = $arow['title'];
                        $fieldmap[$fieldname]['question'] = $arow['question'];
                        $fieldmap[$fieldname]['subquestion'] = $clang->gT('Comment');
                        $fieldmap[$fieldname]['group_name'] = $arow['group_name'];
                        $fieldmap[$fieldname]['mandatory'] = $arow['mandatory'];
                        $fieldmap[$fieldname]['hasconditions'] = $conditions;
                        $fieldmap[$fieldname]['usedinconditions'] = $usedinconditions;
                        $fieldmap[$fieldname]['questionSeq'] = $questionSeq;
                        $fieldmap[$fieldname]['groupSeq'] = $groupSeq;
                    }
                }
            }
            if ($arow['other'] == "Y" && ($arow['type'] == "M" || $arow['type'] == "P")) {
                $fieldname = "{$arow['sid']}X{$arow['gid']}X{$arow['qid']}other";
                if (isset($fieldmap[$fieldname])) {
                    $aDuplicateQIDs[$arow['qid']] = array('fieldname' => $fieldname, 'question' => $arow['question'], 'gid' => $arow['gid']);
                }
                $fieldmap[$fieldname] = array("fieldname" => $fieldname, 'type' => $arow['type'], 'sid' => $surveyid, "gid" => $arow['gid'], "qid" => $arow['qid'], "aid" => "other");
                if ($style == "full") {
                    $fieldmap[$fieldname]['title'] = $arow['title'];
                    $fieldmap[$fieldname]['question'] = $arow['question'];
                    $fieldmap[$fieldname]['subquestion'] = $clang->gT('Other');
                    $fieldmap[$fieldname]['group_name'] = $arow['group_name'];
                    $fieldmap[$fieldname]['mandatory'] = $arow['mandatory'];
                    $fieldmap[$fieldname]['hasconditions'] = $conditions;
                    $fieldmap[$fieldname]['usedinconditions'] = $usedinconditions;
                    $fieldmap[$fieldname]['questionSeq'] = $questionSeq;
                    $fieldmap[$fieldname]['groupSeq'] = $groupSeq;
                    $fieldmap[$fieldname]['other'] = $arow['other'];
                }
                if ($arow['type'] == "P") {
                    $fieldname = "{$arow['sid']}X{$arow['gid']}X{$arow['qid']}othercomment";
                    if (isset($fieldmap[$fieldname])) {
                        $aDuplicateQIDs[$arow['qid']] = array('fieldname' => $fieldname, 'question' => $arow['question'], 'gid' => $arow['gid']);
                    }
                    $fieldmap[$fieldname] = array("fieldname" => $fieldname, 'type' => $arow['type'], 'sid' => $surveyid, "gid" => $arow['gid'], "qid" => $arow['qid'], "aid" => "othercomment");
                    if ($style == "full") {
                        $fieldmap[$fieldname]['title'] = $arow['title'];
                        $fieldmap[$fieldname]['question'] = $arow['question'];
                        $fieldmap[$fieldname]['subquestion'] = $clang->gT('Other comment');
                        $fieldmap[$fieldname]['group_name'] = $arow['group_name'];
                        $fieldmap[$fieldname]['mandatory'] = $arow['mandatory'];
                        $fieldmap[$fieldname]['hasconditions'] = $conditions;
                        $fieldmap[$fieldname]['usedinconditions'] = $usedinconditions;
                        $fieldmap[$fieldname]['questionSeq'] = $questionSeq;
                        $fieldmap[$fieldname]['groupSeq'] = $groupSeq;
                        $fieldmap[$fieldname]['other'] = $arow['other'];
                    }
                }
            }
        }
        if (isset($fieldmap[$fieldname])) {
            $fieldmap[$fieldname]['relevance'] = $arow['relevance'];
            $fieldmap[$fieldname]['grelevance'] = $arow['grelevance'];
            $fieldmap[$fieldname]['questionSeq'] = $questionSeq;
            $fieldmap[$fieldname]['groupSeq'] = $groupSeq;
            $fieldmap[$fieldname]['preg'] = $arow['preg'];
            $fieldmap[$fieldname]['other'] = $arow['other'];
            $fieldmap[$fieldname]['help'] = $arow['help'];
        } else {
            --$questionSeq;
            // didn't generate a valid $fieldmap entry, so decrement the question counter to ensure they are sequential
        }
    }
    if (isset($fieldmap)) {
        if ($questionid == false) {
            // If the fieldmap was randomized, the master will contain the proper order.  Copy that fieldmap with the new language settings.
            if (isset($_SESSION['fieldmap-' . $surveyid . '-randMaster'])) {
                $masterFieldmap = $_SESSION['fieldmap-' . $surveyid . '-randMaster'];
                $mfieldmap = $_SESSION[$masterFieldmap];
                foreach ($mfieldmap as $fieldname => $mf) {
                    if (isset($fieldmap[$fieldname])) {
                        $f = $fieldmap[$fieldname];
                        if (isset($f['question'])) {
                            $mf['question'] = $f['question'];
                        }
                        if (isset($f['subquestion'])) {
                            $mf['subquestion'] = $f['subquestion'];
                        }
                        if (isset($f['subquestion1'])) {
                            $mf['subquestion1'] = $f['subquestion1'];
                        }
                        if (isset($f['subquestion2'])) {
                            $mf['subquestion2'] = $f['subquestion2'];
                        }
                        if (isset($f['group_name'])) {
                            $mf['group_name'] = $f['group_name'];
                        }
                        if (isset($f['answerList'])) {
                            $mf['answerList'] = $f['answerList'];
                        }
                        if (isset($f['defaultvalue'])) {
                            $mf['defaultvalue'] = $f['defaultvalue'];
                        }
                        if (isset($f['help'])) {
                            $mf['help'] = $f['help'];
                        }
                    }
                    $mfieldmap[$fieldname] = $mf;
                }
                $fieldmap = $mfieldmap;
            }
            $_SESSION['fieldmap-' . $surveyid . $clang->langcode] = $fieldmap;
        }
        if (isset($_SESSION['adminlang']) && $clang->langcode != $_SESSION['adminlang']) {
            $clang = new limesurvey_lang($_SESSION['adminlang']);
        }
        return $fieldmap;
    }
}
コード例 #11
0
/**
* This function builds all the required session variables when a survey is first started and
* it loads any answer defaults from command line or from the table defaultvalues
* It is called from the related format script (group.php, question.php, survey.php)
* if the survey has just started.
*
* @returns  $totalquestions Total number of questions in the survey
*
*/
function buildsurveysession()
{
    global $thissurvey, $secerror, $clienttoken;
    global $tokensexist, $thistpl;
    global $surveyid, $dbprefix, $connect;
    global $register_errormsg, $clang;
    global $totalBoilerplatequestions;
    global $templang, $move, $rooturl, $publicurl;
    if (!isset($templang) || $templang == '') {
        $templang = $thissurvey['language'];
    }
    $totalBoilerplatequestions = 0;
    // NO TOKEN REQUIRED BUT CAPTCHA ENABLED FOR SURVEY ACCESS
    if ($tokensexist == 0 && captcha_enabled('surveyaccessscreen', $thissurvey['usecaptcha'])) {
        // IF CAPTCHA ANSWER IS NOT CORRECT OR NOT SET
        if (!isset($_GET['loadsecurity']) || !isset($_SESSION['secanswer']) || $_GET['loadsecurity'] != $_SESSION['secanswer']) {
            sendcacheheaders();
            doHeader();
            // No or bad answer to required security question
            echo templatereplace(file_get_contents("{$thistpl}/startpage.pstpl"));
            //echo makedropdownlist();
            echo templatereplace(file_get_contents("{$thistpl}/survey.pstpl"));
            if (isset($_GET['loadsecurity'])) {
                // was a bad answer
                echo "<font color='#FF0000'>" . $clang->gT("The answer to the security question is incorrect.") . "</font><br />";
            }
            echo "<p class='captcha'>" . $clang->gT("Please confirm access to survey by answering the security question below and click continue.") . "</p>\n\t\t\t        <form class='captcha' method='get' action='{$publicurl}/index.php'>\n\t\t\t        <table align='center'>\n\t\t\t\t        <tr>\n\t\t\t\t\t        <td align='right' valign='middle'>\n\t\t\t\t\t        <input type='hidden' name='sid' value='" . $surveyid . "' id='sid' />\n\t\t\t\t\t        <input type='hidden' name='lang' value='" . $templang . "' id='lang' />";
            // In case we this is a direct Reload previous answers URL, then add hidden fields
            if (isset($_GET['loadall']) && isset($_GET['scid']) && isset($_GET['loadname']) && isset($_GET['loadpass'])) {
                echo "\n\t\t\t\t\t\t<input type='hidden' name='loadall' value='" . htmlspecialchars($_GET['loadall']) . "' id='loadall' />\n\t\t\t\t\t\t<input type='hidden' name='scid' value='" . returnglobal('scid') . "' id='scid' />\n\t\t\t\t\t\t<input type='hidden' name='loadname' value='" . htmlspecialchars($_GET['loadname']) . "' id='loadname' />\n\t\t\t\t\t\t<input type='hidden' name='loadpass' value='" . htmlspecialchars($_GET['loadpass']) . "' id='loadpass' />";
            }
            echo "\n\t\t\t\t        </td>\n\t\t\t        </tr>";
            if (function_exists("ImageCreate") && captcha_enabled('surveyaccessscreen', $thissurvey['usecaptcha'])) {
                echo "<tr>\n\t\t\t\t                <td align='center' valign='middle'><label for='captcha'>" . $clang->gT("Security question:") . "</label></td><td align='left' valign='middle'><table><tr><td valign='middle'><img src='{$rooturl}/verification.php?sid={$surveyid}' alt='captcha' /></td>\n                                <td valign='middle'><input id='captcha' type='text' size='5' maxlength='3' name='loadsecurity' value='' /></td></tr></table>\n\t\t\t\t                </td>\n\t\t\t                </tr>";
            }
            echo "<tr><td colspan='2' align='center'><input class='submit' type='submit' value='" . $clang->gT("Continue") . "' /></td></tr>\n\t\t        </table>\n\t\t        </form>";
            echo templatereplace(file_get_contents("{$thistpl}/endpage.pstpl"));
            doFooter();
            exit;
        }
    }
    //BEFORE BUILDING A NEW SESSION FOR THIS SURVEY, LET'S CHECK TO MAKE SURE THE SURVEY SHOULD PROCEED!
    // TOKEN REQUIRED BUT NO TOKEN PROVIDED
    if ($tokensexist == 1 && !returnglobal('token')) {
        // DISPLAY REGISTER-PAGE if needed
        // DISPLAY CAPTCHA if needed
        sendcacheheaders();
        doHeader();
        echo templatereplace(file_get_contents("{$thistpl}/startpage.pstpl"));
        //echo makedropdownlist();
        echo templatereplace(file_get_contents("{$thistpl}/survey.pstpl"));
        if (isset($thissurvey) && $thissurvey['allowregister'] == "Y") {
            echo templatereplace(file_get_contents("{$thistpl}/register.pstpl"));
        } else {
            if (isset($secerror)) {
                echo "<span class='error'>" . $secerror . "</span><br />";
            }
            echo '<div id="wrapper"><p id="tokenmessage">' . $clang->gT("This is a controlled survey. You need a valid token to participate.") . "<br />";
            echo $clang->gT("If you have been issued a token, please enter it in the box below and click continue.") . "</p>\n            <script type='text/javascript'>var focus_element='#token';</script>\n\t        <form id='tokenform' method='get' action='{$publicurl}/index.php'>\n\n                <ul>\n                <li>\n                    <label for='token'>" . $clang->gT("Token") . "</label><input class='text' id='token' type='text' name='token' />\n                <input type='hidden' name='sid' value='" . $surveyid . "' id='sid' />\n\t\t\t\t<input type='hidden' name='lang' value='" . $templang . "' id='lang' />";
            if (isset($_GET['newtest']) && ($_GET['newtest'] = "Y")) {
                echo "  <input type='hidden' name='newtest' value='Y' id='newtest' />";
            }
            // If this is a direct Reload previous answers URL, then add hidden fields
            if (isset($_GET['loadall']) && isset($_GET['scid']) && isset($_GET['loadname']) && isset($_GET['loadpass'])) {
                echo "\n\t\t\t\t\t<input type='hidden' name='loadall' value='" . htmlspecialchars($_GET['loadall']) . "' id='loadall' />\n\t\t\t\t\t<input type='hidden' name='scid' value='" . returnglobal('scid') . "' id='scid' />\n\t\t\t\t\t<input type='hidden' name='loadname' value='" . htmlspecialchars($_GET['loadname']) . "' id='loadname' />\n\t\t\t\t\t<input type='hidden' name='loadpass' value='" . htmlspecialchars($_GET['loadpass']) . "' id='loadpass' />";
            }
            echo "</li>";
            if (function_exists("ImageCreate") && captcha_enabled('surveyaccessscreen', $thissurvey['usecaptcha'])) {
                echo "<li>\n\t\t\t                <label for='captchaimage'>" . $clang->gT("Security Question") . "</label><img id='captchaimage' src='{$rooturl}/verification.php?sid={$surveyid}' alt='captcha' /><input type='text' size='5' maxlength='3' name='loadsecurity' value='' />\n\t\t                  </li>";
            }
            echo "<li>\n                        <input class='submit' type='submit' value='" . $clang->gT("Continue") . "' />\n                      </li>\n            </ul>\n\t        </form></div>";
        }
        echo templatereplace(file_get_contents("{$thistpl}/endpage.pstpl"));
        doFooter();
        exit;
    } elseif ($tokensexist == 1 && returnglobal('token') && !captcha_enabled('surveyaccessscreen', $thissurvey['usecaptcha'])) {
        //check if token actually does exist
        $tkquery = "SELECT COUNT(*) FROM " . db_table_name('tokens_' . $surveyid) . " WHERE token='" . db_quote(trim(strip_tags(returnglobal('token')))) . "' AND (completed = 'N' or completed='')";
        $tkresult = db_execute_num($tkquery);
        //Checked
        list($tkexist) = $tkresult->FetchRow();
        if (!$tkexist) {
            //TOKEN DOESN'T EXIST OR HAS ALREADY BEEN USED. EXPLAIN PROBLEM AND EXIT
            killSession();
            sendcacheheaders();
            doHeader();
            echo templatereplace(file_get_contents("{$thistpl}/startpage.pstpl"));
            echo templatereplace(file_get_contents("{$thistpl}/survey.pstpl"));
            echo '<div id="wrapper"><p id="tokenmessage">' . $clang->gT("This is a controlled survey. You need a valid token to participate.") . "<br /><br />\n" . "\t" . $clang->gT("The token you have provided is either not valid, or has already been used.") . "<br />\n" . "\t" . sprintf($clang->gT("For further information contact %s"), $thissurvey['adminname']) . " (<a href='mailto:{$thissurvey['adminemail']}'>" . "{$thissurvey['adminemail']}</a>)</p></div>\n";
            echo templatereplace(file_get_contents("{$thistpl}/endpage.pstpl"));
            doFooter();
            exit;
        }
    } elseif ($tokensexist == 1 && returnglobal('token') && captcha_enabled('surveyaccessscreen', $thissurvey['usecaptcha'])) {
        // IF CAPTCHA ANSWER IS CORRECT
        if (isset($_GET['loadsecurity']) && isset($_SESSION['secanswer']) && $_GET['loadsecurity'] == $_SESSION['secanswer']) {
            //check if token actually does exist
            $tkquery = "SELECT COUNT(*) FROM " . db_table_name('tokens_' . $surveyid) . " WHERE token='" . db_quote(trim(sanitize_xss_string(strip_tags(returnglobal('token'))))) . "' AND (completed = 'N' or completed='')";
            $tkresult = db_execute_num($tkquery);
            //Checked
            list($tkexist) = $tkresult->FetchRow();
            if (!$tkexist) {
                sendcacheheaders();
                doHeader();
                //TOKEN DOESN'T EXIST OR HAS ALREADY BEEN USED. EXPLAIN PROBLEM AND EXIT
                echo templatereplace(file_get_contents("{$thistpl}/startpage.pstpl"));
                echo templatereplace(file_get_contents("{$thistpl}/survey.pstpl"));
                echo "\t<center><br />\n" . "\t" . $clang->gT("This is a controlled survey. You need a valid token to participate.") . "<br /><br />\n" . "\t" . $clang->gT("The token you have provided is either not valid, or has already been used.") . "<br/>\n" . "\t" . sprintf($clang->gT("For further information contact %s"), $thissurvey['adminname']) . " (<a href='mailto:{$thissurvey['adminemail']}'>" . "{$thissurvey['adminemail']}</a>)<br /><br />\n";
                echo templatereplace(file_get_contents("{$thistpl}/endpage.pstpl"));
                doFooter();
                exit;
            }
        } else {
            if (!isset($move) || is_null($move)) {
                $gettoken = $clienttoken;
                sendcacheheaders();
                doHeader();
                // No or bad answer to required security question
                echo templatereplace(file_get_contents("{$thistpl}/startpage.pstpl"));
                echo templatereplace(file_get_contents("{$thistpl}/survey.pstpl"));
                // If token wasn't provided and public registration
                // is enabled then show registration form
                if (!isset($gettoken) && isset($thissurvey) && $thissurvey['allowregister'] == "Y") {
                    echo templatereplace(file_get_contents("{$thistpl}/register.pstpl"));
                } else {
                    // only show CAPTCHA
                    echo '<div id="wrapper"><p id="tokenmessage">';
                    if (isset($_GET['loadsecurity'])) {
                        // was a bad answer
                        echo "<span class='error'>" . $clang->gT("The answer to the security question is incorrect.") . "</span><br />";
                    }
                    echo $clang->gT("This is a controlled survey. You need a valid token to participate.") . "<br /><br />";
                    // IF TOKEN HAS BEEN GIVEN THEN AUTOFILL IT
                    // AND HIDE ENTRY FIELD
                    if (!isset($gettoken)) {
                        echo $clang->gT("If you have been issued with a token, please enter it in the box below and click continue.") . "</p>\n\t\t\t            <form id='tokenform' method='get' action='{$publicurl}/index.php'>\n                        <ul>\n                        <li>\n\t\t\t\t\t        <input type='hidden' name='sid' value='" . $surveyid . "' id='sid' />\n\t\t\t\t\t\t    <input type='hidden' name='lang' value='" . $templang . "' id='lang' />";
                        if (isset($_GET['loadall']) && isset($_GET['scid']) && isset($_GET['loadname']) && isset($_GET['loadpass'])) {
                            echo "<input type='hidden' name='loadall' value='" . htmlspecialchars($_GET['loadall']) . "' id='loadall' />\n\t\t\t\t\t\t        <input type='hidden' name='scid' value='" . returnglobal('scid') . "' id='scid' />\n\t\t\t\t\t\t        <input type='hidden' name='loadname' value='" . htmlspecialchars($_GET['loadname']) . "' id='loadname' />\n\t\t\t\t\t\t        <input type='hidden' name='loadpass' value='" . htmlspecialchars($_GET['loadpass']) . "' id='loadpass' />";
                        }
                        echo '<label for="token">' . $clang->gT("Token") . "</label><input class='text' type='text' id=token name='token'></li>";
                    } else {
                        echo $clang->gT("Please confirm the token by answering the security question below and click continue.") . "</p>\n\t\t\t            <form id='tokenform' method='get' action='{$publicurl}/index.php'>\n                        <ul>\n\t\t\t            <li>\n\t\t\t\t\t            <input type='hidden' name='sid' value='" . $surveyid . "' id='sid' />\n\t\t\t\t\t\t        <input type='hidden' name='lang' value='" . $templang . "' id='lang' />";
                        if (isset($_GET['loadall']) && isset($_GET['scid']) && isset($_GET['loadname']) && isset($_GET['loadpass'])) {
                            echo "<input type='hidden' name='loadall' value='" . htmlspecialchars($_GET['loadall']) . "' id='loadall' />\n                              <input type='hidden' name='scid' value='" . returnglobal('scid') . "' id='scid' />\n                              <input type='hidden' name='loadname' value='" . htmlspecialchars($_GET['loadname']) . "' id='loadname' />\n                              <input type='hidden' name='loadpass' value='" . htmlspecialchars($_GET['loadpass']) . "' id='loadpass' />";
                        }
                        echo '<label for="token">' . $clang->gT("Token:") . "</label><span id=token>{$gettoken}</span>" . "<input type='hidden' name='token' value='{$gettoken}'></li>";
                    }
                    if (function_exists("ImageCreate") && captcha_enabled('surveyaccessscreen', $thissurvey['usecaptcha'])) {
                        echo "<li>\n                            <label for='captchaimage'>" . $clang->gT("Security Question") . "</label><img id='captchaimage' src='{$rooturl}/verification.php?sid={$surveyid}' alt='captcha' /><input type='text' size='5' maxlength='3' name='loadsecurity' value='' />\n                          </li>";
                    }
                    echo "<li><input class='submit' type='submit' value='" . $clang->gT("Continue") . "' /></li>\n\t\t                </ul>\n\t\t                </form>\n\t\t                </id>";
                }
                echo '</div>' . templatereplace(file_get_contents("{$thistpl}/endpage.pstpl"));
                doFooter();
                exit;
            }
        }
    }
    //RESET ALL THE SESSION VARIABLES AND START AGAIN
    unset($_SESSION['grouplist']);
    unset($_SESSION['fieldarray']);
    unset($_SESSION['insertarray']);
    unset($_SESSION['thistoken']);
    unset($_SESSION['fieldnamesInfo']);
    $_SESSION['fieldnamesInfo'] = array();
    //RL: multilingual support
    if (isset($_GET['token']) && db_tables_exist($dbprefix . 'tokens_' . $surveyid)) {
        //get language from token (if one exists)
        $tkquery2 = "SELECT * FROM " . db_table_name('tokens_' . $surveyid) . " WHERE token='" . db_quote($clienttoken) . "' AND (completed = 'N' or completed='')";
        //echo $tkquery2;
        $result = db_execute_assoc($tkquery2) or safe_die("Couldn't get tokens<br />{$tkquery}<br />" . $connect->ErrorMsg());
        //Checked
        while ($rw = $result->FetchRow()) {
            $tklanguage = $rw['language'];
        }
    }
    if (returnglobal('lang')) {
        $language_to_set = returnglobal('lang');
    } elseif (isset($tklanguage)) {
        $language_to_set = $tklanguage;
    } else {
        $language_to_set = $thissurvey['language'];
    }
    if (!isset($_SESSION['s_lang'])) {
        SetSurveyLanguage($surveyid, $language_to_set);
    }
    UpdateSessionGroupList($_SESSION['s_lang']);
    // Optimized Query
    // Change query to use sub-select to see if conditions exist.
    $query = "SELECT " . db_table_name('questions') . ".*, " . db_table_name('groups') . ".*,\n" . " (SELECT count(1) FROM " . db_table_name('conditions') . "\n" . " WHERE " . db_table_name('questions') . ".qid = " . db_table_name('conditions') . ".qid) AS hasconditions,\n" . " (SELECT count(1) FROM " . db_table_name('conditions') . "\n" . " WHERE " . db_table_name('questions') . ".qid = " . db_table_name('conditions') . ".cqid) AS usedinconditions\n" . " FROM " . db_table_name('groups') . " INNER JOIN " . db_table_name('questions') . " ON " . db_table_name('groups') . ".gid = " . db_table_name('questions') . ".gid\n" . " WHERE " . db_table_name('questions') . ".sid=" . $surveyid . "\n" . " AND " . db_table_name('groups') . ".language='" . $_SESSION['s_lang'] . "'\n" . " AND " . db_table_name('questions') . ".language='" . $_SESSION['s_lang'] . "'\n" . " AND " . db_table_name('questions') . ".parent_qid=0\n" . " ORDER BY " . db_table_name('groups') . ".group_order," . db_table_name('questions') . ".question_order";
    //var_dump($_SESSION);
    $result = db_execute_assoc($query);
    //Checked
    $arows = $result->GetRows();
    $totalquestions = $result->RecordCount();
    //2. SESSION VARIABLE: totalsteps
    //The number of "pages" that will be presented in this survey
    //The number of pages to be presented will differ depending on the survey format
    switch ($thissurvey['format']) {
        case "A":
            $_SESSION['totalsteps'] = 1;
            break;
        case "G":
            if (isset($_SESSION['grouplist'])) {
                $_SESSION['totalsteps'] = count($_SESSION['grouplist']);
            }
            break;
        case "S":
            $_SESSION['totalsteps'] = $totalquestions;
    }
    if ($totalquestions == "0") {
        sendcacheheaders();
        doHeader();
        echo templatereplace(file_get_contents("{$thistpl}/startpage.pstpl"));
        echo templatereplace(file_get_contents("{$thistpl}/survey.pstpl"));
        echo "\t<center><br />\n" . "\t" . $clang->gT("This survey does not yet have any questions and cannot be tested or completed.") . "<br /><br />\n" . "\t" . sprintf($clang->gT("For further information contact %s"), $thissurvey['adminname']) . " (<a href='mailto:{$thissurvey['adminemail']}'>" . "{$thissurvey['adminemail']}</a>)<br /><br />\n";
        echo templatereplace(file_get_contents("{$thistpl}/endpage.pstpl"));
        doFooter();
        exit;
    }
    //Perform a case insensitive natural sort on group name then question title of a multidimensional array
    //	usort($arows, 'GroupOrderThenQuestionOrder');
    //3. SESSION VARIABLE - insertarray
    //An array containing information about used to insert the data into the db at the submit stage
    //4. SESSION VARIABLE - fieldarray
    //See rem at end..
    $_SESSION['token'] = $clienttoken;
    if ($thissurvey['private'] == "N") {
        $_SESSION['insertarray'][] = "token";
    }
    if ($tokensexist == 1 && $thissurvey['private'] == "N" && db_tables_exist($dbprefix . 'tokens_' . $surveyid)) {
        //Gather survey data for "non anonymous" surveys, for use in presenting questions
        $_SESSION['thistoken'] = getTokenData($surveyid, $clienttoken);
    }
    $qtypes = getqtypelist('', 'array');
    $fieldmap = createFieldMap($surveyid, 'full', false, false, $_SESSION['s_lang']);
    $_SESSION['fieldmap'] = $fieldmap;
    foreach ($fieldmap as $field) {
        if ($field['qid'] != '') {
            $_SESSION['fieldnamesInfo'][$field['fieldname']] = $field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid'];
            $_SESSION['insertarray'][] = $field['fieldname'];
            //fieldarray ARRAY CONTENTS -
            //            [0]=questions.qid,
            //			[1]=fieldname,
            //			[2]=questions.title,
            //			[3]=questions.question
            //                 	[4]=questions.type,
            //			[5]=questions.gid,
            //			[6]=questions.mandatory,
            //			[7]=conditionsexist,
            //			[8]=usedinconditions
            if (!isset($_SESSION['fieldarray'][$field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid']])) {
                $_SESSION['fieldarray'][$field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid']] = array($field['qid'], $field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid'], $field['title'], $field['question'], $field['type'], $field['gid'], $field['mandatory'], $field['hasconditions'], $field['usedinconditions']);
            }
        }
    }
    // Prefill question/answer from defaultvalues
    foreach ($fieldmap as $field) {
        if (isset($field['defaultvalue'])) {
            $_SESSION[$field['fieldname']] = $field['defaultvalue'];
        }
    }
    // Prefill questions/answers from command line params
    if (isset($_SESSION['insertarray'])) {
        foreach ($_SESSION['insertarray'] as $field) {
            if (isset($_GET[$field]) && $field != 'token') {
                $_SESSION[$field] = $_GET[$field];
            }
        }
    }
    $_SESSION['fieldarray'] = array_values($_SESSION['fieldarray']);
    // Check if the current survey language is set - if not set it
    // this way it can be changed later (for example by a special question type)
    //Check if a passthru label and value have been included in the query url
    if (isset($_GET['passthru']) && $_GET['passthru'] != "") {
        if (isset($_GET[$_GET['passthru']]) && $_GET[$_GET['passthru']] != "") {
            $_SESSION['passthrulabel'] = $_GET['passthru'];
            $_SESSION['passthruvalue'] = $_GET[$_GET['passthru']];
        }
    }
    return $totalquestions;
}
コード例 #12
0
/**
* This function builds all the required session variables when a survey is first started and
* it loads any answer defaults from command line or from the table defaultvalues
* It is called from the related format script (group.php, question.php, survey.php)
* if the survey has just started.
*
* @returns  $totalquestions Total number of questions in the survey
*
*/
function buildsurveysession()
{
    global $thissurvey, $secerror, $clienttoken, $databasetype;
    global $tokensexist, $thistpl;
    global $surveyid, $dbprefix, $connect;
    global $register_errormsg, $clang;
    global $totalBoilerplatequestions;
    global $templang, $move, $rooturl, $publicurl;
    if (!isset($templang) || $templang == '') {
        $templang = $thissurvey['language'];
    }
    $totalBoilerplatequestions = 0;
    $loadsecurity = returnglobal('loadsecurity');
    // NO TOKEN REQUIRED BUT CAPTCHA ENABLED FOR SURVEY ACCESS
    if ($tokensexist == 0 && captcha_enabled('surveyaccessscreen', $thissurvey['usecaptcha'])) {
        // IF CAPTCHA ANSWER IS NOT CORRECT OR NOT SET
        if (!isset($loadsecurity) || !isset($_SESSION['secanswer']) || $loadsecurity != $_SESSION['secanswer']) {
            sendcacheheaders();
            doHeader();
            // No or bad answer to required security question
            echo templatereplace(file_get_contents("{$thistpl}/startpage.pstpl"));
            //echo makedropdownlist();
            echo templatereplace(file_get_contents("{$thistpl}/survey.pstpl"));
            if (isset($loadsecurity)) {
                // was a bad answer
                echo "<font color='#FF0000'>" . $clang->gT("The answer to the security question is incorrect.") . "</font><br />";
            }
            echo "<p class='captcha'>" . $clang->gT("Please confirm access to survey by answering the security question below and click continue.") . "</p>\n\t\t\t        <form class='captcha' method='get' action='{$publicurl}/index.php'>\n\t\t\t        <table align='center'>\n\t\t\t\t        <tr>\n\t\t\t\t\t        <td align='right' valign='middle'>\n\t\t\t\t\t        <input type='hidden' name='sid' value='" . $surveyid . "' id='sid' />\n\t\t\t\t\t        <input type='hidden' name='lang' value='" . $templang . "' id='lang' />";
            // In case we this is a direct Reload previous answers URL, then add hidden fields
            if (isset($_GET['loadall']) && isset($_GET['scid']) && isset($_GET['loadname']) && isset($_GET['loadpass'])) {
                echo "\n\t\t\t\t\t\t<input type='hidden' name='loadall' value='" . htmlspecialchars($_GET['loadall']) . "' id='loadall' />\n\t\t\t\t\t\t<input type='hidden' name='scid' value='" . returnglobal('scid') . "' id='scid' />\n\t\t\t\t\t\t<input type='hidden' name='loadname' value='" . htmlspecialchars($_GET['loadname']) . "' id='loadname' />\n\t\t\t\t\t\t<input type='hidden' name='loadpass' value='" . htmlspecialchars($_GET['loadpass']) . "' id='loadpass' />";
            }
            echo "\n\t\t\t\t        </td>\n\t\t\t        </tr>";
            if (function_exists("ImageCreate") && captcha_enabled('surveyaccessscreen', $thissurvey['usecaptcha'])) {
                echo "<tr>\n\t\t\t\t                <td align='center' valign='middle'><label for='captcha'>" . $clang->gT("Security question:") . "</label></td><td align='left' valign='middle'><table><tr><td valign='middle'><img src='{$rooturl}/verification.php?sid={$surveyid}' alt='captcha' /></td>\n                                <td valign='middle'><input id='captcha' type='text' size='5' maxlength='3' name='loadsecurity' value='' /></td></tr></table>\n\t\t\t\t                </td>\n\t\t\t                </tr>";
            }
            echo "<tr><td colspan='2' align='center'><input class='submit' type='submit' value='" . $clang->gT("Continue") . "' /></td></tr>\n\t\t        </table>\n\t\t        </form>";
            echo templatereplace(file_get_contents("{$thistpl}/endpage.pstpl"));
            doFooter();
            exit;
        }
    }
    //BEFORE BUILDING A NEW SESSION FOR THIS SURVEY, LET'S CHECK TO MAKE SURE THE SURVEY SHOULD PROCEED!
    // TOKEN REQUIRED BUT NO TOKEN PROVIDED
    if ($tokensexist == 1 && !returnglobal('token')) {
        if ($thissurvey['nokeyboard'] == 'Y') {
            vIncludeKeypad();
            $kpclass = "text-keypad";
        } else {
            $kpclass = "";
        }
        // DISPLAY REGISTER-PAGE if needed
        // DISPLAY CAPTCHA if needed
        sendcacheheaders();
        doHeader();
        echo templatereplace(file_get_contents("{$thistpl}/startpage.pstpl"));
        //echo makedropdownlist();
        echo templatereplace(file_get_contents("{$thistpl}/survey.pstpl"));
        if (isset($thissurvey) && $thissurvey['allowregister'] == "Y") {
            echo templatereplace(file_get_contents("{$thistpl}/register.pstpl"));
        } else {
            if (isset($secerror)) {
                echo "<span class='error'>" . $secerror . "</span><br />";
            }
            echo '<div id="wrapper"><p id="tokenmessage">' . $clang->gT("This is a controlled survey. You need a valid token to participate.") . "<br />";
            echo $clang->gT("If you have been issued a token, please enter it in the box below and click continue.") . "</p>\n            <script type='text/javascript'>var focus_element='#token';</script>\n\t        <form id='tokenform' method='get' action='{$publicurl}/index.php'>\n                <ul>\n                <li>\n            <label for='token'>" . $clang->gT("Token") . "</label><input class='text {$kpclass}' id='token' type='text' name='token' />";
            echo "<input type='hidden' name='sid' value='" . $surveyid . "' id='sid' />\n\t\t\t\t<input type='hidden' name='lang' value='" . $templang . "' id='lang' />";
            if (isset($_GET['newtest']) && $_GET['newtest'] == "Y") {
                echo "  <input type='hidden' name='newtest' value='Y' id='newtest' />";
            }
            // If this is a direct Reload previous answers URL, then add hidden fields
            if (isset($_GET['loadall']) && isset($_GET['scid']) && isset($_GET['loadname']) && isset($_GET['loadpass'])) {
                echo "\n\t\t\t\t\t<input type='hidden' name='loadall' value='" . htmlspecialchars($_GET['loadall']) . "' id='loadall' />\n\t\t\t\t\t<input type='hidden' name='scid' value='" . returnglobal('scid') . "' id='scid' />\n\t\t\t\t\t<input type='hidden' name='loadname' value='" . htmlspecialchars($_GET['loadname']) . "' id='loadname' />\n\t\t\t\t\t<input type='hidden' name='loadpass' value='" . htmlspecialchars($_GET['loadpass']) . "' id='loadpass' />";
            }
            echo "</li>";
            if (function_exists("ImageCreate") && captcha_enabled('surveyaccessscreen', $thissurvey['usecaptcha'])) {
                echo "<li>\n\t\t\t                <label for='captchaimage'>" . $clang->gT("Security Question") . "</label><img id='captchaimage' src='{$rooturl}/verification.php?sid={$surveyid}' alt='captcha' /><input type='text' size='5' maxlength='3' name='loadsecurity' value='' />\n\t\t                  </li>";
            }
            echo "<li>\n                        <input class='submit' type='submit' value='" . $clang->gT("Continue") . "' />\n                      </li>\n            </ul>\n\t        </form></div>";
        }
        echo templatereplace(file_get_contents("{$thistpl}/endpage.pstpl"));
        doFooter();
        exit;
    } elseif ($tokensexist == 1 && returnglobal('token') && !captcha_enabled('surveyaccessscreen', $thissurvey['usecaptcha'])) {
        //check if tokens actually haven't been already used
        $areTokensUsed = usedTokens(db_quote(trim(strip_tags(returnglobal('token')))));
        //check if token actually does exist
        // check also if it is allowed to change survey after completion
        if ($thissurvey['alloweditaftercompletion'] == 'Y') {
            $tkquery = "SELECT COUNT(*) FROM " . db_table_name('tokens_' . $surveyid) . " WHERE token='" . db_quote(trim(strip_tags(returnglobal('token')))) . "' ";
        } else {
            $tkquery = "SELECT COUNT(*) FROM " . db_table_name('tokens_' . $surveyid) . " WHERE token='" . db_quote(trim(strip_tags(returnglobal('token')))) . "' AND (completed = 'N' or completed='')";
        }
        $tkresult = db_execute_num($tkquery);
        //Checked
        list($tkexist) = $tkresult->FetchRow();
        if (!$tkexist || $areTokensUsed && $thissurvey['alloweditaftercompletion'] != 'Y') {
            //TOKEN DOESN'T EXIST OR HAS ALREADY BEEN USED. EXPLAIN PROBLEM AND EXIT
            killSession();
            sendcacheheaders();
            doHeader();
            echo templatereplace(file_get_contents("{$thistpl}/startpage.pstpl"));
            echo templatereplace(file_get_contents("{$thistpl}/survey.pstpl"));
            echo '<div id="wrapper"><p id="tokenmessage">' . $clang->gT("This is a controlled survey. You need a valid token to participate.") . "<br /><br />\n" . "\t" . $clang->gT("The token you have provided is either not valid, or has already been used.") . "<br />\n" . "\t" . sprintf($clang->gT("For further information please contact %s"), $thissurvey['adminname']) . " (<a href='mailto:{$thissurvey['adminemail']}'>" . "{$thissurvey['adminemail']}</a>)</p></div>\n";
            echo templatereplace(file_get_contents("{$thistpl}/endpage.pstpl"));
            doFooter();
            exit;
        }
    } elseif ($tokensexist == 1 && returnglobal('token') && captcha_enabled('surveyaccessscreen', $thissurvey['usecaptcha'])) {
        // IF CAPTCHA ANSWER IS CORRECT
        if (isset($loadsecurity) && isset($_SESSION['secanswer']) && $loadsecurity == $_SESSION['secanswer']) {
            //check if tokens actually haven't been already used
            $areTokensUsed = usedTokens(db_quote(trim(strip_tags(returnglobal('token')))));
            //check if token actually does exist
            if ($thissurvey['alloweditaftercompletion'] == 'Y') {
                $tkquery = "SELECT COUNT(*) FROM " . db_table_name('tokens_' . $surveyid) . " WHERE token='" . db_quote(trim(sanitize_xss_string(strip_tags(returnglobal('token'))))) . "'";
            } else {
                $tkquery = "SELECT COUNT(*) FROM " . db_table_name('tokens_' . $surveyid) . " WHERE token='" . db_quote(trim(sanitize_xss_string(strip_tags(returnglobal('token'))))) . "' AND (completed = 'N' or completed='')";
            }
            $tkresult = db_execute_num($tkquery);
            //Checked
            list($tkexist) = $tkresult->FetchRow();
            if (!$tkexist || $areTokensUsed && $thissurvey['alloweditaftercompletion'] != 'Y') {
                sendcacheheaders();
                doHeader();
                //TOKEN DOESN'T EXIST OR HAS ALREADY BEEN USED. EXPLAIN PROBLEM AND EXIT
                echo templatereplace(file_get_contents("{$thistpl}/startpage.pstpl"));
                echo templatereplace(file_get_contents("{$thistpl}/survey.pstpl"));
                echo "\t<div id='wrapper'>\n" . "\t<p id='tokenmessage'>\n" . "\t" . $clang->gT("This is a controlled survey. You need a valid token to participate.") . "<br /><br />\n" . "\t" . $clang->gT("The token you have provided is either not valid, or has already been used.") . "<br/>\n" . "\t" . sprintf($clang->gT("For further information please contact %s"), $thissurvey['adminname']) . " (<a href='mailto:{$thissurvey['adminemail']}'>" . "{$thissurvey['adminemail']}</a>)\n" . "\t</p>\n" . "\t</div>\n";
                echo templatereplace(file_get_contents("{$thistpl}/endpage.pstpl"));
                doFooter();
                exit;
            }
        } else {
            if (!isset($move) || is_null($move)) {
                $gettoken = $clienttoken;
                sendcacheheaders();
                doHeader();
                // No or bad answer to required security question
                echo templatereplace(file_get_contents("{$thistpl}/startpage.pstpl"));
                echo templatereplace(file_get_contents("{$thistpl}/survey.pstpl"));
                // If token wasn't provided and public registration
                // is enabled then show registration form
                if (!isset($gettoken) && isset($thissurvey) && $thissurvey['allowregister'] == "Y") {
                    echo templatereplace(file_get_contents("{$thistpl}/register.pstpl"));
                } else {
                    // only show CAPTCHA
                    echo '<div id="wrapper"><p id="tokenmessage">';
                    if (isset($loadsecurity)) {
                        // was a bad answer
                        echo "<span class='error'>" . $clang->gT("The answer to the security question is incorrect.") . "</span><br />";
                    }
                    echo $clang->gT("This is a controlled survey. You need a valid token to participate.") . "<br /><br />";
                    // IF TOKEN HAS BEEN GIVEN THEN AUTOFILL IT
                    // AND HIDE ENTRY FIELD
                    if (!isset($gettoken)) {
                        echo $clang->gT("If you have been issued a token, please enter it in the box below and click continue.") . "</p>\n\t\t\t            <form id='tokenform' method='get' action='{$publicurl}/index.php'>\n                        <ul>\n                        <li>\n\t\t\t\t\t        <input type='hidden' name='sid' value='" . $surveyid . "' id='sid' />\n\t\t\t\t\t\t    <input type='hidden' name='lang' value='" . $templang . "' id='lang' />";
                        if (isset($_GET['loadall']) && isset($_GET['scid']) && isset($_GET['loadname']) && isset($_GET['loadpass'])) {
                            echo "<input type='hidden' name='loadall' value='" . htmlspecialchars($_GET['loadall']) . "' id='loadall' />\n\t\t\t\t\t\t        <input type='hidden' name='scid' value='" . returnglobal('scid') . "' id='scid' />\n\t\t\t\t\t\t        <input type='hidden' name='loadname' value='" . htmlspecialchars($_GET['loadname']) . "' id='loadname' />\n\t\t\t\t\t\t        <input type='hidden' name='loadpass' value='" . htmlspecialchars($_GET['loadpass']) . "' id='loadpass' />";
                        }
                        echo '<label for="token">' . $clang->gT("Token") . "</label><input class='text' type='text' id='token' name='token'></li>";
                    } else {
                        echo $clang->gT("Please confirm the token by answering the security question below and click continue.") . "</p>\n\t\t\t            <form id='tokenform' method='get' action='{$publicurl}/index.php'>\n                        <ul>\n\t\t\t            <li>\n\t\t\t\t\t            <input type='hidden' name='sid' value='" . $surveyid . "' id='sid' />\n\t\t\t\t\t\t        <input type='hidden' name='lang' value='" . $templang . "' id='lang' />";
                        if (isset($_GET['loadall']) && isset($_GET['scid']) && isset($_GET['loadname']) && isset($_GET['loadpass'])) {
                            echo "<input type='hidden' name='loadall' value='" . htmlspecialchars($_GET['loadall']) . "' id='loadall' />\n                              <input type='hidden' name='scid' value='" . returnglobal('scid') . "' id='scid' />\n                              <input type='hidden' name='loadname' value='" . htmlspecialchars($_GET['loadname']) . "' id='loadname' />\n                              <input type='hidden' name='loadpass' value='" . htmlspecialchars($_GET['loadpass']) . "' id='loadpass' />";
                        }
                        echo '<label for="token">' . $clang->gT("Token:") . "</label><span id='token'>{$gettoken}</span>" . "<input type='hidden' name='token' value='{$gettoken}'></li>";
                    }
                    if (function_exists("ImageCreate") && captcha_enabled('surveyaccessscreen', $thissurvey['usecaptcha'])) {
                        echo "<li>\n                            <label for='captchaimage'>" . $clang->gT("Security Question") . "</label><img id='captchaimage' src='{$rooturl}/verification.php?sid={$surveyid}' alt='captcha' /><input type='text' size='5' maxlength='3' name='loadsecurity' value='' />\n                          </li>";
                    }
                    echo "<li><input class='submit' type='submit' value='" . $clang->gT("Continue") . "' /></li>\n\t\t                </ul>\n\t\t                </form>\n\t\t                </id>";
                }
                echo '</div>' . templatereplace(file_get_contents("{$thistpl}/endpage.pstpl"));
                doFooter();
                unset($_SESSION['srid']);
                exit;
            }
        }
    }
    //RESET ALL THE SESSION VARIABLES AND START AGAIN
    unset($_SESSION['grouplist']);
    unset($_SESSION['fieldarray']);
    unset($_SESSION['insertarray']);
    unset($_SESSION['thistoken']);
    unset($_SESSION['fieldnamesInfo']);
    $_SESSION['fieldnamesInfo'] = array();
    //RL: multilingual support
    if (isset($_GET['token']) && db_tables_exist($dbprefix . 'tokens_' . $surveyid)) {
        //get language from token (if one exists)
        $tkquery2 = "SELECT * FROM " . db_table_name('tokens_' . $surveyid) . " WHERE token='" . db_quote($clienttoken) . "' AND (completed = 'N' or completed='')";
        //echo $tkquery2;
        $result = db_execute_assoc($tkquery2) or safe_die("Couldn't get tokens<br />{$tkquery}<br />" . $connect->ErrorMsg());
        //Checked
        while ($rw = $result->FetchRow()) {
            $tklanguage = $rw['language'];
        }
    }
    if (returnglobal('lang')) {
        $language_to_set = returnglobal('lang');
    } elseif (isset($tklanguage)) {
        $language_to_set = $tklanguage;
    } else {
        $language_to_set = $thissurvey['language'];
    }
    if (!isset($_SESSION['s_lang'])) {
        SetSurveyLanguage($surveyid, $language_to_set);
    }
    UpdateSessionGroupList($_SESSION['s_lang']);
    // Optimized Query
    // Change query to use sub-select to see if conditions exist.
    $query = "SELECT " . db_table_name('questions') . ".*, " . db_table_name('groups') . ".*,\n" . " (SELECT count(1) FROM " . db_table_name('conditions') . "\n" . " WHERE " . db_table_name('questions') . ".qid = " . db_table_name('conditions') . ".qid) AS hasconditions,\n" . " (SELECT count(1) FROM " . db_table_name('conditions') . "\n" . " WHERE " . db_table_name('questions') . ".qid = " . db_table_name('conditions') . ".cqid) AS usedinconditions\n" . " FROM " . db_table_name('groups') . " INNER JOIN " . db_table_name('questions') . " ON " . db_table_name('groups') . ".gid = " . db_table_name('questions') . ".gid\n" . " WHERE " . db_table_name('questions') . ".sid=" . $surveyid . "\n" . " AND " . db_table_name('groups') . ".language='" . $_SESSION['s_lang'] . "'\n" . " AND " . db_table_name('questions') . ".language='" . $_SESSION['s_lang'] . "'\n" . " AND " . db_table_name('questions') . ".parent_qid=0\n" . " ORDER BY " . db_table_name('groups') . ".group_order," . db_table_name('questions') . ".question_order";
    //var_dump($_SESSION);
    $result = db_execute_assoc($query);
    //Checked
    $arows = $result->GetRows();
    $totalquestions = $result->RecordCount();
    //2. SESSION VARIABLE: totalsteps
    //The number of "pages" that will be presented in this survey
    //The number of pages to be presented will differ depending on the survey format
    switch ($thissurvey['format']) {
        case "A":
            $_SESSION['totalsteps'] = 1;
            break;
        case "G":
            if (isset($_SESSION['grouplist'])) {
                $_SESSION['totalsteps'] = count($_SESSION['grouplist']);
            }
            break;
        case "S":
            $_SESSION['totalsteps'] = $totalquestions;
    }
    if ($totalquestions == "0") {
        sendcacheheaders();
        doHeader();
        echo templatereplace(file_get_contents("{$thistpl}/startpage.pstpl"));
        echo templatereplace(file_get_contents("{$thistpl}/survey.pstpl"));
        echo "\t<div id='wrapper'>\n" . "\t<p id='tokenmessage'>\n" . "\t" . $clang->gT("This survey does not yet have any questions and cannot be tested or completed.") . "<br /><br />\n" . "\t" . sprintf($clang->gT("For further information please contact %s"), $thissurvey['adminname']) . " (<a href='mailto:{$thissurvey['adminemail']}'>" . "{$thissurvey['adminemail']}</a>)<br /><br />\n" . "\t</p>\n" . "\t</div>\n";
        echo templatereplace(file_get_contents("{$thistpl}/endpage.pstpl"));
        doFooter();
        exit;
    }
    //Perform a case insensitive natural sort on group name then question title of a multidimensional array
    //	usort($arows, 'GroupOrderThenQuestionOrder');
    //3. SESSION VARIABLE - insertarray
    //An array containing information about used to insert the data into the db at the submit stage
    //4. SESSION VARIABLE - fieldarray
    //See rem at end..
    $_SESSION['token'] = $clienttoken;
    if ($thissurvey['anonymized'] == "N") {
        $_SESSION['insertarray'][] = "token";
    }
    if ($tokensexist == 1 && $thissurvey['anonymized'] == "N" && db_tables_exist($dbprefix . 'tokens_' . $surveyid)) {
        //Gather survey data for "non anonymous" surveys, for use in presenting questions
        $_SESSION['thistoken'] = getTokenData($surveyid, $clienttoken);
    }
    $qtypes = getqtypelist('', 'array');
    $fieldmap = createFieldMap($surveyid, 'full', false, false, $_SESSION['s_lang']);
    // Randomization Groups
    // Find all defined randomization groups through question attribute values
    $randomGroups = array();
    if ($databasetype == 'odbc_mssql' || $databasetype == 'odbtp' || $databasetype == 'mssql_n' || $databasetype == 'mssqlnative') {
        $rgquery = "SELECT attr.qid, CAST(value as varchar(255)) FROM " . db_table_name('question_attributes') . " as attr right join " . db_table_name('questions') . " as quests on attr.qid=quests.qid WHERE attribute='random_group' and CAST(value as varchar(255)) <> '' and sid={$surveyid} GROUP BY attr.qid, CAST(value as varchar(255))";
    } else {
        $rgquery = "SELECT attr.qid, value FROM " . db_table_name('question_attributes') . " as attr right join " . db_table_name('questions') . " as quests on attr.qid=quests.qid WHERE attribute='random_group' and value <> '' and sid={$surveyid} GROUP BY attr.qid, value";
    }
    $rgresult = db_execute_assoc($rgquery);
    while ($rgrow = $rgresult->FetchRow()) {
        // Get the question IDs for each randomization group
        $randomGroups[$rgrow['value']][] = $rgrow['qid'];
    }
    // If we have randomization groups set, then lets cycle through each group and
    // replace questions in the group with a randomly chosen one from the same group
    if (count($randomGroups) > 0) {
        $copyFieldMap = array();
        $oldQuestOrder = array();
        $newQuestOrder = array();
        $randGroupNames = array();
        foreach ($randomGroups as $key => $value) {
            $oldQuestOrder[$key] = $randomGroups[$key];
            $newQuestOrder[$key] = $oldQuestOrder[$key];
            // We shuffle the question list to get a random key->qid which will be used to swap from the old key
            shuffle($newQuestOrder[$key]);
            $randGroupNames[] = $key;
        }
        // Loop through the fieldmap and swap each question as they come up
        while (list($fieldkey, $fieldval) = each($fieldmap)) {
            $found = 0;
            foreach ($randomGroups as $gkey => $gval) {
                // We found a qid that is in the randomization group
                if (isset($fieldval['qid']) && in_array($fieldval['qid'], $oldQuestOrder[$gkey])) {
                    // Get the swapped question
                    $oldQuestFlip = array_flip($oldQuestOrder[$gkey]);
                    $qfieldmap = createFieldMap($surveyid, 'full', true, $newQuestOrder[$gkey][$oldQuestFlip[$fieldval['qid']]], $_SESSION['s_lang']);
                    unset($qfieldmap['id']);
                    unset($qfieldmap['submitdate']);
                    unset($qfieldmap['lastpage']);
                    unset($qfieldmap['lastpage']);
                    unset($qfieldmap['token']);
                    foreach ($qfieldmap as $tkey => $tval) {
                        // Assign the swapped question (Might be more than one field)
                        $tval['random_gid'] = $fieldval['gid'];
                        //$tval['gid'] = $fieldval['gid'];
                        $copyFieldMap[$tkey] = $tval;
                    }
                    $found = 1;
                    break;
                } else {
                    $found = 2;
                }
            }
            if ($found == 2) {
                $copyFieldMap[$fieldkey] = $fieldval;
            }
            reset($randomGroups);
        }
        $fieldmap = $copyFieldMap;
    }
    //die(print_r($fieldmap));
    $_SESSION['fieldmap'] = $fieldmap;
    foreach ($fieldmap as $field) {
        if (isset($field['qid']) && $field['qid'] != '') {
            $_SESSION['fieldnamesInfo'][$field['fieldname']] = $field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid'];
            $_SESSION['insertarray'][] = $field['fieldname'];
            //fieldarray ARRAY CONTENTS -
            //            [0]=questions.qid,
            //			[1]=fieldname,
            //			[2]=questions.title,
            //			[3]=questions.question
            //                 	[4]=questions.type,
            //			[5]=questions.gid,
            //			[6]=questions.mandatory,
            //			[7]=conditionsexist,
            //			[8]=usedinconditions
            //			[8]=usedinconditions
            //			[9]=used in group.php for question count
            //			[10]=new group id for question in randomization group (GroupbyGroup Mode)
            if (!isset($_SESSION['fieldarray'][$field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid']])) {
                $_SESSION['fieldarray'][$field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid']] = array($field['qid'], $field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid'], $field['title'], $field['question'], $field['type'], $field['gid'], $field['mandatory'], $field['hasconditions'], $field['usedinconditions']);
            }
            if (isset($field['random_gid'])) {
                $_SESSION['fieldarray'][$field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid']][10] = $field['random_gid'];
            }
        }
    }
    // Prefill question/answer from defaultvalues
    foreach ($fieldmap as $field) {
        if (isset($field['defaultvalue'])) {
            $_SESSION[$field['fieldname']] = $field['defaultvalue'];
        }
    }
    // Prefill questions/answers from command line params
    if (isset($_SESSION['insertarray'])) {
        foreach ($_SESSION['insertarray'] as $field) {
            if (isset($_GET[$field]) && $field != 'token') {
                $_SESSION[$field] = $_GET[$field];
            }
        }
    }
    if (isset($_SESSION['fieldarray'])) {
        $_SESSION['fieldarray'] = array_values($_SESSION['fieldarray']);
    }
    // Check if the current survey language is set - if not set it
    // this way it can be changed later (for example by a special question type)
    //Check if a passthru label and value have been included in the query url
    if (isset($_GET['passthru']) && $_GET['passthru'] != "") {
        if (isset($_GET[$_GET['passthru']]) && $_GET[$_GET['passthru']] != "") {
            $_SESSION['passthrulabel'] = $_GET['passthru'];
            $_SESSION['passthruvalue'] = $_GET[$_GET['passthru']];
        }
    } elseif (isset($_SERVER['QUERY_STRING'])) {
        $_SESSION['ls_initialquerystr'] = $_SERVER['QUERY_STRING'];
    }
    // END NEW
    // Fix totalquestions by substracting Test Display questions
    $sNoOfTextDisplayQuestions = (int) $connect->GetOne("SELECT count(*)\n" . " FROM " . db_table_name('questions') . " WHERE type='X'\n" . " AND sid={$surveyid}" . " AND language='" . $_SESSION['s_lang'] . "'" . " AND parent_qid=0");
    $_SESSION['therearexquestions'] = $totalquestions - $sNoOfTextDisplayQuestions;
    // must be global for THEREAREXQUESTIONS replacement field to work
    return $totalquestions - $sNoOfTextDisplayQuestions;
}
コード例 #13
0
 /**
  * TSV survey definition in format readable by TSVSurveyImport
  * one line each per group, question, sub-question, and answer
  * does not use SGQA naming at all.
  * @param type $sid
  * @return type
  */
 public static function &TSVSurveyExport($sid)
 {
     $aBaseFields = array('class', 'type/scale', 'name', 'relevance', 'text', 'help', 'language', 'validation', 'mandatory', 'other', 'default', 'same_default');
     // Advanced question attributes : @todo get used question attribute by question in survey ?
     $aQuestionAttributes = array_keys(\ls\helpers\questionHelper::getAttributesDefinitions());
     sort($aQuestionAttributes);
     $fields = array_merge($aBaseFields, $aQuestionAttributes);
     $rows = array();
     $primarylang = 'en';
     $otherlangs = '';
     $langs = array();
     // Export survey-level information
     $query = "select * from {{surveys}} where sid = " . $sid;
     $data = dbExecuteAssoc($query);
     foreach ($data->readAll() as $r) {
         foreach ($r as $key => $value) {
             if ($value != '') {
                 $row['class'] = 'S';
                 $row['name'] = $key;
                 $row['text'] = $value;
                 $rows[] = $row;
             }
             if ($key == 'language') {
                 $primarylang = $value;
             }
             if ($key == 'additional_languages') {
                 $otherlangs = $value;
             }
         }
     }
     $langs = explode(' ', $primarylang . ' ' . $otherlangs);
     $langs = array_unique($langs);
     // Export survey language settings
     $query = "select * from {{surveys_languagesettings}} where surveyls_survey_id = " . $sid;
     $data = dbExecuteAssoc($query);
     foreach ($data->readAll() as $r) {
         $_lang = $r['surveyls_language'];
         foreach ($r as $key => $value) {
             if ($value != '' && $key != 'surveyls_language' && $key != 'surveyls_survey_id') {
                 $row['class'] = 'SL';
                 $row['name'] = $key;
                 $row['text'] = $value;
                 $row['language'] = $_lang;
                 $rows[] = $row;
             }
         }
     }
     $surveyinfo = getSurveyInfo($sid);
     $assessments = false;
     if (isset($surveyinfo['assessments']) && $surveyinfo['assessments'] == 'Y') {
         $assessments = true;
     }
     foreach ($langs as $lang) {
         if (trim($lang) == '') {
             continue;
         }
         SetSurveyLanguage($sid, $lang);
         LimeExpressionManager::StartSurvey($sid, 'survey', array('sgqaNaming' => 'N', 'assessments' => $assessments), true);
         $moveResult = LimeExpressionManager::NavigateForwards();
         $LEM =& LimeExpressionManager::singleton();
         if (is_null($moveResult) || is_null($LEM->currentQset) || count($LEM->currentQset) == 0) {
             continue;
         }
         $_gseq = -1;
         foreach ($LEM->currentQset as $q) {
             $gseq = $q['info']['gseq'];
             $gid = $q['info']['gid'];
             $qid = $q['info']['qid'];
             //////
             // SHOW GROUP-LEVEL INFO
             //////
             if ($gseq != $_gseq) {
                 $_gseq = $gseq;
                 $ginfo = $LEM->gseq2info[$gseq];
                 // if relevance equation is using SGQA coding, convert to qcoding
                 $grelevance = $ginfo['grelevance'] == '' ? 1 : $ginfo['grelevance'];
                 $LEM->em->ProcessBooleanExpression($grelevance, $gseq, 0);
                 // $qseq
                 $grelevance = trim(strip_tags($LEM->em->GetPrettyPrintString()));
                 $gtext = trim($ginfo['description']) == '' ? '' : $ginfo['description'];
                 $row = array();
                 $row['class'] = 'G';
                 //create a group code to allow proper importing of multi-lang survey TSVs
                 $row['type/scale'] = 'G' . $gseq;
                 $row['name'] = $ginfo['group_name'];
                 $row['relevance'] = $grelevance;
                 $row['text'] = $gtext;
                 $row['language'] = $lang;
                 $row['random_group'] = $ginfo['randomization_group'];
                 $rows[] = $row;
             }
             //////
             // SHOW QUESTION-LEVEL INFO
             //////
             $row = array();
             $mandatory = $q['info']['mandatory'] == 'Y' ? 'Y' : '';
             $type = $q['info']['type'];
             $sgqas = explode('|', $q['sgqa']);
             if (count($sgqas) == 1 && !is_null($q['info']['default'])) {
                 $default = $q['info']['default'];
             } else {
                 $default = '';
             }
             $qtext = $q['info']['qtext'] != '' ? $q['info']['qtext'] : '';
             $help = $q['info']['help'] != '' ? $q['info']['help'] : '';
             //////
             // SHOW QUESTION ATTRIBUTES THAT ARE PROCESSED BY EM
             //////
             if (isset($LEM->qattr[$qid]) && count($LEM->qattr[$qid]) > 0) {
                 foreach ($LEM->qattr[$qid] as $key => $value) {
                     if (is_null($value) || trim($value) == '') {
                         continue;
                     }
                     switch ($key) {
                         default:
                         case 'exclude_all_others':
                         case 'exclude_all_others_auto':
                         case 'hidden':
                             if ($value == false || $value == '0') {
                                 $value = NULL;
                                 // so can skip this one - just using continue here doesn't work.
                             }
                             break;
                         case 'relevance':
                             $value = NULL;
                             // means an outdate database structure
                             break;
                     }
                     if (is_null($value) || trim($value) == '') {
                         continue;
                         // since continuing from within a switch statement doesn't work
                     }
                     $row[$key] = $value;
                 }
             }
             // if relevance equation is using SGQA coding, convert to qcoding
             $relevanceEqn = $q['info']['relevance'] == '' ? 1 : $q['info']['relevance'];
             $LEM->em->ProcessBooleanExpression($relevanceEqn, $gseq, $q['info']['qseq']);
             // $qseq
             $relevanceEqn = trim(preg_replace("#</(span|a)>#i", "", preg_replace("#<(span|a)[^>]+\\>#i", "", $LEM->em->GetPrettyPrintString())));
             // Relevance can not have HTML : only span and a are returned from GetPrettyPrintString
             $rootVarName = $q['info']['rootVarName'];
             $preg = '';
             if (isset($LEM->q2subqInfo[$q['info']['qid']]['preg'])) {
                 $preg = $LEM->q2subqInfo[$q['info']['qid']]['preg'];
                 if (is_null($preg)) {
                     $preg = '';
                 }
             }
             $row['class'] = 'Q';
             $row['type/scale'] = $type;
             $row['name'] = $rootVarName;
             $row['relevance'] = $relevanceEqn;
             $row['text'] = $qtext;
             $row['help'] = $help;
             $row['language'] = $lang;
             $row['validation'] = $preg;
             $row['mandatory'] = $mandatory;
             $row['other'] = $q['info']['other'];
             $row['default'] = $default;
             $row['same_default'] = 1;
             // TODO - need this: $q['info']['same_default'];
             $rows[] = $row;
             //////
             // SHOW ALL SUB-QUESTIONS
             //////
             $sawThis = array();
             // array of rowdivids already seen so only show them once
             foreach ($sgqas as $sgqa) {
                 if ($LEM->knownVars[$sgqa]['qcode'] == $rootVarName) {
                     continue;
                     // so don't show the main question as a sub-question too
                 }
                 $rowdivid = $sgqa;
                 $varName = $LEM->knownVars[$sgqa]['qcode'];
                 // if SQrelevance equation is using SGQA coding, convert to qcoding
                 $SQrelevance = $LEM->knownVars[$sgqa]['SQrelevance'] == '' ? 1 : $LEM->knownVars[$sgqa]['SQrelevance'];
                 $LEM->em->ProcessBooleanExpression($SQrelevance, $gseq, $q['info']['qseq']);
                 $SQrelevance = trim(preg_replace("#</(span|a)>#i", "", preg_replace("#<(span|a)[^>]+\\>#i", "", $LEM->em->GetPrettyPrintString())));
                 // Relevance can not have HTML : only span and a are returned from GetPrettyPrintString
                 switch ($q['info']['type']) {
                     case '1':
                         if (preg_match('/#1$/', $sgqa)) {
                             $rowdivid = NULL;
                             // so that doesn't show same message for second scale
                         } else {
                             $rowdivid = substr($sgqa, 0, -2);
                             // strip suffix
                             $varName = substr($LEM->knownVars[$sgqa]['qcode'], 0, -2);
                         }
                         break;
                     case 'P':
                         if (preg_match('/comment$/', $sgqa)) {
                             $rowdivid = NULL;
                         }
                         break;
                     case ':':
                     case ';':
                         $_rowdivid = $LEM->knownVars[$sgqa]['rowdivid'];
                         if (isset($sawThis[$qid . '~' . $_rowdivid])) {
                             $rowdivid = NULL;
                             // so don't show again
                         } else {
                             $sawThis[$qid . '~' . $_rowdivid] = true;
                             $rowdivid = $_rowdivid;
                             $sgqa_len = strlen($sid . 'X' . $gid . 'X' . $qid);
                             $varName = $rootVarName . '_' . substr($_rowdivid, $sgqa_len);
                         }
                         break;
                 }
                 if (is_null($rowdivid)) {
                     continue;
                 }
                 $sgqaInfo = $LEM->knownVars[$sgqa];
                 $subqText = $sgqaInfo['subqtext'];
                 if (isset($sgqaInfo['default'])) {
                     $default = $sgqaInfo['default'];
                 } else {
                     $default = '';
                 }
                 $row = array();
                 $row['class'] = 'SQ';
                 $row['type/scale'] = 0;
                 $row['name'] = substr($varName, strlen($rootVarName) + 1);
                 $row['relevance'] = $SQrelevance;
                 $row['text'] = $subqText;
                 $row['language'] = $lang;
                 $row['default'] = $default;
                 $rows[] = $row;
             }
             //////
             // SHOW ANSWER OPTIONS FOR ENUMERATED LISTS, AND FOR MULTIFLEXI
             //////
             if (isset($LEM->qans[$qid]) || isset($LEM->multiflexiAnswers[$qid])) {
                 $_scale = -1;
                 if (isset($LEM->multiflexiAnswers[$qid])) {
                     $ansList = $LEM->multiflexiAnswers[$qid];
                 } else {
                     $ansList = $LEM->qans[$qid];
                 }
                 foreach ($ansList as $ans => $value) {
                     $ansInfo = explode('~', $ans);
                     $valParts = explode('|', $value);
                     $valInfo[0] = array_shift($valParts);
                     $valInfo[1] = implode('|', $valParts);
                     if ($_scale != $ansInfo[0]) {
                         $_scale = $ansInfo[0];
                     }
                     $row = array();
                     if ($type == ':' || $type == ';') {
                         $row['class'] = 'SQ';
                     } else {
                         $row['class'] = 'A';
                     }
                     $row['type/scale'] = $_scale;
                     $row['name'] = $ansInfo[1];
                     $row['relevance'] = $assessments == true ? $valInfo[0] : '';
                     $row['text'] = $valInfo[1];
                     $row['language'] = $lang;
                     $rows[] = $row;
                 }
             }
         }
     }
     // Now generate the array out output data
     $out = array();
     $out[] = $fields;
     foreach ($rows as $row) {
         $tsv = array();
         foreach ($fields as $field) {
             $val = isset($row[$field]) ? $row[$field] : '';
             $tsv[] = $val;
         }
         $out[] = $tsv;
     }
     return $out;
 }
コード例 #14
0
/**
 * This function builds all the required session variables when a survey is first started and
 * it loads any answer defaults from command line or from the table defaultvalues
 * It is called from the related format script (group.php, question.php, survey.php)
 * if the survey has just started.
 * @param int $surveyid
 * @param boolean $preview Defaults to false
 * @return void
 */
function buildsurveysession($surveyid, $preview = false)
{
    Yii::trace('start', 'survey.buildsurveysession');
    global $secerror, $clienttoken;
    global $tokensexist;
    global $move, $rooturl;
    $sLangCode = App()->language;
    $languagechanger = makeLanguageChangerSurvey($sLangCode);
    if (!$preview) {
        $preview = Yii::app()->getConfig('previewmode');
    }
    $thissurvey = getSurveyInfo($surveyid, $sLangCode);
    if ($thissurvey['nokeyboard'] == 'Y') {
        includeKeypad();
        $kpclass = "text-keypad";
    } else {
        $kpclass = '';
    }
    // $thissurvey['template'] already fixed by model : but why put this in session ?
    $_SESSION['survey_' . $surveyid]['templatename'] = $thissurvey['template'];
    $_SESSION['survey_' . $surveyid]['templatepath'] = getTemplatePath($thissurvey['template']) . DIRECTORY_SEPARATOR;
    $sTemplatePath = $_SESSION['survey_' . $surveyid]['templatepath'];
    $oTemplate = Template::model()->getInstance('', $surveyid);
    $sTemplatePath = $oTemplate->path;
    $sTemplateViewPath = $oTemplate->viewPath;
    /**
     * This method has multiple outcomes that virtually do the same thing
     * Possible scenarios/subscenarios are =>
     *   - No token required & no captcha required
     *   - No token required & captcha required
     *       > captcha may be wrong
     *   - token required & captcha required
     *       > token may be wrong/used
     *       > captcha may be wrong
     */
    $scenarios = array("tokenRequired" => $tokensexist == 1, "captchaRequired" => isCaptchaEnabled('surveyaccessscreen', $thissurvey['usecaptcha']) && !isset($_SESSION['survey_' . $surveyid]['captcha_surveyaccessscreen']));
    /**
     *   Set subscenarios depending on scenario outcome
     */
    $subscenarios = array("captchaCorrect" => false, "tokenValid" => false);
    //Check the scenario for token required
    if ($scenarios['tokenRequired']) {
        //Check for the token-validity
        if ($thissurvey['alloweditaftercompletion'] == 'Y') {
            $oTokenEntry = Token::model($surveyid)->findByAttributes(array('token' => $clienttoken));
        } else {
            $oTokenEntry = Token::model($surveyid)->usable()->incomplete()->findByAttributes(array('token' => $clienttoken));
        }
        $subscenarios['tokenValid'] = !empty($oTokenEntry) && $clienttoken != "";
    } else {
        $subscenarios['tokenValid'] = true;
    }
    //Check the scenario for captcha required
    if ($scenarios['captchaRequired']) {
        //Check if the Captcha was correct
        $loadsecurity = returnGlobal('loadsecurity', true);
        $captcha = Yii::app()->getController()->createAction('captcha');
        $subscenarios['captchaCorrect'] = $captcha->validate($loadsecurity, false);
    } else {
        $subscenarios['captchaCorrect'] = true;
        $loadsecurity = false;
    }
    //RenderWay defines which html gets rendered to the user_error
    // Possibilities are main,register,correct
    $renderCaptcha = "";
    $renderToken = "";
    //Define array to render the partials
    $aEnterTokenData = array();
    $aEnterTokenData['bNewTest'] = false;
    $aEnterTokenData['bDirectReload'] = false;
    $aEnterTokenData['error'] = $secerror;
    $aEnterTokenData['iSurveyId'] = $surveyid;
    $aEnterTokenData['sKpClass'] = $kpclass;
    // ???
    $aEnterTokenData['sLangCode'] = $sLangCode;
    if (isset($_GET['bNewTest']) && $_GET['newtest'] == "Y") {
        $aEnterTokenData['bNewTest'] = true;
    }
    // If this is a direct Reload previous answers URL, then add hidden fields
    if (isset($loadall) && isset($scid) && isset($loadname) && isset($loadpass)) {
        $aEnterTokenData['bDirectReload'] = true;
        $aEnterTokenData['sCid'] = $scid;
        $aEnterTokenData['sLoadname'] = htmlspecialchars($loadname);
        $aEnterTokenData['sLoadpass'] = htmlspecialchars($loadpass);
    }
    $FlashError = "";
    // Scenario => Captcha required
    if ($scenarios['captchaRequired'] && !$preview) {
        list($renderCaptcha, $FlashError) = testCaptcha($aEnterTokenData, $subscenarios, $surveyid, $loadsecurity);
    }
    // Scenario => Token required
    if ($scenarios['tokenRequired'] && !$preview) {
        //Test if token is valid
        list($renderToken, $FlashError) = testIfTokenIsValid($subscenarios, $thissurvey, $aEnterTokenData, $clienttoken);
    }
    //If there were errors, display through yii->FlashMessage
    if ($FlashError !== "") {
        $aEnterTokenData['errorMessage'] = $FlashError;
    }
    $renderWay = getRenderWay($renderToken, $renderCaptcha);
    $redata = compact(array_keys(get_defined_vars()));
    renderRenderWayForm($renderWay, $redata, $scenarios, $sTemplateViewPath, $aEnterTokenData, $surveyid);
    // Reset all the session variables and start again
    resetAllSessionVariables($surveyid);
    // Multi lingual support order : by REQUEST, if not by Token->language else by survey default language
    if (returnGlobal('lang', true)) {
        $language_to_set = returnGlobal('lang', true);
    } elseif (isset($oTokenEntry) && $oTokenEntry) {
        // If survey have token : we have a $oTokenEntry
        // Can use $oTokenEntry = Token::model($surveyid)->findByAttributes(array('token'=>$clienttoken)); if we move on another function : this par don't validate the token validity
        $language_to_set = $oTokenEntry->language;
    } else {
        $language_to_set = $thissurvey['language'];
    }
    // Always SetSurveyLanguage : surveys controller SetSurveyLanguage too, if different : broke survey (#09769)
    SetSurveyLanguage($surveyid, $language_to_set);
    UpdateGroupList($surveyid, $_SESSION['survey_' . $surveyid]['s_lang']);
    $totalquestions = Question::model()->getTotalQuestions($surveyid);
    $iTotalGroupsWithoutQuestions = QuestionGroup::model()->getTotalGroupsWithoutQuestions($surveyid);
    // Fix totalquestions by substracting Test Display questions
    $iNumberofQuestions = Question::model()->getNumberOfQuestions($surveyid);
    $_SESSION['survey_' . $surveyid]['totalquestions'] = $totalquestions - (int) reset($iNumberofQuestions);
    // 2. SESSION VARIABLE: totalsteps
    setTotalSteps($surveyid, $thissurvey, $totalquestions);
    // Break out and crash if there are no questions!
    if ($totalquestions == 0 || $iTotalGroupsWithoutQuestions > 0) {
        $redata = compact(array_keys(get_defined_vars()));
        breakOutAndCrash($redata, $sTemplateViewPath, $totalquestions, $iTotalGroupsWithoutQuestions, $thissurvey);
    }
    //Perform a case insensitive natural sort on group name then question title of a multidimensional array
    //    usort($arows, 'groupOrderThenQuestionOrder');
    //3. SESSION VARIABLE - insertarray
    //An array containing information about used to insert the data into the db at the submit stage
    //4. SESSION VARIABLE - fieldarray
    //See rem at end..
    if ($tokensexist == 1 && $clienttoken) {
        $_SESSION['survey_' . $surveyid]['token'] = $clienttoken;
    }
    if ($thissurvey['anonymized'] == "N") {
        $_SESSION['survey_' . $surveyid]['insertarray'][] = "token";
    }
    $qtypes = getQuestionTypeList('', 'array');
    $fieldmap = createFieldMap($surveyid, 'full', true, false, $_SESSION['survey_' . $surveyid]['s_lang']);
    //$seed = ls\mersenne\getSeed($surveyid, $preview);
    // Randomization groups for groups
    list($fieldmap, $randomized1) = randomizationGroup($surveyid, $fieldmap, $preview);
    // Randomization groups for questions
    list($fieldmap, $randomized2) = randomizationQuestion($surveyid, $fieldmap, $preview);
    $randomized = $randomized1 || $randomized2;
    if ($randomized === true) {
        $fieldmap = finalizeRandomization($fieldmap);
        $_SESSION['survey_' . $surveyid]['fieldmap-' . $surveyid . $_SESSION['survey_' . $surveyid]['s_lang']] = $fieldmap;
        $_SESSION['survey_' . $surveyid]['fieldmap-' . $surveyid . '-randMaster'] = 'fieldmap-' . $surveyid . $_SESSION['survey_' . $surveyid]['s_lang'];
    }
    // TMSW Condition->Relevance:  don't need hasconditions, or usedinconditions
    $_SESSION['survey_' . $surveyid]['fieldmap'] = $fieldmap;
    initFieldArray($surveyid, $fieldmap);
    // Prefill questions/answers from command line params
    prefillFromCommandLine($surveyid);
    if (isset($_SESSION['survey_' . $surveyid]['fieldarray'])) {
        $_SESSION['survey_' . $surveyid]['fieldarray'] = array_values($_SESSION['survey_' . $surveyid]['fieldarray']);
    }
    //Check if a passthru label and value have been included in the query url
    checkPassthruLabel($surveyid, $preview, $fieldmap);
    Yii::trace('end', 'survey.buildsurveysession');
    //traceVar($_SESSION['survey_' . $surveyid]);
}
コード例 #15
0
background-color:white;
}

.LEMerror
{
color:red;
font-weight:bold;
}

tr.LEMsubq td
{
background-color:lightyellow;
}
</style>
</head>
<body>
EOD;


    SetSurveyLanguage($surveyid, $language);
    LimeExpressionManager::SetDirtyFlag();
    $result = LimeExpressionManager::ShowSurveyLogicFile($surveyid, $gid, $qid,$LEMdebugLevel,$assessments);
    print $result['html'];

    print <<< EOD
</body>
</html>
EOD;
}
?>
コード例 #16
0
    function run($actionID)
    {
        if (isset($_SESSION['LEMsid']) && ($oSurvey = Survey::model()->findByPk($_SESSION['LEMsid']))) {
            $surveyid = $_SESSION['LEMsid'];
        } else {
            throw new CHttpException(400);
            // See for debug > 1
        }
        if (isset($_SESSION['survey_' . $surveyid]['s_lang'])) {
            $sLanguage = $_SESSION['survey_' . $surveyid]['s_lang'];
        } else {
            $sLanguage = '';
        }
        $clang = SetSurveyLanguage($surveyid, $sLanguage);
        $uploaddir = Yii::app()->getConfig("uploaddir");
        $tempdir = Yii::app()->getConfig("tempdir");
        Yii::app()->loadHelper("database");
        // Fill needed var
        $sFileGetContent = Yii::app()->request->getParam('filegetcontents', '');
        // The file to view fu_ or fu_tmp
        $bDelete = Yii::app()->request->getParam('delete');
        $sFieldName = Yii::app()->request->getParam('fieldname');
        $sFileName = Yii::app()->request->getParam('filename', '');
        // The file to delete fu_ or fu_tmp
        $sOriginalFileName = Yii::app()->request->getParam('name', '');
        // Used for javascript return only
        $sMode = Yii::app()->request->getParam('mode');
        $sPreview = Yii::app()->request->getParam('preview', 0);
        // Validate and filter and throw error if problems
        // Using 'futmp_'.randomChars(15).'_'.$pathinfo['extension'] for filename, then remove all other characters
        $sFileGetContentFiltered = preg_replace('/[^a-zA-Z0-9_]/', '', $sFileGetContent);
        $sFileNameFiltered = preg_replace('/[^a-zA-Z0-9_]/', '', $sFileName);
        $sFieldNameFiltered = preg_replace('/[^X0-9]/', '', $sFieldName);
        if ($sFileGetContent != $sFileGetContentFiltered || $sFileName != $sFileNameFiltered || $sFieldName != $sFieldNameFiltered) {
            // If one seems to be a hack: Bad request
            throw new CHttpException(400);
            // See for debug > 1
        }
        if ($sFileGetContent) {
            if (substr($sFileGetContent, 0, 6) == 'futmp_') {
                $sFileDir = $tempdir . '/upload/';
            } elseif (substr($sFileGetContent, 0, 3) == 'fu_') {
                // Need to validate $_SESSION['srid'], and this file is from this srid !
                $sFileDir = "{$uploaddir}/surveys/{$surveyid}/files/";
            } else {
                throw new CHttpException(400);
                // See for debug > 1
            }
            if (is_file($sFileDir . $sFileGetContent)) {
                header('Content-Type: ' . CFileHelper::getMimeType($sFileDir . $sFileGetContent));
                readfile($sFileDir . $sFileGetContent);
                Yii::app()->end();
            } else {
                Yii::app()->end();
            }
        } elseif ($bDelete) {
            if (substr($sFileName, 0, 6) == 'futmp_') {
                $sFileDir = $tempdir . '/upload/';
            } elseif (substr($sFileName, 0, 3) == 'fu_') {
                // Need to validate $_SESSION['srid'], and this file is from this srid !
                $sFileDir = "{$uploaddir}/surveys/{$surveyid}/files/";
            } else {
                throw new CHttpException(400);
                // See for debug > 1
            }
            if (isset($_SESSION[$sFieldName])) {
                // We already have $sFieldName ?
                $sJSON = $_SESSION[$sFieldName];
                $aFiles = json_decode(stripslashes($sJSON), true);
                if (substr($sFileName, 0, 3) == 'fu_') {
                    $iFileIndex = 0;
                    $found = false;
                    foreach ($aFiles as $aFile) {
                        if ($aFile['filename'] == $sFileName) {
                            $found = true;
                            break;
                        }
                        $iFileIndex++;
                    }
                    if ($found == true) {
                        unset($aFiles[$iFileIndex]);
                    }
                    $_SESSION[$sFieldName] = ls_json_encode($aFiles);
                }
            }
            //var_dump($sFileDir.$sFilename);
            // Return some json to do a beautiful text
            if (@unlink($sFileDir . $sFileName)) {
                echo sprintf($clang->gT('File %s deleted'), $sOriginalFileName);
            } else {
                echo $clang->gT('Oops, There was an error deleting the file');
            }
            Yii::app()->end();
        }
        if ($sMode == "upload") {
            $clang = Yii::app()->lang;
            $sTempUploadDir = $tempdir . '/upload/';
            // Check if exists and is writable
            if (!file_exists($sTempUploadDir)) {
                // Try to create
                mkdir($sTempUploadDir);
            }
            $filename = $_FILES['uploadfile']['name'];
            // Do we filter file name ? It's used on displaying only , but not save like that.
            //$filename = sanitize_filename($_FILES['uploadfile']['name']);// This remove all non alpha numeric characters and replaced by _ . Leave only one dot .
            $size = 0.001 * $_FILES['uploadfile']['size'];
            $preview = Yii::app()->session['preview'];
            $aFieldMap = createFieldMap($surveyid, 'short', false, false, $sLanguage);
            if (!isset($aFieldMap[$sFieldName])) {
                throw new CHttpException(400);
                // See for debug > 1
            }
            $aAttributes = getQuestionAttributeValues($aFieldMap[$sFieldName]['qid'], $aFieldMap[$sFieldName]['type']);
            $maxfilesize = (int) $aAttributes['max_filesize'];
            $valid_extensions_array = explode(",", $aAttributes['allowed_filetypes']);
            $valid_extensions_array = array_map('trim', $valid_extensions_array);
            $pathinfo = pathinfo($_FILES['uploadfile']['name']);
            $ext = $pathinfo['extension'];
            $randfilename = 'futmp_' . randomChars(15) . '_' . $pathinfo['extension'];
            $randfileloc = $sTempUploadDir . $randfilename;
            // check to see that this file type is allowed
            // it is also  checked at the client side, but jst double checking
            if (!in_array(strtolower($ext), $valid_extensions_array)) {
                $return = array("success" => false, "msg" => sprintf($clang->gT("Sorry, this file extension (%s) is not allowed!"), $ext));
                //header('Content-Type: application/json');
                echo ls_json_encode($return);
                Yii::app()->end();
            }
            // If this is just a preview, don't save the file
            if ($preview) {
                if ($size > $maxfilesize) {
                    $return = array("success" => false, "msg" => sprintf($clang->gT("Sorry, this file is too large. Only files upto %s KB are allowed."), $maxfilesize));
                    //header('Content-Type: application/json');
                    echo ls_json_encode($return);
                    Yii::app()->end();
                } else {
                    if (move_uploaded_file($_FILES['uploadfile']['tmp_name'], $randfileloc)) {
                        $return = array("success" => true, "file_index" => $filecount, "size" => $size, "name" => rawurlencode(basename($filename)), "ext" => $ext, "filename" => $randfilename, "msg" => $clang->gT("The file has been successfuly uploaded."));
                        // TODO : unlink this file since this is just a preview. But we can do it only if it's not needed, and still needed to have the file content
                        // Maybe use a javascript 'onunload' on preview question/group
                        // unlink($randfileloc)
                        //header('Content-Type: application/json');
                        echo ls_json_encode($return);
                        Yii::app()->end();
                    }
                }
            } else {
                // if everything went fine and the file was uploaded successfuly,
                // send the file related info back to the client
                $iFileUploadTotalSpaceMB = Yii::app()->getConfig("iFileUploadTotalSpaceMB");
                if ($size > $maxfilesize) {
                    $return = array("success" => false, "msg" => sprintf($clang->gT("Sorry, this file is too large. Only files up to %s KB are allowed.", 'unescaped'), $maxfilesize));
                    //header('Content-Type: application/json');
                    echo ls_json_encode($return);
                    Yii::app()->end();
                } elseif ($iFileUploadTotalSpaceMB > 0 && calculateTotalFileUploadUsage() + $size / 1024 / 1024 > $iFileUploadTotalSpaceMB) {
                    $return = array("success" => false, "msg" => $clang->gT("We are sorry but there was a system error and your file was not saved. An email has been dispatched to notify the survey administrator.", 'unescaped'));
                    //header('Content-Type: application/json');
                    echo ls_json_encode($return);
                    Yii::app()->end();
                } elseif (move_uploaded_file($_FILES['uploadfile']['tmp_name'], $randfileloc)) {
                    $return = array("success" => true, "size" => $size, "name" => rawurlencode(basename($filename)), "ext" => $ext, "filename" => $randfilename, "msg" => $clang->gT("The file has been successfuly uploaded."));
                    //header('Content-Type: application/json');
                    echo ls_json_encode($return);
                    Yii::app()->end();
                } else {
                    // check for upload error
                    if ($_FILES['uploadfile']['error'] > 2) {
                        $return = array("success" => false, "msg" => $clang->gT("Sorry, there was an error uploading your file"));
                        //header('Content-Type: application/json');
                        echo ls_json_encode($return);
                        Yii::app()->end();
                    } else {
                        if ($_FILES['uploadfile']['error'] == 1 || $_FILES['uploadfile']['error'] == 2 || $size > $maxfilesize) {
                            $return = array("success" => false, "msg" => sprintf($clang->gT("Sorry, this file is too large. Only files upto %s KB are allowed."), $maxfilesize));
                            //header('Content-Type: application/json');
                            echo ls_json_encode($return);
                            Yii::app()->end();
                        } else {
                            $return = array("success" => false, "msg" => $clang->gT("Unknown error"));
                            //header('Content-Type: application/json');
                            echo ls_json_encode($return);
                            Yii::app()->end();
                        }
                    }
                }
            }
            return;
        }
        $clang = Yii::app()->lang;
        $meta = '';
        App()->getClientScript()->registerPackage('jqueryui');
        App()->getClientScript()->registerPackage('jquery-superfish');
        $sNeededScriptVar = '
            var uploadurl = "' . $this->createUrl('/uploader/index/mode/upload/') . '";
            var imageurl = "' . Yii::app()->getConfig('imageurl') . '/";
            var surveyid = "' . $surveyid . '";
            var fieldname = "' . $sFieldName . '";
            var questgrppreview  = ' . $sPreview . ';
            csrfToken = ' . ls_json_encode(Yii::app()->request->csrfToken) . ';
            showpopups="' . Yii::app()->getConfig("showpopups") . '";
        ';
        $sLangScriptVar = "\n                translt = {\n                     titleFld: '" . $clang->gT('Title', 'js') . "',\n                     commentFld: '" . $clang->gT('Comment', 'js') . "',\n                     errorNoMoreFiles: '" . $clang->gT('Sorry, no more files can be uploaded!', 'js') . "',\n                     errorOnlyAllowed: '" . $clang->gT('Sorry, only %s files can be uploaded for this question!', 'js') . "',\n                     uploading: '" . $clang->gT('Uploading', 'js') . "',\n                     selectfile: '" . $clang->gT('Select file', 'js') . "',\n                     errorNeedMore: '" . $clang->gT('Please upload %s more file(s).', 'js') . "',\n                     errorMoreAllowed: '" . $clang->gT('If you wish, you may upload %s more file(s); else you may return back to survey.', 'js') . "',\n                     errorMaxReached: '" . $clang->gT('The maximum number of files has been uploaded. You may return back to survey.', 'js') . "',\n                     errorTooMuch: '" . $clang->gT('The maximum number of files has been uploaded. You may return back to survey.', 'js') . "',\n                     errorNeedMoreConfirm: '" . $clang->gT("You need to upload %s more files for this question.\nAre you sure you want to exit?", 'js') . "'\n                    };\n        ";
        $aSurveyInfo = getSurveyInfo($surveyid, $sLanguage);
        $oEvent = new PluginEvent('beforeSurveyPage');
        $oEvent->set('surveyId', $surveyid);
        App()->getPluginManager()->dispatchEvent($oEvent);
        if (!is_null($oEvent->get('template'))) {
            $aSurveyInfo['templatedir'] = $event->get('template');
        }
        $sTemplateDir = getTemplatePath($aSurveyInfo['template']);
        $sTemplateUrl = getTemplateURL($aSurveyInfo['template']) . "/";
        App()->clientScript->registerScript('sNeededScriptVar', $sNeededScriptVar, CClientScript::POS_HEAD);
        App()->clientScript->registerScript('sLangScriptVar', $sLangScriptVar, CClientScript::POS_HEAD);
        App()->getClientScript()->registerScriptFile(Yii::app()->getConfig("generalscripts") . 'ajaxupload.js');
        App()->getClientScript()->registerScriptFile(Yii::app()->getConfig("generalscripts") . 'uploader.js');
        App()->getClientScript()->registerScriptFile("{$sTemplateUrl}template.js");
        App()->clientScript->registerCssFile(Yii::app()->getConfig("publicstyleurl") . "uploader.css");
        if (file_exists($sTemplateDir . DIRECTORY_SEPARATOR . 'jquery-ui-custom.css')) {
            Yii::app()->getClientScript()->registerCssFile("{$sTemplateUrl}jquery-ui-custom.css");
        } elseif (file_exists($sTemplateDir . DIRECTORY_SEPARATOR . 'jquery-ui.css')) {
            Yii::app()->getClientScript()->registerCssFile("{$sTemplateUrl}jquery-ui.css");
        } else {
            Yii::app()->getClientScript()->registerCssFile(Yii::app()->getConfig('publicstyleurl') . "jquery-ui.css");
        }
        App()->clientScript->registerCssFile("{$sTemplateUrl}template.css");
        $header = getHeader($meta);
        echo $header;
        $fn = $sFieldName;
        $qid = (int) Yii::app()->request->getParam('qid');
        $minfiles = (int) Yii::app()->request->getParam('minfiles');
        $maxfiles = (int) Yii::app()->request->getParam('maxfiles');
        $qidattributes = getQuestionAttributeValues($qid);
        $qidattributes['max_filesize'] = floor(min($qidattributes['max_filesize'] * 1024, getMaximumFileUploadSize()) / 1024);
        $body = '</head><body>
                <div id="notice"></div>
                <input type="hidden" id="ia"                value="' . $fn . '" />
                <input type="hidden" id="' . $fn . '_minfiles"          value="' . $minfiles . '" />
                <input type="hidden" id="' . $fn . '_maxfiles"          value="' . $maxfiles . '" />
                <input type="hidden" id="' . $fn . '_maxfilesize"       value="' . $qidattributes['max_filesize'] . '" />
                <input type="hidden" id="' . $fn . '_allowed_filetypes" value="' . $qidattributes['allowed_filetypes'] . '" />
                <input type="hidden" id="preview"                   value="' . Yii::app()->session['preview'] . '" />
                <input type="hidden" id="' . $fn . '_show_comment"      value="' . $qidattributes['show_comment'] . '" />
                <input type="hidden" id="' . $fn . '_show_title"        value="' . $qidattributes['show_title'] . '" />
                <input type="hidden" id="' . $fn . '_licount"           value="0" />
                <input type="hidden" id="' . $fn . '_filecount"         value="0" />

                <!-- The upload button -->
                <div class="upload-div">
                    <button id="button1" class="button upload-button" type="button" >' . $clang->gT("Select file") . '</button>
                </div>

                <p class="uploadmsg">' . sprintf($clang->gT("You can upload %s under %s KB each."), $qidattributes['allowed_filetypes'], $qidattributes['max_filesize']) . '</p>
                <div class="uploadstatus" id="uploadstatus"></div>

                <!-- The list of uploaded files -->

            </body>
        </html>';
        App()->getClientScript()->render($body);
        echo $body;
    }
コード例 #17
0
 /**
  * printanswers::view()
  * View answers at the end of a survey in one place. To export as pdf, set 'usepdfexport' = 1 in lsconfig.php and $printableexport='pdf'.
  * @param mixed $surveyid
  * @param bool $printableexport
  * @return
  */
 function actionView($surveyid, $printableexport = FALSE)
 {
     Yii::app()->loadHelper("frontend");
     Yii::import('application.libraries.admin.pdf');
     $iSurveyID = (int) $surveyid;
     $sExportType = $printableexport;
     Yii::app()->loadHelper('database');
     if (isset($_SESSION['survey_' . $iSurveyID]['sid'])) {
         $iSurveyID = $_SESSION['survey_' . $iSurveyID]['sid'];
     } else {
         //die('Invalid survey/session');
     }
     // Get the survey inforamtion
     // Set the language for dispay
     if (isset($_SESSION['survey_' . $iSurveyID]['s_lang'])) {
         $sLanguage = $_SESSION['survey_' . $iSurveyID]['s_lang'];
     } elseif (Survey::model()->findByPk($iSurveyID)) {
         $sLanguage = Survey::model()->findByPk($iSurveyID)->language;
     } else {
         $iSurveyID = 0;
         $sLanguage = Yii::app()->getConfig("defaultlang");
     }
     $clang = SetSurveyLanguage($iSurveyID, $sLanguage);
     $aSurveyInfo = getSurveyInfo($iSurveyID, $sLanguage);
     //SET THE TEMPLATE DIRECTORY
     if (!isset($aSurveyInfo['templatedir']) || !$aSurveyInfo['templatedir']) {
         $aSurveyInfo['templatedir'] = Yii::app()->getConfig('defaulttemplate');
     }
     $sTemplate = validateTemplateDir($aSurveyInfo['templatedir']);
     //Survey is not finished or don't exist
     if (!isset($_SESSION['survey_' . $iSurveyID]['finished']) || !isset($_SESSION['survey_' . $iSurveyID]['srid'])) {
         sendCacheHeaders();
         doHeader();
         echo templatereplace(file_get_contents(getTemplatePath($sTemplate) . '/startpage.pstpl'), array());
         echo "<center><br />\n" . "\t<font color='RED'><strong>" . $clang->gT("Error") . "</strong></font><br />\n" . "\t" . $clang->gT("We are sorry but your session has expired.") . "<br />" . $clang->gT("Either you have been inactive for too long, you have cookies disabled for your browser, or there were problems with your connection.") . "<br />\n" . "\t" . sprintf($clang->gT("Please contact %s ( %s ) for further assistance."), Yii::app()->getConfig("siteadminname"), Yii::app()->getConfig("siteadminemail")) . "\n" . "</center><br />\n";
         echo templatereplace(file_get_contents(getTemplatePath($sTemplate) . '/endpage.pstpl'), array());
         doFooter();
         exit;
     }
     //Fin session time out
     $sSRID = $_SESSION['survey_' . $iSurveyID]['srid'];
     //I want to see the answers with this id
     //Ensure script is not run directly, avoid path disclosure
     //if (!isset($rootdir) || isset($_REQUEST['$rootdir'])) {die( "browse - Cannot run this script directly");}
     if ($aSurveyInfo['printanswers'] == 'N') {
         die;
         //Die quietly if print answers is not permitted
     }
     //CHECK IF SURVEY IS ACTIVATED AND EXISTS
     $sSurveyName = $aSurveyInfo['surveyls_title'];
     $sAnonymized = $aSurveyInfo['anonymized'];
     //OK. IF WE GOT THIS FAR, THEN THE SURVEY EXISTS AND IT IS ACTIVE, SO LETS GET TO WORK.
     //SHOW HEADER
     $sOutput = CHtml::form(array("printanswers/view/surveyid/{$iSurveyID}/printableexport/pdf"), 'post') . "<center><input type='submit' value='" . $clang->gT("PDF export") . "'id=\"exportbutton\"/><input type='hidden' name='printableexport' /></center></form>";
     if ($sExportType == 'pdf') {
         //require (Yii::app()->getConfig('rootdir').'/application/config/tcpdf.php');
         Yii::import('application.libraries.admin.pdf', true);
         Yii::import('application.helpers.pdfHelper');
         $aPdfLanguageSettings = pdfHelper::getPdfLanguageSettings($clang->langcode);
         $oPDF = new pdf();
         $oPDF->SetTitle($clang->gT("Survey name (ID)", 'unescaped') . ": {$sSurveyName} ({$iSurveyID})");
         $oPDF->SetSubject($sSurveyName);
         $oPDF->SetDisplayMode('fullpage', 'two');
         $oPDF->setLanguageArray($aPdfLanguageSettings['lg']);
         $oPDF->setHeaderFont(array($aPdfLanguageSettings['pdffont'], '', PDF_FONT_SIZE_MAIN));
         $oPDF->setFooterFont(array($aPdfLanguageSettings['pdffont'], '', PDF_FONT_SIZE_DATA));
         $oPDF->SetFont($aPdfLanguageSettings['pdffont'], '', $aPdfLanguageSettings['pdffontsize']);
         $oPDF->AddPage();
         $oPDF->titleintopdf($clang->gT("Survey name (ID)", 'unescaped') . ": {$sSurveyName} ({$iSurveyID})");
     }
     $sOutput .= "\t<div class='printouttitle'><strong>" . $clang->gT("Survey name (ID):") . "</strong> {$sSurveyName} ({$iSurveyID})</div><p>&nbsp;\n";
     LimeExpressionManager::StartProcessingPage(true);
     // means that all variables are on the same page
     // Since all data are loaded, and don't need JavaScript, pretend all from Group 1
     LimeExpressionManager::StartProcessingGroup(1, $aSurveyInfo['anonymized'] != "N", $iSurveyID);
     $printanswershonorsconditions = Yii::app()->getConfig('printanswershonorsconditions');
     $aFullResponseTable = getFullResponseTable($iSurveyID, $sSRID, $sLanguage, $printanswershonorsconditions);
     //Get the fieldmap @TODO: do we need to filter out some fields?
     if ($aSurveyInfo['datestamp'] != "Y" || $sAnonymized == 'Y') {
         unset($aFullResponseTable['submitdate']);
     } else {
         unset($aFullResponseTable['id']);
     }
     unset($aFullResponseTable['token']);
     unset($aFullResponseTable['lastpage']);
     unset($aFullResponseTable['startlanguage']);
     unset($aFullResponseTable['datestamp']);
     unset($aFullResponseTable['startdate']);
     $sOutput .= "<table class='printouttable' >\n";
     foreach ($aFullResponseTable as $sFieldname => $fname) {
         if (substr($sFieldname, 0, 4) == 'gid_') {
             $sOutput .= "\t<tr class='printanswersgroup'><td colspan='2'>{$fname[0]}</td></tr>\n";
         } elseif (substr($sFieldname, 0, 4) == 'qid_') {
             $sOutput .= "\t<tr class='printanswersquestionhead'><td colspan='2'>{$fname[0]}</td></tr>\n";
         } elseif ($sFieldname == 'submitdate') {
             if ($sAnonymized != 'Y') {
                 $sOutput .= "\t<tr class='printanswersquestion'><td>{$fname[0]} {$fname[1]} {$sFieldname}</td><td class='printanswersanswertext'>{$fname[2]}</td></tr>";
             }
         } else {
             $sOutput .= "\t<tr class='printanswersquestion'><td>{$fname[0]} {$fname[1]}</td><td class='printanswersanswertext'>" . flattenText($fname[2]) . "</td></tr>";
         }
     }
     $sOutput .= "</table>\n";
     $sData['thissurvey'] = $aSurveyInfo;
     $sOutput = templatereplace($sOutput, array(), $sData, '', $aSurveyInfo['anonymized'] == "Y", NULL, array(), true);
     // Do a static replacement
     if ($sExportType == 'pdf') {
         $oPDF->writeHTML($sOutput);
         header("Pragma: public");
         header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
         $sExportFileName = sanitize_filename($sSurveyName);
         $oPDF->Output($sExportFileName . "-" . $iSurveyID . ".pdf", "D");
     } else {
         ob_start(function ($buffer, $phase) {
             App()->getClientScript()->render($buffer);
             App()->getClientScript()->reset();
             return $buffer;
         });
         ob_implicit_flush(false);
         sendCacheHeaders();
         doHeader();
         echo templatereplace(file_get_contents(getTemplatePath($sTemplate) . '/startpage.pstpl'), array(), $sData);
         echo templatereplace(file_get_contents(getTemplatePath($sTemplate) . '/printanswers.pstpl'), array('ANSWERTABLE' => $sOutput), $sData);
         echo templatereplace(file_get_contents(getTemplatePath($sTemplate) . '/endpage.pstpl'), array(), $sData);
         echo "</body></html>";
         ob_flush();
     }
     LimeExpressionManager::FinishProcessingGroup();
     LimeExpressionManager::FinishProcessingPage();
 }
コード例 #18
0
    function run($actionID)
    {
        $surveyid = $_SESSION['LEMsid'];
        if (isset($_SESSION['survey_' . $surveyid]['s_lang'])) {
            $sLanguage = $_SESSION['survey_' . $surveyid]['s_lang'];
        } else {
            $sLanguage = '';
        }
        $clang = SetSurveyLanguage($surveyid, $sLanguage);
        $uploaddir = Yii::app()->getConfig("uploaddir");
        $tempdir = Yii::app()->getConfig("tempdir");
        Yii::app()->loadHelper("database");
        $param = $_REQUEST;
        if (isset($param['filegetcontents'])) {
            $sFileName = $param['filegetcontents'];
            if (substr($sFileName, 0, 6) == 'futmp_') {
                $sFileDir = $tempdir . '/upload/';
            } elseif (substr($sFileName, 0, 3) == 'fu_') {
                $sFileDir = "{$uploaddir}/surveys/{$surveyid}/files/";
            }
            header('Content-Type: ' . CFileHelper::getMimeType($sFileDir . $sFileName));
            readfile($sFileDir . $sFileName);
            exit;
        } elseif (isset($param['delete'])) {
            $sFieldname = $param['fieldname'];
            $sFilename = sanitize_filename($param['filename']);
            $sOriginalFileName = sanitize_filename($param['name']);
            if (substr($sFilename, 0, 6) == 'futmp_') {
                $sFileDir = $tempdir . '/upload/';
            } elseif (substr($sFilename, 0, 3) == 'fu_') {
                $sFileDir = "{$uploaddir}/surveys/{$surveyid}/files/";
            } else {
                die('Invalid filename');
            }
            if (isset($_SESSION[$sFieldname])) {
                $sJSON = $_SESSION[$sFieldname];
                $aFiles = json_decode(stripslashes($sJSON), true);
                if (substr($sFilename, 0, 3) == 'fu_') {
                    $iFileIndex = 0;
                    $found = false;
                    foreach ($aFiles as $aFile) {
                        if ($aFile['filename'] == $sFilename) {
                            $found = true;
                            break;
                        }
                        $iFileIndex++;
                    }
                    if ($found == true) {
                        unset($aFiles[$iFileIndex]);
                    }
                    $_SESSION[$sFieldname] = ls_json_encode($aFiles);
                }
            }
            //var_dump($sFileDir.$sFilename);
            if (@unlink($sFileDir . $sFilename)) {
                echo sprintf($clang->gT('File %s deleted'), $sOriginalFileName);
            } else {
                echo $clang->gT('Oops, There was an error deleting the file');
            }
            exit;
        }
        if (isset($param['mode']) && $param['mode'] == "upload") {
            $clang = Yii::app()->lang;
            $sTempUploadDir = $tempdir . '/upload/';
            // Check if exists and is writable
            if (!file_exists($sTempUploadDir)) {
                // Try to create
                mkdir($sTempUploadDir);
            }
            $filename = $_FILES['uploadfile']['name'];
            $size = 0.001 * $_FILES['uploadfile']['size'];
            $valid_extensions = strtolower($_POST['valid_extensions']);
            $maxfilesize = (int) $_POST['max_filesize'];
            $preview = $_POST['preview'];
            $fieldname = $_POST['fieldname'];
            $aFieldMap = createFieldMap($surveyid, 'short', false, false, $_SESSION['survey_' . $surveyid]['s_lang']);
            if (!isset($aFieldMap[$fieldname])) {
                die;
            }
            $aAttributes = getQuestionAttributeValues($aFieldMap[$fieldname]['qid'], $aFieldMap[$fieldname]['type']);
            $valid_extensions_array = explode(",", $aAttributes['allowed_filetypes']);
            $valid_extensions_array = array_map('trim', $valid_extensions_array);
            $pathinfo = pathinfo($_FILES['uploadfile']['name']);
            $ext = $pathinfo['extension'];
            $randfilename = 'futmp_' . randomChars(15) . '_' . $pathinfo['extension'];
            $randfileloc = $sTempUploadDir . $randfilename;
            // check to see that this file type is allowed
            // it is also  checked at the client side, but jst double checking
            if (!in_array(strtolower($ext), $valid_extensions_array)) {
                $return = array("success" => false, "msg" => sprintf($clang->gT("Sorry, this file extension (%s) is not allowed!"), $ext));
                echo ls_json_encode($return);
                exit;
            }
            // If this is just a preview, don't save the file
            if ($preview) {
                if ($size > $maxfilesize) {
                    $return = array("success" => false, "msg" => sprintf($clang->gT("Sorry, this file is too large. Only files upto %s KB are allowed."), $maxfilesize));
                    echo ls_json_encode($return);
                    exit;
                } else {
                    if (move_uploaded_file($_FILES['uploadfile']['tmp_name'], $randfileloc)) {
                        $return = array("success" => true, "file_index" => $filecount, "size" => $size, "name" => rawurlencode(basename($filename)), "ext" => $ext, "filename" => $randfilename, "msg" => $clang->gT("The file has been successfuly uploaded."));
                        echo ls_json_encode($return);
                        // TODO : unlink this file since this is just a preview
                        // unlink($randfileloc);
                        exit;
                    }
                }
            } else {
                // if everything went fine and the file was uploaded successfuly,
                // send the file related info back to the client
                $iFileUploadTotalSpaceMB = Yii::app()->getConfig("iFileUploadTotalSpaceMB");
                if ($size > $maxfilesize) {
                    $return = array("success" => false, "msg" => sprintf($clang->gT("Sorry, this file is too large. Only files up to %s KB are allowed.", 'unescaped'), $maxfilesize));
                    echo ls_json_encode($return);
                    exit;
                } elseif ($iFileUploadTotalSpaceMB > 0 && calculateTotalFileUploadUsage() + $size / 1024 / 1024 > $iFileUploadTotalSpaceMB) {
                    $return = array("success" => false, "msg" => $clang->gT("We are sorry but there was a system error and your file was not saved. An email has been dispatched to notify the survey administrator.", 'unescaped'));
                    echo ls_json_encode($return);
                    exit;
                } elseif (move_uploaded_file($_FILES['uploadfile']['tmp_name'], $randfileloc)) {
                    $return = array("success" => true, "size" => $size, "name" => rawurlencode(basename($filename)), "ext" => $ext, "filename" => $randfilename, "msg" => $clang->gT("The file has been successfuly uploaded."));
                    echo ls_json_encode($return);
                    exit;
                } else {
                    // check for upload error
                    if ($_FILES['uploadfile']['error'] > 2) {
                        $return = array("success" => false, "msg" => $clang->gT("Sorry, there was an error uploading your file"));
                        echo ls_json_encode($return);
                        exit;
                    } else {
                        if ($_FILES['uploadfile']['error'] == 1 || $_FILES['uploadfile']['error'] == 2 || $size > $maxfilesize) {
                            $return = array("success" => false, "msg" => sprintf($clang->gT("Sorry, this file is too large. Only files upto %s KB are allowed."), $maxfilesize));
                            echo ls_json_encode($return);
                            exit;
                        } else {
                            $return = array("success" => false, "msg" => $clang->gT("Unknown error"));
                            echo ls_json_encode($return);
                            exit;
                        }
                    }
                }
            }
            return;
        }
        $meta = '<script type="text/javascript" src="' . Yii::app()->getConfig("generalscripts") . 'jquery/jquery.js"></script>';
        $meta .= '<script type="text/javascript">
		    var uploadurl = "' . $this->createUrl('/uploader/index/mode/upload/') . '";
            var imageurl = "' . Yii::app()->getConfig('imageurl') . '/";
		    var surveyid = "' . $surveyid . '";
		    var fieldname = "' . $param['fieldname'] . '";
		    var questgrppreview  = ' . $param['preview'] . ';
		</script>';
        $meta .= '<script type="text/javascript" src="' . Yii::app()->getConfig("generalscripts") . '/ajaxupload.js"></script>
		<script type="text/javascript" src="' . Yii::app()->getConfig("generalscripts") . '/uploader.js"></script>
		<link type="text/css" href="' . Yii::app()->getConfig("publicstyleurl") . 'uploader.css" rel="stylesheet" />';
        $clang = Yii::app()->lang;
        $header = getHeader($meta);
        echo $header;
        echo "<script type='text/javascript'>\n\t\t        var translt = {\n\t\t             titleFld: '" . $clang->gT('Title', 'js') . "',\n\t\t             commentFld: '" . $clang->gT('Comment', 'js') . "',\n\t\t             errorNoMoreFiles: '" . $clang->gT('Sorry, no more files can be uploaded!', 'js') . "',\n\t\t             errorOnlyAllowed: '" . $clang->gT('Sorry, only %s files can be uploaded for this question!', 'js') . "',\n\t\t             uploading: '" . $clang->gT('Uploading', 'js') . "',\n\t\t             selectfile: '" . $clang->gT('Select file', 'js') . "',\n\t\t             errorNeedMore: '" . $clang->gT('Please upload %s more file(s).', 'js') . "',\n\t\t             errorMoreAllowed: '" . $clang->gT('If you wish, you may upload %s more file(s); else you may return back to survey.', 'js') . "',\n\t\t             errorMaxReached: '" . $clang->gT('The maximum number of files has been uploaded. You may return back to survey.', 'js') . "',\n\t\t             errorTooMuch: '" . $clang->gT('The maximum number of files has been uploaded. You may return back to survey.', 'js') . "',\n\t\t             errorNeedMoreConfirm: '" . $clang->gT("You need to upload %s more files for this question.\nAre you sure you want to exit?", 'js') . "'\n\t\t            };\n\t\t    </script>\n";
        $fn = $param['fieldname'];
        $qid = $param['qid'];
        $minfiles = sanitize_int($param['minfiles']);
        $maxfiles = sanitize_int($param['maxfiles']);
        $qidattributes = getQuestionAttributeValues($qid);
        $body = '
		        <div id="notice"></div>
		        <input type="hidden" id="ia"                value="' . $fn . '" />
                <input type="hidden" id="' . $fn . '_minfiles"          value="' . $minfiles . '" />
                <input type="hidden" id="' . $fn . '_maxfiles"          value="' . $maxfiles . '" />
		        <input type="hidden" id="' . $fn . '_maxfilesize"       value="' . $qidattributes['max_filesize'] . '" />
		        <input type="hidden" id="' . $fn . '_allowed_filetypes" value="' . $qidattributes['allowed_filetypes'] . '" />
		        <input type="hidden" id="preview"                   value="' . Yii::app()->session['preview'] . '" />
		        <input type="hidden" id="' . $fn . '_show_comment"      value="' . $qidattributes['show_comment'] . '" />
		        <input type="hidden" id="' . $fn . '_show_title"        value="' . $qidattributes['show_title'] . '" />
		        <input type="hidden" id="' . $fn . '_licount"           value="0" />
		        <input type="hidden" id="' . $fn . '_filecount"         value="0" />

		        <!-- The upload button -->
		        <div align="center" class="upload-div">
		            <button id="button1" class="upload-button" type="button" >' . $clang->gT("Select file") . '</button>
		        </div>

		        <p class="uploadmsg">' . sprintf($clang->gT("You can upload %s under %s KB each.", 'js'), $qidattributes['allowed_filetypes'], $qidattributes['max_filesize']) . '</p>
		        <div class="uploadstatus" id="uploadstatus"></div>

		        <!-- The list of uploaded files -->
		        <ul id="' . $fn . '_listfiles"></ul>

		    </body>
		</html>';
        echo $body;
    }