Skip to content

Commit

Permalink
DEV: Survey Tablenames 2 (#766)
Browse files Browse the repository at this point in the history
Fixed issue #12394: Adding question to quota shoult order questions in display order
Dev: add quoteColumnName for order
Dev: Put the grouping criteria in separate method (reusable)
Dev: Survey Tabenames
Dev: Survey responsestablename
Dev: Survey tokenstablename
Dev: fix surveyid
  • Loading branch information
TonisOrmisson authored and LouisGac committed Jul 11, 2017
1 parent fede438 commit c9f9501
Show file tree
Hide file tree
Showing 21 changed files with 137 additions and 138 deletions.
14 changes: 8 additions & 6 deletions application/controllers/Statistics_userController.php
Expand Up @@ -50,14 +50,17 @@ public function _remap($method, $params = array())
/**
* @param int $surveyid
* @param string $language
* @throws CHttpException
*/
public function actionAction($surveyid,$language=null)
{
$sLanguage = $language;
$survey = Survey::model()->findByPk($surveyid);

$this->sLanguage = $language;

$iSurveyID = (int) $surveyid;
$this->iSurveyID = (int) $surveyid;
$iSurveyID = (int) $survey->sid;
$this->iSurveyID = $survey->sid;

//$postlang = returnglobal('lang');
//~ Yii::import('application.libraries.admin.progressbar',true);
Expand Down Expand Up @@ -199,13 +202,12 @@ public function actionAction($surveyid,$language=null)
$totalrecords = 0;

//count number of answers
$query = "SELECT count(*) FROM {{survey_".intval($iSurveyID)."}}";
$query = "SELECT count(*) FROM ".$survey->responsesTableName;

//if incompleted answers should be filtert submitdate has to be not null
//this setting is taken from config-defaults.php
if (Yii::app()->getConfig("filterout_incomplete_answers") == true)
{
$query .= " WHERE {{survey_".intval($iSurveyID)."}}.submitdate is not null";
if (Yii::app()->getConfig("filterout_incomplete_answers") == true) {
$query .= " WHERE ".$survey->responsesTableName.".submitdate is not null";
}
$result = Yii::app()->db->createCommand($query)->queryAll();

Expand Down
13 changes: 7 additions & 6 deletions application/controllers/admin/dataentry.php
Expand Up @@ -492,7 +492,7 @@ public function editdata($subaction, $id, $surveyid, $language='')

if (Permission::model()->hasSurveyPermission($surveyid, 'responses','update'))
{
$surveytable = "{{survey_".$surveyid.'}}';
$surveytable = $survey->responsesTableName;
$aData['display']['menu_bars']['browse'] = gT("Data entry");

Yii::app()->loadHelper('database');
Expand Down Expand Up @@ -1386,16 +1386,17 @@ public function delete()
if (!empty($_REQUEST['sid'])) $surveyid = (int)$_REQUEST['sid'];

$surveyid = sanitize_int($surveyid);
$survey = Survey::model()->findByPk($surveyid);
$id = $_REQUEST['id'];

$aData = array(
'surveyid' => $surveyid,
'id' => $id
);

if (Permission::model()->hasSurveyPermission($surveyid, 'responses','read') && Permission::model()->hasSurveyPermission($surveyid, 'responses', 'delete'))
{
$surveytable = "{{survey_".$surveyid.'}}';
if (Permission::model()->hasSurveyPermission($surveyid, 'responses','read')
&& Permission::model()->hasSurveyPermission($surveyid, 'responses', 'delete')) {
$surveytable = $survey->responsesTableName;
$aData['thissurvey'] = getSurveyInfo($surveyid);

$delquery = "DELETE FROM $surveytable WHERE id=$id";
Expand Down Expand Up @@ -1437,7 +1438,7 @@ public function update()
{

Yii::app()->loadHelper("database");
$surveytable = "{{survey_".$surveyid.'}}';
$surveytable = $survey->responsesTableName;
$fieldmap = createFieldMap($survey,'full',false,false,$survey->language);
// restet token if user is not allowed to update
if(!Permission::model()->hasSurveyPermission($surveyid,'tokens','update')) // If not allowed to read: remove it
Expand Down Expand Up @@ -1607,7 +1608,7 @@ public function insert()
}
}

$tokenTableExists = tableExists('{{tokens_'.$thissurvey['sid'].'}}');
$tokenTableExists = $survey->hasTokensTable;

// First Check if the survey uses tokens and if a token has been provided
if ($tokenTableExists && (!$_POST['token']))
Expand Down
12 changes: 5 additions & 7 deletions application/controllers/admin/participantsaction.php
Expand Up @@ -288,17 +288,15 @@ public function displayParticipants()
if (!Permission::model()->hasGlobalPermission('superadmin','read'))
$surveys->permission(Yii::app()->user->getId());

/** @var Survey[] $aSurveyNames */
$aSurveyNames = $surveys->model()->with(array('languagesettings'=>array('condition'=>'surveyls_language=language'), 'owner'))->findAll();

/* Build a list of surveys that have tokens tables */
$tSurveyNames=array();
foreach($aSurveyNames as $row)
{
$row = array_merge($row->attributes, $row->defaultlanguage->attributes);
$bTokenExists = tableExists('{{tokens_' . $row['sid'] . '}}');
if ($bTokenExists) //If tokens table exists
{
$tSurveyNames[]=$row;
foreach($aSurveyNames as $row) {
$trow = array_merge($row->attributes, $row->defaultlanguage->attributes);
if ($row->hasTokensTable) {
$tSurveyNames[]=$trow;
}
}

Expand Down
2 changes: 1 addition & 1 deletion application/controllers/admin/printablesurvey.php
Expand Up @@ -53,7 +53,7 @@ function index($surveyid, $lang = null)
$surveyname = $aSurveyInfo['surveyls_title'];
$surveydesc = $aSurveyInfo['surveyls_description'];
$surveyactive = $aSurveyInfo['active'];
$surveytable = "{{survey_".$aSurveyInfo['sid']."}}";
$surveytable = $survey->responsesTableName;
$surveyexpirydate = $aSurveyInfo['expires'];
$surveyfaxto = $aSurveyInfo['faxto'];
$dateformattype = $aSurveyInfo['surveyls_dateformat'];
Expand Down
9 changes: 5 additions & 4 deletions application/controllers/admin/responses.php
Expand Up @@ -281,7 +281,7 @@ public function view($iSurveyID, $iId, $sBrowseLang = '')
case "name":
$answervalue = CHtml::link(
htmlspecialchars($oPurifier->purify(rawurldecode($phparray[$index][$metadata]))),
$this->getController()->createUrl("/admin/responses",array("sa"=>"actionDownloadfile","surveyid"=>$surveyid,"iResponseId"=>$iId,"iQID"=>$fnames[$i]['qid'],"iIndex"=>$index))
$this->getController()->createUrl("/admin/responses",array("sa"=>"actionDownloadfile","surveyid"=>$iSurveyID,"iResponseId"=>$iId,"iQID"=>$fnames[$i]['qid'],"iIndex"=>$index))
);
break;
default:
Expand Down Expand Up @@ -316,7 +316,7 @@ public function view($iSurveyID, $iId, $sBrowseLang = '')
$aData['menu']['view'] = true;
$aData['menu']['close'] = true;
// This resets the url on the close button to go to the upper view
$aData['menu']['closeurl'] = $this->getController()->createUrl("admin/responses/sa/browse/surveyid/".$iSurveyId);
$aData['menu']['closeurl'] = $this->getController()->createUrl("admin/responses/sa/browse/surveyid/".$iSurveyID);

$this->_renderWrappedTemplate('',$aViewUrls, $aData);
}
Expand All @@ -334,6 +334,7 @@ public function view($iSurveyID, $iId, $sBrowseLang = '')

public function index($iSurveyID)
{
$survey = Survey::model()->findByPk($iSurveyID);
$aData = $this->_getData($iSurveyID);
extract($aData);
$aViewUrls = array();
Expand All @@ -350,9 +351,9 @@ public function index($iSurveyID)

$aData['num_total_answers'] = SurveyDynamic::model($iSurveyID)->count();
$aData['num_completed_answers'] = SurveyDynamic::model($iSurveyID)->count('submitdate IS NOT NULL');
if (tableExists('{{tokens_' . $iSurveyID . '}}') && Permission::model()->hasSurveyPermission($iSurveyID,'tokens','read'))
if ($survey->hasTokensTable && Permission::model()->hasSurveyPermission($iSurveyID,'tokens','read'))
{
$aData['with_token']= Yii::app()->db->schema->getTable('{{tokens_' . $iSurveyID . '}}');
$aData['with_token']= Yii::app()->db->schema->getTable($survey->tokensTableName);
$aData['tokeninfo'] = Token::model($iSurveyID)->summary();
}

Expand Down
3 changes: 2 additions & 1 deletion application/controllers/admin/saved.php
Expand Up @@ -54,8 +54,9 @@ public function view($iSurveyId)
*/
public function delete($iSurveyId, $iSurveyResponseId, $iSavedControlId)
{
$survey = Survey::model()->findByPk($iSurveyId);
SavedControl::model()->deleteAllByAttributes(array('scid' => $iSavedControlId, 'sid' => $iSurveyId)) or die(gT("Couldn't delete"));
Yii::app()->db->createCommand()->delete("{{survey_".intval($iSurveyId)."}}", 'id=:id', array('id' => $iSurveyResponseId)) or die(gT("Couldn't delete"));
Yii::app()->db->createCommand()->delete($survey->responsesTableName, 'id=:id', array('id' => $iSurveyResponseId)) or die(gT("Couldn't delete"));

$this->getController()->redirect(array("admin/saved/sa/view/surveyid/{$iSurveyId}"));
}
Expand Down
4 changes: 2 additions & 2 deletions application/controllers/admin/tokens.php
Expand Up @@ -961,7 +961,7 @@ public function managetokenattributes($iSurveyId)
$this->getController()->redirect(array("/admin/survey/sa/view/surveyid/{$iSurveyId}"));
}
// CHECK TO SEE IF A TOKEN TABLE EXISTS FOR THIS SURVEY
$bTokenExists = tableExists('{{tokens_' . $iSurveyId . '}}');
$bTokenExists = $survey->hasTokensTable;
if (!$bTokenExists) //If no tokens table exists
{
self::_newtokentable($iSurveyId);
Expand Down Expand Up @@ -1038,7 +1038,7 @@ public function updatetokenattributes($iSurveyId)
Yii::app()->db->createCommand(Yii::app()->db->getSchema()->addColumn("{{tokens_".intval($iSurveyId)."}}", 'attribute_' . $i, 'string(255)'))->execute();
}

Yii::app()->db->schema->getTable('{{tokens_' . $iSurveyId . '}}', true); // Refresh schema cache just in case the table existed in the past
Yii::app()->db->schema->getTable($survey->tokensTableName, true); // Refresh schema cache just in case the table existed in the past
LimeExpressionManager::SetDirtyFlag(); // so that knows that token tables have changed

Yii::app()->session['flashmessage'] = sprintf(gT("%s field(s) were successfully added."), $number2add);
Expand Down
3 changes: 2 additions & 1 deletion application/controllers/survey/index.php
Expand Up @@ -26,6 +26,7 @@ function action()
global $surveyid;
global $thissurvey, $thisstep;
global $clienttoken, $tokensexist, $token;
$survey=Survey::model()->findByPk($surveyid);

// only attempt to change session lifetime if using a DB backend
// with file based sessions, it's up to the admin to configure maxlifetime
Expand Down Expand Up @@ -261,7 +262,7 @@ function action()
}

//SEE IF SURVEY USES TOKENS
if ($surveyExists == 1 && tableExists('{{tokens_'.$thissurvey['sid'].'}}')){
if ($surveyExists == 1 && $survey->hasTokensTable){
$tokensexist = 1;
}else{
$tokensexist = 0;
Expand Down
3 changes: 2 additions & 1 deletion application/core/Survey_Common_Action.php
Expand Up @@ -914,6 +914,7 @@ function _surveysidemenu($aData)
{

$iSurveyID = $aData['surveyid'];
$survey=Survey::model()->findByPk($iSurveyID);
// TODO : create subfunctions
$sumresult1 = Survey::model()->with(array(
'languagesettings' => array('condition'=>'surveyls_language=language'))
Expand All @@ -938,7 +939,7 @@ function _surveysidemenu($aData)
$aData['activated'] = ($surveyinfo['active'] == 'Y');

// Tokens
$bTokenExists = tableExists('{{tokens_' . $iSurveyID . '}}');
$bTokenExists = $survey->hasTokensTable;
if (!$bTokenExists) {
$aData['tokenmanagement'] = Permission::model()->hasSurveyPermission($iSurveyID, 'surveysettings', 'update')
|| Permission::model()->hasSurveyPermission($iSurveyID, 'tokens', 'create');
Expand Down
4 changes: 2 additions & 2 deletions application/helpers/admin/activate_helper.php
Expand Up @@ -251,6 +251,7 @@ function checkQuestions($postsid, $iSurveyID, $qtypes)
function activateSurvey($iSurveyID, $simulate = false)
{
// Event beforeSurveyActivate
$oSurvey = Survey::model()->findByPk($iSurveyID);
$event = new PluginEvent('beforeSurveyActivate');
$event->set('surveyId', $iSurveyID);
$event->set('simulate', $simulate);
Expand Down Expand Up @@ -278,7 +279,6 @@ function activateSurvey($iSurveyID, $simulate = false)
$sCollation=" COLLATE SQL_Latin1_General_CP1_CS_AS";
}
//Check for any additional fields for this survey and create necessary fields (token and datestamp)
$oSurvey = Survey::model()->findByPk($iSurveyID);
$oSurvey->fixInvalidQuestions();
//Get list of questions for the base language
$sFieldMap = createFieldMap($oSurvey,'full',true,false,$oSurvey->language);
Expand Down Expand Up @@ -460,7 +460,7 @@ function activateSurvey($iSurveyID, $simulate = false)
Yii::app()->db->createCommand($sQuery)->execute();
// Add back the primaryKey

Yii::app()->db->createCommand()->addPrimaryKey('PRIMARY_'.rand(1,50000), '{{survey_'.$iSurveyID.'}}', 'id');
Yii::app()->db->createCommand()->addPrimaryKey('PRIMARY_'.rand(1,50000), $oSurvey->responsesTableName, 'id');
}
elseif (Yii::app()->db->driverName=='pgsql')
{
Expand Down
18 changes: 9 additions & 9 deletions application/helpers/admin/export/SurveyDao.php
Expand Up @@ -101,24 +101,24 @@ public function loadSurveyResults(SurveyObj $survey, $iMinimum, $iMaximum, $sFil
{

// Get info about the survey
$aSelectFields=Yii::app()->db->schema->getTable('{{survey_' . $survey->id . '}}')->getColumnNames();
$aSelectFields=Yii::app()->db->schema->getTable($survey->responsesTableName)->getColumnNames();
// Allways add Table prefix : see bug #08396 . Don't use array_walk for PHP < 5.3 compatibility
foreach ($aSelectFields as &$sField)
$sField ="{{survey_{$survey->id}}}.".$sField;
$oRecordSet = Yii::app()->db->createCommand()->from('{{survey_' . $survey->id . '}}');
$sField =$survey->responsesTableName.".".$sField;
$oRecordSet = Yii::app()->db->createCommand()->from($survey->responsesTableName);
if (tableExists('tokens_'.$survey->id) && array_key_exists ('token',SurveyDynamic::model($survey->id)->attributes) && Permission::model()->hasSurveyPermission($survey->id,'tokens','read'))
{
$oRecordSet->leftJoin('{{tokens_' . $survey->id . '}} tokentable','tokentable.token={{survey_' . $survey->id . '}}.token');
$aTokenFields=Yii::app()->db->schema->getTable('{{tokens_' . $survey->id . '}}')->getColumnNames();
$oRecordSet->leftJoin($survey->tokensTableName.' tokentable','tokentable.token=' . $survey->tokensTableName . '.token');
$aTokenFields=Yii::app()->db->schema->getTable($survey->tokensTableName)->getColumnNames();
foreach ($aTokenFields as &$sField)
$sField ="tokentable.".$sField;
$aSelectFields=array_merge($aSelectFields,array_diff($aTokenFields, array('tokentable.token')));
//$aSelectFields=array_diff($aSelectFields, array('{{survey_{$survey->id}}}.token'));
//$aSelectFields[]='{{survey_' . $survey->id . '}}.token';
}
if ($survey->info['savetimings']=="Y") {
$oRecordSet->leftJoin($survey->timi." survey_timings", "{{survey_" . $survey->id . "}}.id = survey_timings.id");
$aTimingFields=Yii::app()->db->schema->getTable($oSurvey->hasTimingsTable)->getColumnNames();
$oRecordSet->leftJoin($survey->timi." survey_timings", $survey->responsesTableName. ".id = survey_timings.id");
$aTimingFields=Yii::app()->db->schema->getTable($survey->hasTimingsTable)->getColumnNames();
foreach ($aTimingFields as &$sField)
$sField ="survey_timings.".$sField;
$aSelectFields=array_merge($aSelectFields,array_diff($aTimingFields, array('survey_timings.id')));
Expand All @@ -130,7 +130,7 @@ public function loadSurveyResults(SurveyObj $survey, $iMinimum, $iMaximum, $sFil
'min'=>$iMinimum,
'max'=>$iMaximum
);
$selection = '{{survey_' . $survey->id . '}}.id >= :min AND {{survey_' . $survey->id . '}}.id <= :max';
$selection = $survey->responsesTableName.'.id >= :min AND ' . $survey->responsesTableName . '.id <= :max';
$oRecordSet->where($selection, $aParams);

if(is_string($sFilter) && $sFilter)
Expand All @@ -154,7 +154,7 @@ public function loadSurveyResults(SurveyObj $survey, $iMinimum, $iMaximum, $sFil
// Do nothing, all responses
break;
}
$oRecordSet->order='{{survey_' . $survey->id . '}}.id ASC';
$oRecordSet->order=$survey->responsesTableName . '.id ASC';
$survey->responses=$oRecordSet->select($aSelectFields)->query();
}
}
23 changes: 11 additions & 12 deletions application/helpers/admin/import_helper.php
Expand Up @@ -1576,11 +1576,12 @@ function GetNewSurveyID($iDesiredSurveyId)

/**
* @param string $sFullFilePath
* @return mixed
*/
function XMLImportTokens($sFullFilePath,$iSurveyID,$sCreateMissingAttributeFields=true)
{
Yii::app()->loadHelper('database');

$survey=Survey::model()->findByPk($iSurveyID);
$sXMLdata = file_get_contents($sFullFilePath);
$xml = simplexml_load_string($sXMLdata,'SimpleXMLElement',LIBXML_NONET);
$results['warnings']=array();
Expand All @@ -1603,21 +1604,18 @@ function XMLImportTokens($sFullFilePath,$iSurveyID,$sCreateMissingAttributeField
{
// Get a list with all fieldnames in the XML
$aXLMFieldNames=array();
foreach ($xml->tokens->fields->fieldname as $sFieldName )
{
foreach ($xml->tokens->fields->fieldname as $sFieldName ) {
$aXLMFieldNames[]=(string)$sFieldName;
}
// Get a list of all fieldnames in the token table
$aTokenFieldNames=Yii::app()->db->getSchema()->getTable("{{tokens_$iSurveyID}}",true);
$aTokenFieldNames=Yii::app()->db->getSchema()->getTable($survey->tokensTableName,true);
$aTokenFieldNames=array_keys($aTokenFieldNames->columns);
$aFieldsToCreate=array_diff($aXLMFieldNames, $aTokenFieldNames);
Yii::app()->loadHelper('update/updatedb');

foreach ($aFieldsToCreate as $sField)
{
if (strpos($sField,'attribute')!==false)
{
addColumn('{{tokens_'.$iSurveyID.'}}',$sField, 'string');
foreach ($aFieldsToCreate as $sField) {
if (strpos($sField,'attribute')!==false) {
addColumn($survey->tokensTableName,$sField, 'string');
}
}
}
Expand Down Expand Up @@ -1651,17 +1649,18 @@ function XMLImportTokens($sFullFilePath,$iSurveyID,$sCreateMissingAttributeField

/**
* @param string $sFullFilePath
* @return mixed
*/
function XMLImportResponses($sFullFilePath,$iSurveyID,$aFieldReMap=array())
{
Yii::app()->loadHelper('database');

$survey = Survey::model()->findByPk($iSurveyID);

switchMSSQLIdentityInsert('survey_'.$iSurveyID, true);
$results['responses']=0;
$oXMLReader = new XMLReader();
$oXMLReader->open($sFullFilePath);
$DestinationFields = Yii::app()->db->schema->getTable('{{survey_'.$iSurveyID.'}}')->getColumnNames();
$DestinationFields = Yii::app()->db->schema->getTable($survey->responsesTableName)->getColumnNames();
while ($oXMLReader->read()) {
if ($oXMLReader->name === 'LimeSurveyDocType' && $oXMLReader->nodeType == XMLReader::ELEMENT)
{
Expand Down Expand Up @@ -1710,7 +1709,7 @@ function XMLImportResponses($sFullFilePath,$iSurveyID,$aFieldReMap=array())
switchMSSQLIdentityInsert('survey_'.$iSurveyID,false);
if (Yii::app()->db->getDriverName() == 'pgsql')
{
try {Yii::app()->db->createCommand("SELECT pg_catalog.setval(pg_get_serial_sequence('{{survey_".$iSurveyID."}}', 'id'), (SELECT MAX(id) FROM {{survey_".$iSurveyID."}}))")->execute();} catch(Exception $oException){};
try {Yii::app()->db->createCommand("SELECT pg_catalog.setval(pg_get_serial_sequence('".$survey->responsesTableName."', 'id'), (SELECT MAX(id) FROM ".$survey->responsesTableName."))")->execute();} catch(Exception $oException){};
}
return $results;
}
Expand Down
2 changes: 1 addition & 1 deletion application/helpers/common_helper.php
Expand Up @@ -980,7 +980,7 @@ function getSurveyInfo($surveyid, $languagecode='')
$thissurvey['welcome']=$thissurvey['surveyls_welcometext'];
$thissurvey['templatedir']=$thissurvey['template'];
$thissurvey['adminname']=$thissurvey['admin'];
$thissurvey['tablename']='{{survey_'.$thissurvey['sid'] . '}}';
$thissurvey['tablename']=$oSurvey->responsesTableName;
$thissurvey['urldescrip']=$thissurvey['surveyls_urldescription'];
$thissurvey['url']=$thissurvey['surveyls_url'];
$thissurvey['expiry']=$thissurvey['expires'];
Expand Down

0 comments on commit c9f9501

Please sign in to comment.