diff --git a/application/config/internal.php b/application/config/internal.php index f69c66de9f1..32e27f2e58f 100644 --- a/application/config/internal.php +++ b/application/config/internal.php @@ -87,12 +87,15 @@ 'vardump' => [ 'class' => 'CWebLogRoute', 'levels'=>'error, warning, trace, info', + 'except' => [ + 'system.CModule' + ], 'enabled' => true ], 'trace' => array( 'class' => 'CWebLogRoute', // you can include more levels separated by commas... trace is shown on debug only 'levels' => 'trace', // you can include more separated by commas - 'enabled' => YII_DEBUG && false + 'enabled' => false && true || YII_DEBUG && false ), 'profile' => [ 'class' => 'CProfileLogRoute' diff --git a/application/controllers/OptinController.php b/application/controllers/OptinController.php index bde9334d454..66a258bb14e 100644 --- a/application/controllers/OptinController.php +++ b/application/controllers/OptinController.php @@ -92,11 +92,11 @@ function actiontokens($surveyid, $token, $langcode = '') //PRINT COMPLETED PAGE if (!$aSurveyInfo['templatedir']) { - $sTemplate=getTemplatePath(Yii::app()->getConfig("defaulttemplate")); + $sTemplate=Template::getTemplatePath(Yii::app()->getConfig("defaulttemplate")); } else { - $sTemplate=getTemplatePath($aSurveyInfo['templatedir']); + $sTemplate=Template::getTemplatePath($aSurveyInfo['templatedir']); } $this->_renderHtml($sMessage,$sTemplate,$aSurveyInfo); } diff --git a/application/controllers/OptoutController.php b/application/controllers/OptoutController.php index a7a504fcf01..005591e7b8c 100644 --- a/application/controllers/OptoutController.php +++ b/application/controllers/OptoutController.php @@ -89,11 +89,11 @@ function actiontokens() //PRINT COMPLETED PAGE if (!$aSurveyInfo['templatedir']) { - $sTemplate=getTemplatePath(Yii::app()->getConfig("defaulttemplate")); + $sTemplate=Template::getTemplatePath(Yii::app()->getConfig("defaulttemplate")); } else { - $sTemplate=getTemplatePath($aSurveyInfo['templatedir']); + $sTemplate=Template::getTemplatePath($aSurveyInfo['templatedir']); } $this->_renderHtml($sMessage,$sTemplate,$aSurveyInfo); @@ -176,11 +176,11 @@ function actionparticipants() //PRINT COMPLETED PAGE if (!$aSurveyInfo['templatedir']) { - $sTemplate=getTemplatePath(Yii::app()->getConfig("defaulttemplate")); + $sTemplate=Template::getTemplatePath(Yii::app()->getConfig("defaulttemplate")); } else { - $sTemplate=getTemplatePath($aSurveyInfo['templatedir']); + $sTemplate=Template::getTemplatePath($aSurveyInfo['templatedir']); } $this->_renderHtml($sMessage,$sTemplate, $aSurveyInfo); diff --git a/application/controllers/PrintanswersController.php b/application/controllers/PrintanswersController.php index 224b60b9705..8ec162d1f7a 100644 --- a/application/controllers/PrintanswersController.php +++ b/application/controllers/PrintanswersController.php @@ -67,13 +67,13 @@ function actionView($surveyid,$printableexport=FALSE) { sendCacheHeaders(); doHeader(); - echo templatereplace(file_get_contents(getTemplatePath($sTemplate).'/startpage.pstpl'),array()); + echo templatereplace(file_get_contents(Template::getTemplatePath($sTemplate).'/startpage.pstpl'),array()); echo "

\n" ."\t".gT("Error")."
\n" ."\t".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.")."
\n" ."\t".sprintf(gT("Please contact %s ( %s ) for further assistance."), Yii::app()->getConfig("siteadminname"), Yii::app()->getConfig("siteadminemail"))."\n" ."

\n"; - echo templatereplace(file_get_contents(getTemplatePath($sTemplate).'/endpage.pstpl'),array()); + echo templatereplace(file_get_contents(Template::getTemplatePath($sTemplate).'/endpage.pstpl'),array()); doFooter(); exit; } @@ -143,9 +143,9 @@ function actionView($surveyid,$printableexport=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 templatereplace(file_get_contents(Template::getTemplatePath($sTemplate).'/startpage.pstpl'),array(),$sData); + echo templatereplace(file_get_contents(Template::getTemplatePath($sTemplate).'/printanswers.pstpl'),array('ANSWERTABLE'=>$sOutput),$sData); + echo templatereplace(file_get_contents(Template::getTemplatePath($sTemplate).'/endpage.pstpl'),array(),$sData); echo ""; ob_flush(); @@ -153,7 +153,7 @@ function actionView($surveyid,$printableexport=FALSE) if($sExportType == 'pdf') { // Get images for TCPDF from template directory - define('K_PATH_IMAGES', getTemplatePath($aSurveyInfo['template']).DIRECTORY_SEPARATOR); + define('K_PATH_IMAGES', Template::getTemplatePath($aSurveyInfo['template']).DIRECTORY_SEPARATOR); Yii::import('application.libraries.admin.pdf', true); Yii::import('application.helpers.pdfHelper'); diff --git a/application/controllers/RegisterController.php b/application/controllers/RegisterController.php index c6e9839f61e..37b20766594 100644 --- a/application/controllers/RegisterController.php +++ b/application/controllers/RegisterController.php @@ -52,7 +52,7 @@ public function actionAJAXRegisterForm($surveyid) $sLanguage = Yii::app()->request->getParam('lang',$oSurvey->language); Yii::app()->setLanguage($sLanguage); - $thistpl=getTemplatePath($oSurvey->template); + $thistpl=Template::getTemplatePath($oSurvey->template); $data['sid'] = $iSurveyId; $data['startdate'] = $oSurvey->startdate; $data['enddate'] = $oSurvey->expires; @@ -159,7 +159,7 @@ public function getRegisterErrors($iSurveyId){ public function getRegisterForm($iSurveyId){ $aSurveyInfo=getSurveyInfo($iSurveyId,App()->language); - $sTemplate=getTemplatePath($aSurveyInfo['template']); + $sTemplate=Template::getTemplatePath($aSurveyInfo['template']); // Event to replace register form $event = new PluginEvent('beforeRegisterForm'); @@ -419,7 +419,7 @@ private function display($iSurveyId) $sLanguage=Yii::app()->language; $aData['surveyid']=$surveyid=$iSurveyId; $aData['thissurvey']=getSurveyInfo($iSurveyId,$sLanguage); - $sTemplate=getTemplatePath($aData['thissurvey']['template']); + $sTemplate=Template::getTemplatePath($aData['thissurvey']['template']); Yii::app()->setConfig('surveyID',$iSurveyId);//Needed for languagechanger $aData['languagechanger']=makeLanguageChangerSurvey($sLanguage); $aData['sitename']=App()->name; diff --git a/application/controllers/Statistics_userController.php b/application/controllers/Statistics_userController.php index 84d5c381ec1..813e86b5bf0 100644 --- a/application/controllers/Statistics_userController.php +++ b/application/controllers/Statistics_userController.php @@ -83,7 +83,7 @@ function actionAction($surveyid,$language=null) // 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"]); + $thisSurveyCssPath = \Template::getTemplateURL($surveyinfo["template"]); if ($surveyinfo['publicstatistics']!='Y') { throw new \CHttpException(500, 'The public statistics for this survey are deactivated.'); @@ -353,7 +353,7 @@ function actionAction($surveyid,$language=null) //---------- CREATE STATISTICS ---------- $redata = compact(array_keys(get_defined_vars())); doHeader(); - echo templatereplace(file_get_contents(getTemplatePath($data['sTemplatePath']).DIRECTORY_SEPARATOR."startpage.pstpl"),array(), $redata); + echo templatereplace(file_get_contents(Template::getTemplatePath($data['sTemplatePath']).DIRECTORY_SEPARATOR."startpage.pstpl"),array(), $redata); //some progress bar stuff diff --git a/application/controllers/SurveysController.php b/application/controllers/SurveysController.php index d0b48943568..e535445382f 100644 --- a/application/controllers/SurveysController.php +++ b/application/controllers/SurveysController.php @@ -284,7 +284,7 @@ public function actionAbort() } } - $templatePath = getTemplatePath('default'); + $templatePath = Template::getTemplatePath('default'); return $this->render('abort', [ 'templatePath' => $templatePath, 'surveyId' => isset($surveyId) ? $surveyId : null diff --git a/application/controllers/TokensController.php b/application/controllers/TokensController.php index 9825117f640..4c38c4a0508 100644 --- a/application/controllers/TokensController.php +++ b/application/controllers/TokensController.php @@ -42,7 +42,7 @@ public function actionResponses($id, $surveyId) { 'wrapper' => 'col-md-10 col-md-offset-2' ]); } else { - echo "No responses for this token."; + echo "No responses for this token"; } } public function actionCreate($surveyId) @@ -50,7 +50,7 @@ public function actionCreate($surveyId) $survey = \Survey::model()->findByPk($surveyId); $this->menus['survey'] = $survey; if (!$survey->bool_usetokens) { - throw new \CHttpException(412, "The survey you selected does not have tokens enabled."); + throw new \CHttpException(412, "The survey you selected does not have tokens enabled"); } $token = \Token::create($survey->sid); @@ -60,7 +60,7 @@ public function actionCreate($surveyId) // Validate & safe. if ($token->save()) { // On success. - App()->user->setFlash('success', 'Token created.'); + App()->user->setFlash('success', 'Token created'); $this->redirect(['tokens/index', 'surveyId' => $survey->sid]); } } @@ -102,7 +102,7 @@ public function actionUpdate($surveyId, $id) // Validate & safe. if ($token->save()) { // On success. - App()->user->setFlash('success', 'Token created.'); + App()->user->setFlash('success', 'Token updated'); $this->redirect(['tokens/index', 'surveyId' => $survey->sid]); } } diff --git a/application/controllers/UploaderController.php b/application/controllers/UploaderController.php index 17026a7afa8..d112969c6a1 100644 --- a/application/controllers/UploaderController.php +++ b/application/controllers/UploaderController.php @@ -17,360 +17,334 @@ * */ -class UploaderController extends SurveyController { +class UploaderController extends SurveyController +{ function run($actionID) { - if(isset(App()->surveySessionManager->current) && $oSurvey=Survey::model()->findByPk(App()->surveySessionManager->current->surveyId)){ + if (isset(App()->surveySessionManager->current) && $oSurvey = Survey::model()->findByPk(App()->surveySessionManager->current->surveyId)) { $surveyid = App()->surveySessionManager->current->surveyId; - }else{ + } else { throw new CHttpException(400);// See for debug > 1 - $sLanguage=isset(Yii::app()->session['survey_'.$surveyid]['s_lang']) ? Yii::app()->session['survey_'.$surveyid]['s_lang']: ""; - $uploaddir = Yii::app()->getConfig("uploaddir"); - $tempdir = Yii::app()->getConfig("tempdir"); - Yii::app()->loadHelper("database"); + $sLanguage = isset(Yii::app()->session['survey_' . $surveyid]['s_lang']) ? Yii::app()->session['survey_' . $surveyid]['s_lang'] : ""; + $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); + // 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))// Validate file before else 500 error by getMimeType - { - 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 - { + // 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(isset($_SESSION[$sFieldName])) {// We already have $sFieldName ? - $sJSON = $_SESSION[$sFieldName]; - $aFiles = json_decode(stripslashes($sJSON),true); + 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))// Validate file before else 500 error by getMimeType + { + 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 (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); } - if ($found==true) unset($aFiles[$iFileIndex]); - $_SESSION[$sFieldName] = ls_json_encode($aFiles); } + // Return some json to do a beautiful text + if (@unlink($sFileDir . $sFileName)) { + echo sprintf(gT('File %s deleted'), $sOriginalFileName); + } else { + echo gT('Oops, There was an error deleting the file'); + } + Yii::app()->end(); } - // Return some json to do a beautiful text - if (@unlink($sFileDir.$sFileName)) - { - echo sprintf(gT('File %s deleted'), $sOriginalFileName); - } - else - echo gT('Oops, There was an error deleting the file'); - Yii::app()->end(); - } - if($sMode == "upload") - { - $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=\QuestionAttribute::model()->getQuestionAttributes($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); + if ($sMode == "upload") { + $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 = \QuestionAttribute::model()->getQuestionAttributes($aFieldMap[$sFieldName]['qid'], + $aFieldMap[$sFieldName]['type']); - $pathinfo = pathinfo($_FILES['uploadfile']['name']); - $ext = strtolower($pathinfo['extension']); - $randfilename = 'futmp_'.randomChars(15).'_'.$pathinfo['extension']; - $randfileloc = $sTempUploadDir . $randfilename; + $maxfilesize = (int)$aAttributes['max_filesize']; + $valid_extensions_array = explode(",", $aAttributes['allowed_filetypes']); + $valid_extensions_array = array_map('trim', $valid_extensions_array); - // check to see that this file type is allowed - // it is also checked at the client side, but jst double checking - if (!in_array($ext, $valid_extensions_array)) - { - $return = array( - "success" => false, - "msg" => sprintf(gT("Sorry, this file extension (%s) is not allowed!"),$ext) - ); - //header('Content-Type: application/json'); - echo ls_json_encode($return); - Yii::app()->end(); - } + $pathinfo = pathinfo($_FILES['uploadfile']['name']); + $ext = strtolower($pathinfo['extension']); + $randfilename = 'futmp_' . randomChars(15) . '_' . $pathinfo['extension']; + $randfileloc = $sTempUploadDir . $randfilename; - // If this is just a preview, don't save the file - if ($preview) - { - if ($size > $maxfilesize) - { + // check to see that this file type is allowed + // it is also checked at the client side, but jst double checking + if (!in_array($ext, $valid_extensions_array)) { $return = array( "success" => false, - "msg" => sprintf(gT("Sorry, this file is too large. Only files upto %s KB are allowed."), $maxfilesize) + "msg" => sprintf(gT("Sorry, this file extension (%s) is not allowed!"), $ext) ); //header('Content-Type: application/json'); echo ls_json_encode($return); Yii::app()->end(); } - else if (move_uploaded_file($_FILES['uploadfile']['tmp_name'], $randfileloc)) - { + // If this is just a preview, don't save the file + if ($preview) { + if ($size > $maxfilesize) { + $return = array( + "success" => false, + "msg" => sprintf(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" => gT("The file has been successfuly uploaded.") + $return = array( + "success" => true, + "file_index" => $filecount, + "size" => $size, + "name" => rawurlencode(basename($filename)), + "ext" => $ext, + "filename" => $randfilename, + "msg" => 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(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" => 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" => gT("The file has been successfuly uploaded.") - ); - //header('Content-Type: application/json'); - echo ls_json_encode($return); - Yii::app()->end(); - } - // if there was some error, report error message - else - { - // check for upload error - if ($_FILES['uploadfile']['error'] > 2) - { - $return = array( - "success" => false, - "msg" => gT("Sorry, there was an error uploading your file") - ); - //header('Content-Type: application/json'); - echo ls_json_encode($return); - Yii::app()->end(); + // 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(); + } } - // check to ensure that the file does not cross the maximum file size - else if ( $_FILES['uploadfile']['error'] == 1 || $_FILES['uploadfile']['error'] == 2 || $size > $maxfilesize) - { + } 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(gT("Sorry, this file is too large. Only files upto %s KB are allowed."), $maxfilesize) - ); + "success" => false, + "msg" => sprintf(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(); - } - else - { + } elseif ($iFileUploadTotalSpaceMB > 0 && ((calculateTotalFileUploadUsage() + ($size / 1024 / 1024)) > $iFileUploadTotalSpaceMB)) { $return = array( - "success" => false, - "msg" => gT("Unknown error") - ); + "success" => false, + "msg" => 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" => gT("The file has been successfuly uploaded.") + ); //header('Content-Type: application/json'); echo ls_json_encode($return); Yii::app()->end(); + } // if there was some error, report error message + else { + // check for upload error + if ($_FILES['uploadfile']['error'] > 2) { + $return = array( + "success" => false, + "msg" => gT("Sorry, there was an error uploading your file") + ); + //header('Content-Type: application/json'); + echo ls_json_encode($return); + Yii::app()->end(); + } // check to ensure that the file does not cross the maximum file size + else { + if ($_FILES['uploadfile']['error'] == 1 || $_FILES['uploadfile']['error'] == 2 || $size > $maxfilesize) { + $return = array( + "success" => false, + "msg" => sprintf(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" => gT("Unknown error") + ); + //header('Content-Type: application/json'); + echo ls_json_encode($return); + Yii::app()->end(); + } + } } } + + return; } - return; - } - $meta = ''; - App()->getClientScript()->registerPackage('jqueryui'); - $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").'"; + $meta = ''; + App()->getClientScript()->registerPackage('jqueryui'); + $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=" + $sLangScriptVar = " uploadLang = { - titleFld: '" . gT('Title','js') . "', - commentFld: '" . gT('Comment','js') . "', - errorNoMoreFiles: '" . gT('Sorry, no more files can be uploaded!','js') . "', - errorOnlyAllowed: '" . gT('Sorry, only %s files can be uploaded for this question!','js') . "', - uploading: '" . gT('Uploading','js') . "', - selectfile: '" . gT('Select file','js') . "', - errorNeedMore: '" . gT('Please upload %s more file(s).','js') . "', - errorMoreAllowed: '" . gT('If you wish, you may upload %s more file(s); else you may return back to survey.','js') . "', - errorMaxReached: '" . gT('The maximum number of files has been uploaded. You may return back to survey.','js') . "', - errorTooMuch: '" . gT('The maximum number of files has been uploaded. You may return back to survey.','js') . "', - errorNeedMoreConfirm: '" . gT("You need to upload %s more files for this question.\nAre you sure you want to exit?",'js') . "', - deleteFile : '".gt('Delete','js') . "', - editFile : '".gt('Edit','js') . "', + titleFld: '" . gT('Title', 'js') . "', + commentFld: '" . gT('Comment', 'js') . "', + errorNoMoreFiles: '" . gT('Sorry, no more files can be uploaded!', 'js') . "', + errorOnlyAllowed: '" . gT('Sorry, only %s files can be uploaded for this question!', 'js') . "', + uploading: '" . gT('Uploading', 'js') . "', + selectfile: '" . gT('Select file', 'js') . "', + errorNeedMore: '" . gT('Please upload %s more file(s).', 'js') . "', + errorMoreAllowed: '" . gT('If you wish, you may upload %s more file(s); else you may return back to survey.', + 'js') . "', + errorMaxReached: '" . gT('The maximum number of files has been uploaded. You may return back to survey.', + 'js') . "', + errorTooMuch: '" . gT('The maximum number of files has been uploaded. You may return back to survey.', + 'js') . "', + errorNeedMoreConfirm: '" . gT("You need to upload %s more files for this question.\nAre you sure you want to exit?", + 'js') . "', + deleteFile : '" . gt('Delete', 'js') . "', + editFile : '" . gt('Edit', 'js') . "', }; "; - $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"); - App()->getClientScript()->registerCssFile(Yii::app()->getConfig('publicstyleurl') . "uploader-files.css"); + $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 = \Template::getTemplatePath($aSurveyInfo['template']); + $sTemplateUrl = \Template::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"); + App()->getClientScript()->registerCssFile(Yii::app()->getConfig('publicstyleurl') . "uploader-files.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); + 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; + 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=\QuestionAttribute::model()->getQuestionAttributes($qid); - $qidattributes['max_filesize']=floor(min($qidattributes['max_filesize']*1024,getMaximumFileUploadSize())/1024); - $body = ' + $fn = $sFieldName; + $qid = (int)Yii::app()->request->getParam('qid'); + $minfiles = (int)Yii::app()->request->getParam('minfiles'); + $maxfiles = (int)Yii::app()->request->getParam('maxfiles'); + $qidattributes = \QuestionAttribute::model()->getQuestionAttributes($qid); + $qidattributes['max_filesize'] = floor(min($qidattributes['max_filesize'] * 1024, + getMaximumFileUploadSize()) / 1024); + $body = '
- - - - - - - - - - + + + + + + + + + +
- +
-

'.sprintf(gT("You can upload %s under %s KB each."),$qidattributes['allowed_filetypes'],$qidattributes['max_filesize']).'

+

' . sprintf(gT("You can upload %s under %s KB each."), + $qidattributes['allowed_filetypes'], $qidattributes['max_filesize']) . '

'; - App()->getClientScript()->render($body); - echo $body; + App()->getClientScript()->render($body); + echo $body; - } + } -} + } +} \ No newline at end of file diff --git a/application/controllers/admin/checkintegrity.php b/application/controllers/admin/checkintegrity.php index 97f96495d6d..023091ac8a9 100644 --- a/application/controllers/admin/checkintegrity.php +++ b/application/controllers/admin/checkintegrity.php @@ -355,8 +355,7 @@ protected function _checkintegrity() /*** Check for active survey tables with missing survey entry and rename them ***/ $sDBPrefix = Yii::app()->db->tablePrefix; - $sQuery = dbSelectTablesLike('{{survey}}\_%'); - $aResult = dbQueryOrFalse($sQuery); + $aResult = App()->db->createCommand(dbSelectTablesLike('{{survey}}\_%'))->query(); foreach ($aResult->readAll() as $aRow) { $sTableName = substr(reset($aRow), strlen($sDBPrefix)); @@ -379,7 +378,7 @@ protected function _checkintegrity() } /*** Check for active token tables with missing survey entry ***/ - $aResult = dbQueryOrFalse(dbSelectTablesLike('{{tokens}}\_%')); + $aResult = App()->db->createCommand(dbSelectTablesLike('{{tokens}}\_%'))->query(); foreach ($aResult->readAll() as $aRow) { $sTableName = substr(reset($aRow), strlen($sDBPrefix)); diff --git a/application/controllers/admin/dataentry.php b/application/controllers/admin/dataentry.php index 81ed948aed7..06297923ca2 100644 --- a/application/controllers/admin/dataentry.php +++ b/application/controllers/admin/dataentry.php @@ -1408,7 +1408,7 @@ public function update() { if ($thisvalue == "") { - $updateqr .= dbQuoteID($fieldname)." = NULL, \n"; + $updateqr .= App()->db->quoteColumnName($fieldname)." = NULL, \n"; } else { @@ -1420,35 +1420,35 @@ public function update() //need to check if library get initialized with new value of constructor or not. //$datetimeobj = new Date_Time_Converter($thisvalue,$dateformatdetails['phpdate']); - $updateqr .= dbQuoteID($fieldname)." = '{$datetimeobj->convert("Y-m-d H:i:s")}', \n"; + $updateqr .= App()->db->quoteColumnName($fieldname)." = '{$datetimeobj->convert("Y-m-d H:i:s")}', \n"; } } elseif (($irow['type'] == 'N' || $irow['type'] == 'K') && $thisvalue == "") { - $updateqr .= dbQuoteID($fieldname)." = NULL, \n"; + $updateqr .= App()->db->quoteColumnName($fieldname)." = NULL, \n"; } elseif ($irow['type'] == '|' && strpos($irow['fieldname'], '_filecount') && $thisvalue == "") { - $updateqr .= dbQuoteID($fieldname)." = NULL, \n"; + $updateqr .= App()->db->quoteColumnName($fieldname)." = NULL, \n"; } elseif ($irow['type'] == 'submitdate') { if (isset($_POST['completed']) && ($_POST['completed']== "N")) { - $updateqr .= dbQuoteID($fieldname)." = NULL, \n"; + $updateqr .= App()->db->quoteColumnName($fieldname)." = NULL, \n"; } elseif (isset($_POST['completed']) && $thisvalue=="") { - $updateqr .= dbQuoteID($fieldname)." = " . App()->db->quoteValue($_POST['completed']) . ", \n"; + $updateqr .= App()->db->quoteColumnName($fieldname)." = " . App()->db->quoteValue($_POST['completed']) . ", \n"; } else { - $updateqr .= dbQuoteID($fieldname)." = " . App()->db->quoteValue($thisvalue) . ", \n"; + $updateqr .= App()->db->quoteColumnName($fieldname)." = " . App()->db->quoteValue($thisvalue) . ", \n"; } } else { - $updateqr .= dbQuoteID($fieldname)." = " . App()->db->quoteValue($thisvalue) . ", \n"; + $updateqr .= App()->db->quoteColumnName($fieldname)." = " . App()->db->quoteValue($thisvalue) . ", \n"; } } $updateqr = substr($updateqr, 0, -3); diff --git a/application/controllers/admin/printablesurvey.php b/application/controllers/admin/printablesurvey.php index c8d99a75e5d..f590ae423c2 100644 --- a/application/controllers/admin/printablesurvey.php +++ b/application/controllers/admin/printablesurvey.php @@ -80,11 +80,11 @@ function index($surveyid, $lang = null) $surveyexpirydate=''; } //Fix $templatename : control if print_survey.pstpl exist - if(is_file(getTemplatePath($templatename).DIRECTORY_SEPARATOR.'print_survey.pstpl')) + if(is_file(Template::getTemplatePath($templatename).DIRECTORY_SEPARATOR.'print_survey.pstpl')) { $templatename = $templatename;// Change nothing } - elseif(is_file(getTemplatePath(Yii::app()->getConfig("defaulttemplate")).DIRECTORY_SEPARATOR.'print_survey.pstpl')) + elseif(is_file(Template::getTemplatePath(Yii::app()->getConfig("defaulttemplate")).DIRECTORY_SEPARATOR.'print_survey.pstpl')) { $templatename=Yii::app()->getConfig("defaulttemplate"); } @@ -92,8 +92,8 @@ function index($surveyid, $lang = null) { $templatename="default"; } - $sFullTemplatePath = getTemplatePath($templatename).DIRECTORY_SEPARATOR; - $sFullTemplateUrl = getTemplateURL($templatename)."/"; + $sFullTemplatePath = \Template::getTemplatePath($templatename).DIRECTORY_SEPARATOR; + $sFullTemplateUrl = \Template::getTemplateURL($templatename)."/"; define('PRINT_TEMPLATE_DIR' , $sFullTemplatePath , true); define('PRINT_TEMPLATE_URL' , $sFullTemplateUrl , true); @@ -583,7 +583,7 @@ function index($surveyid, $lang = null) ,'QUESTION_SCENARIO' => $sExplanation // if there are conditions on a question, list the conditions. ,'QUESTION_MANDATORY' => '' // translated 'mandatory' identifier ,'QUESTION_ID' => $deqrow['qid'] // id to be added to wrapping question div - ,'QUESTION_CLASS' => getQuestionClass( $deqrow['type']) // classes to be added to wrapping question div + ,'QUESTION_CLASS' => \Question::getQuestionClass( $deqrow['type']) // classes to be added to wrapping question div ,'QUESTION_TYPE_HELP' => $qinfo['validTip'] // '' // instructions on how to complete the question // prettyValidTip is too verbose; assuming printable surveys will use static values ,'QUESTION_MAN_MESSAGE' => '' // (not sure if this is used) mandatory error ,'QUESTION_VALID_MESSAGE' => '' // (not sure if this is used) validation error diff --git a/application/controllers/admin/questiongroups.php b/application/controllers/admin/questiongroups.php deleted file mode 100644 index 595a07bfec7..00000000000 --- a/application/controllers/admin/questiongroups.php +++ /dev/null @@ -1,407 +0,0 @@ -getConfig('tempdir') . DIRECTORY_SEPARATOR . randomChars(20); - $aPathInfo = pathinfo($_FILES['the_file']['name']); - $sExtension = $aPathInfo['extension']; - - if (!@move_uploaded_file($_FILES['the_file']['tmp_name'], $sFullFilepath)) - { - $fatalerror = sprintf(gT("An error occurred uploading your file. This may be caused by incorrect permissions in your %s folder."), $this->config->item('tempdir')); - } - - // validate that we have a SID - if (!returnGlobal('sid')) - $fatalerror .= gT("No SID (Survey) has been provided. Cannot import question."); - - if (isset($fatalerror)) - { - @unlink($sFullFilepath); - $this->getController()->error($fatalerror); - } - - Yii::app()->loadHelper('admin/import'); - - // IF WE GOT THIS FAR, THEN THE FILE HAS BEEN UPLOADED SUCCESFULLY - if (strtolower($sExtension) == 'lsg') - $aImportResults = XMLImportGroup($sFullFilepath, $iSurveyID); - else - $this->getController()->error('Unknown file extension'); - LimeExpressionManager::SetDirtyFlag(); // so refreshes syntax highlighting - fixLanguageConsistency($iSurveyID); - - if (isset($aImportResults['fatalerror'])) - { - unlink($sFullFilepath); - $this->getController()->error($aImportResults['fatalerror']); - } - - unlink($sFullFilepath); - - $aData['display'] = $importgroup; - $aData['surveyid'] = $iSurveyID; - $aData['aImportResults'] = $aImportResults; - $aData['sExtension'] = $sExtension; - //$aData['display']['menu_bars']['surveysummary'] = 'importgroup'; - - $this->_renderWrappedTemplate('survey/QuestionGroups', 'import_view', $aData); - // TMSW Condition->Relevance: call LEM->ConvertConditionsToRelevance() after import - } - } - - /** - * questiongroup::add() - * Load add new question group screen. - * @return - */ - function add($surveyid) - { - $surveyid = sanitize_int($surveyid); - $aViewUrls = $aData = array(); - - if (App()->user->checkAccess('surveycontent', ['crud' => 'read', 'entity' => 'survey', 'entity_id' => $surveyid])) - { - Yii::app()->session['FileManagerContext'] = "create:group:{$surveyid}"; - - Yii::app()->loadHelper('admin/htmleditor'); - Yii::app()->loadHelper('surveytranslator'); - $grplangs = Survey::model()->findByPk($surveyid)->additionalLanguages; - $baselang = Survey::model()->findByPk($surveyid)->language; - $grplangs[] = $baselang; - $grplangs = array_reverse($grplangs); - App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('adminscripts') . 'questiongroup.js'); - - $aData['display']['menu_bars']['surveysummary'] = 'addgroup'; - $aData['surveyid'] = $surveyid; - $aData['action'] = $aData['display']['menu_bars']['gid_action'] = 'addgroup'; - $aData['grplangs'] = $grplangs; - $aData['baselang'] = $baselang; - - $this->_renderWrappedTemplate('survey/QuestionGroups', 'addGroup_view', $aData); - } - } - - /** - * Insert the new group to the database - * - * @access public - * @param int $surveyid - * @return void - */ - public function insert($surveyid) - { - if (App()->user->checkAccess('surveycontent', ['crud' => 'create', 'entity' => 'survey', 'entity_id' => $surveyid])) - { - Yii::app()->loadHelper('surveytranslator'); - - $grplangs = Survey::model()->findByPk($surveyid)->additionalLanguages; - $baselang = Survey::model()->findByPk($surveyid)->language; - - $grplangs[] = $baselang; - $errorstring = ''; - foreach ($grplangs as $grouplang) - if (empty($_POST['group_name_' . $grouplang])) - $errorstring.= getLanguageNameFromCode($grouplang, false) . "\\n"; - - if ($errorstring != '') - $this->getController()->redirect(array('admin/survey/sa/view/surveyid/' . $surveyid)); - - else - { - $first = true; - foreach ($grplangs as $grouplang) - { - //Clean XSS - $group_name = $_POST['group_name_' . $grouplang]; - $group_description = $_POST['description_' . $grouplang]; - - $group_name = html_entity_decode($group_name, ENT_QUOTES, "UTF-8"); - $group_description = html_entity_decode($group_description, ENT_QUOTES, "UTF-8"); - - // Fix bug with FCKEditor saving strange BR types - $group_name = fixCKeditorText($group_name); - $group_description = fixCKeditorText($group_description); - - - if ($first) - { - $aData = array( - 'sid' => $surveyid, - 'group_name' => $group_name, - 'description' => $group_description, - 'group_order' => getMaxGroupOrder($surveyid), - 'language' => $grouplang, - 'randomization_group' => $_POST['randomization_group'], - 'grelevance' => $_POST['grelevance'], - ); - - $group = new QuestionGroup; - foreach ($aData as $k => $v) - $group->$k = $v; - $group->save(); - $groupid = $group->gid; - $first = false; - } - else - { - switchMSSQLIdentityInsert('groups',true); - $aData = array( - 'gid' => $groupid, - 'sid' => $surveyid, - 'group_name' => $group_name, - 'description' => $group_description, - 'group_order' => getMaxGroupOrder($surveyid), - 'language' => $grouplang, - 'randomization_group' => $_POST['randomization_group'] - ); - - $group = new QuestionGroup; - foreach ($aData as $k => $v) - $group->$k = $v; - $group->save(); - switchMSSQLIdentityInsert('groups',false); - } - } - // This line sets the newly inserted group as the new group - if (isset($groupid)) - $gid = $groupid; - Yii::app()->session['flashmessage'] = gT("New question group was saved."); - } - $this->getController()->redirect(array('admin/survey/sa/view/surveyid/' . $surveyid . '/gid/' . $gid)); - } - } - - /** - * Action to delete a question group. - * - * @access public - * @return void - */ - public function delete($iSurveyId, $iGroupId) - { - $iSurveyId = sanitize_int($iSurveyId); - - if (App()->user->checkAccess('surveycontent', ['crud' => 'delete', 'entity' => 'survey', 'entity_id' => $iSurveyId])) - { - LimeExpressionManager::RevertUpgradeConditionsToRelevance($iSurveyId); - - $iGroupId = sanitize_int($iGroupId); - $iGroupsDeleted = QuestionGroup::deleteWithDependency($iGroupId, $iSurveyId); - - if ($iGroupsDeleted > 0) - { - Yii::app()->setFlashMessage(gT('The question group was deleted.')); - } - else - Yii::app()->setFlashMessage(gT('Group could not be deleted'),'error'); - LimeExpressionManager::UpgradeConditionsToRelevance($iSurveyId); - $this->getController()->redirect(array('admin/survey/sa/view/surveyid/' . $iSurveyId)); - } - } - - /** - * questiongroup::edit() - * Load editing of a question group screen. - * - * @access public - * @param int $surveyid - * @param int $gid - * @return void - */ - public function edit($surveyid, $gid) - { - $surveyid = sanitize_int($surveyid); - $gid = sanitize_int($gid); - $aViewUrls = $aData = array(); - - if (App()->user->checkAccess('surveycontent', ['crud' => 'read', 'entity' => 'survey', 'entity_id' => $surveyid])) - { - Yii::app()->session['FileManagerContext'] = "edit:group:{$surveyid}"; - - Yii::app()->loadHelper('admin/htmleditor'); - Yii::app()->loadHelper('surveytranslator'); - - $aAdditionalLanguages = Survey::model()->findByPk($surveyid)->additionalLanguages; - $aBaseLanguage = Survey::model()->findByPk($surveyid)->language; - - $aLanguages = array_merge(array($aBaseLanguage), $aAdditionalLanguages); - - $grplangs = array_flip($aLanguages); - - // Check out the intgrity of the language versions of this group - $egresult = QuestionGroup::model()->findAllByAttributes(array('sid' => $surveyid, 'gid' => $gid)); - foreach ($egresult as $esrow) - { - $esrow = $esrow->attributes; - - // Language Exists, BUT ITS NOT ON THE SURVEY ANYMORE - if (!in_array($esrow['language'], $aLanguages)) - { - QuestionGroup::model()->deleteAllByAttributes(array('sid' => $surveyid, 'gid' => $gid, 'language' => $esrow['language'])); - } - else - { - $grplangs[$esrow['language']] = 'exists'; - } - - if ($esrow['language'] == $aBaseLanguage) - $basesettings = $esrow; - } - - // Create groups in missing languages - while (list($key, $value) = each($grplangs)) - { - if ($value != 'exists') - { - $basesettings['language'] = $key; - $group = new QuestionGroup; - foreach ($basesettings as $k => $v) - $group->$k = $v; - switchMSSQLIdentityInsert('groups', true); - $group->save(); - switchMSSQLIdentityInsert('groups', false); - } - } - $first = true; - foreach ($aLanguages as $sLanguage) - { - $oResult = QuestionGroup::model()->findByAttributes(array('sid' => $surveyid, 'gid' => $gid, 'language' => $sLanguage)); - $aData['aGroupData'][$sLanguage] = $oResult->attributes; - $aTabTitles[$sLanguage] = getLanguageNameFromCode($sLanguage, false); - if ($first) - { - $aTabTitles[$sLanguage].= ' (' . gT("Base language") . ')'; - $first = false; - } - } - - $aData['action'] = $aData['display']['menu_bars']['gid_action'] = 'editgroup'; - $aData['surveyid'] = $surveyid; - $aData['gid'] = $gid; - $aData['tabtitles'] = $aTabTitles; - $aData['aBaseLanguage'] = $aBaseLanguage; - - $this->_renderWrappedTemplate('survey/QuestionGroups', 'editGroup_view', $aData); - } - - } - - /** - * Provides an interface for updating a group - * - * @access public - * @param int $gid - * @return void - */ - public function update($gid) - { - $gid = (int) $gid; - - $group = QuestionGroup::model()->findByAttributes(array('gid' => $gid)); - $surveyid = $group->sid; - - if (App()->user->checkAccess('surveycontent', ['crud' => 'update', 'entity' => 'survey', 'entity_id' => $surveyid])) - { - Yii::app()->loadHelper('surveytranslator'); - - $grplangs = Survey::model()->findByPk($surveyid)->additionalLanguages; - $baselang = Survey::model()->findByPk($surveyid)->language; - - array_push($grplangs, $baselang); - - foreach ($grplangs as $grplang) - { - if (isset($grplang) && $grplang != "") - { - $group_name = $_POST['group_name_' . $grplang]; - $group_description = $_POST['description_' . $grplang]; - - $group_name = html_entity_decode($group_name, ENT_QUOTES, "UTF-8"); - $group_description = html_entity_decode($group_description, ENT_QUOTES, "UTF-8"); - - // Fix bug with FCKEditor saving strange BR types - $group_name = fixCKeditorText($group_name); - $group_description = fixCKeditorText($group_description); - - $aData = array( - 'group_name' => $group_name, - 'description' => $group_description, - 'randomization_group' => $_POST['randomization_group'], - 'grelevance' => $_POST['grelevance'], - ); - $condition = array( - 'gid' => $gid, - 'sid' => $surveyid, - 'language' => $grplang - ); - $group = QuestionGroup::model()->findByAttributes($condition); - foreach ($aData as $k => $v) - $group->$k = $v; - $ugresult = $group->save(); - if ($ugresult) - { - $groupsummary = getGroupList($gid, $surveyid); - } - } - } - - Yii::app()->session['flashmessage'] = gT("Question group successfully saved."); - $this->getController()->redirect(array('admin/survey/sa/view/surveyid/' . $surveyid . '/gid/' . $gid)); - } - } - - /** - * Renders template(s) wrapped in header and footer - * - * @param string $sAction Current action, the folder to fetch views from - * @param string|array $aViewUrls View url(s) - * @param array $aData Data to be passed on. Optional. - */ - protected function _renderWrappedTemplate($sAction = 'survey/QuestionGroups', $aViewUrls = array(), $aData = array()) - { - - parent::_renderWrappedTemplate($sAction, $aViewUrls, $aData); - } -} \ No newline at end of file diff --git a/application/controllers/admin/questions.php b/application/controllers/admin/questions.php index 713755027fa..5299d1134be 100644 --- a/application/controllers/admin/questions.php +++ b/application/controllers/admin/questions.php @@ -1126,7 +1126,7 @@ public function preview($surveyid, $qid, $lang = null) $answers = retrieveAnswers($ia,$surveyid); - $thistpl = getTemplatePath($thissurvey['template']); + $thistpl = Template::getTemplatePath($thissurvey['template']); doHeader(); @@ -1223,7 +1223,7 @@ function checkconditions(value, name, type, evt_type) $question = $answers[0][0]; $question['code'] = $answers[0][5]; - $question['class'] = getQuestionClass($qrows['type']); + $question['class'] = \Question::getQuestionClass($qrows['type']); $question['essentials'] = 'id="question' . $qrows['qid'] . '"'; $question['sgq'] = $ia[1]; $question['aid']='unknown'; diff --git a/application/controllers/admin/templates.php b/application/controllers/admin/templates.php index f1959827700..6c74df37b25 100644 --- a/application/controllers/admin/templates.php +++ b/application/controllers/admin/templates.php @@ -48,13 +48,13 @@ public function templatezip($templatename) { die('No permission'); } - $templatedir = getTemplatePath($templatename) . DIRECTORY_SEPARATOR; + $templatedir = Template::getTemplatePath($templatename) . DIRECTORY_SEPARATOR; $tempdir = Yii::app()->getConfig('tempdir'); $zipfile = "$tempdir/$templatename.zip"; Yii::app()->loadLibrary('admin.pclzip'); $zip = new PclZip($zipfile); - $zip->create($templatedir, PCLZIP_OPT_REMOVE_PATH, getTemplatePath($templatename)); + $zip->create($templatedir, PCLZIP_OPT_REMOVE_PATH, Template::getTemplatePath($templatename)); if (is_file($zipfile)) { // Send the file for download! @@ -475,7 +475,7 @@ public function templatecopy() // Copies all the files from one template directory to a new one Yii::app()->loadHelper('admin/template'); $newdirname = Yii::app()->getConfig('usertemplaterootdir') . "/" . $newname; - $copydirname = getTemplatePath($copydir); + $copydirname = Template::getTemplatePath($copydir); $oFileHelper=new CFileHelper; $mkdirresult = mkdir_p($newdirname); if ($mkdirresult == 1) { @@ -955,8 +955,8 @@ protected function _initialise($templatename, $screenname, $editfile, $showsumma $surveyid = '1295'; $token = 1234567; - $templatedir = getTemplatePath($templatename); - $templateurl = getTemplateURL($templatename); + $templatedir = \Template::getTemplatePath($templatename); + $templateurl = \Template::getTemplateURL($templatename); // Save these variables in an array $aData['thissurvey'] = $thissurvey; @@ -998,7 +998,7 @@ protected function _initialise($templatename, $screenname, $editfile, $showsumma foreach ($SurveyList as $qs) { $files[] = array("name" => $qs); - $myoutput = array_merge($myoutput, doreplacement(getTemplatePath($templatename) . "/$qs", $aData)); + $myoutput = array_merge($myoutput, doreplacement(Template::getTemplatePath($templatename) . "/$qs", $aData)); } break; @@ -1008,10 +1008,10 @@ protected function _initialise($templatename, $screenname, $editfile, $showsumma $files[] = array("name" => $qs); $myoutput[] = $this->getController()->render('/admin/templates/templateeditor_question_meta_view', array(), true); - $myoutput = array_merge($myoutput, doreplacement(getTemplatePath($templatename) . "/startpage.pstpl", $aData)); - $myoutput = array_merge($myoutput, doreplacement(getTemplatePath($templatename) . "/survey.pstpl", $aData)); - $myoutput = array_merge($myoutput, doreplacement(getTemplatePath($templatename) . "/startgroup.pstpl", $aData)); - $myoutput = array_merge($myoutput, doreplacement(getTemplatePath($templatename) . "/groupdescription.pstpl", $aData)); + $myoutput = array_merge($myoutput, doreplacement(Template::getTemplatePath($templatename) . "/startpage.pstpl", $aData)); + $myoutput = array_merge($myoutput, doreplacement(Template::getTemplatePath($templatename) . "/survey.pstpl", $aData)); + $myoutput = array_merge($myoutput, doreplacement(Template::getTemplatePath($templatename) . "/startgroup.pstpl", $aData)); + $myoutput = array_merge($myoutput, doreplacement(Template::getTemplatePath($templatename) . "/groupdescription.pstpl", $aData)); $aReplacements = array( 'QUESTION_TEXT' => gT("How many roads must a man walk down?"), @@ -1025,7 +1025,7 @@ protected function _initialise($templatename, $screenname, $editfile, $showsumma ); $aReplacements['ANSWER'] = $this->getController()->render('/admin/templates/templateeditor_question_answer_view', array(), true); $aData['aReplacements'] = $aReplacements; - $myoutput = array_merge($myoutput, doreplacement(getTemplatePath($templatename) . "/question.pstpl", $aData)); + $myoutput = array_merge($myoutput, doreplacement(Template::getTemplatePath($templatename) . "/question.pstpl", $aData)); $aReplacements = array( 'QUESTION_TEXT' => gT('Please explain something in detail:'), @@ -1036,10 +1036,10 @@ protected function _initialise($templatename, $screenname, $editfile, $showsumma ); $aReplacements['ANSWER'] = $this->getController()->render('/admin/templates/templateeditor_question_answer_view', array('alt' => true), true); $aData['aReplacements'] = $aReplacements; - $myoutput = array_merge($myoutput, doreplacement(getTemplatePath($templatename) . "/question.pstpl", $aData)); - $myoutput = array_merge($myoutput, doreplacement(getTemplatePath($templatename) . "/endgroup.pstpl", $aData)); - $myoutput = array_merge($myoutput, doreplacement(getTemplatePath($templatename) . "/navigator.pstpl", $aData)); - $myoutput = array_merge($myoutput, doreplacement(getTemplatePath($templatename) . "/endpage.pstpl", $aData)); + $myoutput = array_merge($myoutput, doreplacement(Template::getTemplatePath($templatename) . "/question.pstpl", $aData)); + $myoutput = array_merge($myoutput, doreplacement(Template::getTemplatePath($templatename) . "/endgroup.pstpl", $aData)); + $myoutput = array_merge($myoutput, doreplacement(Template::getTemplatePath($templatename) . "/navigator.pstpl", $aData)); + $myoutput = array_merge($myoutput, doreplacement(Template::getTemplatePath($templatename) . "/endpage.pstpl", $aData)); break; case 'welcome': @@ -1048,7 +1048,7 @@ protected function _initialise($templatename, $screenname, $editfile, $showsumma foreach ($Welcome as $qs) { $files[] = array("name" => $qs); - $myoutput = array_merge($myoutput, doreplacement(getTemplatePath($templatename) . "/$qs", $aData)); + $myoutput = array_merge($myoutput, doreplacement(Template::getTemplatePath($templatename) . "/$qs", $aData)); } break; @@ -1103,7 +1103,7 @@ protected function _initialise($templatename, $screenname, $editfile, $showsumma foreach ($CompletedTemplate as $qs) { $files[] = array("name" => $qs); - $myoutput = array_merge($myoutput, doreplacement(getTemplatePath($templatename) . "/$qs", $aData)); + $myoutput = array_merge($myoutput, doreplacement(Template::getTemplatePath($templatename) . "/$qs", $aData)); } break; diff --git a/application/controllers/survey/index.php b/application/controllers/survey/index.php index 63af79525b5..1e70be48aaa 100644 --- a/application/controllers/survey/index.php +++ b/application/controllers/survey/index.php @@ -229,7 +229,7 @@ function action() //SET THE TEMPLATE DIRECTORY - $thistpl = getTemplatePath($thissurvey['templatedir']); + $thistpl = Template::getTemplatePath($thissurvey['templatedir']); $timeadjust = Yii::app()->getConfig("timeadjust"); @@ -565,11 +565,11 @@ function _niceExit(&$redata, $iDebugLine, $sTemplateDir = null, $asMessage = arr if(isset($redata['surveyid']) && $redata['surveyid'] && !isset($thisurvey)) { $thissurvey=getSurveyInfo($redata['surveyid']); - $sTemplateDir= getTemplatePath($thissurvey['template']); + $sTemplateDir= Template::getTemplatePath($thissurvey['template']); } else { - $sTemplateDir= getTemplatePath($sTemplateDir); + $sTemplateDir= Template::getTemplatePath($sTemplateDir); } sendCacheHeaders(); diff --git a/application/helpers/SurveyRuntimeHelper.php b/application/helpers/SurveyRuntimeHelper.php index 2be5ddd0dc3..bd87b604859 100644 --- a/application/helpers/SurveyRuntimeHelper.php +++ b/application/helpers/SurveyRuntimeHelper.php @@ -30,6 +30,7 @@ protected function createFullQuestionIndex($LEMsessid, $surveyMode) protected function createFullQuestionIndexByGroup($LEMsessid) { + $ssm = App()->surveySessionManager; echo "\n\n\n"; echo CHtml::openTag('div', array('id' => 'index')); echo CHtml::openTag('div', array('class' => 'container')); @@ -81,6 +82,7 @@ protected function createFullQuestionIndexByQuestion($LEMsessid) protected function createIncrementalQuestionIndex($LEMsessid, $surveyMode) { + $ssm = App()->surveySessionManager; echo "\n\n\n"; echo '

' . gT("Question index") . '

'; @@ -171,17 +173,16 @@ protected function createIncrementalQuestionIndex($LEMsessid, $surveyMode) * @param mixed $args */ function run($surveyid,$args) { - global $errormsg; extract($args); $ssm = App()->surveySessionManager; /** @var SurveySession $session */ $session = $ssm->current; - $thissurvey = getSurveyInfo($surveyid); + $thissurvey = getSurveyInfo($session->surveyId); $LEMsessid = 'survey_' . $surveyid; $this->setJavascriptVar($surveyid); - $sTemplatePath=getTemplatePath(Yii::app()->getConfig("defaulttemplate")).DIRECTORY_SEPARATOR; + $sTemplatePath=Template::getTemplatePath(SettingGlobal::get("defaulttemplate")).DIRECTORY_SEPARATOR; // $LEMdebugLevel - customizable debugging for Lime Expression Manager $LEMdebugLevel = 0; // LEM_DEBUG_TIMING; // (LEM_DEBUG_TIMING + LEM_DEBUG_VALIDATION_SUMMARY + LEM_DEBUG_VALIDATION_DETAIL); $LEMskipReprocessing=false; // true if used GetLastMoveResult to avoid generation of unneeded extra JavaScript @@ -544,8 +545,10 @@ function run($surveyid,$args) { } //Update the token if needed and send a confirmation email - if (isset($_SESSION['survey_'.$surveyid]['token'])) - { + set_error_handler(function($errno, $errstr, $errfile, $errline) { + throw new \ErrorException($errstr, $errno, 1, $errfile, $errline); + }); + if (isset($session->response->token)){ submittokens(); } @@ -556,7 +559,7 @@ function run($surveyid,$args) { $content = ''; - $content .= templatereplace(file_get_contents($sTemplatePath."startpage.pstpl"), array(), $redata, 'SubmitStartpage', false, NULL, array(), true ); + $content .= templatereplace(file_get_contents($sTemplatePath."startpage.pstpl"), [], $redata, 'SubmitStartpage', false, NULL, array(), true ); //echo $thissurvey['url']; //Check for assessments @@ -624,11 +627,8 @@ function run($surveyid,$args) { // @todo Remove direct session access. $event = new PluginEvent('afterSurveyComplete'); - if (isset($_SESSION[$LEMsessid]['srid'])) - { - $event->set('responseId', $_SESSION[$LEMsessid]['srid']); - } - $event->set('surveyId', $surveyid); + $event->set('responseId', $session->getResponseId()); + $event->set('surveyId', $session->getSurveyId()); App()->getPluginManager()->dispatchEvent($event); $blocks = array(); @@ -659,6 +659,7 @@ function run($surveyid,$args) { { killSurveySession($surveyid); } + echo 'ok'; exit; } } @@ -1210,8 +1211,8 @@ public static function getQuestionReplacement($aQuestionQanda) $aReplacement['QUESTION_TEXT'] = $aQuestionQanda[0]['text']; $aReplacement['QUESTIONHELP']=$lemQuestionInfo['info']['help'];// User help // To be moved in a extra plugin : QUESTIONHELP img adding - $sTemplateDir=Template::model()->getTemplatePath($oSurveyId->template); - $sTemplateUrl=Template::model()->getTemplateURL($oSurveyId->template); + $sTemplateDir = \Template::getTemplatePath($oSurveyId->template); + $sTemplateUrl = \Template::getTemplateURL($oSurveyId->template); if(flattenText($aReplacement['QUESTIONHELP'], true,true) != '') { if (file_exists($sTemplateDir . '/help.gif')) @@ -1229,7 +1230,7 @@ public static function getQuestionReplacement($aQuestionQanda) $aReplacement['QUESTIONHELP']="Help".$aReplacement['QUESTIONHELP']; } // Core value :the classes - $aReplacement['QUESTION_CLASS'] = Question::getQuestionClass($sType); + $aReplacement['QUESTION_CLASS'] = \Question::getQuestionClass($sType); $aMandatoryClass = array(); if ($lemQuestionInfo['info']['mandatory'] == 'Y')// $aQuestionQanda[0]['mandatory']=="*" { diff --git a/application/helpers/common_helper.php b/application/helpers/common_helper.php index 20736d4cd50..1cd43000020 100644 --- a/application/helpers/common_helper.php +++ b/application/helpers/common_helper.php @@ -631,16 +631,6 @@ function getMaxQuestionOrder($gid,$surveyid) else return $current_max ; } -/** -* getQuestionClass() returns a class name for a given question type to allow custom styling for each question type. -* -* @param string $input containing unique character representing each question type. -* @return string containing the class name for a given question type. -*/ -function getQuestionClass($input) -{ - Question::getQuestionClass($input); -}; /** * setupColumns() defines all the html tags to be wrapped around @@ -874,32 +864,6 @@ function longestString( $new_string , $longest_length ) -/** -* getNotificationList() returns different options for notifications -* -* @param string $notificationcode - the currently selected one -* -* @return This string is returned containing formatted list of notification methods for current survey -*/ -function getNotificationList($notificationcode) -{ - - $ntypes = array( - "0"=>gT("No email notification"), - "1"=>gT("Basic email notification"), - "2"=>gT("Detailed email notification with result codes") - ); - if (!isset($ntypeselector)) {$ntypeselector="";} - foreach($ntypes as $ntcode=>$ntdescription) - { - $ntypeselector .= "\n"; - } - - - return $groupselecter; -} - /** * put your comment there... * @@ -1114,39 +1051,6 @@ function groupOrderThenQuestionOrder($a, $b) return $GroupResult; } - -function fixSortOrderAnswers($qid,$surveyid=null) //Function rewrites the sortorder for a group of answers -{ - $qid=sanitize_int($qid); - $baselang = Survey::model()->findByPk($surveyid)->language; - - Answer::model()->updateSortOrder($qid,$baselang); -} - -/** -* This function rewrites the sortorder for questions inside the named group -* REMOVED the 2012-08-08 : replaced by Question::model()->updateQuestionOrder -* @param integer $groupid the group id -* @param integer $surveyid the survey id -*/ -/** -function fixSortOrderQuestions($groupid, $surveyid) //Function rewrites the sortorder for questions -{ - $gid = sanitize_int($groupid); - $surveyid = sanitize_int($surveyid); - $baselang = Survey::model()->findByPk($surveyid)->language; - - $questions = Question::model()->findAllByAttributes(array('gid' => $gid, 'sid' => $surveyid, 'language' => $baselang)); - $p = 0; - foreach ($questions as $question) - { - $question->question_order = $p; - $question->save(); - $p++; - } -} -*/ - function fixMovedQuestionConditions($qid,$oldgid,$newgid) //Function rewrites the cfieldname for a question after group change { $surveyid = Yii::app()->getConfig('sid'); @@ -2207,8 +2111,6 @@ function createFieldMap($surveyid, $style='short', $force_refresh=false, $questi { --$questionSeq; // didn't generate a valid $fieldmap entry, so decrement the question counter to ensure they are sequential } - } - if (isset($fieldmap)) { if ($questionid == false) { @@ -2246,7 +2148,7 @@ function createFieldMap($surveyid, $style='short', $force_refresh=false, $questi } $requestCache[$key] = $fieldmap; - + } return $requestCache[$key]; } @@ -4675,16 +4577,6 @@ function fixCKeditorText($str) } -/** -* This is a helper function for getAttributeFieldNames -* -* @param mixed $fieldname -*/ -function filterForAttributes ($fieldname) -{ - if (strpos($fieldname,'attribute_')===false) return false; else return true; -} - /** * Returns the full list of attribute token fields including the properties for each field @@ -4694,8 +4586,8 @@ function filterForAttributes ($fieldname) */ function GetParticipantAttributes($iSurveyID) { - if (!tableExists("{{tokens_{$iSurveyID}}}") || !$table = Yii::app()->db->schema->getTable('{{tokens_'.$iSurveyID.'}}')) - return Array(); + if (!Token::valid($iSurveyID)) + return []; return getTokenFieldsAndNames($iSurveyID,true); } @@ -4880,25 +4772,6 @@ function removeBOM($str=""){ return $str; } -/** -* This function returns the complete directory path to a given template name -* -* @param mixed $sTemplateName -*/ -function getTemplatePath($sTemplateName = false) -{ - return Template::getTemplatePath($sTemplateName); -} - -/** -* This function returns the complete URL path to a given template name -* -* @param mixed $sTemplateName -*/ -function getTemplateURL($sTemplateName) -{ - return Template::getTemplateURL($sTemplateName); -} /** * Return an array of subquestions for a given sid/qid @@ -5470,150 +5343,6 @@ function replaceExpressionCodes ($iSurveyID, $aCodeMap) } -/** -* This function is a replacement of accessDenied.php which return appropriate error message which is then displayed. -* -* @params string $action - action for which acces denied error message is to be returned -* @params string sid - survey id -* @return $accesssummary - proper access denied error message -*/ -function accessDenied($action,$sid='') -{ - - if (App()->user->id) - { - $ugid = Yii::app()->getConfig('ugid'); - $accesssummary = "

".gT("Access denied!")."
\n"; - $scriptname = Yii::app()->getConfig('scriptname'); - //$action=returnGlobal('action'); - if ( $action == "dumpdb" ) - { - $accesssummary .= "

".gT("You are not allowed dump the database!")."
"; - $accesssummary .= "".gT("Continue")."
 \n"; - } - elseif($action == "dumplabel") - { - $accesssummary .= "

".gT("You are not allowed export a label set!")."
"; - $accesssummary .= "".gT("Continue")."
 \n"; - } - elseif($action == "edituser") - { - $accesssummary .= "

".gT("You are not allowed to change user data!"); - $accesssummary .= "

".gT("Continue")."
 \n"; - } - elseif($action == "newsurvey") - { - $accesssummary .= "

".gT("You are not allowed to create new surveys!")."
"; - $accesssummary .= "".gT("Continue")."
 \n"; - } - elseif($action == "deletesurvey") - { - $accesssummary .= "

".gT("You are not allowed to delete this survey!")."
"; - $accesssummary .= "".gT("Continue")."
 \n"; - } - elseif($action == "addquestion") - { - $accesssummary .= "

".gT("You are not allowed to add new questions for this survey!")."
"; - $accesssummary .= "".gT("Continue")."
 \n"; - } - elseif($action == "activate") - { - $accesssummary .= "

".gT("You are not allowed to activate this survey!")."
"; - $accesssummary .= "".gT("Continue")."
 \n"; - } - elseif($action == "deactivate") - { - $accesssummary .= "

".gT("You are not allowed to stop this survey!")."
"; - $accesssummary .= "".gT("Continue")."
 \n"; - } - elseif($action == "addgroup") - { - $accesssummary .= "

".gT("You are not allowed to add a group to this survey!")."
"; - $accesssummary .= "".gT("Continue")."
 \n"; - } - elseif($action == "ordergroups") - { - $link = Yii::app()->getController()->createUrl("/admin/survey/sa/view/surveyid/$sid"); - $accesssummary .= "

".gT("You are not allowed to order groups in this survey!")."
"; - $accesssummary .= "".gT("Continue")."
 \n"; - } - elseif($action == "editsurvey") - { - $link = Yii::app()->getController()->createUrl("/admin/survey/sa/view/surveyid/$sid"); - $accesssummary .= "

".gT("You are not allowed to edit this survey!")."

"; - $accesssummary .= "".gT("Continue")."
 \n"; - } - elseif($action == "editgroup") - { - $accesssummary .= "

".gT("You are not allowed to edit groups in this survey!")."

"; - $accesssummary .= "".gT("Continue")."
 \n"; - } - elseif($action == "browse_response" || $action == "listcolumn" || $action == "vvexport" || $action == "vvimport") - { - $accesssummary .= "

".gT("You are not allowed to browse responses!")."

"; - $accesssummary .= "".gT("Continue")."
 \n"; - } - elseif($action == "assessment") - { - $accesssummary .= "

".gT("You are not allowed to set assessment rules!")."

"; - $accesssummary .= "".gT("Continue")."
 \n"; - } - elseif($action == "delusergroup") - { - $accesssummary .= "

".gT("You are not allowed to delete this group!")."

"; - $accesssummary .= "".gT("Continue")."
 \n"; - } - elseif($action == "importsurvey") - { - $accesssummary .= "

".gT("You are not allowed to import a survey!")."

"; - $accesssummary .= "".gT("Continue")."
 \n"; - } - - elseif($action == "importgroup") - { - $accesssummary .= "

".gT("You are not allowed to import a group!")."

"; - $accesssummary .= "".gT("Continue")."
 \n"; - } - elseif($action == "importquestion") - { - $accesssummary .= "

".gT("You are not allowed to to import a question!")."

"; - $accesssummary .= "".gT("Continue")."
 \n"; - } - elseif($action == "CSRFwarn") //won't be used. - { - $sURLID=''; - if (isset($sid)) { - $sURLID="?sid={$sid}"; - } - $accesssummary .= "

".gT("Security alert").": ".gT("Someone may be trying to use your LimeSurvey session (CSRF attack suspected). If you just clicked on a malicious link, please report this to your system administrator.").'
'.gT('Also this problem can occur when you are working/editing in LimeSurvey in several browser windows/tabs at the same time.')."

"; - $accesssummary .= "".gT("Continue")."
 \n"; - } - elseif($action == "FakeGET") - { - $accesssummary .= "

".gT("Security alert").": ".gT("Someone may be trying to use your LimeSurvey session (CSRF attack suspected). If you just clicked on a malicious link, please report this to your system administrator.").'
'.gT('Also this problem can occur when you are working/editing in LimeSurvey in several browser windows/tabs at the same time.')."

"; - $accesssummary .= "".gT("Continue")."
 \n"; - } - else - { - $accesssummary .= "
".gT("You are not allowed to perform this operation!")."
\n"; - if(!empty($sid)) - { - $accesssummary .= "

".gT("Continue")."
 \n"; - } - else - { - $accesssummary .= "

".gT("Continue")."
 \n"; - } - } - return $accesssummary; - } - -} - /** * cleanLanguagesFromSurvey() removes any languages from survey tables that are not in the passed list * @param string $sid - the currently selected survey @@ -5885,70 +5614,7 @@ function getLastInsertID($sTableName) } } -// TMSW Condition->Relevance: This function is not needed? Optionally replace this with call to EM to get similar info -/** -* getGroupDepsForConditions() get Dependencies between groups caused by conditions -* @param string $sid - the currently selected survey -* @param string $depgid - (optionnal) get only the dependencies applying to the group with gid depgid -* @param string $targgid - (optionnal) get only the dependencies for groups dependents on group targgid -* @param string $index-by - (optionnal) "by-depgid" for result indexed with $res[$depgid][$targgid] -* "by-targgid" for result indexed with $res[$targgid][$depgid] -* @return array - returns an array describing the conditions or NULL if no dependecy is found -* -* Example outupt assumin $index-by="by-depgid": -*Array -*( -* [125] => Array // Group Id 125 is dependent on -* ( -* [123] => Array // Group Id 123 -* ( -* [depgpname] => G3 // GID-125 has name G3 -* [targetgpname] => G1 // GID-123 has name G1 -* [conditions] => Array -* ( -* [189] => Array // Because Question Id 189 -* ( -* [0] => 9 // Have condition 9 set -* [1] => 10 // and condition 10 set -* [2] => 14 // and condition 14 set -* ) -* -* ) -* -* ) -* -* [124] => Array // GID 125 is also dependent on GID 124 -* ( -* [depgpname] => G3 -* [targetgpname] => G2 -* [conditions] => Array -* ( -* [189] => Array // Because Question Id 189 have conditions set -* ( -* [0] => 11 -* ) -* -* [215] => Array // And because Question Id 215 have conditions set -* ( -* [0] => 12 -* ) -* -* ) -* -* ) -* -* ) -* -*) -* -* Usage example: -* * Get all group dependencies for SID $sid indexed by depgid: -* $result=getGroupDepsForConditions($sid); -* * Get all group dependencies for GID $gid in survey $sid indexed by depgid: -* $result=getGroupDepsForConditions($sid,$gid); -* * Get all group dependents on group $gid in survey $sid indexed by targgid: -* $result=getGroupDepsForConditions($sid,"all",$gid,"by-targgid"); -*/ + function getGroupDepsForConditions($sid,$depgid="all",$targgid="all",$indexby="by-depgid") { $sid=sanitize_int($sid); @@ -6761,26 +6427,7 @@ function aEncodingsArray() "utf8" => gT("UTF-8 Unicode"), ); } -/** -* Swaps two positions in an array -* -* @param mixed $key1 -* @param mixed $key2 -* @param mixed $array -*/ -function arraySwapAssoc($key1, $key2, $array) { - $newArray = array (); - foreach ($array as $key => $value) { - if ($key == $key1) { - $newArray[$key2] = $array[$key2]; - } elseif ($key == $key2) { - $newArray[$key1] = $array[$key1]; - } else { - $newArray[$key] = $value; - } - } - return $newArray; -} + /** @@ -6953,14 +6600,6 @@ function getSerialClass($sSerial) { return isset($aTypes[$aParts[0]]) ? $aTypes[$aParts[0]] : (isset($aParts[2]) ? trim($aParts[2], '"') : null); } - /** - * Checks if a string looks like it is a MD5 hash - * - * @param mixed $md5 - */ - function isMd5($sMD5 ='') { - return strlen($sMD5) == 32 && ctype_xdigit($sMD5); - } // Closing PHP tag intentionally omitted - yes, it is okay diff --git a/application/helpers/database_helper.php b/application/helpers/database_helper.php index b4d6c899588..ce6f8679444 100644 --- a/application/helpers/database_helper.php +++ b/application/helpers/database_helper.php @@ -46,15 +46,6 @@ function dbExecuteAssoc($sql,$inputarr=false,$silent=true) } -function dbQueryOrFalse($sql) -{ - try { - $dataset=Yii::app()->db->createCommand($sql)->query(); - } catch(CDbException $e) { - $dataset=false; - } - return $dataset; -} function dbSelectLimitAssoc($sql,$numrows=0,$offset=0,$inputarr=false,$dieonerror=true) @@ -88,33 +79,6 @@ function dbSelectLimitAssoc($sql,$numrows=0,$offset=0,$inputarr=false,$dieonerro } -/** -* This functions quotes fieldnames accordingly -* -* @param mixed $id Fieldname to be quoted -*/ - -function dbQuoteID($id) -{ - switch (Yii::app()->db->getDriverName()) - { - case "mysqli" : - case "mysql" : - return "`".$id."`"; - break; - case "dblib": - case "mssql" : - case "sqlsrv" : - return "[".$id."]"; - break; - case "pgsql": - return "\"".$id."\""; - break; - default: - return $id; - } -} - /** * Return the random function to use in ORDER BY sql statements * @@ -122,37 +86,29 @@ function dbQuoteID($id) */ function dbRandom() { - $driver = Yii::app()->db->getDriverName(); - - // Looked up supported db-types in InstallerConfigForm.php - // Use below statement to find them - //$configForm = new InstallerConfigForm(); - //$dbTypes = $configForm->db_names; //Supported types are in this array - - switch ($driver) + switch (App()->db->getDriverName()) { case 'dblib': case 'mssql': case 'sqlsrv': - $srandom='NEWID()'; + $result = 'NEWID()'; break; - case 'pgsql': - $srandom='RANDOM()'; + $result = 'RANDOM()'; break; case 'mysql': case 'mysqli': - $srandom='RAND()'; + $result = 'RAND()'; break; default: //Some db type that is not mentioned above, could fail and if so should get an entry above. - $srandom= 0 + lcg_value()*(abs(1)); + throw new \Exception("This driver does not support random"); break; } - return $srandom; + return $result; } diff --git a/application/helpers/expressions/em_manager_helper.php b/application/helpers/expressions/em_manager_helper.php index ac31263df73..3b3639e23cb 100644 --- a/application/helpers/expressions/em_manager_helper.php +++ b/application/helpers/expressions/em_manager_helper.php @@ -5285,14 +5285,14 @@ private function _UpdateValuesInDatabase($finished=false) $thisstep = 1; break; } - $setter[] = dbQuoteID('lastpage') . "=" . App()->db->quoteValue($thisstep); + $setter[] = App()->db->quoteColumnName('lastpage') . "=" . App()->db->quoteValue($thisstep); if ($this->surveyOptions['datestamp'] && isset($_SESSION[$this->sessid]['datestamp'])) { $_SESSION[$this->sessid]['datestamp']=dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $this->surveyOptions['timeadjust']); - $setter[] = dbQuoteID('datestamp') . "=" . App()->db->quoteValue(dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $this->surveyOptions['timeadjust'])); + $setter[] = App()->db->quoteColumnName('datestamp') . "=" . App()->db->quoteValue(dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $this->surveyOptions['timeadjust'])); } if ($this->surveyOptions['ipaddr']) { - $setter[] = dbQuoteID('ipaddr') . "=" . App()->db->quoteValue(getIPAddress()); + $setter[] = App()->db->quoteColumnName('ipaddr') . "=" . App()->db->quoteValue(getIPAddress()); } foreach ($updatedValues as $key=>$value) @@ -5329,11 +5329,11 @@ private function _UpdateValuesInDatabase($finished=false) if (is_null($val)) { - $setter[] = dbQuoteID($key) . "=NULL"; + $setter[] = App()->db->quoteColumnName($key) . "=NULL"; } else { - $setter[] = dbQuoteID($key) . "=" . App()->db->quoteValue($val); + $setter[] = App()->db->quoteColumnName($key) . "=" . App()->db->quoteValue($val); } } $query .= implode(', ', $setter); @@ -5388,11 +5388,11 @@ private function _UpdateValuesInDatabase($finished=false) if($this->surveyOptions['datestamp']) { // Replace with date("Y-m-d H:i:s") ? See timeadjust - $sQuery .= dbQuoteID('submitdate') . "=" . App()->db->quoteValue(dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $this->surveyOptions['timeadjust'])); + $sQuery .= App()->db->quoteColumnName('submitdate') . "=" . App()->db->quoteValue(dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $this->surveyOptions['timeadjust'])); } else { - $sQuery .= dbQuoteID('submitdate') . "=" . App()->db->quoteValue(date("Y-m-d H:i:s",mktime(0,0,0,1,1,1980))); + $sQuery .= App()->db->quoteColumnName('submitdate') . "=" . App()->db->quoteValue(date("Y-m-d H:i:s",mktime(0,0,0,1,1,1980))); } $sQuery .= " WHERE `id` = '{$_SESSION[$this->sessid]['srid']}'"; dbExecuteAssoc($sQuery); // Checked @@ -5760,7 +5760,7 @@ private function _ValidateSurvey($force=false) * @param boolean $force : force validation to true, even if there are error * @return - detailed information about this group */ - private function _ValidateGroup($groupSeq,$force=false) + public function _ValidateGroup($groupSeq,$force=false) { if ($groupSeq < 0 || $groupSeq >= $this->numGroups) { return NULL; // TODO - what is desired behavior? diff --git a/application/helpers/frontend_helper.php b/application/helpers/frontend_helper.php index 45ab208f87e..54e97c2738f 100644 --- a/application/helpers/frontend_helper.php +++ b/application/helpers/frontend_helper.php @@ -446,24 +446,10 @@ function addtoarray_single($array1, $array2) */ function submittokens($quotaexit=false) { - $surveyid=Yii::app()->getConfig('surveyID'); - if(isset($_SESSION['survey_'.$surveyid]['s_lang'])) - { - $thissurvey=getSurveyInfo($surveyid,$_SESSION['survey_'.$surveyid]['s_lang']); - } - else - { - $thissurvey=getSurveyInfo($surveyid); - } - $clienttoken = $_SESSION['survey_'.$surveyid]['token']; - - $sitename = Yii::app()->getConfig("sitename"); - $emailcharset = Yii::app()->getConfig("emailcharset"); - // Shift the date due to global timeadjust setting - $today = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i", Yii::app()->getConfig("timeadjust")); + $session = App()->surveySessionManager->current; + $survey = $session->survey; + $token = $session->response->tokenObject; - // check how many uses the token has left - $token = Token::model($surveyid)->findByAttributes(array('token' => $clienttoken)); if ($quotaexit==true) { @@ -475,25 +461,29 @@ function submittokens($quotaexit=false) if ($token->usesleft <= 1) { // Finish the token - if (isTokenCompletedDatestamped($thissurvey)) + if (!$token->survey->bool_anonymized) { - $token->completed = $today; + $token->completed = date('Y-m-d'); } else { $token->completed = 'Y'; } if(isset($token->participant_id)) { - $slquery = SurveyLink::model()->find('participant_id = :pid AND survey_id = :sid AND token_id = :tid', array(':pid'=> $token->participant_id, ':sid'=>$surveyid, ':tid'=>$token->tid)); - if ($slquery) + $surveyLink = SurveyLink::model()->findByAttributes([ + 'participant_id' => $token->participant_id, + 'survey_id' => $survey->primaryKey, + 'token_id' => $token->primaryKey + ]); + if (isset($surveyLink)) { - if (isTokenCompletedDatestamped($thissurvey)) + if ($token->survey->bool_anonymized) { - $slquery->date_completed = $today; + $surveyLink->date_completed = date('Y-m-d'); } else { // Update the survey_links table if necessary, to protect anonymity, use the date_created field date - $slquery->date_completed = $slquery->date_created; + $surveyLink->date_completed = $surveyLink->date_created; } - $slquery->save(); + $surveyLink->save(); } } } @@ -503,63 +493,55 @@ function submittokens($quotaexit=false) if ($quotaexit==false) { - if ($token && trim(strip_tags($thissurvey['email_confirm'])) != "" && $thissurvey['sendconfirmation'] == "Y") + if (trim(strip_tags($survey->localizedConfirmationEmail)) != "" && $survey->bool_sendconfirmation) { // if($token->completed == "Y" || $token->completed == $today) // { - $from = "{$thissurvey['adminname']} <{$thissurvey['adminemail']}>"; - $subject=$thissurvey['email_confirm_subj']; + $from = "{$survey->admin} <{$survey->adminemail}>"; + $subject= $survey->localizedConfirmationEmailSubject; - $aReplacementVars=array(); - $aReplacementVars["ADMINNAME"]=$thissurvey['admin']; - $aReplacementVars["ADMINEMAIL"]=$thissurvey['adminemail']; - $aReplacementVars['ADMINEMAIL'] = $thissurvey['adminemail']; + $aReplacementVars= []; + $aReplacementVars["ADMINNAME"] = $survey->admin; + $aReplacementVars["ADMINEMAIL"] = $survey->adminEmail; //Fill with token info, because user can have his information with anonimity control - $aReplacementVars["FIRSTNAME"]=$token->firstname; - $aReplacementVars["LASTNAME"]=$token->lastname; - $aReplacementVars["TOKEN"]=$token->token; + $aReplacementVars["FIRSTNAME"] = $token->firstname; + $aReplacementVars["LASTNAME"] = $token->lastname; + $aReplacementVars["TOKEN"] = $token->token; // added survey url in replacement vars - $surveylink = Yii::app()->createAbsoluteUrl("/survey/index/sid/{$surveyid}",array('lang'=>$_SESSION['survey_'.$surveyid]['s_lang'],'token'=>$token->token)); - $aReplacementVars['SURVEYURL'] = $surveylink; + $aReplacementVars['SURVEYURL'] = App()->createAbsoluteUrl("survey/index", [ + 'lang' => $session->language, + 'token' => $token->token, + 'sid' => $survey->primaryKey + ]); - $attrfieldnames=getAttributeFieldNames($surveyid); + $attrfieldnames = $token->customAttributeNames(); foreach ($attrfieldnames as $attr_name) { $aReplacementVars[strtoupper($attr_name)] = $token->$attr_name; } - $dateformatdatat=getDateFormatData($thissurvey['surveyls_dateformat']); - $numberformatdatat = getRadixPointData($thissurvey['surveyls_numberformat']); - $redata=array('thissurvey'=>$thissurvey); + $dateformatdatat = getDateFormatData($survey->getLocalizedDateFormat()); + $numberformatdatat = getRadixPointData($survey->getLocalizedNumberFormat()); + $redata = []; $subject=templatereplace($subject,$aReplacementVars,$redata,'email_confirm_subj', false, NULL, array(), true ); - $subject=html_entity_decode($subject,ENT_QUOTES,$emailcharset); + $subject = html_entity_decode($subject,ENT_QUOTES); - if (getEmailFormat($surveyid) == 'html') - { - $ishtml=true; - } - else - { - $ishtml=false; - } + $ishtml = $survey->bool_htmlemail; - $message=$thissurvey['email_confirm']; - //$message=ReplaceFields($message, $fieldsarray, true); - $message=templatereplace($message,$aReplacementVars,$redata,'email_confirm', false, NULL, array(), true ); + $message = html_entity_decode( + templatereplace($survey->getLocalizedConfirmationEmail(), $aReplacementVars, $redata,'email_confirm', false, NULL, array(), true ), + ENT_QUOTES + ); if (!$ishtml) { - $message=strip_tags(breakToNewline(html_entity_decode($message,ENT_QUOTES,$emailcharset))); - } - else - { - $message=html_entity_decode($message,ENT_QUOTES, $emailcharset ); + $message=strip_tags(breakToNewline($message)); } //Only send confirmation email if there is a valid email address $sToAddress=validateEmailAddresses($token->email); if ($sToAddress) { - $aAttachments = unserialize($thissurvey['attachments']); + $aAttachments = unserialize($survey->getLocalizedAttachments()); $aRelevantAttachments = array(); /* @@ -577,7 +559,7 @@ function submittokens($quotaexit=false) } } } - SendEmailMessage($message, $subject, $sToAddress, $from, $sitename, $ishtml, null, $aRelevantAttachments); + SendEmailMessage($message, $subject, $sToAddress, $from, SettingGlobal::get('sitename'), $ishtml, null, $aRelevantAttachments); } // } else { // Leave it to send optional confirmation at closed token @@ -848,7 +830,7 @@ function buildsurveysession($surveyid,$preview=false) $thissurvey = getSurveyInfo($surveyid,$sLangCode); $_SESSION['survey_'.$surveyid]['templatename']=$thissurvey['template'];// $thissurvey['template'] already fixed by model : but why put this in session ? - $_SESSION['survey_'.$surveyid]['templatepath']=getTemplatePath($thissurvey['template']).DIRECTORY_SEPARATOR; + $_SESSION['survey_'.$surveyid]['templatepath']=Template::getTemplatePath($thissurvey['template']).DIRECTORY_SEPARATOR; $sTemplatePath=$_SESSION['survey_'.$surveyid]['templatepath']; $loadsecurity = returnGlobal('loadsecurity',true); @@ -1931,7 +1913,7 @@ function checkCompletedQuota($surveyid,$return=false) // Now we have all the information we need about the quotas and their status. // We need to construct the page and do all needed action $aSurveyInfo=getSurveyInfo($surveyid, $_SESSION['survey_'.$surveyid]['s_lang']); - $sTemplatePath=getTemplatePath($aSurveyInfo['template']); + $sTemplatePath=Template::getTemplatePath($aSurveyInfo['template']); $sClientToken=isset($_SESSION['survey_'.$surveyid]['token'])?$_SESSION['survey_'.$surveyid]['token']:""; // $redata for templatereplace $aDataReplacement = array( diff --git a/application/helpers/qanda_helper.php b/application/helpers/qanda_helper.php index 48f0ffeac22..1a0bcf16913 100644 --- a/application/helpers/qanda_helper.php +++ b/application/helpers/qanda_helper.php @@ -330,7 +330,7 @@ function retrieveAnswers($ia) }; if(!defined('QUESTION_START')) { - define('QUESTION_START' , file_get_contents(getTemplatePath($thissurvey['template']).'/question_start.pstpl' , true)); + define('QUESTION_START' , file_get_contents(Template::getTemplatePath($thissurvey['template']).'/question_start.pstpl' , true)); }; $qtitle_custom = str_replace( $find , $replace , QUESTION_START); diff --git a/application/helpers/remotecontrol/remotecontrol_handle.php b/application/helpers/remotecontrol/remotecontrol_handle.php index 82c5531a937..8b81f8063b6 100644 --- a/application/helpers/remotecontrol/remotecontrol_handle.php +++ b/application/helpers/remotecontrol/remotecontrol_handle.php @@ -485,10 +485,10 @@ public function export_timeline($sSessionKey, $iSurveyID, $sType, $dStart, $dEnd { if (!$this->_checkSessionKey($sSessionKey)) return array('status' => 'Invalid session key'); if (!in_array($sType, array('day','hour'))) return array('status' => 'Invalid Period'); - if (!App->user->checkAccess('responses', ['entity' => 'survey', 'entity_id' => $iSurveyID]) return array('status' => 'No permission'); + if (!App()->user->checkAccess('responses', ['entity' => 'survey', 'entity_id' => $iSurveyID])) return array('status' => 'No permission'); $oSurvey=Survey::model()->findByPk($iSurveyID); if (is_null($oSurvey)) return array('status' => 'Error: Invalid survey ID'); - if (!tableExists('{{survey_' . $iSurveyID . '}}')) return array('status' => 'No available data'); + if (!Response::valid($iSurveyID)) return array('status' => 'No available data'); $oResponses = SurveyDynamic::model($iSurveyID)->timeline($sType, $dStart, $dEnd); if (empty($oResponses)) return array('status' => 'No valid Data'); diff --git a/application/helpers/replacements_helper.php b/application/helpers/replacements_helper.php index ddc722dd92e..370d1e8ae25 100644 --- a/application/helpers/replacements_helper.php +++ b/application/helpers/replacements_helper.php @@ -116,8 +116,8 @@ function templatereplace($line, $replacements = array(), &$redata = array(), $de { $templatename=Yii::app()->getConfig('defaulttemplate'); } - if(!isset($templatedir)) $templatedir = getTemplatePath($templatename); - if(!isset($templateurl)) $templateurl = getTemplateURL($templatename)."/"; + if(!isset($templatedir)) $templatedir = \Template::getTemplatePath($templatename); + if(!isset($templateurl)) $templateurl = \Template::getTemplateURL($templatename)."/"; if (!$anonymized && isset($thissurvey['anonymized'])) { $anonymized=($thissurvey['anonymized']=="Y"); } diff --git a/application/helpers/update/updatedb_helper.php b/application/helpers/update/updatedb_helper.php index fbc0751da5a..80873f0764d 100644 --- a/application/helpers/update/updatedb_helper.php +++ b/application/helpers/update/updatedb_helper.php @@ -2206,15 +2206,6 @@ function dropPrimaryKey($sTablename) // find out the constraint name of the old primary key } -function fixLanguageConsistencyAllSurveys() -{ - $surveyidquery = "SELECT sid,additional_languages FROM ".dbQuoteID('{{surveys}}'); - $surveyidresult = Yii::app()->db->createCommand($surveyidquery)->queryAll(); - foreach ( $surveyidresult as $sv ) - { - fixLanguageConsistency($sv['sid'],$sv['additional_languages']); - } -} function alterColumn($sTable, $sColumn, $sFieldType, $bAllowNull=true, $sDefault='NULL') { diff --git a/application/models/Response.php b/application/models/Response.php index 2384058a506..1932b0cb59b 100644 --- a/application/models/Response.php +++ b/application/models/Response.php @@ -2,7 +2,7 @@ /** * Relations - * @property Token $token + * @property Token $tokenObject * @property int $surveyId * @property Question[] $questions * @property Survey $survey @@ -64,11 +64,11 @@ public function getSurveyId() * @param mixed $className Either the classname or the survey id. * @return Response */ - public static function model($className = null) { - if (!is_numeric($className)) { - var_dump($className); die(); + public static function model($surveyId = null) { + if (!is_numeric($surveyId)) { + throw new \InvalidArgumentException("Survey ID must be numeric"); } - return parent::model($className); + return parent::model($surveyId); } /** @@ -122,7 +122,8 @@ public function relations() { $t = $this->getTableAlias(); $result = array( - 'token' => array(self::BELONGS_TO, 'Token_' . $this->dynamicId, array('token' => 'token')), + // Since we have a field named token as well. + 'tokenObject' => array(self::BELONGS_TO, 'Token_' . $this->dynamicId, array('token' => 'token')), 'survey' => array(self::BELONGS_TO, 'Survey', '', 'on' => "sid = {$this->dynamicId}" ), ); return $result; diff --git a/application/models/Survey.php b/application/models/Survey.php index fdca9a8499b..33fba408f68 100644 --- a/application/models/Survey.php +++ b/application/models/Survey.php @@ -20,6 +20,8 @@ * @property-read boolean $isExpired * @property-read SurveyLanguageSetting[] $languagesettings * @property-read QuestionGroup[] $groups + * @property string $admin + * @property string $adminEmail */ class Survey extends LSActiveRecord { @@ -97,6 +99,22 @@ public function getLocalizedEndText() { return $this->localizedProperty('endtext'); } + + public function getLocalizedConfirmationEmail() { + return $this->localizedProperty('email_confirm'); + } + + public function getLocalizedConfirmationEmailSubject() { + return $this->localizedProperty('email_confirm_subj'); + } + + public function getLocalizedAttachments() { + return $this->localizedProperty('attachments', ''); + } + + public function getEmailFormat() { + return $this->bool_htmlemail ? 'html' : 'text'; + } /** * @return string @@ -104,6 +122,7 @@ public function getLocalizedEndText() public function getLocalizedEndUrl() { return $this->localizedProperty('url'); } + /** * Getter to support proper casing of the property: * $this->adminEmail instead of $this->adminemail @@ -112,8 +131,8 @@ public function getLocalizedEndUrl() { public function getAdminEmail() { return $this->attributes['adminemail']; } - protected function localizedProperty($name) { - $property = 'surveyls_' . $name; + protected function localizedProperty($name, $prefix = 'surveyls_') { + $property = $prefix . $name; if (isset($this->languagesettings[App()->language])) { return $this->languagesettings[App()->language]->$property; } elseif (isset($this->languagesettings[$this->language])) { diff --git a/application/models/Token.php b/application/models/Token.php index 192fb2b645e..3fc6f1c0749 100644 --- a/application/models/Token.php +++ b/application/models/Token.php @@ -340,6 +340,13 @@ public function getIsExpired() { && (new DateTime($this->expires)) < new DateTime() && (new DateTime($this->validfrom)) > new DateTime(); } + + + public function customAttributeNames() { + return array_filter($this->attributeNames(), function($attribute) { + return strncmp("attribute_", $attribute, 10) === 0; + }); + } } ?> diff --git a/application/views/admin/survey/Question/editQuestion_view.php b/application/views/admin/survey/Question/editQuestion_view.php index 595a230563f..ab3b032fa38 100644 --- a/application/views/admin/survey/Question/editQuestion_view.php +++ b/application/views/admin/survey/Question/editQuestion_view.php @@ -185,7 +185,9 @@ getConfig('defaulttemplate')) . '/print_template.css" />'; +echo ''; echo $surveydesc . "
"; echo $welcome . "

"; diff --git a/application/views/admin/survey/subview/tabPresentation_view.php b/application/views/admin/survey/subview/tabPresentation_view.php index 55cb612a6f4..0f336e54492 100644 --- a/application/views/admin/survey/subview/tabPresentation_view.php +++ b/application/views/admin/survey/subview/tabPresentation_view.php @@ -159,7 +159,7 @@ 'preview'=>array( 'type'=>'info', 'label'=>gT("Template preview"), - 'content'=>CHtml::image(getTemplateURL($esrow['template']).'/preview.png',gT("Template preview image"),array('id'=>'preview','class'=>'img-thumbnail')), + 'content'=>CHtml::image(\Template::getTemplateURL($esrow['template']).'/preview.png',gT("Template preview image"),array('id'=>'preview','class'=>'img-thumbnail')), ), 'showwelcome'=>array( 'type'=>'select', diff --git a/application/views/global/surveyMenu.php b/application/views/global/surveyMenu.php index 9608719337f..4ade624bfb4 100644 --- a/application/views/global/surveyMenu.php +++ b/application/views/global/surveyMenu.php @@ -23,7 +23,7 @@ ], [ 'title' => gT('Execute survey.'), 'icon' => 'certificate', - 'disabled' => !$model->isActive || $model->isExpired, + 'disabled' => !$model->isActive || $model->isExpired || $model->bool_usetokens, 'linkOptions' => ['target' => '_blank'], 'url' => !$model->isActive || $model->isExpired ? '#' : ["surveys/start", 'id' => $model->sid] ], [ diff --git a/application/views/statistics_user_view.php b/application/views/statistics_user_view.php index 80f4e12e2e2..8f3a22b518e 100644 --- a/application/views/statistics_user_view.php +++ b/application/views/statistics_user_view.php @@ -9,6 +9,6 @@
diff --git a/application/views/tokens/index.php b/application/views/tokens/index.php index 39a23e1a063..e03ba3b1671 100644 --- a/application/views/tokens/index.php +++ b/application/views/tokens/index.php @@ -31,7 +31,10 @@ }, 'url' => function(Token $model, $row) { return App()->createUrl('surveys/start', ['token' => $model->token, 'id' => $model->surveyId]); - } + }, + 'options' => [ + 'target' => '_blank' + ] ] ] ], [ @@ -54,7 +57,7 @@ 'icon' => TbHtml::ICON_PLUS, 'label' => gT("Add empty response to series"), 'visible' => function($row, Token $model) { - return $model->completed != 'N'; + return $model->completed != 'N' && $model->usesleft > 1; }, 'url' => function(Token $model, $row) { return App()->createUrl('responses/append', ['id' => $model->primaryKey, 'surveyId' => $model->surveyId, 'copy' => false]); @@ -64,7 +67,7 @@ 'icon' => TbHtml::ICON_PLUS_SIGN, 'label' => gT("Add response to series, based on last response"), 'visible' => function($row, Token $model) { - return $model->completed != 'N'; + return $model->completed != 'N' && $model->usesleft > 1; }, 'url' => function(Token $model, $row) { return App()->createUrl('responses/append', ['id' => $model->primaryKey, 'surveyId' => $model->surveyId, 'copy' => true]);