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 .= '
'.gT('Error').'

'."\n"; - $sOutput .= $message.'

'."\n"; + $sOutput .= '
' . gT('Error') . '

' . "\n"; + $sOutput .= $message . '

' . "\n"; if (!empty($sURL) && !is_array($sURL)) { $sTitle = gT('Back'); } elseif (!empty($sURL['url'])) { @@ -89,9 +110,9 @@ public function error($message, $sURL = array()) $sTitle = gT('Main Admin Screen'); $sURL = $this->createUrl('/admin'); } - $sOutput .= '

'."\n"; - $sOutput .= '
'."\n"; - $sOutput .= ''."\n"; + $sOutput .= '

' . "\n"; + $sOutput .= '' . "\n"; + $sOutput .= '' . "\n"; echo $sOutput; $this->_getAdminFooter('http://manual.limesurvey.org', gT('LimeSurvey online manual')); @@ -149,7 +170,6 @@ public function run($action) if ($action != "databaseupdate" && $action != "db") { - if (empty($this->user_id) && $action != "authentication" && $action != "remotecontrol") { if (!empty($action) && $action != 'index') { Yii::app()->session['redirect_after_login'] = $this->createUrl('/'); @@ -168,7 +188,7 @@ public function run($action) $this->redirect(array('/admin/authentication/sa/login')); } elseif (!empty($this->user_id) && $action != "remotecontrol") { - if (Yii::app()->session['session_hash'] != hash('sha256', getGlobalSetting('SessionName').Yii::app()->user->getName().Yii::app()->user->getId())) { + if (Yii::app()->session['session_hash'] != hash('sha256', getGlobalSetting('SessionName') . Yii::app()->user->getName() . Yii::app()->user->getId())) { Yii::app()->session->clear(); Yii::app()->session->close(); $this->redirect(array('/admin/authentication/sa/login')); @@ -191,16 +211,16 @@ public function run($action) protected function runModuleController($action) { $aOverridenCoreActions = $this->getOverridenCoreAction(); - if (!empty($aOverridenCoreActions)){ - if (!empty($aOverridenCoreActions[$action])){ - $this->currentModuleAction = $action; // For subviews rendering, see: AdminController::renderPartial() - - // Since module's class has the same name has core class, we need to load the core and module classes with namespace - Yii::import('application\\controllers\\admin\\'.$action, true); - $sActionModuleClass = 'lsadminmodules\\'.$action.'\controller\\'.$action; - Yii::import($sActionModuleClass, true); - } - } + if (!empty($aOverridenCoreActions)) { + if (!empty($aOverridenCoreActions[$action])) { + $this->currentModuleAction = $action; // For subviews rendering, see: AdminController::renderPartial() + + // Since module's class has the same name has core class, we need to load the core and module classes with namespace + Yii::import('application\\controllers\\admin\\' . $action, true); + $sActionModuleClass = 'lsadminmodules\\' . $action . '\controller\\' . $action; + Yii::import($sActionModuleClass, true); + } + } } @@ -219,28 +239,27 @@ protected function runModuleController($action) * @see processOutput * @see render */ - public function renderPartial($view,$data=null,$return=false,$processOutput=false) - { - if (!empty($this->currentModuleAction) ){ + public function renderPartial($view, $data = null, $return = false, $processOutput = false) + { + if (!empty($this->currentModuleAction)) { // Standard: the views are stored in a folder that has the same name as the controler file. // TODO: check if it is the case for all controllers, if not normalize it, so 3rd party coder can easely extend any LS Core controller/action/view. - $sParsedView = explode(DIRECTORY_SEPARATOR, $view); - $sAction = (empty($sParsedView[1]))?'':$sParsedView[1]; + $sParsedView = explode(DIRECTORY_SEPARATOR, $view); + $sAction = (empty($sParsedView[1])) ? '' : $sParsedView[1]; // We allow a module to override only the controller views. - if ( $sAction == $this->currentModuleAction ){ - // Convert the view path to module view alias . - $sModulePath = 'lsadminmodules.' . $sAction . '.views' . substr(ltrim ( str_replace(DIRECTORY_SEPARATOR, '.',$view), '.'), strlen($sAction)) ; + if ($sAction == $this->currentModuleAction) { + // Convert the view path to module view alias . + $sModulePath = 'lsadminmodules.' . $sAction . '.views' . substr(ltrim(str_replace(DIRECTORY_SEPARATOR, '.', $view), '.'), strlen($sAction)) ; - if ( file_exists ( \Yii::getPathOfAlias($sModulePath) . '.php' ) ){ - $view = $sModulePath; + if (file_exists(\Yii::getPathOfAlias($sModulePath) . '.php')) { + $view = $sModulePath; + } } - - } } - return parent::renderPartial($view,$data,$return,$processOutput); - } + return parent::renderPartial($view, $data, $return, $processOutput); + } /** * Routes all the actions to their respective places @@ -265,13 +284,13 @@ public function actions() // We keep a trace of the overriden actions and their path. It will be used in the rendering logic (Survey_Common_Action, renderPartial, etc) foreach ($aModuleActions as $sAction => $sActionClass) { // Module override existing action - if (!empty($aActions[$sAction])){ - $this->aOverridenCoreActions[ $sAction ]['core'] = $aActions[$sAction]; - $this->aOverridenCoreActions[ $sAction ]['module'] = $aModuleActions[$sAction]; - } + if (!empty($aActions[$sAction])) { + $this->aOverridenCoreActions[ $sAction ]['core'] = $aActions[$sAction]; + $this->aOverridenCoreActions[ $sAction ]['module'] = $aModuleActions[$sAction]; + } } - $aActions = array_merge( $aActions, $aModuleActions); + $aActions = array_merge($aActions, $aModuleActions); return $aActions; } @@ -286,16 +305,16 @@ public function actions() */ public function getModulesActions() { - $aActions = $this->getAdminModulesActionClasses(); - $aAdminModulesClasses = array(); + $aActions = $this->getAdminModulesActionClasses(); + $aAdminModulesClasses = array(); // lsadminmodules alias is defined in AdminController::init() // Notice that the file and the directory name must be the same. - foreach ($aActions as $action => $class) { - $aActions[$action] = 'lsadminmodules\\'.$action.'\controller\\'.$action; - } + foreach ($aActions as $action => $class) { + $aActions[$action] = 'lsadminmodules\\' . $action . '\controller\\' . $action; + } - return $aActions; + return $aActions; } /** @@ -307,7 +326,7 @@ public function getModulesActions() */ protected function getOverridenCoreAction() { - if (empty($this->aOverridenCoreActions)){ + if (empty($this->aOverridenCoreActions)) { $this->actions(); } @@ -380,21 +399,21 @@ public function getAdminModulesActionClasses() { // This function is called at least twice by page load. Once from AdminController, another one by Survey_Common_Action - if (empty($this->aAdminModulesClasses)){ - $aAdminModulesClasses = array(); - $slsadminmodules = new DirectoryIterator(Yii::app()->getConfig('lsadminmodulesrootdir')); - Yii::setPathOfAlias('lsadminmodules', Yii::app()->getConfig('lsadminmodulesrootdir') ); - - foreach ($slsadminmodules as $fileinfo) { - if ($fileinfo->isDir() && !$fileinfo->isDot()) { - $sModuleName = $fileinfo->getFilename(); - $aAdminModulesClasses[$sModuleName] = $sModuleName; + if (empty($this->aAdminModulesClasses)) { + $aAdminModulesClasses = array(); + $slsadminmodules = new DirectoryIterator(Yii::app()->getConfig('lsadminmodulesrootdir')); + Yii::setPathOfAlias('lsadminmodules', Yii::app()->getConfig('lsadminmodulesrootdir')); + + foreach ($slsadminmodules as $fileinfo) { + if ($fileinfo->isDir() && !$fileinfo->isDot()) { + $sModuleName = $fileinfo->getFilename(); + $aAdminModulesClasses[$sModuleName] = $sModuleName; + } } + $this->aAdminModulesClasses = $aAdminModulesClasses; } - $this->aAdminModulesClasses = $aAdminModulesClasses; - } - return $this->aAdminModulesClasses; + return $this->aAdminModulesClasses; } /** @@ -432,7 +451,7 @@ public function _getAdminHeader($meta = false, $return = false) $aData['meta'] = $meta; } - $aData['baseurl'] = Yii::app()->baseUrl.'/'; + $aData['baseurl'] = Yii::app()->baseUrl . '/'; $aData['datepickerlang'] = ""; $aData['sitename'] = Yii::app()->getConfig("sitename"); @@ -479,7 +498,7 @@ public function _getAdminFooter($url, $explanation, $return = false) $aData['buildtext'] = ""; if (Yii::app()->getConfig("buildnumber") != "") { - $aData['buildtext'] = "+".Yii::app()->getConfig("buildnumber"); + $aData['buildtext'] = "+" . Yii::app()->getConfig("buildnumber"); } //If user is not logged in, don't print the version number information in the footer. @@ -494,7 +513,6 @@ public function _getAdminFooter($url, $explanation, $return = false) $aData['imageurl'] = Yii::app()->getConfig("imageurl"); $aData['url'] = $url; return $this->renderPartial("/admin/super/footer", $aData, $return); - } /** @@ -540,5 +558,4 @@ public function _loadEndScripts() return $this->renderPartial('/admin/endScripts_view', array()); } - } diff --git a/application/controllers/AssessmentController.php b/application/controllers/AssessmentController.php index 5ff75687328..5d454aafa38 100644 --- a/application/controllers/AssessmentController.php +++ b/application/controllers/AssessmentController.php @@ -1,6 +1,5 @@ currentLanguageSettings->surveyls_title." (".gT("ID").":".$iSurveyID.")"; + $aData['title_bar']['title'] = $oSurvey->currentLanguageSettings->surveyls_title . " (" . gT("ID") . ":" . $iSurveyID . ")"; $aData['gid'] = null; //important for rendering the sidebar ...(why?) Yii::app()->getClientScript()->registerScript( "AssessmentsVariables", - "var strnogroup = '".gT("There are no groups available.", "js")."',\n ';", + "var strnogroup = '" . gT("There are no groups available.", "js") . "',\n ';", LSYii_ClientScript::POS_BEGIN ); - App()->getClientScript()->registerScriptFile(App()->getConfig('adminscripts').'assessments.js', LSYii_ClientScript::POS_BEGIN); + App()->getClientScript()->registerScriptFile(App()->getConfig('adminscripts') . 'assessments.js', LSYii_ClientScript::POS_BEGIN); $this->aData = $aData; $this->render('assessments_view', $this->aData); @@ -108,7 +107,7 @@ public function actionActivate($surveyid) Yii::app()->setFlashMessage(gT("Assessment could not be activated."), 'error'); } - $this->redirect($this->createUrl('/assessment/index', ['surveyid' => $surveyid] )); + $this->redirect($this->createUrl('/assessment/index', ['surveyid' => $surveyid])); } /** @@ -131,7 +130,7 @@ public function actionInsertUpdate($surveyid) //this should not happen, unknown action Yii::app()->setFlashMessage(gT("Unknown action for asessment."), 'error'); - $this->redirect($this->createUrl('/assessment/index', ['surveyid' => $surveyid] )); + $this->redirect($this->createUrl('/assessment/index', ['surveyid' => $surveyid])); } /** @@ -147,7 +146,7 @@ public function actionDelete($surveyid) //must be deleteAll because of languages... $assessmentId = (int) App()->request->getPost('id'); Assessment::model()->deleteAllByAttributes(array('id' => $assessmentId, 'sid' => $iSurveyID)); - }else{ + } else { Yii::app()->setFlashMessage(gT("You have no permission to delete assessments"), 'error'); } } @@ -180,7 +179,7 @@ private function add($surveyid) } } } - $this->redirect($this->createUrl('/assessment/index', ['surveyid' => $surveyid] )); + $this->redirect($this->createUrl('/assessment/index', ['surveyid' => $surveyid])); } /** @@ -202,7 +201,7 @@ private function update($iSurveyID) $aData = $this->getAssessmentPostData($iSurveyID, $language); Assessment::model()->updateAssessment($aid, $iSurveyID, $language, $aData); } - $this->redirect($this->createUrl('/assessment/index', ['surveyid' => $iSurveyID] )); + $this->redirect($this->createUrl('/assessment/index', ['surveyid' => $iSurveyID])); } } @@ -223,8 +222,8 @@ public function actionEdit($surveyid) $aData['editData'] = $oAssessments[0]->attributes; foreach ($oAssessments as $oAssessment) { $aData['models'][] = $oAssessment; - $aData['editData']['name_'.$oAssessment->language] = $oAssessment->name; - $aData['editData']['assessmentmessage_'.$oAssessment->language] = $oAssessment->message; + $aData['editData']['name_' . $oAssessment->language] = $oAssessment->name; + $aData['editData']['assessmentmessage_' . $oAssessment->language] = $oAssessment->message; } $action = 'assessmentedit'; $aData['action'] = $action; @@ -387,9 +386,9 @@ private function getAssessmentPostData($iSurveyID, $language) 'gid' => App()->request->getPost('gid'), 'minimum' => (int) App()->request->getPost('minimum', 0), 'maximum' => (int) App()->request->getPost('maximum', 0), - 'name' => App()->request->getPost('name_'.$language), + 'name' => App()->request->getPost('name_' . $language), 'language' => $language, - 'message' => App()->request->getPost('assessmentmessage_'.$language) + 'message' => App()->request->getPost('assessmentmessage_' . $language) ); } diff --git a/application/controllers/HomepageSettingsController.php b/application/controllers/HomepageSettingsController.php index ee1511b881e..6dc913904bc 100644 --- a/application/controllers/HomepageSettingsController.php +++ b/application/controllers/HomepageSettingsController.php @@ -32,7 +32,7 @@ public function accessRules() */ public function beforeRender($view) { - App()->getClientScript()->registerScriptFile(App()->getConfig('adminscripts').'homepagesettings.js'); + App()->getClientScript()->registerScriptFile(App()->getConfig('adminscripts') . 'homepagesettings.js'); return parent::beforeRender($view); } @@ -55,12 +55,12 @@ public function actionIndex() $this->render('index', [ 'dataProviderBox' => $dataProviderBox, 'bShowLogo' => App()->getConfig('show_logo') == "show", - 'bShowLastSurveyAndQuestion'=> App()->getConfig('show_last_survey_and_question') == "show", - 'bShowSurveyList'=> App()->getConfig('show_survey_list') == "show", - 'bShowSurveyListSearch'=>App()->getConfig('show_survey_list_search') == "show", - 'bBoxesInContainer'=>App()->getConfig('boxes_in_container') == "yes", - 'iBoxesByRow'=>(int) App()->getConfig('boxes_by_row'), - 'iBoxesOffset'=> (int) App()->getConfig('boxes_offset'), + 'bShowLastSurveyAndQuestion' => App()->getConfig('show_last_survey_and_question') == "show", + 'bShowSurveyList' => App()->getConfig('show_survey_list') == "show", + 'bShowSurveyListSearch' => App()->getConfig('show_survey_list_search') == "show", + 'bBoxesInContainer' => App()->getConfig('boxes_in_container') == "yes", + 'iBoxesByRow' => (int) App()->getConfig('boxes_by_row'), + 'iBoxesOffset' => (int) App()->getConfig('boxes_offset'), ]); } @@ -76,7 +76,7 @@ public function actionCreateBox() $this->redirect($this->createUrl("/homepageSettings/index")); } - $model = new Box; + $model = new Box(); if (isset($_POST['Box'])) { if (Yii::app()->getConfig('demoMode')) { Yii::app()->setFlashMessage(gT('This setting cannot be changed because demo mode is active.'), 'error'); @@ -88,7 +88,7 @@ public function actionCreateBox() if (isset($_POST['saveandclose'])) { $this->redirect(array('/homepageSettings/index')); } else { - $this->redirect(array('/homepageSettings/updateBox/id/'.$model->id)); + $this->redirect(array('/homepageSettings/updateBox/id/' . $model->id)); } } else { Yii::app()->user->setFlash('error', gT('Could not create new box')); diff --git a/application/controllers/InstallerController.php b/application/controllers/InstallerController.php index 12be6964e74..7ec0375fabd 100644 --- a/application/controllers/InstallerController.php +++ b/application/controllers/InstallerController.php @@ -1,4 +1,6 @@ -stepWelcome(); break; @@ -85,11 +86,10 @@ public function run($action = 'index') $this->stepOptionalConfiguration(); break; - case 'index' : - default : + case 'index': + default: $this->redirect(array('installer/welcome')); break; - } } @@ -102,7 +102,7 @@ public function run($action = 'index') */ private function _checkInstallation() { - if (file_exists(APPPATH.'config/config.php')) { + if (file_exists(APPPATH . 'config/config.php')) { throw new CHttpException(500, 'Installation has been done already. Installer disabled.'); } } @@ -178,7 +178,7 @@ private function stepLicense() public function stepViewLicense() { header('Content-Type: text/plain; charset=UTF-8'); - readfile(dirname((string) BASEPATH).'/LICENSE'); + readfile(dirname((string) BASEPATH) . '/LICENSE'); exit; } @@ -192,7 +192,7 @@ private function stepPreInstallationCheck() $aData = []; $aData['model'] = $oModel; $aData['title'] = gT('Pre-installation check'); - $aData['descp'] = gT('Pre-installation check for LimeSurvey ').Yii::app()->getConfig('versionnumber'); + $aData['descp'] = gT('Pre-installation check for LimeSurvey ') . Yii::app()->getConfig('versionnumber'); $aData['classesForStep'] = array('off', 'off', 'on', 'off', 'off', 'off'); $aData['progressValue'] = 20; // variable storing next button link.initially null @@ -232,12 +232,12 @@ private function stepDatabaseConfiguration() $aData['descp'] = gT('Please enter the database settings you want to use for LimeSurvey:'); $aData['classesForStep'] = array('off', 'off', 'off', 'on', 'off', 'off'); $aData['progressValue'] = 40; - $aData['model'] = $oModel = new InstallerConfigForm; + $aData['model'] = $oModel = new InstallerConfigForm(); if (!empty(Yii::app()->session['populateerror'])) { - if(is_string(Yii::app()->session['populateerror'])) { + if (is_string(Yii::app()->session['populateerror'])) { $oModel->addError('dblocation', Yii::app()->session['populateerror']); } else { - foreach(Yii::app()->session['populateerror'] as $error) { + foreach (Yii::app()->session['populateerror'] as $error) { $oModel->addError('dblocation', $error); } } @@ -251,7 +251,6 @@ private function stepDatabaseConfiguration() //run validation, if it fails, load the view again else proceed to next step. if ($oModel->validate()) { - //saving the form data to session foreach (array('dblocation', 'dbname', 'dbengine', 'dbtype', 'dbpwd', 'dbuser', 'dbprefix') as $sStatusKey) { Yii::app()->session[$sStatusKey] = $oModel->$sStatusKey; @@ -286,9 +285,9 @@ private function stepDatabaseConfiguration() //Write config file as we no longer redirect to optional view $this->_writeConfigFile(); - header("refresh:5;url=".$this->createUrl("/admin")); + header("refresh:5;url=" . $this->createUrl("/admin")); $aData['noticeMessage'] = gT('The database exists and contains LimeSurvey tables.'); - $aData['text'] = sprintf(gT("You'll be redirected to the database update or (if your database is already up to date) to the administration login in 5 seconds. If not, please click %shere%s."), "", ""); + $aData['text'] = sprintf(gT("You'll be redirected to the database update or (if your database is already up to date) to the administration login in 5 seconds. If not, please click %shere%s."), "", ""); $this->render('/installer/redirectmessage_view', $aData); exit(); } @@ -329,8 +328,8 @@ private function stepDatabaseConfiguration() //$this->connection->database = $model->dbname; // //$this->connection->createCommand("USE DATABASE `".$model->dbname."`")->execute(); - $aValues['adminoutputText'] .= sprintf(gT('A database named "%s" already exists.'), $oModel->dbname)."

\n" - .gT("Do you want to populate that database now by creating the necessary tables?")."

"; + $aValues['adminoutputText'] .= sprintf(gT('A database named "%s" already exists.'), $oModel->dbname) . "

\n" + . gT("Do you want to populate that database now by creating the necessary tables?") . "

"; $aValues['next'] = array( 'action' => 'installer/populatedb', @@ -338,7 +337,7 @@ private function stepDatabaseConfiguration() 'name' => 'createdbstep2', ); } elseif (!$bDBExistsButEmpty) { - $aValues['adminoutput'] .= "
".sprintf(gT('Please log in.', 'unescaped'), $this->createUrl("/admin")); + $aValues['adminoutput'] .= "
" . sprintf(gT('Please log in.', 'unescaped'), $this->createUrl("/admin")); } $this->render('/installer/populatedb_view', $aValues); return; @@ -382,9 +381,9 @@ public function stepCreateDb() unset(Yii::app()->session['databaseDontExist']); $aData['adminoutputText'] = "" - ."
\n" - .gT("Database has been created.")."
\n" - .gT("Please continue with populating the database.")."

\n"; + . "
\n" + . gT("Database has been created.") . "
\n" + . gT("Please continue with populating the database.") . "

\n"; $aData['next'] = array( 'action' => 'installer/populatedb', 'label' => gT("Populate database"), @@ -475,7 +474,6 @@ private function stepOptionalConfiguration() //run validation, if it fails, load the view again else proceed to next step. if ($model->validate()) { - $aData['title'] = gT("Database configuration"); $aData['descp'] = gT("Please enter the database settings you want to use for LimeSurvey:"); $aData['classesForStep'] = array('off', 'off', 'off', 'on', 'off', 'off'); @@ -496,13 +494,12 @@ private function stepOptionalConfiguration() //checking DB Connection if ($model->db->getActive() == true) { try { - if (User::model()->count() > 0) { safeDie('Fatal error: Already an admin user in the system.'); } // Save user - $user = new User; + $user = new User(); // Fix UserID to 1 for MySQL even if installed in master-master configuration scenario if ($model->isMysql) { $user->uid = 1; @@ -516,7 +513,7 @@ private function stepOptionalConfiguration() $user->save(); // Save permissions - $permission = new Permission; + $permission = new Permission(); $permission->entity_id = 0; $permission->entity = 'global'; $permission->uid = $user->uid; @@ -552,11 +549,9 @@ private function stepOptionalConfiguration() $this->render('/installer/success_view', $aData); return; - } catch (Exception $e) { throw new Exception(sprintf('Could not add administrator settings: %s.', $e)); } - } } else { unset($aData['confirmation']); @@ -574,7 +569,7 @@ private function stepOptionalConfiguration() */ public function loadHelper($helper) { - Yii::import('application.helpers.'.$helper.'_helper', true); + Yii::import('application.helpers.' . $helper . '_helper', true); } /** @@ -585,7 +580,7 @@ public function loadHelper($helper) */ public function loadLibrary($library) { - Yii::import('application.libraries.'.$library, true); + Yii::import('application.libraries.' . $library, true); } /** @@ -613,9 +608,11 @@ public function is_writable_recursive($sDirectory) return false; // Dir does not exist } while ($sFile = readdir($sFolder)) { - if ($sFile != '.' && $sFile != '..' && - (!is_writable($sDirectory."/".$sFile) || - (is_dir($sDirectory."/".$sFile) && !$this->is_writable_recursive($sDirectory."/".$sFile)))) { + if ( + $sFile != '.' && $sFile != '..' && + (!is_writable($sDirectory . "/" . $sFile) || + (is_dir($sDirectory . "/" . $sFile) && !$this->is_writable_recursive($sDirectory . "/" . $sFile))) + ) { closedir($sFolder); return false; } @@ -651,8 +648,8 @@ public function checkPHPFunction($sFunctionName, &$sImage) public function checkPathWriteable($path, $type, &$aData, $base, $keyError, $bRecursive = false) { $bResult = false; - $aData[$base.'Present'] = 'Not Found'; - $aData[$base.'Writable'] = ''; + $aData[$base . 'Present'] = 'Not Found'; + $aData[$base . 'Writable'] = ''; switch ($type) { case 1: $exists = is_file($path); @@ -664,12 +661,12 @@ public function checkPathWriteable($path, $type, &$aData, $base, $keyError, $bRe throw new Exception('Invalid type given.'); } if ($exists) { - $aData[$base.'Present'] = 'Found'; + $aData[$base . 'Present'] = 'Found'; if ((!$bRecursive && is_writable($path)) || ($bRecursive && $this->is_writable_recursive($path))) { - $aData[$base.'Writable'] = 'Writable'; + $aData[$base . 'Writable'] = 'Writable'; $bResult = true; } else { - $aData[$base.'Writable'] = 'Unwritable'; + $aData[$base . 'Writable'] = 'Unwritable'; } } $bResult || $aData[$keyError] = true; @@ -731,7 +728,7 @@ private function _check_requirements(&$aData) $bProceed = false; } - // zlib library check + // zlib library check if (!$this->checkPHPFunction('zlib_get_coding_type', $aData['zlibPresent'])) { $bProceed = false; } @@ -744,17 +741,17 @@ private function _check_requirements(&$aData) // ** file and directory permissions checking ** // config directory - if (!$this->checkDirectoryWriteable(Yii::app()->getConfig('rootdir').'/application/config', $aData, 'config', 'derror')) { + if (!$this->checkDirectoryWriteable(Yii::app()->getConfig('rootdir') . '/application/config', $aData, 'config', 'derror')) { $bProceed = false; } // templates directory check - if (!$this->checkDirectoryWriteable(Yii::app()->getConfig('tempdir').'/', $aData, 'tmpdir', 'tperror', true)) { + if (!$this->checkDirectoryWriteable(Yii::app()->getConfig('tempdir') . '/', $aData, 'tmpdir', 'tperror', true)) { $bProceed = false; } //upload directory check - if (!$this->checkDirectoryWriteable(Yii::app()->getConfig('uploaddir').'/', $aData, 'uploaddir', 'uerror', true)) { + if (!$this->checkDirectoryWriteable(Yii::app()->getConfig('uploaddir') . '/', $aData, 'uploaddir', 'uerror', true)) { $bProceed = false; } @@ -826,7 +823,7 @@ public function _executeSQLFile($sFileName, $sDatabasePrefix) try { $this->connection->createCommand($sCommand)->execute(); } catch (Exception $e) { - $aMessages[] = "Executing: ".$sCommand." failed! Reason: ".$e; + $aMessages[] = "Executing: " . $sCommand . " failed! Reason: " . $e; } $sCommand = ''; @@ -874,30 +871,30 @@ private function _writeConfigFile() } if ($model->dbtype) { - $sConfig = " dirname(dirname(__FILE__))," . "\n" ."\t" . "'runtimePath' => dirname(dirname(dirname(__FILE__))).DIRECTORY_SEPARATOR.'tmp'.DIRECTORY_SEPARATOR.'runtime'," . "\n" @@ -913,35 +910,34 @@ private function _writeConfigFile() ."\t" . ")," . "\n" ."\t" . "" . "\n" */ - ."\t"."'components' => array("."\n" - ."\t\t"."'db' => array("."\n" - ."\t\t\t"."'connectionString' => '$sDsn',"."\n"; + . "\t" . "'components' => array(" . "\n" + . "\t\t" . "'db' => array(" . "\n" + . "\t\t\t" . "'connectionString' => '$sDsn'," . "\n"; } if ($model->dbtype != InstallerConfigForm::DB_TYPE_SQLSRV && $model->dbtype != InstallerConfigForm::DB_TYPE_DBLIB) { - $sConfig .= "\t\t\t"."'emulatePrepare' => true,"."\n"; - + $sConfig .= "\t\t\t" . "'emulatePrepare' => true," . "\n"; } - $sConfig .= "\t\t\t"."'username' => '".addcslashes($model->dbuser, "'")."',"."\n" - ."\t\t\t"."'password' => '".addcslashes($model->dbpwd, "'")."',"."\n" - ."\t\t\t"."'charset' => '{$sCharset}',"."\n" - ."\t\t\t"."'tablePrefix' => '{$model->dbprefix}',"."\n"; + $sConfig .= "\t\t\t" . "'username' => '" . addcslashes($model->dbuser, "'") . "'," . "\n" + . "\t\t\t" . "'password' => '" . addcslashes($model->dbpwd, "'") . "'," . "\n" + . "\t\t\t" . "'charset' => '{$sCharset}'," . "\n" + . "\t\t\t" . "'tablePrefix' => '{$model->dbprefix}'," . "\n"; if ($model->isMSSql) { - $sConfig .= "\t\t\t"."'initSQLs'=>array('SET DATEFORMAT ymd;','SET QUOTED_IDENTIFIER ON;'),"."\n"; + $sConfig .= "\t\t\t" . "'initSQLs'=>array('SET DATEFORMAT ymd;','SET QUOTED_IDENTIFIER ON;')," . "\n"; } - $sConfig .= "\t\t"."),"."\n" - ."\t\t".""."\n" + $sConfig .= "\t\t" . ")," . "\n" + . "\t\t" . "" . "\n" - ."\t\t"." 'session' => array ("."\n" - ."\t\t\t"."'sessionName'=>'LS-".$this->_getRandomString(16)."'".",\n" - ."\t\t\t"."// Uncomment the following lines if you need table-based sessions."."\n" - ."\t\t\t"."// Note: Table-based sessions are currently not supported on MSSQL server."."\n" - ."\t\t\t"."// 'class' => 'application.core.web.DbHttpSession',"."\n" - ."\t\t\t"."// 'connectionID' => 'db',"."\n" - ."\t\t\t"."// 'sessionTableName' => '{{sessions}}',"."\n" - ."\t\t"." ),"."\n" - ."\t\t".""."\n" + . "\t\t" . " 'session' => array (" . "\n" + . "\t\t\t" . "'sessionName'=>'LS-" . $this->_getRandomString(16) . "'" . ",\n" + . "\t\t\t" . "// Uncomment the following lines if you need table-based sessions." . "\n" + . "\t\t\t" . "// Note: Table-based sessions are currently not supported on MSSQL server." . "\n" + . "\t\t\t" . "// 'class' => 'application.core.web.DbHttpSession'," . "\n" + . "\t\t\t" . "// 'connectionID' => 'db'," . "\n" + . "\t\t\t" . "// 'sessionTableName' => '{{sessions}}'," . "\n" + . "\t\t" . " )," . "\n" + . "\t\t" . "" . "\n" /** @todo Uncomment after implementing the error controller */ /* @@ -951,47 +947,47 @@ private function _writeConfigFile() ."\t\t" . "" . "\n" */ - ."\t\t"."'urlManager' => array("."\n" - ."\t\t\t"."'urlFormat' => '{$sURLFormat}',"."\n" - ."\t\t\t"."'rules' => array("."\n" - ."\t\t\t\t"."// You can add your own rules here"."\n" - ."\t\t\t"."),"."\n" - ."\t\t\t"."'showScriptName' => {$sShowScriptName},"."\n" - ."\t\t"."),"."\n" - ."\t".""."\n" - - ."\t"."),"."\n" - ."\t"."// For security issue : it's better to set runtimePath out of web access"."\n" - ."\t"."// Directory must be readable and writable by the webuser"."\n" - ."\t"."// 'runtimePath'=>'/var/limesurvey/runtime/'"."\n" - ."\t"."// Use the following config variable to set modified optional settings copied from config-defaults.php"."\n" - ."\t"."'config'=>array("."\n" - ."\t"."// debug: Set this to 1 if you are looking for errors. If you still get no errors after enabling this"."\n" - ."\t"."// then please check your error-logs - either in your hosting provider admin panel or in some /logs directory"."\n" - ."\t"."// on your webspace."."\n" - ."\t"."// LimeSurvey developers: Set this to 2 to additionally display STRICT PHP error messages and get full access to standard templates"."\n" - ."\t\t"."'debug'=>0,"."\n" - ."\t\t"."'debugsql'=>0, // Set this to 1 to enanble sql logging, only active when debug = 2"."\n"; + . "\t\t" . "'urlManager' => array(" . "\n" + . "\t\t\t" . "'urlFormat' => '{$sURLFormat}'," . "\n" + . "\t\t\t" . "'rules' => array(" . "\n" + . "\t\t\t\t" . "// You can add your own rules here" . "\n" + . "\t\t\t" . ")," . "\n" + . "\t\t\t" . "'showScriptName' => {$sShowScriptName}," . "\n" + . "\t\t" . ")," . "\n" + . "\t" . "" . "\n" + + . "\t" . ")," . "\n" + . "\t" . "// For security issue : it's better to set runtimePath out of web access" . "\n" + . "\t" . "// Directory must be readable and writable by the webuser" . "\n" + . "\t" . "// 'runtimePath'=>'/var/limesurvey/runtime/'" . "\n" + . "\t" . "// Use the following config variable to set modified optional settings copied from config-defaults.php" . "\n" + . "\t" . "'config'=>array(" . "\n" + . "\t" . "// debug: Set this to 1 if you are looking for errors. If you still get no errors after enabling this" . "\n" + . "\t" . "// then please check your error-logs - either in your hosting provider admin panel or in some /logs directory" . "\n" + . "\t" . "// on your webspace." . "\n" + . "\t" . "// LimeSurvey developers: Set this to 2 to additionally display STRICT PHP error messages and get full access to standard templates" . "\n" + . "\t\t" . "'debug'=>0," . "\n" + . "\t\t" . "'debugsql'=>0, // Set this to 1 to enanble sql logging, only active when debug = 2" . "\n"; if ($model->isMysql) { - $sConfig .= "\t\t"."// Mysql database engine (INNODB|MYISAM):"."\n" - ."\t\t 'mysqlEngine' => '{$model->dbengine}'\n\n,"; + $sConfig .= "\t\t" . "// Mysql database engine (INNODB|MYISAM):" . "\n" + . "\t\t 'mysqlEngine' => '{$model->dbengine}'\n\n,"; } - $sConfig .= "\t\t"."// Update default LimeSurvey config here"."\n" - ."\t".")"."\n" - . ");"."\n" - . "/* End of file config.php */"."\n" + $sConfig .= "\t\t" . "// Update default LimeSurvey config here" . "\n" + . "\t" . ")" . "\n" + . ");" . "\n" + . "/* End of file config.php */" . "\n" . "/* Location: ./application/config/config.php */"; - if (is_writable(APPPATH.'config')) { - file_put_contents(APPPATH.'config/config.php', $sConfig); + if (is_writable(APPPATH . 'config')) { + file_put_contents(APPPATH . 'config/config.php', $sConfig); Yii::app()->session['configFileWritten'] = true; $oUrlManager = Yii::app()->getComponent('urlManager'); /* @var $oUrlManager CUrlManager */ $oUrlManager->setUrlFormat($sURLFormat); } else { - header('refresh:5;url='.$this->createUrl("installer/welcome")); - echo "".gT("Configuration directory is not writable")."
"; + header('refresh:5;url=' . $this->createUrl("installer/welcome")); + echo "" . gT("Configuration directory is not writable") . "
"; printf(gT('You will be redirected in about 5 secs. If not, click here.', 'unescaped'), $this->createUrl('installer/welcome')); Yii::app()->end(); } @@ -1003,7 +999,7 @@ private function _writeConfigFile() * * @return string */ - private function _getRandomString($iTotalChar=64) + private function _getRandomString($iTotalChar = 64) { $sResult = ''; for ($i = 0; $i < $iTotalChar; $i++) { @@ -1037,7 +1033,8 @@ private function getModelFromSession($scenario = null) /** * clear the session from installation information */ - private function clearSession() { + private function clearSession() + { unset(Yii::app()->session['dbtype']); unset(Yii::app()->session['dbengine']); unset(Yii::app()->session['dbname']); @@ -1101,9 +1098,8 @@ private function checkDefaultExtensions() foreach ($extensions as $extension) { if (!extension_loaded($extension)) { - safeDie('You\'re missing default PHP extension '.$extension); + safeDie('You\'re missing default PHP extension ' . $extension); } } - } } diff --git a/application/controllers/LSBaseController.php b/application/controllers/LSBaseController.php index ab19db003a7..00cbcba5f4e 100644 --- a/application/controllers/LSBaseController.php +++ b/application/controllers/LSBaseController.php @@ -38,16 +38,36 @@ protected function _init() $this->userId = Yii::app()->user->getId(); - 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 AdminTheme::getInstance(); @@ -178,7 +198,7 @@ protected function sessionControl() * @param array $aData * @return void */ - protected function renderJSON($aData, $success=true) + protected function renderJSON($aData, $success = true) { $aData['success'] = $aData['success'] ?? $success; diff --git a/application/controllers/LimereplacementfieldsController.php b/application/controllers/LimereplacementfieldsController.php index ddaa4a296c8..1643e2095a5 100644 --- a/application/controllers/LimereplacementfieldsController.php +++ b/application/controllers/LimereplacementfieldsController.php @@ -1,4 +1,5 @@ findByPk($surveyid); $oCurrentQuestion = Question::model()->findByPk($qid); $aResult = []; @@ -485,16 +483,16 @@ private function collectQuestionReplacements($surveyid, $gid = null, $qid = null if ($gid != null && $qid == null) { $oGroup = QuestionGroup::model()->findByPk($gid); $oCriteria->with = ['group']; - $oCriteria->compare('group_order', '<='.$oGroup->group_order); + $oCriteria->compare('group_order', '<=' . $oGroup->group_order); } if ($qid != null) { $oCriteria->with = ['group']; - $oCriteria->compare('group_order', '<='.$oCurrentQuestion->group->group_order); + $oCriteria->compare('group_order', '<=' . $oCurrentQuestion->group->group_order); if ($oCurrentQuestion->parent_qid != 0) { - $oCriteria->compare('question_order', '<'.$oCurrentQuestion->parent->question_order); + $oCriteria->compare('question_order', '<' . $oCurrentQuestion->parent->question_order); } else { - $oCriteria->compare('question_order', '<'.$oCurrentQuestion->question_order); + $oCriteria->compare('question_order', '<' . $oCurrentQuestion->question_order); } } @@ -502,12 +500,13 @@ private function collectQuestionReplacements($surveyid, $gid = null, $qid = null uasort( $aQuestions, - function ($a,$b) { - if ($a->gid != $b->gid) { - return $a->group->group_order < $b->group->group_order ? -1 : 1; + function ($a, $b) { + if ($a->gid != $b->gid) { + return $a->group->group_order < $b->group->group_order ? -1 : 1; + } + return $a->question_order < $b->question_order ? -1 : 1; } - return $a->question_order < $b->question_order ? -1 : 1; - }); + ); foreach ($aQuestions as $oQuestion) { if ($oCurrentQuestion != null && $oCurrentQuestion->qid == $oQuestion->qid) { @@ -517,12 +516,14 @@ function ($a,$b) { if (safecount($oQuestion->subquestions) != 0) { $aSubquestions = $oQuestion->subquestions; - uasort($aSubquestions, function ($a,$b) { return $a->question_order < $b->question_order ? -1 : 1; }); + uasort($aSubquestions, function ($a, $b) { + return $a->question_order < $b->question_order ? -1 : 1; + }); foreach ($aSubquestions as $oSubQuestion) { - $aResult[$oQuestion->title.'_'.$oSubQuestion->title] = [ + $aResult[$oQuestion->title . '_' . $oSubQuestion->title] = [ 'type' => 'question', - 'value' => ' -('.$oQuestion->title.')| '.$oSubQuestion->questionl10ns[$oSurvey->language]->question + 'value' => ' -(' . $oQuestion->title . ')| ' . $oSubQuestion->questionl10ns[$oSurvey->language]->question ]; } } else { @@ -535,4 +536,3 @@ function ($a,$b) { return $aResult; } } - diff --git a/application/controllers/OptinController.php b/application/controllers/OptinController.php index 1089c4ee519..573078c47db 100644 --- a/application/controllers/OptinController.php +++ b/application/controllers/OptinController.php @@ -1,4 +1,6 @@ -request->getQuery('surveyid'); - $sLanguageCode = Yii::app()->request->getQuery('langcode'); - $sToken = Token::sanitizeToken(Yii::app()->request->getQuery('token')); - $oSurvey = Survey::model()->findByPk($iSurveyID); + function actiontokens() + { - Yii::app()->loadHelper('database'); - Yii::app()->loadHelper('sanitize'); - //IF there is no survey id, redirect back to the default public page - if (!$iSurveyID) { - $this->redirect(array('/')); - } + $iSurveyID = Yii::app()->request->getQuery('surveyid'); + $sLanguageCode = Yii::app()->request->getQuery('langcode'); + $sToken = Token::sanitizeToken(Yii::app()->request->getQuery('token')); + $oSurvey = Survey::model()->findByPk($iSurveyID); - $iSurveyID = (int) $iSurveyID; //Make sure it's an integer (protect from SQL injects) - //Check that there is a SID - // Get passed language from form, so that we dont lose this! - if (!isset($sLanguageCode) || $sLanguageCode == "" || !$sLanguageCode) { - $sBaseLanguage = $oSurvey->language; - } else { - $sBaseLanguage = sanitize_languagecode($sLanguageCode); - } + Yii::app()->loadHelper('database'); + Yii::app()->loadHelper('sanitize'); - Yii::app()->setLanguage($sBaseLanguage); + //IF there is no survey id, redirect back to the default public page + if (!$iSurveyID) { + $this->redirect(array('/')); + } - $aSurveyInfo = getSurveyInfo($iSurveyID, $sBaseLanguage); + $iSurveyID = (int) $iSurveyID; //Make sure it's an integer (protect from SQL injects) + //Check that there is a SID + // Get passed language from form, so that we dont lose this! + if (!isset($sLanguageCode) || $sLanguageCode == "" || !$sLanguageCode) { + $sBaseLanguage = $oSurvey->language; + } else { + $sBaseLanguage = sanitize_languagecode($sLanguageCode); + } - 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.")."

"; - $sMessage .= '

'.gT("I confirm").'

'; - $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.") . "

"; + $sMessage .= '

' . gT("I confirm") . '

'; + $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 = ''; $scripts = ""; $container = $this->renderPartial('/survey/questions/answer/file_upload/modal-container', $aData, true); - $body .= $container.$scripts; + $body .= $container . $scripts; $body .= ' '; App()->getClientScript()->render($body); diff --git a/application/controllers/UserGroupController.php b/application/controllers/UserGroupController.php index 40ccc25fa3c..1abef3776f6 100644 --- a/application/controllers/UserGroupController.php +++ b/application/controllers/UserGroupController.php @@ -1,6 +1,5 @@ findByPk($ugid); $uid = Yii::app()->user->id; - if ($userGroup && - ($userGroup->hasUser($uid) || Permission::model()->hasGlobalPermission('superadmin', 'read'))) { + if ( + $userGroup && + ($userGroup->hasUser($uid) || Permission::model()->hasGlobalPermission('superadmin', 'read')) + ) { $aData['userGroup'] = $userGroup; } } else { @@ -138,7 +139,7 @@ public function actionViewGroup($ugid, $header = false) } $userloop[$row]["userid"] = $oUser->uid; - // output users + // output users $userloop[$row]["rowclass"] = $bgcc; if (Permission::model()->hasGlobalPermission('usergroups', 'update') && $oUser->parent_id == Yii::app()->session['loginID']) { $userloop[$row]["displayactions"] = true; @@ -263,7 +264,7 @@ public function actionAddGroup() $this->redirect(array('userGroup/index')); } else { //show error msg - $errors= $model->getErrors(); + $errors = $model->getErrors(); //show only the first error, so the user could fix them one by one ... foreach ($errors as $key => $value) { $firstError = $key; @@ -309,7 +310,7 @@ public function actionDeleteGroup() ]); } - if ($model!==null && $model->delete()) { + if ($model !== null && $model->delete()) { Yii::app()->user->setFlash("success", gT("Successfully deleted user group.")); } else { Yii::app()->user->setFlash("error", gT("Could not delete user group.")); @@ -442,7 +443,7 @@ public function actionMailToAllUsersInGroup($ugid) $result = UserInGroup::model()->findAllByPk(array('ugid' => (int)$ugid, 'uid' => Yii::app()->session['loginID'])); if (count($result) > 0 || Permission::model()->hasGlobalPermission('superadmin', 'read')) { try { - $sendCopy = Yii::app()->getRequest()->getPost('copymail')==1 ? 1 :0; + $sendCopy = Yii::app()->getRequest()->getPost('copymail') == 1 ? 1 : 0; $emailSendingResults = UserGroup::model()->sendUserEmails( $ugid, Yii::app()->getRequest()->getPost('subject'), diff --git a/application/controllers/UserManagementController.php b/application/controllers/UserManagementController.php index d5dce8203f6..85dbd7a6693 100644 --- a/application/controllers/UserManagementController.php +++ b/application/controllers/UserManagementController.php @@ -1,6 +1,5 @@ hasGlobalPermission('users', 'create')) + if ( + ($userid === null && !Permission::model()->hasGlobalPermission('users', 'create')) || ($userid !== null && !Permission::model()->hasGlobalPermission('users', 'update')) ) { return $this->renderPartial( @@ -158,7 +158,6 @@ public function actionApplyEdit() ] ]); } else { - //generate random password when password is empty if (empty($aUser['password'])) { $newPassword = $this->getRandomPassword(8); @@ -207,7 +206,7 @@ public function actionRunAddDummyUser() for (; $times > 0; $times--) { $name = $this->getRandomUsername($prefix); $password = $this->getRandomPassword($passwordSize); - $oUser = new User; + $oUser = new User(); $oUser->users_name = $name; $oUser->full_name = $name; $oUser->email = $email; @@ -254,7 +253,7 @@ public function actionDeleteUser() $transferTo = Yii::app()->request->getPost('transfer_surveys_to'); if (empty($transferTo)) { - // If $transferTo is empty, check if user owns a survey. + // If $transferTo is empty, check if user owns a survey. // If so, render the "transfer to" selection screen $aOwnedSurveys = Survey::model()->findAllByAttributes(array('owner_id' => $userId)); if (count($aOwnedSurveys)) { @@ -474,8 +473,10 @@ public function actionUserTemplatePermissions() */ public function actionSaveThemePermissions() { - if (!(Permission::model()->hasGlobalPermission('users', 'update') && - Permission::model()->hasGlobalPermission('templates', 'update'))) { + if ( + !(Permission::model()->hasGlobalPermission('users', 'update') && + Permission::model()->hasGlobalPermission('templates', 'update')) + ) { return $this->renderPartial( 'partial/error', ['errors' => [gT("You do not have permission to access this page.")], 'noButton' => true] @@ -1160,7 +1161,6 @@ public function updateAdminUser($aUser) private function createAdminUser($aUser) { if (!isset($aUser['uid']) || $aUser['uid'] == null) { - $newUser = $this->createNewUser($aUser); $sReturnMessage = gT('User successfully created'); $success = true; @@ -1276,7 +1276,7 @@ public function createNewUser($aUser) public function sendAdminMail($aUser, $type = 'registration') { //Get email template from globalSettings - $aAdminEmail = $this->generateAdminCreationEmail($aUser['full_name'], $aUser['users_name'], $aUser['password'], $aUser['uid']); + $aAdminEmail = $this->generateAdminCreationEmail($aUser['full_name'], $aUser['users_name'], $aUser['password'], $aUser['uid']); $body = ""; switch ($type) { @@ -1309,7 +1309,7 @@ public function sendAdminMail($aUser, $type = 'registration') $oCurrentlyLoggedInUser = User::model()->findByPk(Yii::app()->user->id); - $mailer = new LimeMailer; + $mailer = new LimeMailer(); $mailer->addAddress($aUser['email'], $aUser['full_name']); $mailer->Subject = $subject; $mailer->setFrom($oCurrentlyLoggedInUser->email, $oCurrentlyLoggedInUser->users_name); @@ -1401,11 +1401,11 @@ protected function getRandomString() /** - * + * * This function prepare the email template to send to the new created user - * @param string $fullname - * @param string $username - * @param string $password + * @param string $fullname + * @param string $username + * @param string $password * @return mixed $aAdminEmail array with subject and email nody */ public function generateAdminCreationEmail($fullname, $username, $password, $iNewUID) diff --git a/application/controllers/VerificationController.php b/application/controllers/VerificationController.php index 12f43b8f44a..9d2174590ee 100644 --- a/application/controllers/VerificationController.php +++ b/application/controllers/VerificationController.php @@ -1,4 +1,6 @@ -languageFilter($lang)); } else { $aLangs = $oSurvey->allLanguages; @@ -57,30 +58,30 @@ public function quota($iSurveyId, $quota, $lang = null) $aExpressions = array(); $this->iSurveyId = $iSurveyId; foreach ($aLangs as $sLang) { - $oQuotaLanguageSetting = QuotaLanguageSetting::model()->find("quotals_quota_id =:quota_id and quotals_language=:language", array(':quota_id'=>$iQuotaId, ':language'=>$sLang)); + $oQuotaLanguageSetting = QuotaLanguageSetting::model()->find("quotals_quota_id =:quota_id and quotals_language=:language", array(':quota_id' => $iQuotaId, ':language' => $sLang)); // We don't need to go to step since new feature #8823, maybe need to be fixed ? if ($oQuotaLanguageSetting) { $this->sLang = $sLang; - $aExpressions['name_'.$sLang] = array( - 'title'=>sprintf(gT("Quota name (%s)"), $sLang), - 'expression'=> $this->getHtmlExpression($oQuotaLanguageSetting->quotals_name, array(), __METHOD__), + $aExpressions['name_' . $sLang] = array( + 'title' => sprintf(gT("Quota name (%s)"), $sLang), + 'expression' => $this->getHtmlExpression($oQuotaLanguageSetting->quotals_name, array(), __METHOD__), ); - $aExpressions['message_'.$sLang] = array( - 'title'=>sprintf(gT("Quota message (%s)"), $sLang), - 'expression'=> $this->getHtmlExpression($oQuotaLanguageSetting->quotals_message, array(), __METHOD__), + $aExpressions['message_' . $sLang] = array( + 'title' => sprintf(gT("Quota message (%s)"), $sLang), + 'expression' => $this->getHtmlExpression($oQuotaLanguageSetting->quotals_message, array(), __METHOD__), ); - $aExpressions['url_'.$sLang] = array( - 'title'=>sprintf(gT("URL (%s)"), $sLang), - 'expression'=> $this->getHtmlExpression($oQuotaLanguageSetting->quotals_url, array(), __METHOD__), + $aExpressions['url_' . $sLang] = array( + 'title' => sprintf(gT("URL (%s)"), $sLang), + 'expression' => $this->getHtmlExpression($oQuotaLanguageSetting->quotals_url, array(), __METHOD__), ); - $aExpressions['urldescrip_'.$sLang] = array( - 'title'=>sprintf(gT("URL description (%s)"), $sLang), - 'expression'=> $this->getHtmlExpression($oQuotaLanguageSetting->quotals_urldescrip, array(), __METHOD__), + $aExpressions['urldescrip_' . $sLang] = array( + 'title' => sprintf(gT("URL description (%s)"), $sLang), + 'expression' => $this->getHtmlExpression($oQuotaLanguageSetting->quotals_urldescrip, array(), __METHOD__), ); } } $aData = array( - 'aExpressions'=>$aExpressions, + 'aExpressions' => $aExpressions, ); $this->getController()->layout = $this->layout; $this->getController()->pageTitle = gT("Validate quota"); @@ -105,72 +106,72 @@ public function email($iSurveyId, $lang) $this->iSurveyId = $iSurveyId; // This start the survey before Expression : is this allways needed ? $aTypeAttributes = array( - 'invitation'=>array( - 'subject'=>array( - 'attribute'=>'surveyls_email_invite_subj', - 'title'=>gT('Invitation email subject'), + 'invitation' => array( + 'subject' => array( + 'attribute' => 'surveyls_email_invite_subj', + 'title' => gT('Invitation email subject'), ), - 'message'=>array( - 'attribute'=>'surveyls_email_invite', - 'title'=>gT('Invitation email body'), + 'message' => array( + 'attribute' => 'surveyls_email_invite', + 'title' => gT('Invitation email body'), ), ), - 'reminder'=>array( - 'subject'=>array( - 'attribute'=>'surveyls_email_remind_subj', - 'title'=>gT('Reminder email subject'), + 'reminder' => array( + 'subject' => array( + 'attribute' => 'surveyls_email_remind_subj', + 'title' => gT('Reminder email subject'), ), - 'message'=>array( - 'attribute'=>'surveyls_email_remind', - 'title'=>gT('Reminder email body'), + 'message' => array( + 'attribute' => 'surveyls_email_remind', + 'title' => gT('Reminder email body'), ), ), - 'confirmation'=>array( - 'subject'=>array( - 'attribute'=>'surveyls_email_confirm_subj', - 'title'=>gT('Confirmation email subject'), + 'confirmation' => array( + 'subject' => array( + 'attribute' => 'surveyls_email_confirm_subj', + 'title' => gT('Confirmation email subject'), ), - 'message'=>array( - 'attribute'=>'surveyls_email_confirm', - 'title'=>gT('Confirmation email body'), + 'message' => array( + 'attribute' => 'surveyls_email_confirm', + 'title' => gT('Confirmation email body'), ), ), - 'registration'=>array( - 'subject'=>array( - 'attribute'=>'surveyls_email_register_subj', - 'title'=>gT('Registration email subject'), + 'registration' => array( + 'subject' => array( + 'attribute' => 'surveyls_email_register_subj', + 'title' => gT('Registration email subject'), ), - 'message'=>array( - 'attribute'=>'surveyls_email_register', - 'title'=>gT('Registration email body'), + 'message' => array( + 'attribute' => 'surveyls_email_register', + 'title' => gT('Registration email body'), ), ), - 'admin_notification'=>array( - 'subject'=>array( - 'attribute'=>'email_admin_notification_subj', - 'title'=>gT('Basic admin notification subject'), + 'admin_notification' => array( + 'subject' => array( + 'attribute' => 'email_admin_notification_subj', + 'title' => gT('Basic admin notification subject'), ), - 'message'=>array( - 'attribute'=>'email_admin_notification', - 'title'=>gT('Basic admin notification body'), + 'message' => array( + 'attribute' => 'email_admin_notification', + 'title' => gT('Basic admin notification body'), ), ), - 'admin_detailed_notification'=>array( - 'subject'=>array( - 'attribute'=>'email_admin_responses_subj', - 'title'=>gT('Detailed admin notification subject'), + 'admin_detailed_notification' => array( + 'subject' => array( + 'attribute' => 'email_admin_responses_subj', + 'title' => gT('Detailed admin notification subject'), ), - 'message'=>array( - 'attribute'=>'email_admin_responses', - 'title'=>gT('Detailed admin notification body'), + 'message' => array( + 'attribute' => 'email_admin_responses', + 'title' => gT('Detailed admin notification body'), ), ), ); $aSurveyInfo = getSurveyInfo($iSurveyId, $sLang); // Replaced before email edit $aReplacement = array( - 'ADMINNAME'=> $aSurveyInfo['admin'], - 'ADMINEMAIL'=> $aSurveyInfo['adminemail'], + 'ADMINNAME' => $aSurveyInfo['admin'], + 'ADMINEMAIL' => $aSurveyInfo['adminemail'], ); // Not needed : templatereplace do the job : but this can/must be fixed for invitaton/reminder/registration (#9424) $aReplacement["SURVEYNAME"] = gT("Name of the survey"); @@ -183,14 +184,14 @@ public function email($iSurveyId, $lang) $aReplacement["TOKEN:LASTNAME"] = gT("Last name of the participant"); $aReplacement["TOKEN:TOKEN"] = gT("Access code for this participant"); $aReplacement["TOKEN:LANGUAGE"] = gT("language of participant"); - foreach ($aAttributes as $sAttribute=>$aAttribute) { - $aReplacement['TOKEN:'.strtoupper($sAttribute).''] = sprintf(gT("Participant attribute: %s"), $aAttribute['description']); + foreach ($aAttributes as $sAttribute => $aAttribute) { + $aReplacement['TOKEN:' . strtoupper($sAttribute) . ''] = sprintf(gT("Participant attribute: %s"), $aAttribute['description']); } switch ($sType) { - case 'invitation' : - case 'reminder' : - case 'registration' : + case 'invitation': + case 'reminder': + case 'registration': // Replaced when sending email (registration too ?) $aReplacement["EMAIL"] = gT("Email address of the participant"); $aReplacement["FIRSTNAME"] = gT("First name of the participant"); @@ -199,22 +200,22 @@ public function email($iSurveyId, $lang) $aReplacement["OPTOUTURL"] = gT("URL for a respondent to opt-out of this survey"); $aReplacement["OPTINURL"] = gT("URL for a respondent to opt-in to this survey"); $aReplacement["SURVEYURL"] = gT("URL of the survey"); - foreach ($aAttributes as $sAttribute=>$aAttribute) { - $aReplacement[''.strtoupper($sAttribute).''] = sprintf(gT("Participant attribute: %s"), $aAttribute['description']); + foreach ($aAttributes as $sAttribute => $aAttribute) { + $aReplacement['' . strtoupper($sAttribute) . ''] = sprintf(gT("Participant attribute: %s"), $aAttribute['description']); } break; - case 'confirmation' : + case 'confirmation': $aReplacement["EMAIL"] = gT("Email address of the participant"); $aReplacement["FIRSTNAME"] = gT("First name of the participant"); $aReplacement["LASTNAME"] = gT("Last name of the participant"); $aReplacement["SURVEYURL"] = gT("URL of the survey"); - foreach ($aAttributes as $sAttribute=>$aAttribute) { - $aReplacement[''.strtoupper($sAttribute).''] = sprintf(gT("Participant attribute: %s"), $aAttribute['description']); + foreach ($aAttributes as $sAttribute => $aAttribute) { + $aReplacement['' . strtoupper($sAttribute) . ''] = sprintf(gT("Participant attribute: %s"), $aAttribute['description']); } // $moveResult = LimeExpressionManager::NavigateForwards(); // Seems OK without, nut need $LEM::StartSurvey break; - case 'admin_notification' : - case 'admin_detailed_notification' : + case 'admin_notification': + case 'admin_detailed_notification': $aReplacement["RELOADURL"] = gT("Reload URL"); $aReplacement["VIEWRESPONSEURL"] = gT("View response URL"); $aReplacement["EDITRESPONSEURL"] = gT("Edit response URL"); @@ -230,13 +231,13 @@ public function email($iSurveyId, $lang) $aData = array(); //$oSurveyLanguage=SurveyLanguageSetting::model()->find("surveyls_survey_id=:sid and surveyls_language=:language",array(":sid"=>$iSurveyId,":language"=>$sLang)); $aExpressions = array(); - foreach ($aTypeAttributes[$sType] as $key=>$aAttribute) { + foreach ($aTypeAttributes[$sType] as $key => $aAttribute) { $sAttribute = $aAttribute['attribute']; // Email send do : templatereplace + ReplaceField to the Templatereplace done : we need 2 in one // $LEM::ProcessString($oSurveyLanguage->$sAttribute,null,$aReplacement,1,1,false,false,true); // This way : ProcessString don't replace coreReplacements $aExpressions[$key] = array( - 'title'=>$aAttribute['title'], - 'expression'=> $this->getHtmlExpression($aSurveyInfo[$sAttribute], $aReplacement, __METHOD__), + 'title' => $aAttribute['title'], + 'expression' => $this->getHtmlExpression($aSurveyInfo[$sAttribute], $aReplacement, __METHOD__), ); } $aData['aExpressions'] = $aExpressions; @@ -265,7 +266,7 @@ private function getHtmlExpression($sExpression, $aReplacement = array(), $sDebu $aReData = array(); if ($this->iSurveyId) { - $LEM::StartSurvey($this->iSurveyId, 'survey', array('hyperlinkSyntaxHighlighting'=>true)); // replace QCODE + $LEM::StartSurvey($this->iSurveyId, 'survey', array('hyperlinkSyntaxHighlighting' => true)); // replace QCODE $aReData['thissurvey'] = getSurveyInfo($this->iSurveyId, $this->sLang); } // TODO : Find error in class name, style etc .... diff --git a/application/controllers/admin/NotificationController.php b/application/controllers/admin/NotificationController.php index 7f428220aab..3466867d733 100644 --- a/application/controllers/admin/NotificationController.php +++ b/application/controllers/admin/NotificationController.php @@ -29,7 +29,6 @@ public function getNotificationAsJSON($notId) { $this->checkPermission(); if ((string) (int) $notId !== (string) $notId) { - } $not = Notification::model()->findByPk($notId); if (!$not) { @@ -57,7 +56,7 @@ public function notificationRead($notId) throw new CHttpException(404, sprintf(gT("Notification %s not found"), $notId)); } // Check if user is allowed to mark this notification as read - if ($not->entity=='user' && $not->entity_id<>Yii::app()->user->id) { + if ($not->entity == 'user' && $not->entity_id <> Yii::app()->user->id) { throw new CHttpException(404, sprintf(gT("Invalid notification id"), $notId)); } @@ -87,13 +86,13 @@ public function clearAllNotifications($surveyId = null) { Notification::model()->deleteAll( 'entity = :entity AND entity_id = :entity_id', - array(":entity"=>'user', ":entity_id"=>Yii::app()->user->id) + array(":entity" => 'user', ":entity_id" => Yii::app()->user->id) ); if (is_int($surveyId)) { Notification::model()->deleteAll( 'entity = :entity AND entity_id = :entity_id', - array(":entity"=>'survey', ":entity_id"=>$surveyId) + array(":entity" => 'survey', ":entity_id" => $surveyId) ); } } diff --git a/application/controllers/admin/PermissiontemplatesController.php b/application/controllers/admin/PermissiontemplatesController.php index ba3b126d436..0bf3f772950 100644 --- a/application/controllers/admin/PermissiontemplatesController.php +++ b/application/controllers/admin/PermissiontemplatesController.php @@ -49,28 +49,28 @@ public function index() */ public function viewrole($ptid) { - if(!Permission::model()->hasGlobalPermission('superadmin', 'read')) { + if (!Permission::model()->hasGlobalPermission('superadmin', 'read')) { Yii::app()->session['flashmessage'] = gT('You have no access to the role management!'); $this->getController()->redirect(array('/admin')); } $oPermissionTemplate = Permissiontemplates::model()->findByPk($ptid); return $this->getController()->renderPartial( - '/admin/permissiontemplates/partials/_view', + '/admin/permissiontemplates/partials/_view', [ - "oModel" => $oPermissionTemplate, + "oModel" => $oPermissionTemplate, ] ); } - public function editrolemodal($ptid=null) + public function editrolemodal($ptid = null) { - if(!Permission::model()->hasGlobalPermission('superadmin', 'read')) { + if (!Permission::model()->hasGlobalPermission('superadmin', 'read')) { Yii::app()->session['flashmessage'] = gT('You have no access to the role management!'); $this->getController()->redirect(array('/admin')); } $model = $this->loadModel($ptid); - Yii::app()->getController()->renderPartial( 'permissiontemplates/partials/_form', ['model' => $model]); + Yii::app()->getController()->renderPartial('permissiontemplates/partials/_form', ['model' => $model]); } /** @@ -126,19 +126,21 @@ private function renderErrors($errors) return (string)$errorDiv; } - public function showImportXML() { - if(!Permission::model()->hasGlobalPermission('superadmin', 'read')) { + public function showImportXML() + { + if (!Permission::model()->hasGlobalPermission('superadmin', 'read')) { Yii::app()->session['flashmessage'] = gT('You have no access to the role management!'); $this->getController()->redirect(array('/admin')); } - Yii::app()->getController()->renderPartial( 'permissiontemplates/partials/_import', []); + Yii::app()->getController()->renderPartial('permissiontemplates/partials/_import', []); } - public function importXML() { + public function importXML() + { $sRandomFileName = randomChars(20); - $sFilePath = Yii::app()->getConfig('tempdir').DIRECTORY_SEPARATOR.$sRandomFileName; + $sFilePath = Yii::app()->getConfig('tempdir') . DIRECTORY_SEPARATOR . $sRandomFileName; $aPathinfo = pathinfo($_FILES['the_file']['name']); $sExtension = $aPathinfo['extension']; $bMoveFileResult = false; @@ -148,10 +150,10 @@ public function importXML() { Yii::app()->setFlashMessage(sprintf(gT("Sorry, this file is too large. Only files up to %01.2f MB are allowed."), getMaximumFileUploadSize() / 1024 / 1024), 'error'); Yii::app()->getController()->redirect(array('/admin/roles')); Yii::app()->end(); - } elseif (strtolower($sExtension) == 'xml' ||1==1) { + } elseif (strtolower($sExtension) == 'xml' || 1 == 1) { $bMoveFileResult = @move_uploaded_file($_FILES['the_file']['tmp_name'], $sFilePath); } else { - Yii::app()->setFlashMessage(gT("This is not a .xml file."). 'It is a '.$sExtension, 'error'); + Yii::app()->setFlashMessage(gT("This is not a .xml file.") . 'It is a ' . $sExtension, 'error'); Yii::app()->getController()->redirect(array('/admin/roles')); Yii::app()->end(); } @@ -168,8 +170,7 @@ public function importXML() { libxml_disable_entity_loader(true); $oNewRole = Permissiontemplates::model()->createFromXML($oRoleDefinition); - if($oNewRole == false ) { - + if ($oNewRole == false) { Yii::app()->setFlashMessage(gT("Error creating role"), 'error'); Yii::app()->getController()->redirect(array('/admin/roles')); Yii::app()->end(); @@ -182,15 +183,15 @@ public function importXML() { Yii::app()->getController()->redirect(array('/admin/roles')); Yii::app()->end(); return; - } - public function setpermissions() { - if(!Permission::model()->hasGlobalPermission('superadmin', 'read')) { + public function setpermissions() + { + if (!Permission::model()->hasGlobalPermission('superadmin', 'read')) { return $this->getController()->renderPartial( '/admin/permissiontemplates/partial/error', ['errors' => [gT("You do not have permission to access this page.")],'noButton' => true] - ); + ); } $oRequest = Yii::app()->request; @@ -203,8 +204,8 @@ public function setpermissions() { // if not superadmin filter the available permissions as no admin may give more permissions than he owns Yii::app()->session['flashmessage'] = gT("Note: You can only give limited permissions to other users because your own permissions are limited, too."); $aFilteredPermissions = array(); - foreach ($aBasePermissions as $PermissionName=>$aPermission) { - foreach ($aPermission as $sPermissionKey=>&$sPermissionValue) { + foreach ($aBasePermissions as $PermissionName => $aPermission) { + foreach ($aPermission as $sPermissionKey => &$sPermissionValue) { if ($sPermissionKey != 'title' && $sPermissionKey != 'img' && !Permission::model()->hasGlobalPermission($PermissionName, $sPermissionKey)) { $sPermissionValue = false; } @@ -226,7 +227,7 @@ public function setpermissions() { return true; } return array_reduce($oSurvey->permissions, function ($coll, $oPermission) { - if ($oPermission->permission=='surveysecurity' && $oPermission->update_p == 1 && $oPermission->uid == App()->user->id) { + if ($oPermission->permission == 'surveysecurity' && $oPermission->update_p == 1 && $oPermission->uid == App()->user->id) { return true; } return $coll; @@ -234,9 +235,9 @@ public function setpermissions() { }); return $this->getController()->renderPartial( - '/admin/permissiontemplates/partials/_permissions', + '/admin/permissiontemplates/partials/_permissions', [ - "oModel" => $oPermissionTemplate, + "oModel" => $oPermissionTemplate, "aBasePermissions" => $aBasePermissions ] ); @@ -244,16 +245,16 @@ public function setpermissions() { public function savepermissions() { - if(!Permission::model()->hasGlobalPermission('superadmin', 'read')) { + if (!Permission::model()->hasGlobalPermission('superadmin', 'read')) { return $this->getController()->renderPartial( - '/admin/permissiontemplates/partial/error', + '/admin/permissiontemplates/partial/error', ['errors' => [gT("You do not have permission to access this page.")],'noButton' => true] - ); + ); } $oRequest = Yii::app()->request; $ptid = $oRequest->getParam('ptid'); - $aPermissions = Yii::app()->request->getPost('Permission',[]); + $aPermissions = Yii::app()->request->getPost('Permission', []); $oPermissionTemplate = Permissiontemplates::model()->findByPk($ptid); $results = $this->applyPermissionFromArray($ptid, $aPermissions); @@ -261,7 +262,7 @@ public function savepermissions() $save = $oPermissionTemplate->save(); $html = $this->getController()->renderPartial('/userManagement/partial/permissionsuccess', ['results' => $results], true); - return Yii::app()->getController()->renderPartial('/userManagement/partial/json', ["data"=>[ + return Yii::app()->getController()->renderPartial('/userManagement/partial/json', ["data" => [ 'success' => true, 'html' => $html ]]); @@ -271,9 +272,9 @@ public function savepermissions() * Creates a new model. * If creation is successful, the browser will be redirected to the 'view' page. */ - public function edit($ptid=null) + public function edit($ptid = null) { - if(!Permission::model()->hasGlobalPermission('superadmin', 'read')) { + if (!Permission::model()->hasGlobalPermission('superadmin', 'read')) { Yii::app()->session['flashmessage'] = gT('You have no access to the role management!'); $this->getController()->redirect(array('/admin')); } @@ -287,21 +288,20 @@ public function edit($ptid=null) if ($model->save()) { $this->redirect(array('view', 'id' => $model->id)); } - } $this->_renderWrappedTemplate( - null, - 'permissiontemplates/edit', + null, + 'permissiontemplates/edit', array( 'model' => $model, ) ); } - public function batchDelete() + public function batchDelete() { - if(!Permission::model()->hasGlobalPermission('superadmin', 'read')) { + if (!Permission::model()->hasGlobalPermission('superadmin', 'read')) { Yii::app()->session['flashmessage'] = gT('You have no access to the role management!'); $this->getController()->redirect(array('/admin')); } @@ -315,12 +315,11 @@ public function batchDelete() $this->getController()->renderPartial( '/userManagement/partial/success', [ - 'sMessage' => gT('Roles successfully deleted'), - 'sDebug' => json_encode($success, JSON_PRETTY_PRINT), + 'sMessage' => gT('Roles successfully deleted'), + 'sDebug' => json_encode($success, JSON_PRETTY_PRINT), 'noButton' => true ] ); - } /** @@ -330,7 +329,7 @@ public function batchDelete() */ public function delete() { - if(!Permission::model()->hasGlobalPermission('superadmin', 'read')) { + if (!Permission::model()->hasGlobalPermission('superadmin', 'read')) { Yii::app()->session['flashmessage'] = gT('You have no access to the role management!'); $this->getController()->redirect(array('/admin')); } @@ -341,36 +340,37 @@ public function delete() if (!isset($_GET['ajax'])) { $this->getController()->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('/admin/roles')); } - } - public function runexport($ptid) { + public function runexport($ptid) + { $oModel = $this->loadModel($ptid); $oXML = $oModel->compileExportXML(); - $filename = preg_replace("/[^a-zA-Z0-9-_]*/",'',$oModel->name); + $filename = preg_replace("/[^a-zA-Z0-9-_]*/", '', $oModel->name); header('Content-type: application/xml'); - header('Content-Disposition: attachment; filename="'.$filename.'.xml"'); + header('Content-Disposition: attachment; filename="' . $filename . '.xml"'); print($oXML->asXML()); Yii::app()->end(); } - public function batchExport() { - if(!Permission::model()->hasGlobalPermission('superadmin', 'read')) { + public function batchExport() + { + if (!Permission::model()->hasGlobalPermission('superadmin', 'read')) { Yii::app()->session['flashmessage'] = gT('You have no access to the role management!'); $this->getController()->redirect(array('/admin')); } $sPtids = Yii::app()->request->getParam('sItems', ''); - $aPtids = explode(',',$sPtids); + $aPtids = explode(',', $sPtids); $sRandomFolderName = randomChars(20); - $sRandomFileName = "RoleExport-".randomChars(5).'-'.time(); + $sRandomFileName = "RoleExport-" . randomChars(5) . '-' . time(); $tempdir = Yii::app()->getConfig('tempdir'); $zipfile = "$tempdir/$sRandomFileName.zip"; Yii::app()->loadLibrary('admin.pclzip'); $zip = new PclZip($zipfile); - $sFilePath = $tempdir.DIRECTORY_SEPARATOR.$sRandomFolderName; + $sFilePath = $tempdir . DIRECTORY_SEPARATOR . $sRandomFolderName; mkdir($sFilePath); $filesInArchive = []; @@ -378,10 +378,10 @@ public function batchExport() { foreach ($aPtids as $iPtid) { $oModel = $this->loadModel($iPtid); $oXML = $oModel->compileExportXML(); - $filename = preg_replace("/[^a-zA-Z0-9-_]*/",'',$oModel->name).'.xml'; + $filename = preg_replace("/[^a-zA-Z0-9-_]*/", '', $oModel->name) . '.xml'; - file_put_contents($sFilePath.DIRECTORY_SEPARATOR.$filename, $oXML->asXML()); - $filesInArchive[] = $sFilePath.DIRECTORY_SEPARATOR.$filename; + file_put_contents($sFilePath . DIRECTORY_SEPARATOR . $filename, $oXML->asXML()); + $filesInArchive[] = $sFilePath . DIRECTORY_SEPARATOR . $filename; } $zip->create($filesInArchive, PCLZIP_OPT_REMOVE_ALL_PATH); @@ -440,15 +440,15 @@ private function applyPermissionFromArray($iRoleId, $aPermissionArray) $aPermissionsCurrently = Permission::model()->deleteAll($oCriteria); $results = []; //Apply the permission array - foreach($aPermissionArray as $sPermissionKey => $aPermissionSettings) { + foreach ($aPermissionArray as $sPermissionKey => $aPermissionSettings) { $oPermission = new Permission(); $oPermission->entity = 'role'; $oPermission->entity_id = $iRoleId; $oPermission->uid = 0; $oPermission->permission = $sPermissionKey; - foreach($aPermissionSettings as $sSettingKey => $sSettingValue) { - $oPermissionDBSettingKey = $sSettingKey.'_p'; + foreach ($aPermissionSettings as $sSettingKey => $sSettingValue) { + $oPermissionDBSettingKey = $sSettingKey . '_p'; $oPermission->$oPermissionDBSettingKey = $sSettingValue == 'on' ? 1 : 0; } @@ -473,16 +473,16 @@ private function applyPermissionFromXML($iRoleId, $oPermissionObject) $results = []; //Apply the permission array $aCleanPermissionObject = json_decode(json_encode($oPermissionObject), true); - foreach($aCleanPermissionObject as $sPermissionKey => $aPermissionSettings) { + foreach ($aCleanPermissionObject as $sPermissionKey => $aPermissionSettings) { $oPermission = new Permission(); $oPermission->entity = 'role'; $oPermission->entity_id = $iRoleId; $oPermission->uid = 0; $oPermission->permission = $sPermissionKey; - foreach($aPermissionSettings as $sSettingKey => $sSettingValue) { - $oPermissionDBSettingKey = $sSettingKey.'_p'; - if(isset($oPermission->$oPermissionDBSettingKey)) { + foreach ($aPermissionSettings as $sSettingKey => $sSettingValue) { + $oPermissionDBSettingKey = $sSettingKey . '_p'; + if (isset($oPermission->$oPermissionDBSettingKey)) { $oPermission->$oPermissionDBSettingKey = $sSettingValue; } } @@ -497,5 +497,4 @@ private function applyPermissionFromXML($iRoleId, $oPermissionObject) } return $results; } - } diff --git a/application/controllers/admin/PluginHelper.php b/application/controllers/admin/PluginHelper.php index 46928b0e19a..85568b233c6 100644 --- a/application/controllers/admin/PluginHelper.php +++ b/application/controllers/admin/PluginHelper.php @@ -29,7 +29,7 @@ public function sidebody($surveyid = 0, $plugin = '', $method = '') $oSurvey = Survey::model()->findByPk($surveyid); if ($oSurvey) { $aData['surveybar']['buttons']['view'] = true; - $aData['title_bar']['title'] = viewHelper::flatEllipsizeText($oSurvey->defaultlanguage->surveyls_title)." (".gT("ID").":".$surveyid.")"; + $aData['title_bar']['title'] = viewHelper::flatEllipsizeText($oSurvey->defaultlanguage->surveyls_title) . " (" . gT("ID") . ":" . $surveyid . ")"; $aData['activated'] = $oSurvey->active; } // Plugin must test to send 404 if needed, maybe want to “create” a new survey, who know … @@ -92,14 +92,14 @@ protected function getPluginInstanceAndMethod($pluginName, $methodName) $record = Plugin::model()->findByAttributes(array('name' => $pluginName, 'active' => 1)); if (empty($record)) { - throw new Exception('Plugin with name '.$pluginName.' is not active or can\' be found'); + throw new Exception('Plugin with name ' . $pluginName . ' is not active or can\' be found'); } $pluginManager = App()->getPluginManager(); $pluginInstance = $refClass->newInstance($pluginManager, $record->id); /* Check if method is in allowed list */ - if(is_array($pluginInstance->allowedPublicMethods) && !in_array($methodName,$pluginInstance->allowedPublicMethods)) { - throw new \CHttpException(400, sprintf(gT("Forbidden call of method %s for plugin %s"),$methodName,$pluginName)); + if (is_array($pluginInstance->allowedPublicMethods) && !in_array($methodName, $pluginInstance->allowedPublicMethods)) { + throw new \CHttpException(400, sprintf(gT("Forbidden call of method %s for plugin %s"), $methodName, $pluginName)); } Yii::app()->setPlugin($pluginInstance); @@ -107,7 +107,7 @@ protected function getPluginInstanceAndMethod($pluginName, $methodName) try { $refMethod = $refClass->getMethod($methodName); } catch (ReflectionException $ex) { - throw new \CException('Plugin '.$pluginName.' has no method '.$methodName); + throw new \CException('Plugin ' . $pluginName . ' has no method ' . $methodName); } return array($pluginInstance, $refMethod); diff --git a/application/controllers/admin/PluginManagerController.php b/application/controllers/admin/PluginManagerController.php index 7bf21ee4502..44644edc2b7 100644 --- a/application/controllers/admin/PluginManagerController.php +++ b/application/controllers/admin/PluginManagerController.php @@ -12,10 +12,10 @@ * See COPYRIGHT.php for copyright notices and details. */ -use \LimeSurvey\ExtensionInstaller\FileFetcherUploadZip; -use \LimeSurvey\ExtensionInstaller\PluginInstaller; -use \LimeSurvey\Menu\Menu; -use \LimeSurvey\Menu\MenuItem; +use LimeSurvey\ExtensionInstaller\FileFetcherUploadZip; +use LimeSurvey\ExtensionInstaller\PluginInstaller; +use LimeSurvey\Menu\Menu; +use LimeSurvey\Menu\MenuItem; /** * @todo Apply new permission 'extensions' instead of 'settings'. @@ -98,8 +98,8 @@ public function scanFiles() $result = $oPluginManager->scanPlugins(); // Add delete URL for each plugin - foreach($result as $name => &$scannedPlugin) { - if (isset($scannedPlugin['pluginType'])&&$scannedPlugin['pluginType']=='upload') { + foreach ($result as $name => &$scannedPlugin) { + if (isset($scannedPlugin['pluginType']) && $scannedPlugin['pluginType'] == 'upload') { $scannedPlugin['deleteUrl'] = $this->getController()->createUrl( '/admin/pluginmanager', [ @@ -145,11 +145,12 @@ public function scanFiles() //$this->getController()->redirect($indexUrl); } - public function deleteFiles($plugin) { + public function deleteFiles($plugin) + { $this->checkUpdatePermission(); // Pre supposes the plugin is in the uploads folder. Other plugins are not deletable by button. - $pluginDir =Yii::getPathOfAlias(App()->getPluginManager()->pluginDirs['upload']) . DIRECTORY_SEPARATOR . $plugin; + $pluginDir = Yii::getPathOfAlias(App()->getPluginManager()->pluginDirs['upload']) . DIRECTORY_SEPARATOR . $plugin; if (!file_exists($pluginDir)) { Yii::app()->setFlashMessage(gT('Plugin folder does not exist.'), 'error'); @@ -168,7 +169,6 @@ public function deleteFiles($plugin) { Yii::app()->setFlashMessage(gT('Plugin files successfully deleted.'), 'success'); $this->getController()->redirect($this->getPluginManagerUrl()); } - } /** @@ -313,12 +313,12 @@ public function configure($id) $url = App()->createUrl("admin/pluginmanager/sa/index"); $aButtons = array( 'save' => array( - 'label' => '

'.gT('Reloading screen. Please wait.').''; + . ' content="1;URL=' . Yii::app()->session['redirect_after_login'] . '" />'; + $sSummary = '

' . gT('Reloading screen. Please wait.') . ''; unset(Yii::app()->session['redirect_after_login']); } break; @@ -359,5 +360,4 @@ protected function _renderWrappedTemplate($sAction = 'authentication', $aViewUrl $aData['language'] = Yii::app()->getLanguage() != Yii::app()->getConfig("defaultlang") ? Yii::app()->getLanguage() : 'default'; parent::_renderWrappedTemplate($sAction, $aViewUrls, $aData, $sRenderFile); } - } diff --git a/application/controllers/admin/checkintegrity.php b/application/controllers/admin/checkintegrity.php index eaa88fc0d9e..78ffe0a53e7 100644 --- a/application/controllers/admin/checkintegrity.php +++ b/application/controllers/admin/checkintegrity.php @@ -1,4 +1,5 @@ hasGlobalPermission('settings', 'update')) { + if (!Permission::model()->hasGlobalPermission('settings', 'update')) { throw new CHttpException(401, "401 Unauthorized"); } - if(Yii::app()->request->getPost('ok') != 'Y') { + if (Yii::app()->request->getPost('ok') != 'Y') { throw new CHttpException(403); } $aDelete = $this->_checkintegrity(); @@ -152,14 +153,13 @@ public function fixintegrity() } $this->_renderWrappedTemplate('checkintegrity', 'fix_view', $aData); - } private function _deleteOrphanTokenTables(array $tokenTables, array $aData) { foreach ($tokenTables as $aTokenTable) { Yii::app()->db->createCommand()->dropTable($aTokenTable); - $aData['messages'][] = sprintf(gT('Deleting orphan survey participants table: %s'),$aTokenTable); + $aData['messages'][] = sprintf(gT('Deleting orphan survey participants table: %s'), $aTokenTable); } return $aData; } @@ -168,7 +168,7 @@ private function _dropOrphanSurveyTables(array $surveyTables, array $aData) { foreach ($surveyTables as $aSurveyTable) { Yii::app()->db->createCommand()->dropTable($aSurveyTable); - $aData['messages'][] = sprintf(gT('Deleting orphan survey table: %s'),$aSurveyTable); + $aData['messages'][] = sprintf(gT('Deleting orphan survey table: %s'), $aSurveyTable); } return $aData; } @@ -181,11 +181,11 @@ private function _dropOrphanSurveyTables(array $surveyTables, array $aData) */ private function _deleteGroups(array $groups, array $aData) { - $gids = array_unique(array_column($groups,'gid')); + $gids = array_unique(array_column($groups, 'gid')); $count = 0; foreach ($gids as $gid) { - $deleted = QuestionGroup::model()->deleteAll("gid = :gid",array(":gid"=> $gid)); - if($deleted) { + $deleted = QuestionGroup::model()->deleteAll("gid = :gid", array(":gid" => $gid)); + if ($deleted) { $count += $deleted; } else { $aData['warnings'][] = sprintf(gT('Unable to delete question group %s'), $gid); @@ -208,7 +208,7 @@ private function _deleteUserInGroups(array $userInGroups, array $aData) $ugids[] = $group['ugid']; } - $criteria = new CDbCriteria; + $criteria = new CDbCriteria(); $criteria->addInCondition('ugid', $ugids); $deletedRows = UserInGroup::model()->deleteAll($criteria); if ($deletedRows === count($userInGroups)) { @@ -225,11 +225,11 @@ private function _deleteUserInGroups(array $userInGroups, array $aData) */ private function _deleteQuestions(array $questions, array $aData) { - $qids = array_unique(array_column($questions,'qid')); + $qids = array_unique(array_column($questions, 'qid')); $count = 0; foreach ($qids as $qid) { - $deleted = Question::model()->deleteAll("qid = :qid",array(":qid"=> $qid)); - if($deleted) { + $deleted = Question::model()->deleteAll("qid = :qid", array(":qid" => $qid)); + if ($deleted) { $count += $deleted; } else { $aData['warnings'][] = sprintf(gT('Unable to delete question %s'), $qid); @@ -247,11 +247,11 @@ private function _deleteQuestions(array $questions, array $aData) */ private function _deleteSurveyLanguageSettings(array $surveyLanguageSettings, array $aData) { - $slids = array_unique(array_column($surveyLanguageSettings,'slid')); + $slids = array_unique(array_column($surveyLanguageSettings, 'slid')); $count = 0; foreach ($slids as $slid) { - $deleted = SurveyLanguageSetting::model()->deleteAll("surveyls_survey_id = :slid",array(":slid"=> $slid)); - if($deleted) { + $deleted = SurveyLanguageSetting::model()->deleteAll("surveyls_survey_id = :slid", array(":slid" => $slid)); + if ($deleted) { $count += $deleted; } else { $aData['warnings'][] = sprintf(gT('Unable to delete survey languagesettings %s'), $slid); @@ -272,7 +272,7 @@ private function _deleteSurveys(array $surveys, array $aData) $count = 0; foreach ($surveys as $survey) { $deleted = Survey::model()->deleteByPk($survey['sid']); - if($deleted) { + if ($deleted) { $count += $deleted; } else { $aData['warnings'][] = sprintf(gT('Unable to delete survey %s'), $survey['sid']); @@ -293,17 +293,17 @@ private function _deleteAnswers(array $answers, array $aData) $answersDeleted = array();// Keep for multilingual survey (alt : make an array_unique_mutilplekeys function) $count = 0; foreach ($answers as $answer) { - if(!in_array(array($answer['qid'],$answer['code']),$answersDeleted)) { - $deleted = Answer::model()->deleteAll('qid=:qid AND code=:code', array(':qid'=>$answer['qid'], ':code'=>$answer['code'])); - if($deleted) { + if (!in_array(array($answer['qid'],$answer['code']), $answersDeleted)) { + $deleted = Answer::model()->deleteAll('qid=:qid AND code=:code', array(':qid' => $answer['qid'], ':code' => $answer['code'])); + if ($deleted) { $count += $deleted; $answersDeleted[] = array($answer['qid'],$answer['code']); } else { - $aData['warnings'][] = sprintf(gT('Unable to delete answer %s, code %s'), $answer['qid'],$answer['code']); + $aData['warnings'][] = sprintf(gT('Unable to delete answer %s, code %s'), $answer['qid'], $answer['code']); } } } - $aData['messages'][] = sprintf(gT('Deleting answers: %u answers deleted'),$count); + $aData['messages'][] = sprintf(gT('Deleting answers: %u answers deleted'), $count); return $aData; } @@ -315,11 +315,11 @@ private function _deleteAnswers(array $answers, array $aData) */ private function _deleteAssessments(array $assessments, array $aData) { - $assessmentids = array_unique(array_column($assessments,'id')); + $assessmentids = array_unique(array_column($assessments, 'id')); $count = 0; foreach ($assessmentids as $assessmentid) { - $deleted = Assessment::model()->deleteAll("id = :id",array(":id" => $assessmentid)); - if($deleted) { + $deleted = Assessment::model()->deleteAll("id = :id", array(":id" => $assessmentid)); + if ($deleted) { $count += $deleted; } else { $aData['warnings'][] = sprintf(gT('Unable to delete assessment %s'), $assessmentid); @@ -336,7 +336,7 @@ private function _deleteAssessments(array $assessments, array $aData) */ private function _deleteQuotaMembers(array $aData) { - $oCriteria = new CDbCriteria; + $oCriteria = new CDbCriteria(); $oCriteria->join = 'LEFT JOIN {{questions}} q ON t.qid=q.qid LEFT JOIN {{surveys}} s ON t.sid=s.sid'; $oCriteria->condition = '(q.qid IS NULL) OR (s.sid IS NULL)'; $count = 0; @@ -356,7 +356,7 @@ private function _deleteQuotaMembers(array $aData) */ private function _deleteQuotaLanguageSettings(array $aData) { - $oCriteria = new CDbCriteria; + $oCriteria = new CDbCriteria(); $oCriteria->join = 'LEFT JOIN {{quota}} q ON {{quota_languagesettings}}.quotals_quota_id=q.id'; $oCriteria->condition = '(q.id IS NULL)'; $count = QuotaLanguageSetting::model()->deleteAll($oCriteria); @@ -371,7 +371,7 @@ private function _deleteQuotaLanguageSettings(array $aData) */ private function _deleteQuotas(array $aData) { - $oCriteria = new CDbCriteria; + $oCriteria = new CDbCriteria(); $oCriteria->join = 'LEFT JOIN {{surveys}} q ON {{quota}}.sid=q.sid'; $oCriteria->condition = '(q.sid IS NULL)'; $count = Quota::model()->deleteAll($oCriteria); @@ -386,7 +386,7 @@ private function _deleteQuotas(array $aData) */ private function _deleteDefaultValues(array $aData) { - $criteria = new CDbCriteria; + $criteria = new CDbCriteria(); $criteria->join = 'LEFT JOIN {{questions}} q ON t.qid=q.qid'; $criteria->condition = 'q.qid IS NULL'; @@ -397,7 +397,7 @@ private function _deleteDefaultValues(array $aData) $deleted = DefaultValue::model()->deleteAllByAttributes(array('dvid' => $aRecord->dvid)); $count += $deleted ; } - $aData['messages'][] = sprintf(gT('Deleting orphaned default values: %u default values deleted.'),$count); + $aData['messages'][] = sprintf(gT('Deleting orphaned default values: %u default values deleted.'), $count); return $aData; } @@ -409,11 +409,11 @@ private function _deleteDefaultValues(array $aData) */ private function _deleteQuestionAttributes(array $questionAttributes, array $aData) { - $qids = array_unique(array_column($questionAttributes,'qid')); + $qids = array_unique(array_column($questionAttributes, 'qid')); $count = 0; foreach ($qids as $qid) { - $deleted = QuestionAttribute::model()->deleteAll("qid = :qid",array(":qid"=> $qid)); - if($deleted) { + $deleted = QuestionAttribute::model()->deleteAll("qid = :qid", array(":qid" => $qid)); + if ($deleted) { $count += $deleted; } else { $aData['warnings'][] = sprintf(gT('Unable to delete question attributes for question %s'), $qid); @@ -431,11 +431,11 @@ private function _deleteQuestionAttributes(array $questionAttributes, array $aDa */ private function _deleteConditions(array $conditions, array $aData) { - $cids = array_unique(array_column($conditions,'cid')); + $cids = array_unique(array_column($conditions, 'cid')); $count = 0; foreach ($cids as $cid) { $deleted = Condition::model()->deleteByPk($cid); - if($deleted) { + if ($deleted) { $count += $deleted; } else { $aData['warnings'][] = sprintf(gT('Unable to delete condition %s'), $cid); @@ -457,7 +457,7 @@ protected function _checkintegrity() $bDirectlyFixed = false; $aFullOldSIDs = array(); // Delete survey permissions if the user does not exist - $oCriteria = new CDbCriteria; + $oCriteria = new CDbCriteria(); $oCriteria->join = 'LEFT JOIN {{users}} u ON {{permissions}}.uid=u.uid'; $oCriteria->condition = '(u.uid IS NULL)'; if (App()->db->driverName == 'pgsql') { @@ -469,7 +469,7 @@ protected function _checkintegrity() } // Delete survey permissions if the survey does not exist - $oCriteria = new CDbCriteria; + $oCriteria = new CDbCriteria(); $oCriteria->join = 'LEFT JOIN {{surveys}} s ON {{permissions}}.entity_id=s.sid'; $oCriteria->condition = "(s.sid IS NULL AND entity='survey')"; if (App()->db->driverName == 'pgsql') { @@ -487,35 +487,29 @@ protected function _checkintegrity() Yii::app()->setConfig('Updating', true); foreach ($oSurveys as $oSurvey) { - if ($oSurvey->isActive && !$oSurvey->hasResponsesTable) { - Survey::model()->updateByPk($oSurvey->sid, array('active'=>'N')); + Survey::model()->updateByPk($oSurvey->sid, array('active' => 'N')); $bDirectlyFixed = true; } } /** Check for active surveys if questions are in the correct group **/ foreach ($oSurveys as $oSurvey) { - // We get the active surveys if ($oSurvey->isActive && $oSurvey->hasResponsesTable) { - $model = SurveyDynamic::model($oSurvey->sid); $aColumns = $model->getMetaData()->columns; $aQids = array(); // We get the columns of the reponses table foreach ($aColumns as $oColumn) { - // Question columns start with the SID if (strpos($oColumn->name, (string)$oSurvey->sid) !== false) { - // Fileds are separated by X $aFields = explode('X', $oColumn->name); - if ( isset($aFields[1]) ){ - + if (isset($aFields[1])) { $sGid = $aFields[1]; // QID field can be more than just QID, like: 886other or 886A1 @@ -523,38 +517,33 @@ protected function _checkintegrity() $sDirtyQid = $aFields[2]; preg_match('~[a-zA-Z_]~i', $sDirtyQid, $match, PREG_OFFSET_CAPTURE); - if (isset($match[0][1])){ - $sQID = substr ($sDirtyQid, 0, $match[0][1]); - }else{ + if (isset($match[0][1])) { + $sQID = substr($sDirtyQid, 0, $match[0][1]); + } else { // It was just the QID.... $sQID = $sDirtyQid; } // Here, we get the question as defined in backend $oQuestion = Question::model()->findByPk([ 'qid' => $sQID , 'language' => $oSurvey->language]); - if (is_a($oQuestion, 'Question')){ - + if (is_a($oQuestion, 'Question')) { // We check if its GID is the same as the one defined in the column name - if ($oQuestion->gid != $sGid){ - + if ($oQuestion->gid != $sGid) { // If not, we change the column name - $sNvColName = $oSurvey->sid . 'X'. $oQuestion->group->gid . 'X' . $sDirtyQid; + $sNvColName = $oSurvey->sid . 'X' . $oQuestion->group->gid . 'X' . $sDirtyQid; - if ( array_key_exists( $sNvColName, $aColumns ) ){ + if (array_key_exists($sNvColName, $aColumns)) { // This case will not happen often, only when QID + Subquestion ID == QID of a question in the target group // So we'll change the group of the question question group table (so in admin interface, not in frontend) $oQuestion->gid = $sGid; $oQuestion->save(); - - }else{ + } else { $oTransaction = $oDB->beginTransaction(); - $oDB->createCommand()->renameColumn($model->tableName(), $oColumn->name , $sNvColName); + $oDB->createCommand()->renameColumn($model->tableName(), $oColumn->name, $sNvColName); $oTransaction->commit(); } - - } - }else{ + } else { // QID not found: we should do something... // $aUnfoundQIDs[] = $sQID; } @@ -603,21 +592,20 @@ protected function _checkintegrity() if (isset($aTableName[1]) && ctype_digit($aTableName[1])) { $iSurveyID = $aTableName[1]; if (!in_array($iSurveyID, $sSurveyIDs)) { - $sDate = (string) date('YmdHis').rand(1, 1000); - // Check if it's really a survey_XXX table mantis #14938 - if(empty($aTableName[2])) { + $sDate = (string) date('YmdHis') . rand(1, 1000); + // Check if it's really a survey_XXX table mantis #14938 + if (empty($aTableName[2])) { $sOldTable = "survey_{$iSurveyID}"; $sNewTable = "old_survey_{$iSurveyID}_{$sDate}"; Yii::app()->db->createCommand()->renameTable("{{{$sOldTable}}}", "{{{$sNewTable}}}"); $bDirectlyFixed = true; } - if(!empty($aTableName[2]) && $aTableName[2] == "timings" && empty($aTableName[3])) { + if (!empty($aTableName[2]) && $aTableName[2] == "timings" && empty($aTableName[3])) { $sOldTable = "survey_{$iSurveyID}_timings"; $sNewTable = "old_survey_{$iSurveyID}_timings_{$sDate}"; Yii::app()->db->createCommand()->renameTable("{{{$sOldTable}}}", "{{{$sNewTable}}}"); $bDirectlyFixed = true; } - } } } @@ -627,10 +615,10 @@ protected function _checkintegrity() foreach ($aResult as $aRow) { $sTableName = (string) substr($aRow, strlen($sDBPrefix)); $aTableName = explode('_', $sTableName); - $iSurveyID = (integer) substr($sTableName, strpos($sTableName, '_') + 1); - if (isset($aTableName[1]) && ctype_digit($aTableName[1]) && empty($aTableName[2])) { // Check if it's really a token_XXX table mantis #14938 + $iSurveyID = (int) substr($sTableName, strpos($sTableName, '_') + 1); + if (isset($aTableName[1]) && ctype_digit($aTableName[1]) && empty($aTableName[2])) { // Check if it's really a token_XXX table mantis #14938 if (!in_array($iSurveyID, $sSurveyIDs)) { - $sDate = (string) date('YmdHis').rand(1, 1000); + $sDate = (string) date('YmdHis') . rand(1, 1000); $sOldTable = "tokens_{$iSurveyID}"; $sNewTable = "old_tokens_{$iSurveyID}_{$sDate}"; Yii::app()->db->createCommand()->renameTable("{{{$sOldTable}}}", "{{{$sNewTable}}}"); @@ -662,16 +650,15 @@ protected function _checkintegrity() if ($condition['cfieldname']) { // only if cfieldname isn't Tag such as {TOKEN:EMAIL} or any other token if (preg_match('/^\+{0,1}[0-9]+X[0-9]+X*$/', $condition['cfieldname'])) { - list ($surveyid, $gid, $rest) = explode('X', $condition['cfieldname']); - $iRowCount = count(QuestionGroup::model()->findAllByAttributes(array('gid'=>$gid))); + $iRowCount = count(QuestionGroup::model()->findAllByAttributes(array('gid' => $gid))); if (!$iRowCount) { - $aDelete['conditions'][] = array('cid' => $condition['cid'], 'reason' => gT('No matching CFIELDNAME group!')." ($gid) ({$condition['cfieldname']})"); + $aDelete['conditions'][] = array('cid' => $condition['cid'], 'reason' => gT('No matching CFIELDNAME group!') . " ($gid) ({$condition['cfieldname']})"); } } } elseif (!$condition['cfieldname']) { - $aDelete['conditions'][] = array('cid' => $condition['cid'], 'reason' => gT('No CFIELDNAME field set!')." ({$condition['cfieldname']})"); + $aDelete['conditions'][] = array('cid' => $condition['cid'], 'reason' => gT('No CFIELDNAME field set!') . " ({$condition['cfieldname']})"); } } unset($okQuestion); @@ -688,7 +675,7 @@ protected function _checkintegrity() /**********************************************************************/ /* Check default values */ /**********************************************************************/ - $oCriteria = new CDbCriteria; + $oCriteria = new CDbCriteria(); $oCriteria->join = 'LEFT JOIN {{questions}} q ON t.qid=q.qid'; $oCriteria->condition = 'q.qid IS NULL'; $aRecords = DefaultValue::model()->findAll($oCriteria); @@ -698,7 +685,7 @@ protected function _checkintegrity() /* Check quotas */ /**********************************************************************/ - $oCriteria = new CDbCriteria; + $oCriteria = new CDbCriteria(); $oCriteria->join = 'LEFT JOIN {{surveys}} s ON t.sid=s.sid'; $oCriteria->condition = '(s.sid IS NULL)'; $aDelete['quotas'] = count(Quota::model()->findAll($oCriteria)); @@ -706,7 +693,7 @@ protected function _checkintegrity() /**********************************************************************/ /* Check quota languagesettings */ /**********************************************************************/ - $oCriteria = new CDbCriteria; + $oCriteria = new CDbCriteria(); $oCriteria->join = 'LEFT JOIN {{quota}} s ON t.quotals_quota_id=s.id'; $oCriteria->condition = '(s.id IS NULL)'; $aDelete['quotals'] = count(QuotaLanguageSetting::model()->findAll($oCriteria)); @@ -714,7 +701,7 @@ protected function _checkintegrity() /**********************************************************************/ /* Check quota members */ /**********************************************************************/ - $oCriteria = new CDbCriteria; + $oCriteria = new CDbCriteria(); $oCriteria->join = 'LEFT JOIN {{questions}} q ON t.qid=q.qid LEFT JOIN {{surveys}} s ON t.sid=s.sid'; $oCriteria->condition = '(q.qid IS NULL) OR (s.sid IS NULL)'; @@ -723,7 +710,7 @@ protected function _checkintegrity() /**********************************************************************/ /* Check assessments */ /**********************************************************************/ - $oCriteria = new CDbCriteria; + $oCriteria = new CDbCriteria(); $oCriteria->compare('scope', 'T'); $assessments = Assessment::model()->findAll($oCriteria); @@ -734,11 +721,11 @@ protected function _checkintegrity() } } - $oCriteria = new CDbCriteria; + $oCriteria = new CDbCriteria(); $oCriteria->compare('scope', 'G'); $assessments = Assessment::model()->findAll($oCriteria); foreach ($assessments as $assessment) { - $iAssessmentCount = count(QuestionGroup::model()->findAllByPk(array('gid'=>$assessment['gid'], 'language'=>$assessment['language']))); + $iAssessmentCount = count(QuestionGroup::model()->findAllByPk(array('gid' => $assessment['gid'], 'language' => $assessment['language']))); if (!$iAssessmentCount) { $aDelete['assessments'][] = array('id' => $assessment['id'], 'assessment' => $assessment['name'], 'reason' => gT('No matching group')); } @@ -747,7 +734,7 @@ protected function _checkintegrity() /**********************************************************************/ /* Check answers */ /**********************************************************************/ - $oCriteria = new CDbCriteria; + $oCriteria = new CDbCriteria(); $oCriteria->join = 'LEFT JOIN {{questions}} q ON t.qid=q.qid'; $oCriteria->condition = '(q.qid IS NULL)'; @@ -765,9 +752,9 @@ protected function _checkintegrity() $aLanguages[] = $survey->language; foreach ($aLanguages as $langname) { if ($langname) { - $oLanguageSettings = SurveyLanguageSetting::model()->find('surveyls_survey_id=:surveyid AND surveyls_language=:langname', array(':surveyid'=>$survey->sid, ':langname'=>$langname)); + $oLanguageSettings = SurveyLanguageSetting::model()->find('surveyls_survey_id=:surveyid AND surveyls_language=:langname', array(':surveyid' => $survey->sid, ':langname' => $langname)); if (!$oLanguageSettings) { - $oLanguageSettings = new SurveyLanguageSetting; + $oLanguageSettings = new SurveyLanguageSetting(); $languagedetails = getLanguageDetails($langname); $insertdata = array( 'surveyls_survey_id' => $survey->sid, @@ -799,37 +786,37 @@ protected function _checkintegrity() /**********************************************************************/ /* Check questions */ /**********************************************************************/ - $oCriteria = new CDbCriteria; + $oCriteria = new CDbCriteria(); $quotedGroups = Yii::app()->db->quoteTableName('{{groups}}'); $oCriteria->join = "LEFT JOIN {{surveys}} s ON t.sid=s.sid LEFT JOIN $quotedGroups g ON t.gid=g.gid"; $oCriteria->condition = '(g.gid IS NULL) OR (s.sid IS NULL)'; $questions = Question::model()->findAll($oCriteria); foreach ($questions as $question) { - $aDelete['questions'][] = array('qid' => $question['qid'], 'reason' => gT('No matching group')." ({$question['gid']})"); + $aDelete['questions'][] = array('qid' => $question['qid'], 'reason' => gT('No matching group') . " ({$question['gid']})"); } /**********************************************************************/ /* Check groups */ /**********************************************************************/ - $oCriteria = new CDbCriteria; + $oCriteria = new CDbCriteria(); $oCriteria->join = 'LEFT JOIN {{surveys}} s ON t.sid=s.sid'; $oCriteria->condition = '(s.sid IS NULL)'; $groups = QuestionGroup::model()->findAll($oCriteria); /** @var QuestionGroup $group */ foreach ($groups as $group) { - $aDelete['groups'][] = array('gid' => $group['gid'], 'reason' => gT('There is no matching survey.').' SID:'.$group['sid']); + $aDelete['groups'][] = array('gid' => $group['gid'], 'reason' => gT('There is no matching survey.') . ' SID:' . $group['sid']); } /**********************************************************************/ /* Check orphan user_in_groups */ /**********************************************************************/ - $oCriteria = new CDbCriteria; + $oCriteria = new CDbCriteria(); $oCriteria->join = 'LEFT JOIN {{user_groups}} ug ON t.ugid=ug.ugid'; $oCriteria->condition = '(ug.ugid IS NULL)'; $userInGroups = UserInGroup::model()->findAll($oCriteria); /** @var UserInGroup[] $userInGroups */ foreach ($userInGroups as $userInGroup) { - $aDelete['user_in_groups'][] = array('ugid' => $userInGroup->ugid,'uid' => $userInGroup->uid, 'reason' => sprintf(gT('There is no matching user %s in group %s.'),$userInGroup->uid,$userInGroup->ugid)); + $aDelete['user_in_groups'][] = array('ugid' => $userInGroup->ugid,'uid' => $userInGroup->uid, 'reason' => sprintf(gT('There is no matching user %s in group %s.'), $userInGroup->uid, $userInGroup->ugid)); } /**********************************************************************/ @@ -862,13 +849,11 @@ protected function _checkintegrity() } } else { foreach ($aFullOldSIDs[$iOldSID] as $sTableName) { - $aTableParts = explode('_', substr($sTableName, strlen($sDBPrefix))); $sDateTime = $sType = ''; $iSurveyID = $aTableParts[2]; if (count($aTableParts) == 4) { - $sDateTime = $aTableParts[3]; $sType = gT('responses'); } elseif (count($aTableParts) == 5) { @@ -888,9 +873,9 @@ protected function _checkintegrity() $dateformatdetails = getDateFormatData(Yii::app()->session['dateformat']); Yii::app()->loadLibrary('Date_Time_Converter'); $datetimeobj = new date_time_converter(dateShift($sDate, 'Y-m-d H:i:s', getGlobalSetting('timeadjust')), 'Y-m-d H:i:s'); - $sDate = $datetimeobj->convert($dateformatdetails['phpdate']." H:i"); + $sDate = $datetimeobj->convert($dateformatdetails['phpdate'] . " H:i"); - $sQuery = 'SELECT count(*) as recordcount FROM '.$sTableName; + $sQuery = 'SELECT count(*) as recordcount FROM ' . $sTableName; $aFirstRow = Yii::app()->db->createCommand($sQuery)->queryRow(); if ($aFirstRow['recordcount'] == 0) { // empty table - so add it to immediate deletion @@ -942,7 +927,7 @@ protected function _checkintegrity() $iHour = (int) substr($sDateTime, 8, 2); $iMinute = (int) substr($sDateTime, 10, 2); $sDate = (string) date('Y-m-d H:i:s', (int) mktime($iHour, $iMinute, 0, $iMonth, $iDay, $iYear)); - $sQuery = 'SELECT count(*) as recordcount FROM '.$sTableName; + $sQuery = 'SELECT count(*) as recordcount FROM ' . $sTableName; $aFirstRow = Yii::app()->db->createCommand($sQuery)->queryRow(); if ($aFirstRow['recordcount'] == 0) { @@ -955,7 +940,8 @@ protected function _checkintegrity() } } - if ($aDelete['defaultvalues'] == 0 && $aDelete['quotamembers'] == 0 && + if ( + $aDelete['defaultvalues'] == 0 && $aDelete['quotamembers'] == 0 && $aDelete['quotas'] == 0 && $aDelete['quotals'] == 0 && count($aDelete) == 4 ) { $aDelete['integrityok'] = true; @@ -1085,7 +1071,6 @@ protected function checkQuestionOrderDuplicates() 'qid' => $info['parent_qid'] ] ); - } } } diff --git a/application/controllers/admin/conditionsaction.php b/application/controllers/admin/conditionsaction.php index 7a1e5f44beb..c0e50e6cd53 100644 --- a/application/controllers/admin/conditionsaction.php +++ b/application/controllers/admin/conditionsaction.php @@ -1,5 +1,7 @@ -createUrl('questionAdministration/view/surveyid/'.$iSurveyID.'/gid/'.$gid.'/qid/'.$qid); // Close button + $aData['closeUrl'] = Yii::app()->createUrl('questionAdministration/view/surveyid/' . $iSurveyID . '/gid/' . $gid . '/qid/' . $qid); // Close button $aData['currentMode'] = ($subaction == 'conditions' || $subaction == 'copyconditionsform') ? $subaction : 'edit'; //$aData['questionbar']['buttons']['conditions'] = true; @@ -165,14 +167,14 @@ public function index($subaction, $iSurveyID = null, $gid = null, $qid = null) $p_scenario = returnGlobal('scenario'); $p_cqid = returnGlobal('cqid'); if ($p_cqid == '') { - // we are not using another question as source of condition - $p_cqid = 0; + // we are not using another question as source of condition + $p_cqid = 0; } $p_cid = returnGlobal('cid'); $p_subaction = $subaction; $p_cquestions = returnGlobal('cquestions'); - $p_csrctoken = returnGlobal('csrctoken'); + $p_csrctoken = returnGlobal('csrctoken'); $p_prevquestionsgqa = returnGlobal('prevQuestionSGQA'); $p_canswers = null; @@ -282,8 +284,8 @@ public function index($subaction, $iSurveyID = null, $gid = null, $qid = null) if (isset($postquestionscount) && $postquestionscount > 0) { //Build the array used for the questionNav and copyTo select boxes foreach ($postrows as $pr) { - $pquestions[] = array("text" => $pr['title'].": ".(string) substr(strip_tags($pr['question']), 0, 80), - "fieldname" => $pr['sid']."X".$pr['gid']."X".$pr['qid']); + $pquestions[] = array("text" => $pr['title'] . ": " . (string) substr(strip_tags($pr['question']), 0, 80), + "fieldname" => $pr['sid'] . "X" . $pr['gid'] . "X" . $pr['qid']); } } @@ -304,7 +306,7 @@ public function index($subaction, $iSurveyID = null, $gid = null, $qid = null) $aViewUrls = array(); - $oQuestion = Question::model()->find('qid=:qid', array(':qid'=>$qid)); + $oQuestion = Question::model()->find('qid=:qid', array(':qid' => $qid)); $aData['oQuestion'] = $oQuestion; $aData['surveyid'] = $iSurveyID; @@ -362,32 +364,32 @@ public function index($subaction, $iSurveyID = null, $gid = null, $qid = null) $aData['questionNavOptions'] = $questionNavOptions; $aData['conditionsoutput_action_error'] = $conditionsoutput_action_error; $aData['javascriptpre'] = $javascriptpre; - $aData['sCurrentQuestionText'] = $questiontitle.': '.viewHelper::flatEllipsizeText($sCurrentFullQuestionText, true, '120'); + $aData['sCurrentQuestionText'] = $questiontitle . ': ' . viewHelper::flatEllipsizeText($sCurrentFullQuestionText, true, '120'); //$aData['subaction'] = $subaction; $aData['scenariocount'] = $scenariocount; $aViewUrls['conditionslist_view'][] = $aData; if ($scenariocount > 0) { - App()->getClientScript()->registerScriptFile(App()->getConfig('adminscripts').'checkgroup.js', LSYii_ClientScript::POS_BEGIN); + App()->getClientScript()->registerScriptFile(App()->getConfig('adminscripts') . 'checkgroup.js', LSYii_ClientScript::POS_BEGIN); foreach ($scenarios as $scenarionr) { - if ($s == 0 && $scenariocount > 1) { $aData['showScenarioText'] = 'normal'; - } else if ($s > 0) { + } elseif ($s > 0) { $aData['showScenarioText'] = 'withOr'; } else { $aData['showScenarioText'] = null; } - if (!empty($aData['showScenarioText']) && - ($subaction == "editconditionsform" - || $subaction == "insertcondition" - || $subaction == "updatecondition" - || $subaction == "editthiscondition" - || $subaction == "renumberscenarios" - || $subaction == "updatescenario" - || $subaction == "deletescenario" - || $subaction == "delete") + if ( + !empty($aData['showScenarioText']) && + ($subaction == "editconditionsform" || + $subaction == "insertcondition" || + $subaction == "updatecondition" || + $subaction == "editthiscondition" || + $subaction == "renumberscenarios" || + $subaction == "updatescenario" || + $subaction == "deletescenario" || + $subaction == "delete") ) { $aData['showScenarioButtons'] = true; } else { @@ -432,7 +434,7 @@ public function index($subaction, $iSurveyID = null, $gid = null, $qid = null) ////////////////// BUILD CONDITIONS DISPLAY if ($conditionscount > 0) { - $aConditionsMerged = Array(); + $aConditionsMerged = array(); foreach ($resulttoken->readAll() as $arow) { $aConditionsMerged[] = $arow; } @@ -441,7 +443,9 @@ public function index($subaction, $iSurveyID = null, $gid = null, $qid = null) } foreach ($aConditionsMerged as $rows) { - if ($rows['method'] == "") {$rows['method'] = "=="; } //Fill in the empty method from previous versions + if ($rows['method'] == "") { + $rows['method'] = "=="; + } //Fill in the empty method from previous versions // This variable is used for condition.php view; $aData is used for other view $data = array(); @@ -474,8 +478,8 @@ public function index($subaction, $iSurveyID = null, $gid = null, $qid = null) $leftOperandType = 'unknown'; // prevquestion, tokenattr if (preg_match('/^{TOKEN:([^}]*)}$/', $rows['cfieldname'], $extractedTokenAttr) > 0) { - if($surveyIsAnonymized) { - $data['name'] = sprintf(gT("Unable to use %s in anonymized survey."),trim($rows['cfieldname'],"{}")); + if ($surveyIsAnonymized) { + $data['name'] = sprintf(gT("Unable to use %s in anonymized survey."), trim($rows['cfieldname'], "{}")); } else { $leftOperandType = 'tokenattr'; $thisAttrName = $this->getAttributeName($extractedTokenAttr); @@ -490,16 +494,16 @@ public function index($subaction, $iSurveyID = null, $gid = null, $qid = null) $leftOperandType = 'prevquestion'; foreach ($cquestions as $cqn) { if ($cqn[3] == $rows['cfieldname']) { - $data['name'] = $cqn[0]."(qid{$rows['cqid']})"; + $data['name'] = $cqn[0] . "(qid{$rows['cqid']})"; $conditionsList[] = array( "cid" => $rows['cid'], - "text" => $cqn[0]." ({$rows['value']})" + "text" => $cqn[0] . " ({$rows['value']})" ); } } } - if(!isset($data['name'])) { - $data['name'] = sprintf(gT("Variable not found: %s"),$rows['cfieldname']); + if (!isset($data['name'])) { + $data['name'] = sprintf(gT("Variable not found: %s"), $rows['cfieldname']); } // let's read the condition's right operand @@ -522,7 +526,7 @@ public function index($subaction, $iSurveyID = null, $gid = null, $qid = null) } if ($textfound === false) { - $matchedSGQAText = $rows['value'].' ('.gT("Not found").')'; + $matchedSGQAText = $rows['value'] . ' (' . gT("Not found") . ')'; } $data['target'] = HTMLEscape($matchedSGQAText); @@ -530,9 +534,9 @@ public function index($subaction, $iSurveyID = null, $gid = null, $qid = null) $rightOperandType = 'tokenAttr'; $aTokenAttrNames = $this->tokenFieldsAndNames; if ($this->tokenTableExists) { - $thisAttrName = HTMLEscape($aTokenAttrNames[strtolower($extractedTokenAttr[1])]['description'])." [".gT("From survey participants table")."]"; + $thisAttrName = HTMLEscape($aTokenAttrNames[strtolower($extractedTokenAttr[1])]['description']) . " [" . gT("From survey participants table") . "]"; } else { - $thisAttrName = HTMLEscape($extractedTokenAttr[1])." [".gT("Non-existing survey participants table")."]"; + $thisAttrName = HTMLEscape($extractedTokenAttr[1]) . " [" . gT("Non-existing survey participants table") . "]"; } $data['target'] = $thisAttrName; } elseif (isset($canswers)) { @@ -554,7 +558,8 @@ public function index($subaction, $iSurveyID = null, $gid = null, $qid = null) } } - if ($subaction == "editconditionsform" + if ( + $subaction == "editconditionsform" || $subaction == "insertcondition" || $subaction == "updatecondition" || $subaction == "editthiscondition" @@ -586,7 +591,6 @@ public function index($subaction, $iSurveyID = null, $gid = null, $qid = null) $currentfield = $rows['cfieldname']; } - } $s++; @@ -607,17 +611,19 @@ public function index($subaction, $iSurveyID = null, $gid = null, $qid = null) //// To close the div opened in condition header.... see : https://goo.gl/BY7gUJ $aViewUrls['afteroutput'] = ''; - } //END DISPLAY CONDITIONS FOR THIS QUESTION // Display the copy conditions form - if ($subaction == "copyconditionsform" - || $subaction == "copyconditions") { + if ( + $subaction == "copyconditionsform" + || $subaction == "copyconditions" + ) { $aViewUrls['output'] .= $this->getCopyForm($qid, $gid, $conditionsList, $pquestions); } - if ($subaction == "editconditionsform" + if ( + $subaction == "editconditionsform" || $subaction == "insertcondition" || $subaction == "updatecondition" || $subaction == "deletescenario" @@ -671,7 +677,7 @@ protected function resetSurveyLogic($iSurveyID) LimeExpressionManager::RevertUpgradeConditionsToRelevance($iSurveyID); Condition::model()->deleteRecords("qid in (select qid from {{questions}} where sid={$iSurveyID})"); Yii::app()->setFlashMessage(gT("All conditions in this survey have been deleted.")); - $this->getController()->redirect(array('surveyAdministration/view/surveyid/'.$iSurveyID)); + $this->getController()->redirect(array('surveyAdministration/view/surveyid/' . $iSurveyID)); } } @@ -709,7 +715,6 @@ protected function insertCondition(array $args) ); if ($p_canswers) { - $results = array(); foreach ($p_canswers as $ca) { @@ -721,14 +726,15 @@ protected function insertCondition(array $args) $count_caseinsensitivedupes = count($result); if ($count_caseinsensitivedupes == 0) { - $results[] = Condition::model()->insertRecords($condition_data); ; + $results[] = Condition::model()->insertRecords($condition_data); + ; } } // Check if any result returned false if (in_array(false, $results, true)) { Yii::app()->setFlashMessage(gT('Could not insert all conditions.'), 'error'); - } else if (!empty($results)) { + } elseif (!empty($results)) { Yii::app()->setFlashMessage(gT('Condition added.'), 'success'); } else { Yii::app()->setFlashMessage( @@ -739,7 +745,6 @@ protected function insertCondition(array $args) 'error' ); } - } else { $posted_condition_value = null; $request = Yii::app()->request; @@ -747,33 +752,33 @@ protected function insertCondition(array $args) // Other conditions like constant, other question or token field switch ($request->getPost('editTargetTab')) { case '#CONST': - $posted_condition_value = Yii::app()->request->getPost('ConditionConst',''); + $posted_condition_value = Yii::app()->request->getPost('ConditionConst', ''); break; case '#PREVQUESTIONS': - $posted_condition_value = Yii::app()->request->getPost('prevQuestionSGQA',''); + $posted_condition_value = Yii::app()->request->getPost('prevQuestionSGQA', ''); break; case '#TOKENATTRS': - $posted_condition_value = Yii::app()->request->getPost('tokenAttr',''); + $posted_condition_value = Yii::app()->request->getPost('tokenAttr', ''); break; case '#REGEXP': - $posted_condition_value = Yii::app()->request->getPost('ConditionRegexp',''); + $posted_condition_value = Yii::app()->request->getPost('ConditionRegexp', ''); break; default: $posted_condition_value = null; } $result = null; - if ($posted_condition_value !=='') { + if ($posted_condition_value !== '') { $condition_data['value'] = $posted_condition_value; $result = Condition::model()->insertRecords($condition_data); } - if($result) { + if ($result) { Yii::app()->setFlashMessage(gT('Condition added.'), 'success'); } else { - if($result === false) { + if ($result === false) { Yii::app()->setFlashMessage(gT('Could not insert all conditions.'), 'error'); } else { - Yii::app()->setFlashMessage(gT("The condition could not be added! It did not include the question and/or answer upon which the condition was based. Please ensure you have selected a question and an answer."),'error'); + Yii::app()->setFlashMessage(gT("The condition could not be added! It did not include the question and/or answer upon which the condition was based. Please ensure you have selected a question and an answer."), 'error'); } } } @@ -822,7 +827,6 @@ protected function insertConditionAjax($args) ); if (!empty($canswers) && $editSourceTab == '#SRCPREVQUEST') { - $results = array(); foreach ($canswers as $ca) { @@ -834,14 +838,15 @@ protected function insertConditionAjax($args) $count_caseinsensitivedupes = count($result); if ($count_caseinsensitivedupes == 0) { - $results[] = Condition::model()->insertRecords($condition_data); ; + $results[] = Condition::model()->insertRecords($condition_data); + ; } } // Check if any result returned false if (in_array(false, $results, true)) { return array(gT('Could not insert all conditions.'), 'error'); - } else if (!empty($results)) { + } elseif (!empty($results)) { return array(gT('Condition added.'), 'success'); } else { return array( @@ -875,7 +880,7 @@ protected function insertConditionAjax($args) if ($result === false) { return array(gT('Could not insert all conditions.'), 'error'); - } else if ($result === true) { + } elseif ($result === true) { return array(gT('Condition added.'), 'success'); } else { return array( @@ -905,10 +910,10 @@ public function quickAddCondition() if ($status == 'success') { LimeExpressionManager::UpgradeConditionsToRelevance(null, $data['qid']); ls\ajax\AjaxHelper::outputSuccess($message); - } else if ($status == 'error') { + } elseif ($status == 'error') { ls\ajax\AjaxHelper::outputError($message); } else { - ls\ajax\AjaxHelper::outputError('Internal error: Could not add condition, status unknown: '.$status); + ls\ajax\AjaxHelper::outputError('Internal error: Could not add condition, status unknown: ' . $status); } } @@ -939,7 +944,7 @@ protected function getQuickAddData(LSHttpRequest $request) 'tokenAttr' ); foreach ($keys as $key) { - $value = $request->getPost('quick-add-'.$key); + $value = $request->getPost('quick-add-' . $key); $value = str_replace('QUICKADD-', '', $value); // Remove QUICKADD- from editSourceTab/editTargetTab $result[$key] = $value; } @@ -984,13 +989,13 @@ protected function updateCondition(array $args) 'method' => $p_method, 'value' => $ca ); - $results[] = Condition::model()->insertRecords($updated_data, true, array('cid'=>$p_cid)); + $results[] = Condition::model()->insertRecords($updated_data, true, array('cid' => $p_cid)); } // Check if any result returned false if (in_array(false, $results, true)) { Yii::app()->setFlashMessage(gT('Could not update condition.'), 'error'); - } else if (!empty($results)) { + } elseif (!empty($results)) { Yii::app()->setFlashMessage(gT('Condition updated.'), 'success'); } else { Yii::app()->setFlashMessage(gT('Could not update condition.'), 'error'); @@ -998,16 +1003,16 @@ protected function updateCondition(array $args) } else { switch ($request->getPost('editTargetTab')) { case "#CONST": - $posted_condition_value = Yii::app()->request->getPost('ConditionConst',''); + $posted_condition_value = Yii::app()->request->getPost('ConditionConst', ''); break; case "#PREVQUESTIONS": - $posted_condition_value = Yii::app()->request->getPost('prevQuestionSGQA',''); + $posted_condition_value = Yii::app()->request->getPost('prevQuestionSGQA', ''); break; case "#TOKENATTRS": - $posted_condition_value = Yii::app()->request->getPost('tokenAttr',''); + $posted_condition_value = Yii::app()->request->getPost('tokenAttr', ''); break; case "#REGEXP": - $posted_condition_value = Yii::app()->request->getPost('ConditionRegexp',''); + $posted_condition_value = Yii::app()->request->getPost('ConditionRegexp', ''); break; default: $posted_condition_value = null; @@ -1023,15 +1028,15 @@ protected function updateCondition(array $args) 'method' => $p_method, 'value' => $posted_condition_value ); - $result = Condition::model()->insertRecords($updated_data, true, array('cid'=>$p_cid)); + $result = Condition::model()->insertRecords($updated_data, true, array('cid' => $p_cid)); } if ($result) { Yii::app()->setFlashMessage(gT('Condition updated.'), 'success'); } else { - if($result === false) { + if ($result === false) { Yii::app()->setFlashMessage(gT('Could not update condition.'), 'error'); } else { - Yii::app()->setFlashMessage(gT("The condition could not be updated! It did not include the question and/or answer upon which the condition was based. Please ensure you have selected a question and an answer."),'error'); + Yii::app()->setFlashMessage(gT("The condition could not be updated! It did not include the question and/or answer upon which the condition was based. Please ensure you have selected a question and an answer."), 'error'); } } } @@ -1055,7 +1060,7 @@ protected function renumberScenarios(array $args) $newindex = 1; foreach ($result->readAll() as $srow) { - Condition::model()->insertRecords(array('scenario'=>$newindex), true, array('qid'=>$qid, 'scenario'=>$srow['scenario'])); + Condition::model()->insertRecords(array('scenario' => $newindex), true, array('qid' => $qid, 'scenario' => $srow['scenario'])); $newindex++; } LimeExpressionManager::UpgradeConditionsToRelevance(null, $qid); @@ -1079,7 +1084,7 @@ protected function copyConditions(array $args) $entry = Yii::app()->db->quoteValue($entry); } $query = "SELECT * FROM {{conditions}}\n" - ."WHERE cid in ("; + . "WHERE cid in ("; $query .= implode(", ", $copyconditionsfrom); $query .= ")"; $result = Yii::app()->db->createCommand($query)->query() or @@ -1172,28 +1177,28 @@ protected function applySubaction($p_subaction, array $args) // Delete entry if this is delete case "delete": LimeExpressionManager::RevertUpgradeConditionsToRelevance(null, $qid); // in case deleted the last condition - Condition::model()->deleteRecords(array('cid'=>$p_cid)); + Condition::model()->deleteRecords(array('cid' => $p_cid)); LimeExpressionManager::UpgradeConditionsToRelevance(null, $qid); $this->redirectToConditionStart($qid, $gid); break; // Delete all conditions in this scenario case "deletescenario": LimeExpressionManager::RevertUpgradeConditionsToRelevance(null, $qid); // in case deleted the last condition - Condition::model()->deleteRecords(array('qid'=>$qid, 'scenario'=>$p_scenario)); + Condition::model()->deleteRecords(array('qid' => $qid, 'scenario' => $p_scenario)); LimeExpressionManager::UpgradeConditionsToRelevance(null, $qid); $this->redirectToConditionStart($qid, $gid); break; // Update scenario case "updatescenario": // TODO: Check if $p_newscenarionum is null - Condition::model()->insertRecords(array('scenario'=>$p_newscenarionum), true, array( - 'qid'=>$qid, 'scenario'=>$p_scenario)); + Condition::model()->insertRecords(array('scenario' => $p_newscenarionum), true, array( + 'qid' => $qid, 'scenario' => $p_scenario)); LimeExpressionManager::UpgradeConditionsToRelevance(null, $qid); break; // Delete all conditions for this question case "deleteallconditions": LimeExpressionManager::RevertUpgradeConditionsToRelevance(null, $qid); // in case deleted the last condition - Condition::model()->deleteRecords(array('qid'=>$qid)); + Condition::model()->deleteRecords(array('qid' => $qid)); Yii::app()->setFlashMessage(gT("All conditions for this question have been deleted."), 'success'); $this->redirectToConditionStart($qid, $gid); break; @@ -1233,14 +1238,13 @@ protected function getTheseRows(array $questionlist) { $theserows = array(); foreach ($questionlist as $ql) { - $result = Question::model()->with(array( 'group' => array( 'condition' => 'questiongroupl10ns.language = :lang', 'params' => array(':lang' => $this->language), 'alias' => 'group', ), - 'group.questiongroupl10ns' => array('alias' =>'questiongroupl10ns' ), + 'group.questiongroupl10ns' => array('alias' => 'questiongroupl10ns' ), 'questionl10ns' ))->findAllByAttributes(array('qid' => $ql, 'parent_qid' => 0, 'sid' => $this->iSurveyID)); @@ -1315,10 +1319,9 @@ protected function getQuestionRows() { $qresult = Question::model()->findAllByAttributes(array( 'parent_qid' => 0, - 'sid' => $this->iSurveyID) - ); + 'sid' => $this->iSurveyID)); - //'language' => $this->language + //'language' => $this->language $qrows = array(); foreach ($qresult as $k => $v) { $qrows[$k] = array_merge($v->attributes, $v->group->attributes); @@ -1385,38 +1388,45 @@ protected function getCAnswersAndCQuestions(array $theserows) $canswers = array(); foreach ($theserows as $rows) { - $shortquestion = $rows['title'].": ".strip_tags($rows['question']); + $shortquestion = $rows['title'] . ": " . strip_tags($rows['question']); if ($rows['type'] == "A" || $rows['type'] == "B" || $rows['type'] == "C" || $rows['type'] == "E" || $rows['type'] == "F" || $rows['type'] == "H") { - - $aresult = Question::model()->with('questionl10ns')->findAllByAttributes(array('parent_qid'=>$rows['qid']), array('order' => 'question_order ASC')); + $aresult = Question::model()->with('questionl10ns')->findAllByAttributes(array('parent_qid' => $rows['qid']), array('order' => 'question_order ASC')); foreach ($aresult as $arows) { - $shortanswer = "{$arows['title']}: [".flattenText($arows->questionl10ns[$this->language]->question)."]"; - $shortquestion = $rows['title'].":$shortanswer ".flattenText($rows['question']); + $shortanswer = "{$arows['title']}: [" . flattenText($arows->questionl10ns[$this->language]->question) . "]"; + $shortquestion = $rows['title'] . ":$shortanswer " . flattenText($rows['question']); $cquestions[] = array($shortquestion, $rows['qid'], $rows['type'], - $rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$arows['title'] + $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'] ); switch ($rows['type']) { //Array 5 buttons - case "A": for ($i = 1; $i <= 5; $i++) { $canswers[] = array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$arows['title'], $i, $i); } break; + case "A": + for ($i = 1; $i <= 5; $i++) { + $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], $i, $i); + } + break; //Array 10 buttons - case "B": for ($i = 1; $i <= 10; $i++) { $canswers[] = array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$arows['title'], $i, $i); } break; + case "B": + for ($i = 1; $i <= 10; $i++) { + $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], $i, $i); + } + break; //Array Y/N/NA case "C": - $canswers[] = array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$arows['title'], "Y", gT("Yes")); - $canswers[] = array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$arows['title'], "U", gT("Uncertain")); - $canswers[] = array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$arows['title'], "N", gT("No")); + $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], "Y", gT("Yes")); + $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], "U", gT("Uncertain")); + $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], "N", gT("No")); break; //Array >/=/< case "E": - $canswers[] = array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$arows['title'], "I", gT("Increase")); - $canswers[] = array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$arows['title'], "S", gT("Same")); - $canswers[] = array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$arows['title'], "D", gT("Decrease")); + $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], "I", gT("Increase")); + $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], "S", gT("Same")); + $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], "D", gT("Decrease")); break; //Array Flexible Row - case "F": + case "F": //Array Flexible Column case "H": $fresult = Answer::model()->with(array( @@ -1428,18 +1438,19 @@ protected function getCAnswersAndCQuestions(array $theserows) array( 'qid' => $rows['qid'], 'scale_id' => 0, - ), array('order' => 'sortorder, code') + ), + array('order' => 'sortorder, code') ); - foreach ($fresult as $frow) { $canswers[] = array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$arows['title'], $frow['code'], $frow->answerl10ns[$this->language]->answer); } + foreach ($fresult as $frow) { + $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], $frow['code'], $frow->answerl10ns[$this->language]->answer); + } break; } // Only Show No-Answer if question is not mandatory if ($rows['mandatory'] != 'Y' && $rows['mandatory'] != 'S') { - $canswers[] = array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$arows['title'], "", gT("No answer")); + $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], "", gT("No answer")); } - } //foreach - } elseif ($rows['type'] == Question::QT_COLON_ARRAY_MULTI_FLEX_NUMBERS || $rows['type'] == Question::QT_SEMICOLON_ARRAY_MULTI_FLEX_TEXT) { // Multiflexi // Get the Y-Axis @@ -1481,9 +1492,9 @@ protected function getCAnswersAndCQuestions(array $theserows) } foreach ($y_axis_db->readAll() as $yrow) { - foreach ($x_axis as $key=>$val) { - $shortquestion = $rows['title'].":{$yrow['title']}:$key: [".strip_tags($yrow['question'])."][".strip_tags($val)."] ".flattenText($rows['question']); - $cquestions[] = array($shortquestion, $rows['qid'], $rows['type'], $rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$yrow['title']."_".$key); + foreach ($x_axis as $key => $val) { + $shortquestion = $rows['title'] . ":{$yrow['title']}:$key: [" . strip_tags($yrow['question']) . "][" . strip_tags($val) . "] " . flattenText($rows['question']); + $cquestions[] = array($shortquestion, $rows['qid'], $rows['type'], $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $yrow['title'] . "_" . $key); if ($rows['mandatory'] != 'Y' && $rows['mandatory'] != 'S') { } } @@ -1502,13 +1513,13 @@ protected function getCAnswersAndCQuestions(array $theserows) // dualscale_header are allways set, but can be empty $label1 = empty($attr['dualscale_headerA'][$sLanguage]) ? gT('Scale 1') : $attr['dualscale_headerA'][$sLanguage]; $label2 = empty($attr['dualscale_headerB'][$sLanguage]) ? gT('Scale 2') : $attr['dualscale_headerB'][$sLanguage]; - $shortanswer = "{$arows['title']}: [".strip_tags($arows->questionl10ns[$this->language]->question)."][$label1]"; - $shortquestion = $rows['title'].":$shortanswer ".strip_tags($arows->questionl10ns[$this->language]->question); - $cquestions[] = array($shortquestion, $rows['qid'], $rows['type'], $rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$arows['title']."#0"); + $shortanswer = "{$arows['title']}: [" . strip_tags($arows->questionl10ns[$this->language]->question) . "][$label1]"; + $shortquestion = $rows['title'] . ":$shortanswer " . strip_tags($arows->questionl10ns[$this->language]->question); + $cquestions[] = array($shortquestion, $rows['qid'], $rows['type'], $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'] . "#0"); - $shortanswer = "{$arows['title']}: [".strip_tags($arows->questionl10ns[$this->language]->question)."][$label2]"; - $shortquestion = $rows['title'].":$shortanswer ".strip_tags($arows->questionl10ns[$this->language]->question); - $cquestions[] = array($shortquestion, $rows['qid'], $rows['type'], $rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$arows['title']."#1"); + $shortanswer = "{$arows['title']}: [" . strip_tags($arows->questionl10ns[$this->language]->question) . "][$label2]"; + $shortquestion = $rows['title'] . ":$shortanswer " . strip_tags($arows->questionl10ns[$this->language]->question); + $cquestions[] = array($shortquestion, $rows['qid'], $rows['type'], $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'] . "#1"); // first label $lresult = Answer::model()->with(array( @@ -1517,7 +1528,7 @@ protected function getCAnswersAndCQuestions(array $theserows) 'params' => array(':lang' => $this->language) )))->findAllByAttributes(array('qid' => $rows['qid'], 'scale_id' => 0), array('order' => 'sortorder, answer')); foreach ($lresult as $lrows) { - $canswers[] = array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$arows['title']."#0", "{$lrows['code']}", "{$lrows['code']}"); + $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'] . "#0", "{$lrows['code']}", "{$lrows['code']}"); } // second label @@ -1528,16 +1539,16 @@ protected function getCAnswersAndCQuestions(array $theserows) )))->findAllByAttributes(array( 'qid' => $rows['qid'], 'scale_id' => 1 - ), array('order' => 'sortorder, answer')); + ), array('order' => 'sortorder, answer')); foreach ($lresult as $lrows) { - $canswers[] = array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$arows['title']."#1", "{$lrows['code']}", "{$lrows['code']}"); + $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'] . "#1", "{$lrows['code']}", "{$lrows['code']}"); } // Only Show No-Answer if question is not mandatory if ($rows['mandatory'] != 'Y' && $rows['mandatory'] != 'S') { - $canswers[] = array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$arows['title']."#0", "", gT("No answer")); - $canswers[] = array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$arows['title']."#1", "", gT("No answer")); + $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'] . "#0", "", gT("No answer")); + $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'] . "#1", "", gT("No answer")); } } //foreach } elseif ($rows['type'] == Question::QT_K_MULTIPLE_NUMERICAL_QUESTION || $rows['type'] == Question::QT_Q_MULTIPLE_SHORT_TEXT) { @@ -1547,15 +1558,14 @@ protected function getCAnswersAndCQuestions(array $theserows) ), array('order' => 'question_order desc')); foreach ($aresult as $arows) { - $shortanswer = "{$arows['title']}: [".strip_tags($arows->questionl10ns[$this->language]->question)."]"; - $shortquestion = $rows['title'].":$shortanswer ".strip_tags($rows['question']); - $cquestions[] = array($shortquestion, $rows['qid'], $rows['type'], $rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$arows['title']); + $shortanswer = "{$arows['title']}: [" . strip_tags($arows->questionl10ns[$this->language]->question) . "]"; + $shortquestion = $rows['title'] . ":$shortanswer " . strip_tags($rows['question']); + $cquestions[] = array($shortquestion, $rows['qid'], $rows['type'], $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title']); // Only Show No-Answer if question is not mandatory if ($rows['mandatory'] != 'Y' && $rows['mandatory'] != 'S') { - $canswers[] = array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$arows['title'], "", gT("No answer")); + $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], "", gT("No answer")); } - } //foreach } elseif ($rows['type'] == Question::QT_R_RANKING_STYLE) { //Answer Ranking @@ -1564,11 +1574,12 @@ protected function getCAnswersAndCQuestions(array $theserows) 'condition' => 'answerl10ns.language = :lang', 'params' => array(':lang' => $this->language) )))->findAllByAttributes( - array( - "qid" => $rows['qid'], - "scale_id" => 0, - ), - array('order' => 'sortorder, answer')); + array( + "qid" => $rows['qid'], + "scale_id" => 0, + ), + array('order' => 'sortorder, answer') + ); $acount = count($aresult); @@ -1579,22 +1590,21 @@ protected function getCAnswersAndCQuestions(array $theserows) } for ($i = 1; $i <= $acount; $i++) { - $cquestions[] = array("{$rows['title']}: [RANK $i] ".strip_tags($rows['question']), $rows['qid'], $rows['type'], $rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$i); + $cquestions[] = array("{$rows['title']}: [RANK $i] " . strip_tags($rows['question']), $rows['qid'], $rows['type'], $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $i); foreach ($quicky as $qck) { - $canswers[] = array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$i, $qck[0], $qck[1]); + $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $i, $qck[0], $qck[1]); } // Only Show No-Answer if question is not mandatory if ($rows['mandatory'] != 'Y' && $rows['mandatory'] != 'S') { - $canswers[] = array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$i, " ", gT("No answer")); + $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $i, " ", gT("No answer")); } } unset($quicky); // End if type R } elseif ($rows['type'] == Question::QT_M_MULTIPLE_CHOICE || $rows['type'] == Question::QT_P_MULTIPLE_CHOICE_WITH_COMMENTS) { - - $shortanswer = " [".gT("Group of checkboxes")."]"; - $shortquestion = $rows['title'].":$shortanswer ".strip_tags($rows['question']); - $cquestions[] = array($shortquestion, $rows['qid'], $rows['type'], $rows['sid'].$X.$rows['gid'].$X.$rows['qid']); + $shortanswer = " [" . gT("Group of checkboxes") . "]"; + $shortquestion = $rows['title'] . ":$shortanswer " . strip_tags($rows['question']); + $cquestions[] = array($shortquestion, $rows['qid'], $rows['type'], $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid']); $aresult = Question::model()->with('questionl10ns')->findAllByAttributes(array( "parent_qid" => $rows['qid'], @@ -1602,49 +1612,48 @@ protected function getCAnswersAndCQuestions(array $theserows) foreach ($aresult as $arows) { $theanswer = $arows->questionl10ns[$this->language]->question; - $canswers[] = array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'], $arows['title'], $theanswer); - - $shortanswer = "{$arows['title']}: [".strip_tags($theanswer)."]"; - $shortanswer .= "[".gT("Single checkbox")."]"; - $shortquestion = $rows['title'].":$shortanswer ".strip_tags($rows['question']); - $cquestions[] = array($shortquestion, $rows['qid'], $rows['type'], "+".$rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$arows['title']); - $canswers[] = array("+".$rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$arows['title'], 'Y', gT("checked")); - $canswers[] = array("+".$rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$arows['title'], '', gT("not checked")); + $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], $arows['title'], $theanswer); + + $shortanswer = "{$arows['title']}: [" . strip_tags($theanswer) . "]"; + $shortanswer .= "[" . gT("Single checkbox") . "]"; + $shortquestion = $rows['title'] . ":$shortanswer " . strip_tags($rows['question']); + $cquestions[] = array($shortquestion, $rows['qid'], $rows['type'], "+" . $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title']); + $canswers[] = array("+" . $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], 'Y', gT("checked")); + $canswers[] = array("+" . $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], '', gT("not checked")); } - } else { - $cquestions[] = array($shortquestion, $rows['qid'], $rows['type'], $rows['sid'].$X.$rows['gid'].$X.$rows['qid']); + $cquestions[] = array($shortquestion, $rows['qid'], $rows['type'], $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid']); switch ($rows['type']) { case Question::QT_Y_YES_NO_RADIO: // Y/N/NA - $canswers[] = array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'], "Y", gT("Yes")); - $canswers[] = array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'], "N", gT("No")); + $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], "Y", gT("Yes")); + $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], "N", gT("No")); // Only Show No-Answer if question is not mandatory if ($rows['mandatory'] != 'Y' && $rows['mandatory'] != 'S') { - $canswers[] = array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'], " ", gT("No answer")); + $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], " ", gT("No answer")); } break; case Question::QT_G_GENDER_DROPDOWN: //Gender - $canswers[] = array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'], "F", gT("Female")); - $canswers[] = array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'], "M", gT("Male")); + $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], "F", gT("Female")); + $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], "M", gT("Male")); // Only Show No-Answer if question is not mandatory if ($rows['mandatory'] != 'Y' && $rows['mandatory'] != 'S') { - $canswers[] = array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'], " ", gT("No answer")); + $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], " ", gT("No answer")); } break; case Question::QT_5_POINT_CHOICE: // 5 choice for ($i = 1; $i <= 5; $i++) { - $canswers[] = array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'], $i, $i); + $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], $i, $i); } // Only Show No-Answer if question is not mandatory if ($rows['mandatory'] != 'Y' && $rows['mandatory'] != 'S') { - $canswers[] = array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'], " ", gT("No answer")); + $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], " ", gT("No answer")); } break; case Question::QT_N_NUMERICAL: // Simple Numerical questions // Only Show No-Answer if question is not mandatory if ($rows['mandatory'] != 'Y' && $rows['mandatory'] != 'S') { - $canswers[] = array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'], " ", gT("No answer")); + $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], " ", gT("No answer")); } break; @@ -1654,35 +1663,38 @@ protected function getCAnswersAndCQuestions(array $theserows) 'condition' => 'answerl10ns.language = :lang', 'params' => array(':lang' => $this->language), 'alias' => 'answerl10ns', - )) - )->findAllByAttributes(array( + )))->findAllByAttributes(array( 'qid' => $rows['qid'], 'scale_id' => 0, - ), array('order' => 'sortorder, answer')); + ), array('order' => 'sortorder, answer')); foreach ($aresult as $arows) { $theanswer = $arows->answerl10ns[$this->language]->answer; - $canswers[] = array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'], $arows['code'], $theanswer); + $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], $arows['code'], $theanswer); } if ($rows['type'] == Question::QT_D_DATE) { // Only Show No-Answer if question is not mandatory if ($rows['mandatory'] != 'Y' && $rows['mandatory'] != 'S') { - $canswers[] = array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'], " ", gT("No answer")); + $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], " ", gT("No answer")); } - } elseif ($rows['type'] != Question::QT_M_MULTIPLE_CHOICE && + } elseif ( + $rows['type'] != Question::QT_M_MULTIPLE_CHOICE && $rows['type'] != Question::QT_P_MULTIPLE_CHOICE_WITH_COMMENTS && - $rows['type'] != Question::QT_I_LANGUAGE) { + $rows['type'] != Question::QT_I_LANGUAGE + ) { // For dropdown questions // optinnaly add the 'Other' answer - if (($rows['type'] == Question::QT_L_LIST_DROPDOWN || + if ( + ($rows['type'] == Question::QT_L_LIST_DROPDOWN || $rows['type'] == Question::QT_EXCLAMATION_LIST_DROPDOWN) && - $rows['other'] == "Y") { - $canswers[] = array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'], "-oth-", gT("Other")); + $rows['other'] == "Y" + ) { + $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], "-oth-", gT("Other")); } // Only Show No-Answer if question is not mandatory if ($rows['mandatory'] != 'Y' && $rows['mandatory'] != 'S') { - $canswers[] = array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'], " ", gT("No answer")); + $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], " ", gT("No answer")); } } break; @@ -1702,7 +1714,7 @@ protected function getCAnswersAndCQuestions(array $theserows) */ protected function getCopyForm($qid, $gid, array $conditionsList, array $pquestions) { - App()->getClientScript()->registerScriptFile(App()->getConfig('adminscripts').'checkgroup.js', LSYii_ClientScript::POS_BEGIN); + App()->getClientScript()->registerScriptFile(App()->getConfig('adminscripts') . 'checkgroup.js', LSYii_ClientScript::POS_BEGIN); $url = $this->getcontroller()->createUrl( '/admin/conditions/sa/index/subaction/copyconditions/', @@ -1753,7 +1765,7 @@ protected function getEditConditionForm(array $args) $js_getAnswers_onload = $this->getJsAnswersToSelect($cquestions, $p_cquestions, $p_canswers); - App()->getClientScript()->registerScriptFile(App()->getConfig('adminscripts').'conditions.js', LSYii_ClientScript::POS_BEGIN); + App()->getClientScript()->registerScriptFile(App()->getConfig('adminscripts') . 'conditions.js', LSYii_ClientScript::POS_BEGIN); if ($subaction == "editthiscondition" && isset($p_cid)) { $title = gT("Edit condition"); @@ -1794,15 +1806,15 @@ protected function getEditConditionForm(array $args) $result .= $this->getController()->renderPartial('/admin/conditions/includes/form_editconditions_header', $data, true); $scriptResult = "" - . "\t".$js_getAnswers_onload."\n"; + . "\t" . $js_getAnswers_onload . "\n"; if (isset($p_method)) { - $scriptResult .= "\tdocument.getElementById('method').value='".$p_method."';\n"; + $scriptResult .= "\tdocument.getElementById('method').value='" . $p_method . "';\n"; } $scriptResult .= $this->getEditFormJavascript($subaction); if (isset($p_scenario)) { - $scriptResult .= "\tdocument.getElementById('scenario').value='".$p_scenario."';\n"; + $scriptResult .= "\tdocument.getElementById('scenario').value='" . $p_scenario . "';\n"; } $scriptResult .= "\n"; App()->getClientScript()->registerScript('conditionsaction_onstartscripts', $scriptResult, LSYii_ClientScript::POS_END); @@ -1874,9 +1886,9 @@ protected function getJsAnswersToSelect($cquestions, $p_cquestions, $p_canswers) protected function getEDITConditionConst($subaction) { $request = Yii::app()->request; - $EDITConditionConst = HTMLEscape($request->getPost('ConditionConst','')); - if ($subaction == "editthiscondition" && $request->getPost('EDITConditionConst','') !== '') { - $EDITConditionConst = HTMLEscape($request->getPost('EDITConditionConst','')); + $EDITConditionConst = HTMLEscape($request->getPost('ConditionConst', '')); + if ($subaction == "editthiscondition" && $request->getPost('EDITConditionConst', '') !== '') { + $EDITConditionConst = HTMLEscape($request->getPost('EDITConditionConst', '')); } return $EDITConditionConst; } @@ -1912,16 +1924,16 @@ protected function getEditFormJavascript($subaction) $aViewUrls = array('output' => ''); if ($subaction == "editthiscondition") { // in edit mode we read previous values in order to dusplay them in the corresponding inputs - if ($request->getPost('EDITConditionConst','') !== '') { + if ($request->getPost('EDITConditionConst', '') !== '') { // In order to avoid issues with backslash escaping, I don't use javascript to set the value // Thus the value is directly set when creating the Textarea element //$aViewUrls['output'] .= "\tdocument.getElementById('ConditionConst').value='".HTMLEscape($request->getPost('EDITConditionConst'))."';\n"; $aViewUrls['output'] .= "\tdocument.getElementById('editTargetTab').value='#CONST';\n"; } elseif ($request->getPost('EDITprevQuestionSGQA') != '') { - $aViewUrls['output'] .= "\tdocument.getElementById('prevQuestionSGQA').value='".HTMLEscape($request->getPost('EDITprevQuestionSGQA'))."';\n"; + $aViewUrls['output'] .= "\tdocument.getElementById('prevQuestionSGQA').value='" . HTMLEscape($request->getPost('EDITprevQuestionSGQA')) . "';\n"; $aViewUrls['output'] .= "\tdocument.getElementById('editTargetTab').value='#PREVQUESTIONS';\n"; } elseif ($request->getPost('EDITtokenAttr') != '') { - $aViewUrls['output'] .= "\tdocument.getElementById('tokenAttr').value='".HTMLEscape($request->getPost('EDITtokenAttr'))."';\n"; + $aViewUrls['output'] .= "\tdocument.getElementById('tokenAttr').value='" . HTMLEscape($request->getPost('EDITtokenAttr')) . "';\n"; $aViewUrls['output'] .= "\tdocument.getElementById('editTargetTab').value='#TOKENATTRS';\n"; } elseif ($request->getPost('EDITConditionRegexp') != '') { // In order to avoid issues with backslash escaping, I don't use javascript to set the value @@ -1932,26 +1944,26 @@ protected function getEditFormJavascript($subaction) // was a predefined answers post $aViewUrls['output'] .= "\tdocument.getElementById('editTargetTab').value='#CANSWERSTAB';\n"; $EDITcanswers = $request->getPost('EDITcanswers'); - $aViewUrls['output'] .= "\t$('#canswersToSelect').val('".$EDITcanswers[0]."');\n"; + $aViewUrls['output'] .= "\t$('#canswersToSelect').val('" . $EDITcanswers[0] . "');\n"; } if ($request->getPost('csrctoken') != '') { - $aViewUrls['output'] .= "\tdocument.getElementById('csrctoken').value='".HTMLEscape($request->getPost('csrctoken'))."';\n"; - } else if ($request->getPost('cquestions') != '') { - $aViewUrls['output'] .= "\tdocument.getElementById('cquestions').value='".HTMLEscape($request->getPost('cquestions'))."';\n"; + $aViewUrls['output'] .= "\tdocument.getElementById('csrctoken').value='" . HTMLEscape($request->getPost('csrctoken')) . "';\n"; + } elseif ($request->getPost('cquestions') != '') { + $aViewUrls['output'] .= "\tdocument.getElementById('cquestions').value='" . HTMLEscape($request->getPost('cquestions')) . "';\n"; } } else { // in other modes, for the moment we do the same as for edit mode - if ($request->getPost('ConditionConst','') !== '') { + if ($request->getPost('ConditionConst', '') !== '') { // In order to avoid issues with backslash escaping, I don't use javascript to set the value // Thus the value is directly set when creating the Textarea element //$aViewUrls['output'] .= "\tdocument.getElementById('ConditionConst').value='".HTMLEscape($request->getPost('ConditionConst'))."';\n"; $aViewUrls['output'] .= "\tdocument.getElementById('editTargetTab').value='#CONST';\n"; } elseif ($request->getPost('prevQuestionSGQA') != '') { - $aViewUrls['output'] .= "\tdocument.getElementById('prevQuestionSGQA').value='".HTMLEscape($request->getPost('prevQuestionSGQA'))."';\n"; + $aViewUrls['output'] .= "\tdocument.getElementById('prevQuestionSGQA').value='" . HTMLEscape($request->getPost('prevQuestionSGQA')) . "';\n"; $aViewUrls['output'] .= "\tdocument.getElementById('editTargetTab').value='#PREVQUESTIONS';\n"; } elseif ($request->getPost('tokenAttr') != '') { - $aViewUrls['output'] .= "\tdocument.getElementById('tokenAttr').value='".HTMLEscape($request->getPost('tokenAttr'))."';\n"; + $aViewUrls['output'] .= "\tdocument.getElementById('tokenAttr').value='" . HTMLEscape($request->getPost('tokenAttr')) . "';\n"; $aViewUrls['output'] .= "\tdocument.getElementById('editTargetTab').value='#TOKENATTRS';\n"; } elseif ($request->getPost('ConditionRegexp') != '') { // In order to avoid issues with backslash escaping, I don't use javascript to set the value @@ -1961,16 +1973,16 @@ protected function getEditFormJavascript($subaction) } else { // was a predefined answers post if ($request->getPost('cquestions') != '') { - $aViewUrls['output'] .= "\tdocument.getElementById('cquestions').value='".HTMLEscape($request->getPost('cquestions'))."';\n"; + $aViewUrls['output'] .= "\tdocument.getElementById('cquestions').value='" . HTMLEscape($request->getPost('cquestions')) . "';\n"; } $aViewUrls['output'] .= "\tdocument.getElementById('editTargetTab').value='#CANSWERSTAB';\n"; } if ($request->getPost('csrctoken') != '') { - $aViewUrls['output'] .= "\tdocument.getElementById('csrctoken').value='".HTMLEscape($request->getPost('csrctoken'))."';\n"; + $aViewUrls['output'] .= "\tdocument.getElementById('csrctoken').value='" . HTMLEscape($request->getPost('csrctoken')) . "';\n"; } else { if ($request->getPost('cquestions') != '') { - $aViewUrls['output'] .= "\tdocument.getElementById('cquestions').value='".javascriptEscape($request->getPost('cquestions'))."';\n"; + $aViewUrls['output'] .= "\tdocument.getElementById('cquestions').value='" . javascriptEscape($request->getPost('cquestions')) . "';\n"; } } } @@ -1985,7 +1997,7 @@ protected function getEditSourceTab() $request = Yii::app()->request; if ($request->getPost('csrctoken') != '') { return '#SRCTOKENATTRS'; - } else if ($request->getPost('cquestions') != '') { + } elseif ($request->getPost('cquestions') != '') { return '#SRCPREVQUEST'; } else { return '#SRCPREVQUEST'; @@ -1998,7 +2010,7 @@ protected function getEditSourceTab() protected function getEditTargetTab() { $request = Yii::app()->request; - if ($request->getPost('EDITConditionConst','') !== '') { + if ($request->getPost('EDITConditionConst', '') !== '') { return '#CONST'; } elseif ($request->getPost('EDITprevQuestionSGQA') != '') { return '#PREVQUESTIONS'; @@ -2035,7 +2047,7 @@ protected function getQuestionNavOptions($theserows, $postrows, $args) $questionselecter = viewHelper::flatEllipsizeText($question, true, '40'); $theserows2[] = array( 'value' => $this->createNavigatorUrl($row['gid'], $row['qid']), - 'text' => strip_tags($row['title']).':'.$questionselecter + 'text' => strip_tags($row['title']) . ':' . $questionselecter ); } @@ -2045,15 +2057,15 @@ protected function getQuestionNavOptions($theserows, $postrows, $args) $questionselecter = viewHelper::flatEllipsizeText($question, true, '40'); $postrows2[] = array( 'value' => $this->createNavigatorUrl($row['gid'], $row['qid']), - 'text' => strip_tags($row['title']).':'.$questionselecter + 'text' => strip_tags($row['title']) . ':' . $questionselecter ); } $data = array( 'theserows' => $theserows2, 'postrows' => $postrows2, - 'currentValue'=> $this->createNavigatorUrl($gid, $qid), - 'currentText' => $questiontitle.':'.viewHelper::flatEllipsizeText(strip_tags($sCurrentFullQuestionText), true, '40') + 'currentValue' => $this->createNavigatorUrl($gid, $qid), + 'currentText' => $questiontitle . ':' . viewHelper::flatEllipsizeText(strip_tags($sCurrentFullQuestionText), true, '40') ); return $this->getController()->renderPartial('/admin/conditions/includes/navigator', $data, true); @@ -2105,8 +2117,8 @@ protected function getJavascriptForMatching(array $canswers, array $cquestions, $jn = 0; foreach ($cquestions as $cqn) { $javascriptpre .= "QFieldnames[$jn]='$cqn[3]';\n" - ."Qcqids[$jn]='$cqn[1]';\n" - ."Qtypes[$jn]='$cqn[2]';\n"; + . "Qcqids[$jn]='$cqn[1]';\n" + . "Qtypes[$jn]='$cqn[2]';\n"; $jn++; } @@ -2135,9 +2147,9 @@ protected function getAttributeName($extractedTokenAttr) } if ($this->tokenTableExists) { - $thisAttrName .= " [".gT("From survey participants table")."]"; + $thisAttrName .= " [" . gT("From survey participants table") . "]"; } else { - $thisAttrName .= " [".gT("Non-existing survey participants table")."]"; + $thisAttrName .= " [" . gT("Non-existing survey participants table") . "]"; } return $thisAttrName; @@ -2157,12 +2169,14 @@ protected function getHiddenFields(array $rows, $leftOperandType, $rightOperandT // depending on the leftOperandType if ($leftOperandType == 'tokenattr') { $html .= CHtml::hiddenField('csrctoken', HTMLEscape($rows['cfieldname']), array( - 'id' => 'csrctoken'.$rows['cid'] + 'id' => 'csrctoken' . $rows['cid'] )); } else { - $html .= CHtml::hiddenField('cquestions', HTMLEscape($rows['cfieldname']), + $html .= CHtml::hiddenField( + 'cquestions', + HTMLEscape($rows['cfieldname']), array( - 'id' => 'cquestions'.$rows['cid'] + 'id' => 'cquestions' . $rows['cid'] ) ); } @@ -2172,27 +2186,36 @@ protected function getHiddenFields(array $rows, $leftOperandType, $rightOperandT // This is used when editing a condition if ($rightOperandType == 'predefinedAnsw') { $html .= CHtml::hiddenField('EDITcanswers[]', HTMLEscape($rows['value']), array( - 'id' => 'editModeTargetVal'.$rows['cid'] + 'id' => 'editModeTargetVal' . $rows['cid'] )); } elseif ($rightOperandType == 'prevQsgqa') { - $html .= CHtml::hiddenField('EDITprevQuestionSGQA', HTMLEscape($rows['value']), + $html .= CHtml::hiddenField( + 'EDITprevQuestionSGQA', + HTMLEscape($rows['value']), array( - 'id' => 'editModeTargetVal'.$rows['cid'] - )); + 'id' => 'editModeTargetVal' . $rows['cid'] + ) + ); } elseif ($rightOperandType == 'tokenAttr') { $html .= CHtml::hiddenField('EDITtokenAttr', HTMLEscape($rows['value']), array( - 'id' => 'editModeTargetVal'.$rows['cid'] + 'id' => 'editModeTargetVal' . $rows['cid'] )); } elseif ($rightOperandType == 'regexp') { - $html .= CHtml::hiddenField('EDITConditionRegexp', HTMLEscape($rows['value']), + $html .= CHtml::hiddenField( + 'EDITConditionRegexp', + HTMLEscape($rows['value']), array( - 'id' => 'editModeTargetVal'.$rows['cid'] - )); + 'id' => 'editModeTargetVal' . $rows['cid'] + ) + ); } else { - $html .= CHtml::hiddenField('EDITConditionConst', HTMLEscape($rows['value']), + $html .= CHtml::hiddenField( + 'EDITConditionConst', + HTMLEscape($rows['value']), array( - 'id' => 'editModeTargetVal'.$rows['cid'] - )); + 'id' => 'editModeTargetVal' . $rows['cid'] + ) + ); } return $html; @@ -2204,10 +2227,10 @@ protected function getHiddenFields(array $rows, $leftOperandType, $rightOperandT */ protected function getAllScenarios($qid) { - $criteria = new CDbCriteria; + $criteria = new CDbCriteria(); $criteria->select = 'scenario'; // only select the 'scenario' column $criteria->condition = 'qid=:qid'; - $criteria->params = array(':qid'=>$qid); + $criteria->params = array(':qid' => $qid); $criteria->order = 'scenario'; $criteria->group = 'scenario'; diff --git a/application/controllers/admin/database.php b/application/controllers/admin/database.php index d868ba34a21..a4f0fe544c3 100644 --- a/application/controllers/admin/database.php +++ b/application/controllers/admin/database.php @@ -1,4 +1,6 @@ - ['type'=> '', 'default' => false, 'dbname'=>false, 'active'=>true, 'required'=>[]], - 'admin' => ['type'=> '', 'default' => false, 'dbname'=>false, 'active'=>true, 'required'=>[]], - 'faxto' => ['type'=> '', 'default' => false, 'dbname'=>false, 'active'=>true, 'required'=>[]], - 'format' => ['type'=> '', 'default' => false, 'dbname'=>false, 'active'=>true, 'required'=>[]], - 'expires' => ['type'=> '', 'default' => false, 'dbname'=>false, 'active'=>true, 'required'=>[]], - 'startdate' => ['type'=> 'default', 'default' => false, 'dbname'=>false, 'active'=>true, 'required'=>[]], - 'template' => ['type'=> '', 'default' => false, 'dbname'=>false, 'active'=>true, 'required'=>[]], - 'assessments' => ['type'=> 'yesno', 'default' => false, 'dbname'=>false, 'active'=>true, 'required'=>[]], - 'anonymized' => ['type'=> 'yesno', 'default' => false, 'dbname'=>false, 'active'=>true, 'required'=>[]], - 'savetimings' => ['type'=> 'yesno', 'default' => false, 'dbname'=>false, 'active'=>true, 'required'=>[]], - 'datestamp' => ['type'=> 'yesno', 'default' => false, 'dbname'=>false, 'active'=>true, 'required'=>[]], - 'ipaddr' => ['type'=> 'yesno', 'default' => false, 'dbname'=>false, 'active'=>true, 'required'=>[]], - 'ipanonymize'=> ['type'=> 'yesno', 'default' => false, 'dbname'=>false, 'active'=>true, 'required'=>[]], - 'refurl' => ['type'=> 'yesno', 'default' => false, 'dbname'=>false, 'active'=>true, 'required'=>[]], - 'publicgraphs' => ['type'=> 'yesno', 'default' => false, 'dbname'=>false, 'active'=>true, 'required'=>[]], - 'usecookie' => ['type'=> 'yesno', 'default' => false, 'dbname'=>false, 'active'=>true, 'required'=>[]], - 'allowregister' => ['type'=> 'yesno', 'default' => false, 'dbname'=>false, 'active'=>true, 'required'=>[]], - 'allowsave' => ['type'=> 'yesno', 'default' => false, 'dbname'=>false, 'active'=>true, 'required'=>[]], - 'navigationdelay' => ['type'=> '', 'default' => false, 'dbname'=>false, 'active'=>true, 'required'=>[]], - 'printanswers' => ['type'=> 'yesno', 'default' => false, 'dbname'=>false, 'active'=>true, 'required'=>[]], - 'publicstatistics' => ['type'=> 'yesno', 'default' => false, 'dbname'=>false, 'active'=>true, 'required'=>[]], - 'autoredirect' => ['type'=> 'yesno', 'default' => false, 'dbname'=>false, 'active'=>true, 'required'=>[]], - 'showxquestions' => ['type'=> 'yesno', 'default' => false, 'dbname'=>false, 'active'=>true, 'required'=>[]], - 'showgroupinfo' => ['type'=> '', 'default' => false, 'dbname'=>false, 'active'=>true, 'required'=>[]], - 'showqnumcode' => ['type'=> '', 'default' => false, 'dbname'=>false, 'active'=>true, 'required'=>[]], - 'shownoanswer' => ['type'=> 'yesno', 'default' => false, 'dbname'=>false, 'active'=>true, 'required'=>[]], - 'showwelcome' => ['type'=> 'yesno', 'default' => false, 'dbname'=>false, 'active'=>true, 'required'=>[]], - 'showsurveypolicynotice' => ['type'=> '', 'default' => 0, 'dbname'=>false, 'active'=>true, 'required'=>[]], - 'allowprev' => ['type'=> 'yesno', 'default' => false, 'dbname'=>false, 'active'=>true, 'required'=>[]], - 'questionindex' => ['type'=> '', 'default' => false, 'dbname'=>false, 'active'=>true, 'required'=>[]], - 'nokeyboard' => ['type'=> 'yesno', 'default' => false, 'dbname'=>false, 'active'=>true, 'required'=>[]], - 'showprogress' => ['type'=> 'yesno', 'default' => false, 'dbname'=>false, 'active'=>true, 'required'=>[]], - 'listpublic' => ['type'=> 'yesno', 'default' => false, 'dbname'=>false, 'active'=>true, 'required'=>[]], - 'htmlemail' => ['type'=> 'yesno', 'default' => false, 'dbname'=>false, 'active'=>true, 'required'=>[]], - 'sendconfirmation' => ['type'=> 'yesno', 'default' => false, 'dbname'=>false, 'active'=>true, 'required'=>[]], - 'tokenanswerspersistence' => ['type'=> 'yesno', 'default' => false, 'dbname'=>false, 'active'=>true, 'required'=>[]], - 'alloweditaftercompletion' => ['type'=> 'yesno', 'default' => false, 'dbname'=>false, 'active'=>true, 'required'=>[]], - 'emailresponseto' => ['type'=> '', 'default' => false, 'dbname'=>false, 'active'=>true, 'required'=>[]], - 'emailnotificationto' => ['type'=> '', 'default' => false, 'dbname'=>false, 'active'=>true, 'required'=>[]], - 'googleanalyticsapikeysetting' => ['type'=> 'default', 'default' => false, 'dbname'=>false, 'active'=>true, 'required'=>[]], - 'googleanalyticsapikey' => ['type'=> 'default', 'default' => false, 'dbname'=>false, 'active'=>true, 'required'=>[]], - 'googleanalyticsstyle' => ['type'=> '', 'default' => false, 'dbname'=>false, 'active'=>true, 'required'=>[]], - 'tokenlength' => ['type'=> '', 'default' => false, 'dbname'=>false, 'active'=>true, 'required'=>[]], - 'adminemail' => ['type'=> '', 'default' => false, 'dbname'=>false, 'active'=>true, 'required'=>[]], - 'bounce_email' => ['type'=> '', 'default' => false, 'dbname'=>false, 'active'=>true, 'required'=>[]], - 'gsid' => ['type'=> '', 'default' => 1, 'dbname'=>false, 'active'=>true, 'required'=>[]], - 'usecaptcha_surveyaccess' => ['type'=> 'yesno', 'default' => false, 'dbname'=>false, 'active'=>true, 'required'=>[]], - 'usecaptcha_registration' => ['type'=> 'yesno', 'default' => false, 'dbname'=>false, 'active'=>true, 'required'=>[]], - 'usecaptcha_saveandload' => ['type'=> 'yesno', 'default' => false, 'dbname'=>false, 'active'=>true, 'required'=>[]], + 'owner_id' => ['type' => '', 'default' => false, 'dbname' => false, 'active' => true, 'required' => []], + 'admin' => ['type' => '', 'default' => false, 'dbname' => false, 'active' => true, 'required' => []], + 'faxto' => ['type' => '', 'default' => false, 'dbname' => false, 'active' => true, 'required' => []], + 'format' => ['type' => '', 'default' => false, 'dbname' => false, 'active' => true, 'required' => []], + 'expires' => ['type' => '', 'default' => false, 'dbname' => false, 'active' => true, 'required' => []], + 'startdate' => ['type' => 'default', 'default' => false, 'dbname' => false, 'active' => true, 'required' => []], + 'template' => ['type' => '', 'default' => false, 'dbname' => false, 'active' => true, 'required' => []], + 'assessments' => ['type' => 'yesno', 'default' => false, 'dbname' => false, 'active' => true, 'required' => []], + 'anonymized' => ['type' => 'yesno', 'default' => false, 'dbname' => false, 'active' => true, 'required' => []], + 'savetimings' => ['type' => 'yesno', 'default' => false, 'dbname' => false, 'active' => true, 'required' => []], + 'datestamp' => ['type' => 'yesno', 'default' => false, 'dbname' => false, 'active' => true, 'required' => []], + 'ipaddr' => ['type' => 'yesno', 'default' => false, 'dbname' => false, 'active' => true, 'required' => []], + 'ipanonymize' => ['type' => 'yesno', 'default' => false, 'dbname' => false, 'active' => true, 'required' => []], + 'refurl' => ['type' => 'yesno', 'default' => false, 'dbname' => false, 'active' => true, 'required' => []], + 'publicgraphs' => ['type' => 'yesno', 'default' => false, 'dbname' => false, 'active' => true, 'required' => []], + 'usecookie' => ['type' => 'yesno', 'default' => false, 'dbname' => false, 'active' => true, 'required' => []], + 'allowregister' => ['type' => 'yesno', 'default' => false, 'dbname' => false, 'active' => true, 'required' => []], + 'allowsave' => ['type' => 'yesno', 'default' => false, 'dbname' => false, 'active' => true, 'required' => []], + 'navigationdelay' => ['type' => '', 'default' => false, 'dbname' => false, 'active' => true, 'required' => []], + 'printanswers' => ['type' => 'yesno', 'default' => false, 'dbname' => false, 'active' => true, 'required' => []], + 'publicstatistics' => ['type' => 'yesno', 'default' => false, 'dbname' => false, 'active' => true, 'required' => []], + 'autoredirect' => ['type' => 'yesno', 'default' => false, 'dbname' => false, 'active' => true, 'required' => []], + 'showxquestions' => ['type' => 'yesno', 'default' => false, 'dbname' => false, 'active' => true, 'required' => []], + 'showgroupinfo' => ['type' => '', 'default' => false, 'dbname' => false, 'active' => true, 'required' => []], + 'showqnumcode' => ['type' => '', 'default' => false, 'dbname' => false, 'active' => true, 'required' => []], + 'shownoanswer' => ['type' => 'yesno', 'default' => false, 'dbname' => false, 'active' => true, 'required' => []], + 'showwelcome' => ['type' => 'yesno', 'default' => false, 'dbname' => false, 'active' => true, 'required' => []], + 'showsurveypolicynotice' => ['type' => '', 'default' => 0, 'dbname' => false, 'active' => true, 'required' => []], + 'allowprev' => ['type' => 'yesno', 'default' => false, 'dbname' => false, 'active' => true, 'required' => []], + 'questionindex' => ['type' => '', 'default' => false, 'dbname' => false, 'active' => true, 'required' => []], + 'nokeyboard' => ['type' => 'yesno', 'default' => false, 'dbname' => false, 'active' => true, 'required' => []], + 'showprogress' => ['type' => 'yesno', 'default' => false, 'dbname' => false, 'active' => true, 'required' => []], + 'listpublic' => ['type' => 'yesno', 'default' => false, 'dbname' => false, 'active' => true, 'required' => []], + 'htmlemail' => ['type' => 'yesno', 'default' => false, 'dbname' => false, 'active' => true, 'required' => []], + 'sendconfirmation' => ['type' => 'yesno', 'default' => false, 'dbname' => false, 'active' => true, 'required' => []], + 'tokenanswerspersistence' => ['type' => 'yesno', 'default' => false, 'dbname' => false, 'active' => true, 'required' => []], + 'alloweditaftercompletion' => ['type' => 'yesno', 'default' => false, 'dbname' => false, 'active' => true, 'required' => []], + 'emailresponseto' => ['type' => '', 'default' => false, 'dbname' => false, 'active' => true, 'required' => []], + 'emailnotificationto' => ['type' => '', 'default' => false, 'dbname' => false, 'active' => true, 'required' => []], + 'googleanalyticsapikeysetting' => ['type' => 'default', 'default' => false, 'dbname' => false, 'active' => true, 'required' => []], + 'googleanalyticsapikey' => ['type' => 'default', 'default' => false, 'dbname' => false, 'active' => true, 'required' => []], + 'googleanalyticsstyle' => ['type' => '', 'default' => false, 'dbname' => false, 'active' => true, 'required' => []], + 'tokenlength' => ['type' => '', 'default' => false, 'dbname' => false, 'active' => true, 'required' => []], + 'adminemail' => ['type' => '', 'default' => false, 'dbname' => false, 'active' => true, 'required' => []], + 'bounce_email' => ['type' => '', 'default' => false, 'dbname' => false, 'active' => true, 'required' => []], + 'gsid' => ['type' => '', 'default' => 1, 'dbname' => false, 'active' => true, 'required' => []], + 'usecaptcha_surveyaccess' => ['type' => 'yesno', 'default' => false, 'dbname' => false, 'active' => true, 'required' => []], + 'usecaptcha_registration' => ['type' => 'yesno', 'default' => false, 'dbname' => false, 'active' => true, 'required' => []], + 'usecaptcha_saveandload' => ['type' => 'yesno', 'default' => false, 'dbname' => false, 'active' => true, 'required' => []], ]; private $updatedFields = []; @@ -114,7 +116,7 @@ public function index() $this->iQuestionGroupID = (int) returnGlobal('gid'); $this->iQuestionID = (int) returnGlobal('qid'); - $this->oFixCKeditor = new LSYii_Validators; + $this->oFixCKeditor = new LSYii_Validators(); $this->oFixCKeditor->fixCKeditor = true; $this->oFixCKeditor->xssfilter = false; @@ -124,9 +126,11 @@ public function index() if (($sAction == "updatesurveylocalesettings") && (Permission::model()->hasSurveyPermission($this->iSurveyID, 'surveylocale', 'update') || Permission::model()->hasSurveyPermission($iSurveyID, 'surveysettings', 'update'))) { $this->actionUpdateSurveyLocaleSettings($this->iSurveyID); } - if (($sAction == "updatesurveylocalesettings_generalsettings") && + if ( + ($sAction == "updatesurveylocalesettings_generalsettings") && (Permission::model()->hasSurveyPermission($this->iSurveyID, 'surveylocale', 'update') || - Permission::model()->hasSurveyPermission($this->iSurveyID, 'surveysettings', 'update'))) { + Permission::model()->hasSurveyPermission($this->iSurveyID, 'surveysettings', 'update')) + ) { $this->actionUpdateSurveyLocaleSettingsGeneralSettings($this->iSurveyID); } @@ -155,39 +159,39 @@ public function _updateDefaultValues($qid, $sqid, $scale_id, $specialtype, $lang ':sqid' => $sqid, ':scale_id' => $scale_id, ) - ); + ); $dvid = !empty($arDefaultValue->dvid) ? $arDefaultValue->dvid : null; if ($defaultvalue == '') { // Remove the default value if it is empty - if ($dvid !== null){ - DefaultValueL10n::model()->deleteAllByAttributes(array('dvid'=>$dvid, 'language' => $language )); + if ($dvid !== null) { + DefaultValueL10n::model()->deleteAllByAttributes(array('dvid' => $dvid, 'language' => $language )); $iRowCount = DefaultValueL10n::model()->countByAttributes(array('dvid' => $dvid)); - if ($iRowCount == 0){ + if ($iRowCount == 0) { DefaultValue::model()->deleteByPk($dvid); } } } else { if (is_null($dvid)) { - $data = array('qid'=>$qid, 'sqid'=>$sqid, 'scale_id'=>$scale_id, 'specialtype'=>$specialtype); + $data = array('qid' => $qid, 'sqid' => $sqid, 'scale_id' => $scale_id, 'specialtype' => $specialtype); $oDefaultvalue = new DefaultValue(); $oDefaultvalue->attributes = $data; $oDefaultvalue->specialtype = $specialtype; $oDefaultvalue->save(); - if (!empty($oDefaultvalue->dvid)){ - $dataL10n = array('dvid'=>$oDefaultvalue->dvid, 'language'=>$language, 'defaultvalue'=>$defaultvalue); + if (!empty($oDefaultvalue->dvid)) { + $dataL10n = array('dvid' => $oDefaultvalue->dvid, 'language' => $language, 'defaultvalue' => $defaultvalue); $oDefaultvalueL10n = new DefaultValueL10n(); $oDefaultvalueL10n->attributes = $dataL10n; $oDefaultvalueL10n->save(); - } + } } else { - if ($dvid !== null){ + if ($dvid !== null) { $arDefaultValue->with('defaultvaluel10ns'); $idL10n = !empty($arDefaultValue->defaultvaluel10ns) && array_key_exists($language, $arDefaultValue->defaultvaluel10ns) ? $arDefaultValue->defaultvaluel10ns[$language]->id : null; - if ($idL10n !== null){ - DefaultValueL10n::model()->updateAll(array('defaultvalue'=>$defaultvalue), 'dvid = ' . $dvid . ' AND language = \'' . $language . '\''); + if ($idL10n !== null) { + DefaultValueL10n::model()->updateAll(array('defaultvalue' => $defaultvalue), 'dvid = ' . $dvid . ' AND language = \'' . $language . '\''); } else { - $dataL10n = array('dvid'=>$dvid, 'language'=>$language, 'defaultvalue'=>$defaultvalue); + $dataL10n = array('dvid' => $dvid, 'language' => $language, 'defaultvalue' => $defaultvalue); $oDefaultvalueL10n = new DefaultValueL10n(); $oDefaultvalueL10n->attributes = $dataL10n; $oDefaultvalueL10n->save(); @@ -210,32 +214,32 @@ private function actionUpdateDefaultValues($iSurveyID) $aSurveyLanguages = $oSurvey->allLanguages; $sBaseLanguage = $oSurvey->language; - Question::model()->updateAll(array('same_default'=> Yii::app()->request->getPost('samedefault') ? 1 : 0), 'sid=:sid ANd qid=:qid', array(':sid'=>$iSurveyID, ':qid'=>$this->iQuestionID)); + Question::model()->updateAll(array('same_default' => Yii::app()->request->getPost('samedefault') ? 1 : 0), 'sid=:sid ANd qid=:qid', array(':sid' => $iSurveyID, ':qid' => $this->iQuestionID)); - $arQuestion = Question::model()->findByAttributes(array('qid'=>$this->iQuestionID)); + $arQuestion = Question::model()->findByAttributes(array('qid' => $this->iQuestionID)); $sQuestionType = $arQuestion['type']; $questionThemeMetaData = QuestionTheme::findQuestionMetaData($sQuestionType); if ((int)$questionThemeMetaData['settings']->answerscales > 0 && $questionThemeMetaData['settings']->subquestions == 0) { for ($iScaleID = 0; $iScaleID < (int)$questionThemeMetaData['settings']->answerscales; $iScaleID++) { foreach ($aSurveyLanguages as $sLanguage) { - if (!is_null(Yii::app()->request->getPost('defaultanswerscale_'.$iScaleID.'_'.$sLanguage))) { - $this->_updateDefaultValues($this->iQuestionID, 0, $iScaleID, '', $sLanguage, Yii::app()->request->getPost('defaultanswerscale_'.$iScaleID.'_'.$sLanguage)); + if (!is_null(Yii::app()->request->getPost('defaultanswerscale_' . $iScaleID . '_' . $sLanguage))) { + $this->_updateDefaultValues($this->iQuestionID, 0, $iScaleID, '', $sLanguage, Yii::app()->request->getPost('defaultanswerscale_' . $iScaleID . '_' . $sLanguage)); } - if (!is_null(Yii::app()->request->getPost('other_'.$iScaleID.'_'.$sLanguage))) { - $this->_updateDefaultValues($this->iQuestionID, 0, $iScaleID, 'other', $sLanguage, Yii::app()->request->getPost('other_'.$iScaleID.'_'.$sLanguage)); + if (!is_null(Yii::app()->request->getPost('other_' . $iScaleID . '_' . $sLanguage))) { + $this->_updateDefaultValues($this->iQuestionID, 0, $iScaleID, 'other', $sLanguage, Yii::app()->request->getPost('other_' . $iScaleID . '_' . $sLanguage)); } } } } if ((int)$questionThemeMetaData['settings']->subquestions > 0) { foreach ($aSurveyLanguages as $sLanguage) { - $arQuestions = Question::model()->with('questionl10ns', array('condition' => 'language = ' . $sLanguage))->findAllByAttributes(array('sid'=>$iSurveyID, 'gid'=>$this->iQuestionGroupID, 'parent_qid'=>$this->iQuestionID, 'scale_id'=>0)); + $arQuestions = Question::model()->with('questionl10ns', array('condition' => 'language = ' . $sLanguage))->findAllByAttributes(array('sid' => $iSurveyID, 'gid' => $this->iQuestionGroupID, 'parent_qid' => $this->iQuestionID, 'scale_id' => 0)); for ($iScaleID = 0; $iScaleID < (int)$questionThemeMetaData['settings']->subquestions; $iScaleID++) { foreach ($arQuestions as $aSubquestionrow) { - if (!is_null(Yii::app()->request->getPost('defaultanswerscale_'.$iScaleID.'_'.$sLanguage.'_'.$aSubquestionrow['qid']))) { - $this->_updateDefaultValues($this->iQuestionID, $aSubquestionrow['qid'], $iScaleID, '', $sLanguage, Yii::app()->request->getPost('defaultanswerscale_'.$iScaleID.'_'.$sLanguage.'_'.$aSubquestionrow['qid'])); + if (!is_null(Yii::app()->request->getPost('defaultanswerscale_' . $iScaleID . '_' . $sLanguage . '_' . $aSubquestionrow['qid']))) { + $this->_updateDefaultValues($this->iQuestionID, $aSubquestionrow['qid'], $iScaleID, '', $sLanguage, Yii::app()->request->getPost('defaultanswerscale_' . $iScaleID . '_' . $sLanguage . '_' . $aSubquestionrow['qid'])); } } } @@ -251,17 +255,17 @@ private function actionUpdateDefaultValues($iSurveyID) $sLanguage = $aSurveyLanguages[0]; // turn } - if (Yii::app()->request->getPost('defaultanswerscale_0_'.$sLanguage) == 'EM') { + if (Yii::app()->request->getPost('defaultanswerscale_0_' . $sLanguage) == 'EM') { // Case EM, write expression to database - $this->_updateDefaultValues($this->iQuestionID, 0, 0, '', $sLanguage, Yii::app()->request->getPost('defaultanswerscale_0_'.$sLanguage.'_EM')); + $this->_updateDefaultValues($this->iQuestionID, 0, 0, '', $sLanguage, Yii::app()->request->getPost('defaultanswerscale_0_' . $sLanguage . '_EM')); } else { // Case "other", write list value to database - $this->_updateDefaultValues($this->iQuestionID, 0, 0, '', $sLanguage, Yii::app()->request->getPost('defaultanswerscale_0_'.$sLanguage)); + $this->_updateDefaultValues($this->iQuestionID, 0, 0, '', $sLanguage, Yii::app()->request->getPost('defaultanswerscale_0_' . $sLanguage)); } ///// end yes/no } else { - if (!is_null(Yii::app()->request->getPost('defaultanswerscale_0_'.$sLanguage.'_0'))) { - $this->_updateDefaultValues($this->iQuestionID, 0, 0, '', $sLanguage, Yii::app()->request->getPost('defaultanswerscale_0_'.$sLanguage.'_0')); + if (!is_null(Yii::app()->request->getPost('defaultanswerscale_0_' . $sLanguage . '_0'))) { + $this->_updateDefaultValues($this->iQuestionID, 0, 0, '', $sLanguage, Yii::app()->request->getPost('defaultanswerscale_0_' . $sLanguage . '_0')); } } } @@ -271,9 +275,9 @@ private function actionUpdateDefaultValues($iSurveyID) LimeExpressionManager::SetDirtyFlag(); if (Yii::app()->request->getPost('close-after-save') === 'true') { - $this->getController()->redirect(array('questionAdministration/view/surveyid/'.$iSurveyID.'/gid/'.$this->iQuestionGroupID.'/qid/'.$this->iQuestionID)); + $this->getController()->redirect(array('questionAdministration/view/surveyid/' . $iSurveyID . '/gid/' . $this->iQuestionGroupID . '/qid/' . $this->iQuestionID)); } - $this->getController()->redirect(['questionAdministration/editdefaultvalues/surveyid/'.$iSurveyID.'/gid/'.$this->iQuestionGroupID.'/qid/'.$this->iQuestionID]); + $this->getController()->redirect(['questionAdministration/editdefaultvalues/surveyid/' . $iSurveyID . '/gid/' . $this->iQuestionGroupID . '/qid/' . $this->iQuestionID]); } /** @@ -581,17 +585,17 @@ private function actionUpdateSurveyLocaleSettings($iSurveyID) foreach ($languagelist as $langname) { if ($langname) { $data = array(); - $sURLDescription = Yii::app()->request->getPost('urldescrip_'.$langname, null); - $sURL = Yii::app()->request->getPost('url_'.$langname, null); - $short_title = Yii::app()->request->getPost('short_title_'.$langname, null); - $description = Yii::app()->request->getPost('description_'.$langname, null); - $welcome = Yii::app()->request->getPost('welcome_'.$langname, null); - $endtext = Yii::app()->request->getPost('endtext_'.$langname, null); - $datasec = Yii::app()->request->getPost('datasec_'.$langname, null); - $datasecerror = Yii::app()->request->getPost('datasecerror_'.$langname, null); - $dataseclabel = Yii::app()->request->getPost('dataseclabel_'.$langname, null); - $dateformat = Yii::app()->request->getPost('dateformat_'.$langname, null); - $numberformat = Yii::app()->request->getPost('numberformat_'.$langname, null); + $sURLDescription = Yii::app()->request->getPost('urldescrip_' . $langname, null); + $sURL = Yii::app()->request->getPost('url_' . $langname, null); + $short_title = Yii::app()->request->getPost('short_title_' . $langname, null); + $description = Yii::app()->request->getPost('description_' . $langname, null); + $welcome = Yii::app()->request->getPost('welcome_' . $langname, null); + $endtext = Yii::app()->request->getPost('endtext_' . $langname, null); + $datasec = Yii::app()->request->getPost('datasec_' . $langname, null); + $datasecerror = Yii::app()->request->getPost('datasecerror_' . $langname, null); + $dataseclabel = Yii::app()->request->getPost('dataseclabel_' . $langname, null); + $dateformat = Yii::app()->request->getPost('dateformat_' . $langname, null); + $numberformat = Yii::app()->request->getPost('numberformat_' . $langname, null); if ($short_title !== null) { // Fix bug with FCKEditor saving strange BR types @@ -640,7 +644,7 @@ private function actionUpdateSurveyLocaleSettings($iSurveyID) } if (count($data) > 0) { - $oSurveyLanguageSetting = SurveyLanguageSetting::model()->findByPk(array('surveyls_survey_id'=>$iSurveyID, 'surveyls_language'=>$langname)); + $oSurveyLanguageSetting = SurveyLanguageSetting::model()->findByPk(array('surveyls_survey_id' => $iSurveyID, 'surveyls_language' => $langname)); $oSurveyLanguageSetting->setAttributes($data); $oSurveyLanguageSetting->save(); // save the change to database } @@ -676,7 +680,7 @@ private function actionUpdateSurveyLocaleSettings($iSurveyID) $oSurvey->startdate = ""; } else { Yii::app()->loadLibrary('Date_Time_Converter'); - $datetimeobj = new date_time_converter($startdate, $formatdata['phpdate'].' H:i'); + $datetimeobj = new date_time_converter($startdate, $formatdata['phpdate'] . ' H:i'); $startdate = $datetimeobj->convert("Y-m-d H:i:s"); $oSurvey->startdate = $startdate; } @@ -689,7 +693,7 @@ private function actionUpdateSurveyLocaleSettings($iSurveyID) // Must not convert if empty. $oSurvey->expires = ""; } else { - $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"); $oSurvey->expires = $expires; } @@ -767,15 +771,15 @@ private function actionUpdateSurveyLocaleSettings($iSurveyID) if ($oSurvey->save()) { Yii::app()->setFlashMessage(gT("Survey settings were successfully saved.")); } else { - Yii::app()->setFlashMessage(Chtml::errorSummary($oSurvey,Chtml::tag("p",array('class'=>'strong'),gT("Survey could not be updated, please fix the following error:"))), "error"); + Yii::app()->setFlashMessage(Chtml::errorSummary($oSurvey, Chtml::tag("p", array('class' => 'strong'), gT("Survey could not be updated, please fix the following error:"))), "error"); } } $oSurvey->refresh(); // Url params in json - if (Yii::app()->request->getPost('allurlparams',false)!==false) { + if (Yii::app()->request->getPost('allurlparams', false) !== false) { $aURLParams = json_decode(Yii::app()->request->getPost('allurlparams'), true); - SurveyURLParameter::model()->deleteAllByAttributes(array('sid'=>$iSurveyID)); + SurveyURLParameter::model()->deleteAllByAttributes(array('sid' => $iSurveyID)); foreach ($aURLParams as $aURLParam) { $aURLParam['parameter'] = trim($aURLParam['parameter']); if ($aURLParam['parameter'] == '' || !preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $aURLParam['parameter']) || $aURLParam['parameter'] == 'sid' || $aURLParam['parameter'] == 'newtest' || $aURLParam['parameter'] == 'token' || $aURLParam['parameter'] == 'lang') { @@ -797,7 +801,7 @@ private function actionUpdateSurveyLocaleSettings($iSurveyID) } $aURLParam['sid'] = $iSurveyID; - $param = new SurveyURLParameter; + $param = new SurveyURLParameter(); foreach ($aURLParam as $k => $v) { $param->$k = $v; } @@ -809,7 +813,6 @@ private function actionUpdateSurveyLocaleSettings($iSurveyID) $this->_resetEM(); if (Yii::app()->request->getPost('responsejson', 0) == 1) { - $updatedFields = $this->updatedFields; $this->updatedFields = []; return Yii::app()->getController()->renderPartial( @@ -817,12 +820,12 @@ private function actionUpdateSurveyLocaleSettings($iSurveyID) array( 'data' => [ 'success' => true, - 'updated'=> $updatedFields, - 'DEBUG' => ['POST'=>$_POST, - 'reloaded'=>$oSurvey->attributes, + 'updated' => $updatedFields, + 'DEBUG' => ['POST' => $_POST, + 'reloaded' => $oSurvey->attributes, 'aURLParams' => isset($aURLParams) ? $aURLParams : '', - 'initial'=>isset($aOldAttributes) ? $aOldAttributes : '', - 'afterApply'=>isset($aAfterApplyAttributes) ? $aAfterApplyAttributes : ''] + 'initial' => isset($aOldAttributes) ? $aOldAttributes : '', + 'afterApply' => isset($aAfterApplyAttributes) ? $aAfterApplyAttributes : ''] ], ), false, @@ -831,17 +834,16 @@ private function actionUpdateSurveyLocaleSettings($iSurveyID) } else { //////////////////////////////////////// if (Yii::app()->request->getPost('close-after-save') === 'true') { - $this->getController()->redirect(array('surveyAdministration/view/surveyid/'.$iSurveyID)); + $this->getController()->redirect(array('surveyAdministration/view/surveyid/' . $iSurveyID)); } $referrer = Yii::app()->request->urlReferrer; if ($referrer) { $this->getController()->redirect(array($referrer)); } else { - $this->getController()->redirect(array('/surveyAdministration/rendersidemenulink/subaction/generalsettings/surveyid/'.$iSurveyID)); + $this->getController()->redirect(array('/surveyAdministration/rendersidemenulink/subaction/generalsettings/surveyid/' . $iSurveyID)); } } - } /** @@ -870,19 +872,20 @@ protected function actionUpdateSurveyLocaleSettingsGeneralSettings($iSurveyID) $oSurvey->gsid, $oSurvey->sid ); - } $oSurvey->template = $new_template; // Only owner and superadmins may change the survey owner - if ($oSurvey->owner_id == Yii::app()->session['loginID'] - || Permission::model()->hasGlobalPermission('superadmin', 'read')) { + if ( + $oSurvey->owner_id == Yii::app()->session['loginID'] + || Permission::model()->hasGlobalPermission('superadmin', 'read') + ) { $oSurvey->owner_id = $request->getPost('owner_id'); } /* Delete removed language cleanLanguagesFromSurvey do it already why redo it (cleanLanguagesFromSurvey must be moved to model) ?*/ $aAvailableLanguage = $oSurvey->getAllLanguages(); - $oCriteria = new CDbCriteria; + $oCriteria = new CDbCriteria(); $oCriteria->compare('surveyls_survey_id', $iSurveyID); $oCriteria->addNotInCondition('surveyls_language', $aAvailableLanguage); SurveyLanguageSetting::model()->deleteAll($oCriteria); @@ -892,10 +895,10 @@ protected function actionUpdateSurveyLocaleSettingsGeneralSettings($iSurveyID) if ($sLang) { $oLanguageSettings = SurveyLanguageSetting::model()->find( 'surveyls_survey_id=:surveyid AND surveyls_language=:langname', - array(':surveyid'=>$iSurveyID, ':langname'=>$sLang) + array(':surveyid' => $iSurveyID, ':langname' => $sLang) ); if (!$oLanguageSettings) { - $oLanguageSettings = new SurveyLanguageSetting; + $oLanguageSettings = new SurveyLanguageSetting(); $languagedetails = getLanguageDetails($sLang); $oLanguageSettings->surveyls_survey_id = $iSurveyID; $oLanguageSettings->surveyls_language = $sLang; @@ -922,7 +925,7 @@ protected function actionUpdateSurveyLocaleSettingsGeneralSettings($iSurveyID) if ($oSurvey->save()) { Yii::app()->setFlashMessage(gT("Survey settings were successfully saved.")); } else { - Yii::app()->setFlashMessage(Chtml::errorSummary($oSurvey,Chtml::tag("p",array('class'=>'strong'),gT("Survey could not be updated, please fix the following error:"))), "error"); + Yii::app()->setFlashMessage(Chtml::errorSummary($oSurvey, Chtml::tag("p", array('class' => 'strong'), gT("Survey could not be updated, please fix the following error:"))), "error"); } Yii::app()->end(); } @@ -953,14 +956,14 @@ private function _filterEmptyFields($oSurvey, $fieldArrayName, $newValue = null) switch ($options['type']) { case 'yesno': - if ($newValue != 'Y' && $newValue != 'N' && $newValue != 'I') { - $newValue = (int) $newValue; - $newValue = ($newValue === 1) ? 'Y' : 'N'; - } - break; + if ($newValue != 'Y' && $newValue != 'N' && $newValue != 'I') { + $newValue = (int) $newValue; + $newValue = ($newValue === 1) ? 'Y' : 'N'; + } + break; case 'Int': $newValue = (int) $newValue; - break; + break; } return $newValue; @@ -973,8 +976,8 @@ private function _resetEM() LimeExpressionManager::SetDirtyFlag(); // UpgradeConditionsToRelevance SetDirtyFlag too LimeExpressionManager::UpgradeConditionsToRelevance($this->iSurveyID); LimeExpressionManager::SetPreviewMode('database');// Deactivate _UpdateValuesInDatabase - LimeExpressionManager::StartSurvey($oSurvey->sid,'survey',$oSurvey->attributes,true); - LimeExpressionManager::StartProcessingPage(true,true); + LimeExpressionManager::StartSurvey($oSurvey->sid, 'survey', $oSurvey->attributes, true); + LimeExpressionManager::StartProcessingPage(true, true); $aGrouplist = QuestionGroup::model()->findAllByAttributes(['sid' => $this->iSurveyID]); foreach ($aGrouplist as $iGID => $aGroup) { LimeExpressionManager::StartProcessingGroup($aGroup['gid'], $oSurvey->anonymized != 'Y', $this->iSurveyID); diff --git a/application/controllers/admin/databaseupdate.php b/application/controllers/admin/databaseupdate.php index e0f29051bc6..dbd457a23e8 100644 --- a/application/controllers/admin/databaseupdate.php +++ b/application/controllers/admin/databaseupdate.php @@ -1,4 +1,5 @@ getConfig('tempdir')."/".randomChars(20); + $sFullFilePath = Yii::app()->getConfig('tempdir') . "/" . randomChars(20); $fileVV = CUploadedFile::getInstanceByName('csv_vv_file'); if ($fileVV) { if (!$fileVV->SaveAs($sFullFilePath)) { @@ -198,8 +200,8 @@ private function _moveUploadedFile($aData) Yii::app()->getConfig('tempdir') ); $aData['aUrls'][] = array( - 'link'=>$this->getController()->createUrl('admin/dataentry/sa/vvimport/surveyid/'.$aData['surveyid']), - 'text'=>$aData['aUrlText'][] = gT("Back to Response Import"), + 'link' => $this->getController()->createUrl('admin/dataentry/sa/vvimport/surveyid/' . $aData['surveyid']), + 'text' => $aData['aUrlText'][] = gT("Back to Response Import"), ); $this->_renderWrappedTemplate('dataentry', 'vvimport_result', $aData); } else { @@ -259,7 +261,6 @@ public function import($surveyid) } if (!App()->getRequest()->isPostRequest || App()->getRequest()->getPost('table') == 'none') { - // Schema that serves as the base for compatibility checks. $baseSchema = SurveyDynamic::model($iSurveyId)->getTableSchema(); $tables = App()->getApi()->getOldResponseTables($iSurveyId); @@ -301,7 +302,7 @@ public function import($surveyid) $aData['display']['menu_bars']['browse'] = gT("Quick statistics"); $survey = Survey::model()->findByPk($iSurveyId); - $aData['title_bar']['title'] = gT('Browse responses').': '.$survey->currentLanguageSettings->surveyls_title; + $aData['title_bar']['title'] = gT('Browse responses') . ': ' . $survey->currentLanguageSettings->surveyls_title; $aData['sidemenu']['state'] = false; $aData['topBar']['name'] = 'baseTopbar_view'; @@ -344,18 +345,18 @@ public function import($surveyid) $targetResponse = new PluginDynamic("{{survey_$iSurveyId}}"); if (isset($_POST['preserveIDs']) && $_POST['preserveIDs'] == 1) { - $targetResponse->id=$sourceResponse->id; + $targetResponse->id = $sourceResponse->id; } foreach ($fieldMap as $sourceField => $targetField) { $targetResponse[$targetField] = $sourceResponse[$sourceField]; } - if (isset($targetSchema->columns['startdate']) && empty($targetResponse['startdate'])){ + if (isset($targetSchema->columns['startdate']) && empty($targetResponse['startdate'])) { $targetResponse['startdate'] = date("Y-m-d H:i", (int) mktime(0, 0, 0, 1, 1, 1980)); } - if (isset($targetSchema->columns['datestamp']) && empty($targetResponse['datestamp'])){ + if (isset($targetSchema->columns['datestamp']) && empty($targetResponse['datestamp'])) { $targetResponse['datestamp'] = date("Y-m-d H:i", (int) mktime(0, 0, 0, 1, 1, 1980)); } @@ -371,17 +372,17 @@ public function import($surveyid) } Yii::app()->session['flashmessage'] = sprintf(gT("%s old response(s) were successfully imported."), $imported); - $sOldTimingsTable = (string) substr(substr($sourceTable->tableName(), 0, (string) strrpos($sourceTable->tableName(), '_')).'_timings'.(string) substr($sourceTable->tableName(), (string) strrpos($sourceTable->tableName(), '_')), strlen(Yii::app()->db->tablePrefix)); + $sOldTimingsTable = (string) substr(substr($sourceTable->tableName(), 0, (string) strrpos($sourceTable->tableName(), '_')) . '_timings' . (string) substr($sourceTable->tableName(), (string) strrpos($sourceTable->tableName(), '_')), strlen(Yii::app()->db->tablePrefix)); $sNewTimingsTable = "survey_{$surveyid}_timings"; if (isset($_POST['timings']) && $_POST['timings'] == 1 && tableExists($sOldTimingsTable) && tableExists($sNewTimingsTable)) { // Import timings - $aFieldsOldTimingTable = array_values(Yii::app()->db->schema->getTable('{{'.$sOldTimingsTable.'}}')->columnNames); - $aFieldsNewTimingTable = array_values(Yii::app()->db->schema->getTable('{{'.$sNewTimingsTable.'}}')->columnNames); + $aFieldsOldTimingTable = array_values(Yii::app()->db->schema->getTable('{{' . $sOldTimingsTable . '}}')->columnNames); + $aFieldsNewTimingTable = array_values(Yii::app()->db->schema->getTable('{{' . $sNewTimingsTable . '}}')->columnNames); $aValidTimingFields = array_intersect($aFieldsOldTimingTable, $aFieldsNewTimingTable); - $sQueryOldValues = "SELECT ".implode(", ", $aValidTimingFields)." FROM {{{$sOldTimingsTable}}} "; + $sQueryOldValues = "SELECT " . implode(", ", $aValidTimingFields) . " FROM {{{$sOldTimingsTable}}} "; $aQueryOldValues = Yii::app()->db->createCommand($sQueryOldValues)->query()->readAll(); //Checked $iRecordCountT = 0; foreach ($aQueryOldValues as $sRecord) { @@ -409,7 +410,7 @@ protected function tableList($tables) { $list = array(); if (empty($tables)) { - $list['none'] = gT('No old responses found.','unescaped'); + $list['none'] = gT('No old responses found.', 'unescaped'); } foreach ($tables as $table) { @@ -493,7 +494,7 @@ public function editdata($subaction, $id, $surveyid) // Perform a case insensitive natural sort on group name then question title of a multidimensional array // $fnames = (Field Name in Survey Table, Short Title of Question, Question Type, Field Name, Question Code, Predetermined Answer if exist) $fnames = []; - $fnames['completed'] = array('fieldname'=>"completed", 'question'=>gT("Completed"), 'type'=>'completed'); + $fnames['completed'] = array('fieldname' => "completed", 'question' => gT("Completed"), 'type' => 'completed'); $fnames = array_merge($fnames, createFieldMap($oSurvey, 'full', false, false, $sDataEntryLanguage)); // Fix private if disallowed to view token @@ -510,13 +511,13 @@ public function editdata($subaction, $id, $surveyid) $results[] = $idresult->attributes; } elseif ($subaction == "editsaved" && Permission::model()->hasSurveyPermission($surveyid, 'responses', 'update')) { if (isset($_GET['public']) && $_GET['public'] == "true") { - $password = hash('sha256',Yii::app()->request->getParam('accesscode')); + $password = hash('sha256', Yii::app()->request->getParam('accesscode')); } else { $password = Yii::app()->request->getParam('accesscode'); } $svresult = SavedControl::model()->findAllByAttributes( - array( + array( 'sid' => $surveyid, 'identifier' => Yii::app()->request->getParam('identifier'), 'access_code' => $password) @@ -530,7 +531,7 @@ public function editdata($subaction, $id, $surveyid) $saver['ip'] = $svrow['ip']; } - $svresult = SavedControl::model()->findAllByAttributes(array('scid'=>$saver['scid'])); + $svresult = SavedControl::model()->findAllByAttributes(array('scid' => $saver['scid'])); $responses = []; foreach ($svresult as $svrow) { $svrow->decrypt(); @@ -587,11 +588,11 @@ public function editdata($subaction, $id, $surveyid) $highlight = !$highlight; $aDataentryoutput .= ">\n" - ."" - ."\n"; + . "" + . "\n"; $aDataentryoutput .= stripJavaScript($question); $aDataentryoutput .= "\n" - ."\n"; + . "\n"; //$aDataentryoutput .= "\t-={$fname[3]}=-"; //Debugging info $qidattributes = []; if (isset($fname['qid']) && isset($fname['type'])) { @@ -605,38 +606,40 @@ public function editdata($subaction, $id, $surveyid) 'Y' => gT('Yes', 'unescaped') ); - $aDataentryoutput .= CHtml::dropDownList('completed', $selected, $select_options, array('class'=>'form-control')); + $aDataentryoutput .= CHtml::dropDownList('completed', $selected, $select_options, array('class' => 'form-control')); break; case Question::QT_X_BOILERPLATE_QUESTION: //Boilerplate question $aDataentryoutput .= ""; break; case Question::QT_Q_MULTIPLE_SHORT_TEXT: - $aDataentryoutput .= $fname['subquestion'].' '; + $aDataentryoutput .= $fname['subquestion'] . ' '; $aDataentryoutput .= CHtml::textField($fname['fieldname'], $idrow[$fname['fieldname']]); break; case Question::QT_K_MULTIPLE_NUMERICAL_QUESTION: - $aDataentryoutput .= $fname['subquestion'].' '; + $aDataentryoutput .= $fname['subquestion'] . ' '; /* Fix DB DECIMAL type */ $value = $idrow[$fname['fieldname']]; if (strpos($value, ".")) { $value = rtrim(rtrim($value, "0"), "."); } - $aDataentryoutput .= CHtml::textField($fname['fieldname'],$value,array('pattern'=>"[-]?([0-9]{0,20}([\.][0-9]{0,10})?)?",'title'=>gT("Only numbers may be entered in this field."))); + $aDataentryoutput .= CHtml::textField($fname['fieldname'], $value, array('pattern' => "[-]?([0-9]{0,20}([\.][0-9]{0,10})?)?",'title' => gT("Only numbers may be entered in this field."))); break; case "id": - $aDataentryoutput .= CHtml::tag('span', array('style' => 'font-weight: bold;'), ' '.$idrow[$fname['fieldname']]); + $aDataentryoutput .= CHtml::tag('span', array('style' => 'font-weight: bold;'), ' ' . $idrow[$fname['fieldname']]); break; case "seed": - $aDataentryoutput .= CHtml::tag('span', array(), ' '.$idrow[$fname['fieldname']]); + $aDataentryoutput .= CHtml::tag('span', array(), ' ' . $idrow[$fname['fieldname']]); break; case Question::QT_5_POINT_CHOICE: //5 POINT CHOICE radio-buttons for ($i = 1; $i <= 5; $i++) { $checked = false; - if ($idrow[$fname['fieldname']] == $i) { $checked = true; } + if ($idrow[$fname['fieldname']] == $i) { + $checked = true; + } $aDataentryoutput .= ''; - $aDataentryoutput .= CHtml::radioButton($fname['fieldname'], $checked, array('class'=>'', 'value'=>$i, 'id'=>'5-point-choice-'.$i)); - $aDataentryoutput .= ''; + $aDataentryoutput .= CHtml::radioButton($fname['fieldname'], $checked, array('class' => '', 'value' => $i, 'id' => '5-point-choice-' . $i)); + $aDataentryoutput .= ''; $aDataentryoutput .= ''; } break; @@ -646,29 +649,33 @@ public function editdata($subaction, $id, $surveyid) $thisdate = ''; if ($idrow[$fname['fieldname']] != '') { $datetimeobj = DateTime::createFromFormat("Y-m-d H:i:s", $idrow[$fname['fieldname']]); - if($datetimeobj == null) { //MSSQL uses microseconds by default in any datetime object + if ($datetimeobj == null) { //MSSQL uses microseconds by default in any datetime object $datetimeobj = DateTime::createFromFormat("Y-m-d H:i:s.u", $idrow[$fname['fieldname']]); } } if (canShowDatePicker($dateformatdetails)) { - if($datetimeobj) { + if ($datetimeobj) { $thisdate = $datetimeobj->format($dateformatdetails['phpdate']); } $goodchars = str_replace(array("m", "d", "y", "H", "M"), "", $dateformatdetails['dateformat']); - $goodchars = "0123456789".$goodchars[0]; - $aDataentryoutput .= CHtml::textField($fname['fieldname'], $thisdate, - array( - 'class' => 'popupdate', - 'size' => '12', - 'onkeypress' => 'return window.LS.goodchars(event,\''.$goodchars.'\')' - ) + $goodchars = "0123456789" . $goodchars[0]; + $aDataentryoutput .= CHtml::textField( + $fname['fieldname'], + $thisdate, + array( + 'class' => 'popupdate', + 'size' => '12', + 'onkeypress' => 'return window.LS.goodchars(event,\'' . $goodchars . '\')' + ) ); - $aDataentryoutput .= CHtml::hiddenField('dateformat'.$fname['fieldname'], $dateformatdetails['jsdate'], - array('id' => "dateformat{$fname['fieldname']}") + $aDataentryoutput .= CHtml::hiddenField( + 'dateformat' . $fname['fieldname'], + $dateformatdetails['jsdate'], + array('id' => "dateformat{$fname['fieldname']}") ); } else { - if($datetimeobj) { + if ($datetimeobj) { $thisdate = $datetimeobj->format("Y-m-d\TH:i"); } $aDataentryoutput .= CHtml::dateTimeLocalField($fname['fieldname'], $thisdate); @@ -676,7 +683,7 @@ public function editdata($subaction, $id, $surveyid) break; case Question::QT_G_GENDER_DROPDOWN: //GENDER drop-down list $select_options = array( - '' => gT("Please choose").'...', + '' => gT("Please choose") . '...', 'F' => gT("Female"), 'M' => gT("Male") ); @@ -693,18 +700,22 @@ public function editdata($subaction, $id, $surveyid) if (substr($fname['fieldname'], -5) == "other") { $aDataentryoutput .= "\t\n"; + . htmlspecialchars($idrow[$fname['fieldname']], ENT_QUOTES) . "' />\n"; } else { - $lresult = Answer::model()->with('answerl10ns')->findAll(array('condition'=>'qid =:qid AND language = :language', 'params' => array('qid' => $fname['qid'], 'language' => $sDataEntryLanguage))); + $lresult = Answer::model()->with('answerl10ns')->findAll(array('condition' => 'qid =:qid AND language = :language', 'params' => array('qid' => $fname['qid'], 'language' => $sDataEntryLanguage))); $aDataentryoutput .= "\t\n"; } @@ -747,25 +763,29 @@ public function editdata($subaction, $id, $surveyid) case Question::QT_O_LIST_WITH_COMMENT: //LIST WITH COMMENT drop-down/radio-button list + textarea $lresult = Answer::model()->findAll("qid={$fname['qid']}"); $aDataentryoutput .= "\t\n"; (!isset($currentvalues[$i - 1])) ? $selected = " selected=\"selected\"" : $selected = ""; - $aDataentryoutput .= "\t\n"; + $aDataentryoutput .= "\t\n"; foreach ($ansresult as $ansrow) { (isset($currentvalues[$i - 1]) && $currentvalues[$i - 1] == $ansrow['code']) ? $selected = " selected=\"selected\"" : $selected = ""; - $aDataentryoutput .= "\t\n"; + $aDataentryoutput .= "\t\n"; } $aDataentryoutput .= "getClientScript()->registerPackage('jquery-actual'); - App()->getClientScript()->registerScriptFile(App()->getConfig('generalscripts').'ranking.js'); - App()->getClientScript()->registerCssFile(Yii::app()->getConfig('publicstyleurl').'ranking.css'); - App()->getClientScript()->registerCssFile(Yii::app()->getConfig('publicstyleurl').'jquery-ui-custom.css'); + App()->getClientScript()->registerScriptFile(App()->getConfig('generalscripts') . 'ranking.js'); + App()->getClientScript()->registerCssFile(Yii::app()->getConfig('publicstyleurl') . 'ranking.css'); + App()->getClientScript()->registerCssFile(Yii::app()->getConfig('publicstyleurl') . 'jquery-ui-custom.css'); $aDataentryoutput .= "\n"; + . " -->\n" + . "\n"; unset($answers); $fname = prev($fnames); @@ -836,10 +856,12 @@ public function editdata($subaction, $id, $surveyid) while ($fname['qid'] == $thisqid) { if (substr($fname['fieldname'], -5) == "other") { $aDataentryoutput .= "\t\n"; + . htmlspecialchars($idrow[$fname['fieldname']], ENT_QUOTES) . "' />\n"; } else { $aDataentryoutput .= "

\t\n"; + if ($idrow[$fname['fieldname']] == "") { + $aDataentryoutput .= " selected='selected'"; + } + $aDataentryoutput .= ">" . gT("Please choose") . "..\n"; foreach ($slangs as $lang) { $aDataentryoutput .= "\n"; } $aDataentryoutput .= ""; break; @@ -872,23 +898,25 @@ public function editdata($subaction, $id, $surveyid) $thefieldname = $fname['fieldname']; if (substr($thefieldname, -7) == "comment") { $aDataentryoutput .= ""; - $aDataentryoutput .= CHtml::textField($fname['fieldname'], $idrow[$fname['fieldname']],array('size'=>50)); + $aDataentryoutput .= CHtml::textField($fname['fieldname'], $idrow[$fname['fieldname']], array('size' => 50)); $aDataentryoutput .= "\n" - ."\t\n"; + . "\t\n"; } elseif (substr($fname['fieldname'], -5) == "other") { $aDataentryoutput .= "\t\n" - ."\n" - . CHtml::textField($fname['fieldname'], $idrow[$fname['fieldname']],array('size'=>30)) - ."\n" - ."\n"; + . "\n" + . CHtml::textField($fname['fieldname'], $idrow[$fname['fieldname']], array('size' => 30)) + . "\n" + . "\n"; $fname = next($fnames); - $aDataentryoutput .= CHtml::textField($fname['fieldname'], $idrow[$fname['fieldname']],array('size'=>50)) - ."\n" - ."\t\n"; + $aDataentryoutput .= CHtml::textField($fname['fieldname'], $idrow[$fname['fieldname']], array('size' => 50)) + . "\n" + . "\t\n"; } else { $aDataentryoutput .= "\t\n" - ."
{$fname['subquestion']}
\n"; } $fname = next($fnames); @@ -898,51 +926,51 @@ public function editdata($subaction, $id, $surveyid) break; case Question::QT_VERTICAL_FILE_UPLOAD: //FILE UPLOAD $aDataentryoutput .= "\n"; - if ($fname['aid'] !== 'filecount' && isset($idrow[$fname['fieldname'].'_filecount']) && ($idrow[$fname['fieldname'].'_filecount'] > 0)) { + if ($fname['aid'] !== 'filecount' && isset($idrow[$fname['fieldname'] . '_filecount']) && ($idrow[$fname['fieldname'] . '_filecount'] > 0)) { //file metadata $metadata = json_decode($idrow[$fname['fieldname']], true); $qAttributes = QuestionAttribute::model()->getQuestionAttributes($fname['qid']); for ($i = 0; ($i < $qAttributes['max_num_of_files']) && isset($metadata[$i]); $i++) { if ($qAttributes['show_title']) { - $aDataentryoutput .= ''; + $aDataentryoutput .= ''; } if ($qAttributes['show_comment']) { - $aDataentryoutput .= ''; + $aDataentryoutput .= ''; } - $aDataentryoutput .= '' - .'' - .'' - .''; + $aDataentryoutput .= '' + . '' + . '' + . ''; } - $aDataentryoutput .= ''; + $aDataentryoutput .= ''; $aDataentryoutput .= '
'.gT("Title").'
' . gT("Title") . '
'.gT("Comment").'
' . gT("Comment") . '
'.gT("File name").'
' . gT("File name") . '
'; $aDataentryoutput .= ''; } else { //file count - $aDataentryoutput .= ''; + $aDataentryoutput .= ''; } break; case Question::QT_N_NUMERICAL: //NUMERICAL TEXT @@ -952,46 +980,54 @@ public function editdata($subaction, $id, $surveyid) $value = rtrim(rtrim($value, "0"), "."); } /* no number fix with return window.LS.goodchars … */ - $aDataentryoutput .= CHtml::textField($fname['fieldname'],$value,array('pattern'=>"[-]?([0-9]{0,20}([\.][0-9]{0,10})?)?",'title'=>gT("Only numbers may be entered in this field."))); + $aDataentryoutput .= CHtml::textField($fname['fieldname'], $value, array('pattern' => "[-]?([0-9]{0,20}([\.][0-9]{0,10})?)?",'title' => gT("Only numbers may be entered in this field."))); break; case Question::QT_S_SHORT_FREE_TEXT: //SHORT FREE TEXT - $aDataentryoutput .= CHtml::textField($fname['fieldname'],$idrow[$fname['fieldname']]); + $aDataentryoutput .= CHtml::textField($fname['fieldname'], $idrow[$fname['fieldname']]); break; case Question::QT_T_LONG_FREE_TEXT: //LONG FREE TEXT - $aDataentryoutput .= CHtml::textArea($fname['fieldname'],$idrow[$fname['fieldname']],array('cols'=>45,'rows'=>5)); + $aDataentryoutput .= CHtml::textArea($fname['fieldname'], $idrow[$fname['fieldname']], array('cols' => 45,'rows' => 5)); break; case Question::QT_U_HUGE_FREE_TEXT: //HUGE FREE TEXT - $aDataentryoutput .= CHtml::textArea($fname['fieldname'],$idrow[$fname['fieldname']],array('cols'=>70,'rows'=>50)); + $aDataentryoutput .= CHtml::textArea($fname['fieldname'], $idrow[$fname['fieldname']], array('cols' => 70,'rows' => 50)); break; case Question::QT_Y_YES_NO_RADIO: //YES/NO radio-buttons $aDataentryoutput .= "\t\n"; + . "
'; @@ -155,7 +157,7 @@ public function getColumns() array( 'name' => 'message', 'htmlOptions' => ['class' => 'col-sm-5'], - 'value'=>'viewHelper::flatEllipsizeText($data->message,true,0)', + 'value' => 'viewHelper::flatEllipsizeText($data->message,true,0)', "type" => 'raw' ) ); @@ -167,7 +169,7 @@ public function search() $survey = Survey::model()->findByPk($this->sid); - $criteria = new CDbCriteria; + $criteria = new CDbCriteria(); $criteria->compare('id', $this->id); $criteria->compare('sid', $this->sid); @@ -183,7 +185,7 @@ public function search() return new CActiveDataProvider( $this, array( - 'criteria'=>$criteria, + 'criteria' => $criteria, 'pagination' => array( 'pageSize' => $pageSize ) @@ -198,7 +200,7 @@ public function search() */ public static function insertRecords($data) { - $assessment = new self; + $assessment = new self(); foreach ($data as $k => $v) { $assessment->$k = $v; @@ -217,7 +219,7 @@ public static function insertRecords($data) */ public static function updateAssessment($id, $iSurveyID, $language, array $data) { - $assessment = self::model()->findByAttributes(array('id' => $id, 'sid'=> $iSurveyID, 'language' => $language)); + $assessment = self::model()->findByAttributes(array('id' => $id, 'sid' => $iSurveyID, 'language' => $language)); if (!is_null($assessment)) { foreach ($data as $k => $v) { $assessment->$k = $v; @@ -232,20 +234,21 @@ public static function updateAssessment($id, $iSurveyID, $language, array $data) * @param $surveyid * @return boolean true if it is actice, false otherwise and if survey does not exist */ - public static function isAssessmentActive($surveyid){ + public static function isAssessmentActive($surveyid) + { $bActive = false; $oSurvey = Survey::model()->findByPk($surveyid); - if($oSurvey !== null){ + if ($oSurvey !== null) { $assessmentActivated = $oSurvey->assessments; // colud be Y, N or I (check inheritance ...) - if($assessmentActivated === 'I'){ //then value is inherited, check survey group value ... - if($oSurvey->gsid ===1){ //this is the default group (it's always set to 'N') + if ($assessmentActivated === 'I') { //then value is inherited, check survey group value ... + if ($oSurvey->gsid === 1) { //this is the default group (it's always set to 'N') $bActive = false; - }else { - $oSurveyGroupSettings= SurveysGroupsettings::model()->findByPk($oSurvey->gsid); + } else { + $oSurveyGroupSettings = SurveysGroupsettings::model()->findByPk($oSurvey->gsid); $isActiveSurveyGroup = $oSurveyGroupSettings->assessments; $bActive = $isActiveSurveyGroup === 'Y'; } - }else{ + } else { $bActive = $assessmentActivated === 'Y'; } } diff --git a/application/models/AssetVersion.php b/application/models/AssetVersion.php index 2d2e8bcad66..fe9c5d08a87 100644 --- a/application/models/AssetVersion.php +++ b/application/models/AssetVersion.php @@ -1,4 +1,8 @@ -true), + array('version', 'numerical', 'integerOnly' => true), ); } @@ -61,11 +65,11 @@ public function rules() */ public static function getAssetVersion($path) { - if(Yii::app()->getConfig('DBVersion') < 400) { + if (Yii::app()->getConfig('DBVersion') < 400) { return 0; } - $oAssetVersion = self::model()->find('path = :path',array(":path"=>$path)); - if(!$oAssetVersion) { + $oAssetVersion = self::model()->find('path = :path', array(":path" => $path)); + if (!$oAssetVersion) { return 0; } return $oAssetVersion->version; @@ -78,13 +82,13 @@ public static function getAssetVersion($path) */ public static function incrementAssetVersion($path) { - if(Yii::app()->getConfig('DBVersion') < 400) { + if (Yii::app()->getConfig('DBVersion') < 400) { return 0; } /* This increment case insensitivity , (extend_vanilla at same time than Extend_Vanilla) no real issue (update 2 assets in one) , but … */ - $oAssetVersion = self::model()->find('path = :path',array(":path"=>$path)); - if(!$oAssetVersion) { - $oAssetVersion = new self; + $oAssetVersion = self::model()->find('path = :path', array(":path" => $path)); + if (!$oAssetVersion) { + $oAssetVersion = new self(); $oAssetVersion->path = $path; $oAssetVersion->version = 0; } @@ -100,9 +104,9 @@ public static function incrementAssetVersion($path) */ public static function deleteAssetVersion($path) { - if(Yii::app()->getConfig('DBVersion') < 400) { + if (Yii::app()->getConfig('DBVersion') < 400) { return 0; } - return self::model()->deleteAll('path = :path',array(":path"=>$path)); + return self::model()->deleteAll('path = :path', array(":path" => $path)); } } diff --git a/application/models/Box.php b/application/models/Box.php index 958518ae4e3..e6d58a11301 100644 --- a/application/models/Box.php +++ b/application/models/Box.php @@ -28,13 +28,13 @@ public function rules() // will receive user inputs. return array( array('url, title, ico, desc, page', 'required'), - array('url', 'match', 'pattern'=>'/(http:\/\/)?[a-zA-Z]([a-zA-Z0-9-_?&"\'=]\/?)*/'), - array('position', 'numerical', 'integerOnly'=>true), - array('usergroup', 'numerical', 'integerOnly'=>true, 'min'=>-3), - array('ico', 'match', 'pattern'=> '/^[A-Za-z0-9_ \-]+$/u','message'=> gT('Icon name must be a simple class name (alphanumeric, space, minus and underscore).')), + array('url', 'match', 'pattern' => '/(http:\/\/)?[a-zA-Z]([a-zA-Z0-9-_?&"\'=]\/?)*/'), + array('position', 'numerical', 'integerOnly' => true), + array('usergroup', 'numerical', 'integerOnly' => true, 'min' => -3), + array('ico', 'match', 'pattern' => '/^[A-Za-z0-9_ \-]+$/u','message' => gT('Icon name must be a simple class name (alphanumeric, space, minus and underscore).')), // The following rule is used by search(). // @todo Please remove those attributes that should not be searched. - array('id, position, url, title, ico, desc, page, usergroup', 'safe', 'on'=>'search'), + array('id, position, url, title, ico, desc, page, usergroup', 'safe', 'on' => 'search'), ); } @@ -58,7 +58,7 @@ public function attributeLabels() 'ico' => gT('Icon:'), 'desc' => gT('Description:'), 'page' => gT('Name of the page where the box should be shown'), - 'usergroup'=> gT('Display this box to:') + 'usergroup' => gT('Display this box to:') ); } @@ -79,7 +79,7 @@ public function search() { // @todo Please modify the following code to remove attributes that should not be searched. - $criteria = new CDbCriteria; + $criteria = new CDbCriteria(); $criteria->compare('id', $this->id); $criteria->compare('position', $this->position); @@ -90,7 +90,7 @@ public function search() $criteria->compare('page', $this->page, true); return new CActiveDataProvider($this, array( - 'criteria'=>$criteria, + 'criteria' => $criteria, )); } @@ -99,7 +99,7 @@ public function search() */ public function getSpanIcon() { - $spanicon = ''; + $spanicon = ''; return $spanicon; } @@ -136,19 +136,19 @@ public function getbuttons() { $url = Yii::app()->createUrl("/homepageSettings/updateBox/id/"); - $url .= '/'.$this->id; - $button = ''; + $url .= '/' . $this->id; + $button = ''; $url = Yii::app()->createUrl("/homepageSettings/deleteBox"); //$url .= '/'.$this->id; $button .= ' $this->id]).'\'' - .' data-text="'.gT('Are you sure you want to delete this box ?').'"' - .'>'; + . ' data-button-no="' . gT('No, cancel') . '"' + . ' data-button-yes="' . gT('Yes, delete') . '"' + . ' href="' . $url . '"' + . ' title="' . gT("Delete box") . '"' + . ' role="button" data-post=\'' . json_encode(['id' => $this->id]) . '\'' + . ' data-text="' . gT('Are you sure you want to delete this box ?') . '"' + . '>'; return $button; } diff --git a/application/models/Condition.php b/application/models/Condition.php index 621a46444a2..637722d1e99 100644 --- a/application/models/Condition.php +++ b/application/models/Condition.php @@ -88,11 +88,11 @@ public function relations() */ public function deleteRecords($condition = false) { - $criteria = new CDbCriteria; + $criteria = new CDbCriteria(); if ($condition != false) { if (is_array($condition)) { - foreach ($condition as $column=>$value) { + foreach ($condition as $column => $value) { $criteria->addCondition("$column='$value'"); } } else { @@ -114,14 +114,18 @@ public function deleteRecords($condition = false) */ public function updateCFieldName($iSurveyID, $iQuestionID, $iOldGroupID, $iNewGroupID) { - $oResults = $this->findAllByAttributes(array('cqid'=>$iQuestionID)); + $oResults = $this->findAllByAttributes(array('cqid' => $iQuestionID)); foreach ($oResults as $oRow) { $cfnregs = []; - if (preg_match('/(\S*?)'.$iSurveyID."X".$iOldGroupID."X".$iQuestionID."(.*)/", $oRow->cfieldname, $cfnregs) > 0) { - $sNewCfn = $cfnregs[1].$iSurveyID."X".$iNewGroupID."X".$iQuestionID.$cfnregs[2]; + if (preg_match('/(\S*?)' . $iSurveyID . "X" . $iOldGroupID . "X" . $iQuestionID . "(.*)/", $oRow->cfieldname, $cfnregs) > 0) { + $sNewCfn = $cfnregs[1] . $iSurveyID . "X" . $iNewGroupID . "X" . $iQuestionID . $cfnregs[2]; Yii::app()->db->createCommand() - ->update($this->tableName(), array('cfieldname' => $sNewCfn), - 'cid=:cid', array(':cid'=>$oRow->cid)); + ->update( + $this->tableName(), + array('cfieldname' => $sNewCfn), + 'cid=:cid', + array(':cid' => $oRow->cid) + ); LimeExpressionManager::UpgradeConditionsToRelevance($iSurveyID, $oRow->qid); } } @@ -131,16 +135,16 @@ public function updateCFieldName($iSurveyID, $iQuestionID, $iOldGroupID, $iNewGr public function insertRecords($data, $update = false, $condition = false) { - $record = new self; + $record = new self(); foreach ($data as $k => $v) { $v = str_replace(array("'", '"'), '', $v); $record->$k = $v; } if ($update) { - $criteria = new CdbCriteria; + $criteria = new CdbCriteria(); if (is_array($condition)) { - foreach ($condition as $column=>$value) { + foreach ($condition as $column => $value) { $criteria->addCondition("$column='$value'"); } } else { @@ -159,9 +163,9 @@ public function insertRecords($data, $update = false, $condition = false) */ public function getScenarios($qid) { - $query = "SELECT DISTINCT scenario FROM ".$this->tableName()." WHERE qid=:qid ORDER BY scenario"; + $query = "SELECT DISTINCT scenario FROM " . $this->tableName() . " WHERE qid=:qid ORDER BY scenario"; $command = Yii::app()->db->createCommand($query); - $command->params = [':qid'=>$qid]; + $command->params = [':qid' => $qid]; return $command->query(); } @@ -192,13 +196,13 @@ public function getSomeConditions($fields, $condition, $order, $group) public function getConditionsQuestions($distinctrow, $deqrow, $scenariorow, $surveyprintlang) { $conquery = "SELECT cid, cqid, q.title, question, value, q.type, cfieldname " - ."FROM {{conditions}} c " - ."JOIN {{questions}} q on c.cqid=q.qid " - ."JOIN {{question_l10ns}} l on l.qid=q.qid " - ."WHERE c.cqid=:distinctrow " - ."AND c.qid=:deqrow " - ."AND c.scenario=:scenariorow " - ."AND language=:surveyprintlang "; + . "FROM {{conditions}} c " + . "JOIN {{questions}} q on c.cqid=q.qid " + . "JOIN {{question_l10ns}} l on l.qid=q.qid " + . "WHERE c.cqid=:distinctrow " + . "AND c.qid=:deqrow " + . "AND c.scenario=:scenariorow " + . "AND language=:surveyprintlang "; return Yii::app()->db->createCommand($conquery) ->bindParam(":distinctrow", $distinctrow, PDO::PARAM_INT) ->bindParam(":deqrow", $deqrow, PDO::PARAM_INT) @@ -217,7 +221,7 @@ public function getAllCfieldnameWithDependenciesForOneSurvey($sid) ->select('cfieldname') ->from('{{questions}} questions') ->join('{{conditions}} conditions', 'questions.qid=conditions.cqid') - ->where('sid=:sid', array(':sid'=>$sid)) + ->where('sid=:sid', array(':sid' => $sid)) ->queryRow(); return $Qids; @@ -291,11 +295,11 @@ public function getConditions($qid, $language, Condition $scenarionr) 'select' => 't.cid, t.scenario, t.cqid, t.cfieldname, t.method, t.value', 'condition' => 't.qid = ' . $qid . ' and scenario = ' . $scenarionr['scenario'] . ' and cfieldname NOT LIKE \'{%\'' ) - ); + ); $aResults = array(); $i = 0; - foreach($results as $result){ + foreach ($results as $result) { $aResults[$i] = $result->attributes; $aResults[$i]['type'] = $result->questions->type; $i += 1; @@ -313,11 +317,11 @@ public function getConditions($qid, $language, Condition $scenarionr) public function getConditionCountToken($qid, Condition $scenarionr) { $querytoken = "SELECT count(*) as recordcount " - ."FROM {{conditions}} " - ."WHERE " - ." {{conditions}}.qid=:qid " - ."AND {{conditions}}.scenario=:scenario " - ."AND {{conditions}}.cfieldname LIKE '{%' "; // only catching SRCtokenAttr conditions + . "FROM {{conditions}} " + . "WHERE " + . " {{conditions}}.qid=:qid " + . "AND {{conditions}}.scenario=:scenario " + . "AND {{conditions}}.cfieldname LIKE '{%' "; // only catching SRCtokenAttr conditions $resulttoken = Yii::app()->db->createCommand($querytoken) ->bindValue(":scenario", $scenarionr['scenario'], PDO::PARAM_INT) ->bindValue(":qid", $qid, PDO::PARAM_INT) @@ -338,18 +342,18 @@ public function getConditionCountToken($qid, Condition $scenarionr) public function getConditionsToken($qid, Condition $scenarionr) { $querytoken = "SELECT {{conditions}}.cid, " - ."{{conditions}}.scenario, " - ."{{conditions}}.cqid, " - ."{{conditions}}.cfieldname, " - ."{{conditions}}.method, " - ."{{conditions}}.value, " - ."'' AS type " - ."FROM {{conditions}} " - ."WHERE " - ." {{conditions}}.qid=:qid " - ."AND {{conditions}}.scenario=:scenario " - ."AND {{conditions}}.cfieldname LIKE '{%' " // only catching SRCtokenAttr conditions - ."ORDER BY {{conditions}}.cfieldname"; + . "{{conditions}}.scenario, " + . "{{conditions}}.cqid, " + . "{{conditions}}.cfieldname, " + . "{{conditions}}.method, " + . "{{conditions}}.value, " + . "'' AS type " + . "FROM {{conditions}} " + . "WHERE " + . " {{conditions}}.qid=:qid " + . "AND {{conditions}}.scenario=:scenario " + . "AND {{conditions}}.cfieldname LIKE '{%' " // only catching SRCtokenAttr conditions + . "ORDER BY {{conditions}}.cfieldname"; $result = Yii::app()->db->createCommand($querytoken) ->bindValue(":scenario", $scenarionr['scenario'], PDO::PARAM_INT) ->bindValue(":qid", $qid, PDO::PARAM_INT) diff --git a/application/models/DefaultValue.php b/application/models/DefaultValue.php index f124868c7f5..4423967782b 100644 --- a/application/models/DefaultValue.php +++ b/application/models/DefaultValue.php @@ -1,4 +1,6 @@ -true), + array('qid,sqid,scale_id', 'numerical', 'integerOnly' => true), ); } @@ -82,7 +84,7 @@ public function rules() */ public function insertRecords($data) { - $oRecord = new self; + $oRecord = new self(); foreach ($data as $k => $v) { $oRecord->$k = $v; } diff --git a/application/models/DefaultValueL10n.php b/application/models/DefaultValueL10n.php index f528b36077d..3fa7ec283dc 100644 --- a/application/models/DefaultValueL10n.php +++ b/application/models/DefaultValueL10n.php @@ -1,4 +1,6 @@ -true), + array('dvid', 'numerical', 'integerOnly' => true), array('defaultvalue', 'LSYii_Validators'), - array('language', 'length', 'min' => 2, 'max'=>20), // in array languages ? + array('language', 'length', 'min' => 2, 'max' => 20), // in array languages ? ); } @@ -76,7 +78,6 @@ public function relations() public function defaultScope() { - return array('index'=>'language'); - } - + return array('index' => 'language'); + } } diff --git a/application/models/Dynamic.php b/application/models/Dynamic.php index dd3774780fb..43605c15f5f 100644 --- a/application/models/Dynamic.php +++ b/application/models/Dynamic.php @@ -1,4 +1,5 @@ dynamicId; } } diff --git a/application/models/ExpressionError.php b/application/models/ExpressionError.php index ef13bce7474..b9f58258af0 100644 --- a/application/models/ExpressionError.php +++ b/application/models/ExpressionError.php @@ -1,4 +1,6 @@ -db->insert('expression_errors', $data); } - } diff --git a/application/models/ExtensionConfig.php b/application/models/ExtensionConfig.php index 656fcab091b..904d07c7c1b 100644 --- a/application/models/ExtensionConfig.php +++ b/application/models/ExtensionConfig.php @@ -23,7 +23,7 @@ class ExtensionConfig public $xml; /** - * + * */ public function __construct(SimpleXMLElement $xml) { diff --git a/application/models/ExtensionUpdateInfo.php b/application/models/ExtensionUpdateInfo.php index 0c0b5239eae..833725e8799 100644 --- a/application/models/ExtensionUpdateInfo.php +++ b/application/models/ExtensionUpdateInfo.php @@ -49,7 +49,7 @@ public function __construct($type, $versions, $security = false) } /** - * + * */ public function versionIsSecurityUpdate() { diff --git a/application/models/FailedLoginAttempt.php b/application/models/FailedLoginAttempt.php index 1603848dc87..aa36ab505d5 100644 --- a/application/models/FailedLoginAttempt.php +++ b/application/models/FailedLoginAttempt.php @@ -1,4 +1,6 @@ -condition = 'number_attempts > :attempts AND ip = :ip'; $criteria->params = array(':attempts' => Yii::app()->getConfig('maxLoginAttempt'), ':ip' => $ip); @@ -114,7 +116,7 @@ public function addAttempt() $row->last_attempt = $timestamp; $row->save(); } else { - $record = new FailedLoginAttempt; + $record = new FailedLoginAttempt(); $record->ip = $ip; $record->number_attempts = 1; $record->last_attempt = $timestamp; diff --git a/application/models/Field.php b/application/models/Field.php index 27fbe824d50..c8079c0cf35 100644 --- a/application/models/Field.php +++ b/application/models/Field.php @@ -63,6 +63,4 @@ public function getType() throw new \Exception('unfinished method'); } } - - -} \ No newline at end of file +} diff --git a/application/models/InstallerConfigForm.php b/application/models/InstallerConfigForm.php index 7565b1ce934..501cf1c8ed8 100644 --- a/application/models/InstallerConfigForm.php +++ b/application/models/InstallerConfigForm.php @@ -1,4 +1,6 @@ - gT("The type of your database management system"), - 'dblocation' => gT('Set this to the IP/net location of your database server. In most cases "localhost" will work. You can force Unix socket with complete socket path.').' '.gT('If your database is using a custom port attach it using a colon. Example: db.host.com:5431'), + 'dblocation' => gT('Set this to the IP/net location of your database server. In most cases "localhost" will work. You can force Unix socket with complete socket path.') . ' ' . gT('If your database is using a custom port attach it using a colon. Example: db.host.com:5431'), 'dbname' => gT("If the database does not yet exist it will be created (make sure your database user has the necessary permissions). In contrast, if there are existing LimeSurvey tables in that database they will be upgraded automatically after installation."), 'dbuser' => gT('Your database server user name. In most cases "root" will work.'), 'dbpwd' => gT("Your database server password."), @@ -212,7 +214,6 @@ private function checkStatus() $this->isPhpGdPresent = array_key_exists('FreeType Support', gd_info()); } $this->isPhpVersionOK = version_compare(PHP_VERSION, self::MINIMUM_PHP_VERSION, '>='); - } /** @@ -222,16 +223,17 @@ private function checkStatus() public function getHasMinimumRequirements() { - if (!$this->isMemoryLimitOK + if ( + !$this->isMemoryLimitOK or !$this->isUploadDirWriteable or !$this->isTmpDirWriteable or !$this->isConfigDirWriteable or !$this->isPhpVersionOK or !$this->isPhpMbStringPresent or !$this->isPhpZlibPresent - or !$this->isPhpJsonPresent) { + or !$this->isPhpJsonPresent + ) { return false; - } if (count($this->supportedDbTypes) == 0) { @@ -259,14 +261,17 @@ private function checkMemoryLimit() * Memory limit in MB * @return float|int */ - public function getMemoryLimit() { + public function getMemoryLimit() + { return convertPHPSizeToBytes(ini_get('memory_limit')) / 1024 / 1024; } public function validateDBEngine($attribute) { - if ($this->isMysql - && ($this->dbengine === null or !in_array($this->dbengine, array_keys($this->dbEngines)))) { + if ( + $this->isMysql + && ($this->dbengine === null or !in_array($this->dbengine, array_keys($this->dbEngines))) + ) { $this->addError($attribute, gT('The database engine type must be set for MySQL')); } @@ -284,7 +289,8 @@ public function validateDBEngine($attribute) * Get the array of supported DB type * @return array */ - public function getSupportedDbTypes(){ + public function getSupportedDbTypes() + { $result = array(); foreach (CDbConnection::getAvailableDrivers() as $driver) { if (isset($this->db_names[$driver])) { @@ -295,7 +301,8 @@ public function getSupportedDbTypes(){ return $result; } - private function setInitialEngine() { + private function setInitialEngine() + { if (isset($this->supportedDbTypes[self::DB_TYPE_MYSQL])) { if (getenv('DBENGINE')) { $this->dbengine = getenv('DBENGINE'); @@ -308,22 +315,25 @@ private function setInitialEngine() { /** * @return bool */ - public function getIsConfigDirWriteable() { - return is_writable(Yii::app()->getConfig('rootdir').'/application/config'); + public function getIsConfigDirWriteable() + { + return is_writable(Yii::app()->getConfig('rootdir') . '/application/config'); } /** * @return bool */ - public function getIsTmpDirWriteable() { - return self::is_writable_recursive(Yii::app()->getConfig('tempdir').DIRECTORY_SEPARATOR); + public function getIsTmpDirWriteable() + { + return self::is_writable_recursive(Yii::app()->getConfig('tempdir') . DIRECTORY_SEPARATOR); } /** * @return bool */ - public function getIsUploadDirWriteable() { - return self::is_writable_recursive(Yii::app()->getConfig('uploaddir').DIRECTORY_SEPARATOR); + public function getIsUploadDirWriteable() + { + return self::is_writable_recursive(Yii::app()->getConfig('uploaddir') . DIRECTORY_SEPARATOR); } @@ -338,9 +348,11 @@ public static function is_writable_recursive($sDirectory) return false; // Dir does not exist } while ($sFile = readdir($sFolder)) { - if ($sFile != '.' && $sFile != '..' && - (!is_writable($sDirectory.DIRECTORY_SEPARATOR.$sFile) || - (is_dir($sDirectory.DIRECTORY_SEPARATOR.$sFile) && !self::is_writable_recursive($sDirectory.DIRECTORY_SEPARATOR.$sFile)))) { + if ( + $sFile != '.' && $sFile != '..' && + (!is_writable($sDirectory . DIRECTORY_SEPARATOR . $sFile) || + (is_dir($sDirectory . DIRECTORY_SEPARATOR . $sFile) && !self::is_writable_recursive($sDirectory . DIRECTORY_SEPARATOR . $sFile))) + ) { closedir($sFolder); return false; } @@ -349,7 +361,8 @@ public static function is_writable_recursive($sDirectory) return true; } - public function isInnoDbLargeFilePrefixEnabled() { + public function isInnoDbLargeFilePrefixEnabled() + { return $this->getMySqlConfigValue('innodb_large_prefix') == '1'; } @@ -359,9 +372,9 @@ public function isInnoDbLargeFilePrefixEnabled() { */ private function getMySqlConfigValue($itemName) { - $item = "@@".$itemName; + $item = "@@" . $itemName; try { - $query = "SELECT ".$item.";"; + $query = "SELECT " . $item . ";"; $result = $this->db->createCommand($query)->queryRow(); return isset($result[$item]) ? $result[$item] : null; } catch (\Exception $e) { @@ -373,7 +386,8 @@ private function getMySqlConfigValue($itemName) /** * @return bool */ - private function isInnoDbBarracudaFileFormat() { + private function isInnoDbBarracudaFileFormat() + { $check1 = $this->getMySqlConfigValue('innodb_file_format') == 'Barracuda'; $check2 = $this->getMySqlConfigValue('innodb_file_format_max') == 'Barracuda'; return $check1 && $check2; @@ -382,7 +396,8 @@ private function isInnoDbBarracudaFileFormat() { /** * @return array */ - public function getDbEngines() { + public function getDbEngines() + { return [ self::ENGINE_TYPE_MYISAM => 'MyISAM', self::ENGINE_TYPE_INNODB => 'InnoDB' @@ -415,15 +430,14 @@ public function dbConnect() $this->db->emulatePrepare = true; } if (in_array($this->dbtype, [ self::DB_TYPE_SQLSRV, self::DB_TYPE_DBLIB, self::DB_TYPE_MSSQL])) { - $this->db->initSQLs=['SET DATEFORMAT ymd;', 'SET QUOTED_IDENTIFIER ON;']; + $this->db->initSQLs = ['SET DATEFORMAT ymd;', 'SET QUOTED_IDENTIFIER ON;']; } $this->db->tablePrefix = $this->dbprefix; $this->setMySQLDefaultEngine($this->dbengine); - } catch (\Exception $e) { $this->addError('dblocation', gT('Try again! Connection with database failed.')); - $this->addError('dblocation', gT('Reason:').' '.$e->getMessage()); + $this->addError('dblocation', gT('Reason:') . ' ' . $e->getMessage()); } return true; } @@ -447,13 +461,13 @@ private function dbTest() * @param string $dbEngine * @throws CDbException */ - private function setMySQLDefaultEngine($dbEngine) { + private function setMySQLDefaultEngine($dbEngine) + { if (!empty($this->db) && $this->db->driverName === self::DB_TYPE_MYSQL) { $this->db ->createCommand(new CDbExpression(sprintf('SET default_storage_engine=%s;', $dbEngine))) ->execute(); } - } /** @@ -473,7 +487,7 @@ public function getDsn() $sDSN = $this->getPgsqlDsn(); break; case self::DB_TYPE_DBLIB: - $sDSN = $this->dbtype.":host={$this->dblocation};dbname={$this->dbname}"; + $sDSN = $this->dbtype . ":host={$this->dblocation};dbname={$this->dbname}"; break; case self::DB_TYPE_MSSQL: case self::DB_TYPE_SQLSRV: @@ -488,7 +502,8 @@ public function getDsn() /** * @return string */ - private function getMysqlDsn() { + private function getMysqlDsn() + { $port = $this->getDbPort(); @@ -528,13 +543,14 @@ private function getPgsqlDsn() /** * @return string */ - private function getMssqlDsn() { + private function getMssqlDsn() + { $port = $this->getDbPort(); $sDatabaseLocation = $this->dblocation; if ($port != '') { - $sDatabaseLocation = $this->dblocation.','.$port; + $sDatabaseLocation = $this->dblocation . ',' . $port; } - $sDSN = $this->dbtype.":Server={$sDatabaseLocation};"; + $sDSN = $this->dbtype . ":Server={$sDatabaseLocation};"; if ($this->useDbName) { $sDSN .= "Database={$this->dbname}"; } @@ -574,14 +590,16 @@ private function getDbDefaultPort() /** * @return bool */ - public function getIsMysql() { + public function getIsMysql() + { return in_array($this->dbtype, [self::DB_TYPE_MYSQL, self::DB_TYPE_MYSQLI]); } /** * @return bool */ - public function getIsMSSql() { + public function getIsMSSql() + { return in_array($this->dbtype, [self::DB_TYPE_MSSQL, self::DB_TYPE_DBLIB, self::DB_TYPE_SQLSRV]); } @@ -589,7 +607,8 @@ public function getIsMSSql() { * @return void * @throws Exception */ - public function createDatabase() { + public function createDatabase() + { $query = $this->createDbQuery(); try { $this->db->createCommand($query)->execute(); @@ -613,7 +632,7 @@ private function createDbQuery() $query = "CREATE DATABASE {$this->dbname}"; if ($this->isMysql) { $query = "CREATE DATABASE `{$this->dbname}` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci"; - } else if ($this->isMSSql) { + } elseif ($this->isMSSql) { $query = "CREATE DATABASE [{$this->dbname}];"; } if ($this->dbtype === self::DB_TYPE_PGSQL) { @@ -636,14 +655,14 @@ public function setupTables() switch ($this->dbtype) { case self::DB_TYPE_MYSQL: case self::DB_TYPE_MYSQLI: - $this->db->createCommand("ALTER DATABASE ".$this->db->quoteTableName($this->dbname)." DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;") + $this->db->createCommand("ALTER DATABASE " . $this->db->quoteTableName($this->dbname) . " DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;") ->execute(); break; } } catch (Exception $e) { return array($e->getMessage()); } - $fileName = dirname(APPPATH).'/installer/create-database.php'; + $fileName = dirname(APPPATH) . '/installer/create-database.php'; require_once($fileName); try { populateDatabase($this->db); diff --git a/application/models/LSActiveRecord.php b/application/models/LSActiveRecord.php index 51412a8847c..44847e3022f 100644 --- a/application/models/LSActiveRecord.php +++ b/application/models/LSActiveRecord.php @@ -1,4 +1,5 @@ getCommandBuilder()->createCriteria($condition, $params); return $this->query($criteria, true, false); //Notice the third parameter 'false' } @@ -130,7 +131,7 @@ public function getMaxId($field = null, $forceRefresh = false) if ($forceRefresh || !array_key_exists($field, $maxIds)) { $maxId = $this->dbConnection->createCommand() - ->select('MAX('.$this->dbConnection->quoteColumnName($field).')') + ->select('MAX(' . $this->dbConnection->quoteColumnName($field) . ')') ->from($this->tableName()) ->queryScalar(); @@ -162,12 +163,13 @@ public function getMinId($field = null, $forceRefresh = false) $field = $primaryKey; } else { // Composite key, throw a warning to the programmer - throw new Exception(sprintf('Table %s has a composite primary key, please explicitly state what field you need the min value for.', $this->tableName())); } + throw new Exception(sprintf('Table %s has a composite primary key, please explicitly state what field you need the min value for.', $this->tableName())); + } } if ($forceRefresh || !array_key_exists($field, $minIds)) { $minId = $this->dbConnection->createCommand() - ->select('MIN('.$this->dbConnection->quoteColumnName($field).')') + ->select('MIN(' . $this->dbConnection->quoteColumnName($field) . ')') ->from($this->tableName()) ->queryScalar(); @@ -200,71 +202,72 @@ public function deleteAllByAttributes($attributes, $condition = '', $params = ar $criteria = $builder->createColumnCriteria($table, $attributes, $condition, $params); $modelEventName = get_class($this); $eventParams = array(); - if(is_subclass_of($this,'Dynamic')) { - /** @scrutinizer ignore-call since we test if exist by subclass */ + if (is_subclass_of($this, 'Dynamic')) { + /** @scrutinizer ignore-call since we test if exist by subclass */ $eventParams['dynamicId'] = $this->getDynamicId(); $modelEventName = get_parent_class($this); } - $this->dispatchPluginModelEvent('before'.$modelEventName.'DeleteMany', $criteria,$eventParams); - $this->dispatchPluginModelEvent('beforeModelDeleteMany', $criteria,$eventParams); + $this->dispatchPluginModelEvent('before' . $modelEventName . 'DeleteMany', $criteria, $eventParams); + $this->dispatchPluginModelEvent('beforeModelDeleteMany', $criteria, $eventParams); return parent::deleteAllByAttributes(array(), $criteria, array()); } /** - * Overriding of Yii's findByAttributes method to provide encrypted attribute value search - * @param array $attributes list of attribute values (indexed by attribute names) that the active records should match. - * An attribute value can be an array which will be used to generate an IN condition. + * Overriding of Yii's findByAttributes method to provide encrypted attribute value search + * @param array $attributes list of attribute values (indexed by attribute names) that the active records should match. + * An attribute value can be an array which will be used to generate an IN condition. * @param mixed $condition query condition or criteria. - * @param array $params parameters to be bound to an SQL statement. + * @param array $params parameters to be bound to an SQL statement. * @return static|null the record found. Null if none is found. - */ - public function findByAttributes($attributes, $condition='',$params=array()) - { + */ + public function findByAttributes($attributes, $condition = '', $params = array()) + { $attributes = $this->encryptAttributeValues($attributes); return parent::findByAttributes($attributes, $condition, $params); } /** - * Overriding of Yii's findAllByAttributes method to provide encrypted attribute value search + * Overriding of Yii's findAllByAttributes method to provide encrypted attribute value search * @param array $attributes list of attribute values (indexed by attribute names) that the active records should match. - * An attribute value can be an array which will be used to generate an IN condition. - * @param mixed $condition query condition or criteria. - * @param array $params parameters to be bound to an SQL statement. - * @return static[] the records found. An empty array is returned if none is found. - */ - public function findAllByAttributes($attributes, $condition='',$params=array()) - { + * An attribute value can be an array which will be used to generate an IN condition. + * @param mixed $condition query condition or criteria. + * @param array $params parameters to be bound to an SQL statement. + * @return static[] the records found. An empty array is returned if none is found. + */ + public function findAllByAttributes($attributes, $condition = '', $params = array()) + { $attributes = $this->encryptAttributeValues($attributes); return parent::findAllByAttributes($attributes, $condition, $params); - } + } /** * @param int $iSurveyId * @param string $sClassName * @return array */ - public function getAllEncryptedAttributes($iSurveyId = 0, $sClassName){ + public function getAllEncryptedAttributes($iSurveyId = 0, $sClassName) + { $aAttributes = array(); - if ($sClassName == 'ParticipantAttribute'){ + if ($sClassName == 'ParticipantAttribute') { // participants attributes $aAttributes[] = 'value'; } elseif ($sClassName == 'Participant') { // participants $aTokenAttributes = Participant::getParticipantsEncryptionOptions(); - if ($aTokenAttributes['enabled'] = 'Y'){ + if ($aTokenAttributes['enabled'] = 'Y') { foreach ($aTokenAttributes['columns'] as $attribute => $oColumn) { - if ($oColumn == 'Y'){ + if ($oColumn == 'Y') { $aAttributes[] = $attribute; } } } - } elseif ($iSurveyId > 0 && ($sClassName == 'TokenDynamic' || $sClassName == 'Token_'.$iSurveyId || $sClassName == 'Token')) { + } elseif ($iSurveyId > 0 && ($sClassName == 'TokenDynamic' || $sClassName == 'Token_' . $iSurveyId || $sClassName == 'Token')) { //core token attributes $oSurvey = Survey::model()->findByPk($iSurveyId); $aTokenAttributes = $oSurvey->getTokenEncryptionOptions(); - if ($aTokenAttributes['enabled'] = 'Y'){ + if ($aTokenAttributes['enabled'] = 'Y') { foreach ($aTokenAttributes['columns'] as $attribute => $oColumn) { - if ($oColumn == 'Y'){ + if ($oColumn == 'Y') { $aAttributes[] = $attribute; } } @@ -272,11 +275,11 @@ public function getAllEncryptedAttributes($iSurveyId = 0, $sClassName){ // custom token attributes $aCustomAttributes = $oSurvey->tokenAttributes; foreach ($aCustomAttributes as $attribute => $value) { - if ($value['encrypted'] == 'Y'){ + if ($value['encrypted'] == 'Y') { $aAttributes[] = $attribute; } } - } elseif ($sClassName == 'SurveyDynamic' || $sClassName == 'Response_'.$iSurveyId){ + } elseif ($sClassName == 'SurveyDynamic' || $sClassName == 'Response_' . $iSurveyId) { // response attributes $aAttributes = Response::getEncryptedAttributes($iSurveyId); } @@ -285,7 +288,7 @@ public function getAllEncryptedAttributes($iSurveyId = 0, $sClassName){ } /** - * Attribute values are encrypted ( if needed )to be used for searching purposes + * Attribute values are encrypted ( if needed )to be used for searching purposes * @param array $attributes list of attribute values (indexed by attribute names) that the active records should match. * An attribute value can be an array which will be used to generate an IN condition. * @return array attributes array with encrypted atrribute values is returned @@ -295,7 +298,7 @@ public function encryptAttributeValues($attributes = null, $bEncryptedOnly = fal // load sodium library $sodium = Yii::app()->sodium; - if (method_exists($this, 'getSurveyId')){ + if (method_exists($this, 'getSurveyId')) { $iSurveyId = $this->getSurveyId(); } else { $iSurveyId = 0; @@ -303,13 +306,13 @@ public function encryptAttributeValues($attributes = null, $bEncryptedOnly = fal $class = get_class($this); $encryptedAttributes = $this->getAllEncryptedAttributes($iSurveyId, $class); $attributeCount = count($attributes); - foreach($attributes as $key => $attribute){ - if(in_array($key, $encryptedAttributes)){ - if ($bReplaceValues){ + foreach ($attributes as $key => $attribute) { + if (in_array($key, $encryptedAttributes)) { + if ($bReplaceValues) { $attributes[$key] = $sodium->encrypt($attributes[$key]); } } else { - if ($bEncryptedOnly){ + if ($bEncryptedOnly) { unset($attributes[$key]); } } @@ -322,10 +325,9 @@ public function encryptAttributeValues($attributes = null, $bEncryptedOnly = fal * @param string $sValueSingle String value which needs to be decrypted */ public function decrypt($value = '') - { + { // if $sValueSingle is provided, it would decrypt - if (!empty($value)){ - + if (!empty($value)) { // load sodium library $sodium = Yii::app()->sodium; @@ -344,10 +346,9 @@ public function decrypt($value = '') * @param string $value String value which needs to be decrypted */ public static function decryptSingle($value = '') - { + { // if $value is provided, it would decrypt - if (!empty($value)){ - + if (!empty($value)) { // load sodium library $sodium = Yii::app()->sodium; return $sodium->decrypt($value); @@ -360,10 +361,9 @@ public static function decryptSingle($value = '') * @param string $value String value which needs to be decrypted */ public static function encryptSingle($value = '') - { + { // if $value is provided, it would decrypt - if (!empty($value)){ - + if (!empty($value)) { // load sodium library $sodium = Yii::app()->sodium; return $sodium->encrypt($value); @@ -387,13 +387,13 @@ public function encrypt() /** * Encrypt values before saving to the database */ - public function encryptSave($runValidation=false) + public function encryptSave($runValidation = false) { // run validation on attribute values before encryption take place, it is impossible to validate encrypted values - if ($runValidation){ - if(!$this->validate()) { + if ($runValidation) { + if (!$this->validate()) { return false; - } + } } // encrypt attributes @@ -428,21 +428,20 @@ public function decryptEncryptAttributes($action = 'decrypt') } /** * Function to show encryption symbol in gridview attribute header if value ois encrypted - * @param int $surveyId - * @param string $className - * @param string $attributeName - * @return string - * @throws CException + * @param int $surveyId + * @param string $className + * @param string $attributeName + * @return string + * @throws CException */ public function setEncryptedAttributeLabel(int $surveyId = 0, string $className, string $attributeName) { $encryptedAttributes = $this->getAllEncryptedAttributes($surveyId, $className); $encryptionNotice = gT("This field is encrypted and can only be searched by exact match. Please enter the exact value you are looking for."); - if(isset($encryptedAttributes)){ + if (isset($encryptedAttributes)) { if (in_array($attributeName, $encryptedAttributes)) { return ' '; } } - } } diff --git a/application/models/Label.php b/application/models/Label.php index 2d88ba9a60d..3e8b4743719 100644 --- a/application/models/Label.php +++ b/application/models/Label.php @@ -1,4 +1,6 @@ -true), - array('code', 'unique', 'caseSensitive'=>true, 'criteria'=>array( - 'condition'=>'lid = :lid', - 'params'=>array(':lid'=>$this->lid) + array('lid', 'numerical', 'integerOnly' => true), + array('code', 'unique', 'caseSensitive' => true, 'criteria' => array( + 'condition' => 'lid = :lid', + 'params' => array(':lid' => $this->lid) ), - 'message'=>'{attribute} "{value}" is already in use.'), - array('sortorder', 'numerical', 'integerOnly'=>true, 'allowEmpty'=>true), - array('assessment_value', 'numerical', 'integerOnly'=>true, 'allowEmpty'=>true), + 'message' => '{attribute} "{value}" is already in use.'), + array('sortorder', 'numerical', 'integerOnly' => true, 'allowEmpty' => true), + array('assessment_value', 'numerical', 'integerOnly' => true, 'allowEmpty' => true), ); } @@ -82,11 +84,12 @@ public function relations() ); } - public function getTranslated($sLanguage) { + public function getTranslated($sLanguage) + { $ol10N = $this->labell10ns; - if(isset($ol10N[$sLanguage])) { + if (isset($ol10N[$sLanguage])) { return array_merge($this->attributes, $ol10N[$sLanguage]->attributes); - } + } return []; } @@ -106,11 +109,10 @@ public function getLabelCodeInfo($lid) */ public function insertRecords($data) { - $lbls = new self; + $lbls = new self(); foreach ($data as $k => $v) { $lbls->$k = $v; } $lbls->save(); } - } diff --git a/application/models/LabelL10n.php b/application/models/LabelL10n.php index d70bfa81a3f..d6f3dd65518 100644 --- a/application/models/LabelL10n.php +++ b/application/models/LabelL10n.php @@ -1,4 +1,6 @@ -true), + array('label_id', 'numerical', 'integerOnly' => true), array('title', 'LSYii_Validators'), - array('language', 'length', 'min' => 2, 'max'=>20), // in array languages ? + array('language', 'length', 'min' => 2, 'max' => 20), // in array languages ? ); } @@ -75,7 +77,6 @@ public function relations() public function defaultScope() { - return array('index'=>'language'); - } - + return array('index' => 'language'); + } } diff --git a/application/models/LabelSet.php b/application/models/LabelSet.php index 168c7cb24d5..d2e926d3937 100644 --- a/application/models/LabelSet.php +++ b/application/models/LabelSet.php @@ -1,4 +1,6 @@ - 1, 'max'=>100), + array('label_name', 'length', 'min' => 1, 'max' => 100), array('label_name', 'LSYii_Validators'), array('languages', 'required'), - array('languages', 'LSYii_Validators', 'isLanguageMulti'=>true), + array('languages', 'LSYii_Validators', 'isLanguageMulti' => true), ); } @@ -65,7 +67,7 @@ public function relations() // NOTE: you may need to adjust the relation name and the related // class name for the relations automatically generated below. return array( - 'labels' => array(self::HAS_MANY, 'Label', 'lid', 'order'=>'sortorder ASC') + 'labels' => array(self::HAS_MANY, 'Label', 'lid', 'order' => 'sortorder ASC') ); } @@ -104,7 +106,7 @@ public function deleteLabelSet($id) */ public function insertRecords($data) { - $lblset = new self; + $lblset = new self(); foreach ($data as $k => $v) { $lblset->$k = $v; } @@ -114,7 +116,8 @@ public function insertRecords($data) return false; } - public function getLanguageArray() { + public function getLanguageArray() + { return explode(' ', $this->languages); } @@ -126,32 +129,32 @@ public function getbuttons() // View labelset $url = Yii::app()->createUrl("admin/labels/sa/view/lid/$this->lid"); - $button = ''; + $button = ''; // Edit labelset - if (Permission::model()->hasGlobalPermission('labelsets', 'update')) { - $url = Yii::app()->createUrl("admin/labels/sa/editlabelset/lid/$this->lid"); - $button .= ' '; - } + if (Permission::model()->hasGlobalPermission('labelsets', 'update')) { + $url = Yii::app()->createUrl("admin/labels/sa/editlabelset/lid/$this->lid"); + $button .= ' '; + } // Export labelset - if (Permission::model()->hasGlobalPermission('labelsets', 'export')) { - $url = Yii::app()->createUrl("admin/export/sa/dumplabel/lid/$this->lid"); - $button .= ' '; - } + if (Permission::model()->hasGlobalPermission('labelsets', 'export')) { + $url = Yii::app()->createUrl("admin/export/sa/dumplabel/lid/$this->lid"); + $button .= ' '; + } // Delete labelset - if (Permission::model()->hasGlobalPermission('labelsets', 'delete')) { - $button .= '" - .' + if (Permission::model()->hasGlobalPermission('labelsets', 'delete')) { + $button .= '" + . ' '; - } - return $button; } + return $button; + } public function search() { @@ -159,24 +162,24 @@ public function search() $sort = new CSort(); $sort->attributes = array( - 'labelset_id'=>array( - 'asc'=>'lid', - 'desc'=>'lid desc', + 'labelset_id' => array( + 'asc' => 'lid', + 'desc' => 'lid desc', ), - 'name'=>array( - 'asc'=>'label_name', - 'desc'=>'label_name desc', + 'name' => array( + 'asc' => 'label_name', + 'desc' => 'label_name desc', ), - 'languages'=>array( - 'asc'=>'languages', - 'desc'=>'languages desc', + 'languages' => array( + 'asc' => 'languages', + 'desc' => 'languages desc', ), ); $dataProvider = new CActiveDataProvider('LabelSet', array( - 'sort'=>$sort, - 'pagination'=>array( - 'pageSize'=>$pageSize, + 'sort' => $sort, + 'pagination' => array( + 'pageSize' => $pageSize, ), )); diff --git a/application/models/MapTutorialUsers.php b/application/models/MapTutorialUsers.php index 536e678af2f..87207e282e8 100644 --- a/application/models/MapTutorialUsers.php +++ b/application/models/MapTutorialUsers.php @@ -27,10 +27,10 @@ public function rules() // will receive user inputs. return array( array('tid', 'required'), - array('tid, uid, taken', 'numerical', 'integerOnly'=>true), + array('tid, uid, taken', 'numerical', 'integerOnly' => true), // The following rule is used by search(). // @todo Please remove those attributes that should not be searched. - array('tid, uid, taken', 'safe', 'on'=>'search'), + array('tid, uid, taken', 'safe', 'on' => 'search'), ); } @@ -73,14 +73,14 @@ public function search() { // @todo Please modify the following code to remove attributes that should not be searched. - $criteria = new CDbCriteria; + $criteria = new CDbCriteria(); $criteria->compare('tid', $this->tid); $criteria->compare('uid', $this->uid); $criteria->compare('taken', $this->taken); return new CActiveDataProvider($this, array( - 'criteria'=>$criteria, + 'criteria' => $criteria, )); } diff --git a/application/models/Notification.php b/application/models/Notification.php index 1f3c5c48e5c..0b577092549 100644 --- a/application/models/Notification.php +++ b/application/models/Notification.php @@ -49,7 +49,7 @@ public function __construct($options = null) // Only allow 'survey' or 'user' as entity if ($options['entity'] != 'survey' && $options['entity'] != 'user') { - throw new InvalidArgumentException('Invalid entity: '.$options['entity']); + throw new InvalidArgumentException('Invalid entity: ' . $options['entity']); } // Default to 'default' display class @@ -64,7 +64,7 @@ public function __construct($options = null) // importance must be between 1 and 3 if ($options['importance'] < 1 && $options['importance'] > 3) { - throw new InvalidArgumentException('Invalid importance: '.$options['importance']); + throw new InvalidArgumentException('Invalid importance: ' . $options['importance']); } // Set everything up @@ -110,7 +110,7 @@ protected function checkMandatoryFields(array $options, array $mandatory) { foreach ($mandatory as $mand) { if (!isset($options[$mand]) || $options[$mand] == '') { - throw new InvalidArgumentException('Field '.$mand.' is mandatory for notification'); + throw new InvalidArgumentException('Field ' . $mand . ' is mandatory for notification'); } } } @@ -133,13 +133,13 @@ public function rules() // NOTE: you should only define rules for those attributes that // will receive user inputs. return array( - array('entity_id', 'numerical', 'integerOnly'=>true), - array('entity', 'length', 'max'=>64), - array('title', 'length', 'max'=>255), + array('entity_id', 'numerical', 'integerOnly' => true), + array('entity', 'length', 'max' => 64), + array('title', 'length', 'max' => 255), array('message, created, first_read', 'safe'), // The following rule is used by search(). // @todo Please remove those attributes that should not be searched. - array('id, entity, entity_id, message, importance, created, first_read, status, title', 'safe', 'on'=>'search'), + array('id, entity, entity_id, message, importance, created, first_read, status, title', 'safe', 'on' => 'search'), ); } @@ -173,7 +173,7 @@ public function search() { // @todo Please modify the following code to remove attributes that should not be searched. - $criteria = new CDbCriteria; + $criteria = new CDbCriteria(); $criteria->compare('id', $this->id); $criteria->compare('entity', $this->entity, true); @@ -186,7 +186,7 @@ public function search() $criteria->compare('title', $this->title, true); return new CActiveDataProvider($this, array( - 'criteria'=>$criteria, + 'criteria' => $criteria, )); } @@ -286,7 +286,7 @@ public static function getImportantNotifications($surveyId) // TODO this should be in Survey model (relations?) $criteria = self::getCriteria($surveyId); $criteria2 = new CDbCriteria(); - $criteria2->addCondition('importance = '.self::HIGH_IMPORTANCE); + $criteria2->addCondition('importance = ' . self::HIGH_IMPORTANCE); $criteria->mergeWith($criteria2, 'AND'); return self::model()->findAll($criteria); @@ -331,7 +331,7 @@ public static function countImportantNotifications($surveyId) { $criteria = self::getCriteria($surveyId); $criteria2 = new CDbCriteria(); - $criteria2->addCondition('importance = '.self::HIGH_IMPORTANCE); + $criteria2->addCondition('importance = ' . self::HIGH_IMPORTANCE); $criteria->mergeWith($criteria2, 'AND'); return self::model()->count($criteria); diff --git a/application/models/Participant.php b/application/models/Participant.php index 21c47da254c..e15f94d6869 100755 --- a/application/models/Participant.php +++ b/application/models/Participant.php @@ -18,7 +18,9 @@ * Used to spit out error messages if mapping attributes doesn't work. */ class CPDBException extends Exception -{ } +{ + +} /** * This is the model class for table "{{participants}}". @@ -237,15 +239,15 @@ public function getCheckbox() public function attributeLabels() { $returnArray = array( - 'participant_id' => gT('Participant'). $this->setEncryptedAttributeLabel(0 ,'Participant','participant_id'), - 'firstname' => gT('First name'). $this->setEncryptedAttributeLabel(0 ,'Participant','firstname'), - 'lastname' => gT('Last name').$this->setEncryptedAttributeLabel(0 ,'Participant','lastname'), - 'email' => gT('Email address').$this->setEncryptedAttributeLabel(0 ,'Participant','email'), - 'language' => gT('Language').$this->setEncryptedAttributeLabel(0 ,'Participant','language'), - 'blacklisted' => gT('Blacklisted').$this->setEncryptedAttributeLabel(0 ,'Participant','blacklisted'), - 'owner_uid' => gT('Owner ID').$this->setEncryptedAttributeLabel(0 ,'Participant','owner_uid'), - 'surveyid' => gT('Active survey ID').$this->setEncryptedAttributeLabel(0 ,'Participant','surveyid'), - 'created' => gT('Created on').$this->setEncryptedAttributeLabel(0 ,'Participant', 'created') + 'participant_id' => gT('Participant') . $this->setEncryptedAttributeLabel(0, 'Participant', 'participant_id'), + 'firstname' => gT('First name') . $this->setEncryptedAttributeLabel(0, 'Participant', 'firstname'), + 'lastname' => gT('Last name') . $this->setEncryptedAttributeLabel(0, 'Participant', 'lastname'), + 'email' => gT('Email address') . $this->setEncryptedAttributeLabel(0, 'Participant', 'email'), + 'language' => gT('Language') . $this->setEncryptedAttributeLabel(0, 'Participant', 'language'), + 'blacklisted' => gT('Blacklisted') . $this->setEncryptedAttributeLabel(0, 'Participant', 'blacklisted'), + 'owner_uid' => gT('Owner ID') . $this->setEncryptedAttributeLabel(0, 'Participant', 'owner_uid'), + 'surveyid' => gT('Active survey ID') . $this->setEncryptedAttributeLabel(0, 'Participant', 'surveyid'), + 'created' => gT('Created on') . $this->setEncryptedAttributeLabel(0, 'Participant', 'created') ); foreach ($this->allExtraAttributes as $name => $attribute) { $returnArray[$name] = $attribute['defaultname']; @@ -260,7 +262,7 @@ public function getAllExtraAttributes() { $allAttributes = ParticipantAttributeName::model()->getAllAttributes(); $extraAttributes = array(); - foreach ($allAttributes as $attribute) { + foreach ($allAttributes as $attribute) { $extraAttributes["ea_" . $attribute['attribute_id']] = $attribute; } return $extraAttributes; @@ -421,7 +423,7 @@ public function getColumns() $col_array["filter"] = TbHtml::textField("extraAttribute[" . $name . "]", $extraAttributeParams[$name]); } //dropdown - else if ($attribute['attribute_type'] == "DD") { + elseif ($attribute['attribute_type'] == "DD") { $options_raw = $this->getOptionsForAttribute($attribute['attribute_id']); $options_array = array( '' => '' @@ -433,7 +435,7 @@ public function getColumns() $col_array["filter"] = TbHtml::dropDownList("extraAttribute[" . $name . "]", $extraAttributeParams[$name], $options_array); } //date -> still a text field, too many errors with the gridview - else if ($attribute['attribute_type'] == "DP") { + elseif ($attribute['attribute_type'] == "DP") { $col_array["filter"] = TbHtml::textField("extraAttribute[" . $name . "]", $extraAttributeParams[$name]); } $cols[] = $col_array; @@ -446,7 +448,7 @@ public function getColumns() */ public function search() { - $sort = new CSort; + $sort = new CSort(); $sort->defaultOrder = 'lastname'; $sortAttributes = array( 'lastname' => array( @@ -483,8 +485,8 @@ public function search() ) ); - $criteria = new CDbCriteria; - $criteria->join = 'LEFT JOIN {{users}} as owner on uid=owner_uid LEFT JOIN {{participant_shares}} AS shares ON t.participant_id = shares.participant_id AND (shares.share_uid = '.Yii::app()->user->id.' OR shares.share_uid = -1)'; + $criteria = new CDbCriteria(); + $criteria->join = 'LEFT JOIN {{users}} as owner on uid=owner_uid LEFT JOIN {{participant_shares}} AS shares ON t.participant_id = shares.participant_id AND (shares.share_uid = ' . Yii::app()->user->id . ' OR shares.share_uid = -1)'; $criteria->compare('t.participant_id', $this->participant_id, true, 'AND', true); $criteria->compare('t.firstname', $this->firstname, true, 'AND', true); $criteria->compare('t.lastname', $this->lastname, true, 'AND', true); @@ -526,7 +528,7 @@ public function search() } else { /** @var string Param name to bind in prepared statement */ $bindKey = ':value' . $attributeId; - $callParticipantAttributes->where("attribute_id = '" . $attributeId . "' AND value = " . $bindKey , array($bindKey => $value)); + $callParticipantAttributes->where("attribute_id = '" . $attributeId . "' AND value = " . $bindKey, array($bindKey => $value)); // NB: Binding in andWhere() is not enough since the subquery is converted to string. $criteria->params[$bindKey] = $value; } @@ -624,7 +626,7 @@ public static function gen_uuid() */ public function insertParticipant($aData) { - $oParticipant = new self; + $oParticipant = new self(); foreach ($aData as $sField => $sValue) { $oParticipant->$sField = $sValue; } @@ -1122,7 +1124,7 @@ public function getParticipantsSearchMultiple($condition, $page, $limit) // $i = 0; $start = $limit * $page - $limit; - $command = new CDbCriteria; + $command = new CDbCriteria(); $command->condition = ''; //The following code performs an IN-SQL order, but this only works for standard participant fields @@ -1211,7 +1213,7 @@ public function getParticipantsSearchMultiple($condition, $page, $limit) $i += 3; } //This section deals with subsequent filter conditions that have boolean joiner - else if ($condition[$i] != '') { + elseif ($condition[$i] != '') { if (is_numeric($condition[$i + 3])) { $condition[$i + 3] = intval($condition[$i + 3]); } @@ -1318,7 +1320,7 @@ public function getParticipantsSearchMultipleCondition($condition) //As we iterate through the conditions we build up the $command query by adding conditions to it // $i = 0; - $command = new CDbCriteria; + $command = new CDbCriteria(); $command->condition = ''; $aParams = array(); @@ -1757,7 +1759,7 @@ private function writeParticipantsToTokenTable( $insertedtokenid = $oToken->tid; //Create a survey link for the new token entry - $oSurveyLink = new SurveyLink; + $oSurveyLink = new SurveyLink(); $oSurveyLink->participant_id = $oParticipant->participant_id; $oSurveyLink->token_id = $insertedtokenid; $oSurveyLink->survey_id = $surveyId; @@ -2175,13 +2177,13 @@ public function userHasPermissionToEdit() if (Permission::model()->hasGlobalPermission('superadmin') || (Permission::model()->hasGlobalPermission('participantpanel', 'update'))) { // Superadmins can do anything and users with global edit permission can to edit all participants return true; - } else if ($shared && $shared->share_uid == -1 && $shared->can_edit) { + } elseif ($shared && $shared->share_uid == -1 && $shared->can_edit) { // -1 = shared with everyone return true; - } else if ($shared && $shared->exists('share_uid = :userid', [':userid' => $userId]) && $shared->can_edit) { + } elseif ($shared && $shared->exists('share_uid = :userid', [':userid' => $userId]) && $shared->can_edit) { // Shared with this particular user return true; - } else if ($owner) { + } elseif ($owner) { // User owns this participant return true; } else { @@ -2237,7 +2239,7 @@ public function getLanguageOptions() } public function getOwnerOptions() { - return CHtml::listData(User::model()->findAll(),'uid','full_name'); + return CHtml::listData(User::model()->findAll(), 'uid', 'full_name'); } /** diff --git a/application/models/ParticipantAttribute.php b/application/models/ParticipantAttribute.php index b4587737485..d0edce5ecdf 100644 --- a/application/models/ParticipantAttribute.php +++ b/application/models/ParticipantAttribute.php @@ -1,4 +1,6 @@ - array(self::HAS_ONE, 'Participant', 'participant_id'), - 'participant_attribute_name'=>array(self::BELONGS_TO, 'ParticipantAttributeName', 'attribute_id') + 'participant_attribute_name' => array(self::BELONGS_TO, 'ParticipantAttributeName', 'attribute_id') ); } @@ -89,7 +91,7 @@ public function updateParticipantAttributeValue($data) ->queryScalar(); if ($result > 0) { Yii::app()->db->createCommand() - ->update('{{participant_attribute}}', $data, "participant_id = '".$data['participant_id']."' AND attribute_id = ".$data['attribute_id']); + ->update('{{participant_attribute}}', $data, "participant_id = '" . $data['participant_id'] . "' AND attribute_id = " . $data['attribute_id']); } else { Yii::app()->db->createCommand() ->insert('{{participant_attribute}}', $data); @@ -100,7 +102,8 @@ public function updateParticipantAttributeValue($data) * Get current surveyId for other model/function * @return int */ - public function getSurveyId() { + public function getSurveyId() + { return 0; } } diff --git a/application/models/ParticipantAttributeName.php b/application/models/ParticipantAttributeName.php index db496e7eaa2..8ace91bb644 100644 --- a/application/models/ParticipantAttributeName.php +++ b/application/models/ParticipantAttributeName.php @@ -1,4 +1,5 @@ 'strip_tags'), array('attribute_type, visible, encrypted, core_attribute', 'required'), - array('attribute_type', 'length', 'max'=>4), - array('visible, encrypted, core_attribute', 'length', 'max'=>5), + array('attribute_type', 'length', 'max' => 4), + array('visible, encrypted, core_attribute', 'length', 'max' => 5), // The following rule is used by search(). // Please remove those attributes that should not be searched. - array('attribute_id, attribute_type, visible, encrypted, core_attribute', 'safe', 'on'=>'search'), + array('attribute_id, attribute_type, visible, encrypted, core_attribute', 'safe', 'on' => 'search'), ); } @@ -73,8 +74,8 @@ public function relations() // NOTE: you may need to adjust the relation name and the related // class name for the relations automatically generated below. return array( - 'participant_attribute_names_lang'=>array(self::HAS_MANY, 'ParticipantAttributeNameLang', 'attribute_id'), - 'participant_attribute'=>array(self::HAS_ONE, 'ParticipantAttribute', 'attribute_id') + 'participant_attribute_names_lang' => array(self::HAS_MANY, 'ParticipantAttributeNameLang', 'attribute_id'), + 'participant_attribute' => array(self::HAS_ONE, 'ParticipantAttribute', 'attribute_id') ); } @@ -99,7 +100,7 @@ public function attributeLabels() public function getButtons() { // don't show action buttons for core attributes - if ($this->core_attribute == 'Y'){ + if ($this->core_attribute == 'Y') { return ''; } $raw_button_template = "" @@ -124,7 +125,7 @@ public function getButtons() gT("Delete this attribute"), 'trash text-danger' ); - $buttons .= "" + $buttons .= "" . vsprintf($raw_button_template, $deleteData) . ""; @@ -137,12 +138,12 @@ public function getButtons() public function getMassiveActionCheckbox() { // don't show checkbox for core attributes - if ($this->core_attribute == 'Y'){ + if ($this->core_attribute == 'Y') { // BugFix: 317(op), whithout this hidden inputfields, massive action 'delete' is not working correctly // as we have only that special case in cpdb at the moment, it's not necessary to change it in the frontend part (listAction.js line 27) - return ""; + return ""; } - return ""; + return ""; } /** @@ -177,7 +178,7 @@ public function getNamePlusLanguageName() $names[] = $name['attribute_name']; } $defaultname = $this->defaultname; - $returnName = $defaultname." (".join(', ', $names).")"; + $returnName = $defaultname . " (" . join(', ', $names) . ")"; return $returnName; } @@ -186,7 +187,7 @@ public function getNamePlusLanguageName() */ public function getVisibleSwitch() { - $inputHtml = "visible . "' data-on-color='primary' data-off-color='warning' data-off-text='" . gT('No') . "' data-on-text='" . gT('Yes') . "' class='action_changeAttributeVisibility' " . ($this->visible == "TRUE" ? "checked" : "") . ($this->core_attribute == "Y" ? " disabled" : "") . "/>"; @@ -201,7 +202,7 @@ public function getEncryptedSwitch() // load sodium library $sodium = Yii::app()->sodium; $bEncrypted = $sodium->bLibraryExists; - $inputHtml = "encrypted == "Y" ? "checked" : "") + $inputHtml = "encrypted == "Y" ? "checked" : "") . "/>"; return $inputHtml; } @@ -211,7 +212,7 @@ public function getEncryptedSwitch() */ public function getCoreAttributeSwitch() { - $inputHtml = "encrypted . "' data-on-color='primary' data-off-color='warning' data-off-text='" . gT('No') . "' data-on-text='" . gT('Yes') . "' class='action_changeAttributeEncrypted' " . ($this->core_attribute == "Y" ? "checked" : "") . " disabled" . "/>"; @@ -260,7 +261,7 @@ public function getColumns() "value" => '$data->getEncryptedSwitch()', "type" => "raw", "filter" => array("Y" => gT("Yes"), "N" => gT("No")), - "header" => '' . gT("Encrypted"). '', + "header" => '' . gT("Encrypted") . '', ), array( "name" => 'core_attribute', @@ -281,7 +282,7 @@ public function search() // Warning: Please modify the following code to remove attributes that // should not be searched. - $criteria = new CDbCriteria; + $criteria = new CDbCriteria(); $criteria->compare('defaultname', $this->defaultname, true, 'AND', true); $criteria->compare('attribute_id', $this->attribute_id); @@ -296,7 +297,7 @@ public function search() $pageSize = Yii::app()->user->getState('pageSizeAttributes', Yii::app()->params['defaultPageSize']); return new CActiveDataProvider($this, array( - 'criteria'=>$criteria, + 'criteria' => $criteria, 'sort' => $sort, 'pagination' => array( 'pageSize' => $pageSize @@ -336,7 +337,6 @@ public function getVisibleAttributes($sLanguageFilter = null) $ids = ParticipantAttributeName::model()->findAll("visible = 'TRUE' and core_attribute <> 'Y'"); //Then find a language for each one - the current $lang, if possible, english second, otherwise, the first in the list foreach ($ids as $id) { - $langs = ParticipantAttributeNameLang::model()->findAll( "attribute_id = :attribute_id", array( @@ -392,7 +392,7 @@ public function getParticipantVisibleAttribute($participant_id) $findCriteria = new CDbCriteria(); $findCriteria->addCondition('participant_id = :participant_id'); $findCriteria->addCondition("core_attribute <> 'Y'"); - $findCriteria->params = array(':participant_id'=>$participant_id); + $findCriteria->params = array(':participant_id' => $participant_id); $records = ParticipantAttributeName::model()->with('participant_attribute_names_lang', 'participant_attribute') ->findAll($findCriteria); foreach ($records as $row) { @@ -401,19 +401,24 @@ public function getParticipantVisibleAttribute($participant_id) $thislang = ""; foreach ($row->participant_attribute_names_lang as $names) { //Iterate through each language version of this attribute - if ($thisname == "") {$thisname = $names->attribute_name; $thislang = $names->lang; } //Choose the first item by default - if ($names->lang == Yii::app()->session['adminlang']) {$thisname = $names->attribute_name; $thislang = $names->lang; } //Override the default with the admin language version if found + if ($thisname == "") { + $thisname = $names->attribute_name; + $thislang = $names->lang; + } //Choose the first item by default + if ($names->lang == Yii::app()->session['adminlang']) { + $thisname = $names->attribute_name; + $thislang = $names->lang; + } //Override the default with the admin language version if found } - $output[] = array('participant_id'=>$row->participant_attribute->participant_id, - 'attribute_id'=>$row->attribute_id, - 'attribute_type'=>$row->attribute_type, - 'attribute_display'=>$row->visible, - 'attribute_name'=>$thisname, - 'value'=>$row->participant_attribute->value, - 'lang'=>$thislang); + $output[] = array('participant_id' => $row->participant_attribute->participant_id, + 'attribute_id' => $row->attribute_id, + 'attribute_type' => $row->attribute_type, + 'attribute_display' => $row->visible, + 'attribute_name' => $thisname, + 'value' => $row->participant_attribute->value, + 'lang' => $thislang); } return $output; - } else { $findCriteria = new CDbCriteria(); $records = ParticipantAttributeName::model()->with('participant_attribute_names_lang', 'participant_attribute')->findAll($findCriteria); @@ -423,16 +428,22 @@ public function getParticipantVisibleAttribute($participant_id) $thislang = ""; foreach ($row->participant_attribute_names_lang as $names) { //Iterate through each language version of this attribute - if ($thisname == "") {$thisname = $names->attribute_name; $thislang = $names->lang; } //Choose the first item by default - if ($names->lang == Yii::app()->session['adminlang']) {$thisname = $names->attribute_name; $thislang = $names->lang; } //Override the default with the admin language version if found + if ($thisname == "") { + $thisname = $names->attribute_name; + $thislang = $names->lang; + } //Choose the first item by default + if ($names->lang == Yii::app()->session['adminlang']) { + $thisname = $names->attribute_name; + $thislang = $names->lang; + } //Override the default with the admin language version if found } - $output[] = array('participant_id'=>$row->participant_attribute->participant_id, - 'attribute_id'=>$row->attribute_id, - 'attribute_type'=>$row->attribute_type, - 'attribute_display'=>$row->visible, - 'attribute_name'=>$thisname, - 'value'=>$row->participant_attribute->value, - 'lang'=>$thislang); + $output[] = array('participant_id' => $row->participant_attribute->participant_id, + 'attribute_id' => $row->attribute_id, + 'attribute_type' => $row->attribute_type, + 'attribute_display' => $row->visible, + 'attribute_name' => $thisname, + 'value' => $row->participant_attribute->value, + 'lang' => $thislang); } return $output; } @@ -444,7 +455,7 @@ public function getAttributeValue($participantid, $attributeid) ->select('*') ->from('{{participant_attribute}}') ->where('participant_id = :participant_id AND attribute_id = :attribute_id AND core_Attribute <> "Y"') - ->bindValues(array(':participant_id'=>$participantid, ':attribute_id'=>$attributeid)) + ->bindValues(array(':participant_id' => $participantid, ':attribute_id' => $attributeid)) ->queryRow(); return $data; } @@ -471,7 +482,7 @@ function getCPDBAttributes() //Iterate through each attribute to get language and language value foreach ($models as $row) { $thisname = ''; - $thislang =''; + $thislang = ''; foreach ($row->participant_attribute_names_lang as $names) { //Iterate through each language version of this attribute if ($thisname == "") { @@ -485,11 +496,11 @@ function getCPDBAttributes() } $output[] = array( - 'attribute_id'=>$row->attribute_id, - 'attribute_type'=>$row->attribute_type, - 'attribute_display'=>$row->visible, - 'attribute_name'=>$thisname, - 'lang'=>$thislang + 'attribute_id' => $row->attribute_id, + 'attribute_type' => $row->attribute_type, + 'attribute_display' => $row->visible, + 'attribute_name' => $thisname, + 'lang' => $thislang ); } @@ -540,17 +551,22 @@ public function getNotAddedAttributes($attributeIds) $thislang = ""; foreach ($row->participant_attribute_names_lang as $names) { //Iterate through each language version of this attribute - if ($thisname == "") {$thisname = $names->attribute_name; $thislang = $names->lang; } //Choose the first item by default - if ($names->lang == Yii::app()->session['adminlang']) {$thisname = $names->attribute_name; $thislang = $names->lang; } //Override the default with the admin language version if found + if ($thisname == "") { + $thisname = $names->attribute_name; + $thislang = $names->lang; + } //Choose the first item by default + if ($names->lang == Yii::app()->session['adminlang']) { + $thisname = $names->attribute_name; + $thislang = $names->lang; + } //Override the default with the admin language version if found } - $output[] = array('attribute_id'=>$row->attribute_id, - 'attribute_type'=>$row->attribute_type, - 'attribute_display'=>$row->visible, - 'attribute_name'=>$thisname, - 'lang'=>$thislang); + $output[] = array('attribute_id' => $row->attribute_id, + 'attribute_type' => $row->attribute_type, + 'attribute_display' => $row->visible, + 'attribute_name' => $thisname, + 'lang' => $thislang); } return $output; - } /** @@ -565,7 +581,7 @@ public function storeAttribute($data) if (ParticipantAttributeName::model()->count() > 59) { return false; }; - $oParticipantAttributeName = new ParticipantAttributeName; + $oParticipantAttributeName = new ParticipantAttributeName(); $oParticipantAttributeName->attribute_type = $data['attribute_type']; $oParticipantAttributeName->defaultname = $data['defaultname']; $oParticipantAttributeName->visible = $data['visible']; @@ -573,7 +589,7 @@ public function storeAttribute($data) $oParticipantAttributeName->core_attribute = $data['core_attribute']; $oParticipantAttributeName->save(); $iAttributeID = $oParticipantAttributeName->attribute_id; - $oParticipantAttributeNameLang = new ParticipantAttributeNameLang; + $oParticipantAttributeNameLang = new ParticipantAttributeNameLang(); $oParticipantAttributeNameLang->attribute_id = intval($iAttributeID); $oParticipantAttributeNameLang->attribute_name = $data['attribute_name']; $oParticipantAttributeNameLang->lang = Yii::app()->session['adminlang']; @@ -584,22 +600,24 @@ public function storeAttribute($data) public function editParticipantAttributeValue($data) { $query = ParticipantAttribute::model() - ->find('participant_id = :participant_id AND attribute_id=:attribute_id', - array(':participant_id'=>$data['participant_id'], - ':attribute_id'=>$data['attribute_id']) - ); + ->find( + 'participant_id = :participant_id AND attribute_id=:attribute_id', + array(':participant_id' => $data['participant_id'], + ':attribute_id' => $data['attribute_id']) + ); if (count($query) == 0) { Yii::app()->db->createCommand() ->insert('{{participant_attribute}}', $data); } else { Yii::app()->db->createCommand() - ->update('{{participant_attribute}}', + ->update( + '{{participant_attribute}}', $data, 'participant_id = :participant_id2 AND attribute_id = :attribute_id2', - array(':participant_id2' => $data['participant_id'], ':attribute_id2'=>$data['attribute_id'])); + array(':participant_id2' => $data['participant_id'], ':attribute_id2' => $data['attribute_id']) + ); } - } /** @@ -612,7 +630,7 @@ public function delAttribute($attid) // first check if $attid is core attribute // if not attribute could be deleted $participantAttributeName = ParticipantAttributeName::model()->findByPk((int) $attid); - if($participantAttributeName->core_attribute !== 'Y') { + if ($participantAttributeName->core_attribute !== 'Y') { Yii::app()->db->createCommand()->delete('{{participant_attribute_names_lang}}', 'attribute_id = ' . $attid); Yii::app()->db->createCommand()->delete('{{participant_attribute_names}}', 'attribute_id = ' . $attid); Yii::app()->db->createCommand()->delete('{{participant_attribute_values}}', 'attribute_id = ' . $attid); @@ -628,7 +646,7 @@ public function delAttributeValues($attid, $valid) { Yii::app()->db ->createCommand() - ->delete('{{participant_attribute_values}}', 'attribute_id = '.$attid.' AND value_id = '.$valid); + ->delete('{{participant_attribute_values}}', 'attribute_id = ' . $attid . ' AND value_id = ' . $valid); } /** @@ -673,7 +691,7 @@ public function getAttribute($attribute_id) $data = Yii::app()->db->createCommand() ->select('*') ->from('{{participant_attribute_names}}') - ->where('{{participant_attribute_names}}.attribute_id = '.$attribute_id) + ->where('{{participant_attribute_names}}.attribute_id = ' . $attribute_id) ->queryRow(); return $data; } @@ -705,14 +723,14 @@ function saveAttribute($data) } if (!empty($insertnames)) { $oParticipantAttributeName = ParticipantAttributeName::model()->findByPk($data['attribute_id']); - foreach ($insertnames as $sFieldname=>$sValue) { + foreach ($insertnames as $sFieldname => $sValue) { $oParticipantAttributeName->$sFieldname = $sValue; } $oParticipantAttributeName->save(); $test = $oParticipantAttributeName->getErrors(); } if (!empty($data['attribute_name'])) { - $oParticipantAttributeNameLang = ParticipantAttributeNameLang::model()->findByPk(array('attribute_id'=>$data['attribute_id'], 'lang'=>Yii::app()->session['adminlang'])); + $oParticipantAttributeNameLang = ParticipantAttributeNameLang::model()->findByPk(array('attribute_id' => $data['attribute_id'], 'lang' => Yii::app()->session['adminlang'])); $oParticipantAttributeNameLang->attribute_name = $data['attribute_name']; $oParticipantAttributeNameLang->save(); } @@ -735,7 +753,7 @@ public function saveAttributeLanguages($data) if (count($query) == 0) { // A record does not exist, insert one. - $oParticipantAttributeNameLang = new ParticipantAttributeNameLang; + $oParticipantAttributeNameLang = new ParticipantAttributeNameLang(); $oParticipantAttributeNameLang->attribute_id = $data['attribute_id']; $oParticipantAttributeNameLang->attribute_name = $data['attribute_name']; $oParticipantAttributeNameLang->lang = $data['lang']; @@ -771,7 +789,7 @@ public function storeAttributeValue($data) public function clearAttributeValues() { $deleteCommand = Yii::app()->db->createCommand(); - $deleteCommand->delete('{{participant_attribute_values}}', 'attribute_id=:attribute_id', array('attribute_id'=>$this->attribute_id)); + $deleteCommand->delete('{{participant_attribute_values}}', 'attribute_id=:attribute_id', array('attribute_id' => $this->attribute_id)); } /** @@ -780,7 +798,7 @@ public function clearAttributeValues() */ public function storeAttributeCSV($data) { - $oParticipantAttributeName = new ParticipantAttributeName; + $oParticipantAttributeName = new ParticipantAttributeName(); $oParticipantAttributeName->attribute_type = $data['attribute_type']; $oParticipantAttributeName->defaultname = $data['defaultname']; $oParticipantAttributeName->visible = $data['visible']; @@ -790,7 +808,7 @@ public function storeAttributeCSV($data) $iAttributeID = $oParticipantAttributeName->getPrimaryKey(); - $oParticipantAttributeNameLang = new ParticipantAttributeNameLang; + $oParticipantAttributeNameLang = new ParticipantAttributeNameLang(); $oParticipantAttributeNameLang->attribute_id = $iAttributeID; $oParticipantAttributeNameLang->attribute_name = $data['defaultname']; $oParticipantAttributeNameLang->lang = Yii::app()->session['adminlang']; @@ -818,9 +836,9 @@ public function saveAttributeVisible($attid, $visiblecondition) { $attribute_id = explode("_", $attid); - $data = array('visible'=>$visiblecondition); + $data = array('visible' => $visiblecondition); if ($visiblecondition == "") { - $data = array('visible'=>'FALSE'); + $data = array('visible' => 'FALSE'); } Yii::app()->db->createCommand()->update('{{participant_attribute_names}}', $data, 'attribute_id = :attribute_id') ->bindParam(":attribute_id", $attribute_id[1], PDO::PARAM_INT); @@ -834,9 +852,9 @@ public function saveAttributeEncrypted($attid, $encryptedcondition) { $attribute_id = explode("_", $attid); - $data = array('encrypted'=>$encryptedcondition); + $data = array('encrypted' => $encryptedcondition); if ($encryptedcondition == "") { - $data = array('encrypted'=>'FALSE'); + $data = array('encrypted' => 'FALSE'); } Yii::app()->db->createCommand()->update('{{participant_attribute_names}}', $data, 'attribute_id = :attribute_id') ->bindParam(":attribute_id", $attribute_id[1], PDO::PARAM_INT); diff --git a/application/models/ParticipantAttributeNameLang.php b/application/models/ParticipantAttributeNameLang.php index e4156ed7e95..1da94c791d1 100644 --- a/application/models/ParticipantAttributeNameLang.php +++ b/application/models/ParticipantAttributeNameLang.php @@ -1,4 +1,5 @@ 'strip_tags'), // The following rule is used by search(). // Please remove those attributes that should not be searched. - array('attribute_id, attribute_name, lang', 'safe', 'on'=>'search'), + array('attribute_id, attribute_name, lang', 'safe', 'on' => 'search'), ); } @@ -65,8 +66,7 @@ public function relations() // NOTE: you may need to adjust the relation name and the related // class name for the relations automatically generated below. return array( - 'participant_attribute_name'=>array(self::BELONGS_TO, 'ParticipantAttributeName', 'attribute_id') + 'participant_attribute_name' => array(self::BELONGS_TO, 'ParticipantAttributeName', 'attribute_id') ); } - } diff --git a/application/models/ParticipantShare.php b/application/models/ParticipantShare.php index 2aa1716d4a5..64763daa60b 100644 --- a/application/models/ParticipantShare.php +++ b/application/models/ParticipantShare.php @@ -1,4 +1,5 @@ true), - array('participant_id', 'length', 'max'=>50), - array('can_edit', 'length', 'max'=>5), + array('share_uid', 'numerical', 'integerOnly' => true), + array('participant_id', 'length', 'max' => 50), + array('can_edit', 'length', 'max' => 5), // The following rule is used by search(). // Please remove those attributes that should not be searched. - array('participant_id, participant.firstname, participant.lastname, participant.email, share_uid, date_added, can_edit', 'safe', 'on'=>'search'), + array('participant_id, participant.firstname, participant.lastname, participant.email, share_uid, date_added, can_edit', 'safe', 'on' => 'search'), ); } @@ -75,7 +76,7 @@ public function relations() 'participant' => array(self::HAS_ONE, 'Participant', array('participant_id' => 'participant_id')), 'shared_by' => array(self::HAS_ONE, 'User', array('uid' => 'share_uid')), 'surveylinks' => array(self::HAS_ONE, 'SurveyLink', 'participant_id'), - 'participantAttributes' => array(self::HAS_MANY, 'ParticipantAttribute', 'participant_id', 'with'=>'participant_attribute_names', 'joinType'=> 'LEFT JOIN') + 'participantAttributes' => array(self::HAS_MANY, 'ParticipantAttribute', 'participant_id', 'with' => 'participant_attribute_names', 'joinType' => 'LEFT JOIN') ); } @@ -136,7 +137,7 @@ public function getCanEditHtml() { $loggedInUser = yii::app()->user->getId(); if ($this->participant->owner_uid == $loggedInUser) { - $inputHtml = "can_edit ? "checked" : "") . "/>"; return $inputHtml; @@ -155,7 +156,6 @@ public function getButtons() $isOwner = $this->participant->owner_uid == $userId; $isSuperAdmin = Permission::model()->hasGlobalPermission('superadmin', 'read'); if ($isOwner || $isSuperAdmin) { - $url = Yii::app()->createUrl( 'admin/participants/sa/deleteSingleParticipantShare', array( @@ -164,7 +164,7 @@ public function getButtons() ) ); - return "" + return "" . "" . ""; } else { @@ -184,10 +184,10 @@ public function getCheckbox() $isSuperAdmin = Permission::model()->hasGlobalPermission('superadmin', 'read'); // Primary key for ParticipantShare - $participantIdAndShareUid = $this->participant_id.','.$this->share_uid; + $participantIdAndShareUid = $this->participant_id . ',' . $this->share_uid; if ($isOwner || $isSuperAdmin) { - $html = ""; + $html = ""; } else { $html = ''; } @@ -249,12 +249,11 @@ public function getColumns() "name" => 'can_edit', "value" => '$data->getCanEditHtml()', "header" => gT("Can edit?"), - "filter" => array(1 => gT('Yes'), 0=> gT('No')), - "type" =>"raw" + "filter" => array(1 => gT('Yes'), 0 => gT('No')), + "type" => "raw" ), ); return $cols; - } /** * Retrieves a list of models based on the current search/filter conditions. @@ -264,31 +263,31 @@ public function search() { // Warning: Please modify the following code to remove attributes that // should not be searched. - $sort = new CSort; + $sort = new CSort(); $sortAttributes = array( - 'participant.firstname'=>array( - 'asc'=>'participant.firstname asc', - 'desc'=>'participant.firstname desc', + 'participant.firstname' => array( + 'asc' => 'participant.firstname asc', + 'desc' => 'participant.firstname desc', ), - 'participant.lastname'=>array( - 'asc'=>'participant.lastname asc', - 'desc'=>'participant.lastname desc', + 'participant.lastname' => array( + 'asc' => 'participant.lastname asc', + 'desc' => 'participant.lastname desc', ), - 'participant.email'=>array( - 'asc'=>'participant.email asc', - 'desc'=>'participant.email desc', + 'participant.email' => array( + 'asc' => 'participant.email asc', + 'desc' => 'participant.email desc', ), - 'share_uid'=>array( - 'asc'=>'shared_by.full_name asc', - 'desc'=>'shared_by.full_name desc', + 'share_uid' => array( + 'asc' => 'shared_by.full_name asc', + 'desc' => 'shared_by.full_name desc', ), - 'date_added'=>array( - 'asc'=>'date_added asc', - 'desc'=>'date_added desc', + 'date_added' => array( + 'asc' => 'date_added asc', + 'desc' => 'date_added desc', ), - 'can_edit'=>array( - 'asc'=>'can_edit asc', - 'desc'=>'can_edit desc', + 'can_edit' => array( + 'asc' => 'can_edit asc', + 'desc' => 'can_edit desc', ), ); $sort->attributes = $sortAttributes; @@ -296,7 +295,7 @@ public function search() $participantFilter = Yii::app()->request->getPost('Participant'); - $criteria = new CDbCriteria; + $criteria = new CDbCriteria(); $criteria->with = array('participant', 'shared_by'); // This condition is necessary to filter out participants that got deleted, but the share entry is not @@ -311,7 +310,7 @@ public function search() $pageSize = Yii::app()->user->getState('pageSizeShareParticipantView', Yii::app()->params['defaultPageSize']); return new LSCActiveDataProvider($this, array( - 'criteria'=>$criteria, + 'criteria' => $criteria, 'sort' => $sort, 'pagination' => array( 'pageSize' => $pageSize @@ -328,8 +327,8 @@ public function search() */ public function storeParticipantShare($data, $permission) { - $hasUpdatePermission = isset($permission['hasUpdatePermission'])? $permission['hasUpdatePermission'] : false; - $isSuperAdmin = isset($permission['isSuperAdmin'])? $permission['isSuperAdmin'] : false; + $hasUpdatePermission = isset($permission['hasUpdatePermission']) ? $permission['hasUpdatePermission'] : false; + $isSuperAdmin = isset($permission['isSuperAdmin']) ? $permission['isSuperAdmin'] : false; $userId = App()->user->getId(); $ownerid = App()->db->createCommand()->select('*')->from('{{participants}}')->where('participant_id = :participant_id')->bindParam(":participant_id", $data['participant_id'], PDO::PARAM_STR)->queryRow(); @@ -358,9 +357,9 @@ public function updateShare($data) { if (strpos($data['participant_id'], '--') !== false) { list($participantId, $shareuid) = explode("--", $data['participant_id']); - $data = array("participant_id"=>$participantId, "share_uid"=>$shareuid, "can_edit"=>$data['can_edit']); + $data = array("participant_id" => $participantId, "share_uid" => $shareuid, "can_edit" => $data['can_edit']); } - $criteria = new CDbCriteria; + $criteria = new CDbCriteria(); $criteria->addCondition("participant_id = '{$data['participant_id']}'"); $criteria->addCondition("share_uid = '{$data['share_uid']}' "); ParticipantShare::model()->updateAll($data, $criteria); @@ -413,5 +412,4 @@ public function canEditSharedParticipant($participent_id) } return false; } - } diff --git a/application/models/Permission.php b/application/models/Permission.php index fae5a66c82c..59ee27b7ef3 100644 --- a/application/models/Permission.php +++ b/application/models/Permission.php @@ -1,4 +1,6 @@ -50), - array('permission', 'length', 'max'=>100), - array('create_p, read_p, update_p, delete_p, import_p, export_p', 'default', 'value'=>0), - array('create_p, read_p, update_p, delete_p, import_p, export_p', 'numerical', 'integerOnly'=>true), + array('entity', 'length', 'max' => 50), + array('permission', 'length', 'max' => 100), + array('create_p, read_p, update_p, delete_p, import_p, export_p', 'default', 'value' => 0), + array('create_p, read_p, update_p, delete_p, import_p, export_p', 'numerical', 'integerOnly' => true), ); } @@ -122,7 +124,7 @@ public static function getEntityMinimalPermissionRead($sEntityName) /** * Returns the global permissions including description and title * - * @return array of array of permission + * @return array of array of permission */ public static function getGlobalBasePermissions() { @@ -208,7 +210,7 @@ public static function getPermissions($iUserID, $iEntityID = null, $sEntityName } return $aBasePermissions; } - if($sEntityName == 'global') { + if ($sEntityName == 'global') { $aBasePermissions = Permission::model()->getGlobalBasePermissions(); } else { $aBasePermissions = Permission::model()->getEntityBasePermissions($sEntityName); @@ -222,22 +224,22 @@ public static function getPermissions($iUserID, $iEntityID = null, $sEntityName 'permission' => $sPermission )); if ($aPermissionDetail['create']) { - $aPermissionDetail['create'] = ($oCurrentPermissions ? (boolean) $oCurrentPermissions->create_p : false); + $aPermissionDetail['create'] = ($oCurrentPermissions ? (bool) $oCurrentPermissions->create_p : false); } if ($aPermissionDetail['read']) { - $aPermissionDetail['read'] = ($oCurrentPermissions ? (boolean) $oCurrentPermissions->read_p : false); + $aPermissionDetail['read'] = ($oCurrentPermissions ? (bool) $oCurrentPermissions->read_p : false); } if ($aPermissionDetail['update']) { - $aPermissionDetail['update'] = ($oCurrentPermissions ? (boolean) $oCurrentPermissions->update_p : false); + $aPermissionDetail['update'] = ($oCurrentPermissions ? (bool) $oCurrentPermissions->update_p : false); } if ($aPermissionDetail['delete']) { - $aPermissionDetail['delete'] = ($oCurrentPermissions ? (boolean) $oCurrentPermissions->delete_p : false); + $aPermissionDetail['delete'] = ($oCurrentPermissions ? (bool) $oCurrentPermissions->delete_p : false); } if ($aPermissionDetail['import']) { - $aPermissionDetail['import'] = ($oCurrentPermissions ? (boolean) $oCurrentPermissions->import_p : false); + $aPermissionDetail['import'] = ($oCurrentPermissions ? (bool) $oCurrentPermissions->import_p : false); } if ($aPermissionDetail['export']) { - $aPermissionDetail['export'] = ($oCurrentPermissions ? (boolean) $oCurrentPermissions->export_p : false); + $aPermissionDetail['export'] = ($oCurrentPermissions ? (bool) $oCurrentPermissions->export_p : false); } } return $aBasePermissions; @@ -340,15 +342,14 @@ public static function setPermissions($iUserID, $iEntityID, $sEntityName, $aPerm 'import_p' => (int) $aPermission['import'], 'export_p' => (int) $aPermission['export'], ); - $permission = new self; + $permission = new self(); foreach ($data as $k => $v) { $permission->$k = $v; } $permission->save(); } - } - if($sEntityName != 'global') { + if ($sEntityName != 'global') { self::setMinimalEntityPermission($iUserID, $iEntityID, $sEntityName); } return true; @@ -365,7 +366,7 @@ public static function setPermissions($iUserID, $iEntityID, $sEntityName, $aPerm public static function setMinimalEntityPermission($iUserID, $iEntityID, $sEntityName) { $sPermission = self::getEntityMinimalPermissionRead($sEntityName); - if(!$sPermission) { + if (!$sPermission) { return null; } $oPermission = Permission::model()->find( @@ -377,8 +378,8 @@ public static function setMinimalEntityPermission($iUserID, $iEntityID, $sEntity 'permission' => $sPermission, ) ); - if(empty($oPermission)) { - $oPermission = new Permission; + if (empty($oPermission)) { + $oPermission = new Permission(); $oPermission->uid = $iUserID; $oPermission->entity = $sEntityName; $oPermission->entity_id = $iEntityID; @@ -441,15 +442,15 @@ public function giveAllSurveyPermissions($iUserID, $iSurveyID) 'permission' => $sPermissionName )); if (empty($oPermission)) { - $oPermission = new Permission; + $oPermission = new Permission(); $oPermission->entity = 'survey'; $oPermission->entity_id = $iSurveyID; $oPermission->uid = $iUserID; $oPermission->permission = $sPermissionName; } - foreach($aCrud as $crud) { - if(!isset($aPermissionDetails[$crud]) || $aPermissionDetails[$crud]) { - $oPermission->setAttribute($crud."_p", 1); + foreach ($aCrud as $crud) { + if (!isset($aPermissionDetails[$crud]) || $aPermissionDetails[$crud]) { + $oPermission->setAttribute($crud . "_p", 1); } } $oPermission->save(); @@ -473,7 +474,7 @@ public function insertRecords($data) */ public function insertSomeRecords($data) { - $permission = new self; + $permission = new self(); foreach ($data as $k => $v) { $permission->$k = $v; } @@ -607,9 +608,9 @@ public function hasPermission($iEntityID, $sEntityName, $sPermission, $sCRUD = ' /* Find the roles the user is part of and return those permissions */ /* roles are only for global permission */ // @TODO add surveypermission to roles - if($sEntityName == 'global') { + if ($sEntityName == 'global') { $aRoles = self::getUserRole($iUserID); - if (safecount($aRoles) > 0 ) { + if (safecount($aRoles) > 0) { $allowed = false; foreach ($aRoles as $role) { $allowed = $allowed || $this->hasRolePermission($role['ptid'], $sPermission, substr($sCRUD, 0, -2)); @@ -674,7 +675,7 @@ public function hasSurveyPermission($iSurveyID, $sPermission, $sCRUD = 'read', $ if (!$oSurvey) { return false; } - return $oSurvey->hasPermission($sPermission, $sCRUD , $iUserID); + return $oSurvey->hasPermission($sPermission, $sCRUD, $iUserID); } /** @@ -758,7 +759,7 @@ protected function getEntityOwnerId($iEntityID, $sEntityName) if (empty($oEntity)) { return null; } - if(!method_exists($oEntity,'getOwnerId')) { + if (!method_exists($oEntity, 'getOwnerId')) { return null; } return $oEntity->getOwnerId(); @@ -864,12 +865,13 @@ public static function getPermissionGradeList() * @param $aTemplatePermissions array -- permissions to be set * @return array */ - public static function editThemePermissionsUser($userId, $aTemplatePermissions){ + public static function editThemePermissionsUser($userId, $aTemplatePermissions) + { $results = []; foreach ($aTemplatePermissions as $key => $value) { $oPermission = Permission::model()->findByAttributes(array('permission' => $key, 'uid' => $userId, 'entity' => 'template')); if (empty($oPermission)) { - $oPermission = new Permission; + $oPermission = new Permission(); $oPermission->uid = $userId; $oPermission->permission = $key; $oPermission->entity = 'template'; diff --git a/application/models/Permissiontemplates.php b/application/models/Permissiontemplates.php index 30cd6025152..12e69805a31 100644 --- a/application/models/Permissiontemplates.php +++ b/application/models/Permissiontemplates.php @@ -13,41 +13,41 @@ */ class Permissiontemplates extends CActiveRecord { - /** - * @return string the associated database table name - */ - public function tableName() - { - return '{{permissiontemplates}}'; - } - - /** - * @return array validation rules for model attributes. - */ - public function rules() - { - // NOTE: you should only define rules for those attributes that - // will receive user inputs. - return array( - array('name, description, renewed_last, created_at, created_by', 'required'), - array('created_by', 'numerical', 'integerOnly'=>true), - array('name', 'length', 'max'=>192), - // The following rule is used by search(). - // @todo Please remove those attributes that should not be searched. - array('ptid, name, description, renewed_last, created_at, created_by', 'safe', 'on'=>'search'), - ); - } - - /** - * @return array relational rules. - */ - public function relations() - { - // NOTE: you may need to adjust the relation name and the related - // class name for the relations automatically generated below. - return array( + /** + * @return string the associated database table name + */ + public function tableName() + { + return '{{permissiontemplates}}'; + } + + /** + * @return array validation rules for model attributes. + */ + public function rules() + { + // NOTE: you should only define rules for those attributes that + // will receive user inputs. + return array( + array('name, description, renewed_last, created_at, created_by', 'required'), + array('created_by', 'numerical', 'integerOnly' => true), + array('name', 'length', 'max' => 192), + // The following rule is used by search(). + // @todo Please remove those attributes that should not be searched. + array('ptid, name, description, renewed_last, created_at, created_by', 'safe', 'on' => 'search'), + ); + } + + /** + * @return array relational rules. + */ + public function relations() + { + // NOTE: you may need to adjust the relation name and the related + // class name for the relations automatically generated below. + return array( 'connectedusers' => array(self::HAS_MANY, 'UserInPermissionrole', ['ptid']), - ); + ); } /** @@ -55,19 +55,20 @@ public function relations() * * @return array filled with usermodels */ - public function getConnectedUserobjects() + public function getConnectedUserobjects() { return array_map( function ($oMappingInstance) { return User::model()->findByPk($oMappingInstance->uid); - }, + }, $this->connectedusers ); } - public function applyToUser($iUserId, $ptid = null) { + public function applyToUser($iUserId, $ptid = null) + { - if($ptid == null) { + if ($ptid == null) { $ptid = $this->ptid; } @@ -82,7 +83,8 @@ public function applyToUser($iUserId, $ptid = null) { return $oModel->save(); } - public function clearUser($iUserId) { + public function clearUser($iUserId) + { $aModels = UserInPermissionrole::model()->findAllByAttributes(['uid' => $iUserId]); if (safecount($aModels) == 0) { @@ -90,9 +92,9 @@ public function clearUser($iUserId) { } return array_reduce( - $aModels, - function ($cur, $oModel) { - return $cur && $oModel->delete(); + $aModels, + function ($cur, $oModel) { + return $cur && $oModel->delete(); }, true ); @@ -134,42 +136,42 @@ public function getButtons() $roleDetail = "" - .""; + data-href='" . $detailUrl . "'>"; $editPermissionButton = "" - .""; + data-href='" . $setPermissionsUrl . "'>"; $editRoleButton = "" - .""; + data-href='" . $editUrl . "'>"; $exportRoleButton = "" - .""; + . ""; $deleteRoleButton = "" - .""; - return join("\n",[ - $roleDetail, - $editPermissionButton, - $editRoleButton, - $exportRoleButton, + return join("\n", [ + $roleDetail, + $editPermissionButton, + $editRoleButton, + $exportRoleButton, $deleteRoleButton ]); } @@ -210,7 +212,7 @@ public function getColumns() "value" => '$data->formattedDateModified' ), array( - "name" =>"created_at", + "name" => "created_at", "header" => gT("Created on"), "value" => '$data->formattedDateCreated', @@ -220,13 +222,14 @@ public function getColumns() return $cols; } - public function compileExportXML () { + public function compileExportXML() + { $xml = new SimpleXMLElement(''); //Meta section $meta = $xml->addChild('meta'); - $meta->addChild('name', 'name.']]>'); - $meta->addChild('description', 'description.']]>'); + $meta->addChild('name', 'name . ']]>'); + $meta->addChild('description', 'description . ']]>'); $meta->addChild('date', date('Y-m-d H:i:s')); $meta->addChild('createdOn', Yii::app()->getConfig('sitename')); $meta->addChild('createdBy', Yii::app()->user->id); @@ -237,12 +240,12 @@ public function compileExportXML () { //Permission section $permission = $xml->addChild('permissions'); - foreach($aBasePermissions as $sPermissionKey=>$aCRUDPermissions) { + foreach ($aBasePermissions as $sPermissionKey => $aCRUDPermissions) { $curKeyRow = $permission->addChild($sPermissionKey); - foreach ($aCRUDPermissions as $sCRUDKey=>$CRUDValue) { + foreach ($aCRUDPermissions as $sCRUDKey => $CRUDValue) { $curKeyRow->addChild( - $sCRUDKey, - ($this->getHasPermission($sPermissionKey, $sCRUDKey) ? 1 : 0) + $sCRUDKey, + ($this->getHasPermission($sPermissionKey, $sCRUDKey) ? 1 : 0) ); } } @@ -250,7 +253,8 @@ public function compileExportXML () { return $xml; } - public function createFromXML ($xmlEntitiy, $includeRootData = false) { + public function createFromXML($xmlEntitiy, $includeRootData = false) + { $name = $this->removeCdataFormat($xmlEntitiy->meta->name); $iExisiting = self::model()->countByAttributes(['name' => $name]); if ($iExisiting > 0) { @@ -283,29 +287,30 @@ public function removeCdataFormat($node) $regex_patterns = array( '//' - ); - return trim(preg_replace($regex_patterns, $regex_replace, $nodeText)); + ); + return trim(preg_replace($regex_patterns, $regex_replace, $nodeText)); } - public function getHasPermission($sPermission, $sCRUD) { + public function getHasPermission($sPermission, $sCRUD) + { return Permission::model()->hasRolePermission($this->ptid, $sPermission, $sCRUD); } - /** - * Retrieves a list of models based on the current search/filter conditions. - * - * Typical usecase: - * - Initialize the model fields with values from filter form. - * - Execute this method to get CActiveDataProvider instance which will filter - * models according to data in model fields. - * - Pass data provider to CGridView, CListView or any similar widget. - * - * @return CActiveDataProvider the data provider that can return the models - * based on the search/filter conditions. - */ + /** + * Retrieves a list of models based on the current search/filter conditions. + * + * Typical usecase: + * - Initialize the model fields with values from filter form. + * - Execute this method to get CActiveDataProvider instance which will filter + * models according to data in model fields. + * - Pass data provider to CGridView, CListView or any similar widget. + * + * @return CActiveDataProvider the data provider that can return the models + * based on the search/filter conditions. + */ public function search() { - $criteria = new CDbCriteria; + $criteria = new CDbCriteria(); $criteria->compare('ptid', $this->ptid); $criteria->compare('name', $this->name, true); @@ -322,14 +327,14 @@ public function search() )); } - /** - * Returns the static model of the specified AR class. - * Please note that you should have this exact method in all your CActiveRecord descendants! - * @param string $className active record class name. - * @return Permissiontemplates the static model class - */ - public static function model($className=__CLASS__) - { - return parent::model($className); - } + /** + * Returns the static model of the specified AR class. + * Please note that you should have this exact method in all your CActiveRecord descendants! + * @param string $className active record class name. + * @return Permissiontemplates the static model class + */ + public static function model($className = __CLASS__) + { + return parent::model($className); + } } diff --git a/application/models/Plugin.php b/application/models/Plugin.php index dcdb6a115ad..35d97e4bb48 100644 --- a/application/models/Plugin.php +++ b/application/models/Plugin.php @@ -156,8 +156,8 @@ public function getName() */ public function getActionButtons() { - $output=''; - if (Permission::model()->hasGlobalPermission('settings','update')) { + $output = ''; + if (Permission::model()->hasGlobalPermission('settings', 'update')) { if ($this->load_error == 1) { $reloadUrl = Yii::app()->createUrl( 'admin/pluginmanager', @@ -166,7 +166,7 @@ public function getActionButtons() 'pluginId' => $this->id ] ); - $output = ""; + $output = ""; } elseif ($this->active == 0) { $output = $this->getActivateButton(); } else { diff --git a/application/models/PluginDynamic.php b/application/models/PluginDynamic.php index a04afe30561..8770e79d307 100644 --- a/application/models/PluginDynamic.php +++ b/application/models/PluginDynamic.php @@ -74,7 +74,5 @@ public function getMetaData() $md = self::model($this->tableName())->_md; return $this->_md = $md; } - } - } diff --git a/application/models/PluginSetting.php b/application/models/PluginSetting.php index 0b291ddbc0d..5ff7ff1f87d 100644 --- a/application/models/PluginSetting.php +++ b/application/models/PluginSetting.php @@ -56,10 +56,10 @@ public function tableName() public function rules() { return array( - array('plugin_id', 'numerical', 'integerOnly'=>true), // 'allowEmpty'=>false ? - array('model', 'length', 'max'=>255, 'allowEmpty'=>true), - array('model_id', 'numerical', 'integerOnly'=>true, 'allowEmpty'=>true), - array('key', 'length', 'max'=>255), + array('plugin_id', 'numerical', 'integerOnly' => true), // 'allowEmpty'=>false ? + array('model', 'length', 'max' => 255, 'allowEmpty' => true), + array('model_id', 'numerical', 'integerOnly' => true, 'allowEmpty' => true), + array('key', 'length', 'max' => 255), ); } } diff --git a/application/models/Question.php b/application/models/Question.php index 6b5689f56ed..a620d304d46 100644 --- a/application/models/Question.php +++ b/application/models/Question.php @@ -1,4 +1,5 @@ array(self::HAS_ONE, 'Question', array("qid" => "parent_qid")), 'questionattributes' => array(self::HAS_MANY, 'QuestionAttribute', 'qid'), 'questionl10ns' => array(self::HAS_MANY, 'QuestionL10n', 'qid', 'together' => true), - 'subquestions' => array(self::HAS_MANY, 'Question', array('parent_qid'=>'qid'), 'order'=> App()->getDb()->quoteColumnName('subquestions.question_order').' ASC'), + 'subquestions' => array(self::HAS_MANY, 'Question', array('parent_qid' => 'qid'), 'order' => App()->getDb()->quoteColumnName('subquestions.question_order') . ' ASC'), 'conditions' => array(self::HAS_MANY, 'Condition', 'qid'), - 'answers' => array(self::HAS_MANY, 'Answer', 'qid', 'order'=> App()->getDb()->quoteColumnName('answers.sortorder').' ASC'), + 'answers' => array(self::HAS_MANY, 'Answer', 'qid', 'order' => App()->getDb()->quoteColumnName('answers.sortorder') . ' ASC'), ); } @@ -133,24 +134,24 @@ public function relations() public function rules() { $aRules = array( - array('title', 'required', 'on' => 'update, insert', 'message'=>gT('The question code is mandatory.', 'unescaped')), - array('title', 'length', 'min' => 1, 'max'=>20, 'on' => 'update, insert'), - array('qid,sid,gid,parent_qid', 'numerical', 'integerOnly'=>true), - array('qid', 'unique','message'=>sprintf(gT("Question id (qid) : '%s' is already in use."), $this->qid)),// Still needed ? - array('other', 'in', 'range'=>array('Y', 'N'), 'allowEmpty'=>true), - array('mandatory', 'in', 'range'=>array('Y', 'S', 'N'), 'allowEmpty'=>true), - array('encrypted', 'in', 'range'=>array('Y', 'N'), 'allowEmpty'=>true), - array('question_order', 'numerical', 'integerOnly'=>true, 'allowEmpty'=>true), - array('scale_id', 'numerical', 'integerOnly'=>true, 'allowEmpty'=>true), - array('same_default', 'numerical', 'integerOnly'=>true, 'allowEmpty'=>true), - array('type', 'length', 'min' => 1, 'max'=>1), + array('title', 'required', 'on' => 'update, insert', 'message' => gT('The question code is mandatory.', 'unescaped')), + array('title', 'length', 'min' => 1, 'max' => 20, 'on' => 'update, insert'), + array('qid,sid,gid,parent_qid', 'numerical', 'integerOnly' => true), + array('qid', 'unique','message' => sprintf(gT("Question id (qid) : '%s' is already in use."), $this->qid)),// Still needed ? + array('other', 'in', 'range' => array('Y', 'N'), 'allowEmpty' => true), + array('mandatory', 'in', 'range' => array('Y', 'S', 'N'), 'allowEmpty' => true), + array('encrypted', 'in', 'range' => array('Y', 'N'), 'allowEmpty' => true), + array('question_order', 'numerical', 'integerOnly' => true, 'allowEmpty' => true), + array('scale_id', 'numerical', 'integerOnly' => true, 'allowEmpty' => true), + array('same_default', 'numerical', 'integerOnly' => true, 'allowEmpty' => true), + array('type', 'length', 'min' => 1, 'max' => 1), array('preg,relevance', 'safe'), - array('modulename', 'length', 'max'=>255), + array('modulename', 'length', 'max' => 255), ); // Always enforce unicity on Sub question code (DB issue). if ($this->parent_qid) { - $aRules[] = array('title', 'unique', 'caseSensitive'=>false, - 'criteria'=>array( + $aRules[] = array('title', 'unique', 'caseSensitive' => false, + 'criteria' => array( 'condition' => 'sid=:sid AND parent_qid=:parent_qid and scale_id=:scale_id', 'params' => array( ':sid' => $this->sid, @@ -161,23 +162,23 @@ public function rules() 'message' => gT('Subquestion codes must be unique.') ); // Disallow other title if question allow other - $oParentQuestion = Question::model()->findByPk(array("qid"=>$this->parent_qid)); + $oParentQuestion = Question::model()->findByPk(array("qid" => $this->parent_qid)); if ($oParentQuestion->other == "Y") { - $aRules[] = array('title', 'LSYii_CompareInsensitiveValidator', 'compareValue'=>'other', 'operator'=>'!=', 'message'=> sprintf(gT("'%s' can not be used if the 'Other' option for this question is activated."), "other"), 'except' => 'archiveimport'); + $aRules[] = array('title', 'LSYii_CompareInsensitiveValidator', 'compareValue' => 'other', 'operator' => '!=', 'message' => sprintf(gT("'%s' can not be used if the 'Other' option for this question is activated."), "other"), 'except' => 'archiveimport'); } // #14495: comment suffix can't be used with P Question (collapse with table name in database) if ($oParentQuestion->type == "P") { - $aRules[] = array('title', 'match', 'pattern'=>'/comment$/', 'not'=>true, 'message'=> gT("'comment' suffix can not be used with multiple choice with comments.")); + $aRules[] = array('title', 'match', 'pattern' => '/comment$/', 'not' => true, 'message' => gT("'comment' suffix can not be used with multiple choice with comments.")); } } else { // Disallow other if sub question have 'other' for title - $oSubquestionOther = Question::model()->find("parent_qid=:parent_qid and LOWER(title)='other'", array("parent_qid"=>$this->qid)); + $oSubquestionOther = Question::model()->find("parent_qid=:parent_qid and LOWER(title)='other'", array("parent_qid" => $this->qid)); if ($oSubquestionOther) { - $aRules[] = array('other', 'compare', 'compareValue'=>'Y', 'operator'=>'!=', 'message'=> sprintf(gT("'%s' can not be used if the 'Other' option for this question is activated."), 'other'), 'except' => 'archiveimport'); + $aRules[] = array('other', 'compare', 'compareValue' => 'Y', 'operator' => '!=', 'message' => sprintf(gT("'%s' can not be used if the 'Other' option for this question is activated."), 'other'), 'except' => 'archiveimport'); } } if (!$this->isNewRecord) { - $oActualValue = Question::model()->findByPk(array("qid"=>$this->qid)); + $oActualValue = Question::model()->findByPk(array("qid" => $this->qid)); if ($oActualValue && $oActualValue->title == $this->title) { /* We don't change title, then don't put rules on title */ /* We don't want to broke existing survey, We only disallow to set it or update it according to this value */ @@ -187,8 +188,8 @@ public function rules() /* Question was new or title was updated : we add minor rules. This rules don't broke DB, only potential “ExpressionScript Engine” issue. */ if (!$this->parent_qid) { // 0 or empty /* Unicity for ExpressionManager */ - $aRules[] = array('title', 'unique', 'caseSensitive'=>true, - 'criteria'=>array( + $aRules[] = array('title', 'unique', 'caseSensitive' => true, + 'criteria' => array( 'condition' => 'sid=:sid AND parent_qid=0', 'params' => array( ':sid' => $this->sid @@ -210,12 +211,12 @@ public function rules() 'QID','GID','SGQ', // current question related var 'self','that','this', // EM reserved variables ), - 'message'=> sprintf(gT("Code: '%s' is a reserved word."), $this->title), // Usage of {attribute} need attributeLabels, {value} never exist in message + 'message' => sprintf(gT("Code: '%s' is a reserved word."), $this->title), // Usage of {attribute} need attributeLabels, {value} never exist in message 'except' => 'archiveimport' ); } else { - $aRules[] = array('title', 'compare', 'compareValue'=>'time', 'operator'=>'!=', - 'message'=> gT("'time' is a reserved word and can not be used for a subquestion."), + $aRules[] = array('title', 'compare', 'compareValue' => 'time', 'operator' => '!=', + 'message' => gT("'time' is a reserved word and can not be used for a subquestion."), 'except' => 'archiveimport'); $aRules[] = array('title', 'match', 'pattern' => '/^[[:alnum:]]*$/', 'message' => gT('Subquestion codes may only contain alphanumeric characters.'), @@ -238,8 +239,8 @@ public function rules() public static function updateSortOrder($gid, $surveyid) { $questions = self::model()->findAllByAttributes( - array('gid' => $gid, 'sid' => $surveyid, 'parent_qid'=>0), - array('order'=>'question_order') + array('gid' => $gid, 'sid' => $surveyid, 'parent_qid' => 0), + array('order' => 'question_order') ); $p = 0; foreach ($questions as $question) { @@ -271,7 +272,7 @@ public function updateQuestionOrder($gid, $startingOrder = 1) Yii::app()->db->createCommand()->update( $this->tableName(), array('question_order' => $position), - 'qid='.$row['qid'] + 'qid=' . $row['qid'] ); $position++; } @@ -444,7 +445,7 @@ public function delete() // delete defaultvalues and defaultvalueL10ns $oDefaultValues = DefaultValue::model()->findAll((new CDbCriteria())->addInCondition('qid', $ids)); - foreach($oDefaultValues as $defaultvalue){ + foreach ($oDefaultValues as $defaultvalue) { DefaultValue::model()->deleteAll('dvid = :dvid', array(':dvid' => $defaultvalue->dvid)); DefaultValueL10n::model()->deleteAll('dvid = :dvid', array(':dvid' => $defaultvalue->dvid)); } @@ -485,7 +486,7 @@ public function deleteAllSubquestions() QuestionL10n::model()->deleteAll($qidsCriteria); QuotaMember::model()->deleteAll($qidsCriteria); $defaultValues = DefaultValue::model()->findAll((new CDbCriteria())->addInCondition('qid', $ids)); - foreach($defaultValues as $defaultValue){ + foreach ($defaultValues as $defaultValue) { DefaultValue::model()->deleteAll('dvid = :dvid', array(':dvid' => $defaultValue->dvid)); DefaultValueL10n::model()->deleteAll('dvid = :dvid', array(':dvid' => $defaultValue->dvid)); } @@ -522,14 +523,13 @@ public function deleteAllAnswers() */ public function getQuestionsForStatistics($fields, $condition, $orderby = false) { - if ($orderby === false){ + if ($orderby === false) { $oQuestions = Question::model()->with('questionl10ns')->findAll(array('condition' => $condition)); } else { $oQuestions = Question::model()->with('questionl10ns')->findAll(array('condition' => $condition, 'order' => $orderby)); } $arr = array(); - foreach($oQuestions as $key => $question) - { + foreach ($oQuestions as $key => $question) { $arr[$key] = array_merge($question->attributes, current($question->questionl10ns)->attributes); } return $arr; @@ -550,7 +550,7 @@ public function getQuestionList($surveyid) ->with('group') ->findAll( array( - 'condition' => 't.sid='.$surveyid, + 'condition' => 't.sid=' . $surveyid, 'order' => $quotedGroup . '.' . $quotedGrouporder . ' DESC, ' . $quotedQuestionorder ) ); @@ -565,7 +565,7 @@ public function getTypedesc() $typeDesc = $types[$this->type]["description"]; if (YII_DEBUG) { - $typeDesc .= ' '.$this->type.''; + $typeDesc .= ' ' . $this->type . ''; } return $typeDesc; @@ -621,37 +621,68 @@ public static function getQuestionTypeName($sType) public static function getQuestionClass($sType) { switch ($sType) { - case Question::QT_1_ARRAY_MULTISCALE: return 'array-flexible-duel-scale'; - case Question::QT_5_POINT_CHOICE: return 'choice-5-pt-radio'; - case Question::QT_A_ARRAY_5_CHOICE_QUESTIONS: return 'array-5-pt'; - case Question::QT_B_ARRAY_10_CHOICE_QUESTIONS: return 'array-10-pt'; - case Question::QT_C_ARRAY_YES_UNCERTAIN_NO: return 'array-yes-uncertain-no'; - case Question::QT_D_DATE: return 'date'; - case Question::QT_E_ARRAY_OF_INC_SAME_DEC_QUESTIONS: return 'array-increase-same-decrease'; - case Question::QT_F_ARRAY_FLEXIBLE_ROW: return 'array-flexible-row'; - case Question::QT_G_GENDER_DROPDOWN: return 'gender'; - case Question::QT_H_ARRAY_FLEXIBLE_COLUMN: return 'array-flexible-column'; - case Question::QT_I_LANGUAGE: return 'language'; - case Question::QT_K_MULTIPLE_NUMERICAL_QUESTION: return 'numeric-multi'; - case Question::QT_L_LIST_DROPDOWN: return 'list-radio'; - case Question::QT_M_MULTIPLE_CHOICE: return 'multiple-opt'; - case Question::QT_N_NUMERICAL: return 'numeric'; - case Question::QT_O_LIST_WITH_COMMENT: return 'list-with-comment'; - case Question::QT_P_MULTIPLE_CHOICE_WITH_COMMENTS: return 'multiple-opt-comments'; - case Question::QT_Q_MULTIPLE_SHORT_TEXT: return 'multiple-short-txt'; - case Question::QT_R_RANKING_STYLE: return 'ranking'; - case Question::QT_S_SHORT_FREE_TEXT: return 'text-short'; - case Question::QT_T_LONG_FREE_TEXT: return 'text-long'; - case Question::QT_U_HUGE_FREE_TEXT: return 'text-huge'; - case Question::QT_X_BOILERPLATE_QUESTION: return 'boilerplate'; - case Question::QT_Y_YES_NO_RADIO: return 'yes-no'; - case Question::QT_Z_LIST_RADIO_FLEXIBLE: return 'list-radio-flexible'; - case Question::QT_EXCLAMATION_LIST_DROPDOWN: return 'list-dropdown'; - case Question::QT_COLON_ARRAY_MULTI_FLEX_NUMBERS: return 'array-multi-flexi'; - case Question::QT_SEMICOLON_ARRAY_MULTI_FLEX_TEXT: return 'array-multi-flexi-text'; - case Question::QT_VERTICAL_FILE_UPLOAD: return 'upload-files'; - case Question::QT_ASTERISK_EQUATION: return 'equation'; - default: return 'generic_question'; // fallback + case Question::QT_1_ARRAY_MULTISCALE: + return 'array-flexible-duel-scale'; + case Question::QT_5_POINT_CHOICE: + return 'choice-5-pt-radio'; + case Question::QT_A_ARRAY_5_CHOICE_QUESTIONS: + return 'array-5-pt'; + case Question::QT_B_ARRAY_10_CHOICE_QUESTIONS: + return 'array-10-pt'; + case Question::QT_C_ARRAY_YES_UNCERTAIN_NO: + return 'array-yes-uncertain-no'; + case Question::QT_D_DATE: + return 'date'; + case Question::QT_E_ARRAY_OF_INC_SAME_DEC_QUESTIONS: + return 'array-increase-same-decrease'; + case Question::QT_F_ARRAY_FLEXIBLE_ROW: + return 'array-flexible-row'; + case Question::QT_G_GENDER_DROPDOWN: + return 'gender'; + case Question::QT_H_ARRAY_FLEXIBLE_COLUMN: + return 'array-flexible-column'; + case Question::QT_I_LANGUAGE: + return 'language'; + case Question::QT_K_MULTIPLE_NUMERICAL_QUESTION: + return 'numeric-multi'; + case Question::QT_L_LIST_DROPDOWN: + return 'list-radio'; + case Question::QT_M_MULTIPLE_CHOICE: + return 'multiple-opt'; + case Question::QT_N_NUMERICAL: + return 'numeric'; + case Question::QT_O_LIST_WITH_COMMENT: + return 'list-with-comment'; + case Question::QT_P_MULTIPLE_CHOICE_WITH_COMMENTS: + return 'multiple-opt-comments'; + case Question::QT_Q_MULTIPLE_SHORT_TEXT: + return 'multiple-short-txt'; + case Question::QT_R_RANKING_STYLE: + return 'ranking'; + case Question::QT_S_SHORT_FREE_TEXT: + return 'text-short'; + case Question::QT_T_LONG_FREE_TEXT: + return 'text-long'; + case Question::QT_U_HUGE_FREE_TEXT: + return 'text-huge'; + case Question::QT_X_BOILERPLATE_QUESTION: + return 'boilerplate'; + case Question::QT_Y_YES_NO_RADIO: + return 'yes-no'; + case Question::QT_Z_LIST_RADIO_FLEXIBLE: + return 'list-radio-flexible'; + case Question::QT_EXCLAMATION_LIST_DROPDOWN: + return 'list-dropdown'; + case Question::QT_COLON_ARRAY_MULTI_FLEX_NUMBERS: + return 'array-multi-flexi'; + case Question::QT_SEMICOLON_ARRAY_MULTI_FLEX_TEXT: + return 'array-multi-flexi-text'; + case Question::QT_VERTICAL_FILE_UPLOAD: + return 'upload-files'; + case Question::QT_ASTERISK_EQUATION: + return 'equation'; + default: + return 'generic_question'; // fallback }; } @@ -660,35 +691,35 @@ public function getbuttons() { $url = App()->createUrl("questionAdministration/view/surveyid/$this->sid/gid/$this->gid/qid/$this->qid"); $previewUrl = Yii::app()->createUrl("survey/index/action/previewquestion/sid/"); - $previewUrl .= '/'.$this->sid.'/gid/'.$this->gid.'/qid/'.$this->qid; + $previewUrl .= '/' . $this->sid . '/gid/' . $this->gid . '/qid/' . $this->qid; $editurl = Yii::app()->createUrl("questionAdministration/view/surveyid/$this->sid/gid/$this->gid/qid/$this->qid"); - $button = ' '; + $button = ' '; if (Permission::model()->hasSurveyPermission($this->sid, 'surveycontent', 'update')) { - $button .= ''; + $button .= ''; } if (Permission::model()->hasSurveyPermission($this->sid, 'surveycontent', 'read')) { - $button .= ''; + $button .= ''; } $oSurvey = Survey::model()->findByPk($this->sid); $gid_search = $this->gid; if ($oSurvey->active != "Y" && Permission::model()->hasSurveyPermission($this->sid, 'surveycontent', 'delete')) { - $button .= '" - .' + . "});'>" + . ' '; } return $button; } - public function getOrderedAnswers($scale_id=null) + public function getOrderedAnswers($scale_id = null) { //reset answers set prior to this call $aAnswerOptions = [ @@ -703,18 +734,18 @@ public function getOrderedAnswers($scale_id=null) } - if($scale_id !== null) { + if ($scale_id !== null) { return $aAnswerOptions[$scale_id]; } // Random order - if ($this->getQuestionAttribute('random_order') == 1 && $this->getQuestionType()->subquestions == 0){ - foreach($aAnswerOptions as $scaleId => $aScaleArray) { + if ($this->getQuestionAttribute('random_order') == 1 && $this->getQuestionType()->subquestions == 0) { + foreach ($aAnswerOptions as $scaleId => $aScaleArray) { $keys = array_keys($aScaleArray); shuffle($keys); // See: https://forum.yiiframework.com/t/order-by-rand-and-total-posts/68099 $aNew = array(); - foreach($keys as $key) { + foreach ($keys as $key) { $aNew[$key] = $aScaleArray[$key]; } $aAnswerOptions[$scaleId] = $aNew; @@ -726,11 +757,11 @@ public function getOrderedAnswers($scale_id=null) // Alphabetic ordrer $alphasort = $this->getQuestionAttribute('alphasort'); if ($alphasort == 1) { - foreach($aAnswerOptions as $scaleId => $aScaleArray) { + foreach ($aAnswerOptions as $scaleId => $aScaleArray) { $aSorted = array(); // We create an aray aSorted that will use the answer in the current language as key, and that will store its old index as value - foreach($aScaleArray as $iKey => $oAnswer){ + foreach ($aScaleArray as $iKey => $oAnswer) { $aSorted[$oAnswer->answerl10ns[$this->survey->language]->answer] = $iKey; } @@ -738,26 +769,23 @@ public function getOrderedAnswers($scale_id=null) // Now, we create a new array that store the old values of $aAnswerOptions in the order of $aSorted $aNew = array(); - foreach($aSorted as $sAnswer => $iKey) { + foreach ($aSorted as $sAnswer => $iKey) { $aNew[] = $aScaleArray[$iKey]; } $aAnswerOptions[$scaleId] = $aNew; - - } return $aAnswerOptions; } - foreach($aAnswerOptions as $scaleId => $aScaleArray) { - usort($aScaleArray, function($a, $b){ + foreach ($aAnswerOptions as $scaleId => $aScaleArray) { + usort($aScaleArray, function ($a, $b) { return $a->sortorder > $b->sortorder - ? 1 + ? 1 : ($a->sortorder < $b->sortorder ? -1 : 0); }); $aAnswerOptions[$scaleId] = $aScaleArray; } return $aAnswerOptions; - } /** @@ -778,13 +806,15 @@ public function getOrderedSubQuestions($scale_id = null) $aOrderedSubquestions = $this->subquestions; if ($this->getQuestionAttribute('random_order') == 1) { - require_once(Yii::app()->basePath.'/libraries/MersenneTwister.php'); + require_once(Yii::app()->basePath . '/libraries/MersenneTwister.php'); ls\mersenne\setSeed($this->sid); $aOrderedSubquestions = ls\mersenne\shuffle($aOrderedSubquestions); } else { usort($aOrderedSubquestions, function ($oQuestionA, $oQuestionB) { - if ($oQuestionA->question_order == $oQuestionB->question_order) { return 0; } + if ($oQuestionA->question_order == $oQuestionB->question_order) { + return 0; + } return $oQuestionA->question_order < $oQuestionB->question_order ? -1 : 1; }); } @@ -801,7 +831,7 @@ public function getOrderedSubQuestions($scale_id = null) ($this->getQuestionAttribute('exclude_all_others') != '' && $this->getQuestionAttribute('random_order') == 1) && ($oSubquestion->title == $this->getQuestionAttribute('exclude_all_others')) ) { - $excludedSubquestionPosition = (safecount($aSubQuestions[$oSubquestion->scale_id])-1); + $excludedSubquestionPosition = (safecount($aSubQuestions[$oSubquestion->scale_id]) - 1); $excludedSubquestion = $oSubquestion; continue; } @@ -809,10 +839,10 @@ public function getOrderedSubQuestions($scale_id = null) } if ($excludedSubquestion != null) { - array_splice($aSubQuestions[$excludedSubquestion->scale_id], ($excludedSubquestion->question_order-1), 0, [$excludedSubquestion]); + array_splice($aSubQuestions[$excludedSubquestion->scale_id], ($excludedSubquestion->question_order - 1), 0, [$excludedSubquestion]); } - if($scale_id !== null) { + if ($scale_id !== null) { return $aSubQuestions[$scale_id]; } @@ -822,15 +852,15 @@ public function getOrderedSubQuestions($scale_id = null) public function getMandatoryIcon() { if ($this->type != Question::QT_X_BOILERPLATE_QUESTION && $this->type != Question::QT_VERTICAL_FILE_UPLOAD) { - if ($this->mandatory == "Y"){ + if ($this->mandatory == "Y") { $sIcon = ''; - } elseif ($this->mandatory == "S"){ + } elseif ($this->mandatory == "S") { $sIcon = ' ' . gT('Soft') . ''; } else { $sIcon = ''; } } else { - $sIcon = ''; + $sIcon = ''; } return $sIcon; } @@ -840,7 +870,7 @@ public function getOtherIcon() if (($this->type == Question::QT_L_LIST_DROPDOWN) || ($this->type == Question::QT_EXCLAMATION_LIST_DROPDOWN) || ($this->type == Question::QT_P_MULTIPLE_CHOICE_WITH_COMMENTS) || ($this->type == Question::QT_M_MULTIPLE_CHOICE)) { $sIcon = ($this->other === "Y") ? '' : ''; } else { - $sIcon = ''; + $sIcon = ''; } return $sIcon; } @@ -859,13 +889,13 @@ public function getNewTitle($index = 0) /* Maybe it's an old invalid title : try to fix it */ $sNewTitle = preg_replace("/[^A-Za-z0-9]/", '', $sOldTitle); if (is_numeric(substr($sNewTitle, 0, 1))) { - $sNewTitle = 'q'.$sNewTitle; + $sNewTitle = 'q' . $sNewTitle; } /* Maybe there are another question with same title try to fix it 10 times */ $attempts = 0; while (!$this->validate(array('title'))) { $rand = mt_rand(0, 1024); - $sNewTitle = 'q'.$index.'r'.$rand; + $sNewTitle = 'q' . $index . 'r' . $rand; $this->title = $sNewTitle; $attempts++; if ($attempts > 10) { @@ -891,51 +921,51 @@ public function getQuestionListColumns() { return array( array( - 'id'=>'id', - 'class'=>'CCheckBoxColumn', + 'id' => 'id', + 'class' => 'CCheckBoxColumn', 'selectableRows' => '100', ), array( 'header' => gT('Question ID'), 'name' => 'question_id', - 'value'=>'$data->qid', + 'value' => '$data->qid', ), array( 'header' => gT("Group / Question order"), 'name' => 'question_order', - 'value'=>'$data->group->group_order ." / ". $data->question_order', + 'value' => '$data->group->group_order ." / ". $data->question_order', ), array( 'header' => gT('Code'), 'name' => 'title', - 'value'=>'$data->title', + 'value' => '$data->title', 'htmlOptions' => array('class' => 'col-md-1'), ), array( 'header' => gT('Question'), 'name' => 'question', - 'value'=> 'array_key_exists($data->survey->language, $data->questionl10ns) ? viewHelper::flatEllipsizeText($data->questionl10ns[$data->survey->language]->question,true,0) : ""', + 'value' => 'array_key_exists($data->survey->language, $data->questionl10ns) ? viewHelper::flatEllipsizeText($data->questionl10ns[$data->survey->language]->question,true,0) : ""', 'htmlOptions' => array('class' => 'col-md-5'), ), array( 'header' => gT('Question type'), 'name' => 'type', - 'type'=>'raw', - 'value'=>'$data->typedesc', + 'type' => 'raw', + 'value' => '$data->typedesc', 'htmlOptions' => array('class' => 'col-md-1'), ), array( 'header' => gT('Group'), 'name' => 'group', - 'value'=> '$data->group->questiongroupl10ns[$data->survey->language]->group_name', + 'value' => '$data->group->questiongroupl10ns[$data->survey->language]->group_name', ), array( 'header' => gT('Mandatory'), 'type' => 'raw', 'name' => 'mandatory', - 'value'=> '$data->mandatoryIcon', + 'value' => '$data->mandatoryIcon', 'htmlOptions' => array('class' => 'text-center'), ), @@ -943,16 +973,16 @@ public function getQuestionListColumns() 'header' => gT('Other'), 'type' => 'raw', 'name' => 'other', - 'value'=> '$data->otherIcon', + 'value' => '$data->otherIcon', 'htmlOptions' => array('class' => 'text-center'), ), array( - 'header'=>'', - 'name'=>'actions', - 'type'=>'raw', - 'value'=>'$data->buttons', + 'header' => '', + 'name' => 'actions', + 'type' => 'raw', + 'value' => '$data->buttons', 'htmlOptions' => array('class' => 'col-md-2 col-xs-1 text-right nowrap'), ), @@ -965,41 +995,41 @@ public function search() $sort = new CSort(); $sort->attributes = array( - 'question_id'=>array( - 'asc'=>'t.qid asc', - 'desc'=>'t.qid desc', + 'question_id' => array( + 'asc' => 't.qid asc', + 'desc' => 't.qid desc', ), - 'question_order'=>array( - 'asc' =>'g.group_order asc, t.question_order asc', - 'desc'=>'g.group_order desc,t.question_order desc', + 'question_order' => array( + 'asc' => 'g.group_order asc, t.question_order asc', + 'desc' => 'g.group_order desc,t.question_order desc', ), - 'title'=>array( - 'asc'=>'t.title asc', - 'desc'=>'t.title desc', + 'title' => array( + 'asc' => 't.title asc', + 'desc' => 't.title desc', ), - 'question'=>array( - 'asc'=>'ql10n.question asc', - 'desc'=>'ql10n.question desc', + 'question' => array( + 'asc' => 'ql10n.question asc', + 'desc' => 'ql10n.question desc', ), - 'group'=>array( - 'asc'=>'g.gid asc', - 'desc'=>'g.gid desc', + 'group' => array( + 'asc' => 'g.gid asc', + 'desc' => 'g.gid desc', ), - 'mandatory'=>array( - 'asc'=>'t.mandatory asc', - 'desc'=>'t.mandatory desc', + 'mandatory' => array( + 'asc' => 't.mandatory asc', + 'desc' => 't.mandatory desc', ), - 'encrypted'=>array( - 'asc'=>'t.encrypted asc', - 'desc'=>'t.encrypted desc', + 'encrypted' => array( + 'asc' => 't.encrypted asc', + 'desc' => 't.encrypted desc', ), - 'other'=>array( - 'asc'=>'t.other asc', - 'desc'=>'t.other desc', + 'other' => array( + 'asc' => 't.other asc', + 'desc' => 't.other desc', ), ); @@ -1007,19 +1037,19 @@ public function search() 'question_order' => CSort::SORT_ASC, ); - $criteria = new CDbCriteria; + $criteria = new CDbCriteria(); $criteria->compare("t.sid", $this->sid, false, 'AND'); $criteria->compare("t.parent_qid", 0, false, 'AND'); //$criteria->group = 't.qid, t.parent_qid, t.sid, t.gid, t.type, t.title, t.preg, t.other, t.mandatory, t.question_order, t.scale_id, t.same_default, t.relevance, t.modulename, t.encrypted'; - $criteria->with = array('group' => array('alias' => 'g'), 'questionl10ns'=>array('alias'=>'ql10n', 'condition'=>"language='".$this->survey->language."'")); + $criteria->with = array('group' => array('alias' => 'g'), 'questionl10ns' => array('alias' => 'ql10n', 'condition' => "language='" . $this->survey->language . "'")); if (!empty($this->title)) { - $criteria2 = new CDbCriteria; + $criteria2 = new CDbCriteria(); $criteria2->compare('t.title', $this->title, true, 'OR'); $criteria2->compare('ql10n.question', $this->title, true, 'OR'); $criteria2->compare('t.type', $this->title, true, 'OR'); /* search exact qid and make sure it's a numeric */ - if(is_numeric($this->title)) { + if (is_numeric($this->title)) { $criteria2->compare('t.qid', $this->title, false, 'OR'); } $criteria->mergeWith($criteria2, 'AND'); @@ -1031,10 +1061,10 @@ public function search() } $dataProvider = new CActiveDataProvider('Question', array( - 'criteria'=>$criteria, - 'sort'=>$sort, - 'pagination'=>array( - 'pageSize'=>$pageSize, + 'criteria' => $criteria, + 'sort' => $sort, + 'pagination' => array( + 'pageSize' => $pageSize, ), )); return $dataProvider; @@ -1074,19 +1104,19 @@ public function fixSubQuestions() $oSurvey = $this->survey; /* Delete subquestion l10n for unknown languages */ - $criteria = new CDbCriteria; - $criteria->with = array("question", array('condition'=>array('sid'=>$this->qid))); + $criteria = new CDbCriteria(); + $criteria->with = array("question", array('condition' => array('sid' => $this->qid))); $criteria->together = true; $criteria->addNotInCondition('language', $oSurvey->getAllLanguages()); QuestionL10n::model()->deleteAll($criteria); /* Delete invalid subquestions (not in primary language */ $validSubQuestion = Question::model()->findAll(array( - 'select'=>'title', - 'condition'=>'parent_qid=:parent_qid', - 'params'=>array('parent_qid' => $this->qid) + 'select' => 'title', + 'condition' => 'parent_qid=:parent_qid', + 'params' => array('parent_qid' => $this->qid) )); - $criteria = new CDbCriteria; + $criteria = new CDbCriteria(); $criteria->compare('parent_qid', $this->qid); $criteria->addNotInCondition('title', CHtml::listData($validSubQuestion, 'title', 'title')); Question::model()->deleteAll($criteria); @@ -1103,7 +1133,7 @@ public function getBasicFieldName() if ($this->parent_qid != 0) { /* Fix #15228: This survey throw a Error when try to print : seems subquestion gid can be outdated */ // Use parents relation - if(!empty($this->parents)) { // Maybe need to throw error or find it if it's not set ? + if (!empty($this->parents)) { // Maybe need to throw error or find it if it's not set ? return "{$this->parents->sid}X{$this->parents->gid}X{$this->parent_qid}"; } return "{$this->sid}X{$this->gid}X{$this->parent_qid}"; @@ -1119,10 +1149,10 @@ public function getQuestionAttribute($sAttribute) $criteria = new CDbCriteria(); $criteria->addCondition('qid=:qid'); $criteria->addCondition('attribute=:attribute'); - $criteria->params = [':qid'=>$this->qid, ':attribute' => $sAttribute]; + $criteria->params = [':qid' => $this->qid, ':attribute' => $sAttribute]; $oQuestionAttribute = QuestionAttribute::model()->find($criteria); - if($oQuestionAttribute != null) { + if ($oQuestionAttribute != null) { return $oQuestionAttribute->value; } @@ -1160,37 +1190,99 @@ public function getRenderererObject($aFieldArray, $type = null) $type = $type === null ? $this->type : $type; LoadQuestionTypes::load($type); switch ($type) { - case Question::QT_X_BOILERPLATE_QUESTION: $oRenderer = new RenderBoilerplate($aFieldArray); break; - case Question::QT_5_POINT_CHOICE: $oRenderer = new RenderFivePointChoice($aFieldArray); break; - case Question::QT_ASTERISK_EQUATION: $oRenderer = new RenderEquation($aFieldArray); break; - case Question::QT_D_DATE: $oRenderer = new RenderDate($aFieldArray); break; - case Question::QT_1_ARRAY_MULTISCALE: $oRenderer = new RenderArrayMultiscale($aFieldArray); break; - case Question::QT_L_LIST_DROPDOWN: $oRenderer = new RenderListRadio($aFieldArray); break; - case Question::QT_EXCLAMATION_LIST_DROPDOWN: $oRenderer = new RenderListDropdown($aFieldArray); break; - case Question::QT_O_LIST_WITH_COMMENT: $oRenderer = new RenderListComment($aFieldArray); break; - case Question::QT_R_RANKING_STYLE: $oRenderer = new RenderRanking($aFieldArray); break; - case Question::QT_M_MULTIPLE_CHOICE: $oRenderer = new RenderMultipleChoice($aFieldArray); break; - case Question::QT_P_MULTIPLE_CHOICE_WITH_COMMENTS: $oRenderer = new RenderMultipleChoiceWithComments($aFieldArray); break; - case Question::QT_I_LANGUAGE: $oRenderer = new RenderLanguageSelector($aFieldArray); break; - case Question::QT_Q_MULTIPLE_SHORT_TEXT: $oRenderer = new RenderMultipleShortText($aFieldArray); break; - case Question::QT_T_LONG_FREE_TEXT: $oRenderer = new RenderLongFreeText($aFieldArray); break; - case Question::QT_U_HUGE_FREE_TEXT: $oRenderer = new RenderHugeFreeText($aFieldArray); break; - case Question::QT_K_MULTIPLE_NUMERICAL_QUESTION: $oRenderer = new RenderMultipleNumerical($aFieldArray); break; - case Question::QT_A_ARRAY_5_CHOICE_QUESTIONS: $oRenderer = new RenderArray5ChoiceQuestion($aFieldArray); break; - case Question::QT_B_ARRAY_10_CHOICE_QUESTIONS: $oRenderer = new RenderArray10ChoiceQuestion($aFieldArray); break; - case Question::QT_C_ARRAY_YES_UNCERTAIN_NO: $oRenderer = new RenderArrayYesUncertainNo($aFieldArray); break; - case Question::QT_E_ARRAY_OF_INC_SAME_DEC_QUESTIONS: $oRenderer = new RenderArrayOfIncSameDecQuestions($aFieldArray); break; - case Question::QT_F_ARRAY_FLEXIBLE_ROW: $oRenderer = new RenderArrayFlexibleRow($aFieldArray); break; - case Question::QT_G_GENDER_DROPDOWN: $oRenderer = new RenderGenderDropdown($aFieldArray); break; - case Question::QT_H_ARRAY_FLEXIBLE_COLUMN: $oRenderer = new RendererArrayFlexibleColumn($aFieldArray); break; - case Question::QT_N_NUMERICAL: $oRenderer = new RenderNumerical($aFieldArray); break; - case Question::QT_S_SHORT_FREE_TEXT: $oRenderer = new RenderShortFreeText($aFieldArray); break; - case Question::QT_Y_YES_NO_RADIO: $oRenderer = new RenderYesNoRadio($aFieldArray); break; - case Question::QT_Z_LIST_RADIO_FLEXIBLE: $oRenderer = new RenderListRadioFlexible($aFieldArray); break; - case Question::QT_COLON_ARRAY_MULTI_FLEX_NUMBERS: $oRenderer = new RenderArrayMultiFlexNumbers($aFieldArray); break; - case Question::QT_SEMICOLON_ARRAY_MULTI_FLEX_TEXT: $oRenderer = new RenderArrayMultiFlexText($aFieldArray); break; - case Question::QT_VERTICAL_FILE_UPLOAD: $oRenderer = new RenderFileUpload($aFieldArray); break; - default: $oRenderer = new DummyQuestionEditContainer($aFieldArray); break; + case Question::QT_X_BOILERPLATE_QUESTION: + $oRenderer = new RenderBoilerplate($aFieldArray); + break; + case Question::QT_5_POINT_CHOICE: + $oRenderer = new RenderFivePointChoice($aFieldArray); + break; + case Question::QT_ASTERISK_EQUATION: + $oRenderer = new RenderEquation($aFieldArray); + break; + case Question::QT_D_DATE: + $oRenderer = new RenderDate($aFieldArray); + break; + case Question::QT_1_ARRAY_MULTISCALE: + $oRenderer = new RenderArrayMultiscale($aFieldArray); + break; + case Question::QT_L_LIST_DROPDOWN: + $oRenderer = new RenderListRadio($aFieldArray); + break; + case Question::QT_EXCLAMATION_LIST_DROPDOWN: + $oRenderer = new RenderListDropdown($aFieldArray); + break; + case Question::QT_O_LIST_WITH_COMMENT: + $oRenderer = new RenderListComment($aFieldArray); + break; + case Question::QT_R_RANKING_STYLE: + $oRenderer = new RenderRanking($aFieldArray); + break; + case Question::QT_M_MULTIPLE_CHOICE: + $oRenderer = new RenderMultipleChoice($aFieldArray); + break; + case Question::QT_P_MULTIPLE_CHOICE_WITH_COMMENTS: + $oRenderer = new RenderMultipleChoiceWithComments($aFieldArray); + break; + case Question::QT_I_LANGUAGE: + $oRenderer = new RenderLanguageSelector($aFieldArray); + break; + case Question::QT_Q_MULTIPLE_SHORT_TEXT: + $oRenderer = new RenderMultipleShortText($aFieldArray); + break; + case Question::QT_T_LONG_FREE_TEXT: + $oRenderer = new RenderLongFreeText($aFieldArray); + break; + case Question::QT_U_HUGE_FREE_TEXT: + $oRenderer = new RenderHugeFreeText($aFieldArray); + break; + case Question::QT_K_MULTIPLE_NUMERICAL_QUESTION: + $oRenderer = new RenderMultipleNumerical($aFieldArray); + break; + case Question::QT_A_ARRAY_5_CHOICE_QUESTIONS: + $oRenderer = new RenderArray5ChoiceQuestion($aFieldArray); + break; + case Question::QT_B_ARRAY_10_CHOICE_QUESTIONS: + $oRenderer = new RenderArray10ChoiceQuestion($aFieldArray); + break; + case Question::QT_C_ARRAY_YES_UNCERTAIN_NO: + $oRenderer = new RenderArrayYesUncertainNo($aFieldArray); + break; + case Question::QT_E_ARRAY_OF_INC_SAME_DEC_QUESTIONS: + $oRenderer = new RenderArrayOfIncSameDecQuestions($aFieldArray); + break; + case Question::QT_F_ARRAY_FLEXIBLE_ROW: + $oRenderer = new RenderArrayFlexibleRow($aFieldArray); + break; + case Question::QT_G_GENDER_DROPDOWN: + $oRenderer = new RenderGenderDropdown($aFieldArray); + break; + case Question::QT_H_ARRAY_FLEXIBLE_COLUMN: + $oRenderer = new RendererArrayFlexibleColumn($aFieldArray); + break; + case Question::QT_N_NUMERICAL: + $oRenderer = new RenderNumerical($aFieldArray); + break; + case Question::QT_S_SHORT_FREE_TEXT: + $oRenderer = new RenderShortFreeText($aFieldArray); + break; + case Question::QT_Y_YES_NO_RADIO: + $oRenderer = new RenderYesNoRadio($aFieldArray); + break; + case Question::QT_Z_LIST_RADIO_FLEXIBLE: + $oRenderer = new RenderListRadioFlexible($aFieldArray); + break; + case Question::QT_COLON_ARRAY_MULTI_FLEX_NUMBERS: + $oRenderer = new RenderArrayMultiFlexNumbers($aFieldArray); + break; + case Question::QT_SEMICOLON_ARRAY_MULTI_FLEX_TEXT: + $oRenderer = new RenderArrayMultiFlexText($aFieldArray); + break; + case Question::QT_VERTICAL_FILE_UPLOAD: + $oRenderer = new RenderFileUpload($aFieldArray); + break; + default: + $oRenderer = new DummyQuestionEditContainer($aFieldArray); + break; }; return $oRenderer; @@ -1202,37 +1294,68 @@ public function getDataSetObject($type = null) LoadQuestionTypes::load($type); switch ($type) { - case Question::QT_X_BOILERPLATE_QUESTION: return new DataSetBoilerplate($this->qid); - case Question::QT_5_POINT_CHOICE: return new DataSetFivePointChoice($this->qid); - case Question::QT_ASTERISK_EQUATION: return new DataSetEquation($this->qid); - case Question::QT_D_DATE: return new DataSetDate($this->qid); - case Question::QT_1_ARRAY_MULTISCALE: return new DataSetArrayMultiscale($this->qid); - case Question::QT_L_LIST_DROPDOWN: return new DataSetListRadio($this->qid); - case Question::QT_EXCLAMATION_LIST_DROPDOWN: return new DataSetListDropdown($this->qid); - case Question::QT_O_LIST_WITH_COMMENT: return new DataSetListWithComment($this->qid); - case Question::QT_R_RANKING_STYLE: return new DataSetRanking($this->qid); - case Question::QT_M_MULTIPLE_CHOICE: return new DataSetMultipleChoice($this->qid); - case Question::QT_P_MULTIPLE_CHOICE_WITH_COMMENTS: return new DataSetMultipleChoiceWithComments($this->qid); - case Question::QT_I_LANGUAGE: return new DataSetLanguage($this->qid); - case Question::QT_Q_MULTIPLE_SHORT_TEXT: return new DataSetMultipleShortText($this->qid); - case Question::QT_T_LONG_FREE_TEXT: return new DataSetLongFreeText($this->qid); - case Question::QT_U_HUGE_FREE_TEXT: return new DataSetHugeFreeText($this->qid); - case Question::QT_K_MULTIPLE_NUMERICAL_QUESTION: return new DataSetMultipleNumerical($this->qid); - case Question::QT_A_ARRAY_5_CHOICE_QUESTIONS: return new DataSetArray5ChoiceQuestion($this->qid); - case Question::QT_B_ARRAY_10_CHOICE_QUESTIONS: return new DataSetArray10ChoiceQuestion($this->qid); - case Question::QT_C_ARRAY_YES_UNCERTAIN_NO: return new DataSetArrayYesUncertainNo($this->qid); - case Question::QT_E_ARRAY_OF_INC_SAME_DEC_QUESTIONS:return new DataSetArrayOfIncSameDecQuestions($this->qid); - case Question::QT_F_ARRAY_FLEXIBLE_ROW: return new DataSetArrayFlexibleRow($this->qid); - case Question::QT_G_GENDER_DROPDOWN: return new DataSetGenderDropdown($this->qid); - case Question::QT_H_ARRAY_FLEXIBLE_COLUMN: return new DataSetArrayFlexibleColumn($this->qid); - case Question::QT_N_NUMERICAL: return new DataSetNumerical($this->qid); - case Question::QT_S_SHORT_FREE_TEXT: return new DataSetShortFreeText($this->qid); - case Question::QT_Y_YES_NO_RADIO: return new DataSetYesNoRadio($this->qid); - case Question::QT_Z_LIST_RADIO_FLEXIBLE: return new DataSetListRadioFlexible($this->qid); - case Question::QT_COLON_ARRAY_MULTI_FLEX_NUMBERS: return new DataSetArrayMultiFlexNumbers($this->qid); - case Question::QT_SEMICOLON_ARRAY_MULTI_FLEX_TEXT: return new DataSetArrayMultiFlexText($this->qid); - case Question::QT_VERTICAL_FILE_UPLOAD: return new DataSetFileUpload($this->qid); - default: return new DummyQuestionEditContainer($aFieldArray); + case Question::QT_X_BOILERPLATE_QUESTION: + return new DataSetBoilerplate($this->qid); + case Question::QT_5_POINT_CHOICE: + return new DataSetFivePointChoice($this->qid); + case Question::QT_ASTERISK_EQUATION: + return new DataSetEquation($this->qid); + case Question::QT_D_DATE: + return new DataSetDate($this->qid); + case Question::QT_1_ARRAY_MULTISCALE: + return new DataSetArrayMultiscale($this->qid); + case Question::QT_L_LIST_DROPDOWN: + return new DataSetListRadio($this->qid); + case Question::QT_EXCLAMATION_LIST_DROPDOWN: + return new DataSetListDropdown($this->qid); + case Question::QT_O_LIST_WITH_COMMENT: + return new DataSetListWithComment($this->qid); + case Question::QT_R_RANKING_STYLE: + return new DataSetRanking($this->qid); + case Question::QT_M_MULTIPLE_CHOICE: + return new DataSetMultipleChoice($this->qid); + case Question::QT_P_MULTIPLE_CHOICE_WITH_COMMENTS: + return new DataSetMultipleChoiceWithComments($this->qid); + case Question::QT_I_LANGUAGE: + return new DataSetLanguage($this->qid); + case Question::QT_Q_MULTIPLE_SHORT_TEXT: + return new DataSetMultipleShortText($this->qid); + case Question::QT_T_LONG_FREE_TEXT: + return new DataSetLongFreeText($this->qid); + case Question::QT_U_HUGE_FREE_TEXT: + return new DataSetHugeFreeText($this->qid); + case Question::QT_K_MULTIPLE_NUMERICAL_QUESTION: + return new DataSetMultipleNumerical($this->qid); + case Question::QT_A_ARRAY_5_CHOICE_QUESTIONS: + return new DataSetArray5ChoiceQuestion($this->qid); + case Question::QT_B_ARRAY_10_CHOICE_QUESTIONS: + return new DataSetArray10ChoiceQuestion($this->qid); + case Question::QT_C_ARRAY_YES_UNCERTAIN_NO: + return new DataSetArrayYesUncertainNo($this->qid); + case Question::QT_E_ARRAY_OF_INC_SAME_DEC_QUESTIONS: + return new DataSetArrayOfIncSameDecQuestions($this->qid); + case Question::QT_F_ARRAY_FLEXIBLE_ROW: + return new DataSetArrayFlexibleRow($this->qid); + case Question::QT_G_GENDER_DROPDOWN: + return new DataSetGenderDropdown($this->qid); + case Question::QT_H_ARRAY_FLEXIBLE_COLUMN: + return new DataSetArrayFlexibleColumn($this->qid); + case Question::QT_N_NUMERICAL: + return new DataSetNumerical($this->qid); + case Question::QT_S_SHORT_FREE_TEXT: + return new DataSetShortFreeText($this->qid); + case Question::QT_Y_YES_NO_RADIO: + return new DataSetYesNoRadio($this->qid); + case Question::QT_Z_LIST_RADIO_FLEXIBLE: + return new DataSetListRadioFlexible($this->qid); + case Question::QT_COLON_ARRAY_MULTI_FLEX_NUMBERS: + return new DataSetArrayMultiFlexNumbers($this->qid); + case Question::QT_SEMICOLON_ARRAY_MULTI_FLEX_TEXT: + return new DataSetArrayMultiFlexText($this->qid); + case Question::QT_VERTICAL_FILE_UPLOAD: + return new DataSetFileUpload($this->qid); + default: + return new DummyQuestionEditContainer($aFieldArray); }; } @@ -1242,7 +1365,7 @@ public function getDataSetObject($type = null) */ public function insertRecords($data) { - $oRecord = new self; + $oRecord = new self(); foreach ($data as $k => $v) { $oRecord->$k = $v; } @@ -1261,7 +1384,8 @@ public function insertRecords($data) * * @return boolean true if sort numbers had to be set, false otherwise */ - public static function setQuestionOrderForGroup($questionGroupId){ + public static function setQuestionOrderForGroup($questionGroupId) + { $criteriaHighestOrderNumber = new CDbCriteria(); $criteriaHighestOrderNumber->condition = 't.gid=:gid'; $criteriaHighestOrderNumber->addCondition("parent_qid=0"); //no subquestions here ... @@ -1303,7 +1427,7 @@ public static function getHighestQuestionOrderNumberInGroup($questionGroupId) $oQuestionHighestOrderNumber = Question::model()->find($criteriaHighestOrderNumber); - return ($oQuestionHighestOrderNumber === null)? null : $oQuestionHighestOrderNumber->question_order; + return ($oQuestionHighestOrderNumber === null) ? null : $oQuestionHighestOrderNumber->question_order; } /** @@ -1315,26 +1439,26 @@ public static function increaseAllOrderNumbersForGroup($questionGroupId) { $questionsInGroup = Question::model()->findAllByAttributes(["gid" => $questionGroupId]); foreach ($questionsInGroup as $question) { - $question->question_order = $question->question_order +1; + $question->question_order = $question->question_order + 1; $question->save(); } } - public function getHasSubquestions(){ - + public function getHasSubquestions() + { } - public function getHasAnsweroptions(){ - + public function getHasAnsweroptions() + { } /** * Override update() method to "clean" subquestions after saving a parent question */ - public function update($attributes=null) - { - if(parent::update($attributes)) { + public function update($attributes = null) + { + if (parent::update($attributes)) { $this->removeInvalidSubquestions(); return true; } else { @@ -1351,7 +1475,7 @@ protected function removeInvalidSubquestions() // Remove subquestions if the question's type doesn't allow subquestions if (!$this->getQuestionType()->subquestions) { - $aSubquestions = Question::model()->findAll("parent_qid=:parent_qid", array("parent_qid"=>$this->qid)); + $aSubquestions = Question::model()->findAll("parent_qid=:parent_qid", array("parent_qid" => $this->qid)); if (!empty($aSubquestions)) { foreach ($aSubquestions as $oSubquestion) { $oSubquestion->delete(); diff --git a/application/models/QuestionAttribute.php b/application/models/QuestionAttribute.php index efd90f4f0b6..edeb69f08fc 100644 --- a/application/models/QuestionAttribute.php +++ b/application/models/QuestionAttribute.php @@ -1,4 +1,6 @@ -'attribute'); + return array('index' => 'attribute'); } /** @inheritdoc */ @@ -96,12 +98,12 @@ public function rules() */ public function setQuestionAttributeWithLanguage($iQuestionID, $sAttributeName, $sValue, $sLanguage) { - $oModel = new self; - $aResult = $oModel->findAll('attribute=:attributeName and qid=:questionID and language=:language', array(':attributeName'=>$sAttributeName, ':language'=>$sLanguage, ':questionID'=>$iQuestionID)); + $oModel = new self(); + $aResult = $oModel->findAll('attribute=:attributeName and qid=:questionID and language=:language', array(':attributeName' => $sAttributeName, ':language' => $sLanguage, ':questionID' => $iQuestionID)); if (!empty($aResult)) { - $oModel->updateAll(array('value'=>$sValue), 'attribute=:attributeName and qid=:questionID and language=:language', array(':attributeName'=>$sAttributeName, ':language'=>$sLanguage, ':questionID'=>$iQuestionID)); + $oModel->updateAll(array('value' => $sValue), 'attribute=:attributeName and qid=:questionID and language=:language', array(':attributeName' => $sAttributeName, ':language' => $sLanguage, ':questionID' => $iQuestionID)); } else { - $oModel = new self; + $oModel = new self(); $oModel->attribute = $sAttributeName; $oModel->value = $sValue; $oModel->qid = $iQuestionID; @@ -124,12 +126,12 @@ public function setQuestionAttributeWithLanguage($iQuestionID, $sAttributeName, */ public function setQuestionAttribute($iQuestionID, $sAttributeName, $sValue) { - $oModel = new self; - $aResult = $oModel->findAll('attribute=:attributeName and qid=:questionID', array(':attributeName'=>$sAttributeName, ':questionID'=>$iQuestionID)); + $oModel = new self(); + $aResult = $oModel->findAll('attribute=:attributeName and qid=:questionID', array(':attributeName' => $sAttributeName, ':questionID' => $iQuestionID)); if (!empty($aResult)) { - $oModel->updateAll(array('value'=>$sValue), 'attribute=:attributeName and qid=:questionID', array(':attributeName'=>$sAttributeName, ':questionID'=>$iQuestionID)); + $oModel->updateAll(array('value' => $sValue), 'attribute=:attributeName and qid=:questionID', array(':attributeName' => $sAttributeName, ':questionID' => $iQuestionID)); } else { - $oModel = new self; + $oModel = new self(); $oModel->attribute = $sAttributeName; $oModel->value = $sValue; $oModel->qid = $iQuestionID; @@ -179,7 +181,7 @@ public function setMultiple($iSid, $aQids, $aAttributesToUpdate, $aValidQuestion QuestionAttribute::model()->updateAll(['value' => $sValue], 'attribute=:attribute AND qid=:qid', [':attribute' => $sAttribute, ':qid' => $iQid]); } else { // Create - $oAttribute = new QuestionAttribute; + $oAttribute = new QuestionAttribute(); $oAttribute->qid = $iQid; $oAttribute->value = $sValue; $oAttribute->attribute = $sAttribute; @@ -219,7 +221,7 @@ public function getQuestionAttributes($iQuestionID, $sLanguage = null) return $value; } } - $oQuestion = Question::model()->with('survey')->find("qid=:qid", array('qid'=>$iQuestionID)); + $oQuestion = Question::model()->with('survey')->find("qid=:qid", array('qid' => $iQuestionID)); if ($oQuestion) { if ($sLanguage) { $aLanguages = array($sLanguage); @@ -228,7 +230,7 @@ public function getQuestionAttributes($iQuestionID, $sLanguage = null) } // For some reason this happened in bug #10684 if ($oQuestion->type == null) { - throw new \CException("Question is corrupt: no type defined for question ".$iQuestionID); + throw new \CException("Question is corrupt: no type defined for question " . $iQuestionID); } $aAttributeValues = self::getAttributesAsArrayFromDB($iQuestionID); $aAttributeFromXmlOrDefault = self::getQuestionAttributesSettings($oQuestion->type); //from xml files @@ -257,13 +259,14 @@ public function getQuestionAttributes($iQuestionID, $sLanguage = null) * @param array $aLanguages like $aLanguages[0] = 'en' * @return array */ - private static function rewriteQuestionAttributeArray($aAttributeNames, $aAttributeValues, $aLanguages){ + private static function rewriteQuestionAttributeArray($aAttributeNames, $aAttributeValues, $aLanguages) + { $aQuestionAttributes = array(); foreach ($aAttributeNames as $aAttribute) { $aQuestionAttributes[$aAttribute['name']]['expression'] = isset($aAttribute['expression']) ? $aAttribute['expression'] : 0; // convert empty array to empty string - if (empty($aAttribute['default']) && is_array($aAttribute['default'])){ + if (empty($aAttribute['default']) && is_array($aAttribute['default'])) { $aAttribute['default'] = ''; } @@ -301,7 +304,8 @@ private static function rewriteQuestionAttributeArray($aAttributeNames, $aAttrib * $aAttributeValues[$oAttributeValue->attribute][$oAttributeValue->language] * $aAttributeValues[$oAttributeValue->attribute][''] */ - public static function getAttributesAsArrayFromDB($iQuestionID){ + public static function getAttributesAsArrayFromDB($iQuestionID) + { /* Get whole existing attribute for this question in an array */ $oAttributeValues = self::model()->resetScope()->findAll("qid=:qid", ['qid' => $iQuestionID]); $aAttributeValues = array(); @@ -324,12 +328,15 @@ public static function getAttributesAsArrayFromDB($iQuestionID){ * @param Question $oQuestion * @return array|mixed returns $aAttributeNames with appended additional attributes */ - public static function addAdditionalAttributesFromExtendedTheme($aAttributeNames, $oQuestion){ + public static function addAdditionalAttributesFromExtendedTheme($aAttributeNames, $oQuestion) + { $retAttributeNamesExtended = $aAttributeNames; /* @var $oAttributeValue QuestionAttribute*/ - $oAttributeValue = self::model()->resetScope()->find("qid=:qid and attribute=:attribute", - ['qid' => $oQuestion->qid, 'attribute' => 'question_template']); - if($oAttributeValue !== null){ + $oAttributeValue = self::model()->resetScope()->find( + "qid=:qid and attribute=:attribute", + ['qid' => $oQuestion->qid, 'attribute' => 'question_template'] + ); + if ($oAttributeValue !== null) { $aAttributeValueQuestionTemplate['question_template'] = $oAttributeValue->value; $retAttributeNamesExtended = Question::getQuestionTemplateAttributes($retAttributeNamesExtended, $aAttributeValueQuestionTemplate, $oQuestion); } @@ -344,7 +351,7 @@ public static function addAdditionalAttributesFromExtendedTheme($aAttributeNames */ public static function insertRecords($data) { - $attrib = new self; + $attrib = new self(); foreach ($data as $k => $v) { $attrib->$k = $v; } @@ -376,10 +383,10 @@ public function getQuestion() { $criteria = new CDbCriteria(); $criteria->addCondition('qid=:qid'); - $criteria->params = [':qid'=>$this->qid]; + $criteria->params = [':qid' => $this->qid]; if ($this->language) { $criteria->addCondition('language=:language'); - $criteria->params = [':qid'=>$this->qid, ':language'=>$this->language]; + $criteria->params = [':qid' => $this->qid, ':language' => $this->language]; } /** @var Question $model */ $model = Question::model()->find($criteria); @@ -410,10 +417,10 @@ public static function getDefaultSettings() "help" => '', "value" => '', "sortorder" => 1000, - "i18n"=> false, + "i18n" => false, "readonly" => false, "readonly_when_active" => false, - "expression"=> null, + "expression" => null, ); } @@ -442,15 +449,15 @@ public static function getQuestionAttributesSettings($sType) self::$questionAttributesSettings[$sType] = array(); $attributes = \LimeSurvey\Helpers\questionHelper::getAttributesDefinitions(); /* Filter to get this question type setting */ - $aQuestionTypeAttributes = array_filter($attributes, function($attribute) use ($sType) { + $aQuestionTypeAttributes = array_filter($attributes, function ($attribute) use ($sType) { return stripos($attribute['types'], $sType) !== false; }); - foreach ($aQuestionTypeAttributes as $attribute=>$settings) { + foreach ($aQuestionTypeAttributes as $attribute => $settings) { self::$questionAttributesSettings[$sType][$attribute] = array_merge( QuestionAttribute::getDefaultSettings(), - array("category"=>gT("Plugins")), + array("category" => gT("Plugins")), $settings, - array("name"=>$attribute) + array("name" => $attribute) ); } } @@ -460,14 +467,15 @@ public static function getQuestionAttributesSettings($sType) /** * Returns the value for attribute 'question_template'. * Fetches the question_template from a question model. - * + * * Be carefull this attribute is not present in all questions. * Even more, standard question types where question theme are not used (or custom question theme are not used), * the attribute is missing. In those cases, the deault "core" is used. * * @return string question_template or 'core' if it not exists */ - public static function getQuestionTemplateValue($questionID){ + public static function getQuestionTemplateValue($questionID) + { $question_template = QuestionAttribute::model()->findByAttributes([ 'qid' => $questionID, 'attribute' => 'question_template' @@ -483,21 +491,21 @@ public static function getQuestionTemplateValue($questionID){ * * @return array The advanced attribute settings for this question type */ - protected static function getAdvancedAttributesFromXml($sXmlFilePath){ + protected static function getAdvancedAttributesFromXml($sXmlFilePath) + { $aXmlAttributes = array(); $aAttributes = array(); - if(file_exists($sXmlFilePath)){ + if (file_exists($sXmlFilePath)) { // load xml file libxml_disable_entity_loader(false); $xml_config = simplexml_load_file($sXmlFilePath); - $aXmlAttributes = json_decode(json_encode((array)$xml_config->attributes), TRUE); + $aXmlAttributes = json_decode(json_encode((array)$xml_config->attributes), true); // if only one attribute, then it doesn't return numeric index - if (!empty($aXmlAttributes && !array_key_exists('0', $aXmlAttributes['attribute']))){ + if (!empty($aXmlAttributes && !array_key_exists('0', $aXmlAttributes['attribute']))) { $aTemp = $aXmlAttributes['attribute']; unset($aXmlAttributes); $aXmlAttributes['attribute'][0] = $aTemp; - } libxml_disable_entity_loader(true); } else { @@ -505,20 +513,20 @@ protected static function getAdvancedAttributesFromXml($sXmlFilePath){ } // set $aAttributes array with attribute data - if (!empty($aXmlAttributes['attribute'])){ + if (!empty($aXmlAttributes['attribute'])) { foreach ($aXmlAttributes['attribute'] as $key => $value) { - if(empty($value['name'])) { + if (empty($value['name'])) { /* Allow comments in attributes */ continue; } /* settings the default value */ - $aAttributes[$value['name']] =self::getDefaultSettings(); + $aAttributes[$value['name']] = self::getDefaultSettings(); /* settings the xml value */ foreach ($value as $key2 => $value2) { - if ($key2 === 'options' && !empty($value2)){ + if ($key2 === 'options' && !empty($value2)) { foreach ($value2['option'] as $key3 => $value3) { - if (isset($value3['value'])){ - $value4 = is_array($value3['value'])?'':$value3['value']; + if (isset($value3['value'])) { + $value4 = is_array($value3['value']) ? '' : $value3['value']; $aAttributes[$value['name']]['options'][$value4] = $value3['text']; } } @@ -531,11 +539,11 @@ protected static function getAdvancedAttributesFromXml($sXmlFilePath){ // Filter all pesky '[]' values (empty values should be null, e.g. ). foreach ($aAttributes as $attributeName => $attribute) { - foreach ($attribute as $fieldName => $value) { - if ($value === []) { - $aAttributes[$attributeName][$fieldName] = null; + foreach ($attribute as $fieldName => $value) { + if ($value === []) { + $aAttributes[$attributeName][$fieldName] = null; + } } - } } return $aAttributes; @@ -562,7 +570,6 @@ protected static function getGeneralAttibutesFromXml($sXmlFilePath) $aTemp = $aXmlAttributes['attribute']; unset($aXmlAttributes); $aXmlAttributes['attribute'][0] = $aTemp; - } libxml_disable_entity_loader(true); } else { @@ -601,7 +608,8 @@ protected static function getGeneralAttibutesFromXml($sXmlFilePath) * * @return array the event attributes as array or an empty array */ - public static function getOwnQuestionAttributesViaPlugin(){ + public static function getOwnQuestionAttributesViaPlugin() + { $event = new \LimeSurvey\PluginManager\PluginEvent('newQuestionAttributes'); $result = App()->getPluginManager()->dispatchEvent($event); diff --git a/application/models/QuestionBaseDataSet.php b/application/models/QuestionBaseDataSet.php index 3c7dd399fdc..2a4243bdbc1 100644 --- a/application/models/QuestionBaseDataSet.php +++ b/application/models/QuestionBaseDataSet.php @@ -33,13 +33,13 @@ public function __construct($iQuestionId) * @return array * @throws CException */ - public function getGeneralSettingsArray($iQuestionID = null, $sQuestionType = null, $sLanguage = null, $question_template=null) + public function getGeneralSettingsArray($iQuestionID = null, $sQuestionType = null, $sLanguage = null, $question_template = null) { Yii::import('ext.GeneralOptionWidget.settings.*'); if ($iQuestionID != null) { $this->oQuestion = Question::model()->findByPk($iQuestionID); } else { - $iSurveyId = Yii::app()->request->getParam('sid')?? + $iSurveyId = Yii::app()->request->getParam('sid') ?? Yii::app()->request->getParam('surveyid') ?? Yii::app()->request->getParam('surveyId'); $this->oQuestion = $oQuestion = QuestionCreate::getInstance($iSurveyId, $sQuestionType); @@ -85,20 +85,20 @@ public function getGeneralSettingsArray($iQuestionID = null, $sQuestionType = nu // load visible general settings from config.xml $sFolderName = QuestionTemplate::getFolderName($this->sQuestionType); - $sXmlFilePath = App()->getConfig('rootdir').'/application/views/survey/questions/answer/'.$sFolderName.'/config.xml'; - if(file_exists($sXmlFilePath)){ + $sXmlFilePath = App()->getConfig('rootdir') . '/application/views/survey/questions/answer/' . $sFolderName . '/config.xml'; + if (file_exists($sXmlFilePath)) { // load xml file libxml_disable_entity_loader(false); $xml_config = simplexml_load_file($sXmlFilePath); - $aXmlAttributes = json_decode(json_encode((array)$xml_config->generalattributes), TRUE); + $aXmlAttributes = json_decode(json_encode((array)$xml_config->generalattributes), true); libxml_disable_entity_loader(true); } - foreach ($generalOptions as $key => $generalOption){ + foreach ($generalOptions as $key => $generalOption) { if ( (isset($aXmlAttributes['attribute']) && in_array($key, $aXmlAttributes['attribute'])) || !isset($aXmlAttributes['attribute']) - ){ + ) { $generalOptionsFiltered[$key] = $generalOption; }; } @@ -119,7 +119,7 @@ public function getGeneralSettingsArray($iQuestionID = null, $sQuestionType = nu * @return array * @throws CException */ - public function getAdvancedOptions($iQuestionID = null, $sQuestionType = null, $sLanguage = null, $sQuestionTemplate = null) + public function getAdvancedOptions($iQuestionID = null, $sQuestionType = null, $sLanguage = null, $sQuestionTemplate = null) { if ($iQuestionID != null) { $this->oQuestion = Question::model()->findByPk($iQuestionID); @@ -134,7 +134,7 @@ public function getAdvancedOptions($iQuestionID = null, $sQuestionType = null, $ $aAdvancedOptionsArray = []; if ($iQuestionID == null) { //this is only the case if question is new and has not been saved $userSetting = SettingsUser::getUserSettingValue('question_default_values_' . $this->oQuestion->type); - if ($userSetting !== null){ + if ($userSetting !== null) { $aAdvancedOptionsArray = (array) json_decode($userSetting); } } @@ -142,7 +142,7 @@ public function getAdvancedOptions($iQuestionID = null, $sQuestionType = null, $ if (empty($aAdvancedOptionsArray)) { //this function call must be here, because $this->aQuestionAttributes is used in function below (parseFromAttributeHelper) $this->aQuestionAttributes = QuestionAttribute::model()->getQuestionAttributes($this->oQuestion->qid, $sLanguage); - if( $sQuestionTemplate === null && $this->aQuestionAttributes['question_template'] !== 'core') { + if ($sQuestionTemplate === null && $this->aQuestionAttributes['question_template'] !== 'core') { $sQuestionTemplate = $this->aQuestionAttributes['question_template']; } $sQuestionTemplate = $sQuestionTemplate == '' || $sQuestionTemplate == 'core' ? null : $sQuestionTemplate; @@ -247,7 +247,7 @@ public function getPreformattedBlockOfAdvancedSettings($oQuestion, $sQuestionThe */ protected function parseFromAttributeHelper($sAttributeKey, $aAttributeArray, $formElementValue) { - $aAttributeArray = array_merge(QuestionAttribute::getDefaultSettings(),$aAttributeArray); + $aAttributeArray = array_merge(QuestionAttribute::getDefaultSettings(), $aAttributeArray); $aAdvancedAttributeArray = [ 'name' => empty($aAttributeArray['name']) ? $sAttributeKey : $aAttributeArray['name'], 'title' => CHtml::decode($aAttributeArray['caption']), @@ -264,7 +264,7 @@ protected function parseFromAttributeHelper($sAttributeKey, $aAttributeArray, $f $aFormElementOptions = $aAttributeArray; $aFormElementOptions['classes'] = isset($aFormElementOptions['classes']) ? array_merge($aFormElementOptions['classes'], ['form-control']) : ['form-control']; - if(!is_array($aFormElementOptions['expression']) && $aFormElementOptions['expression'] == 2) { + if (!is_array($aFormElementOptions['expression']) && $aFormElementOptions['expression'] == 2) { $aFormElementOptions['inputGroup'] = [ 'prefix' => '{', 'suffix' => '}', diff --git a/application/models/QuestionBaseRenderer.php b/application/models/QuestionBaseRenderer.php index 1263649d2f8..00d7ba1b990 100644 --- a/application/models/QuestionBaseRenderer.php +++ b/application/models/QuestionBaseRenderer.php @@ -47,21 +47,21 @@ public function __construct($aFieldArray, $bRenderDirect = false) $this->sSGQA = $this->aFieldArray[1]; $this->oQuestion = Question::model()->findByPk($aFieldArray[0]); $this->bRenderDirect = $bRenderDirect; - $this->sLanguage = $this->setDefaultIfEmpty(@$aFieldArray['language'], @$_SESSION['survey_'.$this->oQuestion->sid]['s_lang']); - if(!$this->sLanguage) { + $this->sLanguage = $this->setDefaultIfEmpty(@$aFieldArray['language'], @$_SESSION['survey_' . $this->oQuestion->sid]['s_lang']); + if (!$this->sLanguage) { $this->sLanguage = $this->oQuestion->survey->language; } $this->aQuestionAttributes = QuestionAttribute::model()->getQuestionAttributes($this->oQuestion->qid); - $this->aSurveySessionArray = @$_SESSION['survey_'.$this->oQuestion->sid]; + $this->aSurveySessionArray = @$_SESSION['survey_' . $this->oQuestion->sid]; $this->mSessionValue = @$this->setDefaultIfEmpty($this->aSurveySessionArray[$this->sSGQA], ''); $oQuestionTemplate = QuestionTemplate::getNewInstance($this->oQuestion); $oQuestionTemplate->registerAssets(); // Register the custom assets of the question template, if needed - if(!empty($this->oQuestion->questionl10ns[$this->sLanguage]->script)){ - $sScriptRendered = LimeExpressionManager::ProcessString($this->oQuestion->questionl10ns[$this->sLanguage]->script,$this->oQuestion->qid, ['QID' => $this->oQuestion->qid]); - $this->addScript('QuestionStoredScript-'.$this->oQuestion->qid, $sScriptRendered, LSYii_ClientScript::POS_POSTSCRIPT); + if (!empty($this->oQuestion->questionl10ns[$this->sLanguage]->script)) { + $sScriptRendered = LimeExpressionManager::ProcessString($this->oQuestion->questionl10ns[$this->sLanguage]->script, $this->oQuestion->qid, ['QID' => $this->oQuestion->qid]); + $this->addScript('QuestionStoredScript-' . $this->oQuestion->qid, $sScriptRendered, LSYii_ClientScript::POS_POSTSCRIPT); } } @@ -70,27 +70,27 @@ protected function getTimeSettingRender() $oQuestion = $this->oQuestion; $oSurvey = $this->oQuestion->survey; - Yii::app()->getClientScript()->registerScriptFile(Yii::app()->getConfig("generalscripts").'coookies.js', CClientScript::POS_BEGIN); + Yii::app()->getClientScript()->registerScriptFile(Yii::app()->getConfig("generalscripts") . 'coookies.js', CClientScript::POS_BEGIN); Yii::app()->getClientScript()->registerPackage('timer-addition'); $langTimer = array( - 'hours'=>gT("hours"), - 'mins'=>gT("mins"), - 'seconds'=>gT("seconds"), + 'hours' => gT("hours"), + 'mins' => gT("mins"), + 'seconds' => gT("seconds"), ); /* Registering script : don't go to EM : no need usage of ls_json_encode */ - App()->getClientScript()->registerScript("LSVarLangTimer", "LSvar.lang.timer=".json_encode($langTimer).";", CClientScript::POS_BEGIN); + App()->getClientScript()->registerScript("LSVarLangTimer", "LSvar.lang.timer=" . json_encode($langTimer) . ";", CClientScript::POS_BEGIN); /** * The following lines cover for previewing questions, because no $_SESSION['survey_'.Yii::app()->getConfig('surveyID')]['fieldarray'] exists. * This just stops error messages occuring */ - if (!isset($_SESSION['survey_'.Yii::app()->getConfig('surveyID')]['fieldarray'])) { - $_SESSION['survey_'.Yii::app()->getConfig('surveyID')]['fieldarray'] = []; + if (!isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['fieldarray'])) { + $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['fieldarray'] = []; } /* End */ //Used to count how many timer questions in a page, and ensure scripts only load once - $_SESSION['survey_'.$oSurvey->sid]['timercount'] = (isset($_SESSION['survey_'.$oSurvey->sid]['timercount'])) ? $_SESSION['survey_'.$oSurvey->sid]['timercount']++ : 1; + $_SESSION['survey_' . $oSurvey->sid]['timercount'] = (isset($_SESSION['survey_' . $oSurvey->sid]['timercount'])) ? $_SESSION['survey_' . $oSurvey->sid]['timercount']++ : 1; /* Work in all mode system : why disable it ? */ //~ if ($thissurvey['format'] != "S") @@ -103,7 +103,7 @@ protected function getTimeSettingRender() //~ } //Render timer - $timer_html = Yii::app()->twigRenderer->renderQuestion('/survey/questions/question_timer/timer', array('iQid'=>$oQuestion->qid, 'sWarnId'=>''), true); + $timer_html = Yii::app()->twigRenderer->renderQuestion('/survey/questions/question_timer/timer', array('iQid' => $oQuestion->qid, 'sWarnId' => ''), true); $time_limit = $oQuestion->questionattributes['time_limit']['value']; $disable_next = $this->setDefaultIfEmpty($oQuestion->questionattributes['time_limit_disable_next']['value'], 0); @@ -122,7 +122,7 @@ protected function getTimeSettingRender() //Render timer 2 $timer_html = Yii::app()->twigRenderer->renderQuestion( '/survey/questions/question_timer/timer', - array('iQid'=>$ia[0], 'sWarnId'=>'_Warning_2'), + array('iQid' => $ia[0], 'sWarnId' => '_Warning_2'), true ); @@ -138,22 +138,22 @@ protected function getTimeSettingRender() $time_limit_timer_style = $this->setDefaultIfEmpty($oQuestion->questionattributes['time_limit_timer_style'], ''); $time_limit_timer_class = "ls-timer-content ls-timer-countdown ls-no-js-hidden"; - $timersessionname = "timer_question_".$oQuestion->qid; - if (isset($_SESSION['survey_'.Yii::app()->getConfig('surveyID')][$timersessionname])) { - $time_limit = $_SESSION['survey_'.Yii::app()->getConfig('surveyID')][$timersessionname]; + $timersessionname = "timer_question_" . $oQuestion->qid; + if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$timersessionname])) { + $time_limit = $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$timersessionname]; } $output = Yii::app()->twigRenderer->renderQuestion( '/survey/questions/question_timer/timer_header', - array('timersessionname'=>$timersessionname, 'time_limit'=>$time_limit), + array('timersessionname' => $timersessionname, 'time_limit' => $time_limit), true ); - if ($_SESSION['survey_'.$oSurvey->sid]['timercount'] < 2) { + if ($_SESSION['survey_' . $oSurvey->sid]['timercount'] < 2) { $iAction = ''; if ($oSurvey->format == "G") { $qcount = 0; - foreach ($_SESSION['survey_'.$oSurvey->sid]['fieldarray'] as $ib) { + foreach ($_SESSION['survey_' . $oSurvey->sid]['fieldarray'] as $ib) { if ($ib[5] == $oQuestion->gid) { $qcount++; } @@ -172,12 +172,12 @@ protected function getTimeSettingRender() } $output .= Yii::app()->twigRenderer->renderQuestion('/survey/questions/question_timer/timer_javascript', array( - 'timersessionname'=>$timersessionname, - 'time_limit'=>$time_limit, - 'iAction'=>$iAction, - 'disable_next'=>$disable_next, - 'disable_prev'=>$disable_prev, - 'time_limit_countdown_message' =>$time_limit_countdown_message, + 'timersessionname' => $timersessionname, + 'time_limit' => $time_limit, + 'iAction' => $iAction, + 'disable_next' => $disable_next, + 'disable_prev' => $disable_prev, + 'time_limit_countdown_message' => $time_limit_countdown_message, 'time_limit_message_delay' => $time_limit_message_delay ), true); } @@ -185,18 +185,18 @@ protected function getTimeSettingRender() $output .= Yii::app()->twigRenderer->renderQuestion( '/survey/questions/question_timer/timer_content', array( - 'iQid'=>$oQuestion->qid, - 'time_limit_message_style'=>$time_limit_message_style, - 'time_limit_message_class'=>$time_limit_message_class, - 'time_limit_message'=>$time_limit_message, - 'time_limit_warning_style'=>$time_limit_warning_style, - 'time_limit_warning_class'=>$time_limit_warning_class, - 'time_limit_warning_message'=>$time_limit_warning_message, - 'time_limit_warning_2_style'=>$time_limit_warning_2_style, - 'time_limit_warning_2_class'=>$time_limit_warning_2_class, - 'time_limit_warning_2_message'=>$time_limit_warning_2_message, - 'time_limit_timer_style'=>$time_limit_timer_style, - 'time_limit_timer_class'=>$time_limit_timer_class, + 'iQid' => $oQuestion->qid, + 'time_limit_message_style' => $time_limit_message_style, + 'time_limit_message_class' => $time_limit_message_class, + 'time_limit_message' => $time_limit_message, + 'time_limit_warning_style' => $time_limit_warning_style, + 'time_limit_warning_class' => $time_limit_warning_class, + 'time_limit_warning_message' => $time_limit_warning_message, + 'time_limit_warning_2_style' => $time_limit_warning_2_style, + 'time_limit_warning_2_class' => $time_limit_warning_2_class, + 'time_limit_warning_2_message' => $time_limit_warning_2_message, + 'time_limit_timer_style' => $time_limit_timer_style, + 'time_limit_timer_class' => $time_limit_timer_class, ), true ); @@ -204,24 +204,25 @@ protected function getTimeSettingRender() $output .= Yii::app()->twigRenderer->renderQuestion( '/survey/questions/question_timer/timer_footer', array( - 'iQid'=>$oQuestion->qid, - 'iSid'=>Yii::app()->getConfig('surveyID'), - 'time_limit'=>$time_limit, - 'time_limit_action'=>$time_limit_action, - 'time_limit_warning'=>$time_limit_warning, - 'time_limit_warning_2'=>$time_limit_warning_2, - 'time_limit_warning_display_time'=>$time_limit_warning_display_time, - 'time_limit_warning_2_display_time'=>$time_limit_warning_2_display_time, - 'disable'=>$disable, + 'iQid' => $oQuestion->qid, + 'iSid' => Yii::app()->getConfig('surveyID'), + 'time_limit' => $time_limit, + 'time_limit_action' => $time_limit_action, + 'time_limit_warning' => $time_limit_warning, + 'time_limit_warning_2' => $time_limit_warning_2, + 'time_limit_warning_display_time' => $time_limit_warning_display_time, + 'time_limit_warning_2_display_time' => $time_limit_warning_2_display_time, + 'disable' => $disable, ), true ); return $output; } - protected function getQuestionAttribute($key1, $key2=null) { + protected function getQuestionAttribute($key1, $key2 = null) + { $result = isset($this->aQuestionAttributes[$key1]) ? $this->aQuestionAttributes[$key1] : null; - if($key2 !== null && $result !== null) { + if ($key2 !== null && $result !== null) { $result = isset($result[$key2]) ? $result[$key2] : null; } return $result; @@ -238,20 +239,20 @@ protected function setAnsweroptions($scale_id = null) $this->aAnswerOptions = $this->oQuestion->getOrderedAnswers($scale_id); } - protected function getAnswerCount($iScaleId=0) + protected function getAnswerCount($iScaleId = 0) { return count($this->aAnswerOptions[$iScaleId]); } - protected function getQuestionCount($iScaleId=0) + protected function getQuestionCount($iScaleId = 0) { return count($this->aSubQuestions[$iScaleId]); } - protected function getFromSurveySession($sIndex, $default="") + protected function getFromSurveySession($sIndex, $default = "") { - return isset($_SESSION['survey_'.$this->oQuestion->sid][$sIndex]) - ? $_SESSION['survey_'.$this->oQuestion->sid][$sIndex] + return isset($_SESSION['survey_' . $this->oQuestion->sid][$sIndex]) + ? $_SESSION['survey_' . $this->oQuestion->sid][$sIndex] : $default; } @@ -265,7 +266,7 @@ protected function applyPackages() protected function addScript($name, $content, $position = LSYii_ClientScript::POS_BEGIN, $appendId = false) { $this->aScripts[] = [ - 'name' => $name.($appendId ? '_'.$this->oQuestion->qid : ''), + 'name' => $name . ($appendId ? '_' . $this->oQuestion->qid : ''), 'content' => $content, 'position' => $position ]; @@ -293,7 +294,7 @@ protected function applyStyles() protected function setDefaultIfEmpty($value, $default) { - if(!$value) { + if (!$value) { return $default; } return trim($value) == '' ? $default : $value; @@ -324,9 +325,10 @@ public function getCurrentRelevecanceClass($myfname) /* EM don't set difference between relevance in session, if exclude_all_others is set , just ls-disabled */ if ($sExcludeAllOther !== false) { foreach (explode(';', $sExcludeAllOther) as $sExclude) { - $sExclude = $this->sSGQA.$sExclude; - if ((!isset($aSurveySessionArray['relevanceStatus'][$sExclude]) || $aSurveySessionArray['relevanceStatus'][$sExclude]) - && (isset($aSurveySessionArray[$sExclude]) && $aSurveySessionArray[$sExclude] == "Y") + $sExclude = $this->sSGQA . $sExclude; + if ( + (!isset($aSurveySessionArray['relevanceStatus'][$sExclude]) || $aSurveySessionArray['relevanceStatus'][$sExclude]) + && (isset($aSurveySessionArray[$sExclude]) && $aSurveySessionArray[$sExclude] == "Y") ) { return "ls-irrelevant ls-disabled"; } @@ -396,13 +398,13 @@ public function getLabelInputWidth() */ public function includeKeypad() { - Yii::app()->getClientScript()->registerCssFile(Yii::app()->getConfig('third_party')."jquery-keypad/jquery.keypad.alt.css"); + Yii::app()->getClientScript()->registerCssFile(Yii::app()->getConfig('third_party') . "jquery-keypad/jquery.keypad.alt.css"); - $this->aScriptFiles[] = ['path' => Yii::app()->getConfig('third_party').'jquery-keypad/jquery.plugin.min.js', 'position' => LSYii_ClientScript::POS_BEGIN]; - $this->aScriptFiles[] = ['path' => Yii::app()->getConfig('third_party').'jquery-keypad/jquery.keypad.min.js', 'position' => LSYii_ClientScript::POS_BEGIN]; - $localefile = Yii::app()->getConfig('rootdir').'/third_party/jquery-keypad/jquery.keypad-'.App()->language.'.js'; + $this->aScriptFiles[] = ['path' => Yii::app()->getConfig('third_party') . 'jquery-keypad/jquery.plugin.min.js', 'position' => LSYii_ClientScript::POS_BEGIN]; + $this->aScriptFiles[] = ['path' => Yii::app()->getConfig('third_party') . 'jquery-keypad/jquery.keypad.min.js', 'position' => LSYii_ClientScript::POS_BEGIN]; + $localefile = Yii::app()->getConfig('rootdir') . '/third_party/jquery-keypad/jquery.keypad-' . App()->language . '.js'; if (App()->language != 'en' && file_exists($localefile)) { - $this->aScriptFiles[] = ['path' => Yii::app()->getConfig('third_party').'jquery-keypad/jquery.keypad-'.App()->language.'.js', 'position' => LSYii_ClientScript::POS_BEGIN]; + $this->aScriptFiles[] = ['path' => Yii::app()->getConfig('third_party') . 'jquery-keypad/jquery.keypad-' . App()->language . '.js', 'position' => LSYii_ClientScript::POS_BEGIN]; } } diff --git a/application/models/QuestionGroup.php b/application/models/QuestionGroup.php index eeaf2579af4..338fafa2edd 100644 --- a/application/models/QuestionGroup.php +++ b/application/models/QuestionGroup.php @@ -1,4 +1,6 @@ -true, 'allowEmpty'=>true], + ['group_order', 'numerical', 'integerOnly' => true, 'allowEmpty' => true], ['grelevance', 'safe'], ['randomization_group', 'safe'] ]; @@ -74,7 +76,7 @@ public function relations() { return array( 'survey' => array(self::BELONGS_TO, 'Survey', 'sid'), - 'questions' => array(self::HAS_MANY, 'Question', 'gid', 'condition'=>'parent_qid=0', 'order'=>'question_order ASC'), + 'questions' => array(self::HAS_MANY, 'Question', 'gid', 'condition' => 'parent_qid=0', 'order' => 'question_order ASC'), 'questiongroupl10ns' => array(self::HAS_MANY, 'QuestionGroupL10n', 'gid', 'together' => true) ); } @@ -100,31 +102,32 @@ public function updateGroupOrder($iSurveyId, $position = 0) $position = intval($position); foreach ($data->readAll() as $row) { - Yii::app()->db->createCommand()->update($this->tableName(), array('group_order' => $position), 'gid='.$row['gid']); + Yii::app()->db->createCommand()->update($this->tableName(), array('group_order' => $position), 'gid=' . $row['gid']); $position++; } } - public function cleanOrder($surveyid){ + public function cleanOrder($surveyid) + { $iSurveyId = (int) $surveyid; $oSurvey = Survey::model()->findByPk($iSurveyId); $aSurveyLanguages = array_merge([$oSurvey->language], explode(" ", $oSurvey->additional_languages)); foreach ($aSurveyLanguages as $sSurveyLanguage) { - $oCriteria=new CDbCriteria; - $oCriteria->compare('sid',$iSurveyId); + $oCriteria = new CDbCriteria(); + $oCriteria->compare('sid', $iSurveyId); $oCriteria->order = 'group_order ASC'; $aQuestiongroups = QuestionGroup::model()->findAll($oCriteria); - foreach($aQuestiongroups as $itrt => $oQuestiongroup) { - $iQuestionGroupOrder = $itrt+1; + foreach ($aQuestiongroups as $itrt => $oQuestiongroup) { + $iQuestionGroupOrder = $itrt + 1; $oQuestiongroup->group_order = $iQuestionGroupOrder; $oQuestiongroup->save(); $aQuestions = $oQuestiongroup->questions; foreach ($aQuestions as $qitrt => $oQuestion) { - $iQuestionOrder = $qitrt+1; + $iQuestionOrder = $qitrt + 1; $oQuestion->question_order = $iQuestionOrder; $oQuestion->save(true); } @@ -141,7 +144,7 @@ public function cleanOrder($surveyid){ */ public function insertRecords($data) { - $group = new self; + $group = new self(); foreach ($data as $k => $v) { $group->$k = $v; } @@ -169,7 +172,7 @@ public static function deleteWithDependency($groupId, $surveyId) $questionIds = QuestionGroup::getQuestionIdsInGroup($groupId); Question::deleteAllById($questionIds); Assessment::model()->deleteAllByAttributes(array('sid' => $surveyId, 'gid' => $groupId)); - QuestionGroupL10n::model()->deleteAllByAttributes(array('gid' =>$groupId)); + QuestionGroupL10n::model()->deleteAllByAttributes(array('gid' => $groupId)); return QuestionGroup::model()->deleteAllByAttributes(array('sid' => $surveyId, 'gid' => $groupId)); } @@ -191,7 +194,8 @@ public function getGroupDescription($iGroupId, $sLanguage) * @param string $sLanguage * @return string */ - public function getGroupNameI10N($sLanguage) { + public function getGroupNameI10N($sLanguage) + { if (isset($this->questiongroupl10ns[$sLanguage])) { return $this->questiongroupl10ns[$sLanguage]->group_name; } @@ -204,7 +208,8 @@ public function getGroupNameI10N($sLanguage) { * @param string $sLanguage * @return string */ - public function getGroupDescriptionI10N($sLanguage) { + public function getGroupDescriptionI10N($sLanguage) + { if (isset($this->questiongroupl10ns[$sLanguage])) { return $this->questiongroupl10ns[$sLanguage]->description; } @@ -263,52 +268,51 @@ public function getbuttons() // Add question to this group if (Permission::model()->hasSurveyPermission($this->sid, 'surveycontent', 'update')) { $url = Yii::app()->createUrl("questionAdministration/create/surveyid/$this->sid/gid/$this->gid"); - $button .= ''; + $button .= ''; } // Group edition // Edit if (Permission::model()->hasSurveyPermission($this->sid, 'surveycontent', 'update')) { $url = Yii::app()->createUrl("questionGroupsAdministration/view/surveyid/$this->sid/gid/$this->gid"); - $button .= ' '; + $button .= ' '; } // View summary if (Permission::model()->hasSurveyPermission($this->sid, 'surveycontent', 'read')) { $url = Yii::app()->createUrl("/questionGroupsAdministration/view/surveyid/"); - $url .= '/'.$this->sid.'/gid/'.$this->gid; - $button .= ' '; + $url .= '/' . $this->sid . '/gid/' . $this->gid; + $button .= ' '; } // Delete if ($oSurvey->active != "Y" && Permission::model()->hasSurveyPermission($this->sid, 'surveycontent', 'delete')) { $condarray = getGroupDepsForConditions($this->sid, "all", $this->gid, "by-targgid"); if (is_null($condarray)) { - $button .= '' - .'' - .''; - + $button .= '' + . '' + . ''; } else { - $button .= '' - .'' - .''; + $button .= '' + . '' + . ''; } } @@ -324,36 +328,36 @@ public function search() $pageSize = Yii::app()->user->getState('pageSize', Yii::app()->params['defaultPageSize']); $sort = new CSort(); - $sort->defaultOrder = array('group_order'=> false); + $sort->defaultOrder = array('group_order' => false); $sort->attributes = array( - 'group_id'=>array( - 'asc'=>'gid', - 'desc'=>'gid desc', + 'group_id' => array( + 'asc' => 'gid', + 'desc' => 'gid desc', ), - 'group_order'=>array( - 'asc'=>'group_order', - 'desc'=>'group_order desc', + 'group_order' => array( + 'asc' => 'group_order', + 'desc' => 'group_order desc', ), - 'group_name'=>array( - 'asc'=>'group_name', - 'desc'=>'group_name desc', + 'group_name' => array( + 'asc' => 'group_name', + 'desc' => 'group_name desc', ), ); - $criteria = new CDbCriteria; - $criteria->with = array('questiongroupl10ns'=>array("select"=>"group_name, description")); + $criteria = new CDbCriteria(); + $criteria->with = array('questiongroupl10ns' => array("select" => "group_name, description")); $criteria->together = true; $criteria->condition = 'sid=:surveyid AND language=:language'; - $criteria->params = (array(':surveyid'=>$this->sid, ':language'=>$this->language)); + $criteria->params = (array(':surveyid' => $this->sid, ':language' => $this->language)); $criteria->compare('group_name', $this->group_name, true); $dataProvider = new CActiveDataProvider(get_class($this), array( - 'criteria'=>$criteria, + 'criteria' => $criteria, - 'sort'=>$sort, + 'sort' => $sort, - 'pagination'=>array( - 'pageSize'=>$pageSize, + 'pagination' => array( + 'pageSize' => $pageSize, ), )); return $dataProvider; @@ -410,7 +414,7 @@ protected function beforeSave() public static function getFirstGroup($surveyId) { $criteria = new CDbCriteria(); - $criteria->addCondition('sid = '.$surveyId); + $criteria->addCondition('sid = ' . $surveyId); $criteria->mergeWith(array( 'order' => 'gid DESC' )); diff --git a/application/models/QuestionGroupL10n.php b/application/models/QuestionGroupL10n.php index 47c97ec7547..f11b9e04cc2 100644 --- a/application/models/QuestionGroupL10n.php +++ b/application/models/QuestionGroupL10n.php @@ -1,4 +1,6 @@ -'language'); - } + return array('index' => 'language'); + } /** @inheritdoc */ public function rules() { return array( array('group_name,description', 'LSYii_Validators'), - array('language', 'length', 'min' => 2, 'max'=>20), // in array languages ? - array('gid', 'unique', 'criteria'=>array( - 'condition'=>'language=:language', - 'params'=>array(':language'=>$this->language) + array('language', 'length', 'min' => 2, 'max' => 20), // in array languages ? + array('gid', 'unique', 'criteria' => array( + 'condition' => 'language=:language', + 'params' => array(':language' => $this->language) ), - 'message'=>sprintf(gT("Group ID (gid): “%s” already set with language ”%s”."),$this->gid,$this->language), + 'message' => sprintf(gT("Group ID (gid): “%s” already set with language ”%s”."), $this->gid, $this->language), ), ); } @@ -84,5 +86,4 @@ public function attributeLabels() 'group_name' => gt('Group name'), ); } - } diff --git a/application/models/QuestionL10n.php b/application/models/QuestionL10n.php index c19a2e1a968..e7cc5d7c9e1 100644 --- a/application/models/QuestionL10n.php +++ b/application/models/QuestionL10n.php @@ -1,4 +1,6 @@ -'language'); + return array('index' => 'language'); } /** @inheritdoc */ @@ -75,11 +77,11 @@ public function rules() { $rules = array( ['qid,language', 'required'], - ['qid', 'numerical', 'integerOnly'=>true], + ['qid', 'numerical', 'integerOnly' => true], array('question', 'LSYii_Validators'), array('help', 'LSYii_Validators'), array('script', 'LSYii_Validators'), - array('language', 'length', 'min' => 2, 'max'=>20), // in array languages ? + array('language', 'length', 'min' => 2, 'max' => 20), // in array languages ? ); if (!Yii::app()->user->isScriptUpdateAllowed()) { $rules[] = array('script', 'LSYii_NoUpdateValidator'); diff --git a/application/models/QuestionTemplate.php b/application/models/QuestionTemplate.php index 2056fce3d31..03328d3b68a 100644 --- a/application/models/QuestionTemplate.php +++ b/application/models/QuestionTemplate.php @@ -21,21 +21,21 @@ class QuestionTemplate extends CFormModel { // Main variables /** @var Question $oQuestion The current question */ - public $oQuestion; + public $oQuestion; /** @var boolean $bHasTemplate Does this question has a template? */ - public $bHasTemplate; + public $bHasTemplate; /** @var string $sTemplateFolderName The folder of the template * applied to this question (if no template applied, it's false) */ - public $sTemplateFolderName; + public $sTemplateFolderName; /** @var array $aViews Array of views the template can handle ($aViews['path_to_my_view']==true) */ - public $aViews; + public $aViews; /** @var SimpleXMLElement $oConfig */ - public $oConfig; + public $oConfig; /** @var boolean $bHasCustomAttributes Does the template provides custom attributes? */ - public $bHasCustomAttributes; + public $bHasCustomAttributes; /** @var array $aCustomAttributes array (attribute=>value) */ - public $aCustomAttributes; + public $aCustomAttributes; /** @var string $sTemplatePath The path to the template */ private $sTemplatePath; @@ -205,7 +205,6 @@ public function templateLoadsCoreJs() { if (!isset($this->bLoadCoreJs)) { if ($this->bHasTemplate) { - // Init config ($this->bHasConfigFile and $this->bLoadCoreJs ) $this->setConfig(); if ($this->bHasConfigFile) { @@ -225,7 +224,6 @@ public function templateLoadsCoreCss() { if (!isset($this->bLoadCoreCss)) { if ($this->bHasTemplate) { - // Init config ($this->bHasConfigFile and $this->bLoadCoreCss ) $this->setConfig(); if ($this->bHasConfigFile) { @@ -245,7 +243,6 @@ public function templateLoadsCorePackage() { if (!isset($this->bLoadCorePackage)) { if ($this->bHasTemplate) { - // Init config ($this->bHasConfigFile and $this->bLoadCorePackage ) $this->setConfig(); if ($this->bHasConfigFile) { @@ -267,8 +264,8 @@ public function setConfig() $oQuestion = $this->oQuestion; $sTemplatePath = $this->getTemplatePath(); $sFolderName = self::getFolderName($oQuestion->type); - $this->sTemplateQuestionPath = $sTemplatePath.'/survey/questions/answer/'.$sFolderName; - $xmlFile = $this->sTemplateQuestionPath.'/config.xml'; + $this->sTemplateQuestionPath = $sTemplatePath . '/survey/questions/answer/' . $sFolderName; + $xmlFile = $this->sTemplateQuestionPath . '/config.xml'; $this->bHasConfigFile = is_file($xmlFile); if ($this->bHasConfigFile) { @@ -286,11 +283,11 @@ public function setConfig() $this->aCustomAttributes = array(); foreach ($this->oConfig->attributes->attribute as $oCustomAttribute) { $attribute_name = (string) $oCustomAttribute->name; - if (isset($oCustomAttribute->i18n) && $oCustomAttribute->i18n){ + if (isset($oCustomAttribute->i18n) && $oCustomAttribute->i18n) { $sLang = App()->language; - $oAttributeValue = QuestionAttribute::model()->find("qid=:qid and attribute=:custom_attribute and language =:language", array('qid'=>$oQuestion->qid, 'custom_attribute'=>$attribute_name, 'language'=>$sLang)); + $oAttributeValue = QuestionAttribute::model()->find("qid=:qid and attribute=:custom_attribute and language =:language", array('qid' => $oQuestion->qid, 'custom_attribute' => $attribute_name, 'language' => $sLang)); } else { - $oAttributeValue = QuestionAttribute::model()->find("qid=:qid and attribute=:custom_attribute", array('qid'=>$oQuestion->qid, 'custom_attribute'=>$attribute_name)); + $oAttributeValue = QuestionAttribute::model()->find("qid=:qid and attribute=:custom_attribute", array('qid' => $oQuestion->qid, 'custom_attribute' => $attribute_name)); } if (is_object($oAttributeValue)) { $this->aCustomAttributes[$attribute_name] = $oAttributeValue->value; @@ -315,10 +312,10 @@ public function registerAssets() if (!empty($aCssFiles) || !empty($aJsFiles)) { // It will create the asset directory, and publish the css and js files - $questionTemplatePath = 'question.'.$this->oQuestion->qid.'.template.path'; - $package = 'question-template_'.$this->oQuestion->qid; + $questionTemplatePath = 'question.' . $this->oQuestion->qid . '.template.path'; + $package = 'question-template_' . $this->oQuestion->qid; - Yii::setPathOfAlias($questionTemplatePath, $this->sTemplateQuestionPath.'/assets'); // The package creation/publication need an alias + Yii::setPathOfAlias($questionTemplatePath, $this->sTemplateQuestionPath . '/assets'); // The package creation/publication need an alias Yii::app()->clientScript->addPackage($package, array( 'basePath' => $questionTemplatePath, 'css' => $aCssFiles, @@ -337,7 +334,6 @@ public function registerAssets() Yii::app()->getClientScript()->registerScriptFile("{$templateurl}$sJsFile", LSYii_ClientScript::POS_BEGIN); } } - } } } @@ -382,7 +378,7 @@ public function getCustomAttributes() * @param string $type * @return array */ - static public function getQuestionTemplateList($type) + public static function getQuestionTemplateList($type) { $aQuestionTemplateList = QuestionTheme::model()->findAllByAttributes([], 'question_type = :question_type', ['question_type' => $type]); $aQuestionTemplates = []; @@ -411,7 +407,7 @@ static public function getQuestionTemplateList($type) * @return array * @deprecated */ - static public function getQuestionTemplateUserList($type) + public static function getQuestionTemplateUserList($type) { $sUserQTemplateRootDir = Yii::app()->getConfig("userquestionthemerootdir"); $aQuestionTemplates = array(); @@ -422,41 +418,38 @@ static public function getQuestionTemplateUserList($type) $sFolderName = self::getFolderName($type); if ($sUserQTemplateRootDir && is_dir($sUserQTemplateRootDir)) { - $handle = opendir($sUserQTemplateRootDir); while (false !== ($file = readdir($handle))) { // Maybe $file[0] != "." to hide Linux hidden directory if (!is_file("$sUserQTemplateRootDir/$file") && $file != "." && $file != ".." && $file != ".svn") { - $sFullPathToQuestionTemplate = "$sUserQTemplateRootDir/$file/survey/questions/answer/$sFolderName"; if (is_dir($sFullPathToQuestionTemplate)) { - // Get the config file and check if template is available $oConfig = self::getTemplateConfig($sFullPathToQuestionTemplate); if (is_object($oConfig) && isset($oConfig->engine->show_as_template) && $oConfig->engine->show_as_template) { - if (!empty($oConfig->metadata->title)){ - $aQuestionTemplates[$file]['title'] = json_decode(json_encode($oConfig->metadata->title), TRUE)[0]; + if (!empty($oConfig->metadata->title)) { + $aQuestionTemplates[$file]['title'] = json_decode(json_encode($oConfig->metadata->title), true)[0]; } else { $templateName = $file; $aQuestionTemplates[$file]['title'] = $templateName; } - if (!empty($oConfig->files->preview->filename)){ - $fileName = json_decode(json_encode($oConfig->files->preview->filename), TRUE)[0]; - $previewPath = $sFullPathToQuestionTemplate."/assets/".$fileName; - if(is_file($previewPath)) { + if (!empty($oConfig->files->preview->filename)) { + $fileName = json_decode(json_encode($oConfig->files->preview->filename), true)[0]; + $previewPath = $sFullPathToQuestionTemplate . "/assets/" . $fileName; + if (is_file($previewPath)) { $check = LSYii_ImageValidator::validateImage($previewPath); - if($check['check']) { + if ($check['check']) { $aQuestionTemplates[$file]['preview'] = App()->getAssetManager()->publish($previewPath); } else { /* Log it a theme.question.$oConfig->name as error, review ? */ - Yii::log("Unable to use $fileName for preview in $sFullPathToQuestionTemplate/assets/",'error','theme.question.'.$oConfig->metadata->name); + Yii::log("Unable to use $fileName for preview in $sFullPathToQuestionTemplate/assets/", 'error', 'theme.question.' . $oConfig->metadata->name); } } else { /* Log it a theme.question.$oConfig->name as error, review ? */ - Yii::log("Unable to find $fileName for preview in $sFullPathToQuestionTemplate/assets/",'error','theme.question.'.$oConfig->metadata->name); + Yii::log("Unable to find $fileName for preview in $sFullPathToQuestionTemplate/assets/", 'error', 'theme.question.' . $oConfig->metadata->name); } } - if(empty($aQuestionTemplates[$file]['preview'])) { + if (empty($aQuestionTemplates[$file]['preview'])) { $aQuestionTemplates[$file]['preview'] = $aQuestionTemplates['core']['preview']; } } @@ -473,45 +466,43 @@ static public function getQuestionTemplateUserList($type) * @return array * @deprecated */ - static public function getQuestionTemplateCoreList($type) + public static function getQuestionTemplateCoreList($type) { $sCoreQTemplateRootDir = Yii::app()->getConfig("corequestionthemerootdir"); - $sCoreQTemplateRootUrl = Yii::app()->getConfig("publicurl").'themes/question'; + $sCoreQTemplateRootUrl = Yii::app()->getConfig("publicurl") . 'themes/question'; $aQuestionTemplates = array(); $sFolderName = self::getFolderName($type); if ($sCoreQTemplateRootDir && is_dir($sCoreQTemplateRootDir)) { - $handle = opendir($sCoreQTemplateRootDir); while (false !== ($file = readdir($handle))) { // Maybe $file[0] != "." to hide Linux hidden directory if (!is_file("$sCoreQTemplateRootDir/$file") && $file != "." && $file != ".." && $file != ".svn") { - $sFullPathToQuestionTemplate = "$sCoreQTemplateRootDir/$file/survey/questions/answer/$sFolderName"; - if (is_dir($sFullPathToQuestionTemplate)) { - // Get the config file and check if template is available - $oConfig = self::getTemplateConfig($sFullPathToQuestionTemplate); + if (is_dir($sFullPathToQuestionTemplate)) { + // Get the config file and check if template is available + $oConfig = self::getTemplateConfig($sFullPathToQuestionTemplate); - if (is_object($oConfig) && isset($oConfig->engine->show_as_template) && $oConfig->engine->show_as_template) { - if (!empty($oConfig->metadata->title)){ - $aQuestionTemplates[$file]['title'] = json_decode(json_encode($oConfig->metadata->title), TRUE)[0]; - } else { - $templateName = $file; - $aQuestionTemplates[$file]['title'] = $templateName; - } + if (is_object($oConfig) && isset($oConfig->engine->show_as_template) && $oConfig->engine->show_as_template) { + if (!empty($oConfig->metadata->title)) { + $aQuestionTemplates[$file]['title'] = json_decode(json_encode($oConfig->metadata->title), true)[0]; + } else { + $templateName = $file; + $aQuestionTemplates[$file]['title'] = $templateName; + } - if (!empty($oConfig->files->preview->filename)){ - $aQuestionTemplates[$file]['preview'] = "$sCoreQTemplateRootUrl/$file/survey/questions/answer/$sFolderName/assets/".json_decode(json_encode($oConfig->files->preview->filename), TRUE)[0]; - } else { - $aQuestionTemplates[$file]['preview'] = \LimeSurvey\Helpers\questionHelper::getQuestionThemePreviewUrl($type); - } + if (!empty($oConfig->files->preview->filename)) { + $aQuestionTemplates[$file]['preview'] = "$sCoreQTemplateRootUrl/$file/survey/questions/answer/$sFolderName/assets/" . json_decode(json_encode($oConfig->files->preview->filename), true)[0]; + } else { + $aQuestionTemplates[$file]['preview'] = \LimeSurvey\Helpers\questionHelper::getQuestionThemePreviewUrl($type); } } } } + } } return $aQuestionTemplates; } @@ -521,9 +512,9 @@ static public function getQuestionTemplateCoreList($type) * @param string $sFullPathToQuestionTemplate * @return bool|SimpleXMLElement */ - static public function getTemplateConfig($sFullPathToQuestionTemplate) + public static function getTemplateConfig($sFullPathToQuestionTemplate) { - $xmlFile = $sFullPathToQuestionTemplate.'/config.xml'; + $xmlFile = $sFullPathToQuestionTemplate . '/config.xml'; if (is_file($xmlFile)) { $sXMLConfigFile = file_get_contents(realpath($xmlFile)); // Entity loader is disabled, so we can't use simplexml_load_file; so we must read the file with file_get_contents and convert it as a string $oConfig = simplexml_load_string($sXMLConfigFile); @@ -537,7 +528,7 @@ static public function getTemplateConfig($sFullPathToQuestionTemplate) * @return string|null * @deprecated use QuestionTheme::getQuestionXMLPathForBaseType */ - static public function getFolderName($type) + public static function getFolderName($type) { if ($type) { $aTypeToFolder = self::getTypeToFolder(); @@ -553,7 +544,7 @@ static public function getFolderName($type) * @return array * @deprecated */ - static public function getTypeToFolder() + public static function getTypeToFolder() { return array( "1" => 'arrays/dualscale', @@ -587,5 +578,4 @@ static public function getTypeToFolder() "*" => 'equation', ); } - } diff --git a/application/models/QuestionTheme.php b/application/models/QuestionTheme.php index bd79775226a..9b04792a32c 100644 --- a/application/models/QuestionTheme.php +++ b/application/models/QuestionTheme.php @@ -129,7 +129,7 @@ public function search() { $pageSizeTemplateView = App()->user->getState('pageSizeTemplateView', App()->params['defaultPageSize']); - $criteria = new CDbCriteria; + $criteria = new CDbCriteria(); $criteria->compare('id', $this->id); $criteria->compare('name', $this->name, true); $criteria->compare('visible', $this->visible, true); @@ -474,7 +474,6 @@ public static function getQuestionMetaData($pathToXML) } if (substr($pathToXML, 0, strlen($questionDirectories['customCoreTheme'])) === $questionDirectories['customCoreTheme']) { $questionMetaData['coreTheme'] = 1; - } if (substr($pathToXML, 0, strlen($questionDirectories['customUserTheme'])) === $questionDirectories['customUserTheme']) { $questionMetaData['coreTheme'] = 0; @@ -614,12 +613,13 @@ public static function uninstall($oQuestionTheme) * * @return array */ - public static function findQuestionMetaDataForAllTypes(){ + public static function findQuestionMetaDataForAllTypes() + { //getting all question_types which are NOT extended $baseQuestions = self::model()->findAllByAttributes(['extends' => '']); - $aQuestionsIndexedByType =[]; + $aQuestionsIndexedByType = []; - foreach ($baseQuestions as $baseQuestion){ + foreach ($baseQuestions as $baseQuestion) { /**@var QuestionTheme $baseQuestion */ $baseQuestion['settings'] = json_decode($baseQuestion['settings']); $aQuestionsIndexedByType[$baseQuestion->question_type] = $baseQuestion; @@ -640,11 +640,11 @@ public static function findQuestionMetaData($question_type, $question_template = { $criteria = new CDbCriteria(); - if($question_template === 'core') { + if ($question_template === 'core') { $criteria->condition = 'extends = :extends'; $criteria->addCondition('question_type = :question_type', 'AND'); $criteria->params = [':extends' => '', ':question_type' => $question_type]; - }else{ + } else { $criteria->addCondition('question_type = :question_type AND name = :name'); $criteria->params = [':question_type' => $question_type, ':name' => $question_template]; } @@ -831,7 +831,7 @@ public static function getAnswerColumnDefinition($name, $type) * @return string Path to config XML * @throws CException */ - static public function getQuestionXMLPathForBaseType($type) + public static function getQuestionXMLPathForBaseType($type) { $aQuestionTheme = QuestionTheme::model()->findByAttributes([], 'question_type = :question_type AND extends = :extends', ['question_type' => $type, 'extends' => '']); if (empty($aQuestionTheme)) { @@ -961,13 +961,15 @@ public static function getQuestionThemeAttributeValues($type, $sQuestionThemeNam } $additionalAttributes = array(); - if($sQuestionThemeName !== null) { + if ($sQuestionThemeName !== null) { $additionalAttributes = self::getAdditionalAttrFromExtendedTheme($sQuestionThemeName, $type); } - return array_merge($aQuestionAttributes, + return array_merge( + $aQuestionAttributes, $additionalAttributes, - QuestionAttribute::getOwnQuestionAttributesViaPlugin()); + QuestionAttribute::getOwnQuestionAttributesViaPlugin() + ); } /** @@ -978,14 +980,15 @@ public static function getQuestionThemeAttributeValues($type, $sQuestionThemeNam * @param string $type the extended typ (see table question_themes "extends") * @return array additional attributes for an extended theme or empty array */ - public static function getAdditionalAttrFromExtendedTheme($sQuestionThemeName, $type){ + public static function getAdditionalAttrFromExtendedTheme($sQuestionThemeName, $type) + { $additionalAttributes = array(); libxml_disable_entity_loader(false); $questionTheme = QuestionTheme::model()->findByAttributes([], 'name = :name AND extends = :extends', ['name' => $sQuestionThemeName, 'extends' => $type]); - if ($questionTheme !== null) { - $xml_config = simplexml_load_file(App()->getConfig('rootdir') . '/' . $questionTheme['xml_path'] . '/config.xml'); - $attributes = json_decode(json_encode((array)$xml_config->attributes), true); - } + if ($questionTheme !== null) { + $xml_config = simplexml_load_file(App()->getConfig('rootdir') . '/' . $questionTheme['xml_path'] . '/config.xml'); + $attributes = json_decode(json_encode((array)$xml_config->attributes), true); + } libxml_disable_entity_loader(true); if (!empty($attributes)) { diff --git a/application/models/QuestionType.php b/application/models/QuestionType.php index 031c7278f52..9f27d114c83 100644 --- a/application/models/QuestionType.php +++ b/application/models/QuestionType.php @@ -97,10 +97,11 @@ public function attributeLabels() ]; } - public function applyToQuestion($oQuestion) { + public function applyToQuestion($oQuestion) + { $this->question = $oQuestion; $aSettingsArray = self::modelsAttributes($oQuestion->survey->language)[$oQuestion->type]; - foreach($aSettingsArray as $settingKey => $setting) { + foreach ($aSettingsArray as $settingKey => $setting) { $this->$settingKey = $setting; } } @@ -457,7 +458,6 @@ public static function integerCodes() return [ self::QT_VERTICAL_FILE_UPLOAD ]; - } /** @@ -467,7 +467,6 @@ public static function integerCodes() public static function doubleCodes() { return []; - } /** @@ -533,7 +532,6 @@ public function getFieldType() } } return $this->getFieldDataType(); - } /** diff --git a/application/models/Quota.php b/application/models/Quota.php index 8d43ed02852..d3b42e1c5aa 100644 --- a/application/models/Quota.php +++ b/application/models/Quota.php @@ -1,4 +1,6 @@ -true, 'min'=>'0', 'allowEmpty'=>true), - array('action', 'numerical', 'integerOnly'=>true, 'min'=>'1', 'max'=>'2', 'allowEmpty'=>true), // Default is null ? - array('active', 'numerical', 'integerOnly'=>true, 'min'=>'0', 'max'=>'1', 'allowEmpty'=>true), - array('autoload_url', 'numerical', 'integerOnly'=>true, 'min'=>'0', 'max'=>'1', 'allowEmpty'=>true), + array('qlimit', 'numerical', 'integerOnly' => true, 'min' => '0', 'allowEmpty' => true), + array('action', 'numerical', 'integerOnly' => true, 'min' => '1', 'max' => '2', 'allowEmpty' => true), // Default is null ? + array('active', 'numerical', 'integerOnly' => true, 'min' => '0', 'max' => '1', 'allowEmpty' => true), + array('autoload_url', 'numerical', 'integerOnly' => true, 'min' => '0', 'max' => '1', 'allowEmpty' => true), ); } public function attributeLabels() { return array( - 'name'=> gT("Quota name"), - 'active'=> gT("Active"), - 'qlimit'=> gT("Limit"), - 'autoload_url'=> gT("Autoload URL"), - 'action'=> gT("Quota action"), + 'name' => gT("Quota name"), + 'active' => gT("Active"), + 'qlimit' => gT("Limit"), + 'autoload_url' => gT("Autoload URL"), + 'action' => gT("Quota action"), ); } @@ -111,7 +113,7 @@ public function attributeLabels() */ function insertRecords($data) { - $quota = new self; + $quota = new self(); foreach ($data as $k => $v) { $quota->$k = $v; } @@ -146,7 +148,6 @@ function deleteQuota($condition = false, $recursive = true) public function getMainLanguagesetting() { return $this->languagesettings[$this->survey->language]; - } public function getCompleteCount() @@ -174,9 +175,9 @@ public function getCompleteCount() $aQuotaColumns[$member->memberInfo['fieldname']][] = $member->memberInfo['value']; } - $oCriteria = new CDbCriteria; + $oCriteria = new CDbCriteria(); $oCriteria->condition = new CDbExpression("submitdate IS NOT NULL"); - foreach ($aQuotaColumns as $sColumn=>$aValue) { + foreach ($aQuotaColumns as $sColumn => $aValue) { if (count($aValue) == 1) { $oCriteria->compare(Yii::app()->db->quoteColumnName($sColumn), $aValue); // NO need params : compare bind } else { @@ -195,7 +196,7 @@ public function getViewArray() $languageSettings = $this->currentLanguageSetting; $members = array(); foreach ($this->quotaMembers as $quotaMember) { - $members[] = $quotaMember->memberInfo; + $members[] = $quotaMember->memberInfo; } $attributes = $this->attributes; @@ -211,7 +212,7 @@ public function getCurrentLanguageSetting() $oQuotaLanguageSettings = QuotaLanguageSetting::model() ->findByAttributes(array( 'quotals_quota_id' => $this->id, - 'quotals_language'=>Yii::app()->getLanguage(), + 'quotals_language' => Yii::app()->getLanguage(), )); if ($oQuotaLanguageSettings) { return $oQuotaLanguageSettings; @@ -219,6 +220,4 @@ public function getCurrentLanguageSetting() /* If not exist or found, return the one from survey base languague */ return $this->getMainLanguagesetting(); } - - } diff --git a/application/models/QuotaLanguageSetting.php b/application/models/QuotaLanguageSetting.php index 466c2ac7fa4..6151a83515d 100644 --- a/application/models/QuotaLanguageSetting.php +++ b/application/models/QuotaLanguageSetting.php @@ -1,4 +1,6 @@ -true), + array('quotals_url', 'LSYii_Validators', 'isUrl' => true), array('quotals_urldescrip', 'LSYii_Validators'), - array('quotals_url', 'filter', 'filter'=>'trim'), + array('quotals_url', 'filter', 'filter' => 'trim'), array('quotals_url', 'urlValidator'), ); } @@ -88,9 +90,9 @@ public function urlValidator() public function attributeLabels() { return array( - 'quotals_message'=> gT("Quota message:"), - 'quotals_url'=> gT("URL:"), - 'quotals_urldescrip'=> gT("URL Description:"), + 'quotals_message' => gT("Quota message:"), + 'quotals_url' => gT("URL:"), + 'quotals_urldescrip' => gT("URL Description:"), ); } @@ -101,9 +103,9 @@ public function attributeLabels() */ public function insertRecords($data) { - $settings = new self; + $settings = new self(); foreach ($data as $k => $v) { - if ($k === 'autoload_url'){ + if ($k === 'autoload_url') { $settings->quota->autoload_url = $v; } else { $settings->$k = $v; diff --git a/application/models/QuotaMember.php b/application/models/QuotaMember.php index 51d6fb8f185..238be4ed50b 100644 --- a/application/models/QuotaMember.php +++ b/application/models/QuotaMember.php @@ -1,4 +1,6 @@ -array('create')) + array('code', 'required', 'on' => array('create')) ); } /** @@ -96,17 +98,17 @@ public function getMemberInfo() case "G": case "Y": case "*": - $sFieldName = $this->sid.'X'.$this->question->gid.'X'.$this->qid; + $sFieldName = $this->sid . 'X' . $this->question->gid . 'X' . $this->qid; $sValue = $this->code; break; case "M": - $sFieldName = $this->sid.'X'.$this->question->gid.'X'.$this->qid.$this->code; + $sFieldName = $this->sid . 'X' . $this->question->gid . 'X' . $this->qid . $this->code; $sValue = "Y"; break; case "A": case "B": $temp = explode('-', $this->code); - $sFieldName = $this->sid.'X'.$this->question->gid.'X'.$this->qid.$temp[0]; + $sFieldName = $this->sid . 'X' . $this->question->gid . 'X' . $this->qid . $temp[0]; $sValue = $temp[1]; break; default: @@ -132,8 +134,6 @@ public function getMemberInfo() ); } return []; - - } /** @@ -143,7 +143,7 @@ public function getMemberInfo() */ public function insertRecords($data) { - $members = new self; + $members = new self(); foreach ($data as $k => $v) { $members->$k = $v; } diff --git a/application/models/Response.php b/application/models/Response.php index 9d9ce7ef152..83a6ef1e3af 100644 --- a/application/models/Response.php +++ b/application/models/Response.php @@ -1,230 +1,230 @@ deleteFiles(); - return true; - } - return false; + if (parent::beforeDelete()) { + $this->deleteFiles(); + return true; } - /** - * - * @param mixed $className Either the classname or the survey id. - * @return Response - */ - public static function model($className = null) - { - /** @var self $model */ - $model = parent::model($className); - return $model; - } - /** - * - * @param int $surveyId - * @param string $scenario - * @return Response Description - */ - public static function create($surveyId, $scenario = 'insert') - { - return parent::create($surveyId, $scenario); + return false; + } + /** + * + * @param mixed $className Either the classname or the survey id. + * @return Response + */ + public static function model($className = null) + { + /** @var self $model */ + $model = parent::model($className); + return $model; + } + /** + * + * @param int $surveyId + * @param string $scenario + * @return Response Description + */ + public static function create($surveyId, $scenario = 'insert') + { + return parent::create($surveyId, $scenario); + } + + /** + * Get all files related to this response and (optionally) question ID. + * + * @param int $qid + * @return array[] + */ + public function getFiles($qid = null) + { + $survey = Survey::model()->findByPk($this->dynamicId); + $criteria = new CDbCriteria(); + $criteria->compare('sid', $this->dynamicId); + $criteria->compare('type', Question::QT_VERTICAL_FILE_UPLOAD); + $criteria->compare('ql10ns.language', $survey->language); + if ($qid !== null) { + $criteria->compare('t.qid', $qid); } - /** - * Get all files related to this response and (optionally) question ID. - * - * @param int $qid - * @return array[] - */ - public function getFiles($qid = null) - { - $survey = Survey::model()->findByPk($this->dynamicId); - $criteria = new CDbCriteria(); - $criteria->compare('sid', $this->dynamicId); - $criteria->compare('type', Question::QT_VERTICAL_FILE_UPLOAD); - $criteria->compare('ql10ns.language', $survey->language); - if ($qid !== null) { - $criteria->compare('t.qid', $qid); + $questions = Question::model() + ->with(array('questionl10ns' => array('alias' => 'ql10ns'))) + ->findAll($criteria); + $files = array(); + foreach ($questions as $question) { + $field = $question->sid . 'X' . $question->gid . 'X' . $question->qid; + $data = json_decode(urldecode($this->getAttribute($field)), true); + if (is_array($data)) { + /* adding the title and qid to fileinfo , see #14659 */ + $index = 0; + $data = array_map(function ($fileInfo) use (&$index, $question) { + return array_merge($fileInfo, array( + 'question' => array( + 'title' => $question->title, + 'qid' => $question->qid, + ), + 'index' => $index++, + )); + }, $data); + $files = array_merge($files, $data); } - - $questions = Question::model() - ->with(array('questionl10ns' => array('alias' => 'ql10ns'))) - ->findAll($criteria); - $files = array(); - foreach ($questions as $question) { - $field = $question->sid.'X'.$question->gid.'X'.$question->qid; - $data = json_decode(urldecode($this->getAttribute($field)), true); - if (is_array($data)) { - /* adding the title and qid to fileinfo , see #14659 */ - $index = 0; - $data = array_map( function($fileInfo) use (&$index, $question) { - return array_merge($fileInfo, array( - 'question' => array( - 'title' => $question->title, - 'qid' => $question->qid, - ), - 'index' => $index++, - )); - }, $data); - $files = array_merge($files, $data); - } - } - return $files; } + return $files; + } - /** - * Like getFiles() but returns array with key sgqa and value file data. - * @param integer $sQID The question ID - optional - Default 0 - * @return array [string $sgqa, array $fileData] - */ - public function getFilesAndSqga($sQID = 0) - { - $aConditions = array('sid' => $this->dynamicId, 'type' => '|'); - if ($sQID > 0) { - $aConditions['qid'] = $sQID; - } - $aQuestions = Question::model() - ->with(['questionl10ns' => ['language' => $this->survey->language]]) - ->findAllByAttributes($aConditions); - $files = array(); - foreach ($aQuestions as $question) { - $field = $question->sid.'X'.$question->gid.'X'.$question->qid; - $data = json_decode(stripslashes($this->getAttribute($field)), true); - if (is_array($data)) { - $files[$field] = $data; - } + /** + * Like getFiles() but returns array with key sgqa and value file data. + * @param integer $sQID The question ID - optional - Default 0 + * @return array [string $sgqa, array $fileData] + */ + public function getFilesAndSqga($sQID = 0) + { + $aConditions = array('sid' => $this->dynamicId, 'type' => '|'); + if ($sQID > 0) { + $aConditions['qid'] = $sQID; + } + $aQuestions = Question::model() + ->with(['questionl10ns' => ['language' => $this->survey->language]]) + ->findAllByAttributes($aConditions); + $files = array(); + foreach ($aQuestions as $question) { + $field = $question->sid . 'X' . $question->gid . 'X' . $question->qid; + $data = json_decode(stripslashes($this->getAttribute($field)), true); + if (is_array($data)) { + $files[$field] = $data; } - return $files; } + return $files; + } - /** - * Returns true if any uploaded file still exists on the filesystem. - * @return boolean - */ - public function someFileExists() - { - $uploaddir = Yii::app()->getConfig('uploaddir')."/surveys/{$this->dynamicId}/files/"; - foreach ($this->getFiles() as $fileInfo) { - $basename = basename($fileInfo['filename']); - if (file_exists($uploaddir.$basename)) { - return true; - } + /** + * Returns true if any uploaded file still exists on the filesystem. + * @return boolean + */ + public function someFileExists() + { + $uploaddir = Yii::app()->getConfig('uploaddir') . "/surveys/{$this->dynamicId}/files/"; + foreach ($this->getFiles() as $fileInfo) { + $basename = basename($fileInfo['filename']); + if (file_exists($uploaddir . $basename)) { + return true; } - return false; } + return false; + } - /** - * Delete all uploaded files for this response. - * @return string[] Name of files that could not be removed. - */ - public function deleteFiles() - { - $errors = array(); - $uploaddir = Yii::app()->getConfig('uploaddir')."/surveys/{$this->dynamicId}/files/"; - foreach ($this->getFiles() as $fileInfo) { - $basename = basename($fileInfo['filename']); - $result = @unlink($uploaddir.$basename); - if (!$result) { - $errors[] = $fileInfo['filename']; - } + /** + * Delete all uploaded files for this response. + * @return string[] Name of files that could not be removed. + */ + public function deleteFiles() + { + $errors = array(); + $uploaddir = Yii::app()->getConfig('uploaddir') . "/surveys/{$this->dynamicId}/files/"; + foreach ($this->getFiles() as $fileInfo) { + $basename = basename($fileInfo['filename']); + $result = @unlink($uploaddir . $basename); + if (!$result) { + $errors[] = $fileInfo['filename']; } - - return $errors; } - /** - * Delete uploaded files for this response AND modify - * response data to reflect all changes. - * Keep comment and title of file, but remove name/filename. - * @return array Number of successfully moved files and names of files that could not be removed/failed - */ - public function deleteFilesAndFilename() - { - $errors = array(); - $success = 0; - $uploaddir = Yii::app()->getConfig('uploaddir')."/surveys/{$this->dynamicId}/files/"; - $filesData = $this->getFilesAndSqga(); - foreach ($filesData as $sgqa => $fileInfos) { - foreach ($fileInfos as $i => $fileInfo) { - $basename = basename($fileInfo['filename']); - $fullFilename = $uploaddir.$basename; + return $errors; + } + + /** + * Delete uploaded files for this response AND modify + * response data to reflect all changes. + * Keep comment and title of file, but remove name/filename. + * @return array Number of successfully moved files and names of files that could not be removed/failed + */ + public function deleteFilesAndFilename() + { + $errors = array(); + $success = 0; + $uploaddir = Yii::app()->getConfig('uploaddir') . "/surveys/{$this->dynamicId}/files/"; + $filesData = $this->getFilesAndSqga(); + foreach ($filesData as $sgqa => $fileInfos) { + foreach ($fileInfos as $i => $fileInfo) { + $basename = basename($fileInfo['filename']); + $fullFilename = $uploaddir . $basename; - if (file_exists($fullFilename)) { - $result = @unlink($fullFilename); - if (!$result) { - $errors[] = $fileInfo['filename']; + if (file_exists($fullFilename)) { + $result = @unlink($fullFilename); + if (!$result) { + $errors[] = $fileInfo['filename']; + } else { + //$filesData[$sgqa][$i]['filename'] = 'deleted'; + $fileInfos[$i]['name'] = $fileInfo['name'] . sprintf(' (%s)', gT('deleted')); + $this->$sgqa = json_encode($fileInfos); + $result = $this->save(); + if ($result) { + $success++; } else { - //$filesData[$sgqa][$i]['filename'] = 'deleted'; - $fileInfos[$i]['name'] = $fileInfo['name'].sprintf(' (%s)', gT('deleted')); - $this->$sgqa = json_encode($fileInfos); - $result = $this->save(); - if ($result) { - $success++; - } else { - $errors[] = 'Could not update filename info for file '.$fileInfo['filename']; - } + $errors[] = 'Could not update filename info for file ' . $fileInfo['filename']; } - } else { - // TODO: Internal error - wrong filename saved? } + } else { + // TODO: Internal error - wrong filename saved? } } - - return array($success, $errors); - } - - public function delete($deleteFiles = false) - { - if ($deleteFiles) { - $this->deleteFiles(); - } - return parent::delete(); - } - public function relations() - { - $result = array( - 'token' => array(self::BELONGS_TO, 'Token_'.$this->dynamicId, array('token' => 'token')), - 'survey' => array(self::BELONGS_TO, 'Survey', '', 'on' => "sid = {$this->dynamicId}") - ); - return $result; - } - public function tableName() - { - return '{{survey_'.$this->dynamicId.'}}'; - } - /** - * Get current surveyId for other model/function - * @return int - */ - public function getSurveyId() { - return $this->getDynamicId(); } - public function browse() - { - } - public function search() - { + return array($success, $errors); + } + public function delete($deleteFiles = false) + { + if ($deleteFiles) { + $this->deleteFiles(); } + return parent::delete(); + } + public function relations() + { + $result = array( + 'token' => array(self::BELONGS_TO, 'Token_' . $this->dynamicId, array('token' => 'token')), + 'survey' => array(self::BELONGS_TO, 'Survey', '', 'on' => "sid = {$this->dynamicId}") + ); + return $result; + } + public function tableName() + { + return '{{survey_' . $this->dynamicId . '}}'; + } + /** + * Get current surveyId for other model/function + * @return int + */ + public function getSurveyId() + { + return $this->getDynamicId(); + } - public static function getEncryptedAttributes($surveyid = 0){ - $survey = Survey::model()->findByPk($surveyid); - $fieldmap = createFieldMap($survey, 'full', false, false, $survey->language); - $aAttributes = array(); - foreach ($fieldmap as $field){ - if (array_key_exists('encrypted', $field) && $field['encrypted'] == 'Y'){ - $aAttributes[] = $field['fieldname']; - } + public function browse() + { + } + public function search() + { + } + public static function getEncryptedAttributes($surveyid = 0) + { + $survey = Survey::model()->findByPk($surveyid); + $fieldmap = createFieldMap($survey, 'full', false, false, $survey->language); + $aAttributes = array(); + foreach ($fieldmap as $field) { + if (array_key_exists('encrypted', $field) && $field['encrypted'] == 'Y') { + $aAttributes[] = $field['fieldname']; } - return $aAttributes; } - + return $aAttributes; } +} diff --git a/application/models/SavedControl.php b/application/models/SavedControl.php index d905ac6e863..a1bcc1f3623 100644 --- a/application/models/SavedControl.php +++ b/application/models/SavedControl.php @@ -1,4 +1,6 @@ - $value) { @@ -192,7 +194,7 @@ public function getColumns() public function search() { // @todo Please modify the following code to remove attributes that should not be searched. - $criteria = new CDbCriteria; + $criteria = new CDbCriteria(); $criteria->compare('sid', $this->sid, false); //will not be searchable $criteria->compare('srid', $this->srid, true); $criteria->compare('access_code', $this->access_code, true); diff --git a/application/models/Session.php b/application/models/Session.php index 89612cd6997..2d7f64c4d6b 100644 --- a/application/models/Session.php +++ b/application/models/Session.php @@ -1,4 +1,6 @@ -dataBackup = $this->data; $db = $this->getDbConnection(); $dbType = $db->getDriverName(); - switch($dbType) { + switch ($dbType) { case 'sqlsrv': case 'mssql': case 'dblib': - $this->data=new CDbExpression('CONVERT(VARBINARY(MAX), '.$db->quoteValue($this->data).')'); + $this->data = new CDbExpression('CONVERT(VARBINARY(MAX), ' . $db->quoteValue($this->data) . ')'); break; case 'pgsql': - $this->data=new CDbExpression($db->quoteValueWithType($this->data, PDO::PARAM_LOB)."::bytea"); + $this->data = new CDbExpression($db->quoteValueWithType($this->data, PDO::PARAM_LOB) . "::bytea"); break; case 'mysql': // Don't seems to need something diff --git a/application/models/SettingGlobal.php b/application/models/SettingGlobal.php index 6a4fcfa881f..2c3f2cd9bc2 100644 --- a/application/models/SettingGlobal.php +++ b/application/models/SettingGlobal.php @@ -1,4 +1,6 @@ -disableByDb; /* Specific disable settings for demo mode */ if (Yii::app()->getConfig("demoMode")) { - $disableByDb = array_merge($disableByDb,array('sitename','defaultlang','defaulthtmleditormode','filterxsshtml')); + $disableByDb = array_merge($disableByDb, array('sitename','defaultlang','defaulthtmleditormode','filterxsshtml')); } $aRules = array( array('stg_name', 'required'), array('stg_name', 'unique'), array('stg_value', 'default', 'value' => ''), - array('stg_name', 'in', 'not'=>true,'range' => $disableByDb), + array('stg_name', 'in', 'not' => true,'range' => $disableByDb), ); return $aRules; @@ -91,8 +93,8 @@ public function rules() public static function setSetting($settingname, $settingvalue) { $setting = self::model()->findByPk($settingname); - if(empty($setting)) { - $setting = new self; + if (empty($setting)) { + $setting = new self(); $setting->stg_name = $settingname; } $setting->stg_value = $settingvalue; @@ -106,14 +108,14 @@ public static function setSetting($settingname, $settingvalue) protected function afterSave() { parent::afterSave(); - Yii::app()->setConfig($this->stg_name,$this->stg_value); + Yii::app()->setConfig($this->stg_name, $this->stg_value); } /** * Increase the custom asset version number in DB * This will force the refresh of the assets folders content */ - static public function increaseCustomAssetsversionnumber() + public static function increaseCustomAssetsversionnumber() { $iCustomassetversionnumber = getGlobalSetting('customassetversionnumber'); $iCustomassetversionnumber++; @@ -126,17 +128,17 @@ static public function increaseCustomAssetsversionnumber() * Increase the asset version number in version.php * This will force the refresh of the assets folders content */ - static public function increaseAssetsversionnumber() + public static function increaseAssetsversionnumber() { @ini_set('auto_detect_line_endings', '1'); $sRootdir = Yii::app()->getConfig("rootdir"); - $versionlines = file($sRootdir.DIRECTORY_SEPARATOR.'application'.DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'version.php'); - $handle = fopen($sRootdir.DIRECTORY_SEPARATOR.'application'.DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'version.php', "w"); + $versionlines = file($sRootdir . DIRECTORY_SEPARATOR . 'application' . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'version.php'); + $handle = fopen($sRootdir . DIRECTORY_SEPARATOR . 'application' . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'version.php', "w"); $iAssetNumber = self::generateAssetVersionNumber(Yii::app()->getConfig("assetsversionnumber")); foreach ($versionlines as $line) { if (strpos($line, 'assetsversionnumber') !== false) { - $line = '$config[\'assetsversionnumber\'] = \''.$iAssetNumber.'\';'."\r\n"; + $line = '$config[\'assetsversionnumber\'] = \'' . $iAssetNumber . '\';' . "\r\n"; } fwrite($handle, $line); } @@ -152,12 +154,12 @@ static public function increaseAssetsversionnumber() * @param int $iAssetNumber the current asset number * @return int the new asset number */ - static public function generateAssetVersionNumber($iAssetNumber) + public static function generateAssetVersionNumber($iAssetNumber) { - while ( $iAssetNumber == Yii::app()->getConfig("assetsversionnumber")) { - if ($iAssetNumber > 100000){ + while ($iAssetNumber == Yii::app()->getConfig("assetsversionnumber")) { + if ($iAssetNumber > 100000) { $iAssetNumber++; - }else{ + } else { $iAssetNumber = Yii::app()->getConfig("assetsversionnumber") + 100000; } } @@ -169,9 +171,10 @@ static public function generateAssetVersionNumber($iAssetNumber) * * @return int | null */ - static public function getDBVersionNumber(){ + public static function getDBVersionNumber() + { /**@var SettingGlobal $dbVersion */ - $dbVersion = self::model()->findByAttributes(['stg_name' => self::DBVERSION_NUMBER] ); + $dbVersion = self::model()->findByAttributes(['stg_name' => self::DBVERSION_NUMBER]); return ($dbVersion === null) ? null : (int)$dbVersion->stg_value; } diff --git a/application/models/SettingsUser.php b/application/models/SettingsUser.php index 821cb0660be..a0d0e887561 100644 --- a/application/models/SettingsUser.php +++ b/application/models/SettingsUser.php @@ -34,14 +34,14 @@ public function rules() // will receive user inputs. return array( array('uid, stg_name', 'required'), - array('uid', 'numerical', 'integerOnly'=>true), - array('entity', 'length', 'max'=>15), - array('entity_id', 'length', 'max'=>31), - array('stg_name', 'length', 'max'=>63), + array('uid', 'numerical', 'integerOnly' => true), + array('entity', 'length', 'max' => 15), + array('entity_id', 'length', 'max' => 31), + array('stg_name', 'length', 'max' => 63), array('stg_value', 'safe'), // The following rule is used by search(). // @todo Please remove those attributes that should not be searched. - array('uid, entity, entity_id, stg_name, stg_value', 'safe', 'on'=>'search'), + array('uid, entity, entity_id, stg_name, stg_value', 'safe', 'on' => 'search'), ); } @@ -84,7 +84,9 @@ public function attributeLabels() public static function setUserSetting($stg_name, $stg_value, $uid = null, $entity = null, $entity_id = null) { - if ($uid === null) { $uid = Yii::app()->user->getId(); } + if ($uid === null) { + $uid = Yii::app()->user->getId(); + } $setting = self::getUserSetting($stg_name, $uid, $entity, $entity_id); @@ -115,7 +117,9 @@ public static function setUserSetting($stg_name, $stg_value, $uid = null, $entit public static function deleteUserSetting($stg_name, $uid = null, $entity = null, $entity_id = null) { - if ($uid === null) { $uid = Yii::app()->user->getId(); } + if ($uid === null) { + $uid = Yii::app()->user->getId(); + } $setting = self::getUserSetting($stg_name, $uid, $entity, $entity_id); @@ -124,7 +128,6 @@ public static function deleteUserSetting($stg_name, $uid = null, $entity = null, } return false; - } /** @@ -138,8 +141,10 @@ public static function deleteUserSetting($stg_name, $uid = null, $entity = null, */ public static function getUserSetting($stg_name, $uid = null, $entity = null, $entity_id = null) { - if ($uid === null) { $uid = Yii::app()->user->getId(); } - $searchCriteria = new CDbCriteria; + if ($uid === null) { + $uid = Yii::app()->user->getId(); + } + $searchCriteria = new CDbCriteria(); $searchParams = []; $searchCriteria->addCondition('uid=:uid'); @@ -176,16 +181,16 @@ public static function getUserSetting($stg_name, $uid = null, $entity = null, $e * @param integer|null $entity_id | optional defaults to 'null' * @return mixed|null The current settings value or null id there is no setting */ - public static function getUserSettingValue($stg_name, $uid = null, $entity = null, $entity_id = null, $default=null) + public static function getUserSettingValue($stg_name, $uid = null, $entity = null, $entity_id = null, $default = null) { $setting = self::getUserSetting($stg_name, $uid, $entity, $entity_id); return $setting != null ? $setting->getAttribute('stg_value') : $default; } - public static function applyBaseSettings($iUid) + public static function applyBaseSettings($iUid) { $defaults = LsDefaultDataSets::getDefaultUserSettings(); - foreach($defaults as $default) { + foreach ($defaults as $default) { self::setUserSetting($default['stg_name'], $default['stg_value'], $iUid); } } @@ -206,7 +211,7 @@ public function search() { // @todo Please modify the following code to remove attributes that should not be searched. - $criteria = new CDbCriteria; + $criteria = new CDbCriteria(); $criteria->compare('uid', $this->uid); $criteria->compare('entity', $this->entity, true); @@ -215,7 +220,7 @@ public function search() $criteria->compare('stg_value', $this->stg_value, true); return new CActiveDataProvider($this, array( - 'criteria'=>$criteria, + 'criteria' => $criteria, )); } diff --git a/application/models/Survey.php b/application/models/Survey.php index 943790ed1d6..63ab8a58a4e 100755 --- a/application/models/Survey.php +++ b/application/models/Survey.php @@ -15,7 +15,7 @@ * See COPYRIGHT.php for copyright notices and details. * */ -use \LimeSurvey\PluginManager\PluginEvent; +use LimeSurvey\PluginManager\PluginEvent; /** * Class Survey @@ -204,18 +204,18 @@ public function init() /* default template */ $this->template = 'inherit'; /* default language */ - $validator = new LSYii_Validators; + $validator = new LSYii_Validators(); $this->language = $validator->languageFilter(App()->getConfig('defaultlang')); /* default user */ $this->owner_id = 1; $this->admin = App()->getConfig('siteadminname'); $this->adminemail = App()->getConfig('siteadminemail'); - if(!(Yii::app() instanceof CConsoleApplication)) { + if (!(Yii::app() instanceof CConsoleApplication)) { $iUserid = Permission::model()->getUserId(); - if($iUserid) { + if ($iUserid) { $this->owner_id = $iUserid; $oUser = User::model()->findByPk($iUserid); - if($oUser) { + if ($oUser) { $this->admin = $oUser->full_name; $this->adminemail = $oUser->email; } @@ -237,26 +237,26 @@ public function attributeLabels() * @inheritdoc With allow to delete all related models and data and test Permission. * @param bool $recursive **/ - public function delete($recursive=true) + public function delete($recursive = true) { if (!Permission::model()->hasSurveyPermission($this->sid, 'survey', 'delete')) { return false; } - if(!parent::delete()) { + if (!parent::delete()) { return false; } if ($recursive) { //delete the survey_$iSurveyID table - if (tableExists("{{survey_".$this->sid."}}")) { - Yii::app()->db->createCommand()->dropTable("{{survey_".$this->sid."}}"); + if (tableExists("{{survey_" . $this->sid . "}}")) { + Yii::app()->db->createCommand()->dropTable("{{survey_" . $this->sid . "}}"); } //delete the survey_$iSurveyID_timings table - if (tableExists("{{survey_".$this->sid."_timings}}")) { - Yii::app()->db->createCommand()->dropTable("{{survey_".$this->sid."_timings}}"); + if (tableExists("{{survey_" . $this->sid . "_timings}}")) { + Yii::app()->db->createCommand()->dropTable("{{survey_" . $this->sid . "_timings}}"); } //delete the tokens_$iSurveyID table - if (tableExists("{{tokens_".$this->sid."}}")) { - Yii::app()->db->createCommand()->dropTable("{{tokens_".$this->sid."}}"); + if (tableExists("{{tokens_" . $this->sid . "}}")) { + Yii::app()->db->createCommand()->dropTable("{{tokens_" . $this->sid . "}}"); } /* Remove User/global settings part : need Question and QuestionGroup*/ @@ -267,15 +267,15 @@ public function delete($recursive=true) SettingGlobal::model()->deleteAll($oCriteria); // Settings specific for this survey, 2nd part $oCriteria = new CDbCriteria(); - $oCriteria->compare('stg_name', 'last_%'.$this->sid.'%', true, 'AND', false); + $oCriteria->compare('stg_name', 'last_%' . $this->sid . '%', true, 'AND', false); SettingGlobal::model()->deleteAll($oCriteria); // All Group id from this survey for ALL users - $aGroupId = CHtml::listData(QuestionGroup::model()->findAll(array('select'=>'gid', 'condition'=>'sid=:sid', 'params'=>array(':sid'=>$this->sid))), 'gid', 'gid'); + $aGroupId = CHtml::listData(QuestionGroup::model()->findAll(array('select' => 'gid', 'condition' => 'sid=:sid', 'params' => array(':sid' => $this->sid))), 'gid', 'gid'); $oCriteria = new CDbCriteria(); $oCriteria->compare('stg_name', 'last_question_gid_%', true, 'AND', false); // pgsql need casting, unsure for mssql if (Yii::app()->db->getDriverName() == 'pgsql') { - $oCriteria->addInCondition('CAST(stg_value as '.App()->db->schema->getColumnType("integer").')', $aGroupId); + $oCriteria->addInCondition('CAST(stg_value as ' . App()->db->schema->getColumnType("integer") . ')', $aGroupId); } //mysql App()->db->schema->getColumnType("integer") give int(11), mssql seems to have issue if cast alpha to numeric else { @@ -283,11 +283,11 @@ public function delete($recursive=true) } SettingGlobal::model()->deleteAll($oCriteria); // All Question id from this survey for ALL users - $aQuestionId = CHtml::listData(Question::model()->findAll(array('select'=>'qid', 'condition'=>'sid=:sid', 'params'=>array(':sid'=>$this->sid))), 'qid', 'qid'); + $aQuestionId = CHtml::listData(Question::model()->findAll(array('select' => 'qid', 'condition' => 'sid=:sid', 'params' => array(':sid' => $this->sid))), 'qid', 'qid'); $oCriteria = new CDbCriteria(); $oCriteria->compare('stg_name', 'last_question_%', true, 'OR', false); if (Yii::app()->db->getDriverName() == 'pgsql') { - $oCriteria->addInCondition('CAST(NULLIF(stg_value, \'\') AS '.App()->db->schema->getColumnType("integer").')', $aQuestionId); + $oCriteria->addInCondition('CAST(NULLIF(stg_value, \'\') AS ' . App()->db->schema->getColumnType("integer") . ')', $aQuestionId); } else { $oCriteria->addInCondition('stg_value', $aQuestionId); } @@ -298,21 +298,20 @@ public function delete($recursive=true) // answers $oAnswers = Answer::model()->findAllByAttributes(array('qid' => $aQuestion['qid'])); foreach ($oAnswers as $aAnswer) { - AnswerL10n::model()->deleteAllByAttributes(array('aid' =>$aAnswer['aid'])); + AnswerL10n::model()->deleteAllByAttributes(array('aid' => $aAnswer['aid'])); } Answer::model()->deleteAllByAttributes(array('qid' => $aQuestion['qid'])); - Condition::model()->deleteAllByAttributes(array('qid' =>$aQuestion['qid'])); + Condition::model()->deleteAllByAttributes(array('qid' => $aQuestion['qid'])); QuestionAttribute::model()->deleteAllByAttributes(array('qid' => $aQuestion['qid'])); QuestionL10n::model()->deleteAllByAttributes(array('qid' => $aQuestion['qid'])); // delete defaultvalues and defaultvalueL10ns $oDefaultValues = DefaultValue::model()->findAll('qid = :qid', array(':qid' => $aQuestion['qid'])); - foreach($oDefaultValues as $defaultvalue){ + foreach ($oDefaultValues as $defaultvalue) { DefaultValue::model()->deleteAll('dvid = :dvid', array(':dvid' => $defaultvalue->dvid)); DefaultValueL10n::model()->deleteAll('dvid = :dvid', array(':dvid' => $defaultvalue->dvid)); }; - } Question::model()->deleteAllByAttributes(array('sid' => $this->sid)); @@ -321,26 +320,26 @@ public function delete($recursive=true) // question groups $oQuestionGroups = QuestionGroup::model()->findAllByAttributes(array('sid' => $this->sid)); foreach ($oQuestionGroups as $aQuestionGroup) { - QuestionGroupL10n::model()->deleteAllByAttributes(array('gid' =>$aQuestionGroup['gid'])); + QuestionGroupL10n::model()->deleteAllByAttributes(array('gid' => $aQuestionGroup['gid'])); } QuestionGroup::model()->deleteAllByAttributes(array('sid' => $this->sid)); SurveyLanguageSetting::model()->deleteAllByAttributes(array('surveyls_survey_id' => $this->sid)); - Permission::model()->deleteAllByAttributes(array('entity_id' => $this->sid, 'entity'=>'survey')); + Permission::model()->deleteAllByAttributes(array('entity_id' => $this->sid, 'entity' => 'survey')); SavedControl::model()->deleteAllByAttributes(array('sid' => $this->sid)); SurveyURLParameter::model()->deleteAllByAttributes(array('sid' => $this->sid)); //Remove any survey_links to the CPDB SurveyLink::model()->deleteLinksBySurvey($this->sid); Quota::model()->deleteQuota(array('sid' => $this->sid), true); // Remove all related plugin settings - PluginSetting::model()->deleteAllByAttributes(array("model" =>'Survey', "model_id" => $this->sid)); + PluginSetting::model()->deleteAllByAttributes(array("model" => 'Survey', "model_id" => $this->sid)); // Delete all uploaded files. - rmdirr(Yii::app()->getConfig('uploaddir').'/surveys/'.$this->sid); + rmdirr(Yii::app()->getConfig('uploaddir') . '/surveys/' . $this->sid); } // Remove from cache if (array_key_exists($this->sid, $this->findByPkCache)) { - unset ($this->findByPkCache[$this->sid]); + unset($this->findByPkCache[$this->sid]); } return true; @@ -355,7 +354,7 @@ public function getCurrentLanguageSettings() { if (isset($this->languagesettings[App()->language])) { return $this->languagesettings[App()->language]; - } else if(isset($this->languagesettings[$this->language])){ + } elseif (isset($this->languagesettings[$this->language])) { return $this->languagesettings[$this->language]; } else { throw new Exception('Selected Surveys language not found'); @@ -381,8 +380,8 @@ public function getLanguageForSurveyTaking() $sLang = Yii::app()->request->getParam('lang'); } else { // SESSION - if (isset(Yii::app()->session['survey_'.$this->sid]['s_lang'])) { - $sLang = Yii::app()->session['survey_'.$this->sid]['s_lang']; + if (isset(Yii::app()->session['survey_' . $this->sid]['s_lang'])) { + $sLang = Yii::app()->session['survey_' . $this->sid]['s_lang']; } } return $sLang; @@ -390,9 +389,9 @@ public function getLanguageForSurveyTaking() /** * Expires a survey. If the object was invoked using find or new surveyId can be ommited. - * + * * @param int $surveyId Survey ID - * + * * @return boolean|null */ public function expire($surveyId = null) @@ -438,13 +437,13 @@ public static function model($class = __CLASS__) public function relations() { return array( - 'permissions' => array(self::HAS_MANY, 'Permission', array('entity_id'=> 'sid')), // + 'permissions' => array(self::HAS_MANY, 'Permission', array('entity_id' => 'sid')), // 'languagesettings' => array(self::HAS_MANY, 'SurveyLanguageSetting', 'surveyls_survey_id', 'index' => 'surveyls_language'), 'defaultlanguage' => array(self::BELONGS_TO, 'SurveyLanguageSetting', array('language' => 'surveyls_language', 'sid' => 'surveyls_survey_id')), 'correct_relation_defaultlanguage' => array(self::HAS_ONE, 'SurveyLanguageSetting', array('surveyls_language' => 'language', 'surveyls_survey_id' => 'sid')), 'owner' => array(self::BELONGS_TO, 'User', 'owner_id',), - 'groups' => array(self::HAS_MANY, 'QuestionGroup', 'sid', 'order'=>'groups.group_order ASC'), - 'quotas' => array(self::HAS_MANY, 'Quota', 'sid', 'order'=>'name ASC'), + 'groups' => array(self::HAS_MANY, 'QuestionGroup', 'sid', 'order' => 'groups.group_order ASC'), + 'quotas' => array(self::HAS_MANY, 'Quota', 'sid', 'order' => 'name ASC'), 'surveymenus' => array(self::HAS_MANY, 'Surveymenu', array('survey_id' => 'sid')), 'surveygroup' => array(self::BELONGS_TO, 'SurveysGroups', array('gsid' => 'gsid')), 'surveysettings' => array(self::BELONGS_TO, 'SurveysGroupSettings', array('gsid' => 'gsid')), @@ -474,65 +473,65 @@ public function scopes() public function rules() { return array( - array('sid', 'numerical', 'integerOnly'=>true,'min'=>1), // max ? + array('sid', 'numerical', 'integerOnly' => true,'min' => 1), // max ? array('sid', 'unique'),// Not in pk - array('gsid', 'numerical', 'integerOnly'=>true), - array('datecreated', 'default', 'value'=>date("Y-m-d")), - array('startdate', 'default', 'value'=>null), - array('expires', 'default', 'value'=>null), + array('gsid', 'numerical', 'integerOnly' => true), + array('datecreated', 'default', 'value' => date("Y-m-d")), + array('startdate', 'default', 'value' => null), + array('expires', 'default', 'value' => null), array('admin,faxto', 'LSYii_Validators'), - array('admin', 'length', 'min' => 1, 'max'=>50), - array('faxto', 'length', 'min' => 0, 'max'=>20), - array('adminemail', 'filter', 'filter'=>'trim'), - array('bounce_email', 'filter', 'filter'=>'trim'), + array('admin', 'length', 'min' => 1, 'max' => 50), + array('faxto', 'length', 'min' => 0, 'max' => 20), + array('adminemail', 'filter', 'filter' => 'trim'), + array('bounce_email', 'filter', 'filter' => 'trim'), //array('bounce_email', 'LSYii_EmailIDNAValidator', 'allowEmpty'=>true), - array('active', 'in', 'range'=>array('Y', 'N'), 'allowEmpty'=>true), - array('gsid', 'numerical', 'min'=>'0', 'allowEmpty'=>true), - array('anonymized', 'in', 'range'=>array('Y', 'N', 'I'), 'allowEmpty'=>true), - array('savetimings', 'in', 'range'=>array('Y', 'N', 'I'), 'allowEmpty'=>true), - array('datestamp', 'in', 'range'=>array('Y', 'N', 'I'), 'allowEmpty'=>true), - array('usecookie', 'in', 'range'=>array('Y', 'N', 'I'), 'allowEmpty'=>true), - array('allowregister', 'in', 'range'=>array('Y', 'N', 'I'), 'allowEmpty'=>true), - array('allowsave', 'in', 'range'=>array('Y', 'N', 'I'), 'allowEmpty'=>true), - array('autoredirect', 'in', 'range'=>array('Y', 'N', 'I'), 'allowEmpty'=>true), - array('allowprev', 'in', 'range'=>array('Y', 'N', 'I'), 'allowEmpty'=>true), - array('printanswers', 'in', 'range'=>array('Y', 'N', 'I'), 'allowEmpty'=>true), - array('ipaddr', 'in', 'range'=>array('Y', 'N', 'I'), 'allowEmpty'=>true), - array('refurl', 'in', 'range'=>array('Y', 'N', 'I'), 'allowEmpty'=>true), - array('publicstatistics', 'in', 'range'=>array('Y', 'N', 'I'), 'allowEmpty'=>true), - array('publicgraphs', 'in', 'range'=>array('Y', 'N', 'I'), 'allowEmpty'=>true), - array('listpublic', 'in', 'range'=>array('Y', 'N', 'I'), 'allowEmpty'=>true), - array('htmlemail', 'in', 'range'=>array('Y', 'N', 'I'), 'allowEmpty'=>true), - array('sendconfirmation', 'in', 'range'=>array('Y', 'N', 'I'), 'allowEmpty'=>true), - array('tokenanswerspersistence', 'in', 'range'=>array('Y', 'N', 'I'), 'allowEmpty'=>true), - array('assessments', 'in', 'range'=>array('Y', 'N', 'I'), 'allowEmpty'=>true), - array('usetokens', 'in', 'range'=>array('Y', 'N'), 'allowEmpty'=>true), - array('showxquestions', 'in', 'range'=>array('Y', 'N', 'I'), 'allowEmpty'=>true), - array('shownoanswer', 'in', 'range'=>array('Y', 'N', 'I'), 'allowEmpty'=>true), - array('showwelcome', 'in', 'range'=>array('Y', 'N', 'I'), 'allowEmpty'=>true), - array('showsurveypolicynotice', 'in', 'range'=>array('0', '1', '2'), 'allowEmpty'=>true), - array('showprogress', 'in', 'range'=>array('Y', 'N', 'I'), 'allowEmpty'=>true), - array('questionindex', 'numerical', 'min' => -1, 'max' => 2, 'allowEmpty'=>false), - array('nokeyboard', 'in', 'range'=>array('Y', 'N', 'I'), 'allowEmpty'=>true), - array('alloweditaftercompletion', 'in', 'range'=>array('Y', 'N', 'I'), 'allowEmpty'=>true), - array('bounceprocessing', 'in', 'range'=>array('L', 'N', 'G'), 'allowEmpty'=>true), - array('usecaptcha', 'in', 'range'=>array('A', 'B', 'C', 'D', 'X', 'R', 'S', 'N', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'O', 'P', 'T', 'U', '1', '2', '3', '4', '5', '6'), 'allowEmpty'=>true), - array('showgroupinfo', 'in', 'range'=>array('B', 'N', 'D', 'X', 'I'), 'allowEmpty'=>true), - array('showqnumcode', 'in', 'range'=>array('B', 'N', 'C', 'X', 'I'), 'allowEmpty'=>true), - array('format', 'in', 'range'=>array('G', 'S', 'A', 'I'), 'allowEmpty'=>true), - array('googleanalyticsstyle', 'numerical', 'integerOnly'=>true, 'min'=>'0', 'max'=>'3', 'allowEmpty'=>true), - array('autonumber_start', 'numerical', 'integerOnly'=>true, 'allowEmpty'=>true), - array('tokenlength', 'default', 'value'=>15), - array('tokenlength', 'numerical', 'integerOnly'=>true, 'allowEmpty'=>false, 'min'=>'-1', 'max'=>'35'), - array('bouncetime', 'numerical', 'integerOnly'=>true, 'allowEmpty'=>true), - array('navigationdelay', 'numerical', 'integerOnly'=>true, 'allowEmpty'=>true), - array('template', 'filter', 'filter'=>array($this, 'filterTemplateSave')), - array('language', 'LSYii_Validators', 'isLanguage'=>true), + array('active', 'in', 'range' => array('Y', 'N'), 'allowEmpty' => true), + array('gsid', 'numerical', 'min' => '0', 'allowEmpty' => true), + array('anonymized', 'in', 'range' => array('Y', 'N', 'I'), 'allowEmpty' => true), + array('savetimings', 'in', 'range' => array('Y', 'N', 'I'), 'allowEmpty' => true), + array('datestamp', 'in', 'range' => array('Y', 'N', 'I'), 'allowEmpty' => true), + array('usecookie', 'in', 'range' => array('Y', 'N', 'I'), 'allowEmpty' => true), + array('allowregister', 'in', 'range' => array('Y', 'N', 'I'), 'allowEmpty' => true), + array('allowsave', 'in', 'range' => array('Y', 'N', 'I'), 'allowEmpty' => true), + array('autoredirect', 'in', 'range' => array('Y', 'N', 'I'), 'allowEmpty' => true), + array('allowprev', 'in', 'range' => array('Y', 'N', 'I'), 'allowEmpty' => true), + array('printanswers', 'in', 'range' => array('Y', 'N', 'I'), 'allowEmpty' => true), + array('ipaddr', 'in', 'range' => array('Y', 'N', 'I'), 'allowEmpty' => true), + array('refurl', 'in', 'range' => array('Y', 'N', 'I'), 'allowEmpty' => true), + array('publicstatistics', 'in', 'range' => array('Y', 'N', 'I'), 'allowEmpty' => true), + array('publicgraphs', 'in', 'range' => array('Y', 'N', 'I'), 'allowEmpty' => true), + array('listpublic', 'in', 'range' => array('Y', 'N', 'I'), 'allowEmpty' => true), + array('htmlemail', 'in', 'range' => array('Y', 'N', 'I'), 'allowEmpty' => true), + array('sendconfirmation', 'in', 'range' => array('Y', 'N', 'I'), 'allowEmpty' => true), + array('tokenanswerspersistence', 'in', 'range' => array('Y', 'N', 'I'), 'allowEmpty' => true), + array('assessments', 'in', 'range' => array('Y', 'N', 'I'), 'allowEmpty' => true), + array('usetokens', 'in', 'range' => array('Y', 'N'), 'allowEmpty' => true), + array('showxquestions', 'in', 'range' => array('Y', 'N', 'I'), 'allowEmpty' => true), + array('shownoanswer', 'in', 'range' => array('Y', 'N', 'I'), 'allowEmpty' => true), + array('showwelcome', 'in', 'range' => array('Y', 'N', 'I'), 'allowEmpty' => true), + array('showsurveypolicynotice', 'in', 'range' => array('0', '1', '2'), 'allowEmpty' => true), + array('showprogress', 'in', 'range' => array('Y', 'N', 'I'), 'allowEmpty' => true), + array('questionindex', 'numerical', 'min' => -1, 'max' => 2, 'allowEmpty' => false), + array('nokeyboard', 'in', 'range' => array('Y', 'N', 'I'), 'allowEmpty' => true), + array('alloweditaftercompletion', 'in', 'range' => array('Y', 'N', 'I'), 'allowEmpty' => true), + array('bounceprocessing', 'in', 'range' => array('L', 'N', 'G'), 'allowEmpty' => true), + array('usecaptcha', 'in', 'range' => array('A', 'B', 'C', 'D', 'X', 'R', 'S', 'N', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'O', 'P', 'T', 'U', '1', '2', '3', '4', '5', '6'), 'allowEmpty' => true), + array('showgroupinfo', 'in', 'range' => array('B', 'N', 'D', 'X', 'I'), 'allowEmpty' => true), + array('showqnumcode', 'in', 'range' => array('B', 'N', 'C', 'X', 'I'), 'allowEmpty' => true), + array('format', 'in', 'range' => array('G', 'S', 'A', 'I'), 'allowEmpty' => true), + array('googleanalyticsstyle', 'numerical', 'integerOnly' => true, 'min' => '0', 'max' => '3', 'allowEmpty' => true), + array('autonumber_start', 'numerical', 'integerOnly' => true, 'allowEmpty' => true), + array('tokenlength', 'default', 'value' => 15), + array('tokenlength', 'numerical', 'integerOnly' => true, 'allowEmpty' => false, 'min' => '-1', 'max' => '35'), + array('bouncetime', 'numerical', 'integerOnly' => true, 'allowEmpty' => true), + array('navigationdelay', 'numerical', 'integerOnly' => true, 'allowEmpty' => true), + array('template', 'filter', 'filter' => array($this, 'filterTemplateSave')), + array('language', 'LSYii_Validators', 'isLanguage' => true), array('language', 'required', 'on' => 'insert'), - array('language', 'filter', 'filter'=>'trim'), - array('additional_languages', 'filter', 'filter'=>'trim'), - array('additional_languages', 'LSYii_Validators', 'isLanguageMulti'=>true), - array('running', 'safe', 'on'=>'search'), + array('language', 'filter', 'filter' => 'trim'), + array('additional_languages', 'filter', 'filter' => 'trim'), + array('additional_languages', 'LSYii_Validators', 'isLanguageMulti' => true), + array('running', 'safe', 'on' => 'search'), // Date rules currently don't work properly with MSSQL, deactivating for now // array('expires','date', 'format'=>array('yyyy-MM-dd', 'yyyy-MM-dd HH:mm', 'yyyy-MM-dd HH:mm:ss',), 'allowEmpty'=>true), // array('startdate','date', 'format'=>array('yyyy-MM-dd', 'yyyy-MM-dd HH:mm', 'yyyy-MM-dd HH:mm:ss',), 'allowEmpty'=>true), @@ -555,10 +554,10 @@ public function afterFindSurvey() $aAttributes = array_keys($this->getAttributes()); foreach ($aAttributes as $attribute) { if (!is_null($event->get($attribute))) { - $this->setAttribute($attribute,$event->get($attribute)); + $this->setAttribute($attribute, $event->get($attribute)); } } - if ($this->template != 'inherit'){ + if ($this->template != 'inherit') { $this->template = Template::templateNameFilter($this->template); } /* this is fixed, setOptions for inherited after all */ @@ -585,12 +584,11 @@ public function filterTemplateSave($sTemplateName) $sTemplateName = 'inherit'; } } - if ($sTemplateName == 'inherit'){ + if ($sTemplateName == 'inherit') { return $sTemplateName; } else { return Template::templateNameFilter($sTemplateName); } - } @@ -676,7 +674,7 @@ public function getTokenAttributes() 'mandatory' => 'N', 'encrypted' => 'N', 'show_register' => 'N', - 'cpdbmap' =>'' + 'cpdbmap' => '' ); $languagesettings[$fieldname] = $desc; } @@ -698,7 +696,7 @@ public function getTokenAttributes() // We remove deleted attribute even if deleted manually in DB } $aCompleteData = array(); - foreach ($allKnowAttributes as $sKey=>$aValues) { + foreach ($allKnowAttributes as $sKey => $aValues) { if (preg_match("/^attribute_[0-9]{1,}$/", $sKey)) { // Select only extra attributes here if (!is_array($aValues)) { $aValues = array(); @@ -709,7 +707,7 @@ public function getTokenAttributes() 'mandatory' => 'N', 'encrypted' => 'N', 'show_register' => 'N', - 'cpdbmap' =>'' + 'cpdbmap' => '' ), $aValues); } } @@ -722,7 +720,7 @@ public function getTokenAttributes() */ public function getTokensTableName() { - return "{{tokens_".$this->primaryKey."}}"; + return "{{tokens_" . $this->primaryKey . "}}"; } /** @@ -731,7 +729,7 @@ public function getTokensTableName() */ public function getTimingsTableName() { - return "{{survey_".$this->primaryKey."_timings}}"; + return "{{survey_" . $this->primaryKey . "_timings}}"; } /** @@ -740,7 +738,7 @@ public function getTimingsTableName() */ public function getResponsesTableName() { - return '{{survey_'.$this->primaryKey.'}}'; + return '{{survey_' . $this->primaryKey . '}}'; } @@ -785,7 +783,7 @@ public function getGoogleanalyticsapikeysetting() { if ($this->googleanalyticsapikey === "9999useGlobal9999") { return "G"; - } else if ($this->googleanalyticsapikey == "") { + } elseif ($this->googleanalyticsapikey == "") { return "N"; } else { return "Y"; @@ -794,16 +792,16 @@ public function getGoogleanalyticsapikeysetting() /** * Sets Google Analytics API Key Setting. - * + * * @param string $value Google Analytics Key - * + * * @return void */ public function setGoogleanalyticsapikeysetting($value) { if ($value == "G") { $this->googleanalyticsapikey = "9999useGlobal9999"; - } else if ($value == "N") { + } elseif ($value == "N") { $this->googleanalyticsapikey = ""; } } @@ -823,7 +821,7 @@ public function getGoogleanalyticsapikey() /** * Returns Survey Template Configuration. - * + * * @return TemplateConfiguration */ public function getSurveyTemplateConfiguration() @@ -834,9 +832,9 @@ public function getSurveyTemplateConfiguration() /** * Returns the name of the template to be used for the survey. * It resolves inheritance from group and from default settings. - * + * * @return string - * + * * @todo: Cache this on a private attribute? */ public function getTemplateEffectiveName() @@ -847,13 +845,13 @@ public function getTemplateEffectiveName() $sTemplateName = $this->template; // if it is "inherit", get template name form group - if ($sTemplateName == 'inherit') { + if ($sTemplateName == 'inherit') { if (!empty($this->oOptions->template)) { $sTemplateName = $this->oOptions->template; } else { throw new CException("Unable to get a template name from group for survey {$this->sid}"); } - } + } return $sTemplateName; } @@ -863,14 +861,14 @@ public function getTemplateEffectiveName() * * @todo this function can go directly into Surveymenu, why implemted it here? ($this is used here ...) * This will be made bigger in future releases, but right now it only collects the default menu-entries - * + * * @param string $position Position - * + * * @return array */ public function getSurveyMenus($position = '') { - $collapsed = $position==='collapsed'; + $collapsed = $position === 'collapsed'; //Get the default menus $aDefaultSurveyMenus = Surveymenu::model()->getDefaultSurveyMenus($position, $this); //get all survey specific menus @@ -902,9 +900,9 @@ public function insertNewSurvey($aData) if (empty($aData['sid'])) { $aData['sid'] = intval(randomChars(6, '123456789')); } - $survey = new self; + $survey = new self(); /* Remove NULL value (default for not submitted data ) : insert must leave default if not set in POST */ - $aData = array_filter($aData, function($value) { + $aData = array_filter($aData, function ($value) { return !is_null($value); }); foreach ($aData as $k => $v) { @@ -1085,7 +1083,7 @@ public function getState() // And what happen if $sStop < $sStart : must return something other ? return 'willRun'; } - if(!is_null($sStop)) { + if (!is_null($sStop)) { return 'willExpire'; } } @@ -1120,14 +1118,14 @@ public function getRunning() // If the survey is not active, no date test is needed if ($this->active == 'N') { - $running = ''.gT('Inactive').'"'; + $running = '' . gT('Inactive') . '"'; } // If it's active, then we check if not expired elseif ($this->expires != '' || $this->startdate != '') { // Time adjust $sNow = date("Y-m-d H:i:s", strtotime(Yii::app()->getConfig('timeadjust'), strtotime(date("Y-m-d H:i:s")))); - $sStop = ($this->expires != '') ?date("Y-m-d H:i:s", strtotime(Yii::app()->getConfig('timeadjust'), strtotime($this->expires))) : $sNow; - $sStart = ($this->startdate != '') ?date("Y-m-d H:i:s", strtotime(Yii::app()->getConfig('timeadjust'), strtotime($this->startdate))) : $sNow; + $sStop = ($this->expires != '') ? date("Y-m-d H:i:s", strtotime(Yii::app()->getConfig('timeadjust'), strtotime($this->expires))) : $sNow; + $sStart = ($this->startdate != '') ? date("Y-m-d H:i:s", strtotime(Yii::app()->getConfig('timeadjust'), strtotime($this->startdate))) : $sNow; // Time comparaison $oNow = new DateTime($sNow); @@ -1141,9 +1139,9 @@ public function getRunning() $sStart = convertToGlobalSettingFormat($sStart); // Icon generaton (for CGridView) - $sIconRunning = ''.sprintf(gT('End: %s'), $sStop).''; - $sIconExpired = ''.sprintf(gT('Expired: %s'), $sStop).''; - $sIconFuture = ''.sprintf(gT('Start: %s'), $sStart).''; + $sIconRunning = '' . sprintf(gT('End: %s'), $sStop) . ''; + $sIconExpired = '' . sprintf(gT('Expired: %s'), $sStop) . ''; + $sIconFuture = '' . sprintf(gT('Start: %s'), $sStart) . ''; // Icon parsing if ($bExpired || $bWillRun) { @@ -1155,12 +1153,11 @@ public function getRunning() } // If it's active, and doesn't have expire date, it's running else { - $running = ''.gT('Active').'"'; + $running = '' . gT('Active') . '"'; //$running = '
'; } return $running; - } /** @@ -1483,28 +1480,28 @@ public function getCountTotalAnswers() */ public function getbuttons() { - $sEditUrl = App()->createUrl("/surveyAdministration/rendersidemenulink/subaction/generalsettings/surveyid/".$this->sid); - $sStatUrl = App()->createUrl("/admin/statistics/sa/simpleStatistics/surveyid/".$this->sid); - $sAddGroup = App()->createUrl("/questionGroupsAdministration/add/surveyid/".$this->sid); - $sAddquestion = App()->createUrl("/questionAdministration/view/surveyid/".$this->sid); + $sEditUrl = App()->createUrl("/surveyAdministration/rendersidemenulink/subaction/generalsettings/surveyid/" . $this->sid); + $sStatUrl = App()->createUrl("/admin/statistics/sa/simpleStatistics/surveyid/" . $this->sid); + $sAddGroup = App()->createUrl("/questionGroupsAdministration/add/surveyid/" . $this->sid); + $sAddquestion = App()->createUrl("/questionAdministration/view/surveyid/" . $this->sid); $button = ''; if (Permission::model()->hasSurveyPermission($this->sid, 'survey', 'update')) { - $button .= ''.gT('General settings & texts').''; + $button .= '' . gT('General settings & texts') . ''; } if (Permission::model()->hasSurveyPermission($this->sid, 'statistics', 'read') && $this->active == 'Y') { - $button .= ''.gT('Statistics').''; + $button .= '' . gT('Statistics') . ''; } if (Permission::model()->hasSurveyPermission($this->sid, 'survey', 'create')) { if ($this->active != 'Y') { - $groupCount = QuestionGroup::model()->countByAttributes(array('sid' => $this->sid)); + $groupCount = QuestionGroup::model()->countByAttributes(array('sid' => $this->sid)); if ($groupCount > 0) { - $button .= ''.gT('Add new question').''; + $button .= '' . gT('Add new question') . ''; } else { - $button .= ''.gT('Add new group').''; + $button .= '' . gT('Add new group') . ''; } } } @@ -1525,36 +1522,36 @@ public function search() $sort = new CSort(); $sort->attributes = array( - 'survey_id'=>array( - 'asc'=>'t.sid asc', - 'desc'=>'t.sid desc', + 'survey_id' => array( + 'asc' => 't.sid asc', + 'desc' => 't.sid desc', ), - 'title'=>array( - 'asc'=>'correct_relation_defaultlanguage.surveyls_title asc', - 'desc'=>'correct_relation_defaultlanguage.surveyls_title desc', + 'title' => array( + 'asc' => 'correct_relation_defaultlanguage.surveyls_title asc', + 'desc' => 'correct_relation_defaultlanguage.surveyls_title desc', ), - 'creation_date'=>array( - 'asc'=>'t.datecreated asc', - 'desc'=>'t.datecreated desc', + 'creation_date' => array( + 'asc' => 't.datecreated asc', + 'desc' => 't.datecreated desc', ), - 'owner'=>array( - 'asc'=>'owner.users_name asc', - 'desc'=>'owner.users_name desc', + 'owner' => array( + 'asc' => 'owner.users_name asc', + 'desc' => 'owner.users_name desc', ), - 'anonymized_responses'=>array( - 'asc'=>'t.anonymized asc', - 'desc'=>'t.anonymized desc', + 'anonymized_responses' => array( + 'asc' => 't.anonymized asc', + 'desc' => 't.anonymized desc', ), - 'running'=>array( - 'asc'=>'t.active asc, t.expires asc', - 'desc'=>'t.active desc, t.expires desc', + 'running' => array( + 'asc' => 't.active asc, t.expires asc', + 'desc' => 't.active desc, t.expires desc', ), - 'group'=>array( + 'group' => array( 'asc' => 'surveygroup.title asc', 'desc' => 'surveygroup.title desc', ), @@ -1562,7 +1559,7 @@ public function search() ); $sort->defaultOrder = array('creation_date' => CSort::SORT_DESC); - $criteria = new LSDbCriteria; + $criteria = new LSDbCriteria(); $aWithRelations = array('correct_relation_defaultlanguage'); // Search filter @@ -1603,8 +1600,8 @@ public function search() if ($this->active == "R") { $criteria->compare("t.active", 'Y'); - $subCriteria1 = new CDbCriteria; - $subCriteria2 = new CDbCriteria; + $subCriteria1 = new CDbCriteria(); + $subCriteria2 = new CDbCriteria(); $subCriteria1->addCondition("'{$sNow}' > t.startdate", 'OR'); $subCriteria2->addCondition("'{$sNow}' < t.expires", 'OR'); $subCriteria1->addCondition('t.expires IS NULL', "OR"); @@ -1624,10 +1621,10 @@ public function search() $criteria->mergeWith($criteriaPerm, 'AND'); // $criteria->addCondition("t.blabla == 'blub'"); $dataProvider = new CActiveDataProvider('Survey', array( - 'sort'=>$sort, - 'criteria'=>$criteria, - 'pagination'=>array( - 'pageSize'=>$pageSize, + 'sort' => $sort, + 'criteria' => $criteria, + 'pagination' => array( + 'pageSize' => $pageSize, ), )); @@ -1643,16 +1640,15 @@ public function search() * @todo : create an event * @return CDbCriteria */ - protected static function getPermissionCriteria( $userid = null) + protected static function getPermissionCriteria($userid = null) { - if(!$userid) { + if (!$userid) { $userid = Yii::app()->user->id; } // Note: reflect Permission::hasPermission - $criteriaPerm = new CDbCriteria; + $criteriaPerm = new CDbCriteria(); $criteriaPerm->params = array(); if (!Permission::model()->hasGlobalPermission("surveys", 'read', $userid)) { - /* it's the owner of the survey */ $criteriaPerm->compare('t.owner_id', $userid, false); @@ -1660,7 +1656,8 @@ protected static function getPermissionCriteria( $userid = null) $criteriaPerm->mergeWith( array( 'join' => "LEFT JOIN {{permissions}} AS surveypermissions ON (surveypermissions.entity_id = t.sid AND surveypermissions.permission='survey' AND surveypermissions.entity='survey' AND surveypermissions.uid= :surveypermissionuserid) ", - )); + ) + ); $criteriaPerm->params[':surveypermissionuserid'] = $userid; $criteriaPerm->compare('surveypermissions.read_p', '1', false, 'OR'); @@ -1668,17 +1665,19 @@ protected static function getPermissionCriteria( $userid = null) $criteriaPerm->mergeWith( array( 'join' => "LEFT JOIN {{permissions}} AS surveysingrouppermissions ON (surveysingrouppermissions.entity_id = t.gsid AND surveysingrouppermissions.entity='surveysingroup' AND surveysingrouppermissions.uid= :surveysingrouppermissionuserid) ", - )); + ) + ); $criteriaPerm->params[':surveysingrouppermissionuserid'] = $userid; $criteriaPerm->compare('surveysingrouppermissions.read_p', '1', false, 'OR'); // This mean : update, export … didn't allow see in list /* Under condition : owner of group */ - if(App()->getConfig('ownerManageAllSurveysInGroup')) { + if (App()->getConfig('ownerManageAllSurveysInGroup')) { $criteriaPerm->mergeWith( array( 'join' => "LEFT JOIN {{surveys_groups}} AS surveysgroupsowner ON (surveysgroupsowner.gsid = t.gsid) ", - )); - $criteriaPerm->compare('surveysgroupsowner.owner_id',$userid , false, 'OR'); + ) + ); + $criteriaPerm->compare('surveysgroupsowner.owner_id', $userid, false, 'OR'); } } /* Place for a new event */ @@ -1695,7 +1694,7 @@ protected static function getPermissionCriteria( $userid = null) * 'X' = Only survey access * 'R' = Only registration * 'S' = Only save and load - * + * * 'E' = All inherited * 'F' = Inherited save and load + survey access + registration * 'G' = Inherited survey access + registration + save and load @@ -1703,7 +1702,7 @@ protected static function getPermissionCriteria( $userid = null) * 'I' = Inherited save and load + inherited survey access + registration * 'J' = Inherited survey access + inherited registration + save and load * 'K' = Inherited registration + inherited save and load + survey access - * + * * 'L' = Inherited survey access + save and load * 'M' = Inherited survey access + registration * 'O' = Inherited registration + survey access @@ -1713,7 +1712,7 @@ protected static function getPermissionCriteria( $userid = null) * '4' = Inherited survey access * '5' = Inherited save and load * '6' = Inherited registration - * + * * 'N' = None * * @return string One character that corresponds to captcha usage @@ -1726,7 +1725,7 @@ public static function saveTranscribeCaptchaOptions(Survey $oSurvey = null) $saveandload = App()->request->getPost('usecaptcha_saveandload', null); if ($surveyaccess === null && $registration === null && $saveandload === null) { - if ($oSurvey !== null){ + if ($oSurvey !== null) { return $oSurvey->usecaptcha; } } @@ -1799,15 +1798,15 @@ public function calculateEstimatedTime() //@TODO make the time_per_question variable user configureable $time_per_question = 0.5; $criteria = new CDbCriteria(); - $criteria->addCondition('sid = '.$this->sid); + $criteria->addCondition('sid = ' . $this->sid); $criteria->addCondition('parent_qid = 0'); - $criteria->addCondition('language = \''.$this->language.'\''); + $criteria->addCondition('language = \'' . $this->language . '\''); $baseQuestions = Question::model()->count($criteria); // Note: An array questions with one sub question is fetched as 1 base question + 1 sub question $criteria = new CDbCriteria(); - $criteria->addCondition('sid = '.$this->sid); + $criteria->addCondition('sid = ' . $this->sid); $criteria->addCondition('parent_qid != 0'); - $criteria->addCondition('language = \''.$this->language.'\''); + $criteria->addCondition('language = \'' . $this->language . '\''); $subQuestions = Question::model()->count($criteria); // Subquestions are worth less "time" than base questions $subQuestions = intval(($subQuestions - $baseQuestions) / 2); @@ -1821,10 +1820,10 @@ public function calculateEstimatedTime() */ public static function getSurveysWithTokenTable() { - $surveys = self::model()->with(array('languagesettings'=>array('condition'=>'surveyls_language=language'), 'owner'))->findAll(); - $surveys = array_filter($surveys, function($s) - { -return $s->hasTokensTable; }); + $surveys = self::model()->with(array('languagesettings' => array('condition' => 'surveyls_language=language'), 'owner'))->findAll(); + $surveys = array_filter($surveys, function ($s) { + return $s->hasTokensTable; + }); return $surveys; } @@ -1835,11 +1834,11 @@ public function fixInvalidQuestions() { /* Delete invalid questions (don't exist in primary language) using qid like column name*/ $validQuestion = Question::model()->findAll(array( - 'select'=>'qid', - 'condition'=>'sid=:sid AND parent_qid = 0', - 'params'=>array('sid' => $this->sid) + 'select' => 'qid', + 'condition' => 'sid=:sid AND parent_qid = 0', + 'params' => array('sid' => $this->sid) )); - $criteria = new CDbCriteria; + $criteria = new CDbCriteria(); $criteria->compare('sid', $this->sid); $criteria->addCondition('parent_qid = 0'); $criteria->addNotInCondition('qid', CHtml::listData($validQuestion, 'qid', 'qid')); @@ -1847,11 +1846,11 @@ public function fixInvalidQuestions() /* Delete invalid Sub questions (don't exist in primary language) using title like column name*/ $validSubQuestion = Question::model()->findAll(array( - 'select'=>'title', - 'condition'=>'sid=:sid AND parent_qid != 0', - 'params'=>array('sid' => $this->sid) + 'select' => 'title', + 'condition' => 'sid=:sid AND parent_qid != 0', + 'params' => array('sid' => $this->sid) )); - $criteria = new CDbCriteria; + $criteria = new CDbCriteria(); $criteria->compare('sid', $this->sid); $criteria->addCondition('parent_qid != 0'); $criteria->addNotInCondition('title', CHtml::listData($validSubQuestion, 'title', 'title')); @@ -1914,7 +1913,8 @@ public function getBaseQuestions() return $questions; } - private function getSurveyQuestionsCriteria(){ + private function getSurveyQuestionsCriteria() + { $criteria = $this->getQuestionOrderCriteria(); $criteria->addColumnCondition(array( 't.sid' => $this->sid, @@ -1928,15 +1928,15 @@ private function getSurveyQuestionsCriteria(){ */ private function getQuestionOrderCriteria() { - $criteria = new CDbCriteria; + $criteria = new CDbCriteria(); $criteria->select = Yii::app()->db->quoteColumnName('t.*'); $criteria->with = array( 'survey.groups', ); - if (Yii::app()->db->driverName == 'sqlsrv' || Yii::app()->db->driverName == 'dblib'){ + if (Yii::app()->db->driverName == 'sqlsrv' || Yii::app()->db->driverName == 'dblib') { $criteria->order = Yii::app()->db->quoteColumnName('t.question_order'); } else { - $criteria->order = Yii::app()->db->quoteColumnName('groups.group_order').','.Yii::app()->db->quoteColumnName('t.question_order'); + $criteria->order = Yii::app()->db->quoteColumnName('groups.group_order') . ',' . Yii::app()->db->quoteColumnName('t.question_order'); } $criteria->addCondition('groups.gid=t.gid', 'AND'); return $criteria; @@ -1947,7 +1947,7 @@ private function getQuestionOrderCriteria() */ public function getGroupsCount() { - return QuestionGroup::model()->countByAttributes(['sid'=>$this->sid]); + return QuestionGroup::model()->countByAttributes(['sid' => $this->sid]); } /** @@ -1955,7 +1955,7 @@ public function getGroupsCount() */ public function getCountTotalQuestions() { - $condn = array('sid'=>$this->sid, 'parent_qid'=>0); + $condn = array('sid' => $this->sid, 'parent_qid' => 0); $sumresult = Question::model()->countByAttributes($condn); return (int) $sumresult; } @@ -1967,9 +1967,9 @@ public function getCountTotalQuestions() public function getCountNoInputQuestions() { $condn = array( - 'sid'=>$this->sid, - 'parent_qid'=>0, - 'type'=>['X', '*'], + 'sid' => $this->sid, + 'parent_qid' => 0, + 'type' => ['X', '*'], ); $sumresult = Question::model()->countByAttributes($condn); return (int) $sumresult; @@ -2019,31 +2019,31 @@ public function hasQuestionType($type, $includeSubquestions = false) return $result !== false; } - public static function replacePolicyLink($dataSecurityNoticeLabel, $surveyId) { + public static function replacePolicyLink($dataSecurityNoticeLabel, $surveyId) + { $STARTPOLICYLINK = ""; $ENDPOLICYLINK = ""; - if(self::model()->findByPk($surveyId)->showsurveypolicynotice == 2){ - $STARTPOLICYLINK = ""; + if (self::model()->findByPk($surveyId)->showsurveypolicynotice == 2) { + $STARTPOLICYLINK = ""; $ENDPOLICYLINK = ""; - if(!preg_match('/(\{STARTPOLICYLINK\}|\{ENDPOLICYLINK\})/', $dataSecurityNoticeLabel)){ - $dataSecurityNoticeLabel.= "
{STARTPOLICYLINK}".gT("Show policy")."{ENDPOLICYLINK}"; + if (!preg_match('/(\{STARTPOLICYLINK\}|\{ENDPOLICYLINK\})/', $dataSecurityNoticeLabel)) { + $dataSecurityNoticeLabel .= "
{STARTPOLICYLINK}" . gT("Show policy") . "{ENDPOLICYLINK}"; } } - $dataSecurityNoticeLabel = preg_replace('/\{STARTPOLICYLINK\}/', $STARTPOLICYLINK ,$dataSecurityNoticeLabel); + $dataSecurityNoticeLabel = preg_replace('/\{STARTPOLICYLINK\}/', $STARTPOLICYLINK, $dataSecurityNoticeLabel); $countEndLabel = 0; - $dataSecurityNoticeLabel = preg_replace('/\{ENDPOLICYLINK\}/', $ENDPOLICYLINK ,$dataSecurityNoticeLabel, -1, $countEndLabel); - if($countEndLabel == 0){ + $dataSecurityNoticeLabel = preg_replace('/\{ENDPOLICYLINK\}/', $ENDPOLICYLINK, $dataSecurityNoticeLabel, -1, $countEndLabel); + if ($countEndLabel == 0) { $dataSecurityNoticeLabel .= ''; } return $dataSecurityNoticeLabel; - } /** @@ -2051,12 +2051,13 @@ public static function replacePolicyLink($dataSecurityNoticeLabel, $surveyId) { * @param bool $includeSubquestions * @return Question */ - public function findQuestionByType($type, $includeSubquestions = false){ + public function findQuestionByType($type, $includeSubquestions = false) + { $criteria = $this->getSurveyQuestionsCriteria(); - if ($includeSubquestions){ + if ($includeSubquestions) { $criteria->addColumnCondition(['parent_qid' => 0]); } - $criteria->addColumnCondition(['type'=>$type]); + $criteria->addColumnCondition(['type' => $type]); return Question::model()->find($criteria); } @@ -2067,7 +2068,7 @@ public function findQuestionByType($type, $includeSubquestions = false){ public function getTokenEncryptionOptions() { $aOptions = json_decode_ls($this->tokenencryptionoptions); - if (empty($aOptions)){ + if (empty($aOptions)) { $aOptions = Token::getDefaultEncryptionOptions(); } return $aOptions; @@ -2084,13 +2085,12 @@ public function setTokenEncryptionOptions($options) public function setOptions($gsid = 1) { $instance = SurveysGroupsettings::getInstance($gsid, $this, null, 1, $this->bShowRealOptionValues); - if ($instance){ + if ($instance) { $this->oOptions = $instance->oOptions; $this->oOptionLabels = $instance->oOptionLabels; $this->aOptions = (array) $instance->oOptions; $this->showInherited = $instance->showInherited; } - } public function setOptionsFromDatabase() @@ -2103,9 +2103,9 @@ public function setOptionsFromDatabase() public function setToInherit() { $settings = new SurveysGroupsettings(); - $settings->setToInherit(); + $settings->setToInherit(); // set Survey attributes to 'inherit' values - foreach ($settings as $key => $value){ + foreach ($settings as $key => $value) { $this->$key = $value; } } @@ -2130,7 +2130,7 @@ public function getOwnerId() /** * @inheritdoc - * @todo use it in surveyspermission + * @todo use it in surveyspermission */ public static function getMinimalPermissionRead() { @@ -2241,7 +2241,7 @@ public static function getPermissionData() } /** - * @inheritdoc + * @inheritdoc */ public function hasPermission($sPermission, $sCRUD = 'read', $iUserID = null) { @@ -2257,7 +2257,7 @@ public function hasPermission($sPermission, $sCRUD = 'read', $iUserID = null) return true; } /* Inherited by SurveysInGroup */ - if(SurveysInGroup::model()->findByPk($this->gsid)->hasPermission($sPermission, $sGlobalCRUD, $iUserID)) { + if (SurveysInGroup::model()->findByPk($this->gsid)->hasPermission($sPermission, $sGlobalCRUD, $iUserID)) { return true; } return Permission::model()->hasPermission($this->getPrimaryKey(), 'survey', $sPermission, $sCRUD, $iUserID); @@ -2274,7 +2274,7 @@ public function findAllPublic() $aSurveys = $this->findAll($oCriteria); $aSurveys = array_filter( $aSurveys, - function($s) { + function ($s) { return $s->isListPublic; } ); diff --git a/application/models/SurveyActivator.php b/application/models/SurveyActivator.php index 9a36dc63af8..f0fcf030bb1 100644 --- a/application/models/SurveyActivator.php +++ b/application/models/SurveyActivator.php @@ -49,29 +49,29 @@ public function activate() $this->setMySQLDefaultEngine(Yii::app()->getConfig('mysqlEngine')); if (!$this->showEventMessages($event)) { - return ['error'=>'plugin']; + return ['error' => 'plugin']; } $this->prepareResponsesTable(); if ($this->isSimulation) { return array( - 'dbengine'=>Yii::app()->db->getDriverName(), - 'dbtype'=>Yii::app()->db->driverName, - 'fields'=>$this->tableDefinition + 'dbengine' => Yii::app()->db->getDriverName(), + 'dbtype' => Yii::app()->db->driverName, + 'fields' => $this->tableDefinition ); } if (!$this->createResponseTable()) { - return ['error'=>$this->error]; + return ['error' => $this->error]; } if (!$this->createTimingsTable()) { - return ['error'=>'timingstablecreation']; + return ['error' => 'timingstablecreation']; } if (!empty($this->error)) { - return ['error'=>$this->error]; + return ['error' => $this->error]; } Yii::app()->db->createCommand()->update( @@ -184,7 +184,7 @@ protected function prepareTableDefinition(string $collation, array $sFieldMap) } break; case "token": - $aTableDefinition[$aRow['fieldname']] = 'string(' . Token::MAX_LENGTH . ')'.$collation; + $aTableDefinition[$aRow['fieldname']] = 'string(' . Token::MAX_LENGTH . ')' . $collation; break; case Question::QT_ASTERISK_EQUATION: $aTableDefinition[$aRow['fieldname']] = isset($aRow['answertabledefinition']) && !empty($aRow['answertabledefinition']) ? $aRow['answertabledefinition'] : "text"; @@ -218,7 +218,7 @@ protected function prepareTableDefinition(string $collation, array $sFieldMap) $aTableDefinition[$aRow['fieldname']] = (array_key_exists('encrypted', $aRow) && $aRow['encrypted'] == 'Y') ? "text" : (isset($aRow['answertabledefinition']) && !empty($aRow['answertabledefinition']) ? $aRow['answertabledefinition'] : "string(5)"); } if (!$this->survey->isAnonymized && !array_key_exists('token', $aTableDefinition)) { - $aTableDefinition['token'] = 'string('.Token::MAX_LENGTH.')'.$collation; + $aTableDefinition['token'] = 'string(' . Token::MAX_LENGTH . ')' . $collation; } } $this->tableDefinition = $aTableDefinition; @@ -254,9 +254,11 @@ protected function getCollation() if (Yii::app()->db->driverName == 'mysqli' || Yii::app()->db->driverName == 'mysql') { $collation = " COLLATE 'utf8mb4_bin'"; } - if (Yii::app()->db->driverName == 'sqlsrv' + if ( + Yii::app()->db->driverName == 'sqlsrv' || Yii::app()->db->driverName == 'dblib' - || Yii::app()->db->driverName == 'mssql') { + || Yii::app()->db->driverName == 'mssql' + ) { $collation = " COLLATE SQL_Latin1_General_CP1_CS_AS"; } return $collation; @@ -319,7 +321,7 @@ protected function createResponseTable() try { if (isset($this->tableDefinition['token'])) { Yii::app()->db->createCommand()->createIndex( - "idx_survey_token_{$this->survey->primaryKey}_".rand(1, 50000), + "idx_survey_token_{$this->survey->primaryKey}_" . rand(1, 50000), $sTableName, 'token' ); @@ -359,7 +361,7 @@ protected function createResponseTableKeys() $iAutoNumberStart = Yii::app()->db->createCommand() ->select('autonumber_start') ->from(Survey::model()->tableName()) - ->where('sid=:sid', [':sid'=>$this->survey->primaryKey]) + ->where('sid=:sid', [':sid' => $this->survey->primaryKey]) ->queryScalar(); //if there is an autonumber_start field, start auto numbering here @@ -370,7 +372,7 @@ protected function createResponseTableKeys() Yii::app()->db->createCommand($sQuery)->execute(); // Add back the primaryKey - Yii::app()->db->createCommand()->addPrimaryKey('PRIMARY_'.rand(1, 50000), $this->survey->responsesTableName, 'id'); + Yii::app()->db->createCommand()->addPrimaryKey('PRIMARY_' . rand(1, 50000), $this->survey->responsesTableName, 'id'); } elseif (Yii::app()->db->driverName == 'pgsql') { $sQuery = "SELECT setval(pg_get_serial_sequence('{$this->survey->responsesTableName}', 'id'),{$iAutoNumberStart},false);"; // FIXME @ not good @@ -410,11 +412,11 @@ protected function createSurveyDirectory() $iSurveyID = $this->survey->primaryKey; // create the survey directory where the uploaded files can be saved if ($this->createSurveyDir) { - if (!file_exists(Yii::app()->getConfig('uploaddir')."/surveys/".$iSurveyID."/files")) { - if (!(mkdir(Yii::app()->getConfig('uploaddir')."/surveys/".$iSurveyID."/files", 0777, true))) { + if (!file_exists(Yii::app()->getConfig('uploaddir') . "/surveys/" . $iSurveyID . "/files")) { + if (!(mkdir(Yii::app()->getConfig('uploaddir') . "/surveys/" . $iSurveyID . "/files", 0777, true))) { return false; } else { - file_put_contents(Yii::app()->getConfig('uploaddir')."/surveys/".$iSurveyID."/files/index.html", ''); + file_put_contents(Yii::app()->getConfig('uploaddir') . "/surveys/" . $iSurveyID . "/files/index.html", ''); } } } diff --git a/application/models/SurveyDynamic.php b/application/models/SurveyDynamic.php index d610859528f..4656853dc51 100644 --- a/application/models/SurveyDynamic.php +++ b/application/models/SurveyDynamic.php @@ -1,4 +1,6 @@ -getbHaveToken()) { TokenDynamic::sid(self::$sid); return array( - 'survey' => array(self::HAS_ONE, 'Survey', array(), 'condition'=>('sid = '.self::$sid)), + 'survey' => array(self::HAS_ONE, 'Survey', array(), 'condition' => ('sid = ' . self::$sid)), 'tokens' => array(self::HAS_ONE, 'TokenDynamic', array('token' => 'token')) ); } else { @@ -109,7 +111,7 @@ public function primaryKey() */ public function insertRecords($data) { - $record = new self; + $record = new self(); foreach ($data as $k => $v) { $search = array('`', "'"); $k = str_replace($search, '', $k); @@ -123,7 +125,6 @@ public function insertRecords($data) } catch (Exception $e) { return false; } - } /** @@ -137,12 +138,12 @@ public function insertRecords($data) */ public static function deleteSomeRecords($condition = false) { - $survey = new SurveyDynamic; - $criteria = new CDbCriteria; + $survey = new SurveyDynamic(); + $criteria = new CDbCriteria(); if ($condition) { foreach ($condition as $column => $value) { - return $criteria->addCondition($column."=`".$value."`"); + return $criteria->addCondition($column . "=`" . $value . "`"); } } @@ -165,7 +166,7 @@ public function addTimingCriteria($condition) } $alias = $this->getTableAlias(); - $newCriteria->join = "LEFT JOIN ".self::$survey->tokensTableName." survey_timings ON $alias.id = survey_timings.id"; + $newCriteria->join = "LEFT JOIN " . self::$survey->tokensTableName . " survey_timings ON $alias.id = survey_timings.id"; $newCriteria->select = 'survey_timings.*'; // Otherwise we don't get records from the survey participants table $newCriteria->mergeWith($criteria); @@ -187,7 +188,7 @@ public function addTokenCriteria($condition) $aSelect = array(); $alias = $this->getTableAlias(); foreach ($aSelectFields as $sField) { - $aSelect[] = "$alias.".Yii::app()->db->schema->quoteColumnName($sField); + $aSelect[] = "$alias." . Yii::app()->db->schema->quoteColumnName($sField); } $aSelectFields = $aSelect; $aSelectFields[] = "$alias.token"; @@ -196,7 +197,7 @@ public function addTokenCriteria($condition) $criteria->select = $aSelectFields; } - $newCriteria->join = "LEFT JOIN {{tokens_".self::$sid."}} tokens ON $alias.token = tokens.token"; + $newCriteria->join = "LEFT JOIN {{tokens_" . self::$sid . "}} tokens ON $alias.token = tokens.token"; $aTokenFields = Yii::app()->db->schema->getTable(self::$survey->tokensTableName)->getColumnNames(); $aTokenFields = array_diff($aTokenFields, array('token')); @@ -216,11 +217,11 @@ public static function countAllAndPartial($sid) $select = array( 'count(*) AS cntall', 'sum(CASE - WHEN '. Yii::app()->db->quoteColumnName('submitdate').' IS NULL THEN 1 + WHEN ' . Yii::app()->db->quoteColumnName('submitdate') . ' IS NULL THEN 1 ELSE 0 END) AS cntpartial', ); - $result = Yii::app()->db->createCommand()->select($select)->from('{{survey_'.$sid.'}}')->queryRow(); + $result = Yii::app()->db->createCommand()->select($select)->from('{{survey_' . $sid . '}}')->queryRow(); return $result; } @@ -245,7 +246,7 @@ public function isCompleted($srid) $data = Yii::app()->db->createCommand() ->select("submitdate") ->from($this->tableName()) - ->where('id=:id', array(':id'=>$srid)) + ->where('id=:id', array(':id' => $srid)) ->queryRow(); if ($data && $data['submitdate']) { $completed = true; @@ -274,65 +275,65 @@ public function getCompleted() */ public function getGridButtons() { - $sBrowseLanguage=sanitize_languagecode(Yii::app()->request->getParam('browselang', '')); + $sBrowseLanguage = sanitize_languagecode(Yii::app()->request->getParam('browselang', '')); /* detail button */ $gridButtons['detail'] = array( - 'label'=>''.gT("View response details").'', - 'imageUrl'=>false, - 'url' => 'App()->createUrl("/admin/responses/sa/view",array("surveyid"=>'.self::$sid.',"id"=>$data->id,"browselang"=>"'.$sBrowseLanguage.'"));', + 'label' => '' . gT("View response details") . '', + 'imageUrl' => false, + 'url' => 'App()->createUrl("/admin/responses/sa/view",array("surveyid"=>' . self::$sid . ',"id"=>$data->id,"browselang"=>"' . $sBrowseLanguage . '"));', 'options' => array( - 'class'=>"btn btn-default btn-xs", - 'target'=>"_blank", - 'data-toggle'=>"tooltip", - 'title'=>gT("View response details") + 'class' => "btn btn-default btn-xs", + 'target' => "_blank", + 'data-toggle' => "tooltip", + 'title' => gT("View response details") ), ); /* quexmlpdf button */ $gridButtons['quexmlpdf'] = array( - 'label'=>''.gT("View response details as queXML PDF").'', - 'imageUrl'=>false, - 'url' => 'App()->createUrl("/admin/responses/sa/viewquexmlpdf",array("surveyid"=>'.self::$sid.',"id"=>$data->id,"browselang"=>"'.$sBrowseLanguage.'"));', + 'label' => '' . gT("View response details as queXML PDF") . '', + 'imageUrl' => false, + 'url' => 'App()->createUrl("/admin/responses/sa/viewquexmlpdf",array("surveyid"=>' . self::$sid . ',"id"=>$data->id,"browselang"=>"' . $sBrowseLanguage . '"));', 'options' => array( - 'class'=>"btn btn-default btn-xs", - 'target'=>"_blank", - 'data-toggle'=>"tooltip", - 'title'=>gT("View response details as queXML PDF") + 'class' => "btn btn-default btn-xs", + 'target' => "_blank", + 'data-toggle' => "tooltip", + 'title' => gT("View response details as queXML PDF") ), ); /* edit button */ $baseVisible = intval(Permission::model()->hasSurveyPermission(self::$sid, 'responses', 'update')); $gridButtons['edit'] = array( - 'label'=>''.gT("Edit this response").'', - 'imageUrl'=>false, - 'url' => 'App()->createUrl("admin/dataentry/sa/editdata/subaction/edit",array("surveyid"=>'.self::$sid.',"id"=>$data->id,"browselang"=>"'.$sBrowseLanguage.'"));', + 'label' => '' . gT("Edit this response") . '', + 'imageUrl' => false, + 'url' => 'App()->createUrl("admin/dataentry/sa/editdata/subaction/edit",array("surveyid"=>' . self::$sid . ',"id"=>$data->id,"browselang"=>"' . $sBrowseLanguage . '"));', 'options' => array( - 'class'=>"btn btn-default btn-xs", - 'target'=>"_blank", - 'data-toggle'=>"tooltip", - 'title'=>gT("Edit this response") + 'class' => "btn btn-default btn-xs", + 'target' => "_blank", + 'data-toggle' => "tooltip", + 'title' => gT("Edit this response") ), - 'visible'=> 'boolval('.$baseVisible.')', + 'visible' => 'boolval(' . $baseVisible . ')', ); /* downloadfile button */ $baseVisible = intval(Permission::model()->hasSurveyPermission(self::$sid, 'responses', 'update') && hasFileUploadQuestion(self::$sid)); $gridButtons['downloadfiles'] = array( - 'label'=>''.gT("Download all files in this response as a zip file").'', - 'imageUrl'=>false, - 'url' => 'App()->createUrl("admin/responses/sa/actionDownloadfiles",array("surveyid"=>'.self::$sid.',"sResponseId"=>$data->id));', - 'visible'=> 'boolval('.$baseVisible.') && Response::model('.self::$sid.')->findByPk($data->id)->someFileExists()', + 'label' => '' . gT("Download all files in this response as a zip file") . '', + 'imageUrl' => false, + 'url' => 'App()->createUrl("admin/responses/sa/actionDownloadfiles",array("surveyid"=>' . self::$sid . ',"sResponseId"=>$data->id));', + 'visible' => 'boolval(' . $baseVisible . ') && Response::model(' . self::$sid . ')->findByPk($data->id)->someFileExists()', 'options' => array( - 'class'=>"btn btn-default btn-xs", - 'target'=>"_blank", - 'data-toggle'=>"tooltip", - 'title'=>gT("Download all files in this response as a zip file") + 'class' => "btn btn-default btn-xs", + 'target' => "_blank", + 'data-toggle' => "tooltip", + 'title' => gT("Download all files in this response as a zip file") ), ); /* deletefile button */ $gridButtons['deletefiles'] = array( - 'label'=>''.gT("Delete all files of this response").'', - 'imageUrl'=>false, - 'url' => 'App()->createUrl("admin/responses/sa/actionDeleteAttachments",array("surveyid"=>'.self::$sid.',"sResponseId"=>$data->id));', - 'visible'=> 'boolval('.$baseVisible.') && Response::model('.self::$sid.')->findByPk($data->id)->someFileExists()', + 'label' => '' . gT("Delete all files of this response") . '', + 'imageUrl' => false, + 'url' => 'App()->createUrl("admin/responses/sa/actionDeleteAttachments",array("surveyid"=>' . self::$sid . ',"sResponseId"=>$data->id));', + 'visible' => 'boolval(' . $baseVisible . ') && Response::model(' . self::$sid . ')->findByPk($data->id)->someFileExists()', 'options' => array( 'class' => "btn btn-default btn-xs btn-deletefiles", 'data-toggle' => "tooltip", @@ -343,10 +344,10 @@ public function getGridButtons() /* delete button */ $baseVisible = intval(Permission::model()->hasSurveyPermission(self::$sid, 'responses', 'delete')); $gridButtons['deleteresponse'] = array( - 'label'=>''.gT("Delete this response").'', - 'imageUrl'=>false, - 'url' => 'App()->createUrl("admin/responses/sa/actionDelete",array("surveyid"=>'.self::$sid.',"sResponseId"=>$data->id));', - 'visible'=> 'boolval('.$baseVisible.')', + 'label' => '' . gT("Delete this response") . '', + 'imageUrl' => false, + 'url' => 'App()->createUrl("admin/responses/sa/actionDelete",array("surveyid"=>' . self::$sid . ',"sResponseId"=>$data->id));', + 'visible' => 'boolval(' . $baseVisible . ')', 'options' => array( 'class' => "btn btn-default btn-xs btn-delete", 'data-toggle' => "tooltip", @@ -363,7 +364,7 @@ public function getGridButtons() /** * Get buttons HTML for response browse view. * @deprecated , use getGridButtons , - * + * * @return string HTML */ public function getButtons() @@ -386,34 +387,33 @@ public function getExtendedData($colName, $sLanguage, $base64jsonFieldMap) $sFullValue = strip_tags(getExtendedAnswer(self::$sid, $oFieldMap->fieldname, $value, $sLanguage)); if (strlen($sFullValue) > 50) { $sElipsizedValue = ellipsize($sFullValue, $this->ellipsize_question_value); - $sValue = ''.$sElipsizedValue.''; + $sValue = '' . $sElipsizedValue . ''; } else { $sValue = $sFullValue; } // Upload question if ($oFieldMap->type == Question::QT_VERTICAL_FILE_UPLOAD && strpos($oFieldMap->fieldname, 'filecount') === false) { - $sSurveyEntry = ""; $aQuestionAttributes = QuestionAttribute::model()->getQuestionAttributes($oFieldMap->qid); $aFilesInfo = json_decode_ls($this->$colName); for ($iFileIndex = 0; $iFileIndex < $aQuestionAttributes['max_num_of_files']; $iFileIndex++) { $sSurveyEntry .= ''; if (isset($aFilesInfo[$iFileIndex])) { - $sSurveyEntry .= ''; - $sSurveyEntry .= ''; + $sSurveyEntry .= ''; + $sSurveyEntry .= ''; if ($aQuestionAttributes['show_title']) { if (!isset($aFilesInfo[$iFileIndex]['title'])) { $aFilesInfo[$iFileIndex]['title'] = ''; } - $sSurveyEntry .= ''; + $sSurveyEntry .= ''; } if ($aQuestionAttributes['show_comment']) { if (!isset($aFilesInfo[$iFileIndex]['comment'])) { $aFilesInfo[$iFileIndex]['comment'] = ''; } - $sSurveyEntry .= ''; + $sSurveyEntry .= ''; } } $sSurveyEntry .= ''; @@ -440,7 +440,7 @@ public function exist($srid) $data = Yii::app()->db->createCommand() ->select("id") ->from($this->tableName()) - ->where('id=:id', array(':id'=>$srid)) + ->where('id=:id', array(':id' => $srid)) ->queryRow(); if ($data) { $exist = true; @@ -472,7 +472,7 @@ public function next($srId, $useFilterState = false) $data = Yii::app()->db->createCommand() ->select("id") ->from($this->tableName()) - ->where(array('and', $whereFilterState, 'id > :id'), array(':id'=>$srId)) + ->where(array('and', $whereFilterState, 'id > :id'), array(':id' => $srId)) ->order('id ASC') ->queryRow(); if ($data) { @@ -505,7 +505,7 @@ public function previous($srId, $useFilterState = false) $data = Yii::app()->db->createCommand() ->select("id") ->from($this->tableName()) - ->where(array('and', $whereFilterState, 'id < :id'), array(':id'=>$srId)) + ->where(array('and', $whereFilterState, 'id < :id'), array(':id' => $srId)) ->order('id DESC') ->queryRow(); if ($data) { @@ -533,7 +533,7 @@ public function timeline($sType, $dStart, $dEnd) if ($oSurvey['datestamp'] != 'Y') { return false; } else { - $criteria = new CDbCriteria; + $criteria = new CDbCriteria(); $criteria->select = 'submitdate'; $criteria->addCondition('submitdate >= :dstart'); $criteria->addCondition('submitdate <= :dend'); @@ -564,7 +564,7 @@ public function timeline($sType, $dStart, $dEnd) private function getbHaveToken() { if (!isset($this->bHaveToken)) { - $this->bHaveToken = tableExists('tokens_'.self::$sid) && Permission::model()->hasSurveyPermission(self::$sid, 'tokens', 'read'); // Boolean : show (or not) the token; + $this->bHaveToken = tableExists('tokens_' . self::$sid) && Permission::model()->hasSurveyPermission(self::$sid, 'tokens', 'read'); // Boolean : show (or not) the token; } return $this->bHaveToken; } @@ -578,12 +578,11 @@ public function getFirstNameForGrid() // decrypt token information ( if needed ) $tokens = $this->tokens; if (is_object($tokens)) { - if (!empty($tokens)){ + if (!empty($tokens)) { $tokens->decrypt(); } return $tokens->firstname; } - } /** @@ -604,9 +603,9 @@ public function getLastNameForGrid() public function getTokenForGrid() { if (is_object($this->tokens) && !is_null($this->tokens->tid)) { - $sToken = "'true'))."' data-toggle='tooltip' title='".gT("Edit this survey participant")."'>".CHtml::encode($this->token)."   "; + $sToken = " 'true')) . "' data-toggle='tooltip' title='" . gT("Edit this survey participant") . "'>" . CHtml::encode($this->token) . "   "; } else { - $sToken = ''.CHtml::encode($this->token).''; + $sToken = '' . CHtml::encode($this->token) . ''; } return $sToken; @@ -650,8 +649,8 @@ public function search() { $pageSize = Yii::app()->user->getState('pageSize', Yii::app()->params['defaultPageSize']); - $criteria = new CDbCriteria; - $sort = new CSort; + $criteria = new CDbCriteria(); + $sort = new CSort(); $sort->defaultOrder = 'id ASC'; // Make all the model's columns sortable (default behaviour) @@ -681,18 +680,18 @@ public function search() // When selection of responses come from statistics // TODO: This provide a first step to enable the old jQgrid selector system, and could be use for users and tokens - if (Yii::app()->user->getState('sql_'.self::$sid) != null) { - $criteria->condition .= Yii::app()->user->getState('sql_'.self::$sid); + if (Yii::app()->user->getState('sql_' . self::$sid) != null) { + $criteria->condition .= Yii::app()->user->getState('sql_' . self::$sid); } $this->filterColumns($criteria); $dataProvider = new LSCActiveDataProvider('SurveyDynamic', array( - 'sort'=>$sort, - 'criteria'=>$criteria, - 'pagination'=>array( - 'pageSize'=>$pageSize, + 'sort' => $sort, + 'criteria' => $criteria, + 'pagination' => array( + 'pageSize' => $pageSize, ), )); @@ -707,24 +706,24 @@ public function search() protected function joinWithToken(CDbCriteria $criteria, CSort $sort) { $criteria->compare('t.token', $this->token, true); - $criteria->join = "LEFT JOIN {{tokens_".self::$sid."}} as tokens ON t.token = tokens.token"; + $criteria->join = "LEFT JOIN {{tokens_" . self::$sid . "}} as tokens ON t.token = tokens.token"; $criteria->compare('tokens.firstname', $this->firstname_filter, true); $criteria->compare('tokens.lastname', $this->lastname_filter, true); $criteria->compare('tokens.email', $this->email_filter, true); // Add the related token model's columns sortable $aSortVirtualAttributes = array( - 'tokens.firstname'=>array( - 'asc'=>'tokens.firstname ASC', - 'desc'=>'tokens.firstname DESC', + 'tokens.firstname' => array( + 'asc' => 'tokens.firstname ASC', + 'desc' => 'tokens.firstname DESC', ), 'tokens.lastname' => array( - 'asc'=>'lastname ASC', - 'desc'=>'lastname DESC' + 'asc' => 'lastname ASC', + 'desc' => 'lastname DESC' ), 'tokens.email' => array( - 'asc'=>'email ASC', - 'desc'=>'email DESC' + 'asc' => 'email ASC', + 'desc' => 'email DESC' ), ); @@ -752,14 +751,14 @@ protected function filterColumns(CDbCriteria $criteria) if ($column->dbType == 'decimal') { $this->$c1 = (float) $this->$c1; $criteria->compare(Yii::app()->db->quoteColumnName($c1), $this->$c1, false); - } else if ($isDatetime) { + } elseif ($isDatetime) { $s = DateTime::createFromFormat($dateFormatDetails['phpdate'], $this->$c1); if ($s === false) { // This happens when date is in wrong format continue; } $s2 = $s->format('Y-m-d'); - $criteria->addCondition('cast('.Yii::app()->db->quoteColumnName($c1).' as date) = \''.$s2.'\''); + $criteria->addCondition('cast(' . Yii::app()->db->quoteColumnName($c1) . ' as date) = \'' . $s2 . '\''); } else { $criteria->compare(Yii::app()->db->quoteColumnName($c1), $this->$c1, true); } @@ -793,26 +792,28 @@ public function getQuestionArray($oQuestion, $oResponses, $bHonorConditions, $su } // Use survey language is no language is specified - if (empty($sLanguage)) $sLanguage = $oQuestion->survey->language; + if (empty($sLanguage)) { + $sLanguage = $oQuestion->survey->language; + } $aQuestionAttributes = $oQuestion->attributes; $aQuestionAttributes['language'] = $sLanguage; $aQuestionAttributes['questionSrc'] = $oQuestion->questionl10ns[$sLanguage]->question; - $result = LimeExpressionManager::ProcessString($oQuestion->questionl10ns[$sLanguage]->question, 40, NULL, 1, 1); + $result = LimeExpressionManager::ProcessString($oQuestion->questionl10ns[$sLanguage]->question, 40, null, 1, 1); $aQuestionAttributes['question'] = $result; $aQuestionAttributes['helpSrc'] = $oQuestion->questionl10ns[$sLanguage]->help; - $result = LimeExpressionManager::ProcessString($oQuestion->questionl10ns[$sLanguage]->help, 40, NULL, 1, 1); + $result = LimeExpressionManager::ProcessString($oQuestion->questionl10ns[$sLanguage]->help, 40, null, 1, 1); $aQuestionAttributes['help'] = $result; $aQuestionAttributes['questionSrc'] = $oQuestion->questionl10ns[$sLanguage]->question; - $result = LimeExpressionManager::ProcessString($oQuestion->questionl10ns[$sLanguage]->question, 40, NULL, 1, 1); + $result = LimeExpressionManager::ProcessString($oQuestion->questionl10ns[$sLanguage]->question, 40, null, 1, 1); $aQuestionAttributes['question'] = $result; $aQuestionAttributes['helpSrc'] = $oQuestion->questionl10ns[$sLanguage]->help; - $result = LimeExpressionManager::ProcessString($oQuestion->questionl10ns[$sLanguage]->help, 40, NULL, 1, 1); + $result = LimeExpressionManager::ProcessString($oQuestion->questionl10ns[$sLanguage]->help, 40, null, 1, 1); $aQuestionAttributes['help'] = $result; if (count($oQuestion->subquestions) > 0) { @@ -829,8 +830,6 @@ public function getQuestionArray($oQuestion, $oResponses, $bHonorConditions, $su } $aQuestionAttributes['subquestions'][$oSubquestion->qid] = $subQuestionArray; - - } //Get other options if (in_array($oQuestion->type, ["M", "P"]) && $oQuestion->other == "Y") { @@ -850,7 +849,7 @@ public function getQuestionArray($oQuestion, $oResponses, $bHonorConditions, $su ), false); $oOtherQuestion->questionl10ns = [$sLanguage => $oOtherQuestionL10n]; - $aQuestionAttributes['subquestions']["other"] = $this->getQuestionArray($oOtherQuestion, $oResponses, $bHonorConditions, true, false, $sLanguage); + $aQuestionAttributes['subquestions']["other"] = $this->getQuestionArray($oOtherQuestion, $oResponses, $bHonorConditions, true, false, $sLanguage); if ($oQuestion->type == "P") { $aQuestionAttributes['subquestions']["other"]['comment'] = $this->getQuestionArray($oOtherQuestion, $oResponses, $bHonorConditions, true, true, $sLanguage); } @@ -859,8 +858,9 @@ public function getQuestionArray($oQuestion, $oResponses, $bHonorConditions, $su $fieldname = $oQuestion->basicFieldName; //If question is of any Array-Type or a subquestion - if (in_array($oQuestion->type, ["F", "A", "B", "E", "C", "H", "Q", "K", "M", "P", ";",":","1"]) - || ($oQuestion->type=='T' && $oQuestion->parent_qid != 0) + if ( + in_array($oQuestion->type, ["F", "A", "B", "E", "C", "H", "Q", "K", "M", "P", ";",":","1"]) + || ($oQuestion->type == 'T' && $oQuestion->parent_qid != 0) ) { $fieldname .= $oQuestion->title; } @@ -882,10 +882,11 @@ public function getQuestionArray($oQuestion, $oResponses, $bHonorConditions, $su } $aQuestionAttributes['answervalue'] = isset($oResponses[$fieldname]) ? $oResponses[$fieldname] : null; - $aQuestionAttributes['answercode'] = $aQuestionAttributes['answervalue']; // Must keep original code for -oth- and maybe other - if ((in_array($oQuestion->type, ["!", "L", "O", "F", "H"])) - || ($oQuestion->type=='T' && $oQuestion->parent_qid != 0) ) { - + $aQuestionAttributes['answercode'] = $aQuestionAttributes['answervalue']; // Must keep original code for -oth- and maybe other + if ( + (in_array($oQuestion->type, ["!", "L", "O", "F", "H"])) + || ($oQuestion->type == 'T' && $oQuestion->parent_qid != 0) + ) { $aAnswers = ( $oQuestion->parent_qid == 0 ? $oQuestion->answers @@ -895,18 +896,18 @@ public function getQuestionArray($oQuestion, $oResponses, $bHonorConditions, $su ) ); - $oSelectedAnswerOption = array_reduce( $aAnswers , function($carry, $oAnswer) use ($aQuestionAttributes){ + $oSelectedAnswerOption = array_reduce($aAnswers, function ($carry, $oAnswer) use ($aQuestionAttributes) { return $aQuestionAttributes['answervalue'] == $oAnswer->code ? $oAnswer : $carry; }); - if($oSelectedAnswerOption !== null){ + if ($oSelectedAnswerOption !== null) { $aQuestionAttributes['answeroption'] = array_merge( $oSelectedAnswerOption->attributes, $oSelectedAnswerOption->answerl10ns[$sLanguage]->attributes ); - } elseif ($oQuestion->other == 'Y'){ + } elseif ($oQuestion->other == 'Y') { $aQuestionAttributes['answervalue'] = !empty($attributes['other_replace_text'][$sLanguage]) ? $attributes['other_replace_text'][$sLanguage] : gT("Other"); - $aQuestionAttributes['answeroption']['answer'] = isset($oResponses[$fieldname.'other']) ? $oResponses[$fieldname.'other'] : null; + $aQuestionAttributes['answeroption']['answer'] = isset($oResponses[$fieldname . 'other']) ? $oResponses[$fieldname . 'other'] : null; } } @@ -921,7 +922,6 @@ public function getQuestionArray($oQuestion, $oResponses, $bHonorConditions, $su if ($oQuestion->parent_qid != 0 && $oQuestion->parent['type'] === "1") { - $aAnswers = ( $oQuestion->parent_qid == 0 ? $oQuestion->answers @@ -931,26 +931,26 @@ public function getQuestionArray($oQuestion, $oResponses, $bHonorConditions, $su ) ); - foreach($aAnswers as $key=>$value){ + foreach ($aAnswers as $key => $value) { $aAnswerText[$value['code']] = Answer::model()->getAnswerFromCode($value->qid, $value->code, $sLanguage, $value->scale_id); } - $tempFieldname = $fieldname.'#0'; + $tempFieldname = $fieldname . '#0'; $sAnswerCode = isset($oResponses[$tempFieldname]) ? $oResponses[$tempFieldname] : null; $sAnswerText = isset($aAnswerText[$oResponses[$tempFieldname]]) ? $aAnswerText[$oResponses[$tempFieldname]] . ' (' . $sAnswerCode . ')' : null; $aQuestionAttributes['answervalues'][0] = $sAnswerText; - $tempFieldname = $fieldname.'#1'; + $tempFieldname = $fieldname . '#1'; $sAnswerCode = isset($oResponses[$tempFieldname]) ? $oResponses[$tempFieldname] : null; $sAnswerText = isset($aAnswerText[$oResponses[$tempFieldname]]) ? $aAnswerText[$oResponses[$tempFieldname]] . ' (' . $sAnswerCode . ')' : null; $aQuestionAttributes['answervalues'][1] = $sAnswerText; } // array dual scale headers - if (isset($attributes['dualscale_headerA']) && !empty($attributes['dualscale_headerA'][$sLanguage])){ + if (isset($attributes['dualscale_headerA']) && !empty($attributes['dualscale_headerA'][$sLanguage])) { $aQuestionAttributes['dualscale_header'][0] = $attributes['dualscale_headerA'][$sLanguage]; } - if (isset($attributes['dualscale_headerB']) && !empty($attributes['dualscale_headerB'][$sLanguage])){ + if (isset($attributes['dualscale_headerB']) && !empty($attributes['dualscale_headerB'][$sLanguage])) { $aQuestionAttributes['dualscale_header'][1] = $attributes['dualscale_headerB'][$sLanguage]; } @@ -958,9 +958,9 @@ public function getQuestionArray($oQuestion, $oResponses, $bHonorConditions, $su $aQuestionAttributes['answervalues'] = array(); $iterator = 1; do { - $currentResponse = $oResponses[$fieldname.$iterator]; + $currentResponse = $oResponses[$fieldname . $iterator]; - $oSelectedAnswerOption = array_reduce( $oQuestion->answers, function($carry, $oAnswer) use ($currentResponse){ + $oSelectedAnswerOption = array_reduce($oQuestion->answers, function ($carry, $oAnswer) use ($currentResponse) { return $currentResponse == $oAnswer->code ? $oAnswer : $carry; }); @@ -969,8 +969,7 @@ public function getQuestionArray($oQuestion, $oResponses, $bHonorConditions, $su $aQuestionAttributes['answervalues'][] = ['value' => $currentResponse, 'option' => $option]; $iterator++; - } while (isset($oResponses[$fieldname.$iterator])); - + } while (isset($oResponses[$fieldname . $iterator])); } /* Second (X) scale for array text and array number */ @@ -981,14 +980,14 @@ public function getQuestionArray($oQuestion, $oResponses, $bHonorConditions, $su 'params' => array(':parent_qid' => $aQuestionAttributes['parent_qid'], ':scale_id' => 1), )); foreach ($oScaleXSubquestions as $oScaleSubquestion) { - $tempFieldname = $fieldname.'_'.$oScaleSubquestion->title; + $tempFieldname = $fieldname . '_' . $oScaleSubquestion->title; $aQuestionAttributes['answervalues'][$oScaleSubquestion->title] = isset($oResponses[$tempFieldname]) ? $oResponses[$tempFieldname] : null; /* Isue with language, need #15907 fixed */ $aQuestionAttributes['answervalueslabels'][$oScaleSubquestion->title] = isset($oScaleSubquestion->questionl10ns[$sLanguage]->question) ? $oScaleSubquestion->questionl10ns[$sLanguage]->question : null; } } - if ($oQuestion->type=='N' || ($oQuestion->parent_qid != 0 && $oQuestion->parent['type'] === "K")) { + if ($oQuestion->type == 'N' || ($oQuestion->parent_qid != 0 && $oQuestion->parent['type'] === "K")) { if (strpos($aQuestionAttributes['answervalue'], ".") !== false) { // Remove last 0 and last . ALWAYS (see \SurveyObj\getShortAnswer) $aQuestionAttributes['answervalue'] = rtrim(rtrim($aQuestionAttributes['answervalue'], "0"), "."); } @@ -1002,18 +1001,17 @@ public function getPrintAnswersArray($sSRID, $sLanguage, $bHonorConditions = fal $oSurvey = self::$survey; $aGroupArray = array(); - $oResponses = SurveyDynamic::model($oSurvey->sid)->findByAttributes(array('id'=>$sSRID)); + $oResponses = SurveyDynamic::model($oSurvey->sid)->findByAttributes(array('id' => $sSRID)); $oGroupList = $oSurvey->groups; foreach ($oGroupList as $oGroup) { - if (!(LimeExpressionManager::GroupIsRelevant($oGroup->gid) && $bHonorConditions == true)) { continue; } $aAnswersArray = array(); $aQuestionArray = $oGroup->questions; - foreach ( $aQuestionArray as $oQuestion) { + foreach ($aQuestionArray as $oQuestion) { $aQuestionArray = $this->getQuestionArray($oQuestion, $oResponses, $bHonorConditions, false, false, $sLanguage); if ($aQuestionArray === false) { @@ -1030,7 +1028,6 @@ public function getPrintAnswersArray($sSRID, $sLanguage, $bHonorConditions = fal $aGroupAttributes['description'] = $oGroup->getGroupDescriptionI10N($sLanguage); $aGroupAttributes['language'] = $sLanguage; $aGroupArray[$oGroup->gid] = $aGroupAttributes; - } return $aGroupArray; @@ -1040,7 +1037,8 @@ public function getPrintAnswersArray($sSRID, $sLanguage, $bHonorConditions = fal * Get current surveyId for other model/function * @return int */ - public function getSurveyId() { + public function getSurveyId() + { return self::$sid; } } diff --git a/application/models/SurveyLanguageSetting.php b/application/models/SurveyLanguageSetting.php index b94900638d8..42e56b9ae2f 100644 --- a/application/models/SurveyLanguageSetting.php +++ b/application/models/SurveyLanguageSetting.php @@ -1,4 +1,6 @@ - 0, 'max'=>255), + array('surveyls_email_invite_subj', 'length', 'min' => 0, 'max' => 255), array('surveyls_email_invite', 'LSYii_Validators'), array('surveyls_email_remind_subj', 'LSYii_Validators'), - array('surveyls_email_remind_subj', 'length', 'min' => 0, 'max'=>255), + array('surveyls_email_remind_subj', 'length', 'min' => 0, 'max' => 255), array('surveyls_email_remind', 'LSYii_Validators'), array('surveyls_email_confirm_subj', 'LSYii_Validators'), - array('surveyls_email_confirm_subj', 'length', 'min' => 0, 'max'=>255), + array('surveyls_email_confirm_subj', 'length', 'min' => 0, 'max' => 255), array('surveyls_email_confirm', 'LSYii_Validators'), array('surveyls_email_register_subj', 'LSYii_Validators'), - array('surveyls_email_register_subj', 'length', 'min' => 0, 'max'=>255), + array('surveyls_email_register_subj', 'length', 'min' => 0, 'max' => 255), array('surveyls_email_register', 'LSYii_Validators'), array('email_admin_notification_subj', 'LSYii_Validators'), - array('email_admin_notification_subj', 'length', 'min' => 0, 'max'=>255), + array('email_admin_notification_subj', 'length', 'min' => 0, 'max' => 255), array('email_admin_notification', 'LSYii_Validators'), array('email_admin_responses_subj', 'LSYii_Validators'), - array('email_admin_responses_subj', 'length', 'min' => 0, 'max'=>255), + array('email_admin_responses_subj', 'length', 'min' => 0, 'max' => 255), array('email_admin_responses', 'LSYii_Validators'), array('surveyls_title', 'LSYii_Validators'), - array('surveyls_title', 'length', 'min' => 0, 'max'=>200), + array('surveyls_title', 'length', 'min' => 0, 'max' => 200), array('surveyls_description', 'LSYii_Validators'), array('surveyls_welcometext', 'LSYii_Validators'), array('surveyls_endtext', 'LSYii_Validators'), array('surveyls_policy_notice', 'LSYii_Validators'), array('surveyls_policy_error', 'LSYii_Validators'), array('surveyls_policy_notice_label', 'LSYii_Validators'), - array('surveyls_policy_notice_label', 'length', 'min' => 0, 'max'=>192), - array('surveyls_url', 'filter', 'filter'=>'trim'), - array('surveyls_url', 'LSYii_Validators', 'isUrl'=>true), + array('surveyls_policy_notice_label', 'length', 'min' => 0, 'max' => 192), + array('surveyls_url', 'filter', 'filter' => 'trim'), + array('surveyls_url', 'LSYii_Validators', 'isUrl' => true), array('surveyls_urldescription', 'LSYii_Validators'), - array('surveyls_urldescription', 'length', 'min' => 0, 'max'=>255), + array('surveyls_urldescription', 'length', 'min' => 0, 'max' => 255), - array('surveyls_dateformat', 'numerical', 'integerOnly'=>true, 'min'=>'1', 'max'=>'12', 'allowEmpty'=>true), - array('surveyls_numberformat', 'numerical', 'integerOnly'=>true, 'min'=>'0', 'max'=>'1', 'allowEmpty'=>true), + array('surveyls_dateformat', 'numerical', 'integerOnly' => true, 'min' => '1', 'max' => '12', 'allowEmpty' => true), + array('surveyls_numberformat', 'numerical', 'integerOnly' => true, 'min' => '0', 'max' => '1', 'allowEmpty' => true), array('attachments', 'attachmentsInfo'), ); @@ -147,9 +149,9 @@ public function rules() * Remind to use resetScope if you need to disable this behaviour * @see https://www.yiiframework.com/doc/api/1.1/CActiveRecord#resetScope-detail */ - public function defaultScope() + public function defaultScope() { - return array('index'=>'surveyls_language'); + return array('index' => 'surveyls_language'); } /** @@ -176,13 +178,13 @@ public function lsdefault($attribute) 'email_admin_responses_subj' => $aDefaultTexts['admin_detailed_notification_subject'], 'email_admin_responses' => $aDefaultTexts['admin_detailed_notification'] ); - if ($sEmailFormat == "html") { - $aDefaultTextData['admin_detailed_notification'] = $aDefaultTexts['admin_detailed_notification_css'].$aDefaultTexts['admin_detailed_notification']; - } + if ($sEmailFormat == "html") { + $aDefaultTextData['admin_detailed_notification'] = $aDefaultTexts['admin_detailed_notification_css'] . $aDefaultTexts['admin_detailed_notification']; + } - if (empty($this->$attribute)) { - $this->$attribute = $aDefaultTextData[$attribute]; - } + if (empty($this->$attribute)) { + $this->$attribute = $aDefaultTextData[$attribute]; + } } /** @@ -192,7 +194,9 @@ public function lsdefault($attribute) */ public function attachmentsInfo($attribute) { - if (empty($this->$attribute)) return; + if (empty($this->$attribute)) { + return; + } $value = []; $attachmentsByType = unserialize($this->$attribute); @@ -292,7 +296,7 @@ function updateRecord($data, $condition = '', $xssfiltering = false) */ function insertSomeRecords($data) { - $lang = new self; + $lang = new self(); foreach ($data as $k => $v) { $lang->$k = $v; } diff --git a/application/models/SurveyLink.php b/application/models/SurveyLink.php index 048b30d5e74..c709ed8e669 100644 --- a/application/models/SurveyLink.php +++ b/application/models/SurveyLink.php @@ -1,4 +1,6 @@ - array(self::HAS_ONE, 'Particiant', 'participant_id'), - 'survey' => array(self::HAS_ONE, 'Survey', array('sid'=>'survey_id')) + 'survey' => array(self::HAS_ONE, 'Survey', array('sid' => 'survey_id')) ); } @@ -88,9 +90,9 @@ public function getLinkInfo($participantId) public function rebuildLinksFromTokenTable($iSurveyId) { $this->deleteLinksBySurvey($iSurveyId); - $tableName = "{{tokens_".$iSurveyId."}}"; + $tableName = "{{tokens_" . $iSurveyId . "}}"; $dateCreated = date('Y-m-d H:i:s', time()); - $query = "INSERT INTO ".SurveyLink::tableName()." (participant_id, token_id, survey_id, date_created) SELECT participant_id, tid, '".$iSurveyId."', '".$dateCreated."' FROM ".$tableName." WHERE participant_id IS NOT NULL"; + $query = "INSERT INTO " . SurveyLink::tableName() . " (participant_id, token_id, survey_id, date_created) SELECT participant_id, tid, '" . $iSurveyId . "', '" . $dateCreated . "' FROM " . $tableName . " WHERE participant_id IS NOT NULL"; return Yii::app()->db->createCommand($query) ->query(); } @@ -109,8 +111,8 @@ public function rebuildLinksFromTokenTable($iSurveyId) */ function deleteTokenLink($aTokenIds, $surveyId) { - $query = "DELETE FROM ".SurveyLink::tableName() - ." WHERE token_id IN (".implode(", ", $aTokenIds).") AND survey_id=:survey_id"; + $query = "DELETE FROM " . SurveyLink::tableName() + . " WHERE token_id IN (" . implode(", ", $aTokenIds) . ") AND survey_id=:survey_id"; return Yii::app()->db->createCommand($query) ->bindParam(":survey_id", $surveyId) ->query(); @@ -126,7 +128,7 @@ function deleteTokenLink($aTokenIds, $surveyId) */ public function deleteLinksBySurvey($surveyId) { - $query = "DELETE FROM ".SurveyLink::tableName()." WHERE survey_id = :survey_id"; + $query = "DELETE FROM " . SurveyLink::tableName() . " WHERE survey_id = :survey_id"; return Yii::app()->db->createCommand($query) ->bindParam(":survey_id", $surveyId) ->query(); @@ -224,7 +226,7 @@ public function getIsSubmitted() */ public function getCheckbox() { - return ""; + return ""; } /** @inheritdoc */ @@ -298,14 +300,14 @@ public function getColumns() */ public function search() { - $criteria = new CDbCriteria; - $sort = new CSort; + $criteria = new CDbCriteria(); + $sort = new CSort(); $criteria->compare('participant_id', $this->participant_id); return new CActiveDataProvider($this, array( - 'criteria'=>$criteria, - 'sort'=>$sort, + 'criteria' => $criteria, + 'sort' => $sort, 'pagination' => false )); } @@ -316,7 +318,7 @@ public function search() */ public function getSurveyIdLink() { - $url = Yii::app()->getController()->createUrl('surveyAdministration/view/surveyid/'.$this->survey_id); + $url = Yii::app()->getController()->createUrl('surveyAdministration/view/surveyid/' . $this->survey_id); $link = CHtml::link($this->survey_id, $url); return $link; } diff --git a/application/models/SurveyTimingDynamic.php b/application/models/SurveyTimingDynamic.php index 18ffa787a45..21534e69d0e 100644 --- a/application/models/SurveyTimingDynamic.php +++ b/application/models/SurveyTimingDynamic.php @@ -1,4 +1,6 @@ -db->schema->getTable($this->tableName())) { $queryAvg = Yii::app()->db->createCommand() ->select("AVG(interviewtime) AS avg, COUNT(*) as count") - ->from($this->tableName()." t") + ->from($this->tableName() . " t") ->join("{{survey_{$sid}}} s", "t.id = s.id") ->where("s.submitdate IS NOT NULL") ->queryRow(); @@ -105,7 +107,7 @@ public function statistics() $statistics['count'] = $queryAvg['count']; $queryAll = Yii::app()->db->createCommand() ->select("interviewtime") - ->from($this->tableName()." t") + ->from($this->tableName() . " t") ->join("{{survey_{$sid}}} s", "t.id = s.id") ->where("s.submitdate IS NOT NULL") ->order("t.interviewtime") @@ -135,8 +137,8 @@ public function statistics() */ public function insertRecords($data) { - $record = new self; - foreach ($data as $k=>$v) { + $record = new self(); + foreach ($data as $k => $v) { $record->$k = $v; } @@ -163,7 +165,7 @@ public function search($iSurveyID, $language) $oCriteria = new CdbCriteria(); $oCriteria->join = "INNER JOIN {{survey_{$iSurveyID}}} s ON t.id=s.id"; $oCriteria->condition = 'submitdate IS NOT NULL'; - $oCriteria->order = "s.id ".(Yii::app()->request->getParam('order') == 'desc' ? 'desc' : 'asc'); + $oCriteria->order = "s.id " . (Yii::app()->request->getParam('order') == 'desc' ? 'desc' : 'asc'); //$oCriteria->offset = $start; //$oCriteria->limit = $limit; @@ -186,19 +188,19 @@ public function search($iSurveyID, $language) public function getButtons() { // View details - $viewUrl = App()->createUrl("admin/responses/sa/view/surveyid/".self::$sid."/id/".$this->id); - $buttons = ''; + $viewUrl = App()->createUrl("admin/responses/sa/view/surveyid/" . self::$sid . "/id/" . $this->id); + $buttons = ''; // Edit if (Permission::model()->hasSurveyPermission(self::$sid, 'responses', 'update')) { - $editUrl = App()->createUrl("admin/dataentry/sa/editdata/subaction/edit/surveyid/".self::$sid."/id/".$this->id); - $buttons .= ' '; + $editUrl = App()->createUrl("admin/dataentry/sa/editdata/subaction/edit/surveyid/" . self::$sid . "/id/" . $this->id); + $buttons .= ' '; } // Delete if (Permission::model()->hasSurveyPermission(self::$sid, 'responses', 'delete')) { - $deleteUrl = App()->createUrl("admin/dataentry/sa/delete/subaction/edit/surveyid/".self::$sid."/id/".$this->id); - $buttons .= ' '; + $deleteUrl = App()->createUrl("admin/dataentry/sa/delete/subaction/edit/surveyid/" . self::$sid . "/id/" . $this->id); + $buttons .= ' '; } return $buttons; @@ -208,8 +210,8 @@ public function getButtons() * Get current surveyId for other model/function * @return int */ - public function getSurveyId() { + public function getSurveyId() + { return self::$sid; } - } diff --git a/application/models/SurveyURLParameter.php b/application/models/SurveyURLParameter.php index dd6b26287a6..b0f28d8fa4c 100644 --- a/application/models/SurveyURLParameter.php +++ b/application/models/SurveyURLParameter.php @@ -1,4 +1,5 @@ $sFieldvalue) { + foreach ($aConditions as $sFieldname => $sFieldvalue) { Yii::app()->db->createCommand()->where($sFieldname, $sFieldvalue); } return Yii::app()->db->delete('survey_url_parameters'); // Deletes from token @@ -88,5 +89,4 @@ public function insertRecord($aData) { return Yii::app()->db->createCommand()->insert('{{survey_url_parameters}}', $aData); } - } diff --git a/application/models/Surveymenu.php b/application/models/Surveymenu.php index 2c959869428..3a7a2077eb2 100644 --- a/application/models/Surveymenu.php +++ b/application/models/Surveymenu.php @@ -41,14 +41,14 @@ public function rules() return array( array('changed_at, name', 'required'), array('name', 'unique'), - array('ordering, level, changed_by, created_by', 'numerical', 'integerOnly'=>true), + array('ordering, level, changed_by, created_by', 'numerical', 'integerOnly' => true), array('parent_id, survey_id, user_id', 'default', 'value' => null), - array('title, position', 'length', 'max'=>255), - array('name', 'length', 'max'=>128), + array('title, position', 'length', 'max' => 255), + array('name', 'length', 'max' => 128), array('description, created_at', 'safe'), // The following rule is used by search(). // @todo Please remove those attributes that should not be searched. - array('id, parent_id, survey_id, user_id, ordering, level, position, name, title, description, changed_at, changed_by, created_at, created_by', 'safe', 'on'=>'search'), + array('id, parent_id, survey_id, user_id, ordering, level, position, name, title, description, changed_at, changed_by, created_at, created_by', 'safe', 'on' => 'search'), ); } @@ -83,12 +83,12 @@ public static function staticAddMenu($menuArray) $oSurveymenu->created_by = Yii::app()->user->getId(); $oSurveymenu->save(); - return Surveymenu::model()->find('name=:name', [':name'=> $menuArray['name']])->id; + return Surveymenu::model()->find('name=:name', [':name' => $menuArray['name']])->id; } public static function staticRemoveMenu($menuName, $recursive = false) { - $oSurveymenu = Surveymenu::model()->find('name=:name', [':name'=>$menuName]); + $oSurveymenu = Surveymenu::model()->find('name=:name', [':name' => $menuName]); if ($recursive !== true && count($oSurveymenu->surveymenuEntries) > 0) { return false; @@ -102,15 +102,15 @@ public static function staticRemoveMenu($menuName, $recursive = false) } public function getMenuesForGlobalSettings() - { + { $oSettingsMenu = Surveymenu::model()->findByPk(1); $aResultCollected = $this->createSurveymenuArray([$oSettingsMenu], false); $resultMenu = $aResultCollected[1]; $resultMenu['entries'] = array_filter( - $resultMenu['entries'], + $resultMenu['entries'], function ($entry) { //@TODO add a database hook to make this more abstract - return in_array($entry['name'], ['generalsettings','presentation','tokens','notification','publication']); + return in_array($entry['name'], ['generalsettings','presentation','tokens','notification','publication']); } ); @@ -130,7 +130,7 @@ private function __useTranslationForSurveymenu(&$entryData) * @param null $oSurvey * @return array */ - public function createSurveymenuArray($oSurveyMenuObjects, $collapsed=false, $oSurvey=null) + public function createSurveymenuArray($oSurveyMenuObjects, $collapsed = false, $oSurvey = null) { //Posibility to add more languages to the database is given, so it is possible to add a call by language //Also for peripheral menues we may add submenus someday. @@ -142,22 +142,22 @@ public function createSurveymenuArray($oSurveyMenuObjects, $collapsed=false, $oS foreach ($aMenuEntries as $menuEntry) { $aEntry = $menuEntry->attributes; //Skip menuentry if not activated in collapsed mode - if ($collapsed && $aEntry['showincollapse'] == 0 ) { + if ($collapsed && $aEntry['showincollapse'] == 0) { continue; } //Skip menuentry if no permission - if (!empty($aEntry['permission']) && !empty($aEntry['permission_grade'])){ - $inArray = array_search($aEntry['permission'],array_keys(Permission::getGlobalBasePermissions())); - if($inArray) { + if (!empty($aEntry['permission']) && !empty($aEntry['permission_grade'])) { + $inArray = array_search($aEntry['permission'], array_keys(Permission::getGlobalBasePermissions())); + if ($inArray) { $hasPermission = Permission::model()->hasGlobalPermission($aEntry['permission'], $aEntry['permission_grade']); - } else if($oSurvey !== null){ + } elseif ($oSurvey !== null) { $hasPermission = Permission::model()->hasSurveyPermission($oSurvey->sid, $aEntry['permission'], $aEntry['permission_grade']); } else { $hasPermission = true; } - if(!$hasPermission) { + if (!$hasPermission) { continue; } } @@ -202,9 +202,9 @@ public function createSurveymenuArray($oSurveyMenuObjects, $collapsed=false, $oS return $aResultCollected; } - public function getSurveymenuSubmenus($oParentSurveymenu, $collapsed=false) + public function getSurveymenuSubmenus($oParentSurveymenu, $collapsed = false) { - $criteria = new CDbCriteria; + $criteria = new CDbCriteria(); $criteria->addCondition('survey_id=:surveyid OR survey_id IS NULL'); $criteria->addCondition('parent_id=:parentid'); $criteria->addCondition('level=:level'); @@ -216,7 +216,7 @@ public function getSurveymenuSubmenus($oParentSurveymenu, $collapsed=false) $criteria->params = [ ':surveyid' => $oParentSurveymenu->survey_id, ':parentid' => $oParentSurveymenu->id, - ':level'=> ($oParentSurveymenu->level + 1) + ':level' => ($oParentSurveymenu->level + 1) ]; $oMenus = Surveymenu::model()->findAll($criteria); @@ -225,20 +225,20 @@ public function getSurveymenuSubmenus($oParentSurveymenu, $collapsed=false) return $aResultCollected; } - public function getDefaultSurveyMenus($position = '', $oSurvey=null) + public function getDefaultSurveyMenus($position = '', $oSurvey = null) { - $criteria = new CDbCriteria; + $criteria = new CDbCriteria(); $criteria->condition = 'survey_id IS NULL AND (parent_id IS NULL OR parent_id=0)'; - $collapsed = $position==='collapsed'; + $collapsed = $position === 'collapsed'; if ($position != '' && !$collapsed) { $criteria->condition .= ' AND position=:position'; - $criteria->params = array(':position'=>$position); + $criteria->params = array(':position' => $position); } if ($collapsed) { $criteria->condition .= ' AND (position=:position OR showincollapse=1 )'; - $criteria->params = array(':position'=>$position); + $criteria->params = array(':position' => $position); $collapsed = true; } @@ -256,7 +256,7 @@ public function getMenuIdOptions() ]; foreach ($oSurveymenus as $oSurveymenu) { //$options[] = ""; - $options[''.($oSurveymenu->id).''] = '('.$oSurveymenu->id.') '.$oSurveymenu->title; + $options['' . ($oSurveymenu->id) . ''] = '(' . $oSurveymenu->id . ') ' . $oSurveymenu->title; } //return join('\n',$options); return $options; @@ -294,7 +294,7 @@ public function getUserIdOptions() public function getNextOrderPosition() { - $oSurveymenus = Surveymenu::model()->findAll('parent_id=:parent_id', array('parent_id'=>0)); + $oSurveymenus = Surveymenu::model()->findAll('parent_id=:parent_id', array('parent_id' => 0)); return count($oSurveymenus); } @@ -328,19 +328,19 @@ public function attributeLabels() { return array( 'id' => 'ID', - 'parent_id' => gT('Parent'), - 'survey_id' => gT('Survey'), - 'user_id' => gT('User'), - 'ordering' => gT('Order'), - 'level' => gT('Level'), - 'name' => gT('Name'), - 'title' => gT('Title'), - 'position' => gT('Position'), - 'description' => gT('Description'), - 'changed_at' => gT('Changed on'), - 'changed_by' => gT('Changed by'), - 'created_at' => gT('Created on'), - 'created_by' => gT('Created by'), + 'parent_id' => gT('Parent'), + 'survey_id' => gT('Survey'), + 'user_id' => gT('User'), + 'ordering' => gT('Order'), + 'level' => gT('Level'), + 'name' => gT('Name'), + 'title' => gT('Title'), + 'position' => gT('Position'), + 'description' => gT('Description'), + 'changed_at' => gT('Changed on'), + 'changed_by' => gT('Changed by'), + 'created_at' => gT('Created on'), + 'created_by' => gT('Created by'), ); } @@ -426,16 +426,16 @@ public function getColumns() 'type' => 'raw' ), // array( - // 'name' => 'changed_at', + // 'name' => 'changed_at', // ), // array( - // 'name' => 'changed_by', + // 'name' => 'changed_by', // ), // array( - // 'name' => 'created_at', + // 'name' => 'created_at', // ), // array( - // 'name' => 'created_by', + // 'name' => 'created_by', // ), ); @@ -458,7 +458,7 @@ public function onAfterSave($event) $criteria->addCondition(['position=:position']); $criteria->addCondition(['ordering=:ordering']); $criteria->addCondition(['id!=:id']); - $criteria->params = ['position' => $this->position, 'ordering' => (int) $this->ordering, 'id'=> (int) $this->id]; + $criteria->params = ['position' => $this->position, 'ordering' => (int) $this->ordering, 'id' => (int) $this->id]; $criteria->limit = 1; $collidingMenu = Surveymenu::model()->find($criteria); @@ -549,7 +549,7 @@ public function search() { // @todo Please modify the following code to remove attributes that should not be searched. - $criteria = new CDbCriteria; + $criteria = new CDbCriteria(); //Don't show main menu when not superadmin if (Yii::app()->getConfig('demoMode') || !Permission::model()->hasGlobalPermission('superadmin', 'read')) { @@ -575,7 +575,7 @@ public function search() $pageSize = Yii::app()->user->getState('pageSize', Yii::app()->params['defaultPageSize']); return new CActiveDataProvider($this, array( - 'criteria'=>$criteria, + 'criteria' => $criteria, 'pagination' => array( 'pageSize' => $pageSize ) diff --git a/application/models/SurveymenuEntries.php b/application/models/SurveymenuEntries.php index f4edbb8e8cd..fd9140dbf9d 100644 --- a/application/models/SurveymenuEntries.php +++ b/application/models/SurveymenuEntries.php @@ -52,13 +52,13 @@ public function rules() // will receive user inputs. return array( array('title, menu_title, menu_icon, menu_icon_type, changed_at', 'required'), - array('menu_id, user_id, ordering, changed_by, created_by', 'numerical', 'integerOnly'=>true), - array('title, menu_title, menu_icon, menu_icon_type, menu_class, menu_link, action, template, partial, permission, permission_grade, classes, getdatamethod', 'length', 'max'=>255), + array('menu_id, user_id, ordering, changed_by, created_by', 'numerical', 'integerOnly' => true), + array('title, menu_title, menu_icon, menu_icon_type, menu_class, menu_link, action, template, partial, permission, permission_grade, classes, getdatamethod', 'length', 'max' => 255), array('name', 'unique'), array('name, menu_description, language, data, created_at', 'safe'), // The following rule is used by search(). // @todo Please remove those attributes that should not be searched. - array('id, menu_id, user_id, ordering, title, name, menu_title, menu_description, menu_icon, menu_icon_type, menu_class, menu_link, action, template, partial, language, permission, permission_grade, classes, data, getdatamethod, changed_at, changed_by, created_at, created_by', 'safe', 'on'=>'search'), + array('id, menu_id, user_id, ordering, title, name, menu_title, menu_description, menu_icon, menu_icon_type, menu_class, menu_link, action, template, partial, language, permission, permission_grade, classes, data, getdatamethod, changed_at, changed_by, created_at, created_by', 'safe', 'on' => 'search'), ); } @@ -103,7 +103,7 @@ public static function staticAddMenuEntry($menuId, $menuEntryArray) if (is_array($menuEntryArray['manualParams'])) { $oMenuEntryData->linkData = $menuEntryArray['manualParams']; - } else if ($menuEntryArray['manualParams'] != '') { + } elseif ($menuEntryArray['manualParams'] != '') { $oMenuEntryData->linkData = json_decode($menuEntryArray['manualParams'], true); } @@ -124,10 +124,10 @@ public function reorder() { $menusWithEntries = SurveymenuEntries::model()->findAll(array( - 'select'=>'t.menu_id', - 'distinct'=>true, + 'select' => 't.menu_id', + 'distinct' => true, )); - foreach ($menusWithEntries as $key=>$menuWithEntry) { + foreach ($menusWithEntries as $key => $menuWithEntry) { self::reorderMenu($menuWithEntry->menu_id); } } @@ -161,14 +161,13 @@ public function onAfterSave($event) $criteria->addCondition(['menu_id = :menu_id']); $criteria->addCondition(['ordering = :ordering']); $criteria->addCondition(['id!=:id']); - $criteria->params = ['menu_id' => (int) $this->menu_id, 'ordering' => (int) $this->ordering, 'id'=>(int) $this->id]; + $criteria->params = ['menu_id' => (int) $this->menu_id, 'ordering' => (int) $this->ordering, 'id' => (int) $this->id]; $criteria->limit = 1; $collidingMenuEntry = SurveymenuEntries::model()->find($criteria); if ($collidingMenuEntry != null) { $collidingMenuEntry->ordering = (((int) $collidingMenuEntry->ordering) + 1); $collidingMenuEntry->save(); - } return parent::onAfterSave($event); } @@ -213,26 +212,26 @@ public static function returnCombinedMenuLink($data) if ($data->menu_link) { return $data->menu_link; } else { - return gt('Action: ').$data->action.',
' - .gt('Template: ').$data->template.',
' - .gt('Partial: ').$data->partial; + return gt('Action: ') . $data->action . ',
' + . gt('Template: ') . $data->template . ',
' + . gt('Partial: ') . $data->partial; } } public static function returnMenuIcon($data) { if ($data->menu_icon_type == 'fontawesome') { - return ""; - } else if ($data->menu_icon_type == 'image') { - return ''; + return ""; + } elseif ($data->menu_icon_type == 'image') { + return ''; } else { - return $data->menu_icon_type.'|'.$data->menu_icon; + return $data->menu_icon_type . '|' . $data->menu_icon; } } public function getMenuIdOptions() { - $criteria = new CDbCriteria; + $criteria = new CDbCriteria(); if (Yii::app()->getConfig('demoMode') || !Permission::model()->hasGlobalPermission('superadmin', 'read')) { $criteria->compare('id', '<> 0'); $criteria->compare('id', '<> 1'); @@ -240,7 +239,7 @@ public function getMenuIdOptions() $oSurveymenus = Surveymenu::model()->findAll($criteria); $options = []; foreach ($oSurveymenus as $oSurveymenu) { - $options["".$oSurveymenu->id] = $oSurveymenu->title; + $options["" . $oSurveymenu->id] = $oSurveymenu->title; } return $options; } @@ -273,11 +272,11 @@ public function getUserOptions() public function getMenuIconTypeOptions() { return [ - 'fontawesome' => gT('Fontawesome icon'), - 'image' => gT('Image'), + 'fontawesome' => gT('Fontawesome icon'), + 'image' => gT('Image'), ]; // return "" - // .""; + // .""; } public function getButtons() @@ -289,7 +288,6 @@ public function getButtons() . ""; if (Permission::model()->hasGlobalPermission('settings', 'update')) { - $deleteData = array( 'action_surveymenuEntries_deleteModal', 'text-danger', @@ -370,8 +368,8 @@ public function getColumns() ), array( 'name' => 'classes', - 'htmlOptions'=>array('style'=>'white-space: prewrap;'), - 'headerHtmlOptions'=>array('style'=>'white-space: prewrap;'), + 'htmlOptions' => array('style' => 'white-space: prewrap;'), + 'headerHtmlOptions' => array('style' => 'white-space: prewrap;'), ), array( 'name' => 'data', @@ -418,8 +416,8 @@ public function getShortListColumns() array( 'header' => gT('Menu'), 'value' => '' - .'"menu_class."\" title=\"".$data->menu_description."\" data-toggle="tooltip" >' - .'".SurveymenuEntries::returnMenuIcon($data)." ".$data->menu_title.""', + . '"menu_class."\" title=\"".$data->menu_description."\" data-toggle="tooltip" >' + . '".SurveymenuEntries::returnMenuIcon($data)." ".$data->menu_title.""', 'type' => 'raw' ), array( @@ -459,7 +457,7 @@ public function search() { // @todo Please modify the following code to remove attributes that should not be searched. - $criteria = new CDbCriteria; + $criteria = new CDbCriteria(); //Don't show main menu when not superadmin if (Yii::app()->getConfig('demoMode') || !Permission::model()->hasGlobalPermission('superadmin', 'read')) { @@ -495,9 +493,9 @@ public function search() $pageSize = Yii::app()->user->getState('pageSize', Yii::app()->params['defaultPageSize']); return new CActiveDataProvider($this, array( - 'criteria'=>$criteria, - 'sort'=>array( - 'defaultOrder'=>'t.menu_id ASC, t.ordering ASC', + 'criteria' => $criteria, + 'sort' => array( + 'defaultOrder' => 't.menu_id ASC, t.ordering ASC', ), 'pagination' => array( 'pageSize' => $pageSize @@ -523,35 +521,35 @@ public function restoreDefaults() $oDB->createCommand()->insert("{{surveymenu_entries}}", $basicMenu); } $oTransaction->commit(); - } catch (Exception $e) { throw $e; } return true; } - private function _parseUniqueNameFromTitle() { + private function _parseUniqueNameFromTitle() + { - $name = preg_replace("/[^a-z]*/","", strtolower($this->title)); - if(!preg_match("/^[a-z].*$/",$name)) { - $name = 'm'.$name; + $name = preg_replace("/[^a-z]*/", "", strtolower($this->title)); + if (!preg_match("/^[a-z].*$/", $name)) { + $name = 'm' . $name; } $itrt = 0; - while(self::model()->findByAttributes(['name' => $name]) !== null){ - $name = $name.($itrt++); + while (self::model()->findByAttributes(['name' => $name]) !== null) { + $name = $name . ($itrt++); } return $name; } - public function save($runValidation=true,$attributes=null) - { - if($this->getIsNewRecord()){ + public function save($runValidation = true, $attributes = null) + { + if ($this->getIsNewRecord()) { $this->name = $this->_parseUniqueNameFromTitle(); $this->menu_title = empty($this->menu_title) ? $this->title : $this->menu_title; $this->menu_description = empty($this->menu_description) ? $this->title : $this->menu_title; } - parent::save($runValidation,$attributes); - } + parent::save($runValidation, $attributes); + } /** * Returns the static model of the specified AR class. diff --git a/application/models/SurveymenuEntryData.php b/application/models/SurveymenuEntryData.php index 9f6f076f59b..496380f65ae 100644 --- a/application/models/SurveymenuEntryData.php +++ b/application/models/SurveymenuEntryData.php @@ -17,7 +17,7 @@ class SurveymenuEntryData extends CFormModel /** * @param integer|null $surveyid */ - public function apply($menuEntry, $surveyid=null) + public function apply($menuEntry, $surveyid = null) { $this->surveyid = $surveyid; $this->menuEntry = $menuEntry; @@ -67,11 +67,10 @@ public function createOptionJson($addSurveyID = false, $addQuestionGroupId = fal public function linkCreator() { - if( $this->linkExternal ) { + if ($this->linkExternal) { return Yii::app()->getController()->createAbsoluteUrl($this->link, $this->linkData); } return Yii::app()->getController()->createUrl($this->link, $this->linkData); - } private function _parseDataAttribute() @@ -100,7 +99,6 @@ private function _parseLink() } else { $this->link = $this->menuEntry->menu_link; } - } /** @@ -115,17 +113,16 @@ private function _recursiveIssetWithDefault($variable, $checkArray, $i = 0, $fal $default = null; if (is_array($variable) && array_key_exists($checkArray[$i], $variable)) { $default = $variable[$checkArray[$i]]; - } else if (is_object($variable) && property_exists($variable, $checkArray[$i])) { + } elseif (is_object($variable) && property_exists($variable, $checkArray[$i])) { $default = $variable->{$checkArray[$i]}; } if (!isset($default)) { return $fallback; - } else if (count($checkArray) > $i + 1) { + } elseif (count($checkArray) > $i + 1) { return $this->_recursiveIssetWithDefault($default, $checkArray, $i + 1, $fallback); } else { return $default; } - } private function _getValueForLinkData($getDataPair) @@ -143,12 +140,12 @@ private function _getValueForLinkData($getDataPair) break; case 'questiongroup': if (App()->getRequest()->getParam('gid')) { - $oTypeObject = QuestionGroup::model()->findByPk(array('gid'=>App()->getRequest()->getParam('gid'),'language'=>App()->getLanguage())); + $oTypeObject = QuestionGroup::model()->findByPk(array('gid' => App()->getRequest()->getParam('gid'),'language' => App()->getLanguage())); } break; case 'question': if (App()->getRequest()->getParam('qid')) { - $oTypeObject = QuestionGroup::model()->findByPk(array('gid'=>App()->getRequest()->getParam('qid'),'language'=>App()->getLanguage())); + $oTypeObject = QuestionGroup::model()->findByPk(array('gid' => App()->getRequest()->getParam('qid'),'language' => App()->getLanguage())); } break; break; @@ -157,5 +154,4 @@ private function _getValueForLinkData($getDataPair) $result = $oTypeObject != null ? $oTypeObject->{$attribute} : null; return $result; } - } diff --git a/application/models/SurveysGroups.php b/application/models/SurveysGroups.php index 3213d02d4b2..5804bbbc79c 100644 --- a/application/models/SurveysGroups.php +++ b/application/models/SurveysGroups.php @@ -1,4 +1,5 @@ gsid == 1) { + if ($this->gsid == 1) { $this->alwaysavailable = 1; } } @@ -59,15 +60,15 @@ public function rules() // will receive user inputs. return array( array('name, sortorder, created_by, title', 'required'), - array('sortorder, owner_id, parent_id, created_by', 'numerical', 'integerOnly'=>true), - array('name', 'length', 'max'=>45), - array('name', 'match', 'pattern'=> '/^[A-Za-z0-9_\.]+$/u','message'=> gT('Group name can contain only alphanumeric character, underscore or dot.')), - array('title', 'length', 'max'=>100), + array('sortorder, owner_id, parent_id, created_by', 'numerical', 'integerOnly' => true), + array('name', 'length', 'max' => 45), + array('name', 'match', 'pattern' => '/^[A-Za-z0-9_\.]+$/u','message' => gT('Group name can contain only alphanumeric character, underscore or dot.')), + array('title', 'length', 'max' => 100), array('alwaysavailable', 'boolean'), array('description, created, modified', 'safe'), // The following rule is used by search(). // @todo Please remove those attributes that should not be searched. - array('gsid, name, title, description, owner_id, parent_id, created, modified, created_by', 'safe', 'on'=>'search'), + array('gsid, name, title, description, owner_id, parent_id, created, modified, created_by', 'safe', 'on' => 'search'), ); } @@ -109,72 +110,72 @@ public function getColumns() return array( array( - 'id'=>'gsid', - 'class'=>'CCheckBoxColumn', + 'id' => 'gsid', + 'class' => 'CCheckBoxColumn', 'selectableRows' => '100', ), array( 'header' => gT('Survey group ID'), 'name' => 'gsid', - 'value'=>'$data->hasViewSurveyGroupRight ? CHtml::link($data->gsid, Yii::app()->createUrl("admin/surveysgroups/sa/update/",array("id"=>$data->gsid))) : $data->gsid', - 'type'=>'raw', - 'headerHtmlOptions'=>array('class' => 'hidden-xs'), + 'value' => '$data->hasViewSurveyGroupRight ? CHtml::link($data->gsid, Yii::app()->createUrl("admin/surveysgroups/sa/update/",array("id"=>$data->gsid))) : $data->gsid', + 'type' => 'raw', + 'headerHtmlOptions' => array('class' => 'hidden-xs'), 'htmlOptions' => array('class' => 'hidden-xs'), ), array( 'header' => gT('Name'), 'name' => 'name', - 'value'=>'$data->hasViewSurveyGroupRight ? CHtml::link($data->name, Yii::app()->createUrl("admin/surveysgroups/sa/update/",array("id"=>$data->gsid))) : $data->name', - 'type'=>'raw', - 'headerHtmlOptions'=>array('class' => 'hidden-xs'), + 'value' => '$data->hasViewSurveyGroupRight ? CHtml::link($data->name, Yii::app()->createUrl("admin/surveysgroups/sa/update/",array("id"=>$data->gsid))) : $data->name', + 'type' => 'raw', + 'headerHtmlOptions' => array('class' => 'hidden-xs'), ), array( 'header' => gT('Title'), 'name' => 'title', - 'value'=>'$data->title', - 'headerHtmlOptions'=>array('class' => 'hidden-xs'), + 'value' => '$data->title', + 'headerHtmlOptions' => array('class' => 'hidden-xs'), ), array( 'header' => gT('Description'), 'name' => 'description', - 'value'=>'$data->description', - 'headerHtmlOptions'=>array('class' => 'hidden-xs'), + 'value' => '$data->description', + 'headerHtmlOptions' => array('class' => 'hidden-xs'), 'htmlOptions' => array('class' => 'hidden-xs'), ), array( 'header' => gT('Parent group'), 'name' => 'parent', - 'value'=>'$data->parentTitle', - 'headerHtmlOptions'=>array('class' => 'hidden-xs'), + 'value' => '$data->parentTitle', + 'headerHtmlOptions' => array('class' => 'hidden-xs'), 'htmlOptions' => array('class' => 'hidden-xs'), ), array( 'header' => gT('Available'), 'name' => 'alwaysavailable', - 'value'=>'$data->alwaysavailable', - 'headerHtmlOptions'=>array('class' => 'hidden-xs'), + 'value' => '$data->alwaysavailable', + 'headerHtmlOptions' => array('class' => 'hidden-xs'), 'htmlOptions' => array('class' => 'hidden-xs'), ), array( 'header' => gT('Owner'), 'name' => 'owner', - 'value'=>'!empty($data->owner) ? $data->owner->users_name : ""', - 'headerHtmlOptions'=>array('class' => 'hidden-xs'), + 'value' => '!empty($data->owner) ? $data->owner->users_name : ""', + 'headerHtmlOptions' => array('class' => 'hidden-xs'), 'htmlOptions' => array('class' => 'hidden-xs'), ), array( 'header' => gT('Order'), 'name' => 'sortorder', - 'value'=>'$data->sortorder', - 'headerHtmlOptions'=>array('class' => 'hidden-xs'), + 'value' => '$data->sortorder', + 'headerHtmlOptions' => array('class' => 'hidden-xs'), 'htmlOptions' => array('class' => 'hidden-xs'), ), @@ -183,8 +184,8 @@ public function getColumns() 'header' => gT('Actions'), 'name' => 'sortorder', 'type' => 'raw', - 'value'=> '$data->buttons', - 'headerHtmlOptions'=>array('class' => 'hidden-xs'), + 'value' => '$data->buttons', + 'headerHtmlOptions' => array('class' => 'hidden-xs'), 'htmlOptions' => array('class' => 'hidden-xs'), ), @@ -217,7 +218,7 @@ public function search() { // @todo Please modify the following code to remove attributes that should not be searched. - $criteria = new CDbCriteria; + $criteria = new CDbCriteria(); $criteria->select = array('DISTINCT t.*'); @@ -237,7 +238,7 @@ public function search() $criteria->mergeWith($criteriaPerm, 'AND'); $dataProvider = new CActiveDataProvider($this, array( - 'criteria'=>$criteria, + 'criteria' => $criteria, )); $dataProvider->setTotalItemCount(count($dataProvider->getData())); @@ -261,7 +262,7 @@ public function getParentTitle() */ public function getHasSurveys() { - $nbSurvey = Survey::model()->countByAttributes(array("gsid"=>$this->gsid)); + $nbSurvey = Survey::model()->countByAttributes(array("gsid" => $this->gsid)); return $nbSurvey > 0; } @@ -271,18 +272,18 @@ public function getHasSurveys() */ public function getHasChildGroups() { - $nbSurvey = SurveysGroups::model()->countByAttributes(array("parent_id"=>$this->gsid)); + $nbSurvey = SurveysGroups::model()->countByAttributes(array("parent_id" => $this->gsid)); return $nbSurvey > 0; } - public function getAllParents($bOnlyGsid=false) + public function getAllParents($bOnlyGsid = false) { $aParents = array(); $oRSurveyGroup = $this; - while (!empty($oRSurveyGroup->parent_id)){ + while (!empty($oRSurveyGroup->parent_id)) { $oRSurveyGroup = SurveysGroups::model()->findByPk($oRSurveyGroup->parent_id); - $aParents[] = ($bOnlyGsid)?$oRSurveyGroup->gsid:$oRSurveyGroup; + $aParents[] = ($bOnlyGsid) ? $oRSurveyGroup->gsid : $oRSurveyGroup; } return $aParents; @@ -295,23 +296,23 @@ public function getAllParents($bOnlyGsid=false) */ public function getButtons() { - $sDeleteUrl = App()->createUrl("admin/surveysgroups/sa/delete", array("id"=>$this->gsid)); - $sEditUrl = App()->createUrl("admin/surveysgroups/sa/update", array("id"=>$this->gsid)); - $sSurveySettingsUrl = App()->createUrl("admin/surveysgroups/sa/surveysettings", array("id"=>$this->gsid)); - $sPermissionUrl = App()->createUrl("surveysGroupsPermission/index", array("id"=>$this->gsid)); + $sDeleteUrl = App()->createUrl("admin/surveysgroups/sa/delete", array("id" => $this->gsid)); + $sEditUrl = App()->createUrl("admin/surveysgroups/sa/update", array("id" => $this->gsid)); + $sSurveySettingsUrl = App()->createUrl("admin/surveysgroups/sa/surveysettings", array("id" => $this->gsid)); + $sPermissionUrl = App()->createUrl("surveysGroupsPermission/index", array("id" => $this->gsid)); $button = ''; - if($this->hasPermission('group','read')) { - $button .= ''.gT('Edit survey group').''; + if ($this->hasPermission('group', 'read')) { + $button .= '' . gT('Edit survey group') . ''; } - if($this->hasPermission('surveysettings','read')) { - $button .= ''.gT('Survey settings').''; + if ($this->hasPermission('surveysettings', 'read')) { + $button .= '' . gT('Survey settings') . ''; } - if ($this->hasPermission('permission','read')) { - $button .= ''.gT('Permission').''; + if ($this->hasPermission('permission', 'read')) { + $button .= '' . gT('Permission') . ''; } /* Can not delete group #1 + with survey (or move it to hasPermission function ?) */ - if ($this->gsid!=1 && !$this->hasSurveys && $this->hasPermission('group','delete')) { - $button .= ''.gT('Delete survey group').''; + if ($this->gsid != 1 && !$this->hasSurveys && $this->hasPermission('group', 'delete')) { + $button .= '' . gT('Delete survey group') . ''; } return $button; @@ -324,7 +325,7 @@ public function getButtons() public static function getSurveyGroupsList() { $aSurveyList = []; - $criteria = new CDbCriteria; + $criteria = new CDbCriteria(); $criteriaPerm = self::getPermissionCriteria(); $criteria->mergeWith($criteriaPerm, 'AND'); @@ -345,14 +346,14 @@ public function getNextOrderPosition() public function getParentGroupOptions($gsid = null) { - $criteria = new CDbCriteria; - if (!empty($gsid)){ - $criteria->compare("t.gsid", '<>'. $gsid); + $criteria = new CDbCriteria(); + if (!empty($gsid)) { + $criteria->compare("t.gsid", '<>' . $gsid); } // Permission $criteriaPerm = self::getPermissionCriteria(); $criteria->mergeWith($criteriaPerm, 'AND'); - if($gsid && $this->parent_id) { + if ($gsid && $this->parent_id) { /* If gsid is set : be sure to add current parent */ $criteria->compare("t.gsid", $this->parent_id, false, 'OR'); } @@ -366,8 +367,8 @@ public function getParentGroupOptions($gsid = null) $aParentsGsid = $oSurveysGroup->getAllParents(true); - if ( ! in_array( $this->gsid, $aParentsGsid ) ) { - $options[''.($oSurveysGroup->gsid).''] = '('.$oSurveysGroup->name.') '.$oSurveysGroup->title; + if (! in_array($this->gsid, $aParentsGsid)) { + $options['' . ($oSurveysGroup->gsid) . ''] = '(' . $oSurveysGroup->name . ') ' . $oSurveysGroup->title; } } //return join('\n',$options); @@ -393,19 +394,19 @@ public static function model($className = __CLASS__) */ protected static function getPermissionCriteria() { - $criteriaPerm = new CDbCriteria; + $criteriaPerm = new CDbCriteria(); if (!Permission::model()->hasGlobalPermission("surveys", 'read') || !Permission::model()->hasGlobalPermission("surveysgroups", 'read')) { /* owner of surveygroup */ $criteriaPerm->compare('t.owner_id', Yii::app()->user->id, false); /* Simple permission on SurveysGroup inside a group */ $criteriaPerm->mergeWith(array( - 'join'=>"LEFT JOIN {{permissions}} AS permissions ON (permissions.entity_id = t.gsid AND permissions.permission='group' AND permissions.entity='surveysgroups' AND permissions.uid='".Yii::app()->user->id."') ", + 'join' => "LEFT JOIN {{permissions}} AS permissions ON (permissions.entity_id = t.gsid AND permissions.permission='group' AND permissions.entity='surveysgroups' AND permissions.uid='" . Yii::app()->user->id . "') ", )); $criteriaPerm->compare('permissions.read_p', '1', false, 'OR'); /* Permission on Survey inside a group */ $criteriaPerm->mergeWith(array( - 'join'=>"LEFT JOIN {{surveys}} AS surveys ON (surveys.gsid = t.gsid) - LEFT JOIN {{permissions}} AS surveypermissions ON (surveypermissions.entity_id = surveys.sid AND surveypermissions.permission='survey' AND surveypermissions.entity='survey' AND surveypermissions.uid='".Yii::app()->user->id."') ", + 'join' => "LEFT JOIN {{surveys}} AS surveys ON (surveys.gsid = t.gsid) + LEFT JOIN {{permissions}} AS surveypermissions ON (surveypermissions.entity_id = surveys.sid AND surveypermissions.permission='survey' AND surveypermissions.entity='survey' AND surveypermissions.uid='" . Yii::app()->user->id . "') ", )); $criteriaPerm->compare('surveys.owner_id', Yii::app()->user->id, false, 'OR'); $criteriaPerm->compare('surveypermissions.read_p', '1', false, 'OR'); @@ -489,11 +490,10 @@ public function hasPermission($sPermission, $sCRUD = 'read', $iUserID = null) return true; } /* Specific need gsid */ - if(!$this->gsid) { + if (!$this->gsid) { return false; } /* Finally : return specific one */ return Permission::model()->hasPermission($this->gsid, 'surveysgroups', $sPermission, $sCRUD, $iUserID); } - } diff --git a/application/models/SurveysGroupsettings.php b/application/models/SurveysGroupsettings.php index 324ae8277d4..4db816960de 100644 --- a/application/models/SurveysGroupsettings.php +++ b/application/models/SurveysGroupsettings.php @@ -66,9 +66,9 @@ class SurveysGroupsettings extends LSActiveRecord protected $optionAttributesInteger = array('owner_id', 'tokenlength', 'questionindex', 'navigationdelay'); protected $optionAttributesChar = array('anonymized', 'savetimings', 'datestamp', 'usecookie', 'allowregister', 'allowsave', 'autoredirect', 'allowprev', 'printanswers', 'ipaddr','ipanonymize', 'refurl', 'publicstatistics', 'publicgraphs', 'listpublic', 'htmlemail', 'sendconfirmation', 'tokenanswerspersistence', - 'assessments', 'showxquestions', 'showgroupinfo', 'shownoanswer', 'showqnumcode', 'showwelcome', 'showprogress', 'nokeyboard', + 'assessments', 'showxquestions', 'showgroupinfo', 'shownoanswer', 'showqnumcode', 'showwelcome', 'showprogress', 'nokeyboard', 'alloweditaftercompletion'); - protected $optionAttributesText = array('admin', 'adminemail', 'template', 'bounce_email', 'emailresponseto', 'emailnotificationto'); + protected $optionAttributesText = array('admin', 'adminemail', 'template', 'bounce_email', 'emailresponseto', 'emailnotificationto'); public $showInherited = 1; public $active; @@ -76,188 +76,188 @@ class SurveysGroupsettings extends LSActiveRecord /** - * @return string the associated database table name - */ + * @return string the associated database table name + */ public function tableName() - { - return '{{surveys_groupsettings}}'; - } + { + return '{{surveys_groupsettings}}'; + } - /** - * @return array validation rules for model attributes. - */ - public function rules() - { - // NOTE: you should only define rules for those attributes that + /** + * @return array validation rules for model attributes. + */ + public function rules() + { + // NOTE: you should only define rules for those attributes that // will receive user inputs. - $validator = new LSYii_Validators; - return array( - array('autonumber_start, showsurveypolicynotice, tokenlength, questionindex, navigationdelay, owner_id', 'numerical', 'integerOnly'=>true), - array('admin', 'length', 'max'=>50), - array('anonymized, format, savetimings, datestamp, usecookie, allowregister, allowsave, autoredirect, allowprev, printanswers, ipaddr, refurl, publicstatistics, publicgraphs, listpublic, htmlemail, sendconfirmation, tokenanswerspersistence, assessments, usecaptcha, showxquestions, showgroupinfo, shownoanswer, showqnumcode, showwelcome, showprogress, nokeyboard, alloweditaftercompletion, ipanonymize', 'length', 'max'=>1), - array('adminemail, bounce_email', 'length', 'max'=>255), - array('template', 'length', 'max'=>100), - array('expires, startdate, datecreated, attributedescriptions, emailresponseto, emailnotificationto', 'safe'), - // The following rule is used by search(). - // @todo Please remove those attributes that should not be searched. - array('gsid, owner_id, admin, expires, startdate, adminemail, anonymized, format, + $validator = new LSYii_Validators(); + return array( + array('autonumber_start, showsurveypolicynotice, tokenlength, questionindex, navigationdelay, owner_id', 'numerical', 'integerOnly' => true), + array('admin', 'length', 'max' => 50), + array('anonymized, format, savetimings, datestamp, usecookie, allowregister, allowsave, autoredirect, allowprev, printanswers, ipaddr, refurl, publicstatistics, publicgraphs, listpublic, htmlemail, sendconfirmation, tokenanswerspersistence, assessments, usecaptcha, showxquestions, showgroupinfo, shownoanswer, showqnumcode, showwelcome, showprogress, nokeyboard, alloweditaftercompletion, ipanonymize', 'length', 'max' => 1), + array('adminemail, bounce_email', 'length', 'max' => 255), + array('template', 'length', 'max' => 100), + array('expires, startdate, datecreated, attributedescriptions, emailresponseto, emailnotificationto', 'safe'), + // The following rule is used by search(). + // @todo Please remove those attributes that should not be searched. + array('gsid, owner_id, admin, expires, startdate, adminemail, anonymized, format, savetimings, template, datestamp, usecookie, allowregister, allowsave, autonumber_start, autoredirect, allowprev, printanswers, ipaddr, refurl, datecreated, showsurveypolicynotice, publicstatistics, publicgraphs, listpublic, htmlemail, sendconfirmation, tokenanswerspersistence, assessments, usecaptcha, bounce_email, attributedescriptions, emailresponseto, emailnotificationto, tokenlength, showxquestions, showgroupinfo, shownoanswer, showqnumcode, showwelcome, showprogress, - questionindex, navigationdelay, nokeyboard, alloweditaftercompletion', 'safe', 'on'=>'search'), - ); + questionindex, navigationdelay, nokeyboard, alloweditaftercompletion', 'safe', 'on' => 'search'), + ); } - /** - * @return array relational rules. - */ - public function relations() - { - // NOTE: you may need to adjust the relation name and the related - // class name for the relations automatically generated below. - return array( + /** + * @return array relational rules. + */ + public function relations() + { + // NOTE: you may need to adjust the relation name and the related + // class name for the relations automatically generated below. + return array( 'Survey' => array(self::HAS_MANY, 'Survey', 'gsid'), 'SurveysGroups' => array(self::HAS_ONE, 'SurveysGroups', 'gsid'), 'owner' => array(self::BELONGS_TO, 'User', 'owner_id'), - ); - } + ); + } - /** - * @return array customized attribute labels (name=>label) - */ - public function attributeLabels() - { - return array( - 'gsid' => 'Gsid', - 'owner_id' => 'OwnerId', - 'admin' => 'Admin', - 'expires' => 'Expires', - 'startdate' => 'Startdate', - 'adminemail' => 'Adminemail', - 'anonymized' => 'Anonymized', - 'format' => 'Format', - 'savetimings' => 'Savetimings', - 'template' => 'Template', - 'datestamp' => 'Datestamp', - 'usecookie' => 'Usecookie', - 'allowregister' => 'Allowregister', - 'allowsave' => 'Allowsave', - 'autonumber_start' => 'Autonumber Start', - 'autoredirect' => 'Autoredirect', - 'allowprev' => 'Allowprev', - 'printanswers' => 'Printanswers', - 'ipaddr' => 'Ipaddr', - 'refurl' => 'Refurl', - 'datecreated' => 'Datecreated', - 'showsurveypolicynotice' => 'Showsurveypolicynotice', - 'publicstatistics' => 'Publicstatistics', - 'publicgraphs' => 'Publicgraphs', - 'listpublic' => 'Listpublic', - 'htmlemail' => 'Htmlemail', - 'sendconfirmation' => 'Sendconfirmation', - 'tokenanswerspersistence' => 'Tokenanswerspersistence', - 'assessments' => 'Assessments', - 'usecaptcha' => 'Usecaptcha', - 'bounce_email' => 'Bounce Email', - 'attributedescriptions' => 'Attributedescriptions', - 'emailresponseto' => 'Emailresponseto', - 'emailnotificationto' => 'Emailnotificationto', - 'tokenlength' => 'Tokenlength', - 'showxquestions' => 'Showxquestions', - 'showgroupinfo' => 'Showgroupinfo', - 'shownoanswer' => 'Shownoanswer', - 'showqnumcode' => 'Showqnumcode', - 'showwelcome' => 'Showwelcome', - 'showprogress' => 'Showprogress', - 'questionindex' => 'Questionindex', - 'navigationdelay' => 'Navigationdelay', - 'nokeyboard' => 'Nokeyboard', - 'alloweditaftercompletion' => 'Alloweditaftercompletion', - ); - } + /** + * @return array customized attribute labels (name=>label) + */ + public function attributeLabels() + { + return array( + 'gsid' => 'Gsid', + 'owner_id' => 'OwnerId', + 'admin' => 'Admin', + 'expires' => 'Expires', + 'startdate' => 'Startdate', + 'adminemail' => 'Adminemail', + 'anonymized' => 'Anonymized', + 'format' => 'Format', + 'savetimings' => 'Savetimings', + 'template' => 'Template', + 'datestamp' => 'Datestamp', + 'usecookie' => 'Usecookie', + 'allowregister' => 'Allowregister', + 'allowsave' => 'Allowsave', + 'autonumber_start' => 'Autonumber Start', + 'autoredirect' => 'Autoredirect', + 'allowprev' => 'Allowprev', + 'printanswers' => 'Printanswers', + 'ipaddr' => 'Ipaddr', + 'refurl' => 'Refurl', + 'datecreated' => 'Datecreated', + 'showsurveypolicynotice' => 'Showsurveypolicynotice', + 'publicstatistics' => 'Publicstatistics', + 'publicgraphs' => 'Publicgraphs', + 'listpublic' => 'Listpublic', + 'htmlemail' => 'Htmlemail', + 'sendconfirmation' => 'Sendconfirmation', + 'tokenanswerspersistence' => 'Tokenanswerspersistence', + 'assessments' => 'Assessments', + 'usecaptcha' => 'Usecaptcha', + 'bounce_email' => 'Bounce Email', + 'attributedescriptions' => 'Attributedescriptions', + 'emailresponseto' => 'Emailresponseto', + 'emailnotificationto' => 'Emailnotificationto', + 'tokenlength' => 'Tokenlength', + 'showxquestions' => 'Showxquestions', + 'showgroupinfo' => 'Showgroupinfo', + 'shownoanswer' => 'Shownoanswer', + 'showqnumcode' => 'Showqnumcode', + 'showwelcome' => 'Showwelcome', + 'showprogress' => 'Showprogress', + 'questionindex' => 'Questionindex', + 'navigationdelay' => 'Navigationdelay', + 'nokeyboard' => 'Nokeyboard', + 'alloweditaftercompletion' => 'Alloweditaftercompletion', + ); + } - /** - * Retrieves a list of models based on the current search/filter conditions. - * - * Typical usecase: - * - Initialize the model fields with values from filter form. - * - Execute this method to get CActiveDataProvider instance which will filter - * models according to data in model fields. - * - Pass data provider to CGridView, CListView or any similar widget. - * - * @return CActiveDataProvider the data provider that can return the models - * based on the search/filter conditions. - */ - public function search() - { - // @todo Please modify the following code to remove attributes that should not be searched. + /** + * Retrieves a list of models based on the current search/filter conditions. + * + * Typical usecase: + * - Initialize the model fields with values from filter form. + * - Execute this method to get CActiveDataProvider instance which will filter + * models according to data in model fields. + * - Pass data provider to CGridView, CListView or any similar widget. + * + * @return CActiveDataProvider the data provider that can return the models + * based on the search/filter conditions. + */ + public function search() + { + // @todo Please modify the following code to remove attributes that should not be searched. - $criteria=new CDbCriteria; + $criteria = new CDbCriteria(); - $criteria->compare('gsid',$this->gsid); - $criteria->compare('owner_id',$this->owner_id); - $criteria->compare('admin',$this->admin,true); - $criteria->compare('expires',$this->expires,true); - $criteria->compare('startdate',$this->startdate,true); - $criteria->compare('adminemail',$this->adminemail,true); - $criteria->compare('anonymized',$this->anonymized,true); - $criteria->compare('format',$this->format,true); - $criteria->compare('savetimings',$this->savetimings,true); - $criteria->compare('template',$this->template,true); - $criteria->compare('datestamp',$this->datestamp,true); - $criteria->compare('usecookie',$this->usecookie,true); - $criteria->compare('allowregister',$this->allowregister,true); - $criteria->compare('allowsave',$this->allowsave,true); - $criteria->compare('autonumber_start',$this->autonumber_start); - $criteria->compare('autoredirect',$this->autoredirect,true); - $criteria->compare('allowprev',$this->allowprev,true); - $criteria->compare('printanswers',$this->printanswers,true); - $criteria->compare('ipaddr',$this->ipaddr,true); - $criteria->compare('refurl',$this->refurl,true); - $criteria->compare('datecreated',$this->datecreated,true); - $criteria->compare('showsurveypolicynotice',$this->showsurveypolicynotice); - $criteria->compare('publicstatistics',$this->publicstatistics,true); - $criteria->compare('publicgraphs',$this->publicgraphs,true); - $criteria->compare('listpublic',$this->listpublic,true); - $criteria->compare('htmlemail',$this->htmlemail,true); - $criteria->compare('sendconfirmation',$this->sendconfirmation,true); - $criteria->compare('tokenanswerspersistence',$this->tokenanswerspersistence,true); - $criteria->compare('assessments',$this->assessments,true); - $criteria->compare('usecaptcha',$this->usecaptcha,true); - $criteria->compare('bounce_email',$this->bounce_email,true); - $criteria->compare('attributedescriptions',$this->attributedescriptions,true); - $criteria->compare('emailresponseto',$this->emailresponseto,true); - $criteria->compare('emailnotificationto',$this->emailnotificationto,true); - $criteria->compare('tokenlength',$this->tokenlength); - $criteria->compare('showxquestions',$this->showxquestions,true); - $criteria->compare('showgroupinfo',$this->showgroupinfo,true); - $criteria->compare('shownoanswer',$this->shownoanswer,true); - $criteria->compare('showqnumcode',$this->showqnumcode,true); - $criteria->compare('showwelcome',$this->showwelcome,true); - $criteria->compare('showprogress',$this->showprogress,true); - $criteria->compare('questionindex',$this->questionindex); - $criteria->compare('navigationdelay',$this->navigationdelay); - $criteria->compare('nokeyboard',$this->nokeyboard,true); - $criteria->compare('alloweditaftercompletion',$this->alloweditaftercompletion,true); + $criteria->compare('gsid', $this->gsid); + $criteria->compare('owner_id', $this->owner_id); + $criteria->compare('admin', $this->admin, true); + $criteria->compare('expires', $this->expires, true); + $criteria->compare('startdate', $this->startdate, true); + $criteria->compare('adminemail', $this->adminemail, true); + $criteria->compare('anonymized', $this->anonymized, true); + $criteria->compare('format', $this->format, true); + $criteria->compare('savetimings', $this->savetimings, true); + $criteria->compare('template', $this->template, true); + $criteria->compare('datestamp', $this->datestamp, true); + $criteria->compare('usecookie', $this->usecookie, true); + $criteria->compare('allowregister', $this->allowregister, true); + $criteria->compare('allowsave', $this->allowsave, true); + $criteria->compare('autonumber_start', $this->autonumber_start); + $criteria->compare('autoredirect', $this->autoredirect, true); + $criteria->compare('allowprev', $this->allowprev, true); + $criteria->compare('printanswers', $this->printanswers, true); + $criteria->compare('ipaddr', $this->ipaddr, true); + $criteria->compare('refurl', $this->refurl, true); + $criteria->compare('datecreated', $this->datecreated, true); + $criteria->compare('showsurveypolicynotice', $this->showsurveypolicynotice); + $criteria->compare('publicstatistics', $this->publicstatistics, true); + $criteria->compare('publicgraphs', $this->publicgraphs, true); + $criteria->compare('listpublic', $this->listpublic, true); + $criteria->compare('htmlemail', $this->htmlemail, true); + $criteria->compare('sendconfirmation', $this->sendconfirmation, true); + $criteria->compare('tokenanswerspersistence', $this->tokenanswerspersistence, true); + $criteria->compare('assessments', $this->assessments, true); + $criteria->compare('usecaptcha', $this->usecaptcha, true); + $criteria->compare('bounce_email', $this->bounce_email, true); + $criteria->compare('attributedescriptions', $this->attributedescriptions, true); + $criteria->compare('emailresponseto', $this->emailresponseto, true); + $criteria->compare('emailnotificationto', $this->emailnotificationto, true); + $criteria->compare('tokenlength', $this->tokenlength); + $criteria->compare('showxquestions', $this->showxquestions, true); + $criteria->compare('showgroupinfo', $this->showgroupinfo, true); + $criteria->compare('shownoanswer', $this->shownoanswer, true); + $criteria->compare('showqnumcode', $this->showqnumcode, true); + $criteria->compare('showwelcome', $this->showwelcome, true); + $criteria->compare('showprogress', $this->showprogress, true); + $criteria->compare('questionindex', $this->questionindex); + $criteria->compare('navigationdelay', $this->navigationdelay); + $criteria->compare('nokeyboard', $this->nokeyboard, true); + $criteria->compare('alloweditaftercompletion', $this->alloweditaftercompletion, true); - return new CActiveDataProvider($this, array( - 'criteria'=>$criteria, - )); - } + return new CActiveDataProvider($this, array( + 'criteria' => $criteria, + )); + } - /** - * Returns the static model of the specified AR class. - * Please note that you should have this exact method in all your CActiveRecord descendants! - * @param string $className active record class name. - * @return SurveysGroupsettings the static model class - */ - public static function model($className=__CLASS__) - { - return parent::model($className); + /** + * Returns the static model of the specified AR class. + * Please note that you should have this exact method in all your CActiveRecord descendants! + * @param string $className active record class name. + * @return SurveysGroupsettings the static model class + */ + public static function model($className = __CLASS__) + { + return parent::model($className); } /** @@ -265,7 +265,7 @@ public static function model($className=__CLASS__) */ public function getIsActive() { - if (is_object($this->Survey)){ + if (is_object($this->Survey)) { return ($this->Survey->active === 'Y'); } else { return false; @@ -277,7 +277,7 @@ public function getIsActive() */ public function getIsAnonymized() { - if (is_object($this->Survey)){ + if (is_object($this->Survey)) { return ($this->Survey->anonymized === 'Y'); } else { return false; @@ -298,9 +298,10 @@ public function getIsAnonymized() * @param bool $bRealValues * @return SurveysGroupsettings instance */ - public static function getInstance($iSurveyGroupId = 0, $oSurvey = null, $instance = null, $iStep = 1, $bRealValues = false){ + public static function getInstance($iSurveyGroupId = 0, $oSurvey = null, $instance = null, $iStep = 1, $bRealValues = false) + { - if ($iSurveyGroupId > 0){ + if ($iSurveyGroupId > 0) { $model = SurveysGroupsettings::model()->with('SurveysGroups')->findByPk($iSurveyGroupId); } else { //this is the default group setting with gsid=0 !!! @@ -308,8 +309,8 @@ public static function getInstance($iSurveyGroupId = 0, $oSurvey = null, $instan } // set initial values to instance on first run - if ($instance === null){ - if ($model === null){ + if ($instance === null) { + if ($model === null) { $instance = new SurveysGroupsettings(); $instance->optionAttributes = new stdClass(); } else { @@ -322,46 +323,46 @@ public static function getInstance($iSurveyGroupId = 0, $oSurvey = null, $instan $instance->oOptionLabels = new stdClass(); // set visibility of 'inherit' options on buttons - if ($iSurveyGroupId == 0){ + if ($iSurveyGroupId == 0) { $instance->showInherited = 0; } else { $instance->showInherited = 1; } // set instance options from survey model, used for frontend redering - if (($oSurvey !== null && $bRealValues)){ - foreach($instance->optionAttributes as $key=>$attribute){ + if (($oSurvey !== null && $bRealValues)) { + foreach ($instance->optionAttributes as $key => $attribute) { $instance->oOptions->{$attribute} = $oSurvey->$attribute; - $instance->oOptionLabels->{$attribute} = self::translateOptionLabels($instance, $attribute, $oSurvey->$attribute); + $instance->oOptionLabels->{$attribute} = self::translateOptionLabels($instance, $attribute, $oSurvey->$attribute); } } // set instance options from global model - if ($iSurveyGroupId == 0){ - foreach($instance->optionAttributes as $key=>$attribute){ + if ($iSurveyGroupId == 0) { + foreach ($instance->optionAttributes as $key => $attribute) { $instance->oOptions->{$attribute} = $model->$attribute; - $instance->oOptionLabels->{$attribute} = self::translateOptionLabels($instance, $attribute, $model->$attribute); + $instance->oOptionLabels->{$attribute} = self::translateOptionLabels($instance, $attribute, $model->$attribute); } } } // set instance options only if option needs to be inherited - if ($oSurvey !== null || ($oSurvey === null && $iStep > 1)){ - foreach($instance->optionAttributes as $key=>$attribute){ - if ((empty($instance->oOptions->{$attribute})) || (!empty($instance->oOptions->{$attribute}) && ($instance->oOptions->{$attribute} === 'inherit' || $instance->oOptions->{$attribute} === 'I' || $instance->oOptions->{$attribute} === '-1'))){ + if ($oSurvey !== null || ($oSurvey === null && $iStep > 1)) { + foreach ($instance->optionAttributes as $key => $attribute) { + if ((empty($instance->oOptions->{$attribute})) || (!empty($instance->oOptions->{$attribute}) && ($instance->oOptions->{$attribute} === 'inherit' || $instance->oOptions->{$attribute} === 'I' || $instance->oOptions->{$attribute} === '-1'))) { $instance->oOptions->{$attribute} = $model->$attribute; - $instance->oOptionLabels->{$attribute} = self::translateOptionLabels($instance, $attribute, $model->$attribute); + $instance->oOptionLabels->{$attribute} = self::translateOptionLabels($instance, $attribute, $model->$attribute); } } } // fetch parent instance only if parent_id exists - if ($iSurveyGroupId > 0 && !empty($model->SurveysGroups) && $model->SurveysGroups->parent_id !== null){ + if ($iSurveyGroupId > 0 && !empty($model->SurveysGroups) && $model->SurveysGroups->parent_id !== null) { self::getInstance($model->SurveysGroups->parent_id, null, $instance, $iStep + 1); - } + } // fetch global instance - if ($iSurveyGroupId > 0 && !empty($model->SurveysGroups) && $model->SurveysGroups->parent_id === null){ + if ($iSurveyGroupId > 0 && !empty($model->SurveysGroups) && $model->SurveysGroups->parent_id === null) { self::getInstance(0, null, $instance, $iStep + 1); // calling global settings } @@ -371,40 +372,41 @@ public static function getInstance($iSurveyGroupId = 0, $oSurvey = null, $instan /** * @return string */ - protected static function translateOptionLabels($instance, $attribute, $value){ + protected static function translateOptionLabels($instance, $attribute, $value) + { // replace option labels on forms - if ($attribute == 'usecaptcha'){ + if ($attribute == 'usecaptcha') { $usecap = $value; - if ($usecap === 'A' || $usecap === 'B' || $usecap === 'C' || $usecap === 'X' || $usecap === 'F' || $usecap === 'H' || $usecap === 'K' || $usecap === '0'){ + if ($usecap === 'A' || $usecap === 'B' || $usecap === 'C' || $usecap === 'X' || $usecap === 'F' || $usecap === 'H' || $usecap === 'K' || $usecap === '0') { $instance->oOptionLabels->useCaptchaSurveyAccess = gT("On"); } else { $instance->oOptionLabels->useCaptchaSurveyAccess = gT("Off"); } - if ($usecap === 'A' || $usecap === 'B' || $usecap === 'D' || $usecap === 'R' || $usecap === 'F' || $usecap === 'G' || $usecap === 'I' || $usecap === 'M'){ + if ($usecap === 'A' || $usecap === 'B' || $usecap === 'D' || $usecap === 'R' || $usecap === 'F' || $usecap === 'G' || $usecap === 'I' || $usecap === 'M') { $instance->oOptionLabels->useCaptchaRegistration = gT("On"); } else { $instance->oOptionLabels->useCaptchaRegistration = gT("Off"); } - if ($usecap === 'A' || $usecap === 'C' || $usecap === 'D' || $usecap === 'S' || $usecap === 'G' || $usecap === 'H' || $usecap === 'J' || $usecap === 'L'){ + if ($usecap === 'A' || $usecap === 'C' || $usecap === 'D' || $usecap === 'S' || $usecap === 'G' || $usecap === 'H' || $usecap === 'J' || $usecap === 'L') { $instance->oOptionLabels->useCaptchaSaveAndLoad = gT("On"); } else { $instance->oOptionLabels->useCaptchaSaveAndLoad = gT("Off"); } - } elseif ($attribute == 'owner_id' && $value != -1){ + } elseif ($attribute == 'owner_id' && $value != -1) { $instance->oOptions->owner = ""; $instance->oOptions->ownerLabel = ""; $oUser = User::model()->findByPk($instance->oOptions->{$attribute}); - if(!empty($oUser)) { + if (!empty($oUser)) { $instance->oOptions->owner = $oUser->attributes; - $instance->oOptions->ownerLabel = $oUser->users_name.($oUser->full_name ? " - ".$oUser->full_name : ""); + $instance->oOptions->ownerLabel = $oUser->users_name . ($oUser->full_name ? " - " . $oUser->full_name : ""); } - } elseif ($attribute == 'format' && $value != -1){ + } elseif ($attribute == 'format' && $value != -1) { return str_replace(array('S', 'G', 'A'), array(gT("Question by question"), gT("Group by group"), gT("All in one")), $value); - } elseif ($attribute == 'questionindex' && $value != -1){ + } elseif ($attribute == 'questionindex' && $value != -1) { return str_replace(array('0', '1', '2'), array(gT("Disabled"), gT("Incremental"), gT("Full")), $value); - } elseif ($attribute == 'showgroupinfo'){ + } elseif ($attribute == 'showgroupinfo') { return str_replace(array('B', 'D', 'N', 'X'), array(gT("Show both"), gT("Show group description only"), gT("Show group name only"), gT("Hide both")), $value); - } elseif ($attribute == 'showqnumcode'){ + } elseif ($attribute == 'showqnumcode') { return str_replace(array('B', 'C', 'N', 'X'), array(gT("Show both"), gT("Show question code only"), gT("Show question number only"), gT("Hide both")), $value); } else { return str_replace(array('Y', 'N'), array(gT("On"), gT("Off")), $value); @@ -433,17 +435,17 @@ public function setToInherit() // set attribute values to inherit, used only when creating new Survey instance $this->usecaptcha = 'E'; $this->format = 'I'; - foreach ($this->optionAttributesInteger as $attribute){ + foreach ($this->optionAttributesInteger as $attribute) { $this->$attribute = -1; } - foreach ($this->optionAttributesChar as $attribute){ + foreach ($this->optionAttributesChar as $attribute) { //fix for 16179 $dbversion = GetGlobalSetting('DBVersion'); - if( !($attribute==='ipanonymize' && ( $dbversion < 412 ))){ + if (!($attribute === 'ipanonymize' && ( $dbversion < 412 ))) { $this->$attribute = 'I'; } } - foreach ($this->optionAttributesText as $attribute){ + foreach ($this->optionAttributesText as $attribute) { $this->$attribute = 'inherit'; } } diff --git a/application/models/SurveysInGroup.php b/application/models/SurveysInGroup.php index 96053dbb1c6..07f0f62dde6 100644 --- a/application/models/SurveysInGroup.php +++ b/application/models/SurveysInGroup.php @@ -1,13 +1,15 @@ -getConfig('ownerManageAllSurveysInGroup')) { + if (!App()->getConfig('ownerManageAllSurveysInGroup')) { return null; } return $this->owner_id; @@ -84,11 +86,10 @@ public function hasPermission($sPermission, $sCRUD = 'read', $iUserID = null) return true; } /* Specific need gsid */ - if(!$this->gsid) { + if (!$this->gsid) { return false; } /* Finally : return specific one */ return Permission::model()->hasPermission($this->gsid, 'surveysingroup', $sPermission, $sCRUD, $iUserID); } - } diff --git a/application/models/Template.php b/application/models/Template.php index e39c3400b80..76e72ac0285 100755 --- a/application/models/Template.php +++ b/application/models/Template.php @@ -77,15 +77,15 @@ public function rules() // will receive user inputs. return array( array('name, title, creation_date', 'required'), - array('owner_id', 'numerical', 'integerOnly'=>true), - array('name, author, extends', 'length', 'max'=>150), - array('folder, version, api_version, view_folder, files_folder', 'length', 'max'=>45), - array('title', 'length', 'max'=>100), - array('author_email, author_url', 'length', 'max'=>255), + array('owner_id', 'numerical', 'integerOnly' => true), + array('name, author, extends', 'length', 'max' => 150), + array('folder, version, api_version, view_folder, files_folder', 'length', 'max' => 45), + array('title', 'length', 'max' => 100), + array('author_email, author_url', 'length', 'max' => 255), array('copyright, license, description, last_update', 'safe'), // The following rule is used by search(). // @todo Please remove those attributes that should not be searched. - array('name, folder, title, creation_date, author, author_email, author_url, copyright, license, version, api_version, view_folder, files_folder, description, last_update, owner_id, extends', 'safe', 'on'=>'search'), + array('name, folder, title, creation_date, author, author_email, author_url, copyright, license, version, api_version, view_folder, files_folder, description, last_update, owner_id, extends', 'safe', 'on' => 'search'), ); } @@ -183,8 +183,9 @@ public static function templateNameFilter($sTemplateName) SettingGlobal::setSetting('defaulttheme', $sTemplateName); $sDefaultTemplate = App()->getConfig('defaulttheme'); - if(method_exists(Yii::app(), 'setFlashMessage')) + if (method_exists(Yii::app(), 'setFlashMessage')) { Yii::app()->setFlashMessage(sprintf(gT("Default survey theme %s is not installed. Now %s is the new default survey theme"), $sRequestedTemplate, $sTemplateName), 'error'); + } self::$aNamesFiltered[$sTemplateName] = $sTemplateName; return $sTemplateName; @@ -219,7 +220,6 @@ public function checkTemplateExtends() if (!empty($this->extends)) { $oRTemplate = self::model()->findByPk($this->extends); if (empty($oRTemplate)) { - // Why? it blocks the user at login screen.... // It should return false and show a nice warning message. @@ -260,7 +260,7 @@ public function checkExtendsItSelf() */ public static function checkTemplateXML($sTemplateFolder) { - return (is_file(Yii::app()->getConfig("userthemerootdir").DIRECTORY_SEPARATOR.$sTemplateFolder.DIRECTORY_SEPARATOR.'config.xml') || is_file(Yii::app()->getConfig("standardthemerootdir").DIRECTORY_SEPARATOR.$sTemplateFolder.DIRECTORY_SEPARATOR.'config.xml')); + return (is_file(Yii::app()->getConfig("userthemerootdir") . DIRECTORY_SEPARATOR . $sTemplateFolder . DIRECTORY_SEPARATOR . 'config.xml') || is_file(Yii::app()->getConfig("standardthemerootdir") . DIRECTORY_SEPARATOR . $sTemplateFolder . DIRECTORY_SEPARATOR . 'config.xml')); } /** @@ -300,9 +300,9 @@ public static function getTemplatePath($sTemplateName = "") } if (self::isStandardTemplate($sTemplateName)) { - return $aTemplatePath[$sTemplateName] = Yii::app()->getConfig("standardthemerootdir").DIRECTORY_SEPARATOR.$oTemplate->folder; + return $aTemplatePath[$sTemplateName] = Yii::app()->getConfig("standardthemerootdir") . DIRECTORY_SEPARATOR . $oTemplate->folder; } else { - return $aTemplatePath[$sTemplateName] = Yii::app()->getConfig("userthemerootdir").DIRECTORY_SEPARATOR.$oTemplate->folder; + return $aTemplatePath[$sTemplateName] = Yii::app()->getConfig("userthemerootdir") . DIRECTORY_SEPARATOR . $oTemplate->folder; } } @@ -324,7 +324,7 @@ public static function getTemplateConfiguration($sTemplateName = null, $iSurveyI { // First we try to get a confifuration row from DB - if (!$bForceXML ) { + if (!$bForceXML) { // The name need to be filtred only for DB version. From TemplateEditor, the template is not installed. $sTemplateName = (empty($sTemplateName)) ? null : self::templateNameFilter($sTemplateName); $oTemplateConfigurationModel = TemplateConfiguration::getInstance($sTemplateName, $iSurveyGroupId, $iSurveyId, $abstractInstance); @@ -333,7 +333,6 @@ public static function getTemplateConfiguration($sTemplateName = null, $iSurveyI // If no row found, or if the template folder for this configuration row doesn't exist we load the XML config (which will load the default XML) if ($bForceXML || !is_a($oTemplateConfigurationModel, 'TemplateConfiguration') || !$oTemplateConfigurationModel->checkTemplate()) { - $oTemplateConfigurationModel = new TemplateManifest(null); $oTemplateConfigurationModel->setBasics($sTemplateName, $iSurveyId); } @@ -349,7 +348,7 @@ public static function getTemplateConfiguration($sTemplateName = null, $iSurveyI * @param string $filesDir * @return array */ - static public function getOtherFiles($filesDir) + public static function getOtherFiles($filesDir) { $otherFiles = array(); if (file_exists($filesDir) && $handle = opendir($filesDir)) { @@ -389,14 +388,13 @@ public static function getTemplateURL($sTemplateName = "") if (is_object($oTemplate)) { if (self::isStandardTemplate($sTemplateName)) { - return $aTemplateUrl[$sTemplateName] = Yii::app()->getConfig("standardthemerooturl").'/'.$oTemplate->folder.'/'; + return $aTemplateUrl[$sTemplateName] = Yii::app()->getConfig("standardthemerooturl") . '/' . $oTemplate->folder . '/'; } else { - return $aTemplateUrl[$sTemplateName] = Yii::app()->getConfig("userthemerooturl").'/'.$oTemplate->folder.'/'; + return $aTemplateUrl[$sTemplateName] = Yii::app()->getConfig("userthemerooturl") . '/' . $oTemplate->folder . '/'; } } else { return ''; } - } @@ -421,7 +419,6 @@ public static function getTemplatesFileFolder($sTemplateName = "") } else { return ''; } - } /** @@ -444,7 +441,6 @@ public static function getTemplateList() $aTemplateList[$oTemplate->template_name] = (self::isStandardTemplate($oTemplate->template_name)) ? Yii::app()->getConfig("standardthemerootdir") . DIRECTORY_SEPARATOR . $oTemplate->template->folder : Yii::app()->getConfig("userthemerootdir") . DIRECTORY_SEPARATOR . $oTemplate->template->folder; } return $aTemplateList; - } /** @@ -495,27 +491,26 @@ public static function isStandardTemplate($sTemplateName) * @param boolean $last if you want to get the last instace without providing template name or sid * @return TemplateConfiguration */ - public static function getInstance($sTemplateName = null, $iSurveyId = null, $iSurveyGroupId = null, $bForceXML = null, $abstractInstance = false, $last=false) + public static function getInstance($sTemplateName = null, $iSurveyId = null, $iSurveyGroupId = null, $bForceXML = null, $abstractInstance = false, $last = false) { if ($bForceXML === null) { // Template developper could prefer to work with XML rather than DB as a first step, for quick and easy changes - $bForceXML = (App()->getConfig('force_xmlsettings_for_survey_rendering'))?true:false; - + $bForceXML = (App()->getConfig('force_xmlsettings_for_survey_rendering')) ? true : false; } // The error page from default template can be called when no survey found with a specific ID. - if ($sTemplateName === null && $iSurveyId === null && $last===false) { + if ($sTemplateName === null && $iSurveyId === null && $last === false) { $sTemplateName = App()->getConfig('defaulttheme'); } // TODO: this probably not use any more. Check and remove it. - if($abstractInstance === true) { + if ($abstractInstance === true) { return self::getTemplateConfiguration($sTemplateName, $iSurveyId, $iSurveyGroupId, $bForceXML, true); } - if ( empty(self::$instance) || ! self::isCorrectInstance($sTemplateName) ) { - self::$instance = self::getTemplateConfiguration($sTemplateName, $iSurveyId, $iSurveyGroupId, $bForceXML); - self::$instance->prepareTemplateRendering($sTemplateName, $iSurveyId); + if (empty(self::$instance) || ! self::isCorrectInstance($sTemplateName)) { + self::$instance = self::getTemplateConfiguration($sTemplateName, $iSurveyId, $iSurveyGroupId, $bForceXML); + self::$instance->prepareTemplateRendering($sTemplateName, $iSurveyId); } return self::getLastInstance(false); @@ -526,16 +521,17 @@ public static function getInstance($sTemplateName = null, $iSurveyId = null, $iS * @param boolean $bAutoGenerate : should the function try to generate an instance if it doesn't exist? * @return TemplateConfiguration */ - public static function getLastInstance($bAutoGenerate=true) + public static function getLastInstance($bAutoGenerate = true) { - if (empty(self::$instance)){ - if ($bAutoGenerate) - self::getInstance(); - else - throw new \Exception("No Survey theme was generated", 1); - } + if (empty(self::$instance)) { + if ($bAutoGenerate) { + self::getInstance(); + } else { + throw new \Exception("No Survey theme was generated", 1); + } + } - return self::$instance; + return self::$instance; } /** @@ -545,7 +541,7 @@ public static function getLastInstance($bAutoGenerate=true) */ public static function isCorrectInstance($sTemplateName = null) { - return ( $sTemplateName == null || self::$instance->sTemplateName == $sTemplateName); + return ( $sTemplateName == null || self::$instance->sTemplateName == $sTemplateName); } /** @@ -639,7 +635,7 @@ public static function getTemplateInFolder($sFolder) if ($sFolder && $handle = opendir($sFolder)) { while (false !== ($sFileName = readdir($handle))) { if (!is_file("$sFolder/$sFileName") && $sFileName != "." && $sFileName != ".." && $sFileName != ".svn" && (file_exists("{$sFolder}/{$sFileName}/config.xml"))) { - $aTemplateList[$sFileName] = $sFolder.DIRECTORY_SEPARATOR.$sFileName; + $aTemplateList[$sFileName] = $sFolder . DIRECTORY_SEPARATOR . $sFileName; } } closedir($handle); @@ -659,9 +655,9 @@ public function renameTo($sNewName) { Yii::import('application.helpers.sanitize_helper', true); $this->deleteAssetVersion(); - Survey::model()->updateAll(array('template' => $sNewName), "template = :oldname", array(':oldname'=>$this->name)); - Template::model()->updateAll(array('name' => $sNewName, 'folder' => $sNewName), "name = :oldname", array(':oldname'=>$this->name)); - Template::model()->updateAll(array('extends' => $sNewName), "extends = :oldname", array(':oldname'=>$this->name)); + Survey::model()->updateAll(array('template' => $sNewName), "template = :oldname", array(':oldname' => $this->name)); + Template::model()->updateAll(array('name' => $sNewName, 'folder' => $sNewName), "name = :oldname", array(':oldname' => $this->name)); + Template::model()->updateAll(array('extends' => $sNewName), "extends = :oldname", array(':oldname' => $this->name)); TemplateConfiguration::rename($this->name, $sNewName); TemplateManifest::rename($this->name, $sNewName); } @@ -682,7 +678,7 @@ public function search() { // @todo Please modify the following code to remove attributes that should not be searched. - $criteria = new CDbCriteria; + $criteria = new CDbCriteria(); $criteria->compare('name', $this->name, true); $criteria->compare('folder', $this->folder, true); @@ -703,22 +699,22 @@ public function search() $criteria->compare('extends', $this->extends, true); return new CActiveDataProvider($this, array( - 'criteria'=>$criteria, + 'criteria' => $criteria, )); } /** * Retrieves a list of deprecated templates (the templates in upload/templates/) */ - static public function getDeprecatedTemplates() + public static function getDeprecatedTemplates() { - $usertemplaterootdir = Yii::app()->getConfig("uploaddir").DIRECTORY_SEPARATOR."templates"; + $usertemplaterootdir = Yii::app()->getConfig("uploaddir") . DIRECTORY_SEPARATOR . "templates"; $aTemplateList = array(); - if ( (is_dir($usertemplaterootdir)) && $usertemplaterootdir && $handle = opendir($usertemplaterootdir)){ - while (false !== ($file = readdir($handle))){ - if (!is_file("$usertemplaterootdir/$file") && $file != "." && $file != ".." && $file!=".svn"){ - $aTemplateList[$file]['directory'] = $usertemplaterootdir.DIRECTORY_SEPARATOR.$file; + if ((is_dir($usertemplaterootdir)) && $usertemplaterootdir && $handle = opendir($usertemplaterootdir)) { + while (false !== ($file = readdir($handle))) { + if (!is_file("$usertemplaterootdir/$file") && $file != "." && $file != ".." && $file != ".svn") { + $aTemplateList[$file]['directory'] = $usertemplaterootdir . DIRECTORY_SEPARATOR . $file; $aTemplateList[$file]['name'] = $file; } } @@ -732,18 +728,17 @@ static public function getDeprecatedTemplates() /** * Retrieves a list of broken themes */ - public static function getBrokenThemes($sFolder=null) + public static function getBrokenThemes($sFolder = null) { $aBrokenTemplateList = array(); - $sFolder = (empty($sFolder))?Yii::app()->getConfig("userthemerootdir"):$sFolder; + $sFolder = (empty($sFolder)) ? Yii::app()->getConfig("userthemerootdir") : $sFolder; if ($sFolder && $handle = opendir($sFolder)) { while (false !== ($sFileName = readdir($handle))) { - if (!is_file("$sFolder/$sFileName") && $sFileName != "." && $sFileName != ".." && $sFileName != ".svn" && $sFileName != 'generalfiles' ) { - + if (!is_file("$sFolder/$sFileName") && $sFileName != "." && $sFileName != ".." && $sFileName != ".svn" && $sFileName != 'generalfiles') { try { $oTheme = Template::getTemplateConfiguration($sFileName, null, null, true); // Get the manifest; - }catch (Exception $e) { + } catch (Exception $e) { $aBrokenTemplateList[$sFileName] = $e; } } diff --git a/application/models/TemplateConfig.php b/application/models/TemplateConfig.php index 4af61eea50e..922141ba6ae 100644 --- a/application/models/TemplateConfig.php +++ b/application/models/TemplateConfig.php @@ -1,4 +1,5 @@ path.$sFile) && - !file_exists($oRTemplate->viewPath.$sFile) && - !file_exists($oRTemplate->filesPath.$sFile)) { + while ( + !file_exists($oRTemplate->path . $sFile) && + !file_exists($oRTemplate->viewPath . $sFile) && + !file_exists($oRTemplate->filesPath . $sFile) + ) { $oMotherTemplate = $oRTemplate->oMotherTemplate; if (!($oMotherTemplate instanceof TemplateConfiguration)) { if (!$force && App()->twigRenderer->getPathOfFile($sFile)) { @@ -262,8 +264,8 @@ public function getTemplateForFile($sFile, $oRTemplate, $force = false) protected function createTemplatePackage($oTemplate) { // Each template in the inheritance tree needs a specific alias - $sPathName = 'survey.template-'.$oTemplate->sTemplateName.'.path'; - $sViewName = 'survey.template-'.$oTemplate->sTemplateName.'.viewpath'; + $sPathName = 'survey.template-' . $oTemplate->sTemplateName . '.path'; + $sViewName = 'survey.template-' . $oTemplate->sTemplateName . '.viewpath'; Yii::setPathOfAlias($sPathName, $oTemplate->path); Yii::setPathOfAlias($sViewName, $oTemplate->viewPath); @@ -284,9 +286,11 @@ protected function createTemplatePackage($oTemplate) $aJsFiles = array_merge($aJsFiles, $aTJsFiles); // Remove/Replace mother template files - if (App()->getConfig('force_xmlsettings_for_survey_rendering') || + if ( + App()->getConfig('force_xmlsettings_for_survey_rendering') || ($this->template instanceof Template && $this->template->extends) || - !empty($this->config->metadata->extends)) { + !empty($this->config->metadata->extends) + ) { $aCssFiles = $this->changeMotherConfiguration('css', $aCssFiles); $aJsFiles = $this->changeMotherConfiguration('js', $aJsFiles); } @@ -294,7 +298,7 @@ protected function createTemplatePackage($oTemplate) // Then we add the direction files if they exist // TODO: attribute system rather than specific fields for RTL - $this->sPackageName = 'survey-template-'.$this->sTemplateName; + $this->sPackageName = 'survey-template-' . $this->sTemplateName; $sTemplateurl = $oTemplate->getTemplateURL(); $aDepends = empty($oTemplate->depends) ? array() : $oTemplate->depends; @@ -330,10 +334,10 @@ protected function getFilePath($sFile, $oTemplate) $oTemplate = $this->getTemplateForFile($sFile, $oTemplate, false); if ($oTemplate instanceof TemplateConfiguration) { - if (file_exists($oTemplate->path.$sFile)) { - return $oTemplate->path.$sFile; - } elseif (file_exists($oTemplate->viewPath.$sFile)) { - return $oTemplate->viewPath.$sFile; + if (file_exists($oTemplate->path . $sFile)) { + return $oTemplate->path . $sFile; + } elseif (file_exists($oTemplate->viewPath . $sFile)) { + return $oTemplate->viewPath . $sFile; } } $sExtension = substr(strrchr($sFile, '.'), 1); @@ -397,18 +401,17 @@ public function getPreview() if (empty($this->sPreviewImgTag)) { if (is_a($this->template, 'Template')) { $sTemplateFileFolder = Template::getTemplatesFileFolder($this->template->name); - $previewPath = Template::getTemplatePath($this->template->name).'/'.$sTemplateFileFolder; + $previewPath = Template::getTemplatePath($this->template->name) . '/' . $sTemplateFileFolder; - if ($previewPath && file_exists($previewPath.'/preview.png')) { - $previewUrl = Template::getTemplateURL($this->template->name).$sTemplateFileFolder; - $this->sPreviewImgTag = 'template preview'; } } else { - $this->sPreviewImgTag = ''.gT('No preview available').''; + $this->sPreviewImgTag = '' . gT('No preview available') . ''; } - } return $this->sPreviewImgTag; @@ -419,20 +422,20 @@ public function getPreview() * @throws CException * @todo document me */ - public function throwConsoleError($sCustomMessage=null) + public function throwConsoleError($sCustomMessage = null) { $sMessage = "\\n"; $sMessage .= "\\n"; $sMessage .= " (¯`·._.·(¯`·._.· Theme Configuration Error ·._.·´¯)·._.·´¯) \\n"; $sMessage .= "\\n"; - if ($sCustomMessage==null) { + if ($sCustomMessage == null) { $sMessage .= "\\n unknown error"; } else { $sMessage .= $sCustomMessage; } - App()->clientScript->registerScript('error_'.$this->template_name, "throw Error(\"$sMessage\");"); + App()->clientScript->registerScript('error_' . $this->template_name, "throw Error(\"$sMessage\");"); } @@ -489,7 +492,7 @@ public function getClassAndAttributes() $aVariationFile = explode('/', $this->aCssFrameworkReplacement[0]); $aVariationFile = explode('.', end($aVariationFile)); $sVariationName = $aVariationFile[0]; - $aClassAndAttributes['class']['body'] .= ' '.$sVariationName; + $aClassAndAttributes['class']['body'] .= ' ' . $sVariationName; } $aClassAndAttributes['class']['outerframe'] = ' outerframe '; @@ -698,7 +701,7 @@ public function getClassAndAttributes() $aClassAndAttributes['class']['registerformcolrow'] = ' '; $aClassAndAttributes['class']['registerformcolrowb'] = ' '; $aClassAndAttributes['class']['registerformcolrowc'] = ' '; - $aClassAndAttributes['class']['registerformcoladdidtions']= ' register-form-column-additions '; + $aClassAndAttributes['class']['registerformcoladdidtions'] = ' register-form-column-additions '; $aClassAndAttributes['class']['registerformextras'] = ' '; $aClassAndAttributes['class']['registerformcaptcha'] = ' captcha-item '; $aClassAndAttributes['class']['registerformcolrowblabel'] = ' '; @@ -743,8 +746,8 @@ public function getClassAndAttributes() $aClassAndAttributes['class']['errorHtml'] = ' ls-questions-have-errors '; $aClassAndAttributes['class']['activealertbutton'] = ' '; $aClassAndAttributes['class']['errorHtmlbutton'] = ' '; - $aClassAndAttributes['attr']['activealertbutton'] = ' type="button" data-dismiss="alert" aria-label="'.gT("Close").'" '; - $aClassAndAttributes['attr']['errorHtmlbutton'] = ' type="button" data-dismiss="alert" aria-label="'.gT("Close").'" '; + $aClassAndAttributes['attr']['activealertbutton'] = ' type="button" data-dismiss="alert" aria-label="' . gT("Close") . '" '; + $aClassAndAttributes['attr']['errorHtmlbutton'] = ' type="button" data-dismiss="alert" aria-label="' . gT("Close") . '" '; $aClassAndAttributes['attr']['activealert'] = 'role="alert"'; @@ -1030,7 +1033,7 @@ public static function importManifest($sTemplateName, $aDatas) throw new InvalidArgumentException('$aDatas cannot be empty'); } - $oNewTemplate = new Template; + $oNewTemplate = new Template(); $oNewTemplate->name = $sTemplateName; $oNewTemplate->folder = $sTemplateName; $oNewTemplate->title = $sTemplateName; // For now, when created via template editor => name == folder == title. If you change it, please, also update TemplateManifest::getTemplateURL @@ -1046,7 +1049,7 @@ public static function importManifest($sTemplateName, $aDatas) $oNewTemplate->extends = $aDatas['extends']; if ($oNewTemplate->save()) { - $oNewTemplateConfiguration = new TemplateConfiguration; + $oNewTemplateConfiguration = new TemplateConfiguration(); $oNewTemplateConfiguration->template_name = $sTemplateName; $oNewTemplateConfiguration->template_name = $sTemplateName; @@ -1065,7 +1068,8 @@ public static function importManifest($sTemplateName, $aDatas) if ($oNewTemplateConfiguration->save()) { // Find all surveys using this theme (if reinstalling) and create an entry on db for them $aSurveysUsingThisTeme = Survey::model()->findAll( - 'template=:template', array(':template'=>$sTemplateName) + 'template=:template', + array(':template' => $sTemplateName) ); foreach ($aSurveysUsingThisTeme as $oSurvey) { TemplateConfiguration::checkAndcreateSurveyConfig($oSurvey->sid); @@ -1104,7 +1108,9 @@ public static function formatToJsonArray($oFiled, $bConvertEmptyToString = false } } // Converts empty objects to empty strings - if ($bConvertEmptyToString) $jFiled = str_replace('{}','""',$jFiled); + if ($bConvertEmptyToString) { + $jFiled = str_replace('{}', '""', $jFiled); + } return $jFiled; } @@ -1115,7 +1121,7 @@ public static function formatToJsonArray($oFiled, $bConvertEmptyToString = false public function getAllDbTemplateFolders() { if (empty($this->allDbTemplateFolders)) { - $oCriteria = new CDbCriteria; + $oCriteria = new CDbCriteria(); $oCriteria->select = 'folder'; $oAllDbTemplateFolders = Template::model()->findAll($oCriteria); @@ -1183,7 +1189,7 @@ protected function changeMotherConfiguration($sType, $aSettings) // we must add it. // (and leave it in moter template definition if it already exists.) foreach ($aSettings as $key => $sFileName) { - if (file_exists($this->path.$sFileName)) { + if (file_exists($this->path . $sFileName)) { App()->clientScript->removeFileFromPackage( $this->oMotherTemplate->sPackageName, $sType, @@ -1207,7 +1213,6 @@ protected function changeMotherConfiguration($sType, $aSettings) $sMessage .= "\\n"; self::throwConsoleError($sMessage); } - } } } @@ -1223,8 +1228,10 @@ protected function changeMotherConfiguration($sType, $aSettings) public function getTemplateForAsset($sFile, $oRTemplate) { do { - if (!($oRTemplate instanceof TemplateConfiguration) || - !($oRTemplate->oMotherTemplate instanceof TemplateConfiguration)) { + if ( + !($oRTemplate instanceof TemplateConfiguration) || + !($oRTemplate->oMotherTemplate instanceof TemplateConfiguration) + ) { return false; break; } @@ -1235,11 +1242,10 @@ public function getTemplateForAsset($sFile, $oRTemplate) $sFilePath = Yii::getPathOfAlias( App()->clientScript->packages[$oRTemplate->sPackageName]["basePath"] - ) . DIRECTORY_SEPARATOR . $sFile; - - }while(!file_exists($sFilePath)); + ) . DIRECTORY_SEPARATOR . $sFile; + } while (!file_exists($sFilePath)); - return $oRTemplate; + return $oRTemplate; } diff --git a/application/models/TemplateConfiguration.php b/application/models/TemplateConfiguration.php index aaf46ec3083..7582b5fa5ca 100755 --- a/application/models/TemplateConfiguration.php +++ b/application/models/TemplateConfiguration.php @@ -1,4 +1,5 @@ true), - array('template_name', 'length', 'max'=>150), - array('cssframework_name', 'length', 'max'=>45), + array('id, sid, gsid', 'numerical', 'integerOnly' => true), + array('template_name', 'length', 'max' => 150), + array('cssframework_name', 'length', 'max' => 45), array('files_css, files_js, files_print_css, options, cssframework_css, cssframework_js, packages_to_load', 'safe'), // The following rule is used by search(). - array('id, template_name, sid, gsid, files_css, files_js, files_print_css, options, cssframework_name, cssframework_css, cssframework_js, packages_to_load', 'safe', 'on'=>'search'), + array('id, template_name, sid, gsid, files_css, files_js, files_print_css, options, cssframework_name, cssframework_css, cssframework_js, packages_to_load', 'safe', 'on' => 'search'), ); } @@ -145,7 +146,7 @@ public function relations() /** @inheritdoc */ public function defaultScope() { - return array('order'=> App()->db->quoteColumnName($this->getTableAlias(false, false).'.template_name')); + return array('order' => App()->db->quoteColumnName($this->getTableAlias(false, false) . '.template_name')); } /** @@ -186,7 +187,7 @@ public static function getInstanceFromTemplateName($sTemplateName, $abstractInst $oInstance = self::model()->find( 'template_name=:template_name AND sid IS NULL AND gsid IS NULL', - array(':template_name'=>$sTemplateName) + array(':template_name' => $sTemplateName) ); // If the survey configuration table of the wanted template doesn't exist (eg: manually deleted), @@ -328,8 +329,8 @@ public static function getThemeOptionsFromSurveyId($iSurveyId = 0, $bInherited = $aTemplateConfigurations[$key]['sid'] = $iSurveyId; $aTemplateConfigurations[$key]['template_name'] = $oAttributes['template_name']; $aTemplateConfigurations[$key]['config']['options'] = isJson($oAttributes['options']) - ?(array)json_decode($oAttributes['options']) - :$oAttributes['options']; + ? (array)json_decode($oAttributes['options']) + : $oAttributes['options']; } } @@ -446,10 +447,10 @@ public function search() { // @todo Please modify the following code to remove attributes that should not be searched. - $criteria = new CDbCriteria; + $criteria = new CDbCriteria(); - $criteria->join = 'INNER JOIN {{templates}} AS template ON '. - App()->db->quoteColumnName("t.template_name"). + $criteria->join = 'INNER JOIN {{templates}} AS template ON ' . + App()->db->quoteColumnName("t.template_name") . ' = template.name'; //Don't show surveyspecifi settings on the overview $criteria->addCondition('t.sid IS NULL'); @@ -468,7 +469,7 @@ public function search() $criteria->compare('packages_to_load', $this->packages_to_load, true); return new CActiveDataProvider($this, array( - 'criteria'=>$criteria, + 'criteria' => $criteria, )); } @@ -483,10 +484,10 @@ public function searchGrid() // @todo Please modify the following code to remove attributes that should not be searched. $pageSizeTemplateView = App()->user->getState('pageSizeTemplateView', App()->params['defaultPageSize']); - $criteria = new CDbCriteria; + $criteria = new CDbCriteria(); - $criteria->join = 'INNER JOIN {{templates}} AS template ON '. - App()->db->quoteColumnName("t.template_name"). + $criteria->join = 'INNER JOIN {{templates}} AS template ON ' . + App()->db->quoteColumnName("t.template_name") . ' = template.name'; $criteria->together = true; //Don't show surveyspecifi settings on the overview @@ -522,9 +523,9 @@ public function searchGrid() } return new CActiveDataProvider($this, array( - 'criteria'=>$criteria, - 'pagination'=>array( - 'pageSize'=>$pageSizeTemplateView, + 'criteria' => $criteria, + 'pagination' => array( + 'pageSize' => $pageSizeTemplateView, ), )); } @@ -544,9 +545,9 @@ public function getDescription() // It should never happen, but let's avoid to anoy final user in production mode :) if (YII_DEBUG) { App()->setFlashMessage( - "Twig error in template ". - $this->template->name. - " description
Please fix it and reset the theme
". + "Twig error in template " . + $this->template->name . + " description
Please fix it and reset the theme
" . $e, 'error' ); @@ -625,7 +626,8 @@ public function checkTemplate() { if (empty($this->bTemplateCheckResult)) { $this->bTemplateCheckResult = true; - if (!is_object($this->template) || + if ( + !is_object($this->template) || (is_object($this->template) && !Template::checkTemplateXML($this->template->folder)) ) { $this->bTemplateCheckResult = false; @@ -647,8 +649,8 @@ public function setBasics($sTemplateName = '', $iSurveyId = '', $bUseMagicInheri $this->sTemplateName = $this->template->name; $this->setIsStandard(); // Check if it is a CORE template $this->path = ($this->isStandard) - ? App()->getConfig("standardthemerootdir").DIRECTORY_SEPARATOR.$this->template->folder.DIRECTORY_SEPARATOR - : App()->getConfig("userthemerootdir").DIRECTORY_SEPARATOR.$this->template->folder.DIRECTORY_SEPARATOR; + ? App()->getConfig("standardthemerootdir") . DIRECTORY_SEPARATOR . $this->template->folder . DIRECTORY_SEPARATOR + : App()->getConfig("userthemerootdir") . DIRECTORY_SEPARATOR . $this->template->folder . DIRECTORY_SEPARATOR; } /** @@ -663,7 +665,7 @@ public function setBasics($sTemplateName = '', $iSurveyId = '', $bUseMagicInheri */ public function addFileReplacement($sFile, $sType) { - $sField = 'files_'.$sType; + $sField = 'files_' . $sType; $oFiles = (array) json_decode($this->$sField); $oFiles['replace'][] = $sFile; @@ -673,7 +675,7 @@ public function addFileReplacement($sFile, $sType) if ($this->save()) { return true; } else { - throw new Exception("could not add $sFile to $sField replacements! ".$this->getErrors()); + throw new Exception("could not add $sFile to $sField replacements! " . $this->getErrors()); } } @@ -702,14 +704,14 @@ public function getButtons() /* What ? We can get but $this->getAttribute ??? */ $gsid = App()->request->getQuery('id', null); // $this->gsid; // don't show any buttons if user doesn't have update permission - if(!Permission::model()->hasGlobalPermission('templates', 'update')) { + if (!Permission::model()->hasGlobalPermission('templates', 'update')) { /* Global settings */ if (empty($gsid) || App()->getController()->action->id != "surveysgroups") { return ''; } /* SurveysGroups settings */ $oSurveysGroups = SurveysGroups::model()->findByPk($gsid); - if(empty($oSurveysGroups)) { + if (empty($oSurveysGroups)) { return ''; } if (!$oSurveysGroups->hasPermission('surveys', 'update')) { @@ -732,7 +734,7 @@ public function getButtons() ); $sUninstallUrl = Yii::app()->getController()->createUrl('themeOptions/uninstall/'); - $sResetUrl = Yii::app()->getController()->createUrl('themeOptions/reset/', array("gsid"=> (int) $gsid)); + $sResetUrl = Yii::app()->getController()->createUrl('themeOptions/reset/', array("gsid" => (int) $gsid)); $sEditorLink = " '; $sUninstallLink = 'template_name.'" }\' - data-text="'.gT('This will reset all the specific configurations of this theme.').'
'.gT('Do you want to continue?').'" - title="'.gT('Uninstall this theme').'" + id="remove_fromdb_link_' . $this->template_name . '" + href="' . $sUninstallUrl . '" + data-post=\'{ "templatename": "' . $this->template_name . '" }\' + data-text="' . gT('This will reset all the specific configurations of this theme.') . '
' . gT('Do you want to continue?') . '" + title="' . gT('Uninstall this theme') . '" class="btn btn-danger btn-block selector--ConfirmModal"> - '.gT('Uninstall').' + ' . gT('Uninstall') . '
'; $sResetLink = 'template_name.'" }\' - data-text="'.gT('This will reload the configuration file of this theme.').'
'.gT('Do you want to continue?').'" - title="'.gT('Reset this theme').'" + id="remove_fromdb_link_' . $this->template_name . '" + href="' . $sResetUrl . '" + data-post=\'{ "templatename": "' . $this->template_name . '" }\' + data-text="' . gT('This will reload the configuration file of this theme.') . '
' . gT('Do you want to continue?') . '" + title="' . gT('Reset this theme') . '" class="btn btn-warning btn-block selector--ConfirmModal"> - '.gT('Reset').' + ' . gT('Reset') . '
'; if (App()->getController()->action->id == "surveysgroups") { @@ -809,10 +811,10 @@ class="btn btn-warning btn-block selector--ConfirmModal"> class="btn btn-danger btn-block" disabled data-toggle="tooltip" - title="' . gT('You cannot uninstall the default template.').'" + title="' . gT('You cannot uninstall the default template.') . '" > - '.gT('Uninstall').' + ' . gT('Uninstall') . ' '; } @@ -834,8 +836,8 @@ public function getHasOptionPage() $filteredName = Template::templateNameFilter($this->template->name); $oRTemplate = $this->prepareTemplateRendering($filteredName); - $sOptionFile = 'options'.DIRECTORY_SEPARATOR.'options.twig'; - while (!file_exists($oRTemplate->path.$sOptionFile)) { + $sOptionFile = 'options' . DIRECTORY_SEPARATOR . 'options.twig'; + while (!file_exists($oRTemplate->path . $sOptionFile)) { $oMotherTemplate = $oRTemplate->oMotherTemplate; if (!($oMotherTemplate instanceof TemplateConfiguration)) { return false; @@ -877,7 +879,7 @@ public function addOptionFromXMLToLiveTheme() { if ($this->options != 'inherit') { $oOptions = get_object_vars(json_decode($this->options)); - $oTemplateConfigurationModel = new TemplateManifest; + $oTemplateConfigurationModel = new TemplateManifest(); $oTemplateConfigurationModel->setBasics(); $oXmlOptions = get_object_vars($oTemplateConfigurationModel->config->options); @@ -943,7 +945,7 @@ private function getRelativePath($from, $to) array_shift($dir); array_shift($file); } - return str_repeat('..'.DIRECTORY_SEPARATOR, count($dir)) . implode(DIRECTORY_SEPARATOR, $file); + return str_repeat('..' . DIRECTORY_SEPARATOR, count($dir)) . implode(DIRECTORY_SEPARATOR, $file); } /** @@ -969,7 +971,7 @@ private function getImageInfo($file) 'preview' => $previewFilePath, 'filepath' => $filePath, 'filepathOptions' => $filePath , - 'filename'=>basename($file) + 'filename' => basename($file) ]; } @@ -993,13 +995,13 @@ public function getOptionPageAttributes() if ($this->sid) { $categoryList[] = [ 'group' => gT("Survey"), - 'path' => App()->getConfig('uploaddir').'/surveys/'.$this->sid.'/images/' + 'path' => App()->getConfig('uploaddir') . '/surveys/' . $this->sid . '/images/' ]; } foreach ($categoryList as $category) { $fileList = Template::getOtherFiles($category['path']); foreach ($fileList as $file) { - $imageInfo = $this->getImageInfo($category['path'].$file['name']); + $imageInfo = $this->getImageInfo($category['path'] . $file['name']); if ($imageInfo) { $aData['imageFileList'][] = array_merge($category, $imageInfo); } @@ -1074,7 +1076,7 @@ protected function getFilesTo($oTemplate, $sType, $sAction) $this->aFilesTo[$oTemplate->template->name][$sType][$sAction] = array(); } - $sField = 'files_'.$sType; + $sField = 'files_' . $sType; $oFiles = $this->getOfiles($oTemplate, $sField); $aFiles = array(); @@ -1214,12 +1216,12 @@ protected function setThisTemplate() { $this->apiVersion = (!empty($this->template->api_version)) ? $this->template->api_version : null; // Mandtory setting in config XML - $this->viewPath = $this->path.$this->getTemplateForPath($this, 'view_folder') - ->template->view_folder.DIRECTORY_SEPARATOR; - $this->filesPath = $this->path.$this->getTemplateForPath($this, 'files_folder') - ->template->files_folder.DIRECTORY_SEPARATOR; + $this->viewPath = $this->path . $this->getTemplateForPath($this, 'view_folder') + ->template->view_folder . DIRECTORY_SEPARATOR; + $this->filesPath = $this->path . $this->getTemplateForPath($this, 'files_folder') + ->template->files_folder . DIRECTORY_SEPARATOR; $this->generalFilesPath = App()->getConfig("userthemerootdir") - .DIRECTORY_SEPARATOR.'generalfiles'.DIRECTORY_SEPARATOR; + . DIRECTORY_SEPARATOR . 'generalfiles' . DIRECTORY_SEPARATOR; // Options are optional $this->setOptions(); @@ -1250,7 +1252,6 @@ private function setCssFramework() $this->cssFramework->name = $this->cssframework_name; $this->cssFramework->css = json_decode($this->cssframework_css); $this->cssFramework->js = json_decode($this->cssframework_js); - } else { $this->cssFramework = ''; } @@ -1303,7 +1304,6 @@ protected function getOptionKey($key) } else { $this->uninstallIncorectTheme($this->template_name); } - } return $value; } else { @@ -1321,7 +1321,7 @@ protected function addMotherTemplatePackage($packages) { if (!empty($this->template->extends)) { $sMotherTemplateName = (string) $this->template->extends; - $packages[] = 'survey-template-'.$sMotherTemplateName; + $packages[] = 'survey-template-' . $sMotherTemplateName; } return $packages; } @@ -1340,7 +1340,7 @@ protected function getFrameworkAssetsToReplace($sType, $bInlcudeRemove = false) $this->aFrameworkAssetsToReplace[$sType] = array(); - $sFieldName = 'cssframework_'.$sType; + $sFieldName = 'cssframework_' . $sType; $aFieldValue = (array) json_decode($this->$sFieldName); if (!empty($aFieldValue) && !empty($aFieldValue['replace'])) { @@ -1427,7 +1427,6 @@ public function getParentConfiguration() $this->oParentTemplate->bUseMagicInherit = $this->bUseMagicInherit; return $this->oParentTemplate; } - } } @@ -1452,7 +1451,7 @@ public static function rename($sOldName, $sNewName) self::model()->updateAll( array('template_name' => $sNewName), "template_name = :oldname", - array(':oldname'=>$sOldName) + array(':oldname' => $sOldName) ); } @@ -1522,7 +1521,7 @@ public function getGlobalParent() { return self::model()->find( 'sid IS NULL AND uid IS NULL and gsid IS NULL AND template_name = :template_name', - [':template_name'=>$this->template_name] + [':template_name' => $this->template_name] ); } diff --git a/application/models/TemplateManifest.php b/application/models/TemplateManifest.php index 2eda5a77248..61a158618e4 100755 --- a/application/models/TemplateManifest.php +++ b/application/models/TemplateManifest.php @@ -1,4 +1,5 @@ templateEditor->screens->xpath('//file') : $this->templateEditor->screens->xpath('//'.$sScreen.'/file'); + $filesFromXML = (is_null($sScreen)) ? (array) $this->templateEditor->screens->xpath('//file') : $this->templateEditor->screens->xpath('//' . $sScreen . '/file'); foreach ($filesFromXML as $file) { if ($file->attributes()->type == $sType) { @@ -75,7 +76,7 @@ public function getValidScreenFiles($sType = "view", $sScreen = null) $oEvent = new PluginEvent('getValidScreenFiles'); $oEvent->set('type', $sType); - $oEvent->set('screen',$sScreen); + $oEvent->set('screen', $sScreen); //$oEvent->set('files',$aScreenFiles); // Not needed since we have remove and add event App()->getPluginManager()->dispatchEvent($oEvent); $aScreenFiles = array_values(array_diff($aScreenFiles, (array) $oEvent->get('remove'))); @@ -90,48 +91,45 @@ public function getValidScreenFiles($sType = "view", $sScreen = null) */ public function getScreensDetails() { - $aContent = array(); - - $oScreensFromXML = $this->templateEditor->xpath('//screens'); - foreach ($oScreensFromXML[0] as $sScreen => $oScreen){ - - // We reset LayoutName and FileName at each loop to avoid errors - $sLayoutName = ""; - $sFileName = ""; - $sTitle = ""; + $aContent = array(); + + $oScreensFromXML = $this->templateEditor->xpath('//screens'); + foreach ($oScreensFromXML[0] as $sScreen => $oScreen) { + // We reset LayoutName and FileName at each loop to avoid errors + $sLayoutName = ""; + $sFileName = ""; + $sTitle = ""; + + foreach ($oScreen as $sKey => $oField) { + if ($oField->attributes()->role == "layout") { + $sLayoutName = (string) $oField; + } - foreach ($oScreen as $sKey => $oField){ + if ($oField->attributes()->role == "content") { + $sFile = (string) $oField; - if ($oField->attributes()->role == "layout") { - $sLayoutName = (string) $oField; - } + // From command line, we need to remove the full path for content. It's inside the layout. This could be an option + $aFile = explode("/", $sFile); + $aFileName = explode(".", end($aFile)); + $sContent = $aFileName[0]; + } - if ($oField->attributes()->role == "content") { - $sFile = (string) $oField; + if ($oField->attributes()->role == "title") { + $sTitle = (string) $oField; - // From command line, we need to remove the full path for content. It's inside the layout. This could be an option - $aFile = explode("/", $sFile); - $aFileName = explode(".", end($aFile)); - $sContent = $aFileName[0]; + if ($oField->attributes()->twig == "on") { + $sTitle = Yii::app()->twigRenderer->convertTwigToHtml($sTitle); + } + } } - if ($oField->attributes()->role == "title") { - $sTitle = (string) $oField; - - if ($oField->attributes()->twig == "on") { - $sTitle = Yii::app()->twigRenderer->convertTwigToHtml($sTitle); - } + if (!empty($sLayoutName)) { + $aContent[$sScreen]['title'] = $sTitle; + $aContent[$sScreen]['layouts'][$sLayoutName] = $sContent; } - } - if (!empty ($sLayoutName)){ - $aContent[$sScreen]['title'] = $sTitle; - $aContent[$sScreen]['layouts'][$sLayoutName] = $sContent; - } - } - - return $aContent; + return $aContent; } /** @@ -142,45 +140,44 @@ public function getScreensDetails() */ public function getScreensList() { - $aScreenList = $this->getScreensDetails(); - $aScreens = array(); + $aScreenList = $this->getScreensDetails(); + $aScreens = array(); - foreach($aScreenList as $sScreenName => $aTitleAndLayouts){ - $aScreens[$sScreenName] = $aTitleAndLayouts['title']; - } + foreach ($aScreenList as $sScreenName => $aTitleAndLayouts) { + $aScreens[$sScreenName] = $aTitleAndLayouts['title']; + } // We check there is at least one screen title in the array. Else, the theme manifest is outdated, so we use the default values - $bEmptyTitles = true; - foreach($aScreens as $sScreenName => $sTitle){ - if (!empty($sTitle)){ - $bEmptyTitles = false; - break; + $bEmptyTitles = true; + foreach ($aScreens as $sScreenName => $sTitle) { + if (!empty($sTitle)) { + $bEmptyTitles = false; + break; + } + } + + if ($bEmptyTitles) { + if (YII_DEBUG) { + Yii::app()->setFlashMessage("Your theme does not implement screen definition in XML. Using the default ones
this message will not appear when debug mode is off", 'error'); + } + + $aScreens['welcome'] = gT('Welcome', 'unescaped'); + $aScreens['question'] = gT('Question', 'unescaped'); + $aScreens['completed'] = gT('Completed', 'unescaped'); + $aScreens['clearall'] = gT('Clear all', 'unescaped'); + $aScreens['load'] = gT('Load', 'unescaped'); + $aScreens['save'] = gT('Save', 'unescaped'); + $aScreens['surveylist'] = gT('Survey list', 'unescaped'); + $aScreens['error'] = gT('Error', 'unescaped'); + $aScreens['assessments'] = gT('Assessments', 'unescaped'); + $aScreens['register'] = gT('Registration', 'unescaped'); + $aScreens['printanswers'] = gT('Print answers', 'unescaped'); + $aScreens['pdf'] = gT('PDF', 'unescaped'); + $aScreens['navigation'] = gT('Navigation', 'unescaped'); + $aScreens['misc'] = gT('Miscellaneous files', 'unescaped'); } - } - - if ($bEmptyTitles){ - if(YII_DEBUG){ - Yii::app()->setFlashMessage("Your theme does not implement screen definition in XML. Using the default ones
this message will not appear when debug mode is off", 'error'); - } - - $aScreens['welcome'] = gT('Welcome', 'unescaped'); - $aScreens['question'] = gT('Question', 'unescaped'); - $aScreens['completed'] = gT('Completed', 'unescaped'); - $aScreens['clearall'] = gT('Clear all', 'unescaped'); - $aScreens['load'] = gT('Load', 'unescaped'); - $aScreens['save'] = gT('Save', 'unescaped'); - $aScreens['surveylist'] = gT('Survey list', 'unescaped'); - $aScreens['error'] = gT('Error', 'unescaped'); - $aScreens['assessments'] = gT('Assessments', 'unescaped'); - $aScreens['register'] = gT('Registration', 'unescaped'); - $aScreens['printanswers'] = gT('Print answers', 'unescaped'); - $aScreens['pdf'] = gT('PDF', 'unescaped'); - $aScreens['navigation'] = gT('Navigation', 'unescaped'); - $aScreens['misc'] = gT('Miscellaneous files', 'unescaped'); - } - - return $aScreens; + return $aScreens; } /** @@ -188,32 +185,32 @@ public function getScreensList() * This is used when rendering the views outside of the normal survey taking. * Currently used in two cases: theme editor preview, and twig cache file generation from command line. */ - public function getDefaultDataForRendering($thissurvey=array()) + public function getDefaultDataForRendering($thissurvey = array()) { - $thissurvey = empty($thissurvey)?$this->getDefaultCoreDataForRendering():$thissurvey; + $thissurvey = empty($thissurvey) ? $this->getDefaultCoreDataForRendering() : $thissurvey; - $thissurvey = $this->getDefaultDataForRenderingFromXml($thissurvey); + $thissurvey = $this->getDefaultDataForRenderingFromXml($thissurvey); //$thissurvey['alanguageChanger'] = $this->getDefaultDataForLanguageChanger(); // Redundant values - $thissurvey['surveyls_title'] = $thissurvey['name']; - $thissurvey['surveyls_description'] = $thissurvey['description']; - $thissurvey['surveyls_welcometext'] = $thissurvey['welcome']; + $thissurvey['surveyls_title'] = $thissurvey['name']; + $thissurvey['surveyls_description'] = $thissurvey['description']; + $thissurvey['surveyls_welcometext'] = $thissurvey['welcome']; - return $thissurvey; + return $thissurvey; } - public function getDefaultDataForLanguageChanger($thissurvey=array()) + public function getDefaultDataForLanguageChanger($thissurvey = array()) { - $thissurvey = empty($thissurvey)?array():$thissurvey; - $oDataFromXML = $this->templateEditor->default_data->xpath('//survey_data'); + $thissurvey = empty($thissurvey) ? array() : $thissurvey; + $oDataFromXML = $this->templateEditor->default_data->xpath('//survey_data'); - $thissurvey['alanguageChanger']['datas'] = [ + $thissurvey['alanguageChanger']['datas'] = [ 'sSelected' => 'en', //'withForm' => true, // Set to true for no-js functionality. 'aListLang' => [ @@ -221,13 +218,11 @@ public function getDefaultDataForLanguageChanger($thissurvey=array()) 'de' => gT('German') ] ]; - - } - public function getDefaultDataForRenderingFromXml($thissurvey=array()) + public function getDefaultDataForRenderingFromXml($thissurvey = array()) { - $thissurvey = empty($thissurvey)?array():$thissurvey; + $thissurvey = empty($thissurvey) ? array() : $thissurvey; if (empty($this->templateEditor)) { return $thissurvey; @@ -258,41 +253,39 @@ public function getDefaultDataForRenderingFromXml($thissurvey=array()) */ protected function getCustomScreenData($thissurvey = array()) { - $oDataFromXML = $this->templateEditor->xpath("//default_data"); // + $oDataFromXML = $this->templateEditor->xpath("//default_data"); // - foreach( $oDataFromXML[0] as $sScreenName => $oData){ - if ($oData->attributes()->type == "custom"){ - $sArrayName = (string) $oData->attributes()->arrayName; - $thissurvey[$sArrayName] = array(); - $thissurvey[$sArrayName] = $this->parseDefaultData($sScreenName, $thissurvey[$sArrayName]); + foreach ($oDataFromXML[0] as $sScreenName => $oData) { + if ($oData->attributes()->type == "custom") { + $sArrayName = (string) $oData->attributes()->arrayName; + $thissurvey[$sArrayName] = array(); + $thissurvey[$sArrayName] = $this->parseDefaultData($sScreenName, $thissurvey[$sArrayName]); + } } - } - return $thissurvey; + return $thissurvey; } protected function parseDefaultData($sXpath, $aArrayToFeed) { - $oDataFromXML = $this->templateEditor->default_data->xpath('//'.$sXpath); - $oDataFromXML = end($oDataFromXML); + $oDataFromXML = $this->templateEditor->default_data->xpath('//' . $sXpath); + $oDataFromXML = end($oDataFromXML); - foreach( $oDataFromXML as $sKey => $oData){ + foreach ($oDataFromXML as $sKey => $oData) { + if (!empty($sKey)) { + $sData = (string) $oData; - if (!empty($sKey)){ - - $sData = (string) $oData; - - if ($oData->attributes()->twig == "on") { - $sData = Yii::app()->twigRenderer->convertTwigToHtml($sData); - } + if ($oData->attributes()->twig == "on") { + $sData = Yii::app()->twigRenderer->convertTwigToHtml($sData); + } - $aArrayToFeed[$sKey] = $sData; + $aArrayToFeed[$sKey] = $sData; + } } - } - return $aArrayToFeed; + return $aArrayToFeed; } /** @@ -304,14 +297,14 @@ protected function parseDefaultData($sXpath, $aArrayToFeed) */ public function getTwigStrings($items = array()) { - $oDataFromXML = $this->config; - $oElements = $oDataFromXML->xpath('//*[@twig="on"]'); + $oDataFromXML = $this->config; + $oElements = $oDataFromXML->xpath('//*[@twig="on"]'); - foreach($oElements as $key => $oELement){ - $items[] = (string) $oELement; - } + foreach ($oElements as $key => $oELement) { + $items[] = (string) $oELement; + } - return $items; + return $items; } /** @@ -396,8 +389,8 @@ public function getDefaultCoreDataForRendering() $thissurvey['aGroups'][1]["aQuestions"][1]["mandatory"] = true; // If called from command line to generate Twig temp, renderPartial doesn't exist in ConsoleApplication - if (method_exists ( Yii::app()->getController() , 'renderPartial' ) ){ - $thissurvey['aGroups'][1]["aQuestions"][1]["answer"] = Yii::app()->getController()->renderPartial('/admin/themes/templateeditor_question_answer_view', array(), true); + if (method_exists(Yii::app()->getController(), 'renderPartial')) { + $thissurvey['aGroups'][1]["aQuestions"][1]["answer"] = Yii::app()->getController()->renderPartial('/admin/themes/templateeditor_question_answer_view', array(), true); } $thissurvey['aGroups'][1]["aQuestions"][1]["help"]["show"] = true; $thissurvey['aGroups'][1]["aQuestions"][1]["help"]["text"] = gT("This is some helpful text."); @@ -406,8 +399,8 @@ public function getDefaultCoreDataForRendering() $thissurvey['aGroups'][1]["aQuestions"][2]["qid"] = "1"; $thissurvey['aGroups'][1]["aQuestions"][2]["mandatory"] = false; - if (method_exists ( Yii::app()->getController() , 'renderPartial' ) ){ - $thissurvey['aGroups'][1]["aQuestions"][2]["answer"] = Yii::app()->getController()->renderPartial('/admin/themes/templateeditor_question_answer_view', array('alt' => true), true); + if (method_exists(Yii::app()->getController(), 'renderPartial')) { + $thissurvey['aGroups'][1]["aQuestions"][2]["answer"] = Yii::app()->getController()->renderPartial('/admin/themes/templateeditor_question_answer_view', array('alt' => true), true); } $thissurvey['aGroups'][1]["aQuestions"][2]["help"]["show"] = true; $thissurvey['aGroups'][1]["aQuestions"][2]["help"]["text"] = gT("This is some helpful text."); @@ -443,11 +436,11 @@ public function getDefaultCoreDataForRendering() // Those values can be overwritten by XML $thissurvey['name'] = gT("Template Sample"); $thissurvey['description'] = - "

".gT('This is a sample survey description. It could be quite long.')."

". - "

".gT("But this one isn't.")."

"; + "

" . gT('This is a sample survey description. It could be quite long.') . "

" . + "

" . gT("But this one isn't.") . "

"; $thissurvey['welcome'] = - "

".gT('Welcome to this sample survey')."

". - "

".gT('You should have a great time doing this')."

"; + "

" . gT('Welcome to this sample survey') . "

" . + "

" . gT('You should have a great time doing this') . "

"; $thissurvey['therearexquestions'] = gT('There is 1 question in this survey'); $thissurvey['surveyls_url'] = "https://www.limesurvey.org/"; $thissurvey['surveyls_urldescription'] = gT("Some URL description"); @@ -467,11 +460,10 @@ public function getLayoutForScreen($sScreen) return false; } - $filesFromXML = $this->templateEditor->screens->xpath('//'.$sScreen.'/file'); + $filesFromXML = $this->templateEditor->screens->xpath('//' . $sScreen . '/file'); foreach ($filesFromXML as $file) { - if ($file->attributes()->role == "layout") { return (string) $file; } @@ -494,12 +486,10 @@ public function getContentForScreen($sScreen) return false; } - $filesFromXML = $this->templateEditor->screens->xpath('//'.$sScreen.'/file'); + $filesFromXML = $this->templateEditor->screens->xpath('//' . $sScreen . '/file'); foreach ($filesFromXML as $file) { - if ($file->attributes()->role == "content") { - // The path of the file is defined inside the theme itself. $aExplodedFile = explode(DIRECTORY_SEPARATOR, $file); $sFormatedFile = end($aExplodedFile); @@ -540,11 +530,10 @@ public function getFilePathForEditing($sFile, $aAllowedFiles = null) */ public function extendsFile($sFile) { - if (!file_exists($this->path.$sFile) && !file_exists($this->viewPath.$sFile)) { - + if (!file_exists($this->path . $sFile) && !file_exists($this->viewPath . $sFile)) { // Copy file from mother template to local directory $sSourceFilePath = $this->getFilePath($sFile, $this); - $sDestinationFilePath = (pathinfo($sFile, PATHINFO_EXTENSION) == 'twig') ? $this->viewPath.$sFile : $this->path.$sFile; + $sDestinationFilePath = (pathinfo($sFile, PATHINFO_EXTENSION) == 'twig') ? $this->viewPath . $sFile : $this->path . $sFile; //PHP 7 seems not to create the folder on copy automatically. @mkdir(dirname($sDestinationFilePath), 0775, true); @@ -554,7 +543,6 @@ public function extendsFile($sFile) // If it's a css or js file from config... must update DB and XML too.... $sExt = pathinfo($sDestinationFilePath, PATHINFO_EXTENSION); if ($sExt == "css" || $sExt == "js") { - // Check if that CSS/JS file is in DB/XML $aFiles = $this->getFilesForPackages($sExt, $this); $sFile = str_replace('./', '', $sFile); @@ -598,7 +586,7 @@ public function getFilesForPackages($type, $oRTemplate) */ public function addFileReplacementInDB($sFile, $sType) { - $oTemplateConfigurationModels = TemplateConfiguration::model()->findAllByAttributes(array('template_name'=>$this->sTemplateName)); + $oTemplateConfigurationModels = TemplateConfiguration::model()->findAllByAttributes(array('template_name' => $this->sTemplateName)); foreach ($oTemplateConfigurationModels as $oTemplateConfigurationModel) { $oTemplateConfigurationModel->addFileReplacement($sFile, $sType); } @@ -617,11 +605,10 @@ public function getOtherFiles() } if (file_exists($this->filesPath) && $handle = opendir($this->filesPath)) { - while (false !== ($file = readdir($handle))) { if (!array_search($file, array("DUMMYENTRY", ".", "..", "preview.png"))) { - if (!is_dir($this->viewPath.DIRECTORY_SEPARATOR.$file)) { - $otherfiles[$file] = $this->filesPath.DIRECTORY_SEPARATOR.$file; + if (!is_dir($this->viewPath . DIRECTORY_SEPARATOR . $file)) { + $otherfiles[$file] = $this->filesPath . DIRECTORY_SEPARATOR . $file; } } } @@ -639,11 +626,11 @@ public function getTemplateURL() { // By default, theme folder is always the folder name. @See:TemplateConfig::importManifest(). - if (Template::isStandardTemplate($this->sTemplateName)) { - return Yii::app()->getConfig("standardthemerooturl").'/'.$this->sTemplateName.'/'; - } else { - return Yii::app()->getConfig("userthemerooturl").'/'.$this->sTemplateName.'/'; - } + if (Template::isStandardTemplate($this->sTemplateName)) { + return Yii::app()->getConfig("standardthemerooturl") . '/' . $this->sTemplateName . '/'; + } else { + return Yii::app()->getConfig("userthemerooturl") . '/' . $this->sTemplateName . '/'; + } // return Template::getTemplateURL($this->sTemplateName); } @@ -651,49 +638,48 @@ public function getTemplateURL() public function getButtons() { - $sEditorUrl = Yii::app()->getController()->createUrl('admin/themes/sa/view', array("templatename"=>$this->sTemplateName)); + $sEditorUrl = Yii::app()->getController()->createUrl('admin/themes/sa/view', array("templatename" => $this->sTemplateName)); $sDeleteUrl = Yii::app()->getController()->createUrl('admin/themes/sa/deleteAvailableTheme/'); // TODO: load to DB $sEditorLink = " - ".gT('Theme editor')." + " . gT('Theme editor') . " "; // // TODO: Installs Theme (maybe rename importManifest to install ?) - $sLoadLink = CHtml::form( array("themeOptions/importManifest/"), 'post', array('id'=>'frmínstalltheme','name'=>'frmínstalltheme')) . - " - "; $sDeleteLink = ''; // We don't want user to be able to delete standard theme. Must be done via ftp (advanced users only) - if(Permission::model()->hasGlobalPermission('templates','delete') && !Template::isStandardTemplate($this->sTemplateName) ){ - $sDeleteLink = 'sTemplateName.'" }\' - data-text="'.gT('Are you sure you want to delete this theme? ').'" - title="'.gT('Delete').'" + if (Permission::model()->hasGlobalPermission('templates', 'delete') && !Template::isStandardTemplate($this->sTemplateName)) { + $sDeleteLink = 'sTemplateName . '" }\' + data-text="' . gT('Are you sure you want to delete this theme? ') . '" + title="' . gT('Delete') . '" class="btn btn-danger btn-block selector--ConfirmModal"> - '.gT('Delete').' + ' . gT('Delete') . ' '; - } - - return $sEditorLink.$sLoadLink.$sDeleteLink; + } + return $sEditorLink . $sLoadLink . $sDeleteLink; } /** @@ -754,10 +740,10 @@ public static function importManifest($sTemplateName, $aDatas = array()) * @param $xml SimpleXMLElement * @return boolean true on success */ - public static function importManifestLss($iSurveyId = 0, $xml =null) + public static function importManifestLss($iSurveyId = 0, $xml = null) { - if ((int)$iSurveyId > 0 && !empty($xml)){ - $oTemplateConfiguration = new TemplateConfiguration; + if ((int)$iSurveyId > 0 && !empty($xml)) { + $oTemplateConfiguration = new TemplateConfiguration(); $oTemplateConfiguration->setToInherit(); $oTemplateConfiguration->bJustCreated = true; @@ -766,11 +752,11 @@ public static function importManifestLss($iSurveyId = 0, $xml =null) $oTemplateConfiguration->template_name = $xml->template_name->__toString(); $oTemplateConfiguration->sid = $iSurveyId; - if (isAssociativeArray((array)$xml->config->options)){ + if (isAssociativeArray((array)$xml->config->options)) { $oTemplateConfiguration->options = TemplateConfig::formatToJsonArray($xml->config->options); } - if ($oTemplateConfiguration->save()){ + if ($oTemplateConfiguration->save()) { return true; } } @@ -824,7 +810,7 @@ public static function getManifestDOM($sConfigPath) { // First we get the XML file $oNewManifest = new DOMDocument(); - $oNewManifest->load($sConfigPath."/config.xml"); + $oNewManifest->load($sConfigPath . "/config.xml"); return $oNewManifest; } @@ -854,20 +840,20 @@ public static function changeDateInDOM($oNewManifest, $sDate = '') $sDate = (empty($sDate)) ? dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i", Yii::app()->getConfig("timeadjust")) : $sDate; $oConfig = $oNewManifest->getElementsByTagName('config')->item(0); $ometadata = $oConfig->getElementsByTagName('metadata')->item(0); - if($ometadata->getElementsByTagName('creationDate')) { + if ($ometadata->getElementsByTagName('creationDate')) { $oOldDateNode = $ometadata->getElementsByTagName('creationDate')->item(0); } $oNvDateNode = $oNewManifest->createElement('creationDate', $sDate); - if(empty($oOldDateNode)) { + if (empty($oOldDateNode)) { $ometadata->appendChild($oNvDateNode); } else { $ometadata->replaceChild($oNvDateNode, $oOldDateNode); } - if($ometadata->getElementsByTagName('lastUpdate')) { + if ($ometadata->getElementsByTagName('lastUpdate')) { $oOldUpdateNode = $ometadata->getElementsByTagName('lastUpdate')->item(0); } $oNvDateNode = $oNewManifest->createElement('lastUpdate', $sDate); - if(empty($oOldUpdateNode)) { + if (empty($oOldUpdateNode)) { $ometadata->appendChild($oNvDateNode); } else { $ometadata->replaceChild($oNvDateNode, $oOldUpdateNode); @@ -884,11 +870,11 @@ public static function changeDateInDOM($oNewManifest, $sDate = '') public static function rename($sOldName, $sNewName) { libxml_disable_entity_loader(false); - $sConfigPath = Yii::app()->getConfig('userthemerootdir')."/".$sNewName; + $sConfigPath = Yii::app()->getConfig('userthemerootdir') . "/" . $sNewName; $oNewManifest = self::getManifestDOM($sConfigPath); self::changeNameInDOM($oNewManifest, $sNewName); self::changeDateInDOM($oNewManifest); - $oNewManifest->save($sConfigPath."/config.xml"); + $oNewManifest->save($sConfigPath . "/config.xml"); libxml_disable_entity_loader(true); } @@ -985,7 +971,7 @@ public static function changeExtendsInDom($oNewManifest, $sToExtends) */ public static function extendsConfig($sToExtends, $sNewName) { - $sConfigPath = Yii::app()->getConfig('userthemerootdir')."/".$sNewName; + $sConfigPath = Yii::app()->getConfig('userthemerootdir') . "/" . $sNewName; // First we get the XML file libxml_disable_entity_loader(false); @@ -998,7 +984,7 @@ public static function extendsConfig($sToExtends, $sNewName) self::changeEmailInDom($oNewManifest); self::changeExtendsInDom($oNewManifest, $sToExtends); - $oNewManifest->save($sConfigPath."/config.xml"); + $oNewManifest->save($sConfigPath . "/config.xml"); libxml_disable_entity_loader(true); } @@ -1008,12 +994,12 @@ public static function extendsConfig($sToExtends, $sNewName) */ private function readManifest() { - $this->xmlFile = $this->path.'config.xml'; + $this->xmlFile = $this->path . 'config.xml'; if (file_exists(realpath($this->xmlFile))) { $bOldEntityLoaderState = libxml_disable_entity_loader(true); // @see: http://phpsecurity.readthedocs.io/en/latest/Injection-Attacks.html#xml-external-entity-injection $sXMLConfigFile = file_get_contents(realpath($this->xmlFile)); // @see: Now that entity loader is disabled, we can't use simplexml_load_file; so we must read the file with file_get_contents and convert it as a string - $oDOMConfig = new DOMDocument; + $oDOMConfig = new DOMDocument(); $oDOMConfig->loadXML($sXMLConfigFile); $oXPath = new DOMXpath($oDOMConfig); foreach ($oXPath->query('//comment()') as $oComment) { @@ -1038,31 +1024,30 @@ private function readManifest() private function setPath() { // If the template is standard, its root is based on standardthemerootdir, else, it is a user template, its root is based on userthemerootdir - $this->path = ($this->isStandard) ? Yii::app()->getConfig("standardthemerootdir").DIRECTORY_SEPARATOR.$this->sTemplateName.DIRECTORY_SEPARATOR : Yii::app()->getConfig("userthemerootdir").DIRECTORY_SEPARATOR.$this->sTemplateName.DIRECTORY_SEPARATOR; + $this->path = ($this->isStandard) ? Yii::app()->getConfig("standardthemerootdir") . DIRECTORY_SEPARATOR . $this->sTemplateName . DIRECTORY_SEPARATOR : Yii::app()->getConfig("userthemerootdir") . DIRECTORY_SEPARATOR . $this->sTemplateName . DIRECTORY_SEPARATOR; // If the template directory doesn't exist, we just set Default as the template to use // TODO: create a method "setToDefault" if (!is_dir($this->path)) { if (!$this->iSurveyId) { - \SettingGlobal::setSetting('defaulttheme',Yii::app()->getConfig('defaultfixedtheme')); + \SettingGlobal::setSetting('defaulttheme', Yii::app()->getConfig('defaultfixedtheme')); /* @todo ? : check if installed, install if not */ } $this->sTemplateName = Yii::app()->getConfig('defaulttheme'); - if(Template::isStandardTemplate(Yii::app()->getConfig('defaulttheme'))) { + if (Template::isStandardTemplate(Yii::app()->getConfig('defaulttheme'))) { $this->isStandard = true; - $this->path = Yii::app()->getConfig("standardthemerootdir").DIRECTORY_SEPARATOR.$this->sTemplateName.DIRECTORY_SEPARATOR; + $this->path = Yii::app()->getConfig("standardthemerootdir") . DIRECTORY_SEPARATOR . $this->sTemplateName . DIRECTORY_SEPARATOR; } else { $this->isStandard = false; - $this->path = Yii::app()->getConfig("userthemerootdir").DIRECTORY_SEPARATOR.$this->sTemplateName.DIRECTORY_SEPARATOR; + $this->path = Yii::app()->getConfig("userthemerootdir") . DIRECTORY_SEPARATOR . $this->sTemplateName . DIRECTORY_SEPARATOR; } } // If the template doesn't have a config file (maybe it has been deleted, or whatever), // then, we load the default template - $this->hasConfigFile = (string) is_file($this->path.'config.xml'); + $this->hasConfigFile = (string) is_file($this->path . 'config.xml'); if (!$this->hasConfigFile) { - $this->path = Yii::app()->getConfig("standardthemerootdir").DIRECTORY_SEPARATOR.$this->sTemplateName.DIRECTORY_SEPARATOR; - + $this->path = Yii::app()->getConfig("standardthemerootdir") . DIRECTORY_SEPARATOR . $this->sTemplateName . DIRECTORY_SEPARATOR; } } @@ -1114,14 +1099,15 @@ public function setBasics($sTemplateName = '', $iSurveyId = '', $bUseMagicInheri /** * Get showpopups value from config or template configuration */ - public function getshowpopups(){ + public function getshowpopups() + { $config = (int)Yii::app()->getConfig('showpopups'); - if ($config == 2){ - if (isset($this->oOptions->showpopups)){ + if ($config == 2) { + if (isset($this->oOptions->showpopups)) { $this->showpopups = (int)$this->oOptions->showpopups; } else { - $this->showpopups = 1; - } + $this->showpopups = 1; + } } else { $this->showpopups = $config; } @@ -1139,7 +1125,7 @@ public function addFileReplacement($sFile, $sType) // First we get the XML file libxml_disable_entity_loader(false); $oNewManifest = new DOMDocument(); - $oNewManifest->load($this->path."config.xml"); + $oNewManifest->load($this->path . "config.xml"); $oConfig = $oNewManifest->getElementsByTagName('config')->item(0); $oFiles = $oNewManifest->getElementsByTagName('files')->item(0); @@ -1163,7 +1149,7 @@ public function addFileReplacement($sFile, $sType) $oAssetElem->appendChild($replaceAttribute); $oAssetType->appendChild($oAssetElem); $oConfig->insertBefore($oFiles, $oOptions); - $oNewManifest->save($this->path."config.xml"); + $oNewManifest->save($this->path . "config.xml"); libxml_disable_entity_loader(true); } @@ -1210,13 +1196,11 @@ protected function setMotherTemplates() { if (isset($this->config->metadata->extends)) { $sMotherTemplateName = (string) $this->config->metadata->extends; - if (!empty($sMotherTemplateName)){ - - $instance= Template::getTemplateConfiguration($sMotherTemplateName, null, null, true); + if (!empty($sMotherTemplateName)) { + $instance = Template::getTemplateConfiguration($sMotherTemplateName, null, null, true); $instance->prepareTemplateRendering($sMotherTemplateName); $this->oMotherTemplate = $instance; // $instance->prepareTemplateRendering($sMotherTemplateName, null); } - } } @@ -1245,8 +1229,8 @@ protected function setThisTemplate() $this->apiVersion = (isset($this->config->metadata->apiVersion)) ? $this->config->metadata->apiVersion : null; - $this->viewPath = $this->path.$this->getTemplateForPath($this, '//viewdirectory')->config->engine->viewdirectory.DIRECTORY_SEPARATOR; - $this->filesPath = $this->path.$this->getTemplateForPath($this, '//filesdirectory')->config->engine->filesdirectory.DIRECTORY_SEPARATOR; + $this->viewPath = $this->path . $this->getTemplateForPath($this, '//viewdirectory')->config->engine->viewdirectory . DIRECTORY_SEPARATOR; + $this->filesPath = $this->path . $this->getTemplateForPath($this, '//filesdirectory')->config->engine->filesdirectory . DIRECTORY_SEPARATOR; $this->templateEditor = $this->getTemplateForPath($this, '//template_editor')->config->engine->template_editor; // Options are optional @@ -1286,7 +1270,7 @@ protected function addMotherTemplatePackage($packages) { if (isset($this->config->metadata->extends)) { $sMotherTemplateName = (string) $this->config->metadata->extends; - $packages[] = 'survey-template-'.$sMotherTemplateName; + $packages[] = 'survey-template-' . $sMotherTemplateName; } return $packages; } @@ -1317,7 +1301,7 @@ protected function getFrameworkAssetsToReplace($sType, $bInlcudeRemove = false) * @param boolean $bInlcudeRemove also get the files to remove * @return stdClass */ - static public function getAssetsToReplaceFormated($oEngine, $sType, $bInlcudeRemove = false) + public static function getAssetsToReplaceFormated($oEngine, $sType, $bInlcudeRemove = false) { $oAssetsToReplaceFormated = new stdClass(); if (!empty($oEngine->cssframework->$sType) && !empty($oEngine->cssframework->$sType->attributes()->replace)) { @@ -1328,7 +1312,6 @@ static public function getAssetsToReplaceFormated($oEngine, $sType, $bInlcudeRem // {"replace":[["css/bootstrap.css","css/cerulean.css"]]} $oAssetsToReplaceFormated->replace = array(array($sAssetsToReplace, $sAssetsReplacement)); - } return $oAssetsToReplaceFormated; } @@ -1342,7 +1325,7 @@ protected function getFrameworkAssetsReplacement($sType) { $aAssetsToRemove = array(); if (!empty($this->cssFramework->$sType)) { - $nodes = (array) $this->config->xpath('//cssframework/'.$sType.'[@replace]'); + $nodes = (array) $this->config->xpath('//cssframework/' . $sType . '[@replace]'); if (!empty($nodes)) { foreach ($nodes as $key => $node) { $nodes[$key] = (string) $node[0]; @@ -1363,7 +1346,6 @@ public function getTemplateAndMotherNames() $sTemplateNames = $this->sTemplateName; while (!empty($oRTemplate->oMotherTemplate)) { - $sTemplateNames .= ' ' . $oRTemplate->config->metadata->extends; $oRTemplate = $oRTemplate->oMotherTemplate; if (!($oRTemplate instanceof TemplateConfiguration)) { @@ -1378,15 +1360,16 @@ public function getTemplateAndMotherNames() /** * Get options_page value from template configuration */ - public static function getOptionAttributes($path){ + public static function getOptionAttributes($path) + { libxml_disable_entity_loader(false); - $file = realpath($path."config.xml"); + $file = realpath($path . "config.xml"); if (file_exists($file)) { $sXMLConfigFile = file_get_contents($file); $oXMLConfig = simplexml_load_string($sXMLConfigFile); $aOptions['categories'] = array(); - foreach($oXMLConfig->options->children() as $key => $option){ + foreach ($oXMLConfig->options->children() as $key => $option) { $aOptions['optionAttributes'][$key]['type'] = !empty($option['type']) ? (string)$option['type'] : ''; $aOptions['optionAttributes'][$key]['title'] = !empty($option['title']) ? (string)$option['title'] : ''; $aOptions['optionAttributes'][$key]['category'] = !empty($option['category']) ? (string)$option['category'] : gT('Simple options'); @@ -1395,12 +1378,12 @@ public static function getOptionAttributes($path){ $aOptions['optionAttributes'][$key]['optionlabels'] = !empty($option['optionlabels']) ? (string)$option['optionlabels'] : ''; $aOptions['optionAttributes'][$key]['parent'] = !empty($option['parent']) ? (string)$option['parent'] : ''; - if (!empty($option->dropdownoptions)){ + if (!empty($option->dropdownoptions)) { $dropdownOptions = ''; - if ($key == 'font'){ + if ($key == 'font') { $dropdownOptions .= TemplateManifest::getFontDropdownOptions(); } - foreach($option->xpath('//options/' . $key . '/dropdownoptions') as $option){ + foreach ($option->xpath('//options/' . $key . '/dropdownoptions') as $option) { $dropdownOptions .= $option->asXml(); } @@ -1409,7 +1392,7 @@ public static function getOptionAttributes($path){ $aOptions['optionAttributes'][$key]['dropdownoptions'] = ''; } - if (!in_array($aOptions['optionAttributes'][$key]['category'], $aOptions['categories'])){ + if (!in_array($aOptions['optionAttributes'][$key]['category'], $aOptions['categories'])) { $aOptions['categories'][] = $aOptions['optionAttributes'][$key]['category']; } } @@ -1421,7 +1404,8 @@ public static function getOptionAttributes($path){ return false; } - public static function getFontDropdownOptions(){ + public static function getFontDropdownOptions() + { $fontOptions = ''; $fontPackages = App()->getClientScript()->fontPackages; $coreFontPackages = $fontPackages['core']; @@ -1434,31 +1418,31 @@ public static function getFontDropdownOptions(){ // generate CORE fonts package list $i = 0; - foreach($coreFontPackages as $coreKey => $corePackage){ - $i+=1; - if ($i === 1){ - $fontOptions .=''; + foreach ($coreFontPackages as $coreKey => $corePackage) { + $i += 1; + if ($i === 1) { + $fontOptions .= ''; } - $fontOptions .=''; + $fontOptions .= ''; } - if ($i > 0){ - $fontOptions .=''; + if ($i > 0) { + $fontOptions .= ''; } // generate USER fonts package list $i = 0; - foreach($userFontPackages as $userKey => $userPackage){ - $i+=1; - if ($i === 1){ - $fontOptions .=''; + foreach ($userFontPackages as $userKey => $userPackage) { + $i += 1; + if ($i === 1) { + $fontOptions .= ''; } - $fontOptions .=''; + $fontOptions .= ''; } - if ($i > 0){ - $fontOptions .=''; + if ($i > 0) { + $fontOptions .= ''; } - $fontOptions .=''; + $fontOptions .= ''; return $fontOptions; } @@ -1499,9 +1483,9 @@ public function getDescription() */ public function __get($name) { - if ($name=="options"){ - return json_encode( $this->config->options); - } - return parent::__get($name); + if ($name == "options") { + return json_encode($this->config->options); + } + return parent::__get($name); } } diff --git a/application/models/Timing.php b/application/models/Timing.php index c263ea164c2..6e157051ea5 100644 --- a/application/models/Timing.php +++ b/application/models/Timing.php @@ -29,7 +29,6 @@ public function __construct($iSurveyId, $scenario = 'insert') $this->survey = $survey; parent::__construct($scenario); } - } /** @inheritdoc */ @@ -94,8 +93,8 @@ public function getMetaData() * Get current surveyId for other model/function * @return int */ - public function getSurveyId() { + public function getSurveyId() + { return $this->surveyId; } - } diff --git a/application/models/Token.php b/application/models/Token.php index 26c13deda53..15d00027d84 100644 --- a/application/models/Token.php +++ b/application/models/Token.php @@ -1,4 +1,5 @@ gT('Blacklisted'), 'sent' => gT('Invitation sent date'), 'remindersent' => gT('Last reminder sent date'), - 'remindercount' =>gT('Total numbers of sent reminders'), + 'remindercount' => gT('Total numbers of sent reminders'), 'completed' => gT('Completed'), 'usesleft' => gT('Uses left'), 'validfrom' => gT('Valid from'), @@ -129,18 +130,18 @@ public function beforeDelete() */ public function deleteAllByAttributes($attributes, $condition = '', $params = array()) { - $builder=$this->getCommandBuilder(); - $participantCriteria=$builder->createCriteria($condition,$params); + $builder = $this->getCommandBuilder(); + $participantCriteria = $builder->createCriteria($condition, $params); $participantCriteria->select = array('tid','participant_id'); $participantCriteria->addCondition('participant_id is not null'); $oParticipantToDelete = self::model($this->dynamicId)->findAll($participantCriteria); $result = parent::deleteAllByAttributes($attributes, $condition, $params); - if($result && !empty($oParticipantToDelete)) { + if ($result && !empty($oParticipantToDelete)) { /* Get the participant not deleted : we must not delete survey link */ $oParticipantNotDeleted = self::model($this->dynamicId)->findAll($participantCriteria); - $tidToDelete = array_diff(CHtml::listData($oParticipantToDelete,'tid','tid'),CHtml::listData($oParticipantNotDeleted,'tid','tid')); - if(!empty($tidToDelete)) { - SurveyLink::model()->deleteAllByAttributes(array('token_id'=>$tidToDelete,'survey_id'=>$this->dynamicId)); + $tidToDelete = array_diff(CHtml::listData($oParticipantToDelete, 'tid', 'tid'), CHtml::listData($oParticipantNotDeleted, 'tid', 'tid')); + if (!empty($tidToDelete)) { + SurveyLink::model()->deleteAllByAttributes(array('token_id' => $tidToDelete,'survey_id' => $this->dynamicId)); } } return $result; @@ -160,15 +161,16 @@ public static function createTable($surveyId, array $extraFields = array()) $sCollation = ''; if (Yii::app()->db->driverName == 'mysql' || Yii::app()->db->driverName == 'mysqli') { $sCollation = "COLLATE 'utf8mb4_bin'"; - if(!empty(Yii::app()->getConfig('mysqlEngine'))) { + if (!empty(Yii::app()->getConfig('mysqlEngine'))) { $options .= sprintf(" ENGINE = %s ", Yii::app()->getConfig('mysqlEngine')); } } - if (Yii::app()->db->driverName == 'sqlsrv' + if ( + Yii::app()->db->driverName == 'sqlsrv' || Yii::app()->db->driverName == 'dblib' - || Yii::app()->db->driverName == 'mssql') { - + || Yii::app()->db->driverName == 'mssql' + ) { $sCollation = "COLLATE SQL_Latin1_General_CP1_CS_AS"; } $fields = array( @@ -197,7 +199,7 @@ public static function createTable($surveyId, array $extraFields = array()) // create fields for the custom token attributes associated with this survey $oSurvey = Survey::model()->findByPk($surveyId); - foreach ($oSurvey->tokenAttributes as $attrname=>$attrdetails) { + foreach ($oSurvey->tokenAttributes as $attrname => $attrdetails) { if (!isset($fields[$attrname])) { $fields[$attrname] = 'text'; } @@ -209,20 +211,20 @@ public static function createTable($surveyId, array $extraFields = array()) $db->createCommand()->createTable($sTableName, $fields, $options); /** - * The random component in the index name is needed because Postgres is being the dorky kid and - * complaining about duplicates when renaming the table and trying to use the same index again + * The random component in the index name is needed because Postgres is being the dorky kid and + * complaining about duplicates when renaming the table and trying to use the same index again * on a new token table (for example on reactivation) */ - $db->createCommand()->createIndex("idx_token_token_{$surveyId}_".rand(1, 50000), $sTableName, 'token'); + $db->createCommand()->createIndex("idx_token_token_{$surveyId}_" . rand(1, 50000), $sTableName, 'token'); // MSSQL does not support indexes on text fields so not needed here - switch (Yii::app()->db->driverName){ + switch (Yii::app()->db->driverName) { case 'mysql': case 'mysqli': $db->createCommand()->createIndex('idx_email', $sTableName, 'email(30)', false); break; case 'pgsql': - $db->createCommand()->createIndex('idx_email_'.$surveyId.'_'.rand(1, 50000), $sTableName, 'email', false); + $db->createCommand()->createIndex('idx_email_' . $surveyId . '_' . rand(1, 50000), $sTableName, 'email', false); break; } @@ -242,13 +244,13 @@ public function findByToken($token) } /** - * Get survey token length from survey. + * Get survey token length from survey. * Use default if not possible. */ public function getSurveyTokenLength() { // Use default token length - $iTokenLength = self::DEFAULT_LENGTH; + $iTokenLength = self::DEFAULT_LENGTH; // Use survey token length, if defined if (isset($this->survey) && !empty($this->survey->oOptions) && !empty($this->survey->oOptions->tokenlength) && is_numeric($this->survey->oOptions->tokenlength)) { @@ -262,11 +264,11 @@ public function getSurveyTokenLength() * Generates a token for this object. * @throws CHttpException */ - public function generateToken($iTokenLength = NULL) + public function generateToken($iTokenLength = null) { - if(empty($iTokenLength)) { + if (empty($iTokenLength)) { $iTokenLength = $this->getSurveyTokenLength(); - } + } $this->token = $this->_generateRandomToken($iTokenLength); $counter = 0; @@ -345,11 +347,11 @@ public function generateTokens() } // Do NOT replace the following select with ActiveRecord as it uses too much memory - $ntresult=Yii::app()->db->createCommand()->select('token')->from($this->tableName())-> where("token IS NOT NULL and token<>''")->queryColumn(); + $ntresult = Yii::app()->db->createCommand()->select('token')->from($this->tableName())-> where("token IS NOT NULL and token<>''")->queryColumn(); // select all existing tokens foreach ($ntresult as $tkrow) { $existingtokens[$tkrow] = true; - } + } $newtokencount = 0; $invalidtokencount = 0; $newtoken = null; @@ -374,7 +376,6 @@ public function generateTokens() } return array($newtokencount, count($tkresult)); - } /** * @inheritdoc @@ -400,7 +401,7 @@ public static function create($surveyId, $scenario = 'insert') public function relations() { $result = array( - 'responses' => array(self::HAS_MANY, 'Response_'.$this->dynamicId, array('token' => 'token')), + 'responses' => array(self::HAS_MANY, 'Response_' . $this->dynamicId, array('token' => 'token')), 'survey' => array(self::BELONGS_TO, 'Survey', '', 'on' => "sid = {$this->dynamicId}"), 'surveylink' => array(self::BELONGS_TO, 'SurveyLink', array('participant_id' => 'participant_id'), 'on' => "survey_id = {$this->dynamicId}") ); @@ -412,32 +413,32 @@ public function rules() { $aRules = array( array('token', 'unique', 'allowEmpty' => true), - array('token', 'length', 'min' => 0, 'max'=>36), + array('token', 'length', 'min' => 0, 'max' => 36), array('token', 'filter', 'filter' => array(self::class, 'sanitizeToken')), array('firstname', 'filter', 'filter' => array(self::class, 'sanitizeAttribute')), array('lastname', 'filter', 'filter' => array(self::class, 'sanitizeAttribute')), - array('language', 'LSYii_Validators', 'isLanguage'=>true), + array('language', 'LSYii_Validators', 'isLanguage' => true), array(implode(',', $this->tableSchema->columnNames), 'safe'), /* pseudo date : force date or specific string ? */ - array('remindersent', 'length', 'min' => 0, 'max'=>17), + array('remindersent', 'length', 'min' => 0, 'max' => 17), array('remindersent', 'filter', 'filter' => array(self::class, 'sanitizeAttribute')), - array('completed', 'length', 'min' => 0, 'max'=>17), + array('completed', 'length', 'min' => 0, 'max' => 17), array('remindersent', 'filter', 'filter' => array(self::class, 'sanitizeAttribute')), - array('remindercount', 'numerical', 'integerOnly'=>true, 'allowEmpty'=>true), - array('email', 'filter', 'filter'=>'trim'), - array('email', 'LSYii_EmailIDNAValidator', 'allowEmpty'=>true, 'allowMultiple'=>true, 'except'=>'allowinvalidemail'), - array('usesleft', 'numerical', 'integerOnly'=>true, 'allowEmpty'=>true, 'min'=>-2147483647, 'max'=>2147483647), - array('mpid', 'numerical', 'integerOnly'=>true, 'allowEmpty'=>true), - array('blacklisted', 'in', 'range'=>array('Y', 'N'), 'allowEmpty'=>true), - array('validfrom', 'date','format'=>['yyyy-M-d H:m:s.???','yyyy-M-d H:m:s','yyyy-M-d H:m'],'allowEmpty'=>true), - array('validuntil','date','format'=>['yyyy-M-d H:m:s.???','yyyy-M-d H:m:s','yyyy-M-d H:m'],'allowEmpty'=>true), + array('remindercount', 'numerical', 'integerOnly' => true, 'allowEmpty' => true), + array('email', 'filter', 'filter' => 'trim'), + array('email', 'LSYii_EmailIDNAValidator', 'allowEmpty' => true, 'allowMultiple' => true, 'except' => 'allowinvalidemail'), + array('usesleft', 'numerical', 'integerOnly' => true, 'allowEmpty' => true, 'min' => -2147483647, 'max' => 2147483647), + array('mpid', 'numerical', 'integerOnly' => true, 'allowEmpty' => true), + array('blacklisted', 'in', 'range' => array('Y', 'N'), 'allowEmpty' => true), + array('validfrom', 'date','format' => ['yyyy-M-d H:m:s.???','yyyy-M-d H:m:s','yyyy-M-d H:m'],'allowEmpty' => true), + array('validuntil','date','format' => ['yyyy-M-d H:m:s.???','yyyy-M-d H:m:s','yyyy-M-d H:m'],'allowEmpty' => true), array('emailstatus', 'default', 'value' => 'OK'), ); foreach (decodeTokenAttributes($this->survey->attributedescriptions) as $key => $info) { $aRules[] = array( $key, 'filter', 'filter' => array(self::class, 'sanitizeAttribute'), - 'except'=>'FinalSubmit' + 'except' => 'FinalSubmit' ); } return $aRules; @@ -484,22 +485,25 @@ public function summary() /** @inheritdoc */ public function tableName() { - return '{{tokens_'.$this->dynamicId.'}}'; + return '{{tokens_' . $this->dynamicId . '}}'; } /** * Get current surveyId for other model/function * @return int */ - public function getSurveyId() { + public function getSurveyId() + { return $this->getDynamicId(); } - public static function getEncryptedAttributes(){ + public static function getEncryptedAttributes() + { return self::$aEncryptedAttributes; } - public static function getDefaultEncryptionOptions(){ + public static function getDefaultEncryptionOptions() + { $sEncrypted = 'N'; return array( 'enabled' => 'N', @@ -510,5 +514,4 @@ public static function getDefaultEncryptionOptions(){ ) ); } - } diff --git a/application/models/TokenDynamic.php b/application/models/TokenDynamic.php index 56763ec8a4e..d93bc9205fc 100644 --- a/application/models/TokenDynamic.php +++ b/application/models/TokenDynamic.php @@ -1,4 +1,6 @@ - array(self::BELONGS_TO, 'Survey', array(), 'condition'=>'sid='.self::$sid, 'together' => true), + 'survey' => array(self::BELONGS_TO, 'Survey', array(), 'condition' => 'sid=' . self::$sid, 'together' => true), 'responses' => array(self::HAS_MANY, 'SurveyDynamic', array('token' => 'token')) ); } @@ -126,7 +128,7 @@ public function relations() public function checkColumns() { $sid = self::$sid; - $sTableName = '{{tokens_'.$sid.'}}'; + $sTableName = '{{tokens_' . $sid . '}}'; $columncheck = array("tid", "participant_id", "firstname", "lastname", "email", "emailstatus", "token", "language", "blacklisted", "sent", "remindersent", "completed", "usesleft", "validfrom", "validuntil"); $tableSchema = Yii::app()->db->schema->getTable($sTableName); $columns = $tableSchema->getColumnNames(); @@ -135,12 +137,12 @@ public function checkColumns() if (count($missingcolumns) > 0) { Yii::app()->loadHelper('update/updatedb'); //Load the admin helper to allow column creation $columninfo = array( - 'validfrom'=>'datetime', - 'validuntil'=>'datetime', - 'blacklisted'=> 'string(17)', - 'participant_id'=> 'string(50)', - 'remindercount'=>"integer DEFAULT '0'", - 'usesleft'=>'integer NOT NULL default 1' + 'validfrom' => 'datetime', + 'validuntil' => 'datetime', + 'blacklisted' => 'string(17)', + 'participant_id' => 'string(50)', + 'remindercount' => "integer DEFAULT '0'", + 'usesleft' => 'integer NOT NULL default 1' ); //Not sure if any other fields would ever turn up here - please add if you can think of any others foreach ($missingcolumns as $columnname) { addColumn($sTableName, $columnname, $columninfo[$columnname]); @@ -172,7 +174,7 @@ public function checkColumns() */ public function findUninvited($aTokenIds = false, $iMaxEmails = 0, $bEmail = true, $SQLemailstatuscondition = '', $SQLremindercountcondition = '', $SQLreminderdelaycondition = '') { - $command = new CDbCriteria; + $command = new CDbCriteria(); $command->condition = ''; $command->addCondition("(completed ='N') or (completed='')"); $command->addCondition("token <> ''"); @@ -197,7 +199,7 @@ public function findUninvited($aTokenIds = false, $iMaxEmails = 0, $bEmail = tru } if ($aTokenIds) { - $command->addCondition("tid IN ('".implode("', '", $aTokenIds)."')"); + $command->addCondition("tid IN ('" . implode("', '", $aTokenIds) . "')"); } if ($iMaxEmails) { @@ -207,7 +209,7 @@ public function findUninvited($aTokenIds = false, $iMaxEmails = 0, $bEmail = tru $command->order = 'tid'; $oResult = TokenDynamic::model()->findAll($command); - foreach($oResult as $key=>$result){ + foreach ($oResult as $key => $result) { $oResult[$key] = $result->decrypt(); } return $oResult; @@ -224,7 +226,7 @@ public function findUninvited($aTokenIds = false, $iMaxEmails = 0, $bEmail = tru */ public function findUninvitedIDs($aTokenIds = false, $iMaxEmails = 0, $bEmail = true, $SQLemailstatuscondition = '', $SQLremindercountcondition = '', $SQLreminderdelaycondition = '') { - $command = new CDbCriteria; + $command = new CDbCriteria(); $command->condition = ''; $command->addCondition("(completed ='N') or (completed='')"); $command->addCondition("token <> ''"); @@ -248,7 +250,7 @@ public function findUninvitedIDs($aTokenIds = false, $iMaxEmails = 0, $bEmail = } if ($aTokenIds) { - $command->addCondition("tid IN ('".implode("', '", $aTokenIds)."')"); + $command->addCondition("tid IN ('" . implode("', '", $aTokenIds) . "')"); } if ($iMaxEmails) { @@ -270,7 +272,7 @@ public function findUninvitedIDs($aTokenIds = false, $iMaxEmails = 0, $bEmail = */ public function insertParticipant($data) { - $token = new self; + $token = new self(); foreach ($data as $k => $v) { $token->$k = $v; } @@ -316,7 +318,7 @@ public function updateToken($tid, $newToken) public function selectEmptyTokens($iSurveyID) { $survey = Survey::model()->findByPk($iSurveyID); - return Yii::app()->db->createCommand("SELECT tid FROM ".$survey->tokensTableName." WHERE token IS NULL OR token=''")->queryAll(); + return Yii::app()->db->createCommand("SELECT tid FROM " . $survey->tokensTableName . " WHERE token IS NULL OR token=''")->queryAll(); } /** @@ -327,12 +329,12 @@ public static function countAllAndCompleted($sid) { $select = array( 'count(*) AS cntall', - 'sum(CASE '.Yii::app()->db->quoteColumnName('completed').' - WHEN '.Yii::app()->db->quoteValue('N').' THEN 0 + 'sum(CASE ' . Yii::app()->db->quoteColumnName('completed') . ' + WHEN ' . Yii::app()->db->quoteValue('N') . ' THEN 0 ELSE 1 END) AS cntcompleted', ); - $result = Yii::app()->db->createCommand()->select($select)->from('{{tokens_'.$sid.'}}')->queryRow(); + $result = Yii::app()->db->createCommand()->select($select)->from('{{tokens_' . $sid . '}}')->queryRow(); return $result; } @@ -345,7 +347,7 @@ public static function countAllAndCompleted($sid) public function createToken($iTokenID) { //get token length from survey settings - $tlrow = Survey::model()->findByAttributes(array("sid"=>self::$sid)); + $tlrow = Survey::model()->findByAttributes(array("sid" => self::$sid)); $iTokenLength = $tlrow->tokenlength; //get all existing tokens @@ -385,7 +387,7 @@ public function createTokens($iSurveyID) } //get token length from survey settings - $tlrow = Survey::model()->findByAttributes(array("sid"=>$iSurveyID)); + $tlrow = Survey::model()->findByAttributes(array("sid" => $iSurveyID)); $iTokenLength = $tlrow->tokenlength; //if tokenlength is not set or there are other problems use the default value (15) @@ -454,7 +456,7 @@ public function deleteToken($tokenid) */ public function deleteRecords($iTokenIds) { - return Token::model(self::$sid)->deleteAllByAttributes(array('tid'=>$iTokenIds)); + return Token::model(self::$sid)->deleteAllByAttributes(array('tid' => $iTokenIds)); } /** @@ -466,14 +468,14 @@ public function getHasResponses($sToken) $oSurvey = Survey::model()->findByPk(intval(self::$sid)); if (!$oSurvey->hasResponsesTable) { return false; - } + } $command = Yii::app()->db->createCommand() ->select('COUNT(token)') - ->from('{{survey_'.intval(self::$sid).'}}') + ->from('{{survey_' . intval(self::$sid) . '}}') ->where('token=:token') ->bindParam(':token', $sToken, PDO::PARAM_STR); - return ((int)$command->queryScalar()>0); + return ((int)$command->queryScalar() > 0); } @@ -485,7 +487,7 @@ public function getEmailStatus($token) { $command = Yii::app()->db->createCommand() ->select('emailstatus') - ->from('{{tokens_'.intval(self::$sid).'}}') + ->from('{{tokens_' . intval(self::$sid) . '}}') ->where('token=:token') ->bindParam(':token', $token, PDO::PARAM_STR); @@ -499,7 +501,7 @@ public function getEmailStatus($token) */ public function updateEmailStatus($token, $status) { - return Yii::app()->db->createCommand()->update('{{tokens_'.intval(self::$sid).'}}', array('emailstatus' => $status), 'token = :token', array(':token' => $token)); + return Yii::app()->db->createCommand()->update('{{tokens_' . intval(self::$sid) . '}}', array('emailstatus' => $status), 'token = :token', array(':token' => $token)); } /** @@ -598,10 +600,10 @@ private function getYesNoDateFormated($field) { if ($field != 'N' && $field != '') { if ($field == 'Q') { - $field = ''.gT('Quota out').''; + $field = '' . gT('Quota out') . ''; } elseif ($field != 'Y') { $fieldDate = convertToGlobalSettingFormat($field); - $field = ''.$fieldDate.''; + $field = '' . $fieldDate . ''; } else { $field = ''; } @@ -617,7 +619,7 @@ private function getYesNoDateFormated($field) public function getEmailFormated() { if ($this->emailstatus == "bounced") { - return ' '.$this->email.''; + return ' ' . $this->email . ''; } else { return $this->email; } @@ -629,7 +631,7 @@ public function getEmailFormated() public function getEmailstatusFormated() { if ($this->emailstatus == "bounced") { - return ' '.$this->emailstatus.''; + return ' ' . $this->emailstatus . ''; } else { return $this->emailstatus; } @@ -811,142 +813,142 @@ public function getGridButtons() /* viewresponse button */ $baseView = intval(Permission::model()->hasSurveyPermission(self::$sid, 'responses', 'read') && $this->survey->active == "Y" && $this->survey->anonymized != "Y"); $gridButtons['viewresponse'] = array( - 'label'=>''.gT("View response details").'', - 'imageUrl'=>false, - 'url' => 'App()->createUrl("admin/responses/sa/viewbytoken",array("surveyid"=>'.self::$sid.',"token"=>$data->token));', + 'label' => '' . gT("View response details") . '', + 'imageUrl' => false, + 'url' => 'App()->createUrl("admin/responses/sa/viewbytoken",array("surveyid"=>' . self::$sid . ',"token"=>$data->token));', 'options' => array( - 'class'=>"btn btn-default btn-xs", - 'data-toggle'=>"tooltip", - 'title'=>gT("View response details") + 'class' => "btn btn-default btn-xs", + 'data-toggle' => "tooltip", + 'title' => gT("View response details") ), - 'visible'=> $baseView .' && $data->getHasResponses($data->token)', + 'visible' => $baseView . ' && $data->getHasResponses($data->token)', ); $gridButtons['spacerviewresponse'] = array( - 'label'=>'', - 'imageUrl'=>false, + 'label' => '', + 'imageUrl' => false, 'url' => '#', 'options' => array( - 'class'=>"btn btn-default btn-xs invisible", + 'class' => "btn btn-default btn-xs invisible", 'disabled' => 'disabled', - 'title'=>'' + 'title' => '' ), - 'visible'=> $baseView .'&& !$data->getHasResponses($data->token)', + 'visible' => $baseView . '&& !$data->getHasResponses($data->token)', 'click' => 'function(event){ window.LS.gridButton.noGridAction(event,$(this)); }', ); /* previewsurvey button */ $baseView = intval(Permission::model()->hasSurveyPermission(self::$sid, 'responses', 'create')); $gridButtons['previewsurvey'] = array( - 'label'=>''.gT("Launch the survey with this participant").'', - 'imageUrl'=>false, - 'url' => 'App()->createUrl("/survey/index",array("sid"=>'.self::$sid.',"token"=>$data->token,"newtest"=>"Y"));', + 'label' => '' . gT("Launch the survey with this participant") . '', + 'imageUrl' => false, + 'url' => 'App()->createUrl("/survey/index",array("sid"=>' . self::$sid . ',"token"=>$data->token,"newtest"=>"Y"));', 'options' => array( - 'class'=>"btn btn-default btn-xs", - 'target'=>"_blank", - 'data-toggle'=>"tooltip", - 'title'=>gT("Launch the survey with this participant") + 'class' => "btn btn-default btn-xs", + 'target' => "_blank", + 'data-toggle' => "tooltip", + 'title' => gT("Launch the survey with this participant") ), - 'visible'=> $baseView . ' && !empty($data->token) && ( $data->completed == "N" || empty($data->completed) || $data->survey->alloweditaftercompletion == "Y")' + 'visible' => $baseView . ' && !empty($data->token) && ( $data->completed == "N" || empty($data->completed) || $data->survey->alloweditaftercompletion == "Y")' ); $gridButtons['previewsurveyspacer'] = array( - 'label'=>'', - 'imageUrl'=>false, + 'label' => '', + 'imageUrl' => false, 'url' => '#', 'options' => array( - 'class'=>"btn btn-default btn-xs invisible", + 'class' => "btn btn-default btn-xs invisible", 'disabled' => 'disabled', - 'title'=> '' + 'title' => '' ), - 'visible'=> $baseView . ' && (empty($data->token) || !( $data->completed == "N" || empty($data->completed) || $data->survey->alloweditaftercompletion == "Y"))', + 'visible' => $baseView . ' && (empty($data->token) || !( $data->completed == "N" || empty($data->completed) || $data->survey->alloweditaftercompletion == "Y"))', 'click' => 'function(event){ window.LS.gridButton.noGridAction(event,$(this)); }', ); /* mail button */ $baseView = Permission::model()->hasSurveyPermission(self::$sid, 'tokens', 'update'); /* mailing mail button */ $gridButtons['mail'] = array( - 'label'=>''.gT("Send email invitation").'',// fa-enveloppe-o - 'imageUrl'=>false, - 'url' => 'App()->createUrl("/admin/tokens/sa/email",array("surveyid"=>'.self::$sid.',"tokenids"=>$data->tid,));', + 'label' => '' . gT("Send email invitation") . '',// fa-enveloppe-o + 'imageUrl' => false, + 'url' => 'App()->createUrl("/admin/tokens/sa/email",array("surveyid"=>' . self::$sid . ',"tokenids"=>$data->tid,));', 'options' => array( - 'class'=>"btn btn-default btn-xs btn-email", - 'data-toggle'=>"tooltip", - 'title'=>gT("Send email invitation") + 'class' => "btn btn-default btn-xs btn-email", + 'data-toggle' => "tooltip", + 'title' => gT("Send email invitation") ), - 'visible'=> $baseView . ' && !empty($data->token) && ($data->sent== "N" || empty($data->sent)) && $data->emailstatus == "OK" && $data->email && $data->completed == "N" && ($data->usesleft > 0 || $data->survey->alloweditaftercompletion == "Y")', + 'visible' => $baseView . ' && !empty($data->token) && ($data->sent== "N" || empty($data->sent)) && $data->emailstatus == "OK" && $data->email && $data->completed == "N" && ($data->usesleft > 0 || $data->survey->alloweditaftercompletion == "Y")', ); /* mailing remind button */ $gridButtons['remind'] = array( - 'label'=>''.gT("Send email reminder").'', - 'imageUrl'=>false, - 'url' => 'App()->createUrl("/admin/tokens/sa/email/action/remind",array("surveyid"=>'.self::$sid.',"tokenids"=>$data->tid));', + 'label' => '' . gT("Send email reminder") . '', + 'imageUrl' => false, + 'url' => 'App()->createUrl("/admin/tokens/sa/email/action/remind",array("surveyid"=>' . self::$sid . ',"tokenids"=>$data->tid));', 'options' => array( - 'class'=>"btn btn-default btn-xs btn-email", - 'data-toggle'=>"tooltip", - 'title'=>gT("Send email reminder") + 'class' => "btn btn-default btn-xs btn-email", + 'data-toggle' => "tooltip", + 'title' => gT("Send email reminder") ), - 'visible'=> $baseView . ' && !empty($data->token) && !($data->sent== "N" || empty($data->sent)) && $data->emailstatus == "OK" && $data->email && $data->completed == "N" && ($data->usesleft > 0 || $data->survey->alloweditaftercompletion == "Y")', + 'visible' => $baseView . ' && !empty($data->token) && !($data->sent== "N" || empty($data->sent)) && $data->emailstatus == "OK" && $data->email && $data->completed == "N" && ($data->usesleft > 0 || $data->survey->alloweditaftercompletion == "Y")', ); $gridButtons['mailspacer'] = array( - 'label'=>'', - 'imageUrl'=>false, + 'label' => '', + 'imageUrl' => false, 'url' => '#', 'options' => array( - 'class'=>"btn btn-default btn-xs invisible", + 'class' => "btn btn-default btn-xs invisible", 'disabled' => 'disabled', - 'title'=> '' + 'title' => '' ), - 'visible'=> $baseView . ' && (empty($data->token) || ($data->emailstatus != "OK" || empty($data->email) || $data->completed != "N" || ($data->usesleft <= 0 && $data->survey->alloweditaftercompletion != "Y")))', + 'visible' => $baseView . ' && (empty($data->token) || ($data->emailstatus != "OK" || empty($data->email) || $data->completed != "N" || ($data->usesleft <= 0 && $data->survey->alloweditaftercompletion != "Y")))', ); /* edit button button */ $gridButtons['edit'] = array( - 'label'=>''.gT('Edit this survey participant').'', - 'imageUrl'=>false, - 'url' => 'App()->createUrl("/admin/tokens/sa/edit",array("iSurveyId"=>'.self::$sid.',"iTokenId"=>$data->tid,"ajax"=>"true"));', + 'label' => '' . gT('Edit this survey participant') . '', + 'imageUrl' => false, + 'url' => 'App()->createUrl("/admin/tokens/sa/edit",array("iSurveyId"=>' . self::$sid . ',"iTokenId"=>$data->tid,"ajax"=>"true"));', 'options' => array( - 'class'=>"btn btn-default btn-xs btn-edit", - 'data-toggle'=>"tooltip", - 'title'=>gT('Edit this survey participant'), + 'class' => "btn btn-default btn-xs btn-edit", + 'data-toggle' => "tooltip", + 'title' => gT('Edit this survey participant'), 'data-sid' => self::$sid ), - 'visible' => ''.Permission::model()->hasSurveyPermission(self::$sid, 'tokens', 'update'), + 'visible' => '' . Permission::model()->hasSurveyPermission(self::$sid, 'tokens', 'update'), 'click' => 'startEditToken' ); /* delete button */ $gridButtons['deletetoken'] = array( - 'label'=>''.gT('Delete survey participant').'', - 'imageUrl'=>false, - 'url' => 'App()->createUrl("/admin/tokens/sa/deleteToken",array("sid"=>'.self::$sid.',"sItem"=>$data->tid,"ajax"=>"true"));', + 'label' => '' . gT('Delete survey participant') . '', + 'imageUrl' => false, + 'url' => 'App()->createUrl("/admin/tokens/sa/deleteToken",array("sid"=>' . self::$sid . ',"sItem"=>$data->tid,"ajax"=>"true"));', 'options' => array( - 'class'=>"btn btn-default btn-xs btn-delete", - 'data-toggle'=>"tooltip", - 'title'=>gT('Delete survey participant'), + 'class' => "btn btn-default btn-xs btn-delete", + 'data-toggle' => "tooltip", + 'title' => gT('Delete survey participant'), ), - 'visible' => ''.Permission::model()->hasSurveyPermission(self::$sid, 'tokens', 'delete'), + 'visible' => '' . Permission::model()->hasSurveyPermission(self::$sid, 'tokens', 'delete'), 'click' => 'function(event){ window.LS.gridButton.confirmGridAction(event,$(this)); }', ); /* CPDB link */ $baseVisible = intval(Permission::model()->hasGlobalPermission('participantpanel', 'read') && self::model(self::$sid)->count("participant_id is not null")); $gridButtons['viewparticipant'] = array( - 'label'=>''.gT('View this participant in the central participants database').'', - 'imageUrl'=>false, + 'label' => '' . gT('View this participant in the central participants database') . '', + 'imageUrl' => false, 'url' => 'App()->createUrl("admin/participants/sa/displayParticipants",array("#" => json_encode(["searchcondition"=>"participant_id||equal||".$data->participant_id],JSON_FORCE_OBJECT)))', 'options' => array( - 'class'=>"btn btn-default btn-xs btn-participant", - 'data-toggle'=>"tooltip", - 'title'=>gT('View this participant in the central participants database'), + 'class' => "btn btn-default btn-xs btn-participant", + 'data-toggle' => "tooltip", + 'title' => gT('View this participant in the central participants database'), ), 'click' => 'function(event){ window.LS.gridButton.postGridAction(event,$(this)); }', - 'visible' => $baseVisible.' && $data->participant_id', + 'visible' => $baseVisible . ' && $data->participant_id', ); $gridButtons['viewparticipantspacer'] = array( - 'label'=>'', - 'imageUrl'=>false, + 'label' => '', + 'imageUrl' => false, 'url' => '#', 'options' => array( - 'class'=>"btn btn-default btn-xs invisible", - 'data-toggle'=>"tooltip", - 'title'=>"", + 'class' => "btn btn-default btn-xs invisible", + 'data-toggle' => "tooltip", + 'title' => "", ), - 'visible' => $baseVisible.' && empty($data->participant_id)', + 'visible' => $baseVisible . ' && empty($data->participant_id)', 'click' => 'function(event){ window.LS.gridButton.noGridAction(event,$(this)); }', ); return $gridButtons; @@ -971,95 +973,95 @@ public function search() $sort = new CSort(); $sort->defaultOrder = 'tid ASC'; $sort->attributes = array( - 'tid'=>array( - 'asc'=>'tid', - 'desc'=>'tid desc', + 'tid' => array( + 'asc' => 'tid', + 'desc' => 'tid desc', ), - 'partcipant'=>array( - 'asc'=>'partcipant', - 'desc'=>'partcipant desc', + 'partcipant' => array( + 'asc' => 'partcipant', + 'desc' => 'partcipant desc', ), - 'firstname'=>array( - 'asc'=>'firstname', - 'desc'=>'firstname desc', + 'firstname' => array( + 'asc' => 'firstname', + 'desc' => 'firstname desc', ), - 'lastname'=>array( - 'asc'=>'lastname', - 'desc'=>'lastname desc', + 'lastname' => array( + 'asc' => 'lastname', + 'desc' => 'lastname desc', ), - 'email'=>array( - 'asc'=>'email', - 'desc'=>'email desc', + 'email' => array( + 'asc' => 'email', + 'desc' => 'email desc', ), - 'emailstatus'=>array( - 'asc'=>'emailstatus', - 'desc'=>'emailstatus desc', + 'emailstatus' => array( + 'asc' => 'emailstatus', + 'desc' => 'emailstatus desc', ), - 'token'=>array( - 'asc'=>'token', - 'desc'=>'token desc', + 'token' => array( + 'asc' => 'token', + 'desc' => 'token desc', ), - 'language'=>array( - 'asc'=>'language', - 'desc'=>'language desc', + 'language' => array( + 'asc' => 'language', + 'desc' => 'language desc', ), - 'blacklisted'=>array( - 'asc'=>'blacklisted', - 'desc'=>'blacklisted desc', + 'blacklisted' => array( + 'asc' => 'blacklisted', + 'desc' => 'blacklisted desc', ), - 'sent'=>array( - 'asc'=>'sent', - 'desc'=>'sent desc', + 'sent' => array( + 'asc' => 'sent', + 'desc' => 'sent desc', ), - 'remindersent'=>array( - 'asc'=>'remindersent', - 'desc'=>'remindersent desc', + 'remindersent' => array( + 'asc' => 'remindersent', + 'desc' => 'remindersent desc', ), - 'remindercount'=>array( + 'remindercount' => array( 'asc' => 'remindercount', 'desc' => 'remindercount desc', ), - 'completed'=>array( - 'asc'=>'completed', - 'desc'=>'completed desc', + 'completed' => array( + 'asc' => 'completed', + 'desc' => 'completed desc', ), - 'usesleft'=>array( - 'asc'=>'usesleft', - 'desc'=>'usesleft desc', + 'usesleft' => array( + 'asc' => 'usesleft', + 'desc' => 'usesleft desc', ), - 'validfrom'=>array( - 'asc'=>'validfrom', - 'desc'=>'validfrom desc', + 'validfrom' => array( + 'asc' => 'validfrom', + 'desc' => 'validfrom desc', ), - 'validuntil'=>array( - 'asc'=>'validuntil', - 'desc'=>'validuntil desc', + 'validuntil' => array( + 'asc' => 'validuntil', + 'desc' => 'validuntil desc', ), ); // Make sortable custom attributes foreach ($this->custom_attributes as $sColName => $oColumn) { $sort->attributes[$sColName] = array( - 'asc'=>$sColName, - 'desc'=>$sColName.' desc', + 'asc' => $sColName, + 'desc' => $sColName . ' desc', ); } - $criteria = new LSDbCriteria; + $criteria = new LSDbCriteria(); $criteria->compare('tid', $this->tid, false); $criteria->compare('token', $this->token, true); $criteria->compare('firstname', $this->firstname, true); @@ -1076,15 +1078,15 @@ public function search() $dateformatdetails = getDateFormatData(Yii::app()->session['dateformat']); if ($this->validfrom) { - $s = DateTime::createFromFormat($dateformatdetails['phpdate'].' H:i', $this->validfrom); + $s = DateTime::createFromFormat($dateformatdetails['phpdate'] . ' H:i', $this->validfrom); $s2 = $s->format('Y-m-d H:i'); - $criteria->addCondition('validfrom <= \''.$s2.'\''); + $criteria->addCondition('validfrom <= \'' . $s2 . '\''); } if ($this->validuntil) { - $s = DateTime::createFromFormat($dateformatdetails['phpdate'].' H:i', $this->validuntil); + $s = DateTime::createFromFormat($dateformatdetails['phpdate'] . ' H:i', $this->validuntil); $s2 = $s->format('Y-m-d H:i'); - $criteria->addCondition('validuntil >= \''.$s2.'\''); + $criteria->addCondition('validuntil >= \'' . $s2 . '\''); } foreach ($this->custom_attributes as $sColName => $oColumn) { @@ -1092,10 +1094,10 @@ public function search() } $dataProvider = new LSCActiveDataProvider('TokenDynamic', array( - 'sort'=>$sort, - 'criteria'=>$criteria, - 'pagination'=>array( - 'pageSize'=>$pageSizeTokenView, + 'sort' => $sort, + 'criteria' => $criteria, + 'pagination' => array( + 'pageSize' => $pageSizeTokenView, ), )); diff --git a/application/models/Tutorial.php b/application/models/Tutorial.php index 21b3280b90b..0752db202f5 100644 --- a/application/models/Tutorial.php +++ b/application/models/Tutorial.php @@ -36,13 +36,13 @@ public function rules() // will receive user inputs. return array( array('name, description, active, permission, permission_grade', 'required'), - array('active', 'numerical', 'integerOnly'=>true), - array('name, permission, permission_grade', 'length', 'max'=>128), - array('title', 'length', 'max'=>192), - array('icon', 'length', 'max'=>64), + array('active', 'numerical', 'integerOnly' => true), + array('name, permission, permission_grade', 'length', 'max' => 128), + array('title', 'length', 'max' => 192), + array('icon', 'length', 'max' => 64), // The following rule is used by search(). // @todo Please remove those attributes that should not be searched. - array('tid, name, description, active, permission, permission_grade', 'safe', 'on'=>'search'), + array('tid, name, description, active, permission, permission_grade', 'safe', 'on' => 'search'), ); } @@ -121,7 +121,7 @@ public function search() { // @todo Please modify the following code to remove attributes that should not be searched. - $criteria = new CDbCriteria; + $criteria = new CDbCriteria(); $criteria->compare('tid', $this->tid); $criteria->compare('name', $this->name, true); @@ -133,7 +133,7 @@ public function search() $criteria->compare('permission_grade', $this->permission_grade, true); return new CActiveDataProvider($this, array( - 'criteria'=>$criteria, + 'criteria' => $criteria, )); } @@ -148,13 +148,13 @@ public function findByName($tutorialName) if (array_key_exists($tutorialName, $defaultTutorials)) { $oTutorial = new Tutorial(); - array_walk($defaultTutorials[$tutorialName], function($attribute, $key) use (&$oTutorial) { + array_walk($defaultTutorials[$tutorialName], function ($attribute, $key) use (&$oTutorial) { $oTutorial->setAttribute($key, $attribute); }); return $oTutorial; } - return $this->find('name=:name', [':name' => $tutorialName]); + return $this->find('name=:name', [':name' => $tutorialName]); } public function getDefaultTutorials() @@ -205,7 +205,7 @@ public function getTutorialDataArray($tutorialName) $aSteps[] = $oTutorialEntry->getStepFromEntry(); } } else { - $aTutorialEntryRelations = TutorialEntryRelation::model()->findAll('tid=:tid', [':tid'=>$this->tid]); + $aTutorialEntryRelations = TutorialEntryRelation::model()->findAll('tid=:tid', [':tid' => $this->tid]); foreach ($aTutorialEntryRelations as $oTutorialMapEntry) { $oTutorialEntry = $oTutorialMapEntry->tutorialEntry; $aSteps[] = $oTutorialEntry->getStepFromEntry(); diff --git a/application/models/TutorialEntry.php b/application/models/TutorialEntry.php index f0c5f68231e..09b0643c230 100644 --- a/application/models/TutorialEntry.php +++ b/application/models/TutorialEntry.php @@ -34,7 +34,7 @@ public function rules() array('title, content, settings', 'required'), // The following rule is used by search(). // @todo Please remove those attributes that should not be searched. - array('teid, title, content, settings', 'safe', 'on'=>'search'), + array('teid, title, content, settings', 'safe', 'on' => 'search'), ); } @@ -63,7 +63,8 @@ public function attributeLabels() ); } - public function getColumns(){ + public function getColumns() + { return [ [ 'name' => 'teid', @@ -96,7 +97,7 @@ public function search() { // @todo Please modify the following code to remove attributes that should not be searched. - $criteria = new CDbCriteria; + $criteria = new CDbCriteria(); $criteria->compare('teid', $this->teid); $criteria->compare('title', $this->title, true); @@ -104,7 +105,7 @@ public function search() $criteria->compare('settings', $this->settings, true); return new CActiveDataProvider($this, array( - 'criteria'=>$criteria, + 'criteria' => $criteria, )); } diff --git a/application/models/TutorialEntryRelation.php b/application/models/TutorialEntryRelation.php index 102bd14b3f6..de60464bf70 100644 --- a/application/models/TutorialEntryRelation.php +++ b/application/models/TutorialEntryRelation.php @@ -28,10 +28,10 @@ public function rules() // will receive user inputs. return array( array('teid, tid', 'required'), - array('teid, tid, uid, sid', 'numerical', 'integerOnly'=>true), + array('teid, tid, uid, sid', 'numerical', 'integerOnly' => true), // The following rule is used by search(). // @todo Please remove those attributes that should not be searched. - array('teid, tid, uid, sid', 'safe', 'on'=>'search'), + array('teid, tid, uid, sid', 'safe', 'on' => 'search'), ); } @@ -44,7 +44,7 @@ public function relations() // class name for the relations automatically generated below. return array( 'tutorials' => array(self::HAS_ONE, 'Tutorial', 'tid', 'together' => true), - 'tutorialEntry' => array(self::HAS_ONE, 'TutorialEntry', 'teid', 'order'=>'ordering ASC', 'together' => true), + 'tutorialEntry' => array(self::HAS_ONE, 'TutorialEntry', 'teid', 'order' => 'ordering ASC', 'together' => true), ); } @@ -77,7 +77,7 @@ public function search() { // @todo Please modify the following code to remove attributes that should not be searched. - $criteria = new CDbCriteria; + $criteria = new CDbCriteria(); $criteria->compare('teid', $this->teid); $criteria->compare('tid', $this->tid); @@ -85,7 +85,7 @@ public function search() $criteria->compare('sid', $this->sid); return new CActiveDataProvider($this, array( - 'criteria'=>$criteria, + 'criteria' => $criteria, )); } diff --git a/application/models/UniqueNotification.php b/application/models/UniqueNotification.php index c6db6968d61..707ca016937 100644 --- a/application/models/UniqueNotification.php +++ b/application/models/UniqueNotification.php @@ -47,7 +47,7 @@ public function __construct($options = null) */ public function save($runValidation = true, $attributes = null) { - $toHash = $this->entity.$this->entity_id.$this->title.$this->message; + $toHash = $this->entity . $this->entity_id . $this->title . $this->message; $this->hash = hash('sha256', $toHash); $duplicate = self::model()->findByAttributes(array( @@ -57,7 +57,6 @@ public function save($runValidation = true, $attributes = null) if (empty($duplicate)) { parent::save($runValidation, $attributes); } else { - if ($this->markAsNew) { $duplicate->status = 'new'; } @@ -68,7 +67,6 @@ public function save($runValidation = true, $attributes = null) $duplicate->update(); } - } /** @inheritdoc */ diff --git a/application/models/UpdateForm.php b/application/models/UpdateForm.php index 74ad0624e6b..8b27012bafd 100644 --- a/application/models/UpdateForm.php +++ b/application/models/UpdateForm.php @@ -1,4 +1,5 @@ tempdir = Yii::app()->getConfig("tempdir"); $this->rootdir = Yii::app()->getConfig("rootdir"); $this->publicdir = Yii::app()->getConfig("publicdir"); - $this->path_cookie = $this->tempdir.DIRECTORY_SEPARATOR.'comfort_updater_cookie.txt'; + $this->path_cookie = $this->tempdir . DIRECTORY_SEPARATOR . 'comfort_updater_cookie.txt'; } /** @@ -75,7 +76,7 @@ public function getUpdateInfo($crosscheck = "1") if (Yii::app()->getConfig("updatable")) { if ($this->build != '') { $crosscheck = (int) $crosscheck; - $getters = '/index.php?r=updates/updateinfo¤tbuild='.$this->build.'&id='.md5(getGlobalSetting('SessionName')).'&crosscheck='.$crosscheck; + $getters = '/index.php?r=updates/updateinfo¤tbuild=' . $this->build . '&id=' . md5(getGlobalSetting('SessionName')) . '&crosscheck=' . $crosscheck; $content = $this->_performRequest($getters); } else { $content = new stdClass(); @@ -106,7 +107,7 @@ public function getWelcomeMessage($updateKey = null, $destinationBuild) $updater_version = Yii::app()->getConfig("updaterversion"); touch($this->path_cookie); - $getters = '/index.php?r=updates/getwelcome¤tbuild='.$this->build.'&keyid='.$updateKey.'&destinationbuild='.$destinationBuild.'&updater_version='.$updater_version; + $getters = '/index.php?r=updates/getwelcome¤tbuild=' . $this->build . '&keyid=' . $updateKey . '&destinationbuild=' . $destinationBuild . '&updater_version=' . $updater_version; $content = $this->_performRequest($getters, true); return $content; } @@ -118,7 +119,7 @@ public function getWelcomeMessage($updateKey = null, $destinationBuild) */ public function checkUpdateKeyonServer($submittedUpdateKey) { - $getters = '/index.php?r=updates/checkupdatekey&keyid='.$submittedUpdateKey; + $getters = '/index.php?r=updates/checkupdatekey&keyid=' . $submittedUpdateKey; $content = $this->_performRequest($getters); return $content; } @@ -145,7 +146,7 @@ public function setUpdateKey($submittedUpdateKey) $result = $updateKey->save(); } else { //Update - $result = SettingGlobal::model()->updateByPk('update_key', array('stg_value'=>$submittedUpdateKey)); + $result = SettingGlobal::model()->updateByPk('update_key', array('stg_value' => $submittedUpdateKey)); } if ($result) { @@ -155,7 +156,7 @@ public function setUpdateKey($submittedUpdateKey) return $updateKey; } else { // Else we return the errors - return array('result'=>false, 'error'=>'db_error'); + return array('result' => false, 'error' => 'db_error'); } } @@ -195,20 +196,20 @@ public function getLocalChecksForUpdater() $readOnly = array(); // We check the write permission of files - $lsRootPath = dirname(Yii::app()->request->scriptFile).'/'; + $lsRootPath = dirname(Yii::app()->request->scriptFile) . '/'; foreach ($toCheck as $check) { - if (file_exists($lsRootPath.$check)) { - if (!is_writable($lsRootPath.$check)) { - $readOnly[] = $lsRootPath.$check; + if (file_exists($lsRootPath . $check)) { + if (!is_writable($lsRootPath . $check)) { + $readOnly[] = $lsRootPath . $check; } } } if (count($readOnly) <= 0) { - return (object) array('result'=>true); + return (object) array('result' => true); } - return (object) array('result'=>false, 'readOnly'=>$readOnly); + return (object) array('result' => false, 'readOnly' => $readOnly); } @@ -220,7 +221,7 @@ public function getLocalChecksForUpdater() */ public function getChangelog($destinationBuild) { - $getters = '/index.php?r=updates/changelog&frombuild='.$this->build.'&tobuild='.$destinationBuild; + $getters = '/index.php?r=updates/changelog&frombuild=' . $this->build . '&tobuild=' . $destinationBuild; $content = $this->_performRequest($getters); return $content; } @@ -232,7 +233,7 @@ public function getChangelog($destinationBuild) */ public function getChangedFiles($destinationBuild) { - $getters = '/index.php?r=updates/changed-files&frombuild='.$this->build.'&tobuild='.$destinationBuild; + $getters = '/index.php?r=updates/changed-files&frombuild=' . $this->build . '&tobuild=' . $destinationBuild; $content = $this->_performRequest($getters); return $content; } @@ -246,8 +247,8 @@ public function getChangedFiles($destinationBuild) */ public function downloadUpdateFile($downloadid, $tobuild) { - $getters = '/index.php?r=updates/download&frombuild='.$this->build.'&tobuild='.$tobuild; - $getters .= "&access_token=".$_REQUEST['access_token']; + $getters = '/index.php?r=updates/download&frombuild=' . $this->build . '&tobuild=' . $tobuild; + $getters .= "&access_token=" . $_REQUEST['access_token']; $file = $this->_performDownload($getters); return $file; } @@ -260,7 +261,7 @@ public function downloadUpdateFile($downloadid, $tobuild) */ public function downloadUpdateUpdaterFile($tobuild) { - $getters = '/index.php?r=updates/download-updater&tobuild='.$tobuild.'&frombuild='.$this->build; + $getters = '/index.php?r=updates/download-updater&tobuild=' . $tobuild . '&frombuild=' . $this->build; $file = $this->_performDownload($getters, 'update_updater'); return $file; } @@ -273,26 +274,26 @@ public function downloadUpdateUpdaterFile($tobuild) */ public function unzipUpdateFile($file_to_unzip = 'update.zip') { - if (file_exists($this->tempdir.DIRECTORY_SEPARATOR.$file_to_unzip)) { + if (file_exists($this->tempdir . DIRECTORY_SEPARATOR . $file_to_unzip)) { // To debug pcl_zip, uncomment the following line : require_once('/var/www/limesurvey/LimeSurvey/application/libraries/admin/pclzip/pcltrace.lib.php'); require_once('/var/www/limesurvey/LimeSurvey/application/libraries/admin/pclzip/pclzip-trace.lib.php'); PclTraceOn(2); // To debug pcl_zip, comment the following line: Yii::app()->loadLibrary("admin/pclzip"); - $archive = new PclZip($this->tempdir.DIRECTORY_SEPARATOR.$file_to_unzip, false); + $archive = new PclZip($this->tempdir . DIRECTORY_SEPARATOR . $file_to_unzip, false); // TODO : RESTORE REPLACE NEWER !! // To debug pcl_zip, uncomment the following line : //if ($archive->extract(PCLZIP_OPT_PATH, $this->rootdir.'/', PCLZIP_OPT_REPLACE_NEWER)== 0) - if ($archive->extract(PCLZIP_OPT_PATH, $this->rootdir.DIRECTORY_SEPARATOR, PCLZIP_OPT_REPLACE_NEWER) == 0) { + if ($archive->extract(PCLZIP_OPT_PATH, $this->rootdir . DIRECTORY_SEPARATOR, PCLZIP_OPT_REPLACE_NEWER) == 0) { // To debug pcl_zip, uncomment the following line : //PclTraceDisplay(); die(); - $return = array('result'=>false, 'error'=>'unzip_error', 'message'=>$archive->errorInfo(true)); + $return = array('result' => false, 'error' => 'unzip_error', 'message' => $archive->errorInfo(true)); return (object) $return; } - $return = array('result'=>true); + $return = array('result' => true); return (object) $return; } else { - $return = array('result'=>false, 'error'=>'zip_update_not_found'); + $return = array('result' => false, 'error' => 'zip_update_not_found'); return (object) $return; } } @@ -316,15 +317,15 @@ public function removeDeletedFiles($updateinfos) { foreach ($updateinfos as $file) { $sFileToDelete = str_replace("..", "", $file['file']); - if ($file['type'] == 'D' && file_exists($this->rootdir.$sFileToDelete)) { - if (is_file($this->rootdir.$sFileToDelete)) { - if (!@unlink($this->rootdir.$sFileToDelete)) { - $return = array('result'=>false, 'error'=>'cant_remove_deleted_files', 'message'=>'file : '.$sFileToDelete); + if ($file['type'] == 'D' && file_exists($this->rootdir . $sFileToDelete)) { + if (is_file($this->rootdir . $sFileToDelete)) { + if (!@unlink($this->rootdir . $sFileToDelete)) { + $return = array('result' => false, 'error' => 'cant_remove_deleted_files', 'message' => 'file : ' . $sFileToDelete); return (object) $return; } } else { - if (!rmdir($this->rootdir.$sFileToDelete)) { - $return = array('result'=>false, 'error'=>'cant_remove_deleted_directory', 'message'=>'dir : '.$sFileToDelete); + if (!rmdir($this->rootdir . $sFileToDelete)) { + $return = array('result' => false, 'error' => 'cant_remove_deleted_directory', 'message' => 'dir : ' . $sFileToDelete); return (object) $return; } } @@ -341,10 +342,10 @@ public function removeDeletedFiles($updateinfos) */ public function removeTmpFile($sTmpFile = 'update.zip') { - $sTmpFilePath = $this->tempdir.DIRECTORY_SEPARATOR.$sTmpFile; + $sTmpFilePath = $this->tempdir . DIRECTORY_SEPARATOR . $sTmpFile; if (file_exists($sTmpFilePath)) { if (!@unlink($sTmpFilePath)) { - $return = array('result'=>false, 'error'=>'cant_remove_update_file', 'message'=>'file : '.$sTmpFilePath); + $return = array('result' => false, 'error' => 'cant_remove_update_file', 'message' => 'file : ' . $sTmpFilePath); return (object) $return; } } @@ -366,13 +367,13 @@ public function republishAssets() } // Delete all the content in the asset directory, but not the directory itself nor the index.html file at its root ^^ - $sAssetsDir = Yii::app()->getConfig('tempdir').'/assets/'; + $sAssetsDir = Yii::app()->getConfig('tempdir') . '/assets/'; $dir = dir($sAssetsDir); while (false !== $entry = $dir->read()) { if ($entry == '.' || $entry == '..' || $entry == 'index.html') { continue; } - rmdirr($sAssetsDir.DIRECTORY_SEPARATOR.$entry); + rmdirr($sAssetsDir . DIRECTORY_SEPARATOR . $entry); } } @@ -386,11 +387,11 @@ public function updateVersion($destinationBuild) { $destinationBuild = (int) $destinationBuild; @ini_set('auto_detect_line_endings', '1'); - $versionlines = file($this->rootdir.DIRECTORY_SEPARATOR.'application'.DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'version.php'); - $handle = fopen($this->rootdir.DIRECTORY_SEPARATOR.'application'.DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'version.php', "w"); + $versionlines = file($this->rootdir . DIRECTORY_SEPARATOR . 'application' . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'version.php'); + $handle = fopen($this->rootdir . DIRECTORY_SEPARATOR . 'application' . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'version.php', "w"); foreach ($versionlines as $line) { if (strpos($line, 'buildnumber') !== false) { - $line = '$config[\'buildnumber\'] = '.$destinationBuild.';'."\r\n"; + $line = '$config[\'buildnumber\'] = ' . $destinationBuild . ';' . "\r\n"; } fwrite($handle, $line); } @@ -419,7 +420,9 @@ public function destroyGlobalSettings() */ public function getFileStatus($updateinfo) { - $existingfiles = array(); $modifiedfiles = array(); $readonlyfiles = array(); + $existingfiles = array(); + $modifiedfiles = array(); + $readonlyfiles = array(); foreach ($updateinfo as $file) { $file = (array) $file; @@ -452,9 +455,9 @@ public function getFileStatus($updateinfo) } return array( - 'readonlyfiles'=>$readonlyfiles, - 'modifiedfiles'=>$modifiedfiles, - 'existingfiles'=>$existingfiles + 'readonlyfiles' => $readonlyfiles, + 'modifiedfiles' => $modifiedfiles, + 'existingfiles' => $existingfiles ); } @@ -468,18 +471,17 @@ public function backupFiles($updateinfos) $filestozip = array(); foreach ($updateinfos as $file) { - // To block the access to subdirectories $sFileToZip = str_replace("..", "", $file['file']); - if (is_file($this->publicdir.$sFileToZip) === true && basename($sFileToZip) != 'config.php') { - $filestozip[] = $this->publicdir.$sFileToZip; + if (is_file($this->publicdir . $sFileToZip) === true && basename($sFileToZip) != 'config.php') { + $filestozip[] = $this->publicdir . $sFileToZip; } } Yii::app()->loadLibrary("admin/pclzip"); - $basefilename = dateShift(date("Y-m-d H:i:s"), "Y-m-d", Yii::app()->getConfig('timeadjust')).'_'.md5(uniqid(rand(), true)); - $archive = new PclZip($this->tempdir.DIRECTORY_SEPARATOR.'LimeSurvey_files_backup_'.$basefilename.'.zip'); + $basefilename = dateShift(date("Y-m-d H:i:s"), "Y-m-d", Yii::app()->getConfig('timeadjust')) . '_' . md5(uniqid(rand(), true)); + $archive = new PclZip($this->tempdir . DIRECTORY_SEPARATOR . 'LimeSurvey_files_backup_' . $basefilename . '.zip'); $v_list = $archive->add($filestozip, PCLZIP_OPT_REMOVE_PATH, $this->publicdir); $backup = new stdClass(); @@ -539,7 +541,6 @@ public function backupDb($destinationBuild) } return $backupDb; - } /** @@ -612,7 +613,7 @@ public function getUpdateNotification() $next_update_check = $today->add(new DateInterval('P1D')); Yii::app()->session['next_update_check'] = $next_update_check; - $updates = array('result'=>$update_available, 'security_update'=>$security_update_available, 'unstable_update'=>$unstable_update_available); + $updates = array('result' => $update_available, 'security_update' => $security_update_available, 'unstable_update' => $unstable_update_available); } else { $next_update_check = $today->add(new DateInterval('P1D')); Yii::app()->session['next_update_check'] = $next_update_check; @@ -623,12 +624,12 @@ public function getUpdateNotification() $update_available = Yii::app()->session['update_result']; $unstable_update_available = Yii::app()->session['unstable_update']; $security_update_available = Yii::app()->session['security_update']; - $updates = array('result'=>$update_available, 'security_update'=>$security_update_available, 'unstable_update'=>$unstable_update_available); + $updates = array('result' => $update_available, 'security_update' => $security_update_available, 'unstable_update' => $unstable_update_available); } } else { Yii::app()->session['notificationstate'] = 0; Yii::app()->session['update_result'] = false; - $updates = array('result'=>false); + $updates = array('result' => false); } return (object) $updates; } @@ -644,7 +645,7 @@ public function getUpdateNotification() */ private function _getDbChecks($destinationBuild) { - $getters = '/index.php?r=updates/get-db-checks&build='.$destinationBuild; + $getters = '/index.php?r=updates/get-db-checks&build=' . $destinationBuild; $content = $this->_performRequest($getters); return $content; } @@ -677,9 +678,9 @@ private function _createDbBackup() { Yii::app()->loadHelper("admin/backupdb"); $backupDb = new stdClass(); - $basefilename = dateShift(date("Y-m-d H:i:s"), "Y-m-d", Yii::app()->getConfig('timeadjust')).'_'.md5(uniqid(rand(), true)); - $sfilename = $this->tempdir.DIRECTORY_SEPARATOR."backup_db_".randomChars(20)."_".dateShift(date("Y-m-d H:i:s"), "Y-m-d", Yii::app()->getConfig('timeadjust')).".sql"; - $dfilename = $this->tempdir.DIRECTORY_SEPARATOR."LimeSurvey_database_backup_".$basefilename.".zip"; + $basefilename = dateShift(date("Y-m-d H:i:s"), "Y-m-d", Yii::app()->getConfig('timeadjust')) . '_' . md5(uniqid(rand(), true)); + $sfilename = $this->tempdir . DIRECTORY_SEPARATOR . "backup_db_" . randomChars(20) . "_" . dateShift(date("Y-m-d H:i:s"), "Y-m-d", Yii::app()->getConfig('timeadjust')) . ".sql"; + $dfilename = $this->tempdir . DIRECTORY_SEPARATOR . "LimeSurvey_database_backup_" . $basefilename . ".zip"; outputDatabase('', false, $sfilename); if (is_file($sfilename) && filesize($sfilename)) { @@ -692,14 +693,13 @@ private function _createDbBackup() } else { $backupDb->result = true; $backupDb->message = htmlspecialchars($dfilename); - $backupDb->fileurl = Yii::app()->getBaseUrl(true).'/tmp/LimeSurvey_database_backup_'.$basefilename.'.zip'; + $backupDb->fileurl = Yii::app()->getBaseUrl(true) . '/tmp/LimeSurvey_database_backup_' . $basefilename . '.zip'; } } else { $backupDb->result = false; $backupDb->message = htmlspecialchars('db_backup_failed'); } return $backupDb; - } @@ -715,9 +715,8 @@ private function _getReadOnlyCheckedFile($file) $checkedfile->file = ''; // We check if the file read only - if ($file['type'] == 'A' && !file_exists($this->rootdir.$file['file']) || ($file['type'] == 'D' && file_exists($this->rootdir.$file['file']))) { - - $searchpath = $this->rootdir.$file['file']; + if ($file['type'] == 'A' && !file_exists($this->rootdir . $file['file']) || ($file['type'] == 'D' && file_exists($this->rootdir . $file['file']))) { + $searchpath = $this->rootdir . $file['file']; $is_writable = is_writable(dirname($searchpath)); // LOUIS : snippet from the original code. @@ -733,11 +732,12 @@ private function _getReadOnlyCheckedFile($file) $checkedfile->type = 'readonlyfile'; $checkedfile->file = $searchpath; } - } elseif (file_exists($this->rootdir.$file['file']) - && !is_writable($this->rootdir.$file['file'])) { - + } elseif ( + file_exists($this->rootdir . $file['file']) + && !is_writable($this->rootdir . $file['file']) + ) { $checkedfile->type = 'readonlyfile'; - $checkedfile->file = $this->rootdir.$file['file']; + $checkedfile->file = $this->rootdir . $file['file']; } return $checkedfile; @@ -759,18 +759,18 @@ private function _getCheckedFile($file) $checkedfile->file = ''; if ($file['file'] != '/application/config/version.php') { - // We check if the file exist - if ($file['type'] == 'A' && file_exists($this->rootdir.$file['file'])) { + if ($file['type'] == 'A' && file_exists($this->rootdir . $file['file'])) { //A new file, check if this already exists $checkedfile->type = 'existingfile'; $checkedfile->file = $file; } // We check if the file has been modified - elseif (($file['type'] == 'D' || $file['type'] == 'M') && is_file($this->rootdir.$file['file']) - && sha1_file($this->rootdir.$file['file']) != $file['checksum']) { - + elseif ( + ($file['type'] == 'D' || $file['type'] == 'M') && is_file($this->rootdir . $file['file']) + && sha1_file($this->rootdir . $file['file']) != $file['checksum'] + ) { $checkedfile->type = 'modifiedfile'; $checkedfile->file = $file; } @@ -795,7 +795,7 @@ private function _getFileSystemCheckList() // Could also use params in the futur : YAGNI !!!!! $files = array(); foreach ($fileSystemCheck as $key => $obj) { - $method = '_fileSystemCheck'.$obj->type; + $method = '_fileSystemCheck' . $obj->type; $files[$key] = $this->$method($obj); } @@ -835,7 +835,7 @@ private function _fileSystemCheck($obj) */ private function _fileSystemCheckAppath($obj) { - $obj->name = APPPATH.$obj->name; + $obj->name = APPPATH . $obj->name; return $this->_fileSystemCheck($obj); } @@ -859,7 +859,7 @@ private function _fileSystemCheckConfig($obj) */ private function _phpVerCheck($build) { - $getters = '/index.php?r=updates/get-php-ver&build='.$build; + $getters = '/index.php?r=updates/get-php-ver&build=' . $build; $php_ver = $this->_performRequest($getters); $return = new stdClass(); @@ -882,7 +882,7 @@ private function _phpVerCheck($build) */ private function _getModuleChecks($build) { - $getters = '/index.php?r=updates/get-php-modules&build='.$build; + $getters = '/index.php?r=updates/get-php-modules&build=' . $build; $php_module_list = $this->_performRequest($getters); $return = new stdClass(); @@ -911,11 +911,11 @@ private function _getMysqlChecks($build) $dbType = Yii::app()->db->getDriverName(); if (in_array($dbType, array('mysql', 'mysqli'))) { $checks->docheck = 'do'; - $getters = '/index.php?r=updates/get-mysql-ver&build='.$build; + $getters = '/index.php?r=updates/get-mysql-ver&build=' . $build; $mysql_requirements = $this->_performRequest($getters); $checks->mysql_ver = $mysql_requirements->version; $checks->local_mysql_ver = Yii::app()->db->getServerVersion(); - $checks->result = (version_compare($checks->local_mysql_ver, $checks->mysql_ver, '<')) ?false:true; + $checks->result = (version_compare($checks->local_mysql_ver, $checks->mysql_ver, '<')) ? false : true; } else { $checks->docheck = 'pass'; } @@ -950,10 +950,10 @@ private function _performDownload($getters, $fileName = 'update') { // TODO : Could test if curl is loaded, and if not, use httprequest2 $ch = curl_init(); - $pFile = fopen($this->tempdir.DIRECTORY_SEPARATOR.$fileName.'.zip', 'w'); - curl_setopt($ch, CURLOPT_URL, $this->_getProtocol().Yii::app()->getConfig("comfort_update_server_url").$getters); + $pFile = fopen($this->tempdir . DIRECTORY_SEPARATOR . $fileName . '.zip', 'w'); + curl_setopt($ch, CURLOPT_URL, $this->_getProtocol() . Yii::app()->getConfig("comfort_update_server_url") . $getters); if ($this->proxy_host_name != '') { - $proxy = $this->proxy_host_name.':'.$this->proxy_host_port; + $proxy = $this->proxy_host_name . ':' . $this->proxy_host_port; curl_setopt($ch, CURLOPT_PROXY, $proxy); } curl_setopt($ch, CURLOPT_COOKIEFILE, $this->path_cookie); @@ -966,7 +966,7 @@ private function _performDownload($getters, $fileName = 'update') $content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE); // But we want the header to be returned to the controller so we can check if a file has been returned curl_close($ch); - $result = ($content_type == "application/zip") ? array("result"=>true) : array('result'=>false, 'error'=>'error_while_processing_download'); + $result = ($content_type == "application/zip") ? array("result" => true) : array('result' => false, 'error' => 'error_while_processing_download'); return (object) $result; } @@ -982,13 +982,13 @@ private function _performRequest($getters, $create_new_cookie_file = false) { if ((extension_loaded("curl"))) { if (isset($_REQUEST['access_token'])) { - $getters .= "&access_token=".$_REQUEST['access_token']; + $getters .= "&access_token=" . $_REQUEST['access_token']; } - $ch = curl_init($this->_getProtocol().Yii::app()->getConfig("comfort_update_server_url").$getters); + $ch = curl_init($this->_getProtocol() . Yii::app()->getConfig("comfort_update_server_url") . $getters); if ($this->proxy_host_name != '') { - $proxy = $this->proxy_host_name.':'.$this->proxy_host_port; + $proxy = $this->proxy_host_name . ':' . $this->proxy_host_port; curl_setopt($ch, CURLOPT_PROXY, $proxy); } @@ -1014,7 +1014,7 @@ private function _performRequest($getters, $create_new_cookie_file = false) } else { // Should happen only on first step (get buttons), diplayed in check_updates/update_buttons/_updatesavailable_error.php // Could rather define a call to httprequest2 functions. - return (object) array('result' => false, 'error'=>"php_curl_not_loaded"); + return (object) array('result' => false, 'error' => "php_curl_not_loaded"); } } } diff --git a/application/models/User.php b/application/models/User.php index 823678c838a..679959b75cc 100644 --- a/application/models/User.php +++ b/application/models/User.php @@ -1,4 +1,5 @@ 64), - array('full_name', 'length','max'=>50), + array('users_name', 'length','max' => 64), + array('full_name', 'length','max' => 50), array('email', 'email'), array('full_name', 'LSYii_Validators'), // XSS if non super-admin - array('parent_id', 'default', 'value'=>0), - array('parent_id', 'numerical', 'integerOnly'=>true), - array('lang', 'default', 'value'=>Yii::app()->getConfig('defaultlang')), - array('lang', 'LSYii_Validators', 'isLanguage'=>true), - array('htmleditormode', 'default', 'value'=>'default'), - array('htmleditormode', 'in', 'range'=>array('default', 'wysiwyg', 'source'), 'allowEmpty'=>true), - array('questionselectormode', 'default', 'value'=>'default'), - array('questionselectormode', 'in', 'range'=>array('default', 'full', 'none'), 'allowEmpty'=>true), - array('templateeditormode', 'default', 'value'=>'default'), - array('templateeditormode', 'in', 'range'=>array('default', 'full', 'none'), 'allowEmpty'=>true), + array('parent_id', 'default', 'value' => 0), + array('parent_id', 'numerical', 'integerOnly' => true), + array('lang', 'default', 'value' => Yii::app()->getConfig('defaultlang')), + array('lang', 'LSYii_Validators', 'isLanguage' => true), + array('htmleditormode', 'default', 'value' => 'default'), + array('htmleditormode', 'in', 'range' => array('default', 'wysiwyg', 'source'), 'allowEmpty' => true), + array('questionselectormode', 'default', 'value' => 'default'), + array('questionselectormode', 'in', 'range' => array('default', 'full', 'none'), 'allowEmpty' => true), + array('templateeditormode', 'default', 'value' => 'default'), + array('templateeditormode', 'in', 'range' => array('default', 'full', 'none'), 'allowEmpty' => true), //array('dateformat', 'default','value'=>????), // What is the default ? - array('dateformat', 'numerical', 'integerOnly'=>true, 'allowEmpty'=>true), + array('dateformat', 'numerical', 'integerOnly' => true, 'allowEmpty' => true), // created as datetime default current date in create scenario ? // modifier as datetime default current date ? ); } - public function attributeLabels() { + public function attributeLabels() + { return [ 'uid' => gT('User ID'), 'users_name' => gT('Username'), @@ -129,7 +131,7 @@ public function attributeLabels() { */ public function getSurveysCreated() { - $noofsurveys = Survey::model()->countByAttributes(array("owner_id" =>$this->uid)); + $noofsurveys = Survey::model()->countByAttributes(array("owner_id" => $this->uid)); return $noofsurveys; } @@ -194,7 +196,7 @@ public function deleteOTPwd($username) */ public static function insertUser($new_user, $new_pass, $new_full_name, $parent_user, $new_email) { - $oUser = new self; + $oUser = new self(); $oUser->users_name = $new_user; $oUser->setPassword($new_pass); $oUser->full_name = $new_full_name; @@ -233,7 +235,7 @@ public static function findByUsername($sUserName) */ public static function updatePassword($iUserID, $sPassword) { - return User::model()->updateByPk($iUserID, array('password'=>password_hash($sPassword, PASSWORD_DEFAULT))); + return User::model()->updateByPk($iUserID, array('password' => password_hash($sPassword, PASSWORD_DEFAULT))); } /** @@ -275,7 +277,8 @@ public function checkPassword($sPassword) return false; } - public function checkPasswordStrength($password){ + public function checkPasswordStrength($password) + { $settings = Yii::app()->getConfig("passwordValidationRules"); $length = strlen($password); $lowercase = preg_match_all('@[a-z]@', $password); @@ -284,23 +287,35 @@ public function checkPasswordStrength($password){ $specialChars = preg_match_all('@[^\w]@', $password); $error = ""; - if((int) $settings['min'] > 0){ - if($length < $settings['min']) $error = sprintf(ngT('Password must be at least %d character long|Password must be at least %d characters long', $settings['min']), $settings['min']); + if ((int) $settings['min'] > 0) { + if ($length < $settings['min']) { + $error = sprintf(ngT('Password must be at least %d character long|Password must be at least %d characters long', $settings['min']), $settings['min']); + } } - if((int) $settings['max'] > 0){ - if($length > $settings['max']) $error = sprintf(ngT('Password must be at most %d character long|Password must be at most %d characters long', $settings['max']), $settings['max']); + if ((int) $settings['max'] > 0) { + if ($length > $settings['max']) { + $error = sprintf(ngT('Password must be at most %d character long|Password must be at most %d characters long', $settings['max']), $settings['max']); + } } - if((int) $settings['lower'] > 0){ - if($lowercase < $settings['lower']) $error = sprintf(ngT('Password must include at least %d lowercase letter|Password must include at least %d lowercase letters', $settings['lower']), $settings['lower']); + if ((int) $settings['lower'] > 0) { + if ($lowercase < $settings['lower']) { + $error = sprintf(ngT('Password must include at least %d lowercase letter|Password must include at least %d lowercase letters', $settings['lower']), $settings['lower']); + } } - if((int) $settings['upper'] > 0){ - if($uppercase < $settings['upper']) $error = sprintf(ngT('Password must include at least %d uppercase letter|Password must include at least %d uppercase letters', $settings['upper']), $settings['upper']); + if ((int) $settings['upper'] > 0) { + if ($uppercase < $settings['upper']) { + $error = sprintf(ngT('Password must include at least %d uppercase letter|Password must include at least %d uppercase letters', $settings['upper']), $settings['upper']); + } } - if((int) $settings['numeric'] > 0){ - if($number < $settings['numeric']) $error = sprintf(ngT('Password must include at least %d number|Password must include at least %d numbers', $settings['numeric']), $settings['numeric']); + if ((int) $settings['numeric'] > 0) { + if ($number < $settings['numeric']) { + $error = sprintf(ngT('Password must include at least %d number|Password must include at least %d numbers', $settings['numeric']), $settings['numeric']); + } } - if((int) $settings['symbol'] > 0){ - if($specialChars < $settings['symbol']) $error = sprintf(ngT('Password must include at least %d special character|Password must include at least %d special characters', $settings['symbol']), $settings['symbol']); + if ((int) $settings['symbol'] > 0) { + if ($specialChars < $settings['symbol']) { + $error = sprintf(ngT('Password must include at least %d special character|Password must include at least %d special characters', $settings['symbol']), $settings['symbol']); + } } return($error); @@ -319,14 +334,15 @@ public function checkPasswordStrength($password){ * @param $repeatPassword * @return string empty string means everything is ok, otherwise error message is returned */ - public function validateNewPassword($newPassword, $oldPassword,$repeatPassword){ + public function validateNewPassword($newPassword, $oldPassword, $repeatPassword) + { $errorMsg = ''; if (!empty($newPassword)) { $errorMsg = $this->checkPasswordStrength($newPassword); } - if($errorMsg === '') { + if ($errorMsg === '') { if (!$this->checkPassword($oldPassword)) { // Always check password $errorMsg = gT("Your new password was not saved because the old password was wrong."); @@ -345,23 +361,35 @@ public function validateNewPassword($newPassword, $oldPassword,$repeatPassword){ return $errorMsg; } - public function getPasswordHelpText(){ + public function getPasswordHelpText() + { $settings = Yii::app()->getConfig("passwordValidationRules"); $txt = gT('A password must meet the following requirements: '); - if((int) $settings['min'] > 0) $txt .= sprintf(ngT('At least %d character long.|At least %d characters long.', $settings['min']), $settings['min']).' '; - if((int) $settings['max'] > 0) $txt .= sprintf(ngT('At most %d character long.|At most %d characters long.', $settings['max']), $settings['max']).' '; - if((int) $settings['min'] > 0 && (int) $settings['max'] > 0){ - if($settings['min'] == $settings['max']){ - $txt .= sprintf(ngT('Exactly %d character long.|Exactly %d characters long.', $settings['min']), $settings['min']).' '; - } else - if($settings['min'] < $settings['max']){ - $txt .= sprintf(gT('Between %d and %d characters long.'), $settings['min'], $settings['max']).' '; - } - } - if((int) $settings['lower'] > 0) $txt .= sprintf(ngT('At least %d lower case letter.|At least %d lower case letters.', $settings['lower']), $settings['lower']).' '; - if((int) $settings['upper'] > 0) $txt .= sprintf(ngT('At least %d upper case letter.|At least %d upper case letters.', $settings['upper']), $settings['upper']).' '; - if((int) $settings['numeric'] > 0) $txt .= sprintf(ngT('At least %d number.|At least %d numbers.', $settings['numeric']), $settings['numeric']).' '; - if((int) $settings['symbol'] > 0) $txt .= sprintf(ngT('At least %d special character.|At least %d special characters.', $settings['symbol']), $settings['symbol']).' '; + if ((int) $settings['min'] > 0) { + $txt .= sprintf(ngT('At least %d character long.|At least %d characters long.', $settings['min']), $settings['min']) . ' '; + } + if ((int) $settings['max'] > 0) { + $txt .= sprintf(ngT('At most %d character long.|At most %d characters long.', $settings['max']), $settings['max']) . ' '; + } + if ((int) $settings['min'] > 0 && (int) $settings['max'] > 0) { + if ($settings['min'] == $settings['max']) { + $txt .= sprintf(ngT('Exactly %d character long.|Exactly %d characters long.', $settings['min']), $settings['min']) . ' '; + } elseif ($settings['min'] < $settings['max']) { + $txt .= sprintf(gT('Between %d and %d characters long.'), $settings['min'], $settings['max']) . ' '; + } + } + if ((int) $settings['lower'] > 0) { + $txt .= sprintf(ngT('At least %d lower case letter.|At least %d lower case letters.', $settings['lower']), $settings['lower']) . ' '; + } + if ((int) $settings['upper'] > 0) { + $txt .= sprintf(ngT('At least %d upper case letter.|At least %d upper case letters.', $settings['upper']), $settings['upper']) . ' '; + } + if ((int) $settings['numeric'] > 0) { + $txt .= sprintf(ngT('At least %d number.|At least %d numbers.', $settings['numeric']), $settings['numeric']) . ' '; + } + if ((int) $settings['symbol'] > 0) { + $txt .= sprintf(ngT('At least %d special character.|At least %d special characters.', $settings['symbol']), $settings['symbol']) . ' '; + } return($txt); } @@ -390,8 +418,9 @@ public function getCommonUID($surveyid, $postusergroupid) return Yii::app()->db->createCommand($query2)->bindParam(":surveyid", $surveyid, PDO::PARAM_INT)->bindParam(":postugid", $postusergroupid, PDO::PARAM_INT)->query(); //Checked } - public function getGroupList() { - $collector = array_map(function($oUserInGroup) { + public function getGroupList() + { + $collector = array_map(function ($oUserInGroup) { return $oUserInGroup->name; }, $this->groups); return join(', ', $collector); @@ -434,69 +463,77 @@ public function getButtons() // Edit self $editUser = ""; } else { - if (Permission::model()->hasGlobalPermission('superadmin', 'read') + if ( + Permission::model()->hasGlobalPermission('superadmin', 'read') || $this->uid == Yii::app()->session['loginID'] || (Permission::model()->hasGlobalPermission('users', 'update') && $this->parent_id == Yii::app()->session['loginID'] ) ) { - $editUser = ""; + $editUser = ""; } - if (((Permission::model()->hasGlobalPermission('superadmin', 'read') && + if ( + ((Permission::model()->hasGlobalPermission('superadmin', 'read') && $this->uid != Yii::app()->session['loginID']) || (Permission::model()->hasGlobalPermission('users', 'update') && - $this->parent_id == Yii::app()->session['loginID'])) && !Permission::isForcedSuperAdmin($this->uid)) { + $this->parent_id == Yii::app()->session['loginID'])) && !Permission::isForcedSuperAdmin($this->uid) + ) { //'admin/user/sa/setuserpermissions' - $setPermissionsUser = ""; - } - if ((Permission::model()->hasGlobalPermission('superadmin', 'read') + $setPermissionsUser = ""; + } + if ( + (Permission::model()->hasGlobalPermission('superadmin', 'read') || Permission::model()->hasGlobalPermission('templates', 'read')) - && !Permission::isForcedSuperAdmin($this->uid)) { + && !Permission::isForcedSuperAdmin($this->uid) + ) { //'admin/user/sa/setusertemplates') - $setTemplatePermissionUser = ""; - } - if ((Permission::model()->hasGlobalPermission('superadmin', 'read') + $setTemplatePermissionUser = ""; + } + if ( + (Permission::model()->hasGlobalPermission('superadmin', 'read') || (Permission::model()->hasGlobalPermission('users', 'delete') - && $this->parent_id == Yii::app()->session['loginID'])) && !Permission::isForcedSuperAdmin($this->uid)) { - $deleteUrl = Yii::app()->getController()->createUrl('admin/user/sa/deluser', array( - "action"=> "deluser", - "uid"=>$this->uid, - "user" => htmlspecialchars(Yii::app()->user->getId()) - )); - - //'admin/user/sa/deluser' - $deleteUser = " + && $this->parent_id == Yii::app()->session['loginID'])) && !Permission::isForcedSuperAdmin($this->uid) + ) { + $deleteUrl = Yii::app()->getController()->createUrl('admin/user/sa/deluser', array( + "action" => "deluser", + "uid" => $this->uid, + "user" => htmlspecialchars(Yii::app()->user->getId()) + )); + + //'admin/user/sa/deluser' + $deleteUser = " "; - } - if (Permission::isForcedSuperAdmin(Yii::app()->session['loginID']) + } + if ( + Permission::isForcedSuperAdmin(Yii::app()->session['loginID']) && $this->parent_id != Yii::app()->session['loginID'] - ) { - //'admin/user/sa/setasadminchild' - $changeOwnership = ""; - } + ) { + //'admin/user/sa/setasadminchild' + $changeOwnership = ""; + } } return "

" . $editUser @@ -523,70 +560,70 @@ public function getManagementButtons() $userDetail = "" - .""; + data-href='" . $detailUrl . "'>"; $editPermissionButton = "" - .""; + data-href='" . $setPermissionsUrl . "'>"; $addRoleButton = "" - .""; + data-href='" . $setRoleUrl . "'>"; $editTemplatePermissionButton = "" - .""; + data-href='" . $setTemplatePermissionsUrl . "'>"; $editUserButton = "" - .""; + data-href='" . $editUrl . "'>"; $takeOwnershipButton = "" - .""; $deleteUserButton = "" - .""; + title='" . gT("Delete User") . "' + data-href='" . $deleteUrl . "'>"; /*$deleteUserButton = "" - ."'; + $button .= ' '; } return $button; @@ -364,55 +365,55 @@ public function searchMine($isMine) $sort = new CSort(); $sort->attributes = array( - 'usergroup_id'=>array( - 'asc'=>'ugid', - 'desc'=>'ugid desc', + 'usergroup_id' => array( + 'asc' => 'ugid', + 'desc' => 'ugid desc', ), - 'name'=>array( - 'asc'=>'name', - 'desc'=>'name desc', + 'name' => array( + 'asc' => 'name', + 'desc' => 'name desc', ), - 'description'=>array( - 'asc'=>'description', - 'desc'=>'description desc', + 'description' => array( + 'asc' => 'description', + 'desc' => 'description desc', ), - 'owner'=>array( - 'asc'=>'users.users_name', - 'desc'=>'users.users_name desc', + 'owner' => array( + 'asc' => 'users.users_name', + 'desc' => 'users.users_name desc', ), - 'members'=>array( - 'asc'=>'member_count', - 'desc'=>'member_count desc', + 'members' => array( + 'asc' => 'member_count', + 'desc' => 'member_count desc', ), ); $user_in_groups_table = UserInGroup::model()->tableName(); $member_count_sql = "(SELECT count(*) FROM $user_in_groups_table AS users_in_groups WHERE users_in_groups.ugid = t.ugid)"; - $criteria = new CDbCriteria; + $criteria = new CDbCriteria(); // select $criteria->select = array( '*', - $member_count_sql." as member_count", + $member_count_sql . " as member_count", ); $criteria->join .= 'LEFT JOIN {{users}} AS users ON ( users.uid = t.owner_id )'; if (!Permission::model()->hasGlobalPermission('superadmin', 'read')) { if ($isMine) { - $criteria->addCondition("t.owner_id=".App()->user->getId(), "AND"); + $criteria->addCondition("t.owner_id=" . App()->user->getId(), "AND"); } else { - $criteria->addCondition("t.owner_id<>".App()->user->getId(), "AND"); - $criteria->addCondition("t.ugid IN (SELECT ugid FROM $user_in_groups_table WHERE ".$user_in_groups_table.".uid = ".App()->user->getId().")", "AND"); + $criteria->addCondition("t.owner_id<>" . App()->user->getId(), "AND"); + $criteria->addCondition("t.ugid IN (SELECT ugid FROM $user_in_groups_table WHERE " . $user_in_groups_table . ".uid = " . App()->user->getId() . ")", "AND"); } } $dataProvider = new CActiveDataProvider('UserGroup', array( - 'sort'=>$sort, - 'criteria'=>$criteria, - 'pagination'=>array( - 'pageSize'=>$pageSize, + 'sort' => $sort, + 'criteria' => $criteria, + 'pagination' => array( + 'pageSize' => $pageSize, ), )); @@ -428,7 +429,7 @@ public function searchMine($isMine) */ public function hasUser($uid) { - $userInGroup = UserInGroup::model()->findByAttributes(['ugid'=>$this->ugid], 'uid=:uid', [':uid'=>$uid]); + $userInGroup = UserInGroup::model()->findByAttributes(['ugid' => $this->ugid], 'uid=:uid', [':uid' => $uid]); if ($userInGroup) { return true; } @@ -463,10 +464,11 @@ public function addUser($uid) * * @throws \PHPMailer\PHPMailer\Exception */ - public function sendUserEmails($ugid, $subject, $body, $copy){ + public function sendUserEmails($ugid, $subject, $body, $copy) + { $sendEmailSuccessErrors = []; - $criteria = new CDbCriteria; + $criteria = new CDbCriteria(); $criteria->compare('ugid', $ugid)->addNotInCondition('users.uid', array(Yii::app()->session['loginID'])); /**@var $eruresult UserInGroup[] */ $usersInGroup = UserInGroup::model()->with('users')->findAll($criteria); @@ -497,24 +499,26 @@ public function sendUserEmails($ugid, $subject, $body, $copy){ $sendEmailSuccessErrors[$cnt]['success'] = true; } else { $sendEmailSuccessErrors[$cnt]['success'] = false; - $sendEmailSuccessErrors[$cnt]['msg'] = sprintf(gT("Email to %s failed. Error Message : %s"), - \CHtml::encode("{$userInGroup->users->users_name} <{$userInGroup->users->email}>"), $mailer->getError()); + $sendEmailSuccessErrors[$cnt]['msg'] = sprintf( + gT("Email to %s failed. Error Message : %s"), + \CHtml::encode("{$userInGroup->users->users_name} <{$userInGroup->users->email}>"), + $mailer->getError() + ); } $mailer->ErrorInfo = ''; $cnt++; } - $msgToUser = gt('Sending emails to users(sucess/errors):') ."
"; - foreach ($sendEmailSuccessErrors as $emaiLResult){ + $msgToUser = gt('Sending emails to users(sucess/errors):') . "
"; + foreach ($sendEmailSuccessErrors as $emaiLResult) { $msgToUser .= $emaiLResult['username'] . ': '; - if($emaiLResult['success']){ - $msgToUser .= gt('Sending successful') ."
"; - }else{ - $msgToUser .= gt('Error: ') . $emaiLResult['msg'] ."
"; + if ($emaiLResult['success']) { + $msgToUser .= gt('Sending successful') . "
"; + } else { + $msgToUser .= gt('Error: ') . $emaiLResult['msg'] . "
"; } } return $msgToUser; } - } diff --git a/application/models/UserInGroup.php b/application/models/UserInGroup.php index 377e5737e8a..bb8a1cff93b 100644 --- a/application/models/UserInGroup.php +++ b/application/models/UserInGroup.php @@ -1,4 +1,6 @@ -true), + array('uid, ugid', 'numerical', 'integerOnly' => true), ); - } /** @inheritdoc */ @@ -106,5 +107,4 @@ public function join($fields, $from, $condition = false, $join = false, $order = $data = $user->queryRow(); return $data; } - } diff --git a/application/models/UserInPermissionrole.php b/application/models/UserInPermissionrole.php index 406420893d0..158c10c9689 100644 --- a/application/models/UserInPermissionrole.php +++ b/application/models/UserInPermissionrole.php @@ -9,96 +9,97 @@ */ class UserInPermissionrole extends CActiveRecord { - /** - * @return string the associated database table name - */ - public function tableName() - { - return '{{user_in_permissionrole}}'; - } + /** + * @return string the associated database table name + */ + public function tableName() + { + return '{{user_in_permissionrole}}'; + } - /** - * @return array validation rules for model attributes. - */ - public function rules() - { - // NOTE: you should only define rules for those attributes that - // will receive user inputs. - return array( - array('ptid, uid', 'required'), - array('ptid, uid', 'numerical', 'integerOnly'=>true), - // The following rule is used by search(). - // @todo Please remove those attributes that should not be searched. - array('ptid, uid', 'safe', 'on'=>'search'), - ); - } + /** + * @return array validation rules for model attributes. + */ + public function rules() + { + // NOTE: you should only define rules for those attributes that + // will receive user inputs. + return array( + array('ptid, uid', 'required'), + array('ptid, uid', 'numerical', 'integerOnly' => true), + // The following rule is used by search(). + // @todo Please remove those attributes that should not be searched. + array('ptid, uid', 'safe', 'on' => 'search'), + ); + } - /** - * @return array relational rules. - */ - public function relations() - { - // NOTE: you may need to adjust the relation name and the related - // class name for the relations automatically generated below. - return array( + /** + * @return array relational rules. + */ + public function relations() + { + // NOTE: you may need to adjust the relation name and the related + // class name for the relations automatically generated below. + return array( 'role' => array(self::BELONGS_TO, 'Permissiontemplates', ['ptid']), 'user' => array(self::BELONGS_TO, 'User', 'uid'), - ); - } + ); + } - /** - * @return array customized attribute labels (name=>label) - */ - public function attributeLabels() - { - return array( - 'ptid' => 'Ptid', - 'uid' => 'Uid', - ); - } + /** + * @return array customized attribute labels (name=>label) + */ + public function attributeLabels() + { + return array( + 'ptid' => 'Ptid', + 'uid' => 'Uid', + ); + } - public function getRoleForUser($userId, $single = false) { + public function getRoleForUser($userId, $single = false) + { $aRoles = self::model()->findAllByAttributes(['uid' => $userId]); - if($single) { + if ($single) { return $aRoles[0]; } return $aRoles; } - /** - * Retrieves a list of models based on the current search/filter conditions. - * - * Typical usecase: - * - Initialize the model fields with values from filter form. - * - Execute this method to get CActiveDataProvider instance which will filter - * models according to data in model fields. - * - Pass data provider to CGridView, CListView or any similar widget. - * - * @return CActiveDataProvider the data provider that can return the models - * based on the search/filter conditions. - */ - public function search() - { - // @todo Please modify the following code to remove attributes that should not be searched. + /** + * Retrieves a list of models based on the current search/filter conditions. + * + * Typical usecase: + * - Initialize the model fields with values from filter form. + * - Execute this method to get CActiveDataProvider instance which will filter + * models according to data in model fields. + * - Pass data provider to CGridView, CListView or any similar widget. + * + * @return CActiveDataProvider the data provider that can return the models + * based on the search/filter conditions. + */ + public function search() + { + // @todo Please modify the following code to remove attributes that should not be searched. - $criteria=new CDbCriteria; + $criteria = new CDbCriteria(); - $criteria->compare('ptid',$this->ptid); - $criteria->compare('uid',$this->uid); + $criteria->compare('ptid', $this->ptid); + $criteria->compare('uid', $this->uid); - return new CActiveDataProvider($this, array( - 'criteria'=>$criteria, - )); - } + return new CActiveDataProvider($this, array( + 'criteria' => $criteria, + )); + } - /** - * Returns the static model of the specified AR class. - * Please note that you should have this exact method in all your CActiveRecord descendants! - * @param string $className active record class name. - * @return UserInPermissionrole the static model class - */ - public static function model($className=__CLASS__) - { - return parent::model($className); - } + /** + * Returns the static model of the specified AR class. + * Please note that you should have this exact method in all your CActiveRecord descendants! + * @param string $className active record class name. + * @return UserInPermissionrole the static model class + */ + public static function model($className = __CLASS__) + { + return parent::model($className); + } } diff --git a/application/models/UserParser.php b/application/models/UserParser.php index 0eaa6bc1795..c464b0c260d 100644 --- a/application/models/UserParser.php +++ b/application/models/UserParser.php @@ -1,11 +1,12 @@ * @license GPL3.0 */ -class UserParser +class UserParser { /** * reads an uploaded csv file @@ -16,7 +17,7 @@ class UserParser public static function getDataFromCSV($FILES) { $sRandomFileName = randomChars(20); - $sFilePath = Yii::app()->getConfig('tempdir').DIRECTORY_SEPARATOR.$sRandomFileName; + $sFilePath = Yii::app()->getConfig('tempdir') . DIRECTORY_SEPARATOR . $sRandomFileName; $aPathinfo = pathinfo($FILES['the_file']['name']); $sExtension = $aPathinfo['extension']; $bMoveFileResult = false; @@ -26,10 +27,10 @@ public static function getDataFromCSV($FILES) Yii::app()->setFlashMessage(sprintf(gT("Sorry, this file is too large. Only files up to %01.2f MB are allowed."), getMaximumFileUploadSize() / 1024 / 1024), 'error'); Yii::app()->getController()->redirect(array('/userManagement/index')); Yii::app()->end(); - } elseif (strtolower($sExtension) == 'csv' ) { + } elseif (strtolower($sExtension) == 'csv') { $bMoveFileResult = @move_uploaded_file($_FILES['the_file']['tmp_name'], $sFilePath); } else { - Yii::app()->setFlashMessage(gT("This is not a .csv file."). 'It is a '.$sExtension, 'error'); + Yii::app()->setFlashMessage(gT("This is not a .csv file.") . 'It is a ' . $sExtension, 'error'); Yii::app()->getController()->redirect(array('/userManagement/index')); Yii::app()->end(); } @@ -47,11 +48,11 @@ public static function getDataFromCSV($FILES) safeDie('File not found.'); } - $aFirstLine = fgetcsv($oCSVFile, 0,$delimiter, '"'); + $aFirstLine = fgetcsv($oCSVFile, 0, $delimiter, '"'); $iHeaderCount = count($aFirstLine); $aToBeAddedUsers = []; - while (($row = fgetcsv($oCSVFile, 0,$delimiter, '"')) !== false) { + while (($row = fgetcsv($oCSVFile, 0, $delimiter, '"')) !== false) { $rowarray = array(); for ($i = 0; $i < $iHeaderCount; ++$i) { $val = (isset($row[$i]) ? $row[$i] : ''); @@ -80,12 +81,12 @@ public static function getDataFromJSON($FILES) $json = file_get_contents($FILES['the_file']['tmp_name']); $decoded = json_decode($json, true); - foreach($decoded as $data){ - if(!isset($data["email"]) || !isset($data["users_name"]) || !isset($data["full_name"]) || !isset($data["lang"]) || !isset($data["password"])){ + foreach ($decoded as $data) { + if (!isset($data["email"]) || !isset($data["users_name"]) || !isset($data["full_name"]) || !isset($data["lang"]) || !isset($data["password"])) { Yii::app()->setFlashMessage( - sprintf(gT("Wrong definition! Please make sure that your JSON arrays contains the fields '%s', '%s', '%s', '%s', and '%s'"), 'users_name','full_name','email','lang','password'), + sprintf(gT("Wrong definition! Please make sure that your JSON arrays contains the fields '%s', '%s', '%s', '%s', and '%s'"), 'users_name', 'full_name', 'email', 'lang', 'password'), 'error' - ); + ); Yii::app()->getController()->redirect(array('/userManagement/index')); Yii::app()->end(); } @@ -94,7 +95,7 @@ public static function getDataFromJSON($FILES) return $decoded; } - /** + /** *Function to get the delimiter of a Csv file * @param string $csvFile Path to the CSV file * @return string Delimiter @@ -110,7 +111,7 @@ private static function detectCsvDelimiter($csvFile) $handle = fopen($csvFile, "r"); $firstLine = fgets($handle); - fclose($handle); + fclose($handle); foreach ($delimiters as $delimiter => &$count) { $count = count(str_getcsv($firstLine, $delimiter)); } diff --git a/application/models/behaviors/PluginEventBehavior.php b/application/models/behaviors/PluginEventBehavior.php index 04a1fb1f881..3cadd35eee1 100644 --- a/application/models/behaviors/PluginEventBehavior.php +++ b/application/models/behaviors/PluginEventBehavior.php @@ -1,6 +1,6 @@ dispatchPluginModelEvent('after'.get_class($this->owner).'Delete'); - $this->_dispatchDynamic('after','Delete'); + $this->dispatchPluginModelEvent('after' . get_class($this->owner) . 'Delete'); + $this->_dispatchDynamic('after', 'Delete'); $this->dispatchPluginModelEvent('afterModelDelete'); } @@ -31,16 +31,16 @@ public function afterSave(CEvent $event) if ($pluginManager->shutdownObject->isEnabled()) { return; } - $this->dispatchPluginModelEvent('after'.get_class($this->owner).'Save'); - $this->_dispatchDynamic('after','Save'); + $this->dispatchPluginModelEvent('after' . get_class($this->owner) . 'Save'); + $this->_dispatchDynamic('after', 'Save'); $this->dispatchPluginModelEvent('afterModelSave'); } public function beforeDelete(CModelEvent $event) { - $this->dispatchPluginModelEvent('before'.get_class($this->owner).'Delete'); - $this->_dispatchDynamic('before','Delete'); + $this->dispatchPluginModelEvent('before' . get_class($this->owner) . 'Delete'); + $this->_dispatchDynamic('before', 'Delete'); $this->dispatchPluginModelEvent('beforeModelDelete'); } @@ -52,8 +52,8 @@ public function beforeSave(CModelEvent $event) if ($pluginManager->shutdownObject->isEnabled()) { return; } - $this->dispatchPluginModelEvent('before'.get_class($this->owner).'Save'); - $this->_dispatchDynamic('before','Save'); + $this->dispatchPluginModelEvent('before' . get_class($this->owner) . 'Save'); + $this->_dispatchDynamic('before', 'Save'); $this->dispatchPluginModelEvent('beforeModelSave'); } @@ -64,13 +64,13 @@ public function beforeSave(CModelEvent $event) * @param string $what * @return PluginEvent the dispatched event */ - private function _dispatchDynamic($when,$what) + private function _dispatchDynamic($when, $what) { - if(is_subclass_of($this->owner,'Dynamic')) { + if (is_subclass_of($this->owner, 'Dynamic')) { $params = array( 'dynamicId' => $this->owner->getDynamicId() ); - return $this->dispatchPluginModelEvent($when.get_parent_class($this->owner).$what,null,$params); + return $this->dispatchPluginModelEvent($when . get_parent_class($this->owner) . $what, null, $params); } } /** @@ -86,11 +86,11 @@ public function dispatchPluginModelEvent($sEventName, $criteria = null, $eventPa { $oPluginEvent = new PluginEvent($sEventName, $this); $oPluginEvent->set('model', $this->owner); - if(method_exists($this->owner,'getSurveyId')) { + if (method_exists($this->owner, 'getSurveyId')) { $oPluginEvent->set('iSurveyID', $this->owner->getSurveyId()); $oPluginEvent->set('surveyId', $this->owner->getSurveyId()); } - foreach($eventParams as $param => $value) { + foreach ($eventParams as $param => $value) { $oPluginEvent->set($param, $value); } if (isset($criteria)) {
'.CHtml::link(CHtml::encode(rawurldecode($aFilesInfo[$iFileIndex]['name'])), App()->createUrl("/admin/responses", array("sa"=>"actionDownloadfile", "surveyid"=>self::$sid, "iResponseId"=>$this->id, "iQID"=>$oFieldMap->qid, "iIndex"=>$iFileIndex))).''.sprintf('%s Mb', round($aFilesInfo[$iFileIndex]['size'] / 1000, 2)).'' . CHtml::link(CHtml::encode(rawurldecode($aFilesInfo[$iFileIndex]['name'])), App()->createUrl("/admin/responses", array("sa" => "actionDownloadfile", "surveyid" => self::$sid, "iResponseId" => $this->id, "iQID" => $oFieldMap->qid, "iIndex" => $iFileIndex))) . '' . sprintf('%s Mb', round($aFilesInfo[$iFileIndex]['size'] / 1000, 2)) . ''.htmlspecialchars($aFilesInfo[$iFileIndex]['title'], ENT_QUOTES, 'UTF-8').'' . htmlspecialchars($aFilesInfo[$iFileIndex]['title'], ENT_QUOTES, 'UTF-8') . ''.htmlspecialchars($aFilesInfo[$iFileIndex]['comment'], ENT_QUOTES, 'UTF-8').'' . htmlspecialchars($aFilesInfo[$iFileIndex]['comment'], ENT_QUOTES, 'UTF-8') . '