diff --git a/application/commands/CompileAssetsCommand.php b/application/commands/CompileAssetsCommand.php index 9ab2f8efc17..0869de937ac 100644 --- a/application/commands/CompileAssetsCommand.php +++ b/application/commands/CompileAssetsCommand.php @@ -1,4 +1,5 @@ liveExecuteCommand("(cd {$packageFolder} && {$method})", $logfile); break; - case "npm" : + case "npm": $this->liveExecuteCommand("(cd {$packageFolder} && {$method} run compile)", $logfile); break; - case "bash" : + case "bash": $this->liveExecuteCommand("(cd {$packageFolder} && {$method} compile.sh)", $logfile); break; } @@ -95,7 +96,7 @@ private function liveExecuteCommand($cmd, $logfile = false) while (!feof($proc)) { $live_output = fread($proc, 4096); - $complete_output = $complete_output.$live_output; + $complete_output = $complete_output . $live_output; echo "$live_output"; @ flush(); @@ -109,7 +110,7 @@ private function liveExecuteCommand($cmd, $logfile = false) // return exit status and intended output return array( 'exit_status' => intval($matches[0]), - 'output' => str_replace("Exit status : ".$matches[0], '', $complete_output) + 'output' => str_replace("Exit status : " . $matches[0], '', $complete_output) ); } } diff --git a/application/commands/DemomodeCommand.php b/application/commands/DemomodeCommand.php index ccaa082d2e2..d8243c9aa59 100644 --- a/application/commands/DemomodeCommand.php +++ b/application/commands/DemomodeCommand.php @@ -1,4 +1,5 @@ db->quoteTableName($table); - $actquery = "truncate table ".$quotedTable; + $actquery = "truncate table " . $quotedTable; Yii::app()->db->createCommand($actquery)->execute(); } - //Now delete the basics in all other tables + //Now delete the basics in all other tables $actquery = "delete from {{permissions}} where uid<>1"; Yii::app()->db->createCommand($actquery)->execute(); $actquery = "delete from {{users}} where uid<>1"; @@ -71,18 +71,18 @@ private function _resetDatabase() $surveyidresult = dbGetTablesLike("tokens%"); foreach ($surveyidresult as $sv) { - Yii::app()->db->createCommand("drop table ".$sv)->execute(); + Yii::app()->db->createCommand("drop table " . $sv)->execute(); } $surveyidresult = dbGetTablesLike("old\_%"); foreach ($surveyidresult as $sv) { - Yii::app()->db->createCommand("drop table ".$sv)->execute(); + Yii::app()->db->createCommand("drop table " . $sv)->execute(); } $surveyidresult = dbGetTablesLike("survey\_%"); foreach ($surveyidresult as $sv) { if (strpos($sv, 'survey_links') === false && strpos($sv, 'survey_url_parameters') === false) { - Yii::app()->db->createCommand("drop table ".$sv)->execute(); + Yii::app()->db->createCommand("drop table " . $sv)->execute(); } } @@ -90,7 +90,7 @@ private function _resetDatabase() foreach ($templateData = LsDefaultDataSets::getBoxesData() as $boxes) { Yii::app()->db->createCommand()->insert("{{boxes}}", $boxes); } - // At last reset the basic themes + // At last reset the basic themes foreach ($templateData = LsDefaultDataSets::getTemplatesData() as $template) { Yii::app()->db->createCommand()->insert("{{templates}}", $template); } @@ -102,44 +102,43 @@ private function _resetDatabase() private function _resetFiles() { - $sBaseUploadDir = dirname(dirname(dirname(__FILE__))).DIRECTORY_SEPARATOR.'upload'; + $sBaseUploadDir = dirname(dirname(dirname(__FILE__))) . DIRECTORY_SEPARATOR . 'upload'; - SureRemoveDir($sBaseUploadDir.DIRECTORY_SEPARATOR.'surveys', false, ['index.html']); - SureRemoveDir($sBaseUploadDir.DIRECTORY_SEPARATOR.'global', false, ['index.html']); - SureRemoveDir($sBaseUploadDir.DIRECTORY_SEPARATOR.'templates', false); - SureRemoveDir($sBaseUploadDir.DIRECTORY_SEPARATOR.'themes'.DIRECTORY_SEPARATOR.'survey', false, ['index.html']); - SureRemoveDir($sBaseUploadDir.DIRECTORY_SEPARATOR.'themes'.DIRECTORY_SEPARATOR.'question', false); + SureRemoveDir($sBaseUploadDir . DIRECTORY_SEPARATOR . 'surveys', false, ['index.html']); + SureRemoveDir($sBaseUploadDir . DIRECTORY_SEPARATOR . 'global', false, ['index.html']); + SureRemoveDir($sBaseUploadDir . DIRECTORY_SEPARATOR . 'templates', false); + SureRemoveDir($sBaseUploadDir . DIRECTORY_SEPARATOR . 'themes' . DIRECTORY_SEPARATOR . 'survey', false, ['index.html']); + SureRemoveDir($sBaseUploadDir . DIRECTORY_SEPARATOR . 'themes' . DIRECTORY_SEPARATOR . 'question', false); } private function _createDemo() { Yii::app()->loadHelper('admin/import'); - require_once(dirname(dirname(dirname(__FILE__))).'/application/helpers/replacements_helper.php'); - require_once(dirname(dirname(dirname(__FILE__))).'/application/helpers/expressions/em_manager_helper.php'); - require_once(dirname(dirname(dirname(__FILE__))).'/application/helpers/expressions/em_core_helper.php'); - require_once(dirname(dirname(dirname(__FILE__))).'/application/helpers/admin/activate_helper.php'); + require_once(dirname(dirname(dirname(__FILE__))) . '/application/helpers/replacements_helper.php'); + require_once(dirname(dirname(dirname(__FILE__))) . '/application/helpers/expressions/em_manager_helper.php'); + require_once(dirname(dirname(dirname(__FILE__))) . '/application/helpers/expressions/em_core_helper.php'); + require_once(dirname(dirname(dirname(__FILE__))) . '/application/helpers/admin/activate_helper.php'); Yii::app()->session->add('loginID', 1); - $documentationSurveyPath = dirname(dirname(dirname(__FILE__))).DIRECTORY_SEPARATOR.'docs'.DIRECTORY_SEPARATOR.'demosurveys'.DIRECTORY_SEPARATOR; + $documentationSurveyPath = dirname(dirname(dirname(__FILE__))) . DIRECTORY_SEPARATOR . 'docs' . DIRECTORY_SEPARATOR . 'demosurveys' . DIRECTORY_SEPARATOR; $aSamplesurveys = scandir($documentationSurveyPath); $surveysToActivate = []; foreach ($aSamplesurveys as $sSamplesurvey) { $result = null; //Try catch for console application to be able to import surveys - $result = @ XMLImportSurvey($documentationSurveyPath.$sSamplesurvey); + $result = @ XMLImportSurvey($documentationSurveyPath . $sSamplesurvey); if (in_array($sSamplesurvey, ['ls205_sample_survey_multilingual.lss', 'ls205_randomization_group_test.lss', 'ls205_cascading_array_filter_exclude.lss'])) { $surveysToActivate[] = $result['newsid']; } } - require_once(__DIR__.'/../helpers/admin/activate_helper.php'); + require_once(__DIR__ . '/../helpers/admin/activate_helper.php'); array_map('activateSurvey', $surveysToActivate); - } - + } } -function SureRemoveDir($dir, $DeleteMe, $excludes=[]) +function SureRemoveDir($dir, $DeleteMe, $excludes = []) { if (!$dh = @opendir($dir)) { return; @@ -148,15 +147,14 @@ function SureRemoveDir($dir, $DeleteMe, $excludes=[]) if ($obj == '.' || $obj == '..' || in_array($obj, $excludes)) { continue; } - if (!@unlink($dir.'/'.$obj)) { - SureRemoveDir($dir.'/'.$obj, true); + if (!@unlink($dir . '/' . $obj)) { + SureRemoveDir($dir . '/' . $obj, true); } } closedir($dh); if ($DeleteMe) { if (!@rmdir($dir)) { - echo "Error: could not delete ".$dir; + echo "Error: could not delete " . $dir; } - } } diff --git a/application/commands/FlushAssetsCommand.php b/application/commands/FlushAssetsCommand.php index e00c8ee5063..a6d65341a84 100644 --- a/application/commands/FlushAssetsCommand.php +++ b/application/commands/FlushAssetsCommand.php @@ -1,4 +1,5 @@ _sureRemoveFiles($tmpFolder.'/assets/', false, ['index.html']); - $this->_sureRemoveFiles($tmpFolder.'/runtime/cache/', false, ['index.html']); - + $this->_sureRemoveFiles($tmpFolder . '/assets/', false, ['index.html']); + $this->_sureRemoveFiles($tmpFolder . '/runtime/cache/', false, ['index.html']); } private function _sureRemoveFiles($dir, $DeleteMe, $exclude = array()) { @@ -42,16 +42,15 @@ private function _sureRemoveFiles($dir, $DeleteMe, $exclude = array()) if ($obj == '.' || $obj == '..' || in_array($obj, $exclude)) { continue; } - if (!@unlink($dir.'/'.$obj)) { - $this->_sureRemoveFiles($dir.'/'.$obj, true); + if (!@unlink($dir . '/' . $obj)) { + $this->_sureRemoveFiles($dir . '/' . $obj, true); } } closedir($dh); if ($DeleteMe) { if (!@rmdir($dir)) { - echo "Error: could not delete ".$dir; + echo "Error: could not delete " . $dir; } - } } } diff --git a/application/commands/InstallCommand.php b/application/commands/InstallCommand.php index d1f5973ce99..7bac5f73c71 100644 --- a/application/commands/InstallCommand.php +++ b/application/commands/InstallCommand.php @@ -44,21 +44,21 @@ public function run($aArguments) $this->output('Connecting to database...'); $this->connection = App()->getDb(); $this->connection->active = true; - $this->output('Using connection string '.$this->connection->connectionString); + $this->output('Using connection string ' . $this->connection->connectionString); } catch (CDbException $e) { - $this->output('Could not connect to database: '.$e->getMessage()); + $this->output('Could not connect to database: ' . $e->getMessage()); $this->createDatabase(); }; $this->prepareCharset(); - $sFileName = dirname(APPPATH).'/installer/create-database.php'; + $sFileName = dirname(APPPATH) . '/installer/create-database.php'; require_once($sFileName); try { $this->output('Creating tables...'); populateDatabase($this->connection); } catch (Exception $e) { - $this->output('Could not create LimeSurvey tables: '.$e->getMessage()); + $this->output('Could not create LimeSurvey tables: ' . $e->getMessage()); return 1; } @@ -87,7 +87,7 @@ public function getDBConnectionStringProperty($sProperty, $connectionString = nu $connectionString = $this->connection->connectionString; } // Yii doesn't give us a good way to get the database name - if (preg_match('/'.$sProperty.'=([^;]*)/', $connectionString, $aMatches) == 1) { + if (preg_match('/' . $sProperty . '=([^;]*)/', $connectionString, $aMatches) == 1) { return $aMatches[1]; } return null; @@ -101,10 +101,10 @@ public function getDBConnectionStringProperty($sProperty, $connectionString = nu protected function createDatabase() { $this->output('Creating database...'); - App()->configure(array('components'=>array('db'=>array('autoConnect'=>false)))); + App()->configure(array('components' => array('db' => array('autoConnect' => false)))); $this->connection = App()->db; - App()->configure(array('components'=>array('db'=>array('autoConnect'=>true)))); + App()->configure(array('components' => array('db' => array('autoConnect' => true)))); $connectionString = $this->connection->connectionString; $this->output($connectionString); $this->connection->connectionString = preg_replace('/dbname=([^;]*)/', '', $connectionString); @@ -164,7 +164,7 @@ protected function createDatabase() public function output($msg) { if ($this->noisy) { - echo $msg.PHP_EOL; + echo $msg . PHP_EOL; } } @@ -187,7 +187,7 @@ private function prepareCharset() switch ($this->connection->driverName) { case 'mysql': case 'mysqli': - $this->connection->createCommand("ALTER DATABASE ".$this->connection->quoteTableName($this->getDBConnectionStringProperty('dbname'))." DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;")->execute(); + $this->connection->createCommand("ALTER DATABASE " . $this->connection->quoteTableName($this->getDBConnectionStringProperty('dbname')) . " DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;")->execute(); break; case 'pgsql': case 'dblib': @@ -197,21 +197,20 @@ private function prepareCharset() default: throw new Exception(sprintf('Unknown database type "%s".', $this->connection->driverName)); } - } private function createUser($data) { $this->output('Creating admin user...'); $this->connection->createCommand()->insert( - $this->connection->tablePrefix.'users', + $this->connection->tablePrefix . 'users', array( - 'users_name'=>$data[0], - 'password'=>password_hash($data[1], PASSWORD_DEFAULT), - 'full_name'=>$data[2], - 'parent_id'=>0, - 'lang'=>'auto', - 'email'=>$data[3] + 'users_name' => $data[0], + 'password' => password_hash($data[1], PASSWORD_DEFAULT), + 'full_name' => $data[2], + 'parent_id' => 0, + 'lang' => 'auto', + 'email' => $data[3] ) ); } @@ -220,21 +219,19 @@ private function createPermissions() { $this->output('Creating permissions ...'); $this->connection->createCommand()->insert( - $this->connection->tablePrefix.'permissions', + $this->connection->tablePrefix . 'permissions', array( - 'entity'=>'global', - 'entity_id'=>0, - 'uid'=>1, - 'permission'=>'superadmin', - 'create_p'=>0, - 'read_p'=>1, - 'update_p'=>0, - 'delete_p'=>0, - 'import_p'=>0, - 'export_p'=>0 + 'entity' => 'global', + 'entity_id' => 0, + 'uid' => 1, + 'permission' => 'superadmin', + 'create_p' => 0, + 'read_p' => 1, + 'update_p' => 0, + 'delete_p' => 0, + 'import_p' => 0, + 'export_p' => 0 ) ); } - - } diff --git a/application/commands/InstallFromConfigCommand.php b/application/commands/InstallFromConfigCommand.php index 65876bb32f9..a66bb394ad5 100644 --- a/application/commands/InstallFromConfigCommand.php +++ b/application/commands/InstallFromConfigCommand.php @@ -46,8 +46,8 @@ public function run($aArguments) $this->configuration = include($readFromConfig); $this->dbConnectionArray = $this->configuration['components']['db']; - foreach($this->configuration as $configKey => $configValue){ - Yii::app()->params[$configKey] = $configValue; + foreach ($this->configuration as $configKey => $configValue) { + Yii::app()->params[$configKey] = $configValue; } Yii::import('application.helpers.common_helper', true); @@ -59,11 +59,11 @@ public function run($aArguments) $this->connection = App()->getDb(); $this->connection->connectionString = $this->dbConnectionArray['connectionString']; $this->connection->username = $this->dbConnectionArray['username']; - $this->connection->password = $this->dbConnectionArray['password']; + $this->connection->password = $this->dbConnectionArray['password']; $this->connection->active = true; - $this->output('Using connection string '.$this->connection->connectionString); + $this->output('Using connection string ' . $this->connection->connectionString); } catch (CDbException $e) { - $this->output('Could not connect to database: '.$e->getMessage()); + $this->output('Could not connect to database: ' . $e->getMessage()); $this->createDatabase(); }; @@ -72,52 +72,52 @@ public function run($aArguments) switch ($this->connection->driverName) { case 'mysql': case 'mysqli': - $this->connection->createCommand("ALTER DATABASE ".$this->connection->quoteTableName($this->getDBConnectionStringProperty('dbname'))." DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;")->execute(); + $this->connection->createCommand("ALTER DATABASE " . $this->connection->quoteTableName($this->getDBConnectionStringProperty('dbname')) . " DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;")->execute(); break; case 'pgsql': case 'dblib': case 'mssql': case 'sqlsrv': break; - default: + default: throw new Exception(sprintf('Unknown database type "%s".', $this->connection->driverName)); } - $sFileName = dirname(APPPATH).'/installer/create-database.php'; + $sFileName = dirname(APPPATH) . '/installer/create-database.php'; require_once($sFileName); try { $this->output('Creating tables...'); populateDatabase($this->connection); } catch (Exception $e) { - $this->output('Could not create LimeSurvey tables: '.$e->getMessage()); + $this->output('Could not create LimeSurvey tables: ' . $e->getMessage()); return 1; } $this->output('Creating admin user...'); $this->connection->createCommand()->insert( - $this->connection->tablePrefix.'users', + $this->connection->tablePrefix . 'users', array( - 'users_name'=>$this->configuration['config']['defaultuser'], - 'password'=>password_hash($this->configuration['config']['defaultpass'], PASSWORD_DEFAULT), - 'full_name'=>"", - 'parent_id'=>0, - 'lang'=>'auto', - 'email'=>$this->configuration['config']['siteadminemail'] + 'users_name' => $this->configuration['config']['defaultuser'], + 'password' => password_hash($this->configuration['config']['defaultpass'], PASSWORD_DEFAULT), + 'full_name' => "", + 'parent_id' => 0, + 'lang' => 'auto', + 'email' => $this->configuration['config']['siteadminemail'] ) ); $this->connection->createCommand()->insert( - $this->connection->tablePrefix.'permissions', + $this->connection->tablePrefix . 'permissions', array( - 'entity'=>'global', - 'entity_id'=>0, - 'uid'=>1, - 'permission'=>'superadmin', - 'create_p'=>0, - 'read_p'=>1, - 'update_p'=>0, - 'delete_p'=>0, - 'import_p'=>0, - 'export_p'=>0 + 'entity' => 'global', + 'entity_id' => 0, + 'uid' => 1, + 'permission' => 'superadmin', + 'create_p' => 0, + 'read_p' => 1, + 'update_p' => 0, + 'delete_p' => 0, + 'import_p' => 0, + 'export_p' => 0 ) ); $this->output('All done!'); @@ -140,7 +140,7 @@ public function getDBConnectionStringProperty($sProperty, $connectionString = nu $connectionString = $this->dbConnectionArray['connectionString']; } // Yii doesn't give us a good way to get the database name - if (preg_match('/'.$sProperty.'=([^;]*)/', $connectionString, $aMatches) == 1) { + if (preg_match('/' . $sProperty . '=([^;]*)/', $connectionString, $aMatches) == 1) { return $aMatches[1]; } return null; @@ -153,7 +153,7 @@ public function getDBConnectionStringProperty($sProperty, $connectionString = nu protected function createDatabase() { $this->output('Creating database...'); - App()->configure(array('components'=>array('db'=>array('autoConnect'=>false)))); + App()->configure(array('components' => array('db' => array('autoConnect' => false)))); $dbConnectArray = $this->configuration['components']['db']; @@ -173,7 +173,7 @@ protected function createDatabase() $this->output('Opening connection...'); $this->connection->active = true; } catch (Exception $e) { - print_r( $dbConnectArray); + print_r($dbConnectArray); throw new CException("Invalid access data. Check your config.php db access data"); } @@ -220,7 +220,7 @@ protected function createDatabase() public function output($msg) { if ($this->noisy) { - echo $msg.PHP_EOL; + echo $msg . PHP_EOL; } } diff --git a/application/commands/PluginCommand.php b/application/commands/PluginCommand.php index f3277647086..2bf3110cf2b 100644 --- a/application/commands/PluginCommand.php +++ b/application/commands/PluginCommand.php @@ -1,4 +1,5 @@ pluginManager; - $event = new PluginEvent('cron'); - $event->set('interval', $interval); - $pm->dispatchEvent($event); - } + /** + * register some needed or a lot used part + */ + public function init() + { + parent::init(); + Yii::import('application.helpers.common_helper', true); + } - /** - * Call directly an event by command (it's default) - * @param string $target Target of action, plugin name for example - * @param mixed $function Extra parameters for plugin - * @param mixed $option Extra parameters for plugin - * @return void - */ - public function actionIndex($target, $function = null, $option = null) - { - $pm = \Yii::app()->pluginManager; - $event = new PluginEvent('direct'); - $event->set('target', $target); - $event->set('function', $function); - $event->set('option', $option); - $pm->dispatchEvent($event); - } + /** + * Call for cron action + * @param int $interval Minutes for interval + * @return void + */ + public function actionCron($interval = null) + { + $pm = \Yii::app()->pluginManager; + $event = new PluginEvent('cron'); + $event->set('interval', $interval); + $pm->dispatchEvent($event); + } + /** + * Call directly an event by command (it's default) + * @param string $target Target of action, plugin name for example + * @param mixed $function Extra parameters for plugin + * @param mixed $option Extra parameters for plugin + * @return void + */ + public function actionIndex($target, $function = null, $option = null) + { + $pm = \Yii::app()->pluginManager; + $event = new PluginEvent('direct'); + $event->set('target', $target); + $event->set('function', $function); + $event->set('option', $option); + $pm->dispatchEvent($event); } +} diff --git a/application/commands/ResetPasswordCommand.php b/application/commands/ResetPasswordCommand.php index eea7ece4400..dc552448a35 100644 --- a/application/commands/ResetPasswordCommand.php +++ b/application/commands/ResetPasswordCommand.php @@ -1,4 +1,5 @@ setPassword($sArgument[1]); - if ($oUser->save()) { - echo "Password for user {$sArgument[0]} was set.\n"; - return 0; - } else { - echo "An error happen when set password for user {$sArgument[0]}.\n"; - return 1; - } + public function run($sArgument) + { + if (isset($sArgument) && isset($sArgument[0]) && isset($sArgument[1])) { + $oUser = User::findByUsername($sArgument[0]); + if ($oUser) { + $oUser->setPassword($sArgument[1]); + if ($oUser->save()) { + echo "Password for user {$sArgument[0]} was set.\n"; + return 0; } else { - echo "User ".$sArgument[0]." not found.\n"; + echo "An error happen when set password for user {$sArgument[0]}.\n"; return 1; } - } else { - //TODO: a valid error process - echo 'You have to set username and password on the command line like this: php console.php username password'; + echo "User " . $sArgument[0] . " not found.\n"; + return 1; } + } else { + //TODO: a valid error process + echo 'You have to set username and password on the command line like this: php console.php username password'; } } +} diff --git a/application/commands/TwigCommand.php b/application/commands/TwigCommand.php index 3975133fb74..678b2c84055 100644 --- a/application/commands/TwigCommand.php +++ b/application/commands/TwigCommand.php @@ -11,7 +11,8 @@ * It will execute all the functions */ -class TwigCommand extends CConsoleCommand { +class TwigCommand extends CConsoleCommand +{ public $aLogs; // Array of logs @@ -21,16 +22,16 @@ class TwigCommand extends CConsoleCommand { public function init() { // Needed helpers for correct rendering - Yii::import('application.helpers.surveytranslator_helper', true); - Yii::import('application.helpers.common_helper', true); - Yii::import('application.helpers.expressions.em_manager_helper', true); - Yii::import('application.helpers.admin.htmleditor_helper', true); + Yii::import('application.helpers.surveytranslator_helper', true); + Yii::import('application.helpers.common_helper', true); + Yii::import('application.helpers.expressions.em_manager_helper', true); + Yii::import('application.helpers.admin.htmleditor_helper', true); // Directories where the assets will be created. - Yii::app()->assetManager->setBasePath(realpath(__DIR__.'/../../tmp/assets/')); + Yii::app()->assetManager->setBasePath(realpath(__DIR__ . '/../../tmp/assets/')); // This command can be used even with no DB installed. So we force the usage of config.xml rather than DB entries - Yii::app()->setConfig('force_xmlsettings_for_survey_rendering', true); + Yii::app()->setConfig('force_xmlsettings_for_survey_rendering', true); } public function actionIndex() @@ -42,33 +43,32 @@ public function actionIndex() echo "\n"; echo "To execute this command :\n"; echo "php application/commands/console.php Twig generateTwigTmpFiles \n"; - } /** * Generate twig cache files for each core Survey Theme and core questions views. * */ - public function actionGenerateTwigTmpFiles( $sThemeDir=null, $bGenerateSurveyCache=true, $bGenerateQuestionsCache=true, $bGenerateAdminCache=true, $bShowLogs=false ) + public function actionGenerateTwigTmpFiles($sThemeDir = null, $bGenerateSurveyCache = true, $bGenerateQuestionsCache = true, $bGenerateAdminCache = true, $bShowLogs = false) { - $this->aLogs = array(); - $this->aLogs["action"] = "actionGenerateTwigTmpFiles $sThemeDir $bGenerateSurveyCache $bGenerateQuestionsCache $bGenerateAdminCache $bShowLogs"; - if ($bGenerateSurveyCache){ - $this->actionGenerateSurveyThemesCache($sThemeDir ); - } + $this->aLogs = array(); + $this->aLogs["action"] = "actionGenerateTwigTmpFiles $sThemeDir $bGenerateSurveyCache $bGenerateQuestionsCache $bGenerateAdminCache $bShowLogs"; + if ($bGenerateSurveyCache) { + $this->actionGenerateSurveyThemesCache($sThemeDir); + } - if ($bGenerateQuestionsCache){ - $this->actionGenerateQuestionsCache(null); - } + if ($bGenerateQuestionsCache) { + $this->actionGenerateQuestionsCache(null); + } - if ($bGenerateAdminCache){ - $this->actionGenerateAdminCache(null); - } + if ($bGenerateAdminCache) { + $this->actionGenerateAdminCache(null); + } // TODO: here add something more complex to create a file log on the server, something that can be return to the CU server at release creation, etc - if ($bShowLogs){ - var_dump($this->aLogs); - } + if ($bShowLogs) { + var_dump($this->aLogs); + } } /** @@ -76,27 +76,27 @@ public function actionGenerateTwigTmpFiles( $sThemeDir=null, $bGenerateSurveyCac * * @param string $sThemeDir the directory to parse, where to find the manifests. */ - public function actionGenerateSurveyThemesCache($sThemeDir=null) + public function actionGenerateSurveyThemesCache($sThemeDir = null) { - $this->aLogs["action"] = "actionGenerateSurveyThemesCache $sThemeDir"; + $this->aLogs["action"] = "actionGenerateSurveyThemesCache $sThemeDir"; // NOTE 1: by default used only for core theme. // NOTE 2: Later, we'll can use this function to offer to generate .po files for themes developers - $sThemeDir = ($sThemeDir==null) ? dirname(__FILE__).'/../../themes/survey':$sThemeDir; - $oThemeDir = new DirectoryIterator($sThemeDir); + $sThemeDir = ($sThemeDir == null) ? dirname(__FILE__) . '/../../themes/survey' : $sThemeDir; + $oThemeDir = new DirectoryIterator($sThemeDir); - foreach ($oThemeDir as $fileinfo) { - if ($fileinfo->getFilename() != ".." && $fileinfo->getFilename() != "." && $fileinfo->getFilename() != "index.html"){ - $templatename = $fileinfo->getFilename(); - $oTemplateForPreview = Template::getInstance($templatename, null, null, true, true)->prepareTemplateRendering($templatename, null, true); + foreach ($oThemeDir as $fileinfo) { + if ($fileinfo->getFilename() != ".." && $fileinfo->getFilename() != "." && $fileinfo->getFilename() != "index.html") { + $templatename = $fileinfo->getFilename(); + $oTemplateForPreview = Template::getInstance($templatename, null, null, true, true)->prepareTemplateRendering($templatename, null, true); - // Render Survey theme - $this->renderSurveyTheme($oTemplateForPreview); + // Render Survey theme + $this->renderSurveyTheme($oTemplateForPreview); - // Render all the twig strings inside the XML itself - $this->renderSurveyThemeManifest($oTemplateForPreview); + // Render all the twig strings inside the XML itself + $this->renderSurveyThemeManifest($oTemplateForPreview); + } } - } } /** @@ -106,46 +106,46 @@ public function actionGenerateSurveyThemesCache($sThemeDir=null) * * @param string $sQuestionDir the directory to parse, where to find the answer.twig file. */ - public function actionGenerateQuestionsCache( $sQuestionDir=null ) + public function actionGenerateQuestionsCache($sQuestionDir = null) { - $this->aLogs["action"] = "actionGenerateQuestionsCache $sQuestionDir"; + $this->aLogs["action"] = "actionGenerateQuestionsCache $sQuestionDir"; // Generate cache for question theme - $sQuestionDir = ($sQuestionDir===null)?dirname(__FILE__).'/../views/survey/questions/answer':$sQuestionDir; - $oQuestionDir = new DirectoryIterator($sQuestionDir); - - foreach ($oQuestionDir as $fileinfo) { - if ($fileinfo->getFilename() != ".." && $fileinfo->getFilename() != "." && $fileinfo->getFilename() != "index.html"){ - $sQuestionName = $fileinfo->getFilename(); - - $sQuestionDirectory = $sQuestionDir.DIRECTORY_SEPARATOR.$sQuestionName; - - /** - * TODO for ls4/ls5: - * - get the Question XML rather than answer.twig - * - load the default data from the XML - * - * NOTE 1: as long as this is not done, it's highly probable that some twig files will never be reached. - * - * NOTE 2: It should be possible to parse the XML to get the different values for the attributes, and then to generate a cache file for each attribue possible value. - * Doing this could allow to test easely the rendering for all question type, with all question attribute variations. - * Since we're very far to get this with Unit Test (it will imlpy to write around 1000 tests in a row), it could be a first step. - * One way to do: for a stable version, save the rendered HTML somwhere, then in unitest, call this function, compare the rendered HTML to the saved one. - * Enjoy the 1000 test in a single one :) (sadly, only for HTML rendering, not for JS or DB saving) - */ - $sTwigFile = $sQuestionDirectory.DIRECTORY_SEPARATOR."answer.twig"; - $aQuestionData = array(); // See todo - if (file_exists($sTwigFile)){ - $this->aLogs[$sQuestionName] = "$sTwigFile"; - $line = file_get_contents($sTwigFile); - $sHtml = Yii::app()->twigRenderer->convertTwigToHtml($line, $aQuestionData); - }elseif(is_dir($sQuestionDirectory) && $sQuestionName != "arrays"){ - // Recursive step - $this->actionGenerateQuestionsCache($sQuestionDirectory); - } + $sQuestionDir = ($sQuestionDir === null) ? dirname(__FILE__) . '/../views/survey/questions/answer' : $sQuestionDir; + $oQuestionDir = new DirectoryIterator($sQuestionDir); + + foreach ($oQuestionDir as $fileinfo) { + if ($fileinfo->getFilename() != ".." && $fileinfo->getFilename() != "." && $fileinfo->getFilename() != "index.html") { + $sQuestionName = $fileinfo->getFilename(); + + $sQuestionDirectory = $sQuestionDir . DIRECTORY_SEPARATOR . $sQuestionName; + + /** + * TODO for ls4/ls5: + * - get the Question XML rather than answer.twig + * - load the default data from the XML + * + * NOTE 1: as long as this is not done, it's highly probable that some twig files will never be reached. + * + * NOTE 2: It should be possible to parse the XML to get the different values for the attributes, and then to generate a cache file for each attribue possible value. + * Doing this could allow to test easely the rendering for all question type, with all question attribute variations. + * Since we're very far to get this with Unit Test (it will imlpy to write around 1000 tests in a row), it could be a first step. + * One way to do: for a stable version, save the rendered HTML somwhere, then in unitest, call this function, compare the rendered HTML to the saved one. + * Enjoy the 1000 test in a single one :) (sadly, only for HTML rendering, not for JS or DB saving) + */ + $sTwigFile = $sQuestionDirectory . DIRECTORY_SEPARATOR . "answer.twig"; + $aQuestionData = array(); // See todo + if (file_exists($sTwigFile)) { + $this->aLogs[$sQuestionName] = "$sTwigFile"; + $line = file_get_contents($sTwigFile); + $sHtml = Yii::app()->twigRenderer->convertTwigToHtml($line, $aQuestionData); + } elseif (is_dir($sQuestionDirectory) && $sQuestionName != "arrays") { + // Recursive step + $this->actionGenerateQuestionsCache($sQuestionDirectory); + } + } } - } } /** @@ -154,26 +154,26 @@ public function actionGenerateQuestionsCache( $sQuestionDir=null ) * * @param string $sAdminDir the directory to parse, where to find the twig files. */ - public function actionGenerateAdminCache( $sAdminDir=null ) + public function actionGenerateAdminCache($sAdminDir = null) { - $this->aLogs["action"] = "actionGenerateAdminCache $sAdminDir"; + $this->aLogs["action"] = "actionGenerateAdminCache $sAdminDir"; // Generate cache for admin area - $sAdminDir = ($sAdminDir===null)?dirname(__FILE__).'/../views/admin':$sAdminDir; - $oAdminDirectory = new RecursiveDirectoryIterator($sAdminDir); - $oAdminIterator = new RecursiveIteratorIterator($oAdminDirectory); - $oAdminRegex = new RegexIterator($oAdminIterator, '/^.+\.twig$/i', RecursiveRegexIterator::GET_MATCH); - - $aAdminData = array(); - foreach ($oAdminRegex as $oTwigFile) { - $sTwigFile = $oTwigFile[0]; - if (file_exists($sTwigFile)){ - $this->aLogs["twig"] = "$sTwigFile"; - $line = file_get_contents($sTwigFile); - $sHtml = Yii::app()->twigRenderer->convertTwigToHtml($line); + $sAdminDir = ($sAdminDir === null) ? dirname(__FILE__) . '/../views/admin' : $sAdminDir; + $oAdminDirectory = new RecursiveDirectoryIterator($sAdminDir); + $oAdminIterator = new RecursiveIteratorIterator($oAdminDirectory); + $oAdminRegex = new RegexIterator($oAdminIterator, '/^.+\.twig$/i', RecursiveRegexIterator::GET_MATCH); + + $aAdminData = array(); + foreach ($oAdminRegex as $oTwigFile) { + $sTwigFile = $oTwigFile[0]; + if (file_exists($sTwigFile)) { + $this->aLogs["twig"] = "$sTwigFile"; + $line = file_get_contents($sTwigFile); + $sHtml = Yii::app()->twigRenderer->convertTwigToHtml($line); + } } - } } /** @@ -182,26 +182,26 @@ public function actionGenerateAdminCache( $sAdminDir=null ) */ private function renderSurveyTheme($oTemplateForPreview) { - $thissurvey = $oTemplateForPreview->getDefaultDataForRendering(); - $thissurvey['templatedir'] = $oTemplateForPreview->sTemplateName; // $templatename; - - $aScreenList = $oTemplateForPreview->getScreensDetails(); - - foreach($aScreenList as $sScreenName => $aTitleAndLayouts){ - foreach($aTitleAndLayouts['layouts'] as $sLayout => $sContent){ - $this->aLogs[$oTemplateForPreview->sTemplateName][$sScreenName][$sLayout] = $sContent; - $sLayoutFile = $sLayout ; - $thissurvey['include_content'] = $sContent; - - $myoutput = Yii::app()->twigRenderer->renderTemplateForTemplateEditor( - $sLayoutFile, - array( - 'aSurveyInfo' =>$thissurvey, - ), - $oTemplateForPreview - ); + $thissurvey = $oTemplateForPreview->getDefaultDataForRendering(); + $thissurvey['templatedir'] = $oTemplateForPreview->sTemplateName; // $templatename; + + $aScreenList = $oTemplateForPreview->getScreensDetails(); + + foreach ($aScreenList as $sScreenName => $aTitleAndLayouts) { + foreach ($aTitleAndLayouts['layouts'] as $sLayout => $sContent) { + $this->aLogs[$oTemplateForPreview->sTemplateName][$sScreenName][$sLayout] = $sContent; + $sLayoutFile = $sLayout ; + $thissurvey['include_content'] = $sContent; + + $myoutput = Yii::app()->twigRenderer->renderTemplateForTemplateEditor( + $sLayoutFile, + array( + 'aSurveyInfo' => $thissurvey, + ), + $oTemplateForPreview + ); + } } - } } /** @@ -211,12 +211,12 @@ private function renderSurveyTheme($oTemplateForPreview) private function renderSurveyThemeManifest($oTemplateForPreview) { // So the twig string inside the theme manifest will be added to the .po file - $aTwigFromXml = $oTemplateForPreview->getTwigStrings(); + $aTwigFromXml = $oTemplateForPreview->getTwigStrings(); - foreach($aTwigFromXml as $sTwig){ - Yii::app()->twigRenderer->convertTwigToHtml($sTwig); - } + foreach ($aTwigFromXml as $sTwig) { + Yii::app()->twigRenderer->convertTwigToHtml($sTwig); + } - $this->aLogs[$oTemplateForPreview->sTemplateName]['manifest'] = "done"; + $this->aLogs[$oTemplateForPreview->sTemplateName]['manifest'] = "done"; } } diff --git a/application/commands/UpdateDbCommand.php b/application/commands/UpdateDbCommand.php index 42a86750021..32c311b7b36 100644 --- a/application/commands/UpdateDbCommand.php +++ b/application/commands/UpdateDbCommand.php @@ -6,7 +6,7 @@ * @version 0.1 * * Usage: application/commands/console.php updatedb - * + * * Copyright (C) 2017 LimeSurvey Team * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by @@ -37,8 +37,8 @@ public function run($args = null) } if ($newDbVersion > $currentDbVersion) { - echo "Update ".Yii::app()->db->connectionString." with prefix :"; - echo Yii::app()->db->tablePrefix." from {$currentDbVersion} to {$newDbVersion}\n"; + echo "Update " . Yii::app()->db->connectionString . " with prefix :"; + echo Yii::app()->db->tablePrefix . " from {$currentDbVersion} to {$newDbVersion}\n"; Yii::import('application.helpers.common_helper', true); Yii::import('application.helpers.update.updatedb_helper', true); $result = db_upgrade_all($currentDbVersion); diff --git a/application/commands/WipeCommand.php b/application/commands/WipeCommand.php index fc813f1ff70..5f18d66837f 100644 --- a/application/commands/WipeCommand.php +++ b/application/commands/WipeCommand.php @@ -1,4 +1,5 @@ db->createCommand("drop table ".$sv)->execute(); + Yii::app()->db->createCommand("drop table " . $sv)->execute(); } $surveyidresult = dbGetTablesLike("old\_%"); foreach ($surveyidresult as $sv) { - Yii::app()->db->createCommand("drop table ".$sv)->execute(); + Yii::app()->db->createCommand("drop table " . $sv)->execute(); } $surveyidresult = dbGetTablesLike("survey\_%"); foreach ($surveyidresult as $sv) { if (strpos($sv, 'survey_links') === false && strpos($sv, 'survey_url_parameters') === false) { - Yii::app()->db->createCommand("drop table ".$sv)->execute(); + Yii::app()->db->createCommand("drop table " . $sv)->execute(); } } - $sBaseUploadDir = dirname(dirname(dirname(__FILE__))).DIRECTORY_SEPARATOR.'upload'; + $sBaseUploadDir = dirname(dirname(dirname(__FILE__))) . DIRECTORY_SEPARATOR . 'upload'; - SureRemoveDir($sBaseUploadDir.DIRECTORY_SEPARATOR.'surveys', false); - SureRemoveDir($sBaseUploadDir.DIRECTORY_SEPARATOR.'templates', false); - SureRemoveDir($sBaseUploadDir.DIRECTORY_SEPARATOR.'themes'.DIRECTORY_SEPARATOR.'survey', false); - SureRemoveDir($sBaseUploadDir.DIRECTORY_SEPARATOR.'themes'.DIRECTORY_SEPARATOR.'question', false); + SureRemoveDir($sBaseUploadDir . DIRECTORY_SEPARATOR . 'surveys', false); + SureRemoveDir($sBaseUploadDir . DIRECTORY_SEPARATOR . 'templates', false); + SureRemoveDir($sBaseUploadDir . DIRECTORY_SEPARATOR . 'themes' . DIRECTORY_SEPARATOR . 'survey', false); + SureRemoveDir($sBaseUploadDir . DIRECTORY_SEPARATOR . 'themes' . DIRECTORY_SEPARATOR . 'question', false); } else { // TODO: a valid error process echo 'This CLI command wipes a LimeSurvey installation clean (including all user except for the user ID 1 and user-uploaded content). For security reasons this command can only started if you add the parameter \'yes\' to the command line.'; } - } - - } @@ -157,15 +154,14 @@ function SureRemoveDir($dir, $DeleteMe) if ($obj == '.' || $obj == '..') { continue; } - if (!@unlink($dir.'/'.$obj)) { - SureRemoveDir($dir.'/'.$obj, true); + if (!@unlink($dir . '/' . $obj)) { + SureRemoveDir($dir . '/' . $obj, true); } } closedir($dh); if ($DeleteMe) { if (!@rmdir($dir)) { - echo "Error: could not delete ".$dir; + echo "Error: could not delete " . $dir; } - } } diff --git a/application/commands/console.php b/application/commands/console.php index e58458cc3fc..38252252083 100644 --- a/application/commands/console.php +++ b/application/commands/console.php @@ -15,34 +15,34 @@ * File edited by Sam Mousa for Marcel Minke. * This loader bypasses the default Yii loader and loads a custom console class instead. */ - if (!isset($argv[0])) { - die(); - } +if (!isset($argv[0])) { + die(); +} define('BASEPATH', '.'); - require_once __DIR__.'/../../third_party/autoload.php'; - require_once(dirname(dirname(dirname(__FILE__))).DIRECTORY_SEPARATOR.'framework'.DIRECTORY_SEPARATOR.'yii.php'); + require_once __DIR__ . '/../../third_party/autoload.php'; + require_once(dirname(dirname(dirname(__FILE__))) . DIRECTORY_SEPARATOR . 'framework' . DIRECTORY_SEPARATOR . 'yii.php'); // Load configuration. $sCurrentDir = dirname(__FILE__); - $settings = require (dirname($sCurrentDir).DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'config-defaults.php'); - $config = require (dirname($sCurrentDir).DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'internal.php'); + $settings = require(dirname($sCurrentDir) . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'config-defaults.php'); + $config = require(dirname($sCurrentDir) . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'internal.php'); $config['components']['session']['class'] = 'ConsoleHttpSession'; $config['components']['session']['cookieMode'] = 'none'; $config['components']['session']['cookieParams'] = []; - $core = dirname($sCurrentDir).DIRECTORY_SEPARATOR.'core'.DIRECTORY_SEPARATOR; - if (isset($config['config'])) { - $settings = array_merge($settings, $config['config']); - } - unset ($config['defaultController']); - unset ($config['config']); + $core = dirname($sCurrentDir) . DIRECTORY_SEPARATOR . 'core' . DIRECTORY_SEPARATOR; +if (isset($config['config'])) { + $settings = array_merge($settings, $config['config']); +} + unset($config['defaultController']); + unset($config['config']); /* fix runtime path, unsure you can lauch function anywhere (if you use php /var/www/limesurvey/... : can be /root/ for config */ - if (!isset($config['runtimePath'])) { - $runtimePath = $settings['tempdir'].'/runtime'; - if (!is_dir($runtimePath) || !is_writable($runtimePath)) { - $runtimePath = str_replace($settings['rootdir'], dirname(dirname(dirname(__FILE__))), $runtimePath); - } - $config['runtimePath'] = $runtimePath; +if (!isset($config['runtimePath'])) { + $runtimePath = $settings['tempdir'] . '/runtime'; + if (!is_dir($runtimePath) || !is_writable($runtimePath)) { + $runtimePath = str_replace($settings['rootdir'], dirname(dirname(dirname(__FILE__))), $runtimePath); } + $config['runtimePath'] = $runtimePath; +} // fix for fcgi defined('STDIN') or define('STDIN', fopen('php://stdin', 'r')); @@ -51,15 +51,15 @@ /* specific for web */ unset($config['defaultController']); - if (isset($config)) { - require_once($core.'ConsoleApplication.php'); - $app = Yii::createApplication('ConsoleApplication', $config); - define('APPPATH', Yii::app()->getBasePath().DIRECTORY_SEPARATOR); - $app->commandRunner->addCommands(YII_PATH.'/cli/commands'); - $env = (string) @getenv('YII_CONSOLE_COMMANDS'); - if (!empty($env)) { - $app->commandRunner->addCommands($env); - } +if (isset($config)) { + require_once($core . 'ConsoleApplication.php'); + $app = Yii::createApplication('ConsoleApplication', $config); + define('APPPATH', Yii::app()->getBasePath() . DIRECTORY_SEPARATOR); + $app->commandRunner->addCommands(YII_PATH . '/cli/commands'); + $env = (string) @getenv('YII_CONSOLE_COMMANDS'); + if (!empty($env)) { + $app->commandRunner->addCommands($env); } +} $app->run(); ?> diff --git a/application/commands/starter.php b/application/commands/starter.php index 74f50daffe9..cbc7f256f9d 100644 --- a/application/commands/starter.php +++ b/application/commands/starter.php @@ -1,5 +1,5 @@ #!/usr/bin/php - \ No newline at end of file +?> diff --git a/application/controllers/AdminController.php b/application/controllers/AdminController.php index 877fde46a34..eb524b53311 100644 --- a/application/controllers/AdminController.php +++ b/application/controllers/AdminController.php @@ -1,4 +1,5 @@ user_id = Yii::app()->user->getId(); // Check if the user really exists // This scenario happens if the user was deleted while still being logged in - if ( !empty( $this->user_id ) && User::model()->findByPk( $this->user_id ) == null ){ + if (!empty($this->user_id) && User::model()->findByPk($this->user_id) == null) { $this->user_id = null; Yii::app()->session->destroy(); } - if (!Yii::app()->getConfig("surveyid")) {Yii::app()->setConfig("surveyid", returnGlobal('sid')); } //SurveyID - if (!Yii::app()->getConfig("surveyID")) {Yii::app()->setConfig("surveyID", returnGlobal('sid')); } //SurveyID - if (!Yii::app()->getConfig("ugid")) {Yii::app()->setConfig("ugid", returnGlobal('ugid')); } //Usergroup-ID - if (!Yii::app()->getConfig("gid")) {Yii::app()->setConfig("gid", returnGlobal('gid')); } //GroupID - if (!Yii::app()->getConfig("qid")) {Yii::app()->setConfig("qid", returnGlobal('qid')); } //QuestionID - if (!Yii::app()->getConfig("lid")) {Yii::app()->setConfig("lid", returnGlobal('lid')); } //LabelID - if (!Yii::app()->getConfig("code")) {Yii::app()->setConfig("code", returnGlobal('code')); } // ?? - if (!Yii::app()->getConfig("action")) {Yii::app()->setConfig("action", returnGlobal('action')); } //Desired action - if (!Yii::app()->getConfig("subaction")) {Yii::app()->setConfig("subaction", returnGlobal('subaction')); } //Desired subaction - if (!Yii::app()->getConfig("editedaction")) {Yii::app()->setConfig("editedaction", returnGlobal('editedaction')); } // for html editor integration + if (!Yii::app()->getConfig("surveyid")) { + Yii::app()->setConfig("surveyid", returnGlobal('sid')); + } //SurveyID + if (!Yii::app()->getConfig("surveyID")) { + Yii::app()->setConfig("surveyID", returnGlobal('sid')); + } //SurveyID + if (!Yii::app()->getConfig("ugid")) { + Yii::app()->setConfig("ugid", returnGlobal('ugid')); + } //Usergroup-ID + if (!Yii::app()->getConfig("gid")) { + Yii::app()->setConfig("gid", returnGlobal('gid')); + } //GroupID + if (!Yii::app()->getConfig("qid")) { + Yii::app()->setConfig("qid", returnGlobal('qid')); + } //QuestionID + if (!Yii::app()->getConfig("lid")) { + Yii::app()->setConfig("lid", returnGlobal('lid')); + } //LabelID + if (!Yii::app()->getConfig("code")) { + Yii::app()->setConfig("code", returnGlobal('code')); + } // ?? + if (!Yii::app()->getConfig("action")) { + Yii::app()->setConfig("action", returnGlobal('action')); + } //Desired action + if (!Yii::app()->getConfig("subaction")) { + Yii::app()->setConfig("subaction", returnGlobal('subaction')); + } //Desired subaction + if (!Yii::app()->getConfig("editedaction")) { + Yii::app()->setConfig("editedaction", returnGlobal('editedaction')); + } // for html editor integration // This line is needed for template editor to work $oAdminTheme = AdminTheme::getInstance(); - Yii::setPathOfAlias('lsadminmodules', Yii::app()->getConfig('lsadminmodulesrootdir') ); + Yii::setPathOfAlias('lsadminmodules', Yii::app()->getConfig('lsadminmodulesrootdir')); } /** @@ -74,8 +95,8 @@ public function error($message, $sURL = array()) { $this->_getAdminHeader(); $sOutput = "
'."\n"; - $sOutput .= ''."\n"; + $sOutput .= '".gT('Please confirm that you want to opt out of this survey by clicking the button below.').'
'.gT("After confirmation you won't receive any invitations or reminders for this survey anymore.")."
'; - $this->renderHtml($sMessage, $aSurveyInfo, $iSurveyID); - } + Yii::app()->setLanguage($sBaseLanguage); + $aSurveyInfo = getSurveyInfo($iSurveyID, $sBaseLanguage); + if ($aSurveyInfo == false || !tableExists("{{tokens_{$iSurveyID}}}")) { + throw new CHttpException(404, "The survey in which you are trying to participate does not seem to exist. It may have been deleted or the link you were given is outdated or incorrect."); + } else { + $sMessage = "
" . gT('Please confirm that you want to opt out of this survey by clicking the button below.') . '
' . gT("After confirmation you won't receive any invitations or reminders for this survey anymore.") . "
';
+ $this->renderHtml($sMessage, $aSurveyInfo, $iSurveyID);
}
+ }
/**
* This function is run when opting out of an individual survey participants table. The other function /optout/participants
@@ -103,7 +103,7 @@ function actionremovetokens()
throw new CHttpException(404, "The survey in which you are trying to participate does not seem to exist. It may have been deleted or the link you were given is outdated or incorrect.");
} else {
LimeExpressionManager::singleton()->loadTokenInformation($iSurveyID, $sToken, false);
- $oToken = Token::model($iSurveyID)->findByAttributes(array('token'=>$sToken));
+ $oToken = Token::model($iSurveyID)->findByAttributes(array('token' => $sToken));
if (!isset($oToken)) {
$sMessage = gT('You are not a participant in this survey.');
diff --git a/application/controllers/PluginsController.php b/application/controllers/PluginsController.php
index 08f615fc022..b91a07c73cb 100644
--- a/application/controllers/PluginsController.php
+++ b/application/controllers/PluginsController.php
@@ -65,5 +65,4 @@ public function actionIndex()
// Or shortcut for actionDirect ?
$this->redirect($this->createUrl("admin/pluginmanager/sa/index"));
}
-
}
diff --git a/application/controllers/PrintanswersController.php b/application/controllers/PrintanswersController.php
index 6a6d6020d1e..7bf661ad117 100644
--- a/application/controllers/PrintanswersController.php
+++ b/application/controllers/PrintanswersController.php
@@ -43,80 +43,79 @@ class PrintanswersController extends LSYii_Controller
* @param bool $printableexport
* @return
*/
- function actionView($surveyid, $printableexport = false)
- {
- Yii::app()->loadHelper("frontend");
- Yii::import('application.libraries.admin.pdf');
- $survey = Survey::model()->findByPk($surveyid);
- $iSurveyID = $survey->sid;
- $sExportType = $printableexport;
-
- Yii::app()->loadHelper('database');
-
- if (isset($_SESSION['survey_'.$iSurveyID]['sid'])) {
- $iSurveyID = $_SESSION['survey_'.$iSurveyID]['sid'];
- } else {
- //die('Invalid survey/session');
- }
- // Get the survey inforamtion
- // Set the language for dispay
- if (isset($_SESSION['survey_'.$iSurveyID]['s_lang'])) {
- $sLanguage = $_SESSION['survey_'.$iSurveyID]['s_lang'];
- } elseif ($survey) {
- // survey exist
+ function actionView($surveyid, $printableexport = false)
+ {
+ Yii::app()->loadHelper("frontend");
+ Yii::import('application.libraries.admin.pdf');
+ $survey = Survey::model()->findByPk($surveyid);
+ $iSurveyID = $survey->sid;
+ $sExportType = $printableexport;
+
+ Yii::app()->loadHelper('database');
+
+ if (isset($_SESSION['survey_' . $iSurveyID]['sid'])) {
+ $iSurveyID = $_SESSION['survey_' . $iSurveyID]['sid'];
+ } else {
+ //die('Invalid survey/session');
+ }
+ // Get the survey inforamtion
+ // Set the language for dispay
+ if (isset($_SESSION['survey_' . $iSurveyID]['s_lang'])) {
+ $sLanguage = $_SESSION['survey_' . $iSurveyID]['s_lang'];
+ } elseif ($survey) {
+ // survey exist
{
- $sLanguage = $survey->language;
- }
- } else {
- $iSurveyID = 0;
- $sLanguage = Yii::app()->getConfig("defaultlang");
- }
- SetSurveyLanguage($iSurveyID, $sLanguage);
- Yii::import('application.helpers.SurveyRuntimeHelper');
- $SurveyRuntimeHelper = new SurveyRuntimeHelper();
- $SurveyRuntimeHelper->setJavascriptVar($iSurveyID);
- $aSurveyInfo = getSurveyInfo($iSurveyID, $sLanguage);
- $oTemplate = Template::model()->getInstance(null, $iSurveyID);
- /* Need a Template function to replace this line */
- //Yii::app()->clientScript->registerPackage( 'survey-template' );
-
- //Survey is not finished or don't exist
- if (!isset($_SESSION['survey_'.$iSurveyID]['srid'])) {
-
- //display "sorry but your session has expired"
- $this->sTemplate = $oTemplate->sTemplateName;
- $error = $this->renderPartial("/survey/system/errorWarning", array(
- 'aErrors'=>array(
- gT("We are sorry but your session has expired."),
- ),
- ), true);
- $message = $this->renderPartial("/survey/system/message", array(
- 'aMessage'=>array(
- gT("Either you have been inactive for too long, you have cookies disabled for your browser, or there were problems with your connection."),
- ),
- ), true);
- /* Set the data for templatereplace */
- $aReplacementData['title'] = 'session-timeout';
- $aReplacementData['message'] = $error."
".$message;
-
- $aData = array();
- $aData['aSurveyInfo'] = getSurveyInfo($iSurveyID);
- $aData['aError'] = $aReplacementData;
-
- Yii::app()->twigRenderer->renderTemplateFromFile('layout_errors.twig', $aData, false);
- // $content=templatereplace(file_get_contents($oTemplate->pstplPath."message.pstpl"),$aReplacementData,$this->aGlobalData);
- // $this->render("/survey/system/display",array('content'=>$content));
- // App()->end();
- }
- //Fin session time out
- $sSRID = $_SESSION['survey_'.$iSurveyID]['srid']; //I want to see the answers with this id
- //Ensure script is not run directly, avoid path disclosure
- //if (!isset($rootdir) || isset($_REQUEST['$rootdir'])) {die( "browse - Cannot run this script directly");}
-
- //Ensure Participants printAnswer setting is set to true or that the logged user have read permissions over the responses.
- if ($aSurveyInfo['printanswers'] == 'N' && !Permission::model()->hasSurveyPermission($iSurveyID, 'responses', 'read')) {
- throw new CHttpException(401, gT('You are not allowed to print answers.'));
+ $sLanguage = $survey->language;
}
+ } else {
+ $iSurveyID = 0;
+ $sLanguage = Yii::app()->getConfig("defaultlang");
+ }
+ SetSurveyLanguage($iSurveyID, $sLanguage);
+ Yii::import('application.helpers.SurveyRuntimeHelper');
+ $SurveyRuntimeHelper = new SurveyRuntimeHelper();
+ $SurveyRuntimeHelper->setJavascriptVar($iSurveyID);
+ $aSurveyInfo = getSurveyInfo($iSurveyID, $sLanguage);
+ $oTemplate = Template::model()->getInstance(null, $iSurveyID);
+ /* Need a Template function to replace this line */
+ //Yii::app()->clientScript->registerPackage( 'survey-template' );
+
+ //Survey is not finished or don't exist
+ if (!isset($_SESSION['survey_' . $iSurveyID]['srid'])) {
+ //display "sorry but your session has expired"
+ $this->sTemplate = $oTemplate->sTemplateName;
+ $error = $this->renderPartial("/survey/system/errorWarning", array(
+ 'aErrors' => array(
+ gT("We are sorry but your session has expired."),
+ ),
+ ), true);
+ $message = $this->renderPartial("/survey/system/message", array(
+ 'aMessage' => array(
+ gT("Either you have been inactive for too long, you have cookies disabled for your browser, or there were problems with your connection."),
+ ),
+ ), true);
+ /* Set the data for templatereplace */
+ $aReplacementData['title'] = 'session-timeout';
+ $aReplacementData['message'] = $error . "
" . $message;
+
+ $aData = array();
+ $aData['aSurveyInfo'] = getSurveyInfo($iSurveyID);
+ $aData['aError'] = $aReplacementData;
+
+ Yii::app()->twigRenderer->renderTemplateFromFile('layout_errors.twig', $aData, false);
+ // $content=templatereplace(file_get_contents($oTemplate->pstplPath."message.pstpl"),$aReplacementData,$this->aGlobalData);
+ // $this->render("/survey/system/display",array('content'=>$content));
+ // App()->end();
+ }
+ //Fin session time out
+ $sSRID = $_SESSION['survey_' . $iSurveyID]['srid']; //I want to see the answers with this id
+ //Ensure script is not run directly, avoid path disclosure
+ //if (!isset($rootdir) || isset($_REQUEST['$rootdir'])) {die( "browse - Cannot run this script directly");}
+
+ //Ensure Participants printAnswer setting is set to true or that the logged user have read permissions over the responses.
+ if ($aSurveyInfo['printanswers'] == 'N' && !Permission::model()->hasSurveyPermission($iSurveyID, 'responses', 'read')) {
+ throw new CHttpException(401, gT('You are not allowed to print answers.'));
+ }
//CHECK IF SURVEY IS ACTIVATED AND EXISTS
$sSurveyName = $aSurveyInfo['surveyls_title'];
@@ -139,17 +138,16 @@ function actionView($surveyid, $printableexport = false)
$aData['aSurveyInfo'] = $aSurveyInfo;
$aData['aSurveyInfo']['dateFormat'] = getDateFormatData(Yii::app()->session['dateformat']);
$aData['aSurveyInfo']['groupArray'] = $groupArray;
- $aData['aSurveyInfo']['printAnswersHeadFormUrl'] = Yii::App()->getController()->createUrl('printanswers/view/', array('surveyid'=>$iSurveyID, 'printableexport'=>'pdf'));
- $aData['aSurveyInfo']['printAnswersHeadFormQueXMLUrl'] = Yii::App()->getController()->createUrl('printanswers/view/', array('surveyid'=>$iSurveyID, 'printableexport'=>'quexmlpdf'));
+ $aData['aSurveyInfo']['printAnswersHeadFormUrl'] = Yii::App()->getController()->createUrl('printanswers/view/', array('surveyid' => $iSurveyID, 'printableexport' => 'pdf'));
+ $aData['aSurveyInfo']['printAnswersHeadFormQueXMLUrl'] = Yii::App()->getController()->createUrl('printanswers/view/', array('surveyid' => $iSurveyID, 'printableexport' => 'quexmlpdf'));
if (empty($sExportType)) {
Yii::app()->setLanguage($sLanguage);
$aData['aSurveyInfo']['include_content'] = 'printanswers';
Yii::app()->twigRenderer->renderTemplateFromFile('layout_printanswers.twig', $aData, false);
-
- } else if ($sExportType == 'pdf') {
+ } elseif ($sExportType == 'pdf') {
// Get images for TCPDF from template directory
- define('K_PATH_IMAGES', Template::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');
@@ -158,7 +156,7 @@ function actionView($surveyid, $printableexport = false)
$oPDF = new pdf();
$oPDF->setCellMargins(1, 1, 1, 1);
$oPDF->setCellPaddings(1, 1, 1, 1);
- $sDefaultHeaderString = $sSurveyName." (".gT("ID", 'unescaped').":".$iSurveyID.")";
+ $sDefaultHeaderString = $sSurveyName . " (" . gT("ID", 'unescaped') . ":" . $iSurveyID . ")";
$oPDF->initAnswerPDF($aSurveyInfo, $aPdfLanguageSettings, Yii::app()->getConfig('sitename'), $sSurveyName, $sDefaultHeaderString);
LimeExpressionManager::StartProcessingPage(true); // means that all variables are on the same page
// Since all data are loaded, and don't need JavaScript, pretend all from Group 1
@@ -183,11 +181,10 @@ function actionView($surveyid, $printableexport = false)
header("Cache-Control: must-revalidate, no-store, no-cache"); // Don't store in cache because it is sensitive data
$sExportFileName = sanitize_filename($sSurveyName);
- $oPDF->Output($sExportFileName."-".$iSurveyID.".pdf", "D");
+ $oPDF->Output($sExportFileName . "-" . $iSurveyID . ".pdf", "D");
LimeExpressionManager::FinishProcessingGroup();
LimeExpressionManager::FinishProcessingPage();
- } else if ($sExportType == 'quexmlpdf') {
-
+ } elseif ($sExportType == 'quexmlpdf') {
Yii::import("application.libraries.admin.quexmlpdf", true);
$quexmlpdf = new quexmlpdf();
@@ -206,7 +203,7 @@ function actionView($surveyid, $printableexport = false)
$quexmlpdf->create($quexmlpdf->createqueXML($quexml));
$sExportFileName = sanitize_filename($sSurveyName);
- $quexmlpdf->Output($sExportFileName."-".$iSurveyID."-queXML.pdf", 'D');
+ $quexmlpdf->Output($sExportFileName . "-" . $iSurveyID . "-queXML.pdf", 'D');
}
}
}
diff --git a/application/controllers/QuestionAdministrationController.php b/application/controllers/QuestionAdministrationController.php
index ad6b317a297..a942accbd60 100644
--- a/application/controllers/QuestionAdministrationController.php
+++ b/application/controllers/QuestionAdministrationController.php
@@ -31,7 +31,7 @@ public function accessRules()
* This part comes from _renderWrappedTemplate
*
* @param string $view View
- *
+ *
* @return bool
*/
protected function beforeRender($view)
@@ -170,7 +170,7 @@ public function renderFormAux(Question $question)
App()->session['FileManagerContext'] = "edit:survey:{$question->sid}";
initKcfinder();
- $questionTemplate = 'core';
+ $questionTemplate = 'core';
if ($question->qid !== 0) {
$questionTemplate = QuestionAttribute::getQuestionTemplateValue($question->qid);
}
@@ -288,8 +288,8 @@ public function actionListQuestions($surveyid, $landOnSideMenuTab = 'settings')
$aData["surveyHasGroup"] = $oSurvey->groups;
$aData['subaction'] = gT("Questions in this survey");
- $aData['title_bar']['title'] = $oSurvey->currentLanguageSettings->surveyls_title.
- " (".gT("ID").":".$iSurveyID.")";
+ $aData['title_bar']['title'] = $oSurvey->currentLanguageSettings->surveyls_title .
+ " (" . gT("ID") . ":" . $iSurveyID . ")";
// The DataProvider will be build from the Question model, search method
$model = new Question('search');
@@ -404,14 +404,18 @@ public function actionSaveQuestionData()
);
// save advanced attributes default values for given question type
- if (array_key_exists('save_as_default', $questionData['question'])
- && $questionData['question']['save_as_default'] == 'Y') {
+ if (
+ array_key_exists('save_as_default', $questionData['question'])
+ && $questionData['question']['save_as_default'] == 'Y'
+ ) {
SettingsUser::setUserSetting(
'question_default_values_' . $questionData['question']['type'],
ls_json_encode($questionData['advancedSettings'])
);
- } elseif (array_key_exists('clear_default', $questionData['question'])
- && $questionData['question']['clear_default'] == 'Y') {
+ } elseif (
+ array_key_exists('clear_default', $questionData['question'])
+ && $questionData['question']['clear_default'] == 'Y'
+ ) {
SettingsUser::deleteUserSetting('question_default_values_' . $questionData['question']['type']);
}
@@ -444,7 +448,7 @@ public function actionSaveQuestionData()
$question->refresh();
$tabOverviewEditorValue = $request->getPost('tabOverviewEditor');
//only those two values are valid
- if(!($tabOverviewEditorValue==='overview' || $tabOverviewEditorValue==='editor')){
+ if (!($tabOverviewEditorValue === 'overview' || $tabOverviewEditorValue === 'editor')) {
$tabOverviewEditorValue = 'overview';
}
@@ -1049,14 +1053,14 @@ public function actionImport()
if ($_FILES['the_file']['error'] == 1 || $_FILES['the_file']['error'] == 2) {
$fatalerror = sprintf(
- gT("Sorry, this file is too large. Only files up to %01.2f MB are allowed."),
- getMaximumFileUploadSize() / 1024 / 1024
- ) . '
';
+ gT("Sorry, this file is too large. Only files up to %01.2f MB are allowed."),
+ getMaximumFileUploadSize() / 1024 / 1024
+ ) . '
';
} elseif (!@move_uploaded_file($_FILES['the_file']['tmp_name'], $sFullFilepath)) {
$fatalerror = gT(
- "An error occurred uploading your file."
+ "An error occurred uploading your file."
. " This may be caused by incorrect permissions for the application /tmp folder."
- ) . '
';
+ ) . '
';
}
// validate that we have a SID and GID
@@ -1179,10 +1183,14 @@ public function actionEditdefaultvalues($surveyid, $gid, $qid)
];
$aData['title_bar']['title'] = $oSurvey->currentLanguageSettings->surveyls_title . " (" . gT("ID") . ":" . $iSurveyID . ")";
$aData['questiongroupbar']['savebutton']['form'] = 'frmeditgroup';
- $this->createUrl("questionAdministration/view",
- ["surveyid" => $iSurveyID , "gid" => $gid , "qid" => $qid]);
- $aData['questiongroupbar']['closebutton']['url'] = $this->createUrl("questionAdministration/view",
- ["surveyid" => $iSurveyID , "gid" => $gid , "qid" => $qid]);
+ $this->createUrl(
+ "questionAdministration/view",
+ ["surveyid" => $iSurveyID , "gid" => $gid , "qid" => $qid]
+ );
+ $aData['questiongroupbar']['closebutton']['url'] = $this->createUrl(
+ "questionAdministration/view",
+ ["surveyid" => $iSurveyID , "gid" => $gid , "qid" => $qid]
+ );
$aData['questiongroupbar']['saveandclosebutton']['form'] = 'frmeditgroup';
$aData['display']['menu_bars']['surveysummary'] = 'editdefaultvalues';
$aData['display']['menu_bars']['qid_action'] = 'editdefaultvalues';
@@ -1281,27 +1289,27 @@ public function actionDelete($qid = null, $massAction = false, $redirectTo = nul
throw new CHttpException(405, gT("Invalid action"));
}
- if (empty($redirectTo)) {
- $redirectTo = Yii::app()->getRequest()->getPost('redirectTo', 'questionlist');
- }
- if ($redirectTo == 'groupoverview') {
- $redirect = Yii::app()->createUrl(
- 'questionGroupsAdministration/view/',
- [
- 'surveyid' => $surveyid,
- 'gid' => $oQuestion->gid,
- 'landOnSideMenuTab' => 'structure'
- ]
- );
- } else {
- $redirect = Yii::app()->createUrl(
- 'questionAdministration/listQuestions/',
- [
- 'surveyid' => $surveyid,
- 'landOnSideMenuTab' => 'settings'
- ]
- );
- }
+ if (empty($redirectTo)) {
+ $redirectTo = Yii::app()->getRequest()->getPost('redirectTo', 'questionlist');
+ }
+ if ($redirectTo == 'groupoverview') {
+ $redirect = Yii::app()->createUrl(
+ 'questionGroupsAdministration/view/',
+ [
+ 'surveyid' => $surveyid,
+ 'gid' => $oQuestion->gid,
+ 'landOnSideMenuTab' => 'structure'
+ ]
+ );
+ } else {
+ $redirect = Yii::app()->createUrl(
+ 'questionAdministration/listQuestions/',
+ [
+ 'surveyid' => $surveyid,
+ 'landOnSideMenuTab' => 'settings'
+ ]
+ );
+ }
LimeExpressionManager::RevertUpgradeConditionsToRelevance(null, $qid);
@@ -1423,9 +1431,11 @@ public function actionChangeMultipleQuestionAttributes()
*/
public function actionAjaxLoadPositionWidget($gid, $classes = '')
{
- $oQuestionGroup = QuestionGroup::model()->find('gid=:gid', [':gid' =>$gid]);
- if (is_a($oQuestionGroup, 'QuestionGroup') &&
- Permission::model()->hasSurveyPermission($oQuestionGroup->sid, 'surveycontent', 'read')) {
+ $oQuestionGroup = QuestionGroup::model()->find('gid=:gid', [':gid' => $gid]);
+ if (
+ is_a($oQuestionGroup, 'QuestionGroup') &&
+ Permission::model()->hasSurveyPermission($oQuestionGroup->sid, 'surveycontent', 'read')
+ ) {
$aOptions = [
'display' => 'form_group',
'oQuestionGroup' => $oQuestionGroup,
@@ -1592,7 +1602,8 @@ public function actionCopyQuestion()
if (!empty($oldQuestion)) {
Yii::app()->user->setFlash('error', gT("Duplicate question code"));
$this->redirect(
- $this->createUrl('surveyAdministration/view/',
+ $this->createUrl(
+ 'surveyAdministration/view/',
[
'surveyid' => $surveyId,
]
@@ -1606,14 +1617,14 @@ public function actionCopyQuestion()
$copyQuestionValues->setQuestionGroupId((int)Yii::app()->request->getParam('gid'));
$copyQuestionValues->setQuestiontoCopy($oQuestion);
$questionPosition = Yii::app()->request->getParam('questionposition');
- if ($questionPosition==='') { //this means "at the end"
+ if ($questionPosition === '') { //this means "at the end"
$questionPosition = -1; //integer indicator for "end"
}
//first ensure that all questions for the group have a question_order>0 and possibly set to this state
Question::setQuestionOrderForGroup($questionGroupId);
switch ((int)$questionPosition) {
case -1: //at the end
- $newQuestionPosition = Question::getHighestQuestionOrderNumberInGroup($questionGroupId) +1;
+ $newQuestionPosition = Question::getHighestQuestionOrderNumberInGroup($questionGroupId) + 1;
break;
case 0: //at beginning
//set all existing order numbers to +1, and the copied question to order number 1
@@ -1634,7 +1645,8 @@ public function actionCopyQuestion()
App()->user->setFlash('success', gT("Saved copied question"));
$newQuestion = $copyQuestionService->getNewCopiedQuestion();
$this->redirect(
- $this->createUrl('questionAdministration/view/',
+ $this->createUrl(
+ 'questionAdministration/view/',
array(
'surveyid' => $surveyId,
'gid' => $newQuestion->gid,
@@ -1707,18 +1719,20 @@ public function actionGetLabelsetDetails($lid)
$result = [];
$languages = [];
- if($labelSet !== null) {
+ if ($labelSet !== null) {
$usedLanguages = explode(' ', $labelSet->languages);
foreach ($usedLanguages as $sLanguage) {
$result[$sLanguage] = array_map(
- function($attribute) { return \viewHelper::flatten($attribute); },
+ function ($attribute) {
+ return \viewHelper::flatten($attribute);
+ },
$labelSet->attributes
);
foreach ($labelSet->labels as $oLabel) {
$result[$sLanguage]['labels'][] = $oLabel->getTranslated($sLanguage);
};
- $languages[$sLanguage] = getLanguageNameFromCode($sLanguage,false);
+ $languages[$sLanguage] = getLanguageNameFromCode($sLanguage, false);
};
}
@@ -1747,12 +1761,12 @@ function($attribute) { return \viewHelper::flatten($attribute); },
*/
public function actionGetLabelsetPicker($sid, $match = 0)
{
- $criteria = new CDbCriteria;
+ $criteria = new CDbCriteria();
// TODO: Always null
$language = null;
if ($match === 1) {
$criteria->addCondition('languages LIKE :language');
- $criteria->params = [':language' => '%'.$language.'%'];
+ $criteria->params = [':language' => '%' . $language . '%'];
}
$labelSets = LabelSet::model()->findAll($criteria);
@@ -1760,7 +1774,9 @@ public function actionGetLabelsetPicker($sid, $match = 0)
$result = [];
foreach ($labelSets as $labelSet) {
$result[] = array_map(
- function($attribute) { return \viewHelper::flatten($attribute); },
+ function ($attribute) {
+ return \viewHelper::flatten($attribute);
+ },
$labelSet->attributes
);
}
@@ -1793,14 +1809,14 @@ public function actionCheckLabel($lid, $languages, $checkAssessments)
$labelSetLangauges = explode(' ', $labelSet->languages);
$errorMessages = [];
if ($checkAssessments && $label) {
- $errorMessages[] = gT('The existing label set has assessment values assigned.').''.gT('If you replace the label set the existing asssessment values will be lost.').'';
+ $errorMessages[] = gT('The existing label set has assessment values assigned.') . '' . gT('If you replace the label set the existing asssessment values will be lost.') . '';
}
if (count(array_diff($labelSetLangauges, $languages))) {
- $errorMessages[] = gT('The existing label set has different/more languages.').''.gT('If you replace the label set these translations will be lost.').'';
+ $errorMessages[] = gT('The existing label set has different/more languages.') . '' . gT('If you replace the label set these translations will be lost.') . '';
}
if (count($errorMessages)) {
foreach ($errorMessages as $errorMessage) {
- echo $errorMessage.'
';
+ echo $errorMessage . '
';
}
eT('Do you really want to continue?');
} else {
@@ -1825,12 +1841,13 @@ public function actionCheckLabel($lid, $languages, $checkAssessments)
*
* @todo While refactoring (at some point) this function should be removed and only one unique identifier should be used
*/
- private function getSurveyIdFromGetRequest(){
+ private function getSurveyIdFromGetRequest()
+ {
$surveyId = Yii::app()->request->getParam('sid');
- if($surveyId === null){
+ if ($surveyId === null) {
$surveyId = Yii::app()->request->getParam('surveyid');
}
- if($surveyId === null){
+ if ($surveyId === null) {
$surveyId = Yii::app()->request->getParam('iSurveyID');
}
@@ -1862,10 +1879,12 @@ public static function setMultipleQuestionOtherState($aQids, $sOther, $iSid)
$iQid = (int)$sQid;
$oQuestion = Question::model()->findByPk(["qid" => $iQid], ['sid=:sid'], [':sid' => $iSid]);
// Only set the other state for question types that have this attribute
- if (($oQuestion->type == Question::QT_L_LIST_DROPDOWN)
+ if (
+ ($oQuestion->type == Question::QT_L_LIST_DROPDOWN)
|| ($oQuestion->type == Question::QT_EXCLAMATION_LIST_DROPDOWN)
|| ($oQuestion->type == Question::QT_P_MULTIPLE_CHOICE_WITH_COMMENTS)
- || ($oQuestion->type == Question::QT_M_MULTIPLE_CHOICE)) {
+ || ($oQuestion->type == Question::QT_M_MULTIPLE_CHOICE)
+ ) {
$oQuestion->other = $sOther;
$oQuestion->save();
}
@@ -2024,8 +2043,10 @@ public static function getDefaultValues(int $iSurveyID, int $gid, int $qid)
}
// If there are subquestions and no answerscales
- if ($aQuestionTypeMetadata[$aQuestionAttributes['type']]['answerscales'] == 0 &&
- $aQuestionTypeMetadata[$aQuestionAttributes['type']]['subquestions'] > 0) {
+ if (
+ $aQuestionTypeMetadata[$aQuestionAttributes['type']]['answerscales'] == 0 &&
+ $aQuestionTypeMetadata[$aQuestionAttributes['type']]['subquestions'] > 0
+ ) {
for ($scale_id = 0; $scale_id < $aQuestionTypeMetadata[$aQuestionAttributes['type']]['subquestions']; $scale_id++) {
$aDefaultValues[$language][$aQuestionAttributes['type']][$scale_id] = [];
@@ -2077,8 +2098,10 @@ public static function getDefaultValues(int $iSurveyID, int $gid, int $qid)
}
}
}
- if ($aQuestionTypeMetadata[$aQuestionAttributes['type']]['answerscales'] == 0 &&
- $aQuestionTypeMetadata[$aQuestionAttributes['type']]['subquestions'] == 0) {
+ if (
+ $aQuestionTypeMetadata[$aQuestionAttributes['type']]['answerscales'] == 0 &&
+ $aQuestionTypeMetadata[$aQuestionAttributes['type']]['subquestions'] == 0
+ ) {
$defaultvalue = DefaultValue::model()
->with('defaultvaluel10ns')
->find(
@@ -2349,7 +2372,7 @@ private function storeNewQuestionData($aQuestionData = null, $subquestion = fals
if ($highestOrderNumber === null) { //this means there is no question inside this group ...
$oQuestion->question_order = Question::START_SORTING_VALUE;
} else {
- $oQuestion->question_order = $highestOrderNumber +1;
+ $oQuestion->question_order = $highestOrderNumber + 1;
}
@@ -2488,11 +2511,13 @@ private function unparseAndSetGeneralOptions($oQuestion, $dataSet)
}
if (array_key_exists($sAttributeKey, $aQuestionBaseAttributes)) {
$oQuestion->$sAttributeKey = $attributeValue;
- } elseif (!QuestionAttribute::model()->setQuestionAttribute(
- $oQuestion->qid,
- $sAttributeKey,
- $attributeValue
- )) {
+ } elseif (
+ !QuestionAttribute::model()->setQuestionAttribute(
+ $oQuestion->qid,
+ $sAttributeKey,
+ $attributeValue
+ )
+ ) {
throw new CHttpException(500, gT("Could not store general options"));
}
}
@@ -2529,8 +2554,10 @@ private function unparseAndSetAdvancedOptions($oQuestion, $dataSet)
// Set default value if empty.
// TODO: Default value
- if ($newValue === ""
- && isset($attributeValue['aFormElementOptions']['default'])) {
+ if (
+ $newValue === ""
+ && isset($attributeValue['aFormElementOptions']['default'])
+ ) {
$newValue = $attributeValue['aFormElementOptions']['default'];
}
@@ -2539,22 +2566,26 @@ private function unparseAndSetAdvancedOptions($oQuestion, $dataSet)
if ($lngKey === 'expression') {
continue;
}
- if (!QuestionAttribute::model()->setQuestionAttributeWithLanguage(
- $oQuestion->qid,
- $sAttributeKey,
- $content,
- $lngKey
- )) {
+ if (
+ !QuestionAttribute::model()->setQuestionAttributeWithLanguage(
+ $oQuestion->qid,
+ $sAttributeKey,
+ $content,
+ $lngKey
+ )
+ ) {
throw new CHttpException(500, gT("Could not store advanced options"));
}
}
} elseif (array_key_exists($sAttributeKey, $aQuestionBaseAttributes)) {
$oQuestion->$sAttributeKey = $newValue;
- } elseif (!QuestionAttribute::model()->setQuestionAttribute(
- $oQuestion->qid,
- $sAttributeKey,
- $newValue
- )) {
+ } elseif (
+ !QuestionAttribute::model()->setQuestionAttribute(
+ $oQuestion->qid,
+ $sAttributeKey,
+ $newValue
+ )
+ ) {
throw new CHttpException(500, gT("Could not store advanced options"));
}
}
@@ -2824,7 +2855,8 @@ function ($oAnsweroption) use (&$dataSet) {
$exists = false;
foreach ($dataSet as $scaleId => $aAnsweroptions) {
foreach ($aAnsweroptions as $i => $aAnsweroptionDataSet) {
- if (((is_numeric($aAnsweroptionDataSet['aid'])
+ if (
+ ((is_numeric($aAnsweroptionDataSet['aid'])
&& $oAnsweroption->aid == $aAnsweroptionDataSet['aid'])
|| $oAnsweroption->code == $aAnsweroptionDataSet['code'])
&& ($oAnsweroption->scale_id == $scaleId)
diff --git a/application/controllers/QuestionGroupsAdministrationController.php b/application/controllers/QuestionGroupsAdministrationController.php
index d7442200856..83cc144e58e 100644
--- a/application/controllers/QuestionGroupsAdministrationController.php
+++ b/application/controllers/QuestionGroupsAdministrationController.php
@@ -46,7 +46,7 @@ public function accessRules()
protected function beforeRender($view)
{
// Set topbar type if not already set
- if(!isset($this->aData['topBar'])||!isset($this->aData['topBar']['type'])) {
+ if (!isset($this->aData['topBar']) || !isset($this->aData['topBar']['type'])) {
$this->aData['topBar']['type'] = 'group';
}
if (empty($this->aData['topBar']['showCloseButton'])) {
@@ -99,7 +99,7 @@ public function actionView($surveyid, $gid, $landOnSideMenuTab = 'structure')
$aData['oSurvey'] = $survey;
$aData['gid'] = $gid;
$baselang = $survey->language;
- if ($gid!==null) {
+ if ($gid !== null) {
$condarray = getGroupDepsForConditions($surveyid, "all", $gid, "by-targgid");
}
$aData['condarray'] = $condarray;
@@ -117,7 +117,7 @@ public function actionView($surveyid, $gid, $landOnSideMenuTab = 'structure')
$aData['grow'] = $grow;
$aData['title_bar']['title'] = $survey->currentLanguageSettings->surveyls_title
- . " (".gT("ID").":".$iSurveyID.")";
+ . " (" . gT("ID") . ":" . $iSurveyID . ")";
$aData['topBar']['name'] = 'baseTopbar_view';
$aData['topBar']['leftSideView'] = 'groupTopbarLeft_view';
@@ -172,25 +172,25 @@ public function actionEdit($surveyid, $gid, $landOnSideMenuTab = 'structure')
/**
* TODO: check integrity of the group languages?
- *
+ *
* In LS3, group languages are checked here to make sure they match the survey languages:
* If language exists in group but not in survey, remove from group.
* If language exists in survey but not in group, create based on survey's base language.
- *
+ *
* Reference: https://github.com/LimeSurvey/LimeSurvey/blob/85cc864e2624b5c9c6daecce3c75af3c8701a237/application/controllers/admin/questiongroups.php#L349
- *
+ *
* It doesn't seem necessary here. And, if it's needed, it probably better in the Model.
- *
+ *
*/
// Load question group data for each language
foreach ($aLanguages as $sLanguage) {
- if(isset($oQuestionGroup->questiongroupl10ns[$sLanguage])) {
+ if (isset($oQuestionGroup->questiongroupl10ns[$sLanguage])) {
$aGroupData = $oQuestionGroup->questiongroupl10ns[$sLanguage];
$aData['aGroupData'][$sLanguage] = $aGroupData->attributes;
$aTabTitles[$sLanguage] = getLanguageNameFromCode($sLanguage, false);
if ($sLanguage == $sBaseLanguage) {
- $aTabTitles[$sLanguage] .= ' ('.gT("Base language").')';
+ $aTabTitles[$sLanguage] .= ' (' . gT("Base language") . ')';
}
}
}
@@ -200,13 +200,13 @@ public function actionEdit($surveyid, $gid, $landOnSideMenuTab = 'structure')
$aData['tabtitles'] = $aTabTitles;
$aData['action'] = $aData['display']['menu_bars']['gid_action'] = 'editgroup';
$aData['oSurvey'] = $oSurvey;
- if ($gid!==null) {
+ if ($gid !== null) {
$condarray = getGroupDepsForConditions($surveyid, "all", $gid, "by-targgid");
}
$aData['condarray'] = $condarray;
$aData['title_bar']['title'] = $oSurvey->currentLanguageSettings->surveyls_title
- . " (".gT("ID").":".$surveyid.")";
+ . " (" . gT("ID") . ":" . $surveyid . ")";
$aData['closeBtnUrl'] = $this->createUrl(
'questionGroupsAdministration/view',
@@ -235,7 +235,6 @@ public function actionEdit($surveyid, $gid, $landOnSideMenuTab = 'structure')
$this->aData = $aData;
$this->render('editGroup_view', $this->aData);
-
}
/**
@@ -267,7 +266,7 @@ public function actionAdd($surveyid, $landOnSideMenuTab = 'structure')
$aSurveyLanguages[] = $sBaseLanguage;
$aSurveyLanguages = array_reverse($aSurveyLanguages);
- App()->getClientScript()->registerScriptFile(App()->getConfig('adminscripts').'questiongroup.js');
+ App()->getClientScript()->registerScriptFile(App()->getConfig('adminscripts') . 'questiongroup.js');
//$aData['display']['menu_bars']['surveysummary'] = 'addgroup';
$aData['action'] = $aData['display']['menu_bars']['gid_action'] = 'addgroup';
@@ -276,7 +275,7 @@ public function actionAdd($surveyid, $landOnSideMenuTab = 'structure')
$aData['baselang'] = $sBaseLanguage;
$aData['title_bar']['title'] = $oSurvey->currentLanguageSettings->surveyls_title
- . " (".gT("ID").":".$surveyid.")";
+ . " (" . gT("ID") . ":" . $surveyid . ")";
$aData['closeBtnUrl'] = $this->createUrl(
'questionGroupsAdministration/listquestiongroups',
[
@@ -297,7 +296,6 @@ public function actionAdd($surveyid, $landOnSideMenuTab = 'structure')
$this->aData = $aData;
$this->render('addGroup_view', $this->aData);
-
}
/**
@@ -337,7 +335,7 @@ public function actionListquestiongroups($surveyid)
$aData['sidemenu']['questiongroups'] = true;
$aData['sidemenu']['listquestiongroups'] = true;
$aData['title_bar']['title'] =
- $survey->currentLanguageSettings->surveyls_title." (".gT("ID").":".$iSurveyID.")";
+ $survey->currentLanguageSettings->surveyls_title . " (" . gT("ID") . ":" . $iSurveyID . ")";
$aData['subaction'] = gT("Question groups in this survey");
$baselang = $survey->language;
@@ -381,14 +379,14 @@ public function actionImport()
if (!Permission::model()->hasSurveyPermission($surveyid, 'surveycontent', 'import')) {
App()->user->setFlash('error', gT("Access denied"));
- $this->redirect(array('questionGroupsAdministration/listquestiongroups/surveyid/'.$surveyid));
+ $this->redirect(array('questionGroupsAdministration/listquestiongroups/surveyid/' . $surveyid));
}
if ($action == 'importgroup') {
$importgroup = "\n";
$importgroup .= "\n";
- $sFullFilepath = App()->getConfig('tempdir').DIRECTORY_SEPARATOR.randomChars(20);
+ $sFullFilepath = App()->getConfig('tempdir') . DIRECTORY_SEPARATOR . randomChars(20);
$aPathInfo = pathinfo($_FILES['the_file']['name']);
$sExtension = $aPathInfo['extension'];
@@ -397,7 +395,7 @@ public function actionImport()
gT("Sorry, this file is too large. Only files up to %01.2f MB are allowed."),
getMaximumFileUploadSize() / 1024 / 1024
)
- .'
';
+ . '
';
} elseif (!@move_uploaded_file($_FILES['the_file']['tmp_name'], $sFullFilepath)) {
$fatalerror = gT(
"An error occurred uploading your file.
@@ -413,7 +411,7 @@ public function actionImport()
if (isset($fatalerror)) {
@unlink($sFullFilepath);
App()->user->setFlash('error', $fatalerror);
- $this->redirect(array('questionGroupsAdministration/importview/surveyid/'.$surveyid));
+ $this->redirect(array('questionGroupsAdministration/importview/surveyid/' . $surveyid));
}
App()->loadHelper('admin/import');
@@ -427,7 +425,7 @@ public function actionImport()
);
} else {
App()->user->setFlash('error', gT("Unknown file extension"));
- $this->redirect(array('questionGroupsAdministration/importview/surveyid/'.$surveyid));
+ $this->redirect(array('questionGroupsAdministration/importview/surveyid/' . $surveyid));
}
LimeExpressionManager::SetDirtyFlag(); // so refreshes syntax highlighting
fixLanguageConsistency($iSurveyID);
@@ -435,7 +433,7 @@ public function actionImport()
if (isset($aImportResults['fatalerror'])) {
unlink($sFullFilepath);
App()->user->setFlash('error', $aImportResults['fatalerror']);
- $this->redirect(array('questionGroupsAdministration/importview/surveyid/'.$surveyid));
+ $this->redirect(array('questionGroupsAdministration/importview/surveyid/' . $surveyid));
}
unlink($sFullFilepath);
@@ -448,7 +446,7 @@ public function actionImport()
$aData['sidemenu']['state'] = false;
$aData['title_bar']['title'] = $survey->currentLanguageSettings->surveyls_title
- ." (".gT("ID").":".$iSurveyID.")";
+ . " (" . gT("ID") . ":" . $iSurveyID . ")";
$this->aData = $aData;
$this->render('import_view', [
@@ -491,13 +489,13 @@ public function actionImportView($surveyid, $landOnSideMenuTab = 'structure')
$aData['title_bar']['title'] = $survey->currentLanguageSettings->surveyls_title
- ." (".gT("ID").":".$iSurveyID.")";
+ . " (" . gT("ID") . ":" . $iSurveyID . ")";
$this->aData = $aData;
$this->render('importGroup_view', $aData);
} else {
App()->user->setFlash('error', gT("Access denied"));
- $this->redirect(array('questionGroupsAdministration/listquestiongroups/surveyid/'.$surveyid));
+ $this->redirect(array('questionGroupsAdministration/listquestiongroups/surveyid/' . $surveyid));
}
}
@@ -518,7 +516,7 @@ public function actionDelete($iGroupId = null, $asJson = false)
if (is_null($iGroupId)) {
$iGroupId = App()->getRequest()->getPost('gid');
}
- $oQuestionGroup = QuestionGroup::model()->find("gid = :gid", array(":gid"=>$iGroupId));
+ $oQuestionGroup = QuestionGroup::model()->find("gid = :gid", array(":gid" => $iGroupId));
if (empty($oQuestionGroup)) {
throw new CHttpException(401, gT("Invalid question group id"));
}
@@ -542,7 +540,7 @@ public function actionDelete($iGroupId = null, $asJson = false)
[
'success' => $success,
'deletedGroups' => $iGroupsDeleted,
- 'message' => ($success ?gT('The question group was deleted.') : gT('Group could not be deleted')),
+ 'message' => ($success ? gT('The question group was deleted.') : gT('Group could not be deleted')),
'redirect' => $this->createUrl(
'questionGroupsAdministration/listquestiongroups/',
['surveyid' => $iSurveyId]
@@ -560,7 +558,7 @@ public function actionDelete($iGroupId = null, $asJson = false)
}
LimeExpressionManager::UpgradeConditionsToRelevance($iSurveyId);
- $this->redirect(array('questionGroupsAdministration/listquestiongroups/surveyid/'.$iSurveyId));
+ $this->redirect(array('questionGroupsAdministration/listquestiongroups/surveyid/' . $iSurveyId));
}
/**
@@ -816,7 +814,7 @@ public function actionUpdateOrder($surveyid)
'data' => [
'success' => false,
'message' => gT("You can't reorder in an active survey"),
- 'DEBUG' => ['POST'=>$_POST, 'grouparray' => $grouparray]
+ 'DEBUG' => ['POST' => $_POST, 'grouparray' => $grouparray]
],
),
false,
@@ -831,7 +829,7 @@ public function actionUpdateOrder($surveyid)
//first set up the ordering for questiongroups
$oQuestiongroups = QuestionGroup::model()->findAll(
"gid=:gid AND sid=:sid",
- [':gid'=> $aQuestiongroup['gid'], ':sid'=> $surveyid]
+ [':gid' => $aQuestiongroup['gid'], ':sid' => $surveyid]
);
array_map(
function ($oQuestiongroup) use ($aQuestiongroup, $success) {
@@ -849,7 +847,7 @@ function ($oQuestiongroup) use ($aQuestiongroup, $success) {
foreach ($aQuestiongroup['questions'] as $aQuestion) {
$aQuestions = Question::model()->findAll(
"qid=:qid AND sid=:sid",
- [':qid'=> $aQuestion['qid'], ':sid'=> $surveyid]
+ [':qid' => $aQuestion['qid'], ':sid' => $surveyid]
);
array_walk(
$aQuestions,
@@ -880,7 +878,7 @@ function ($oSubQuestion) use ($aQuestion, $success) {
array(
'data' => [
'success' => $success,
- 'DEBUG' => ['POST'=>$_POST, 'grouparray' => $grouparray]
+ 'DEBUG' => ['POST' => $_POST, 'grouparray' => $grouparray]
],
),
false,
@@ -893,7 +891,7 @@ function ($oSubQuestion) use ($aQuestion, $success) {
'data' => [
'success' => false,
'message' => gT("You can't reorder in an active survey"),
- 'DEBUG' => ['POST'=>$_POST, 'grouparray' => $grouparray]
+ 'DEBUG' => ['POST' => $_POST, 'grouparray' => $grouparray]
],
),
false,
@@ -993,12 +991,12 @@ private function newQuestionGroup($iSurveyId, $aQuestionGroupData = null)
throw new CException("Object creation failed, input array malformed or invalid");
}
// Always add at the end
- $oQuestionGroup->group_order = safecount($oSurvey->groups)+1;
+ $oQuestionGroup->group_order = safecount($oSurvey->groups) + 1;
$saved = $oQuestionGroup->save();
if ($saved == false) {
throw new CException(
"Object creation failed, couldn't save.\n ERRORS:"
- .print_r($oQuestionGroup->getErrors(), true)
+ . print_r($oQuestionGroup->getErrors(), true)
);
}
@@ -1038,7 +1036,7 @@ private function editQuestionGroup(&$oQuestionGroup, $aQuestionGroupData)
if ($saved == false) {
throw new CException(
"Object update failed, couldn't save. ERRORS:"
- .print_r($oQuestionGroup->getErrors(), true)
+ . print_r($oQuestionGroup->getErrors(), true)
);
}
return $oQuestionGroup;
diff --git a/application/controllers/RegisterController.php b/application/controllers/RegisterController.php
index 18622c7290c..a4c97a875e7 100644
--- a/application/controllers/RegisterController.php
+++ b/application/controllers/RegisterController.php
@@ -1,4 +1,6 @@
- array(
'class' => 'CaptchaExtendedAction',
- 'mode'=>CaptchaExtendedAction::MODE_MATH
+ 'mode' => CaptchaExtendedAction::MODE_MATH
)
);
}
@@ -96,7 +98,7 @@ public function actionIndex($sid = null)
$iSurveyId = Yii::app()->request->getPost('sid');
}
- $oSurvey = Survey::model()->find("sid=:sid", array(':sid'=>$iSurveyId));
+ $oSurvey = Survey::model()->find("sid=:sid", array(':sid' => $iSurveyId));
/* Throw 404 if needed */
$sLanguage = Yii::app()->request->getParam('lang', Yii::app()->getConfig('defaultlang'));
Yii::app()->setLanguage($sLanguage);
@@ -105,7 +107,7 @@ public function actionIndex($sid = null)
} elseif ($oSurvey->allowregister != 'Y' || !tableExists("{{tokens_{$iSurveyId}}}")) {
throw new CHttpException(404, "The survey in which you are trying to register don't accept registration. It may have been updated or the link you were given is outdated or incorrect.");
} elseif (!is_null($oSurvey->expires) && $oSurvey->expires < dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i", Yii::app()->getConfig('timeadjust'))) {
- $this->redirect(array('survey/index', 'sid'=>$iSurveyId, 'lang'=>$sLanguage));
+ $this->redirect(array('survey/index', 'sid' => $iSurveyId, 'lang' => $sLanguage));
}
/* Fix language according to existing language in survey */
if (!in_array($sLanguage, $oSurvey->getAllLanguages())) {
@@ -131,11 +133,11 @@ public function actionIndex($sid = null)
if (empty($this->aRegisterErrors) && $iTokenId && $this->sMessage === null) {
$directLogin = $event->get('directLogin', false);
if ($directLogin == true) {
- if($event->get('sendRegistrationEmail', false)) {
+ if ($event->get('sendRegistrationEmail', false)) {
self::sendRegistrationEmail($iSurveyId, $iTokenId);
}
$oToken = Token::model($iSurveyId)->findByPk($iTokenId)->decrypt();
- $redirectUrl = Yii::app()->getController()->createUrl('/survey/', array('sid' => $iSurveyId,'token' => $oToken->token, 'lang'=>$sLanguage));
+ $redirectUrl = Yii::app()->getController()->createUrl('/survey/', array('sid' => $iSurveyId,'token' => $oToken->token, 'lang' => $sLanguage));
Yii::app()->getController()->redirect($redirectUrl);
Yii::app()->end();
}
@@ -190,7 +192,7 @@ public function getRegisterErrors($iSurveyId)
*
* @param Integer $iSurveyId The survey id
* @param Integer $iTokenId The token id
- *
+ *
* @return array The rendereable array
*/
public function getRegisterSuccess($iSurveyId, $iTokenId)
@@ -199,7 +201,7 @@ public function getRegisterSuccess($iSurveyId, $iTokenId)
$oToken = Token::model($iSurveyId)->findByPk($iTokenId)->decrypt();
- $aData['active'] = $oSurvey->active;
+ $aData['active'] = $oSurvey->active;
$aData['iSurveyId'] = $iSurveyId;
$aData['sLanguage'] = App()->language;
$aData['sFirstName'] = $oToken->firstname;
@@ -215,7 +217,7 @@ public function getRegisterSuccess($iSurveyId, $iTokenId)
* Takes eventual changes through plugins into account
*
* @param Integer $iSurveyId The surey id
- *
+ *
* @return array The rendereable array
*/
public function getRegisterForm($iSurveyId)
@@ -249,7 +251,7 @@ public function getRegisterForm($iSurveyId)
$aData['aAttribute'] = $aFieldValue['aAttribute'];
$aData['aExtraAttributes'] = $aRegisterAttributes;
$aData['bCaptcha'] = isCaptchaEnabled('registrationscreen', $oSurvey->usecaptcha);
- $aData['sRegisterFormUrl'] = App()->createUrl('register/index', array('sid'=>$iSurveyId));
+ $aData['sRegisterFormUrl'] = App()->createUrl('register/index', array('sid' => $iSurveyId));
$aData['formAdditions'] = '';
if (!empty($registerFormEvent)) {
@@ -284,15 +286,15 @@ public function sendRegistrationEmail($iSurveyId, $iTokenId)
$mailer = new \LimeMailer();
$mailer->setSurvey($iSurveyId);
$mailer->setToken($oToken->token);
- $mailer->setTypeWithRaw('register',$sLanguage);
+ $mailer->setTypeWithRaw('register', $sLanguage);
$mailer->replaceTokenAttributes = true;
$mailerSent = $mailer->sendMessage();
- if($mailer->getEventMessage()) {
+ if ($mailer->getEventMessage()) {
$this->sMailMessage = $mailer->getEventMessage();
}
$aMessage = array();
$aMessage['mail-thanks'] = gT("Thank you for registering to participate in this survey.");
- if($mailerSent) {
+ if ($mailerSent) {
$today = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i", Yii::app()->getConfig('timeadjust'));
Token::model($iSurveyId)->updateByPk($iTokenId, array('sent' => $today));
$aMessage['mail-message'] = $this->sMailMessage;
@@ -300,7 +302,7 @@ public function sendRegistrationEmail($iSurveyId, $iTokenId)
$aMessage['mail-message-error'] = gT("You are registered but an error happened when trying to send the email - please contact the survey administrator.");
}
$aMessage['mail-contact'] = sprintf(gT("Survey administrator %s (%s)"), $aSurveyInfo['adminname'], $aSurveyInfo['adminemail']);
- $this->sMessage = $this->renderPartial('/survey/system/message', array('aMessage'=>$aMessage), true);
+ $this->sMessage = $this->renderPartial('/survey/system/message', array('aMessage' => $aMessage), true);
// Allways return true : if we come here, we allways trye to send an email
return true;
}
@@ -327,9 +329,9 @@ public function getTokenId($iSurveyId)
$this->aRegisterErrors[] = gT("The email address you have entered is already registered and the survey has been completed.");
} elseif (strtolower(substr(trim($oToken->emailstatus), 0, 6)) === "optout") {
// And global blacklisting ?
- {
+ {
$this->aRegisterErrors[] = gT("This email address cannot be used because it was opted out of this survey.");
- }
+ }
} elseif (!$oToken->emailstatus && $oToken->emailstatus != "OK") {
$this->aRegisterErrors[] = gT("This email address is already registered but the email adress was bounced.");
} else {
@@ -374,9 +376,9 @@ public function getFieldValue($iSurveyId)
$aFieldValue['sEmail'] = App()->request->getPost('register_email', '');
$aRegisterAttributes = $aSurveyInfo['attributedescriptions'];
$aFieldValue['aAttribute'] = array();
- foreach ($aRegisterAttributes as $key=>$aRegisterAttribute) {
+ foreach ($aRegisterAttributes as $key => $aRegisterAttribute) {
if ($aRegisterAttribute['show_register'] == 'Y') {
- $aFieldValue['aAttribute'][$key] = App()->request->getPost('register_'.$key, '');
+ $aFieldValue['aAttribute'][$key] = App()->request->getPost('register_' . $key, '');
}
}
return $aFieldValue;
@@ -392,7 +394,7 @@ public function getExtraAttributeInfo($iSurveyId)
$sLanguage = Yii::app()->language;
$aSurveyInfo = getSurveyInfo($iSurveyId, $sLanguage);
$aRegisterAttributes = $aSurveyInfo['attributedescriptions'];
- foreach ($aRegisterAttributes as $key=>$aRegisterAttribute) {
+ foreach ($aRegisterAttributes as $key => $aRegisterAttribute) {
if ($aRegisterAttribute['show_register'] != 'Y') {
unset($aRegisterAttributes[$key]);
} else {
@@ -444,7 +446,7 @@ private function display($iSurveyId, $iTokenId = null, $registerContent)
$aData['aSurveyInfo']['registration_view'] = $registerContent;
- $aData['aSurveyInfo']['registerform']['hiddeninputs'] = '';
+ $aData['aSurveyInfo']['registerform']['hiddeninputs'] = '';
$aData['aSurveyInfo']['include_content'] = 'register';
$aData['aSurveyInfo'] = array_merge($aSurveyInfo, $aData['aSurveyInfo']);
@@ -456,9 +458,7 @@ private function display($iSurveyId, $iTokenId = null, $registerContent)
$aData['aSurveyInfo']['alanguageChanger']['show'] = true;
$aData['aSurveyInfo']['alanguageChanger']['datas'] = $alanguageChangerDatas;
}
- Yii::app()->clientScript->registerScriptFile(Yii::app()->getConfig("generalscripts").'nojs.js', CClientScript::POS_HEAD);
+ Yii::app()->clientScript->registerScriptFile(Yii::app()->getConfig("generalscripts") . 'nojs.js', CClientScript::POS_HEAD);
Yii::app()->twigRenderer->renderTemplateFromFile('layout_global.twig', $aData, false);
-
}
-
}
diff --git a/application/controllers/Statistics_userController.php b/application/controllers/Statistics_userController.php
index 3abad8d27f6..e97afc317e1 100644
--- a/application/controllers/Statistics_userController.php
+++ b/application/controllers/Statistics_userController.php
@@ -1,4 +1,5 @@
moveStep($process_status);
-
} // end foreach -> loop through all questions
$helper = new userstatistics_helper();
$statisticsoutput .= $helper->generate_statistics($iSurveyID, $summary, $summary, $publicgraphs, 'html', null, $sLanguage, false);
-
} //end if -> show summary results
$data['statisticsoutput'] = $statisticsoutput;
@@ -368,7 +366,6 @@ public function createSGQA(array $filters)
default: //Default settings
$allfields[] = $SGQidentifier;
break;
-
} //end switch -> check question types and create filter forms
}
diff --git a/application/controllers/SurveyAdministrationController.php b/application/controllers/SurveyAdministrationController.php
index 8e4aca6bedb..62ea92f283b 100644
--- a/application/controllers/SurveyAdministrationController.php
+++ b/application/controllers/SurveyAdministrationController.php
@@ -123,10 +123,10 @@ public function actionView()
LimeExpressionManager::SetSurveyId($iSurveyID);
LimeExpressionManager::StartProcessingPage(false, true);
- if(isset($survey->currentLanguageSettings) && isset($survey->currentLanguageSettings->surveyls_title)) {
+ if (isset($survey->currentLanguageSettings) && isset($survey->currentLanguageSettings->surveyls_title)) {
$aData['title_bar']['title'] =
$survey->currentLanguageSettings->surveyls_title . " (" . gT("ID") . ":" . $iSurveyID . ")";
- }else{
+ } else {
$aData['title_bar']['title'] = 'Unknown_language_title' . " (" . gT("ID") . ":" . $iSurveyID . ")";
}
$aData['surveyid'] = $iSurveyID;
@@ -198,8 +198,7 @@ public function actionListsurveys()
if (Permission::model()->hasGlobalPermission('superadmin', 'read')) {
$aData['issuperadmin'] = true;
- }else{
-
+ } else {
}
$aData['model'] = new Survey('search');
$aData['groupModel'] = new SurveysGroups('search');
@@ -289,7 +288,7 @@ public function actionRegenerateQuestionCodes()
}
//check subaction
- if(!($sSubAction ==='straight' || $sSubAction === 'bygroup')){
+ if (!($sSubAction === 'straight' || $sSubAction === 'bygroup')) {
Yii::app()->setFlashMessage(gT("Wrong parameter for subaction (straight or bygroup."), 'error');
$this->redirect(array('surveyAdministration/view', 'surveyid' => $iSurveyID));
}
@@ -435,7 +434,7 @@ public function actionInsert($iSurveyID = null)
$simpleSurveyValues = new \LimeSurvey\Datavalueobjects\SimpleSurveyValues();
$baseLanguage = App()->request->getPost('language');
$searchForValidLanguage = getLanguageCodefromLanguage($baseLanguage);
- if($baseLanguage===null) {
+ if ($baseLanguage === null) {
$baseLanguage = 'en'; //shoulb be const somewhere ... or get chosen language from user
}
$simpleSurveyValues->setBaseLanguage($baseLanguage);
@@ -542,8 +541,10 @@ public function actionImportsurveyresources()
$zip = new PclZip($zipfilename);
if (!is_writeable($basedestdir)) {
- Yii::app()->user->setFlash('error', sprintf(gT("Incorrect permissions in your %s folder."),
- $basedestdir));
+ Yii::app()->user->setFlash('error', sprintf(
+ gT("Incorrect permissions in your %s folder."),
+ $basedestdir
+ ));
$this->redirect(array('surveyAdministration/editlocalsettings/surveyid/' . $iSurveyID));
}
@@ -557,8 +558,10 @@ public function actionImportsurveyresources()
if (is_file($zipfilename)) {
if ($zip->extract($extractdir) <= 0) {
- Yii::app()->user->setFlash('error',
- gT("This file is not a valid ZIP file archive. Import failed. ") . $zip->errorInfo(true));
+ Yii::app()->user->setFlash(
+ 'error',
+ gT("This file is not a valid ZIP file archive. Import failed. ") . $zip->errorInfo(true)
+ );
$this->redirect(array('surveyAdministration/editlocalsettings/surveyid/' . $iSurveyID));
}
// now read tempdir and copy authorized files only
@@ -582,14 +585,18 @@ public function actionImportsurveyresources()
unlink($zipfilename);
if (is_null($aErrorFilesInfo) && is_null($aImportedFilesInfo)) {
- Yii::app()->user->setFlash('error',
- gT("This ZIP archive contains no valid Resources files. Import failed."));
+ Yii::app()->user->setFlash(
+ 'error',
+ gT("This ZIP archive contains no valid Resources files. Import failed.")
+ );
$this->redirect(array('surveyAdministration/view/surveyid/' . $iSurveyID));
}
} else {
- Yii::app()->setFlashMessage(gT("An error occurred uploading your file.
+ Yii::app()->setFlashMessage(
+ gT("An error occurred uploading your file.
This may be caused by incorrect permissions for the application /tmp folder."),
- 'error');
+ 'error'
+ );
$this->redirect(array('surveyAdministration/view/' . $iSurveyID));
}
$aData = array(
@@ -620,7 +627,7 @@ public function actionImportsurveyresources()
public function actionGetCurrentEditorValues($sid)
{
//Permission check
- if(!Permission::model()->hasSurveyPermission($sid, 'surveycontent', 'read')){
+ if (!Permission::model()->hasSurveyPermission($sid, 'surveycontent', 'read')) {
return $this->renderPartial(
'/admin/super/_renderJson',
array(
@@ -719,7 +726,7 @@ public function actionGetCurrentEditorValues($sid)
public function actionChangeMultipleTheme()
{
//only superadmin can do this
- if (!Permission::model()->hasGlobalPermission('superadmin', 'update')){
+ if (!Permission::model()->hasGlobalPermission('superadmin', 'update')) {
Yii::app()->user->setFlash('error', gT("Access denied"));
$this->redirect(Yii::app()->request->urlReferrer);
}
@@ -749,7 +756,7 @@ public function actionChangeMultipleTheme()
*/
public function actionChangeMultipleSurveyGroup()
{
- if (!Permission::model()->hasGlobalPermission('superadmin', 'update')){
+ if (!Permission::model()->hasGlobalPermission('superadmin', 'update')) {
Yii::app()->user->setFlash('error', gT("Access denied"));
$this->redirect(Yii::app()->request->urlReferrer);
}
@@ -874,7 +881,6 @@ public function actionGetAjaxQuestionGroupArray($surveyid)
$curQuestion['question_flat'] = viewHelper::flatEllipsizeText($questionText, true);
$curGroup['questions'][] = $curQuestion;
}
-
}
$aGroupViewable[] = $curGroup;
}
@@ -1258,8 +1264,10 @@ public function actionUploadimagefile()
);
}
if ($_FILES['file']['error'] == 1 || $_FILES['file']['error'] == 2) {
- $uploadresult = sprintf(gT("Sorry, this file is too large. Only files up to %01.2f MB are allowed."),
- getMaximumFileUploadSize() / 1024 / 1024);
+ $uploadresult = sprintf(
+ gT("Sorry, this file is too large. Only files up to %01.2f MB are allowed."),
+ getMaximumFileUploadSize() / 1024 / 1024
+ );
return $this->renderPartial(
'/admin/super/_renderJson',
array('data' => ['success' => $success, 'message' => $uploadresult, 'debug' => $debug]),
@@ -1300,8 +1308,12 @@ public function actionUploadimagefile()
);
}
- $filename = sanitize_filename($_FILES['file']['name'], false, false,
- false); // Don't force lowercase or alphanumeric
+ $filename = sanitize_filename(
+ $_FILES['file']['name'],
+ false,
+ false,
+ false
+ ); // Don't force lowercase or alphanumeric
$fullfilepath = $destdir . $filename;
$debug[] = $destdir;
$debug[] = $filename;
@@ -1377,10 +1389,16 @@ public function actionGetSurveyTopbar($sid, $saveButton = false)
$countLanguage = count($oSurvey->allLanguages);
$hasAdditionalLanguages = (count($oSurvey->additionalLanguages) > 0);
$canactivate = $sumcount > 0 && $hasSurveyActivationPermission;
- $expired = $oSurvey->expires != '' && ($oSurvey->expires < dateShift(date("Y-m-d H:i:s"),
- "Y-m-d H:i", Yii::app()->getConfig('timeadjust')));
- $notstarted = ($oSurvey->startdate != '') && ($oSurvey->startdate > dateShift(date("Y-m-d H:i:s"),
- "Y-m-d H:i", Yii::app()->getConfig('timeadjust')));
+ $expired = $oSurvey->expires != '' && ($oSurvey->expires < dateShift(
+ date("Y-m-d H:i:s"),
+ "Y-m-d H:i",
+ Yii::app()->getConfig('timeadjust')
+ ));
+ $notstarted = ($oSurvey->startdate != '') && ($oSurvey->startdate > dateShift(
+ date("Y-m-d H:i:s"),
+ "Y-m-d H:i",
+ Yii::app()->getConfig('timeadjust')
+ ));
if (!$isActive) {
$context = gT("Preview survey");
@@ -1477,9 +1495,7 @@ public function actionDeactivate()
// @todo: What if two plugins change this?
$aData['nostep'] = true;
$this->aData = $aData;
-
} else {
-
if (Yii::app()->request->getPost('ok') == '') {
if (!tableExists('survey_' . $iSurveyID)) {
$_SESSION['flashmessage'] = gT("Error: Response table does not exist. Survey cannot be deactivated.");
@@ -1589,18 +1605,18 @@ public function actionActivate($iSurveyID)
$survey = Survey::model()->findByPk($iSurveyID);
$surveyActivator = new SurveyActivator($survey);
- Yii::app()->user->setState('sql_'.$iSurveyID, ''); //If user has set some filters for responses from statistics on a previous activation, it must be wiped out
+ Yii::app()->user->setState('sql_' . $iSurveyID, ''); //If user has set some filters for responses from statistics on a previous activation, it must be wiped out
$aData = array();
$aData['oSurvey'] = $survey;
$aData['sidemenu']['state'] = false;
$aData['aSurveysettings'] = getSurveyInfo($iSurveyID);
$aData['surveyid'] = $iSurveyID;
$aData['sid'] = $iSurveyID;
- $aData['title_bar']['title'] = $survey->currentLanguageSettings->surveyls_title." (".gT("ID").":".$iSurveyID.")";
+ $aData['title_bar']['title'] = $survey->currentLanguageSettings->surveyls_title . " (" . gT("ID") . ":" . $iSurveyID . ")";
// Redirect if this is not possible
if (!isset($aData['aSurveysettings']['active']) || $aData['aSurveysettings']['active'] == 'Y') {
Yii::app()->setFlashMessage(gT("This survey is already active."), 'error');
- $this->redirect(array('surveyAdministration/view', 'surveyid'=>$iSurveyID));
+ $this->redirect(array('surveyAdministration/view', 'surveyid' => $iSurveyID));
}
Yii::app()->loadHelper("admin/activate");
@@ -1637,35 +1653,36 @@ public function actionActivate($iSurveyID)
$aResult = $surveyActivator->activate();
$aViewUrls = array();
- if ((isset($aResult['error']) && $aResult['error'] == 'plugin')
+ if (
+ (isset($aResult['error']) && $aResult['error'] == 'plugin')
|| (isset($aResult['blockFeedback']) && $aResult['blockFeedback'])
) {
// Got false from plugin, redirect to survey front-page
- $this->redirect(array('surveyAdministration/view', 'surveyid'=>$iSurveyID));
- } else if (isset($aResult['pluginFeedback'])) {
+ $this->redirect(array('surveyAdministration/view', 'surveyid' => $iSurveyID));
+ } elseif (isset($aResult['pluginFeedback'])) {
// Special feedback from plugin
$aViewUrls['output'] = $aResult['pluginFeedback'];
//check if feedback is given to user ...
$this->aData = $aData;
$this->render('_activation_feedback', $aData);
- } else if (isset($aResult['error'])) {
+ } elseif (isset($aResult['error'])) {
$data['result'] = $aResult;
$this->aData = $aData;
$this->render('_activation_error', $data);
} else {
- $warning = (isset($aResult['warning'])) ?true:false;
+ $warning = (isset($aResult['warning'])) ? true : false;
$allowregister = $survey->isAllowRegister;
- $onclickAction = convertGETtoPOST(Yii::app()->getController()->createUrl("admin/tokens/sa/index/surveyid/".$iSurveyID));
- $closedOnclickAction = convertGETtoPOST(Yii::app()->getController()->createUrl("admin/tokens/sa/index/surveyid/".$iSurveyID));
- $noOnclickAction = "window.location.href='".(Yii::app()->getController()->createUrl("surveyAdministration/view/surveyid/".$iSurveyID))."'";
+ $onclickAction = convertGETtoPOST(Yii::app()->getController()->createUrl("admin/tokens/sa/index/surveyid/" . $iSurveyID));
+ $closedOnclickAction = convertGETtoPOST(Yii::app()->getController()->createUrl("admin/tokens/sa/index/surveyid/" . $iSurveyID));
+ $noOnclickAction = "window.location.href='" . (Yii::app()->getController()->createUrl("surveyAdministration/view/surveyid/" . $iSurveyID)) . "'";
$activationData = array(
- 'iSurveyID'=>$iSurveyID,
- 'warning'=>$warning,
- 'allowregister'=>$allowregister,
- 'onclickAction'=>$onclickAction,
- 'closedOnclickAction'=>$closedOnclickAction,
- 'noOnclickAction'=>$noOnclickAction,
+ 'iSurveyID' => $iSurveyID,
+ 'warning' => $warning,
+ 'allowregister' => $allowregister,
+ 'onclickAction' => $onclickAction,
+ 'closedOnclickAction' => $closedOnclickAction,
+ 'noOnclickAction' => $noOnclickAction,
);
$this->aData = $aData;
$this->render('_activation_feedback', $activationData);
@@ -1692,11 +1709,11 @@ public function actionDelete()
$survey = Survey::model()->findByPk($iSurveyID);
$aData['sidemenu']['state'] = false;
- $aData['title_bar']['title'] = $survey->currentLanguageSettings->surveyls_title." (".gT("ID").":".$iSurveyID.")";
+ $aData['title_bar']['title'] = $survey->currentLanguageSettings->surveyls_title . " (" . gT("ID") . ":" . $iSurveyID . ")";
$aData['sidemenu']['state'] = false;
$aData['survey'] = $survey;
- if (Yii::app()->request->getPost("delete") == 'yes'){
+ if (Yii::app()->request->getPost("delete") == 'yes') {
$aData['issuperadmin'] = Permission::model()->hasGlobalPermission('superadmin', 'read');
Survey::model()->deleteSurvey($iSurveyID);
Yii::app()->session['flashmessage'] = gT("Survey deleted.");
@@ -1722,7 +1739,7 @@ public function actionPurge($purge_sid)
if (Permission::model()->hasGlobalPermission('superadmin', 'delete')) {
$survey = Survey::model()->findByPk($purge_sid);
if (empty($survey)) {
- $result = rmdirr(Yii::app()->getConfig('uploaddir').'/surveys/'.$purge_sid);
+ $result = rmdirr(Yii::app()->getConfig('uploaddir') . '/surveys/' . $purge_sid);
if ($result) {
Yii::app()->user->setFlash('success', gT('Survey files deleted.'));
} else {
@@ -1808,11 +1825,11 @@ public function actionRendersidemenulink($surveyid, $subaction)
array_unshift($grplangs, $baselang);
//@TODO add language checks here
- $menuEntry = SurveymenuEntries::model()->find('name=:name', array(':name'=>$menuaction));
+ $menuEntry = SurveymenuEntries::model()->find('name=:name', array(':name' => $menuaction));
if (!(Permission::model()->hasSurveyPermission($iSurveyID, $menuEntry->permission, $menuEntry->permission_grade))) {
Yii::app()->setFlashMessage(gT("You do not have permission to access this page."), 'error');
- $this->redirect(array('surveyAdministration/view', 'surveyid'=>$iSurveyID));
+ $this->redirect(array('surveyAdministration/view', 'surveyid' => $iSurveyID));
}
$templateData = is_array($menuEntry->data) ? $menuEntry->data : [];
@@ -1820,7 +1837,8 @@ public function actionRendersidemenulink($surveyid, $subaction)
if (!empty($menuEntry->getdatamethod)) {
$templateData = array_merge($templateData, call_user_func_array(
array($this, $menuEntry->getdatamethod), //info: getdatamethod is the name of a function here in this controller!!!
- array('survey'=>$survey)));
+ array('survey' => $survey)
+ ));
}
$templateData = array_merge($this->getGeneralTemplateData($iSurveyID), $templateData);
@@ -1840,11 +1858,11 @@ public function actionRendersidemenulink($surveyid, $subaction)
array(
'surveyls_survey_id' => $iSurveyID,
'surveyls_language' => $language)
- )->getAttributes();
+ )->getAttributes();
$aTabTitles[$language] = getLanguageNameFromCode($surveyLanguageSetting['surveyls_language'], false);
if ($surveyLanguageSetting['surveyls_language'] == $survey->language) {
- $aTabTitles[$language] .= ' ('.gT("Base language").')';
+ $aTabTitles[$language] .= ' (' . gT("Base language") . ')';
}
$temp['aSurveyLanguageSettings'] = $surveyLanguageSetting;
@@ -1860,15 +1878,15 @@ public function actionRendersidemenulink($surveyid, $subaction)
$aData['moreInfo'] = $temp;
}
- App()->getClientScript()->registerScriptFile(App()->getConfig('adminscripts').'surveysettings.js');
+ App()->getClientScript()->registerScriptFile(App()->getConfig('adminscripts') . 'surveysettings.js');
App()->getClientScript()->registerPackage('jquery-json');
App()->getClientScript()->registerPackage('bootstrap-switch');
// override survey settings if global settings exist
- $templateData['showqnumcode'] = getGlobalSetting('showqnumcode') !=='choose' ? getGlobalSetting('showqnumcode') : $survey->showqnumcode;
- $templateData['shownoanswer'] = getGlobalSetting('shownoanswer') !=='choose' ? getGlobalSetting('shownoanswer') : $survey->shownoanswer;
- $templateData['showgroupinfo'] = getGlobalSetting('showgroupinfo') !=='2' ? getGlobalSetting('showgroupinfo') : $survey->showgroupinfo;
- $templateData['showxquestions'] = getGlobalSetting('showxquestions') !=='choose' ? getGlobalSetting('showxquestions') : $survey->showxquestions;
+ $templateData['showqnumcode'] = getGlobalSetting('showqnumcode') !== 'choose' ? getGlobalSetting('showqnumcode') : $survey->showqnumcode;
+ $templateData['shownoanswer'] = getGlobalSetting('shownoanswer') !== 'choose' ? getGlobalSetting('shownoanswer') : $survey->shownoanswer;
+ $templateData['showgroupinfo'] = getGlobalSetting('showgroupinfo') !== '2' ? getGlobalSetting('showgroupinfo') : $survey->showgroupinfo;
+ $templateData['showxquestions'] = getGlobalSetting('showxquestions') !== 'choose' ? getGlobalSetting('showxquestions') : $survey->showxquestions;
//Start collecting aData
$aData['surveyid'] = $iSurveyID;
@@ -1882,7 +1900,7 @@ public function actionRendersidemenulink($surveyid, $subaction)
$aData['dateformatdetails'] = getDateFormatData(Yii::app()->session['dateformat']);
$aData['subaction'] = $menuEntry->title;
$aData['display']['menu_bars']['surveysummary'] = $menuEntry->title;
- $aData['title_bar']['title'] = $survey->currentLanguageSettings->surveyls_title." (".gT("ID").":".$iSurveyID.")";
+ $aData['title_bar']['title'] = $survey->currentLanguageSettings->surveyls_title . " (" . gT("ID") . ":" . $iSurveyID . ")";
$aData['surveybar']['buttons']['view'] = true;
$aData['surveybar']['savebutton']['form'] = 'globalsetting';
$aData['surveybar']['savebutton']['useformid'] = 'true';
@@ -1932,7 +1950,7 @@ public function actionOrganize()
$closeAfterSave = $request->getPost('close-after-save') === 'true';
if ($closeAfterSave) {
- $this->redirect(array('surveyAdministration/view/surveyid/'.$iSurveyID));
+ $this->redirect(array('surveyAdministration/view/surveyid/' . $iSurveyID));
}
}
$aData = $this->showReorderForm($iSurveyID);
@@ -2015,7 +2033,6 @@ public function actionCopy()
if (isset($aPathInfo['extension'])) {
$sExtension = $aPathInfo['extension'];
}
-
} elseif ($action == 'copysurvey') {
$aData['sHeader'] = gT("Copy survey");
$aData['sSummaryHeader'] = gT("Survey copy summary");
@@ -2025,10 +2042,9 @@ public function actionCopy()
$aData['bFailed'] = false; // Put a var for continue
$sFullFilepath = '';
if ($action == 'importsurvey') {
-
- $sFullFilepath = Yii::app()->getConfig('tempdir').DIRECTORY_SEPARATOR.randomChars(30).'.'.$sExtension;
+ $sFullFilepath = Yii::app()->getConfig('tempdir') . DIRECTORY_SEPARATOR . randomChars(30) . '.' . $sExtension;
if ($_FILES['the_file']['error'] == 1 || $_FILES['the_file']['error'] == 2) {
- $aData['sErrorMessage'] = sprintf(gT("Sorry, this file is too large. Only files up to %01.2f MB are allowed."), getMaximumFileUploadSize() / 1024 / 1024).'
';
+ $aData['sErrorMessage'] = sprintf(gT("Sorry, this file is too large. Only files up to %01.2f MB are allowed."), getMaximumFileUploadSize() / 1024 / 1024) . '
';
$aData['bFailed'] = true;
} elseif (!in_array(strtolower($sExtension), array('lss', 'txt', 'tsv', 'lsa'))) {
$aData['sErrorMessage'] = sprintf(gT("Import failed. You specified an invalid file type '%s'."), CHtml::encode($sExtension));
@@ -2073,8 +2089,10 @@ public function actionCopy()
} elseif (!Survey::model()->findByPk($iSurveyID)) {
$aData['sErrorMessage'] = gT("Invalid survey ID");
$aData['bFailed'] = true;
- } elseif (!Permission::model()->hasSurveyPermission($iSurveyID, 'surveycontent', 'export')
- && !Permission::model()->hasSurveyPermission($iSurveyID, 'surveycontent', 'export')) {
+ } elseif (
+ !Permission::model()->hasSurveyPermission($iSurveyID, 'surveycontent', 'export')
+ && !Permission::model()->hasSurveyPermission($iSurveyID, 'surveycontent', 'export')
+ ) {
$aData['sErrorMessage'] = gT("We are sorry but you don't have permissions to do this.");
$aData['bFailed'] = true;
} else {
@@ -2090,15 +2108,14 @@ public function actionCopy()
$aImportResults = importSurveyFile($sFullFilepath, (Yii::app()->request->getPost('translinksfields') == '1'));
if (is_null($aImportResults)) {
$aImportResults = array(
- 'error'=>gT("Unknown error while reading the file, no survey created.")
+ 'error' => gT("Unknown error while reading the file, no survey created.")
);
}
} elseif ($action == 'copysurvey' && !$aData['bFailed']) {
-
$aImportResults = XMLImportSurvey('', $copysurveydata, $sNewSurveyName, sanitize_int(App()->request->getParam('copysurveyid')), (Yii::app()->request->getPost('copysurveytranslinksfields') == '1'));
if (isset($aExcludes['conditions'])) {
- Question::model()->updateAll(array('relevance'=>'1'), 'sid='.$aImportResults['newsid']);
- QuestionGroup::model()->updateAll(array('grelevance'=>'1'), 'sid='.$aImportResults['newsid']);
+ Question::model()->updateAll(array('relevance' => '1'), 'sid=' . $aImportResults['newsid']);
+ QuestionGroup::model()->updateAll(array('grelevance' => '1'), 'sid=' . $aImportResults['newsid']);
}
if (isset($aExcludes['reset_response_id'])) {
@@ -2110,7 +2127,6 @@ public function actionCopy()
if (!isset($aExcludes['permissions'])) {
Permission::model()->copySurveyPermissions($iSurveyID, $aImportResults['newsid']);
}
-
} else {
$aData['bFailed'] = true;
}
@@ -2123,8 +2139,8 @@ public function actionCopy()
$aData['aImportResults'] = $aImportResults;
$aData['action'] = $action;
if (isset($aImportResults['newsid'])) {
- $aData['sLink'] = $this->createUrl('surveyAdministration/view/',['iSurveyID' => $aImportResults['newsid']]);
- $aData['sLinkApplyThemeOptions'] = 'surveyAdministration/applythemeoptions/surveyid/'.$aImportResults['newsid'];
+ $aData['sLink'] = $this->createUrl('surveyAdministration/view/', ['iSurveyID' => $aImportResults['newsid']]);
+ $aData['sLinkApplyThemeOptions'] = 'surveyAdministration/applythemeoptions/surveyid/' . $aImportResults['newsid'];
}
}
}
@@ -2138,7 +2154,7 @@ public function actionCopy()
LimeExpressionManager::UpgradeConditionsToRelevance($aImportResults['newsid']);
@LimeExpressionManager::StartSurvey($oSurvey->sid, 'survey', $oSurvey->attributes, true);
LimeExpressionManager::StartProcessingPage(true, true);
- $aGrouplist = QuestionGroup::model()->findAllByAttributes(['sid'=>$aImportResults['newsid']]);
+ $aGrouplist = QuestionGroup::model()->findAllByAttributes(['sid' => $aImportResults['newsid']]);
foreach ($aGrouplist as $aGroup) {
LimeExpressionManager::StartProcessingGroup($aGroup['gid'], $oSurvey->anonymized != 'Y', $aImportResults['newsid']);
LimeExpressionManager::FinishProcessingGroup();
@@ -2201,7 +2217,7 @@ public function actionDatetimesettings()
{
if (Permission::model()->hasGlobalPermission('surveys', 'read')) {
$data = array(
- 'dateformatsettings'=>getDateFormatData(Yii::app()->session['dateformat']),
+ 'dateformatsettings' => getDateFormatData(Yii::app()->session['dateformat']),
'showClear' => true,
'allowInputToggle' => true,
);
@@ -2219,7 +2235,7 @@ public function actionDatetimesettings()
public function actionExpireMultipleSurveys()
{
//permission check: only superadmin is allowed to do this
- if(!Permission::model()->hasGlobalPermission('superadmin')){
+ if (!Permission::model()->hasGlobalPermission('superadmin')) {
Yii::app()->user->setFlash('error', gT("Access denied"));
$this->redirect(Yii::app()->request->urlReferrer);
}
@@ -2234,7 +2250,7 @@ public function actionExpireMultipleSurveys()
$expires = null;
} else {
//new Date_Time_Converter($expires, $formatdata['phpdate'].' H:i');
- $datetimeobj = new date_time_converter($expires, $formatdata['phpdate'].' H:i');
+ $datetimeobj = new date_time_converter($expires, $formatdata['phpdate'] . ' H:i');
$expires = $datetimeobj->convert("Y-m-d H:i:s");
}
@@ -2250,7 +2266,7 @@ public function actionExpireMultipleSurveys()
}
$this->renderPartial(
'ext.admin.survey.ListSurveysWidget.views.massive_actions._action_results',
- array('aResults'=>$aResults, 'successLabel'=>gT('OK'))
+ array('aResults' => $aResults, 'successLabel' => gT('OK'))
);
}
@@ -2271,14 +2287,15 @@ public function actionExpireMultipleSurveys()
*
* @todo While refactoring (at some point) this function should be removed and only one unique identifier should be used
*/
- private function getSurveyIdFromGetRequest(){
+ private function getSurveyIdFromGetRequest()
+ {
$surveyId = Yii::app()->request->getParam('sid');
- if($surveyId === null){
- $surveyId = Yii::app()->request->getParam('surveyid');
- }
- if($surveyId === null){
- $surveyId = Yii::app()->request->getParam('iSurveyID');
- }
+ if ($surveyId === null) {
+ $surveyId = Yii::app()->request->getParam('surveyid');
+ }
+ if ($surveyId === null) {
+ $surveyId = Yii::app()->request->getParam('iSurveyID');
+ }
return (int) $surveyId;
}
@@ -2299,9 +2316,9 @@ private function tabResourceManagement($oSurvey)
global $sCKEditorURL;
// TAB Uploaded Resources Management
- $ZIPimportAction = " onclick='if (window.LS.validatefilename(this.form,\"".gT('Please select a file to import!', 'js')."\")) { this.form.submit();}'";
+ $ZIPimportAction = " onclick='if (window.LS.validatefilename(this.form,\"" . gT('Please select a file to import!', 'js') . "\")) { this.form.submit();}'";
if (!function_exists("zip_open")) {
- $ZIPimportAction = " onclick='alert(\"".gT("The ZIP library is not activated in your PHP configuration thus importing ZIP files is currently disabled.", "js")."\");'";
+ $ZIPimportAction = " onclick='alert(\"" . gT("The ZIP library is not activated in your PHP configuration thus importing ZIP files is currently disabled.", "js") . "\");'";
}
$disabledIfNoResources = '';
@@ -2334,7 +2351,7 @@ private function showReorderForm($iSurveyID)
{
$survey = Survey::model()->findByPk($iSurveyID);
$aData = [];
- $aData['title_bar']['title'] = $survey->currentLanguageSettings->surveyls_title." (".gT("ID").":".$iSurveyID.")";
+ $aData['title_bar']['title'] = $survey->currentLanguageSettings->surveyls_title . " (" . gT("ID") . ":" . $iSurveyID . ")";
$aData['sid'] = $iSurveyID; //frontend need this to render topbar for the view
// Prepare data for the view
@@ -2365,7 +2382,7 @@ private function showReorderForm($iSurveyID)
foreach ($oQuestionData->readAll() as $q) {
$relevance = ($q['relevance'] == '') ? 1 : $q['relevance'];
- $question = '[{'.$relevance.'}] '.$q['title'];
+ $question = '[{' . $relevance . '}] ' . $q['title'];
LimeExpressionManager::ProcessString($question, $q['qid']);
$q['question'] = viewHelper::stripTagsEM(LimeExpressionManager::GetLastPrettyPrintExpression());
$q['gid'] = $aGroup['gid'];
@@ -2434,12 +2451,13 @@ private function reorderGroup($iSurveyID)
}
$sBaseLanguage = Survey::model()->findByPk($iSurveyID)->language;
- $oQuestion = Question::model()->findByPk(array("qid"=>$qid, 'language'=>$sBaseLanguage));
+ $oQuestion = Question::model()->findByPk(array("qid" => $qid, 'language' => $sBaseLanguage));
$oldGid = $oQuestion['gid'];
if ($oldGid != $gid) {
fixMovedQuestionConditions($qid, $oldGid, $gid, $iSurveyID);
}
- Question::model()->updateAll(array(
+ Question::model()->updateAll(
+ array(
'question_order' => $aQuestionOrder[$gid],
'gid' => $gid),
'qid=:qid',
@@ -2582,7 +2600,7 @@ private function createSampleQuestion($iSurveyID, $iGroupID)
{
// Now create a new dummy question
$sLanguage = Survey::model()->findByPk($iSurveyID)->language;
- $oQuestion = new Question;
+ $oQuestion = new Question();
$oQuestion->sid = $iSurveyID;
$oQuestion->gid = $iGroupID;
$oQuestion->type = Question::QT_T_LONG_FREE_TEXT;
@@ -2777,7 +2795,7 @@ private function surveysummary(&$aData)
private function fetchSurveyInfo($action, $iSurveyID = null)
{
if ($action == 'newsurvey') {
- $oSurvey = new Survey;
+ $oSurvey = new Survey();
} elseif ($action == 'editsurvey' && $iSurveyID) {
$oSurvey = Survey::model()->findByPk($iSurveyID);
}
@@ -2837,7 +2855,7 @@ private function getGeneralTemplateData($iSurveyID)
$aData['surveyid'] = $iSurveyID;
$oSurvey = Survey::model()->findByPk($iSurveyID);
if (empty($oSurvey)) {
- $oSurvey = new Survey;
+ $oSurvey = new Survey();
}
$inheritOwner = empty($oSurvey->oOptions->ownerLabel) ? $oSurvey->owner_id : $oSurvey->oOptions->ownerLabel;
$users = getUserList();
@@ -2919,7 +2937,7 @@ private function getDataSecurityEditData($survey)
$aTabTitles[$sLang] = getLanguageNameFromCode($aSurveyLanguageSettings['surveyls_language'], false);
if ($aSurveyLanguageSettings['surveyls_language'] == $survey->language) {
- $aTabTitles[$sLang] .= ' ('.gT("Base language").')';
+ $aTabTitles[$sLang] .= ' (' . gT("Base language") . ')';
}
$aLanguageData['aSurveyLanguageSettings'] = $aSurveyLanguageSettings;
@@ -3034,22 +3052,22 @@ private function tabPanelIntegration($survey, $sLang = null)
if (count($oRecord->subquestions)) {
foreach ($oRecord->subquestions as $oSubquestion) {
$aQuestions[] = array_merge(
- $oRecord->attributes,
+ $oRecord->attributes,
$oRecord->questionl10ns[$survey->language]->attributes,
array(
- 'sqid' => $oSubquestion->qid,
- 'sqtitle' => $oSubquestion->title,
+ 'sqid' => $oSubquestion->qid,
+ 'sqtitle' => $oSubquestion->title,
'sqquestion' => $oSubquestion->questionl10ns[$survey->language]->question
)
);
}
} else {
$aQuestions[] = array_merge(
- $oRecord->attributes,
+ $oRecord->attributes,
$oRecord->questionl10ns[$survey->language]->attributes,
array(
- 'sqid' => null,
- 'sqtitle' => null,
+ 'sqid' => null,
+ 'sqtitle' => null,
'sqquestion' => null
)
);
diff --git a/application/controllers/SurveyController.php b/application/controllers/SurveyController.php
index 8ddad409f19..97163a84ae5 100644
--- a/application/controllers/SurveyController.php
+++ b/application/controllers/SurveyController.php
@@ -1,4 +1,5 @@
-session['FileManagerContext']);
- if (!Yii::app()->getConfig("surveyid")) {Yii::app()->setConfig("surveyid", returnGlobal('sid')); } //SurveyID
- if (!Yii::app()->getConfig("ugid")) {Yii::app()->setConfig("ugid", returnGlobal('ugid')); } //Usergroup-ID
- if (!Yii::app()->getConfig("gid")) {Yii::app()->setConfig("gid", returnGlobal('gid')); } //GroupID
- if (!Yii::app()->getConfig("qid")) {Yii::app()->setConfig("qid", returnGlobal('qid')); } //QuestionID
- if (!Yii::app()->getConfig("lid")) {Yii::app()->setConfig("lid", returnGlobal('lid')); } //LabelID
- if (!Yii::app()->getConfig("code")) {Yii::app()->setConfig("code", returnGlobal('code')); } // ??
- if (!Yii::app()->getConfig("action")) {Yii::app()->setConfig("action", returnGlobal('action')); } //Desired action
- if (!Yii::app()->getConfig("subaction")) {Yii::app()->setConfig("subaction", returnGlobal('subaction')); } //Desired subaction
- if (!Yii::app()->getConfig("editedaction")) {Yii::app()->setConfig("editedaction", returnGlobal('editedaction')); } // for html editor integration
+ if (!Yii::app()->getConfig("surveyid")) {
+ Yii::app()->setConfig("surveyid", returnGlobal('sid'));
+ } //SurveyID
+ if (!Yii::app()->getConfig("ugid")) {
+ Yii::app()->setConfig("ugid", returnGlobal('ugid'));
+ } //Usergroup-ID
+ if (!Yii::app()->getConfig("gid")) {
+ Yii::app()->setConfig("gid", returnGlobal('gid'));
+ } //GroupID
+ if (!Yii::app()->getConfig("qid")) {
+ Yii::app()->setConfig("qid", returnGlobal('qid'));
+ } //QuestionID
+ if (!Yii::app()->getConfig("lid")) {
+ Yii::app()->setConfig("lid", returnGlobal('lid'));
+ } //LabelID
+ if (!Yii::app()->getConfig("code")) {
+ Yii::app()->setConfig("code", returnGlobal('code'));
+ } // ??
+ if (!Yii::app()->getConfig("action")) {
+ Yii::app()->setConfig("action", returnGlobal('action'));
+ } //Desired action
+ if (!Yii::app()->getConfig("subaction")) {
+ Yii::app()->setConfig("subaction", returnGlobal('subaction'));
+ } //Desired subaction
+ if (!Yii::app()->getConfig("editedaction")) {
+ Yii::app()->setConfig("editedaction", returnGlobal('editedaction'));
+ } // for html editor integration
Yii::app()->clientScript->registerPackage('decimal'); // decimal
Yii::app()->clientScript->registerPackage('decimalcustom'); // decimal-customisations
}
@@ -99,9 +118,9 @@ public function actions()
'uploader' => 'application.controllers.uploader',
'verification' => 'application.controllers.verification',
'captcha' => array(
- 'class'=>'CaptchaExtendedAction',
+ 'class' => 'CaptchaExtendedAction',
// if needed, modify settings
- 'mode'=>CaptchaExtendedAction::MODE_MATH,
+ 'mode' => CaptchaExtendedAction::MODE_MATH,
)
);
}
@@ -130,7 +149,7 @@ public function renderExitMessage($iSurveyId, $sType, $aMessages = array(), $aUr
$message = $this->renderPartial(
"/survey/system/message",
array(
- 'aMessage'=>$aMessages
+ 'aMessage' => $aMessages
),
true
);
@@ -143,7 +162,7 @@ public function renderExitMessage($iSurveyId, $sType, $aMessages = array(), $aUr
$error = $this->renderPartial(
"/survey/system/errorWarning",
array(
- 'aErrors'=>$aErrors
+ 'aErrors' => $aErrors
),
true
);
@@ -173,7 +192,7 @@ public function renderExitMessage($iSurveyId, $sType, $aMessages = array(), $aUr
Yii::app()->twigRenderer->renderTemplateFromFile(
"layout_errors.twig",
- array('aError'=>$aReplacementData, 'aSurveyInfo' => $aSurveyInfo),
+ array('aError' => $aReplacementData, 'aSurveyInfo' => $aSurveyInfo),
false
);
App()->end();
diff --git a/application/controllers/SurveysController.php b/application/controllers/SurveysController.php
index 2a849811072..5a92f0ea833 100755
--- a/application/controllers/SurveysController.php
+++ b/application/controllers/SurveysController.php
@@ -19,16 +19,16 @@ class SurveysController extends LSYii_Controller
public function actionPublicList($lang = null)
{
- if ( !empty($lang) ) {
- // Validate if languages exists and fall back to default lang if needed
- $aLanguages = getLanguageDataRestricted( false,'short' );
- if ( !isset($aLanguages[ $lang ]) ) {
- $lang=App()->getConfig( 'defaultlang' );
- }
- } else {
- $lang=App()->getConfig( 'defaultlang' );
+ if (!empty($lang)) {
+ // Validate if languages exists and fall back to default lang if needed
+ $aLanguages = getLanguageDataRestricted(false, 'short');
+ if (!isset($aLanguages[ $lang ])) {
+ $lang = App()->getConfig('defaultlang');
}
- App()->setLanguage( $lang );
+ } else {
+ $lang = App()->getConfig('defaultlang');
+ }
+ App()->setLanguage($lang);
$oTemplate = Template::model()->getInstance(getGlobalSetting('defaulttheme'));
@@ -53,14 +53,14 @@ public function actionPublicList($lang = null)
$aData['alanguageChanger']['datas'] = $alanguageChangerDatas;
}
- Yii::app()->clientScript->registerScriptFile(Yii::app()->getConfig("generalscripts").'nojs.js', CClientScript::POS_HEAD);
+ Yii::app()->clientScript->registerScriptFile(Yii::app()->getConfig("generalscripts") . 'nojs.js', CClientScript::POS_HEAD);
// maintenance mode
$sMaintenanceMode = getGlobalSetting('maintenancemode');
if ($sMaintenanceMode == 'hard' || $sMaintenanceMode == 'soft') {
- Yii::app()->twigRenderer->renderTemplateFromFile("layout_maintenance.twig", array('aSurveyInfo'=>$aData), false);
+ Yii::app()->twigRenderer->renderTemplateFromFile("layout_maintenance.twig", array('aSurveyInfo' => $aData), false);
} else {
- Yii::app()->twigRenderer->renderTemplateFromFile("layout_survey_list.twig", array('aSurveyInfo'=>$aData), false);
+ Yii::app()->twigRenderer->renderTemplateFromFile("layout_survey_list.twig", array('aSurveyInfo' => $aData), false);
}
}
@@ -137,7 +137,7 @@ public function spitOutHtmlError(array $error, $oException = null)
break;
case '404':
$title = gT('404: Not Found');
- $message = gT('The requested URL was not found on this server.')." \n"
+ $message = gT('The requested URL was not found on this server.') . " \n"
. gT('If you entered the URL manually please check your spelling and try again.');
break;
case '500':
diff --git a/application/controllers/SurveysGroupsPermissionController.php b/application/controllers/SurveysGroupsPermissionController.php
index a33b080e548..29368aa6df8 100644
--- a/application/controllers/SurveysGroupsPermissionController.php
+++ b/application/controllers/SurveysGroupsPermissionController.php
@@ -1,4 +1,5 @@
setPermissions($uid);
}
}
- if($success) {
+ if ($success) {
App()->setFlashMessage("Surveys groups permissions were successfully updated");
} else {
App()->setFlashMessage("An error happen when update surveys groups permissions", 'danger');
@@ -463,7 +464,7 @@ private function viewUserOrUserGroup($id, $to, $type = 'user')
'url' => App()->createUrl('surveyAdministration/listsurveys', array('#' => 'surveygroups')),
)
);
- if($model->hasPermission('permission', 'update')) {
+ if ($model->hasPermission('permission', 'update')) {
$buttons = array(
'savebutton' => array(
'form' => 'permissionsSave'
diff --git a/application/controllers/ThemeOptionsController.php b/application/controllers/ThemeOptionsController.php
index 6a92ba74186..ea860d9e08f 100644
--- a/application/controllers/ThemeOptionsController.php
+++ b/application/controllers/ThemeOptionsController.php
@@ -36,7 +36,7 @@ public function accessRules()
*
* @return bool
*/
- protected function beforeRender($view) : bool
+ protected function beforeRender($view): bool
{
if (isset($this->aData['surveyid'])) {
$this->aData['oSurvey'] = $this->aData['oSurvey'] ?? Survey::model()->findByPk($this->aData['surveyid']);
@@ -115,7 +115,7 @@ public function actionCreate(): void
* @return void
* @throws CException
*/
- public function actionResetMultiple() : void
+ public function actionResetMultiple(): void
{
$aTemplates = json_decode(App()->request->getPost('sItems'));
$gridid = App()->request->getPost('gridvalue');
@@ -162,7 +162,7 @@ public function actionResetMultiple() : void
* @return void
* @throws Exception
*/
- public function actionUninstallMultiple() : void
+ public function actionUninstallMultiple(): void
{
$aTemplates = json_decode(App()->request->getPost('sItems'));
$gridid = App()->request->getPost('grididvalue');
@@ -179,7 +179,6 @@ public function actionUninstallMultiple() : void
$aUninstallResult = QuestionTheme::uninstall($model);
$aResults[$template]['result'] = isset($aUninstallResult['result']) ? $aUninstallResult['result'] : false;
$aResults[$template]['error'] = isset($aUninstallResult['error']) ? $aUninstallResult['error'] : null;
-
} elseif ($gridid === 'themeoptions-grid') {
$aResults[$template]['title'] = $model->template_name;
$templatename = $model->template_name;
@@ -191,7 +190,6 @@ public function actionUninstallMultiple() : void
$aResults[$template]['result'] = false;
$aResults[$template]['error'] = gT('Error! You cannot uninstall the default template.');
}
-
} else {
$aResults[$template]['result'] = false;
$aResults[$template]['error'] = gT('Error! Some theme(s) inherit from this theme');
@@ -199,7 +197,7 @@ public function actionUninstallMultiple() : void
}
}
//set Modal table labels
- $tableLabels= array(gT('Template id'),gT('Template name') ,gT('Status'));
+ $tableLabels = array(gT('Template id'),gT('Template name') ,gT('Status'));
$this->renderPartial(
'ext.admin.survey.ListSurveysWidget.views.massive_actions._action_results',
@@ -210,7 +208,6 @@ public function actionUninstallMultiple() : void
'tableLabels' => $tableLabels
)
);
-
} else {
App()->setFlashMessage(gT("We are sorry but you don't have permissions to do this."), 'error');
}
@@ -223,7 +220,7 @@ public function actionUninstallMultiple() : void
* @throws CException
* @throws CHttpException
*/
- public function actionSelectedItems() : void
+ public function actionSelectedItems(): void
{
$aTemplates = json_decode(App()->request->getPost('$oCheckedItems'));
$aResults = [];
@@ -242,7 +239,7 @@ public function actionSelectedItems() : void
$aResults[$template]['result'] = gT('Selected');
}
//set Modal table labels
- $tableLabels= array(gT('Template id'),gT('Template name') ,gT('Status'));
+ $tableLabels = array(gT('Template id'),gT('Template name') ,gT('Status'));
$this->renderPartial(
'ext.admin.grid.MassiveActionsWidget.views._selected_items',
@@ -264,7 +261,7 @@ public function actionSelectedItems() : void
* @throws CException
* @throws CHttpException
*/
- public function actionUpdate(int $id) : void
+ public function actionUpdate(int $id): void
{
$model = $this->loadModel($id);
@@ -276,7 +273,7 @@ public function actionUpdate(int $id) : void
$model->attributes = $_POST['TemplateConfiguration'];
if ($model->save()) {
App()->user->setFlash('success', gT('Theme options saved.'));
- $this->redirect(array('themeOptions/update/id/'.$model->id));
+ $this->redirect(array('themeOptions/update/id/' . $model->id));
}
}
$this->updateCommon($model);
@@ -293,7 +290,7 @@ public function actionUpdate(int $id) : void
*
* @return TemplateConfiguration
*/
- private function turnAjaxmodeOffAsDefault(TemplateConfiguration $templateConfiguration) : TemplateConfiguration
+ private function turnAjaxmodeOffAsDefault(TemplateConfiguration $templateConfiguration): TemplateConfiguration
{
$attributes = $templateConfiguration->getAttributes();
$hasOptions = isset($attributes['options']);
@@ -319,10 +316,11 @@ private function turnAjaxmodeOffAsDefault(TemplateConfiguration $templateConfigu
*
* @return void
*/
- public function actionUpdateSurvey() : void
+ public function actionUpdateSurvey(): void
{
$sid = $this->getSurveyIdFromGetRequest();
- if (!Permission::model()->hasGlobalPermission('templates', 'update')
+ if (
+ !Permission::model()->hasGlobalPermission('templates', 'update')
&& !Permission::model()->hasSurveyPermission($sid, 'surveysettings', 'update')
) {
throw new CHttpException(403, gT("You do not have permission to access this page."));
@@ -354,15 +352,14 @@ public function actionUpdateSurvey() : void
*
* @return void
*/
- public function actionUpdateSurveyGroup(int $id = null, int $gsid, $l = null) : void
+ public function actionUpdateSurveyGroup(int $id = null, int $gsid, $l = null): void
{
- if (!Permission::model()->hasGlobalPermission('templates', 'update'))
- {
- if(empty($gsid)) {
+ if (!Permission::model()->hasGlobalPermission('templates', 'update')) {
+ if (empty($gsid)) {
throw new CHttpException(403, gT("You do not have permission to access this page."));
}
$oSurveysInGroup = SurveysInGroup::model()->findByPk($gsid);
- if(empty($oSurveysInGroup) && !$oSurveysInGroup->hasPermission('surveys', 'update')) {
+ if (empty($oSurveysInGroup) && !$oSurveysInGroup->hasPermission('surveys', 'update')) {
throw new CHttpException(403, gT("You do not have permission to access this page."));
}
}
@@ -370,7 +367,7 @@ public function actionUpdateSurveyGroup(int $id = null, int $gsid, $l = null) :
$model = TemplateConfiguration::getInstance($sTemplateName, $gsid);
if ($model->bJustCreated === true && $l === null) {
- $this->redirect(array("themeOptions/updateSurveyGroup/", 'id'=>$id, 'gsid'=>$gsid, 'l'=>1));
+ $this->redirect(array("themeOptions/updateSurveyGroup/", 'id' => $id, 'gsid' => $gsid, 'l' => 1));
}
if (isset($_POST['TemplateConfiguration'])) {
@@ -391,7 +388,7 @@ public function actionUpdateSurveyGroup(int $id = null, int $gsid, $l = null) :
*
* @return void
*/
- public function actionSetAdminTheme(string $sAdminThemeName) : void
+ public function actionSetAdminTheme(string $sAdminThemeName): void
{
if (!Permission::model()->hasGlobalPermission('settings', 'update')) {
throw new CHttpException(403, gT("You do not have permission to access this page."));
@@ -407,7 +404,7 @@ public function actionSetAdminTheme(string $sAdminThemeName) : void
*
* @return void
*/
- public function actionIndex() : void
+ public function actionIndex(): void
{
if (!Permission::model()->hasGlobalPermission('templates', 'read')) {
throw new CHttpException(403, gT("You do not have permission to access this page."));
@@ -415,17 +412,17 @@ public function actionIndex() : void
$aData = array();
$oSurveyTheme = new TemplateConfiguration();
$aData['oAdminTheme'] = new AdminTheme();
- $aData['oQuestionTheme'] = new QuestionTheme;
+ $aData['oQuestionTheme'] = new QuestionTheme();
$canImport = true;
$importErrorMessage = null;
if (!is_writable(App()->getConfig('tempdir'))) {
$canImport = false;
$importErrorMessage = gT("The template upload directory doesn't exist or is not writable.");
- } else if (!is_writable(App()->getConfig('userthemerootdir'))) {
+ } elseif (!is_writable(App()->getConfig('userthemerootdir'))) {
$canImport = false;
$importErrorMessage = gT("Some directories are not writable. Please change the folder permissions for /tmp and /upload/themes in order to enable this option.");
- } else if (!function_exists("zip_open")) {
+ } elseif (!function_exists("zip_open")) {
$canImport = false;
$importErrorMessage = gT("You do not have the required ZIP library installed in PHP.");
}
@@ -477,7 +474,7 @@ public function actionIndex() : void
*
* @return void
*/
- public function actionAdmin() : void
+ public function actionAdmin(): void
{
if (Permission::model()->hasGlobalPermission('templates', 'read')) {
$model = new TemplateOptions('search');
@@ -489,7 +486,7 @@ public function actionAdmin() : void
$this->render(
'admin',
array(
- 'model'=>$model,
+ 'model' => $model,
)
);
} else {
@@ -558,7 +555,7 @@ public function actionImportManifest()
*
* @return void
*/
- public function actionUninstall() : void
+ public function actionUninstall(): void
{
$templatename = App()->request->getPost('templatename');
if (Permission::model()->hasGlobalPermission('templates', 'update')) {
@@ -589,29 +586,29 @@ public function actionUninstall() : void
*
* @throws Exception
*/
- public function actionReset(int $gsid) : void
+ public function actionReset(int $gsid): void
{
- if (!Permission::model()->hasGlobalPermission('templates', 'update'))
- {
- if(empty($gsid)) {
+ if (!Permission::model()->hasGlobalPermission('templates', 'update')) {
+ if (empty($gsid)) {
throw new CHttpException(403, gT("You do not have permission to access this page."));
}
$oSurveysInGroup = SurveysInGroup::model()->findByPk($gsid);
- if(empty($oSurveysInGroup) && !$oSurveysInGroup->hasPermission('surveys', 'update')) {
+ if (empty($oSurveysInGroup) && !$oSurveysInGroup->hasPermission('surveys', 'update')) {
throw new CHttpException(403, gT("You do not have permission to access this page."));
}
}
$templatename = App()->request->getPost('templatename');
- if($gsid) {
- $oTemplateConfiguration = TemplateConfiguration::model()->find("gsid = :gsid AND template_name = :templatename",
+ if ($gsid) {
+ $oTemplateConfiguration = TemplateConfiguration::model()->find(
+ "gsid = :gsid AND template_name = :templatename",
array(":gsid" => $gsid, ":templatename" => $templatename)
);
- if(empty($oTemplateConfiguration)) {
+ if (empty($oTemplateConfiguration)) {
throw new CHttpException(401, gT("Invalid template configuration for this group."));
}
$oTemplateConfiguration->setToInherit();
- if($oTemplateConfiguration->save()) {
+ if ($oTemplateConfiguration->save()) {
App()->setFlashMessage(sprintf(gT("The theme '%s' has been reset."), $templatename), 'success');
}
$this->redirect(array("admin/surveysgroups/sa/update", 'id' => $gsid, "#" => "templateSettingsFortThisGroup"));
@@ -629,7 +626,7 @@ public function actionReset(int $gsid) : void
*
* @return void
*/
- public function actionPerformAjaxValidation(TemplateOptions $model) : void
+ public function actionPerformAjaxValidation(TemplateOptions $model): void
{
if (isset($_POST['ajax']) && $_POST['ajax'] === 'template-options-form') {
echo CActiveForm::validate($model);
@@ -665,7 +662,7 @@ public function actionGetPreviewTag()
*
* @return void
*/
- private function updateCommon(TemplateConfiguration $model, int $sid = null, int $gsid = null) : void
+ private function updateCommon(TemplateConfiguration $model, int $sid = null, int $gsid = null): void
{
/* init the template to current one if option use some twig function (imageSrc for example) mantis #14363 */
$oTemplate = Template::model()->getInstance($model->template_name, $sid, $gsid);
@@ -740,12 +737,13 @@ private function updateCommon(TemplateConfiguration $model, int $sid = null, int
*
* @todo While refactoring (at some point) this function should be removed and only one unique identifier should be used
*/
- private function getSurveyIdFromGetRequest(){
+ private function getSurveyIdFromGetRequest()
+ {
$surveyId = Yii::app()->request->getParam('sid');
- if($surveyId === null){
+ if ($surveyId === null) {
$surveyId = Yii::app()->request->getParam('surveyid');
}
- if($surveyId === null){
+ if ($surveyId === null) {
$surveyId = Yii::app()->request->getParam('iSurveyID');
}
diff --git a/application/controllers/UploaderController.php b/application/controllers/UploaderController.php
index 336304059d6..abf6ac64f74 100644
--- a/application/controllers/UploaderController.php
+++ b/application/controllers/UploaderController.php
@@ -1,4 +1,6 @@
-session['survey_'.$surveyid]['s_lang']) ? Yii::app()->session['survey_'.$surveyid]['s_lang'] : "";
+ $sLanguage = isset(Yii::app()->session['survey_' . $surveyid]['s_lang']) ? Yii::app()->session['survey_' . $surveyid]['s_lang'] : "";
Yii::app()->setLanguage($sLanguage);
$uploaddir = Yii::app()->getConfig("uploaddir");
$tempdir = Yii::app()->getConfig("tempdir");
@@ -56,28 +58,28 @@ public function run($actionID)
}
if ($sFileGetContent) {
if (substr($sFileGetContent, 0, 6) == 'futmp_') {
- $sFileDir = $tempdir.'/upload/';
+ $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)) {
+ if (is_file($sFileDir . $sFileGetContent)) {
// Validate file before else 500 error by getMimeType
- $mimeType = LSFileHelper::getMimeType($sFileDir.$sFileGetContent, null, false);
+ $mimeType = LSFileHelper::getMimeType($sFileDir . $sFileGetContent, null, false);
if (is_null($mimeType)) {
$mimeType = "application/octet-stream"; // Can not really get content if not image
}
- header('Content-Type: '.$mimeType);
- readfile($sFileDir.$sFileGetContent);
+ header('Content-Type: ' . $mimeType);
+ readfile($sFileDir . $sFileGetContent);
Yii::app()->end();
} else {
Yii::app()->end();
}
} elseif ($bDelete) {
if (substr($sFileName, 0, 6) == 'futmp_') {
- $sFileDir = $tempdir.'/upload/';
+ $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/";
@@ -107,7 +109,7 @@ public function run($actionID)
}
//var_dump($sFileDir.$sFilename);
// Return some json to do a beautiful text
- if (@unlink($sFileDir.$sFileName)) {
+ if (@unlink($sFileDir . $sFileName)) {
echo sprintf(gT('File %s deleted'), $sOriginalFileName);
} else {
echo gT('Oops, There was an error deleting the file');
@@ -121,7 +123,7 @@ public function run($actionID)
// That probably indicates post_max_size has been exceeded.
// https://www.php.net/manual/en/ini.core.php#ini.post-max-size
if (empty($_POST) && empty($_FILES)) {
- if( YII_DEBUG || Permission::isForcedSuperAdmin(Permission::getUserId()) ) {
+ if (YII_DEBUG || Permission::isForcedSuperAdmin(Permission::getUserId())) {
throw new CHttpException(500, "Empty \$_POST and \$_FILES. Probably post_max_size was exceeded.");
}
$return = array(
@@ -132,7 +134,7 @@ public function run($actionID)
Yii::app()->end();
}
- $sTempUploadDir = $tempdir.'/upload/';
+ $sTempUploadDir = $tempdir . '/upload/';
// Check if exists and is writable
if (!file_exists($sTempUploadDir)) {
// Try to create
@@ -149,7 +151,7 @@ public function run($actionID)
}
$aAttributes = QuestionAttribute::model()->getQuestionAttributes($aFieldMap[$sFieldName]['qid']);
$maxfilesize = min(intval($aAttributes['max_filesize']), getMaximumFileUploadSize() / 1024);
- if($maxfilesize <= 0 ) {
+ if ($maxfilesize <= 0) {
$maxfilesize = getMaximumFileUploadSize() / 1024;
}
/* Start to check upload error */
@@ -159,8 +161,8 @@ public function run($actionID)
"msg" => gT("Sorry, there was an error uploading your file.")
);
/* Show error code for user forcedSuperAdmin right */
- if( Permission::isForcedSuperAdmin(Permission::model()->getUserId()) ) {
- $return['msg'] = sprintf(gT("Sorry, there was an error uploading your file, error code : %s."),$_FILES['uploadfile']['error']);
+ if (Permission::isForcedSuperAdmin(Permission::model()->getUserId())) {
+ $return['msg'] = sprintf(gT("Sorry, there was an error uploading your file, error code : %s."), $_FILES['uploadfile']['error']);
}
//header('Content-Type: application/json');
echo ls_json_encode($return);
@@ -168,7 +170,7 @@ public function run($actionID)
}
/* Upload error due file size */
/* and check too $aAttributes['max_filesize'] */
- if ($size > $maxfilesize || $_FILES['uploadfile']['error'] == 1 || $_FILES['uploadfile']['error'] == 2 ) {
+ if ($size > $maxfilesize || $_FILES['uploadfile']['error'] == 1 || $_FILES['uploadfile']['error'] == 2) {
$return = array(
"success" => false,
"msg" => sprintf(gT("Sorry, this file is too large. Only files upto %s KB are allowed."), $maxfilesize)
@@ -183,8 +185,8 @@ public function run($actionID)
$pathinfo = pathinfo($_FILES['uploadfile']['name']);
$ext = strtolower($pathinfo['extension']);
$cleanExt = CHtml::encode($ext);
- $randfilename = 'futmp_'.randomChars(15).'_'.$pathinfo['extension'];
- $randfileloc = $sTempUploadDir.$randfilename;
+ $randfilename = 'futmp_' . randomChars(15) . '_' . $pathinfo['extension'];
+ $randfileloc = $sTempUploadDir . $randfilename;
// check to see that this file type is allowed
// it is also checked at the client side, but jst double checking
@@ -200,23 +202,23 @@ public function run($actionID)
/* extension checked : check mimeType */
$extByMimeType = LSFileHelper::getExtensionByMimeType($_FILES['uploadfile']['tmp_name'], null);
$disableCheck = false;
- if(is_null($extByMimeType)) {
+ if (is_null($extByMimeType)) {
/* Lack of finfo_open or mime_content_type ? But can be a not found extension too.*/
/* Check if can find mime type of favicon.ico , without extension */
/* Use CFileHelper because sure it work with included */
- if(empty(LSFileHelper::getMimeType(APPPATH."favicon.ico", null, null)) ) {
+ if (empty(LSFileHelper::getMimeType(APPPATH . "favicon.ico", null, null))) {
$disableCheck = true;
- Yii::log("Unable to check mime type of files, check for finfo_open or mime_content_type function.",\CLogger::LEVEL_ERROR,'application.controller.uploader.upload');
- if( YII_DEBUG || Permission::isForcedSuperAdmin(Permission::model()->getUserId()) ) {
+ Yii::log("Unable to check mime type of files, check for finfo_open or mime_content_type function.", \CLogger::LEVEL_ERROR, 'application.controller.uploader.upload');
+ if (YII_DEBUG || Permission::isForcedSuperAdmin(Permission::model()->getUserId())) {
/* This is a security issue and a server issue : always show at forced super admin */
throw new CHttpException(500, "Unable to check mime type of files, please activate FileInfo on server.");
}
}
}
- if(!$disableCheck && empty($extByMimeType)) {
+ if (!$disableCheck && empty($extByMimeType)) {
// FileInfo is OK, but can not find the mime type of file …
- $realMimeType = LSFileHelper::getMimeType($_FILES['uploadfile']['tmp_name'], null,false);
- Yii::log("Unable to extension for mime type ".$realMimeType,\CLogger::LEVEL_ERROR,'application.controller.uploader.upload');
+ $realMimeType = LSFileHelper::getMimeType($_FILES['uploadfile']['tmp_name'], null, false);
+ Yii::log("Unable to extension for mime type " . $realMimeType, \CLogger::LEVEL_ERROR, 'application.controller.uploader.upload');
$return = array(
"success" => false,
"msg" => sprintf(gT("Sorry, unable to check extension of this file type %s."), $realMimeType),
@@ -226,10 +228,10 @@ public function run($actionID)
Yii::app()->end();
}
if (!$disableCheck && !in_array($extByMimeType, $valid_extensions_array)) {
- $realMimeType = LSFileHelper::getMimeType($_FILES['uploadfile']['tmp_name'], null,false);
+ $realMimeType = LSFileHelper::getMimeType($_FILES['uploadfile']['tmp_name'], null, false);
$return = array(
"success" => false,
- "msg" => sprintf(gT("Sorry, file type %s (extension : %s) is not allowed!"), $realMimeType,$extByMimeType)
+ "msg" => sprintf(gT("Sorry, file type %s (extension : %s) is not allowed!"), $realMimeType, $extByMimeType)
);
//header('Content-Type: application/json');
echo ls_json_encode($return);
@@ -288,8 +290,8 @@ public function run($actionID)
"msg" => gT("An unknown error occured")
);
/* Add information for for user forcedSuperAdmin right */
- if( Permission::isForcedSuperAdmin(Permission::model()->getUserId()) ) {
- $return['msg'] = sprintf(gT("An unknown error happened when moving file %s to %s."),$_FILES['uploadfile']['tmp_name'],$randfileloc);
+ if (Permission::isForcedSuperAdmin(Permission::model()->getUserId())) {
+ $return['msg'] = sprintf(gT("An unknown error happened when moving file %s to %s."), $_FILES['uploadfile']['tmp_name'], $randfileloc);
}
//header('Content-Type: application/json');
echo ls_json_encode($return);
@@ -307,29 +309,29 @@ public function run($actionID)
$aSurveyInfo['templatedir'] = $event->get('template');
}
$sTemplateDir = getTemplatePath($aSurveyInfo['template']);
- $sTemplateUrl = getTemplateURL($aSurveyInfo['template'])."/";
+ $sTemplateUrl = getTemplateURL($aSurveyInfo['template']) . "/";
$oTemplate = Template::model()->getInstance('', $surveyid);
$sNeededScriptVar = '
- var uploadurl = uploadurl || "'.$this->createUrl('/uploader/index/mode/upload/').'";
- var imageurl = imageurl || "'.Yii::app()->getConfig('imageurl').'/";
- var surveyid = surveyid || "'.$surveyid.'";
- showpopups="'.$oTemplate->showpopups.'";
+ var uploadurl = uploadurl || "' . $this->createUrl('/uploader/index/mode/upload/') . '";
+ var imageurl = imageurl || "' . Yii::app()->getConfig('imageurl') . '/";
+ var surveyid = surveyid || "' . $surveyid . '";
+ showpopups="' . $oTemplate->showpopups . '";
';
$sLangScript = "{
- titleFld: '" . gT('Title', 'js')."',
- commentFld: '" . gT('Comment', 'js')."',
- filenameFld: '" . gT('File name', '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') . "',
+ filenameFld: '" . gT('File name', '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') . "'
}
";
@@ -352,7 +354,7 @@ public function run($actionID)
$maxfiles = (int) Yii::app()->request->getParam('maxfiles');
$qidattributes = QuestionAttribute::model()->getQuestionAttributes($qid);
$qidattributes['max_filesize'] = floor(min(intval($qidattributes['max_filesize']), getMaximumFileUploadSize() / 1024));
- if($qidattributes['max_filesize'] <=0 ) {
+ if ($qidattributes['max_filesize'] <= 0) {
$qidattributes['max_filesize'] = getMaximumFileUploadSize() / 1024;
}
$aData = [
@@ -366,24 +368,24 @@ public function run($actionID)
$body = '