/** * Show dialogs and create a new tokens table */ function _newtokentable($iSurveyId) { $clang = $this->getController()->lang; $aSurveyInfo = getSurveyInfo($iSurveyId); if (!Permission::model()->hasSurveyPermission($iSurveyId, 'surveysettings', 'update') && !Permission::model()->hasSurveyPermission($iSurveyId, 'tokens', 'create')) { Yii::app()->session['flashmessage'] = $clang->gT("Tokens have not been initialised for this survey."); $this->getController()->redirect(array("/admin/survey/sa/view/surveyid/{$iSurveyId}")); } $bTokenExists = tableExists('{{tokens_' . $iSurveyId . '}}'); if ($bTokenExists) { Yii::app()->session['flashmessage'] = $clang->gT("Tokens already exist for this survey."); $this->getController()->redirect(array("/admin/survey/sa/view/surveyid/{$iSurveyId}")); } // The user have rigth to create token, then don't test right after Yii::import('application.helpers.admin.token_helper', true); if (Yii::app()->request->getQuery('createtable') == "Y") { createTokenTable($iSurveyId); LimeExpressionManager::SetDirtyFlag(); // LimeExpressionManager needs to know about the new token table $this->_renderWrappedTemplate('token', array('message' => array('title' => $clang->gT("Token control"), 'message' => $clang->gT("A token table has been created for this survey.") . " (\"" . Yii::app()->db->tablePrefix . "tokens_{$iSurveyId}\")<br /><br />\n" . "<input type='submit' value='" . $clang->gT("Continue") . "' onclick=\"window.open('" . $this->getController()->createUrl("admin/tokens/sa/index/surveyid/{$iSurveyId}") . "', '_top')\" />\n"))); } elseif (returnGlobal('restoretable') == "Y" && Yii::app()->request->getPost('oldtable')) { //Rebuild attributedescription value for the surveys table $table = Yii::app()->db->schema->getTable(Yii::app()->request->getPost('oldtable')); $fields = array_filter(array_keys($table->columns), 'filterForAttributes'); $fieldcontents = $aSurveyInfo['attributedescriptions']; if (!is_array($fieldcontents)) { $fieldcontents = array(); } foreach ($fields as $fieldname) { $name = $fieldname; if ($fieldname[10] == 'c') { //This belongs to a cpdb attribute $cpdbattid = substr($fieldname, 15); $data = ParticipantAttributeName::model()->getAttributeName($cpdbattid, Yii::app()->session['adminlang']); $name = $data['attribute_name']; } if (!isset($fieldcontents[$fieldname])) { $fieldcontents[$fieldname] = array('description' => $name, 'mandatory' => 'N', 'show_register' => 'N'); } } Survey::model()->updateByPk($iSurveyId, array('attributedescriptions' => serialize($fieldcontents))); Yii::app()->db->createCommand()->renameTable(Yii::app()->request->getPost('oldtable'), Yii::app()->db->tablePrefix . "tokens_" . intval($iSurveyId)); Yii::app()->db->schema->getTable(Yii::app()->db->tablePrefix . "tokens_" . intval($iSurveyId), true); // Refresh schema cache just in case the table existed in the past //Check that the tokens table has the required fields TokenDynamic::model($iSurveyId)->checkColumns(); //Add any survey_links from the renamed table SurveyLink::model()->rebuildLinksFromTokenTable($iSurveyId); $this->_renderWrappedTemplate('token', array('message' => array('title' => $clang->gT("Import old tokens"), 'message' => $clang->gT("A token table has been created for this survey and the old tokens were imported.") . " (\"" . Yii::app()->db->tablePrefix . "tokens_{$iSurveyId}" . "\")<br /><br />\n" . "<input type='submit' value='" . $clang->gT("Continue") . "' onclick=\"window.open('" . $this->getController()->createUrl("admin/tokens/sa/index/surveyid/{$iSurveyId}") . "', '_top')\" />\n"))); LimeExpressionManager::SetDirtyFlag(); // so that knows that token tables have changed } else { $this->getController()->loadHelper('database'); $result = Yii::app()->db->createCommand(dbSelectTablesLike("{{old_tokens_" . intval($iSurveyId) . "_%}}"))->queryAll(); $tcount = count($result); if ($tcount > 0) { foreach ($result as $rows) { $oldlist[] = reset($rows); } $aData['oldlist'] = $oldlist; } $thissurvey = getSurveyInfo($iSurveyId); $aData['thissurvey'] = $thissurvey; $aData['surveyid'] = $iSurveyId; $aData['tcount'] = $tcount; $aData['databasetype'] = Yii::app()->db->getDriverName(); $this->_renderWrappedTemplate('token', 'tokenwarning', $aData); } }
/** * This function deletes the participant from the participants table, * references in the survey_links table (but not in matching tokens tables) * and then all the participants attributes. * @param $rows Participants ID separated by comma * @return void **/ function deleteParticipants($rows, $bFilter = true) { // Converting the comma separated IDs to an array and assign chunks of 100 entries to have a reasonable query size $aParticipantsIDChunks = array_chunk(explode(",", $rows), 100); foreach ($aParticipantsIDChunks as $aParticipantsIDs) { if ($bFilter) { $aParticipantsIDs = $this->filterParticipantIDs($aParticipantsIDs); } foreach ($aParticipantsIDs as $aID) { $oParticipant = Participant::model()->findByPk($aID); if ($oParticipant) { $oParticipant->delete(); } } Yii::app()->db->createCommand()->delete(Participant::model()->tableName(), array('in', 'participant_id', $aParticipantsIDs)); // Delete survey links Yii::app()->db->createCommand()->delete(SurveyLink::model()->tableName(), array('in', 'participant_id', $aParticipantsIDs)); // Delete participant attributes Yii::app()->db->createCommand()->delete(ParticipantAttribute::model()->tableName(), array('in', 'participant_id', $aParticipantsIDs)); } }
/** * Function responsible to deactivate a survey. * * @access public * @param int $iSurveyID * @return void */ public function deactivate($iSurveyID = null) { $iSurveyID = Yii::app()->request->getPost('sid', $iSurveyID); $iSurveyID = sanitize_int($iSurveyID); $date = date('YmdHis'); //'His' adds 24hours+minutes to name to allow multiple deactiviations in a day if (empty($_POST['ok'])) { if (!tableExists('survey_' . $iSurveyID)) { $_SESSION['flashmessage'] = gT("Error: Response table does not exist. Survey cannot be deactivated."); $this->getController()->redirect($this->getController()->createUrl("admin/survey/sa/view/surveyid/{$iSurveyID}")); } $aData['surveyid'] = $iSurveyID; $aData['date'] = $date; $aData['dbprefix'] = Yii::app()->db->tablePrefix; $aData['step1'] = true; } else { //See if there is a tokens table for this survey if (tableExists("{{tokens_{$iSurveyID}}}")) { $toldtable = Yii::app()->db->tablePrefix . "tokens_{$iSurveyID}"; $tnewtable = Yii::app()->db->tablePrefix . "old_tokens_{$iSurveyID}_{$date}"; if (Yii::app()->db->getDriverName() == 'pgsql') { $tidDefault = Yii::app()->db->createCommand("SELECT pg_attrdef.adsrc FROM pg_attribute JOIN pg_class ON (pg_attribute.attrelid=pg_class.oid) JOIN pg_attrdef ON(pg_attribute.attrelid=pg_attrdef.adrelid AND pg_attribute.attnum=pg_attrdef.adnum) WHERE pg_class.relname='{$toldtable}' and pg_attribute.attname='tid'")->queryScalar(); if (preg_match("/nextval\\('(tokens_\\d+_tid_seq\\d*)'::regclass\\)/", $tidDefault, $matches)) { $oldSeq = $matches[1]; $deactivateresult = Yii::app()->db->createCommand()->renameTable($oldSeq, $tnewtable . '_tid_seq'); $setsequence = "ALTER TABLE " . Yii::app()->db->quoteTableName($toldtable) . " ALTER COLUMN tid SET DEFAULT nextval('{$tnewtable}_tid_seq'::regclass);"; $deactivateresult = Yii::app()->db->createCommand($setsequence)->query(); } } $tdeactivateresult = Yii::app()->db->createCommand()->renameTable($toldtable, $tnewtable); $aData['tnewtable'] = $tnewtable; $aData['toldtable'] = $toldtable; } //Remove any survey_links to the CPDB SurveyLink::model()->deleteLinksBySurvey($iSurveyID); // IF there are any records in the saved_control table related to this survey, they have to be deleted $result = SavedControl::model()->deleteSomeRecords(array('sid' => $iSurveyID)); //Yii::app()->db->createCommand($query)->query(); $sOldSurveyTableName = Yii::app()->db->tablePrefix . "survey_{$iSurveyID}"; $sNewSurveyTableName = Yii::app()->db->tablePrefix . "old_survey_{$iSurveyID}_{$date}"; $aData['sNewSurveyTableName'] = $sNewSurveyTableName; //Update the autonumber_start in the survey properties $new_autonumber_start = 0; $query = "SELECT id FROM " . Yii::app()->db->quoteTableName($sOldSurveyTableName) . " ORDER BY id desc"; $sLastID = Yii::app()->db->createCommand($query)->limit(1)->queryScalar(); $new_autonumber_start = $sLastID + 1; $insertdata = array('autonumber_start' => $new_autonumber_start); $survey = Survey::model()->findByAttributes(array('sid' => $iSurveyID)); $survey->autonumber_start = $new_autonumber_start; $survey->save(); if (Yii::app()->db->getDriverName() == 'pgsql') { $idDefault = Yii::app()->db->createCommand("SELECT pg_attrdef.adsrc FROM pg_attribute JOIN pg_class ON (pg_attribute.attrelid=pg_class.oid) JOIN pg_attrdef ON(pg_attribute.attrelid=pg_attrdef.adrelid AND pg_attribute.attnum=pg_attrdef.adnum) WHERE pg_class.relname='{$sOldSurveyTableName}' and pg_attribute.attname='id'")->queryScalar(); if (preg_match("/nextval\\('(survey_\\d+_id_seq\\d*)'::regclass\\)/", $idDefault, $matches)) { $oldSeq = $matches[1]; $deactivateresult = Yii::app()->db->createCommand()->renameTable($oldSeq, $sNewSurveyTableName . '_id_seq'); $setsequence = "ALTER TABLE " . Yii::app()->db->quoteTableName($sOldSurveyTableName) . " ALTER COLUMN id SET DEFAULT nextval('{{{$sNewSurveyTableName}}}_id_seq'::regclass);"; $deactivateresult = Yii::app()->db->createCommand($setsequence)->query(); } } $deactivateresult = Yii::app()->db->createCommand()->renameTable($sOldSurveyTableName, $sNewSurveyTableName); $insertdata = array('active' => 'N'); $survey->active = 'N'; $survey->save(); $prow = Survey::model()->find('sid = :sid', array(':sid' => $iSurveyID)); if ($prow->savetimings == "Y") { $sOldTimingsTableName = Yii::app()->db->tablePrefix . "survey_{$iSurveyID}_timings"; $sNewTimingsTableName = Yii::app()->db->tablePrefix . "old_survey_{$iSurveyID}_timings_{$date}"; $deactivateresult2 = Yii::app()->db->createCommand()->renameTable($sOldTimingsTableName, $sNewTimingsTableName); $deactivateresult = $deactivateresult && $deactivateresult2; $aData['sNewTimingsTableName'] = $sNewTimingsTableName; } $aData['surveyid'] = $iSurveyID; Yii::app()->db->schema->refresh(); } $this->_renderWrappedTemplate('survey', 'deactivateSurvey_view', $aData); }
/** * Marks a tokens as completed and sends a confirmation email to the participiant. * If $quotaexit is set to true then the user exited the survey due to a quota * restriction and the according token is only marked as 'Q' * * @param mixed $quotaexit */ function submittokens($quotaexit = false) { $surveyid = Yii::app()->getConfig('surveyID'); if (isset($_SESSION['survey_' . $surveyid]['s_lang'])) { $thissurvey = getSurveyInfo($surveyid, $_SESSION['survey_' . $surveyid]['s_lang']); } else { $thissurvey = getSurveyInfo($surveyid); } $clienttoken = $_SESSION['survey_' . $surveyid]['token']; $sitename = Yii::app()->getConfig("sitename"); $emailcharset = Yii::app()->getConfig("emailcharset"); // Shift the date due to global timeadjust setting $today = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i", Yii::app()->getConfig("timeadjust")); // check how many uses the token has left $token = Token::model($surveyid)->findByAttributes(array('token' => $clienttoken)); if ($quotaexit == true) { $token->completed = 'Q'; $token->usesleft--; } else { if ($token->usesleft <= 1) { // Finish the token if (isTokenCompletedDatestamped($thissurvey)) { $token->completed = $today; } else { $token->completed = 'Y'; } if (isset($token->participant_id)) { $slquery = SurveyLink::model()->find('participant_id = :pid AND survey_id = :sid AND token_id = :tid', array(':pid' => $token->participant_id, ':sid' => $surveyid, ':tid' => $token->tid)); if ($slquery) { if (isTokenCompletedDatestamped($thissurvey)) { $slquery->date_completed = $today; } else { // Update the survey_links table if necessary, to protect anonymity, use the date_created field date $slquery->date_completed = $slquery->date_created; } $slquery->save(); } } } $token->usesleft--; } $token->save(); if ($quotaexit == false) { if ($token && trim(strip_tags($thissurvey['email_confirm'])) != "" && $thissurvey['sendconfirmation'] == "Y") { // if($token->completed == "Y" || $token->completed == $today) // { $from = "{$thissurvey['adminname']} <{$thissurvey['adminemail']}>"; $subject = $thissurvey['email_confirm_subj']; $aReplacementVars = array(); $aReplacementVars["ADMINNAME"] = $thissurvey['admin']; $aReplacementVars["ADMINEMAIL"] = $thissurvey['adminemail']; $aReplacementVars['ADMINEMAIL'] = $thissurvey['adminemail']; //Fill with token info, because user can have his information with anonimity control $aReplacementVars["FIRSTNAME"] = $token->firstname; $aReplacementVars["LASTNAME"] = $token->lastname; $aReplacementVars["TOKEN"] = $token->token; // added survey url in replacement vars $surveylink = Yii::app()->createAbsoluteUrl("/survey/index/sid/{$surveyid}", array('lang' => $_SESSION['survey_' . $surveyid]['s_lang'], 'token' => $token->token)); $aReplacementVars['SURVEYURL'] = $surveylink; $attrfieldnames = getAttributeFieldNames($surveyid); foreach ($attrfieldnames as $attr_name) { $aReplacementVars[strtoupper($attr_name)] = $token->{$attr_name}; } $dateformatdatat = getDateFormatData($thissurvey['surveyls_dateformat']); $numberformatdatat = getRadixPointData($thissurvey['surveyls_numberformat']); $redata = array('thissurvey' => $thissurvey); $subject = templatereplace($subject, $aReplacementVars, $redata, '', false, null, array(), true); $subject = html_entity_decode($subject, ENT_QUOTES, $emailcharset); if (getEmailFormat($surveyid) == 'html') { $ishtml = true; } else { $ishtml = false; } $message = $thissurvey['email_confirm']; //$message=ReplaceFields($message, $fieldsarray, true); $message = templatereplace($message, $aReplacementVars, $redata, '', false, null, array(), true); if (!$ishtml) { $message = strip_tags(breakToNewline(html_entity_decode($message, ENT_QUOTES, $emailcharset))); } else { $message = html_entity_decode($message, ENT_QUOTES, $emailcharset); } //Only send confirmation email if there is a valid email address $sToAddress = validateEmailAddresses($token->email); if ($sToAddress) { $aAttachments = unserialize($thissurvey['attachments']); $aRelevantAttachments = array(); /* * Iterate through attachments and check them for relevance. */ if (isset($aAttachments['confirmation'])) { foreach ($aAttachments['confirmation'] as $aAttachment) { $relevance = $aAttachment['relevance']; // If the attachment is relevant it will be added to the mail. if (LimeExpressionManager::ProcessRelevance($relevance) && file_exists($aAttachment['url'])) { $aRelevantAttachments[] = $aAttachment['url']; } } } SendEmailMessage($message, $subject, $sToAddress, $from, $sitename, $ishtml, null, $aRelevantAttachments); } // } else { // Leave it to send optional confirmation at closed token // } } } }
/** * Receives an ajax call containing the participant id in the fourth segment of the url * Supplies list of survey links - surveys of which this participant is on the tokens table * URL: [localurl]/limesurvey/admin/participants/getSurveyInfo_json/pid/[participant_id] * RETURNS: json data containing linked survey information (Survey name, survey id, token_id and date_added) */ function getSurveyInfo_json() { $participantid = Yii::app()->request->getQuery('pid'); $records = SurveyLink::model()->findAllByAttributes(array('participant_id' => $participantid)); $aData = new stdClass(); $aData->page = 1; $aData->records = count($records); $aData->total = ceil($aData->records / 10); $i = 0; foreach ($records as $row) { $oSurvey = Survey::model()->with(array('languagesettings' => array('condition' => 'surveyls_language=language')))->findByAttributes(array('sid' => $row['survey_id'])); foreach ($oSurvey->languagesettings as $oLanguageSetting) { $surveyname = $oLanguageSetting->surveyls_title; } $surveylink = ""; /* Check permissions of each survey before creating a link */ if (!Permission::model()->hasSurveyPermission($row['survey_id'], 'tokens', 'read')) { $surveylink = $row['survey_id']; } else { $surveylink = '<a href=' . Yii::app()->getController()->createUrl("/admin/tokens/sa/browse/surveyid/{$row['survey_id']}") . '>' . $row['survey_id'] . '</a>'; } $aData->rows[$i]['cell'] = array($surveyname, $surveylink, $row['token_id'], $row['date_created'], $row['date_invited'], $row['date_completed']); $i++; } echo ls_json_encode($aData); }
/** * Deletes a survey and all its data * * @access public * @param int $iSurveyID * @param bool @recursive * @return void */ public function deleteSurvey($iSurveyID, $recursive = true) { Survey::model()->deleteByPk($iSurveyID); if ($recursive == true) { if (tableExists("{{survey_" . intval($iSurveyID) . "}}")) { Yii::app()->db->createCommand()->dropTable("{{survey_" . intval($iSurveyID) . "}}"); } if (tableExists("{{survey_" . intval($iSurveyID) . "_timings}}")) { Yii::app()->db->createCommand()->dropTable("{{survey_" . intval($iSurveyID) . "_timings}}"); } if (tableExists("{{tokens_" . intval($iSurveyID) . "}}")) { Yii::app()->db->createCommand()->dropTable("{{tokens_" . intval($iSurveyID) . "}}"); } $oResult = Question::model()->findAllByAttributes(array('sid' => $iSurveyID)); foreach ($oResult as $aRow) { Answer::model()->deleteAllByAttributes(array('qid' => $aRow['qid'])); Condition::model()->deleteAllByAttributes(array('qid' => $aRow['qid'])); QuestionAttribute::model()->deleteAllByAttributes(array('qid' => $aRow['qid'])); DefaultValue::model()->deleteAllByAttributes(array('qid' => $aRow['qid'])); } Question::model()->deleteAllByAttributes(array('sid' => $iSurveyID)); Assessment::model()->deleteAllByAttributes(array('sid' => $iSurveyID)); QuestionGroup::model()->deleteAllByAttributes(array('sid' => $iSurveyID)); SurveyLanguageSetting::model()->deleteAllByAttributes(array('surveyls_survey_id' => $iSurveyID)); Permission::model()->deleteAllByAttributes(array('entity_id' => $iSurveyID, 'entity' => 'survey')); SavedControl::model()->deleteAllByAttributes(array('sid' => $iSurveyID)); SurveyURLParameter::model()->deleteAllByAttributes(array('sid' => $iSurveyID)); //Remove any survey_links to the CPDB SurveyLink::model()->deleteLinksBySurvey($iSurveyID); Quota::model()->deleteQuota(array('sid' => $iSurveyID), true); } }
/** * Deletes a survey and all its data * * @access public * @param int $iSurveyID * @param bool @recursive * @return void */ public function deleteSurvey($iSurveyID, $recursive = true) { Survey::model()->deleteByPk($iSurveyID); if ($recursive == true) { if (tableExists("{{survey_" . intval($iSurveyID) . "}}")) { Yii::app()->db->createCommand()->dropTable("{{survey_" . intval($iSurveyID) . "}}"); } if (tableExists("{{survey_" . intval($iSurveyID) . "_timings}}")) { Yii::app()->db->createCommand()->dropTable("{{survey_" . intval($iSurveyID) . "_timings}}"); } if (tableExists("{{tokens_" . intval($iSurveyID) . "}}")) { Yii::app()->db->createCommand()->dropTable("{{tokens_" . intval($iSurveyID) . "}}"); } /* Remove User/global settings part : need Question and QuestionGroup*/ // Settings specific for this survey $oCriteria = new CDbCriteria(); $oCriteria->compare('stg_name', 'last_%', true, 'AND', false); $oCriteria->compare('stg_value', $iSurveyID, false, 'AND'); SettingGlobal::model()->deleteAll($oCriteria); // Settings specific for this survey, 2nd part $oCriteria = new CDbCriteria(); $oCriteria->compare('stg_name', 'last_%' . $iSurveyID . '%', 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' => $iSurveyID))), 'gid', 'gid'); $oCriteria = new CDbCriteria(); $oCriteria->compare('stg_name', 'last_question_gid_%', true, 'AND', false); if (Yii::app()->db->getDriverName() == 'pgsql') { $oCriteria->addInCondition('CAST(stg_value as ' . App()->db->schema->getColumnType("integer") . ')', $aGroupId); } else { $oCriteria->addInCondition('stg_value', $aGroupId); } 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' => $iSurveyID))), 'qid', 'qid'); $oCriteria = new CDbCriteria(); $oCriteria->compare('stg_name', 'last_question_%', true, 'OR', false); if (Yii::app()->db->getDriverName() == 'pgsql') { $oCriteria->addInCondition('CAST(stg_value as ' . App()->db->schema->getColumnType("integer") . ')', $aQuestionId); } else { $oCriteria->addInCondition('stg_value', $aQuestionId); } SettingGlobal::model()->deleteAll($oCriteria); $oResult = Question::model()->findAllByAttributes(array('sid' => $iSurveyID)); foreach ($oResult as $aRow) { Answer::model()->deleteAllByAttributes(array('qid' => $aRow['qid'])); Condition::model()->deleteAllByAttributes(array('qid' => $aRow['qid'])); QuestionAttribute::model()->deleteAllByAttributes(array('qid' => $aRow['qid'])); DefaultValue::model()->deleteAllByAttributes(array('qid' => $aRow['qid'])); } Question::model()->deleteAllByAttributes(array('sid' => $iSurveyID)); Assessment::model()->deleteAllByAttributes(array('sid' => $iSurveyID)); QuestionGroup::model()->deleteAllByAttributes(array('sid' => $iSurveyID)); SurveyLanguageSetting::model()->deleteAllByAttributes(array('surveyls_survey_id' => $iSurveyID)); Permission::model()->deleteAllByAttributes(array('entity_id' => $iSurveyID, 'entity' => 'survey')); SavedControl::model()->deleteAllByAttributes(array('sid' => $iSurveyID)); SurveyURLParameter::model()->deleteAllByAttributes(array('sid' => $iSurveyID)); //Remove any survey_links to the CPDB SurveyLink::model()->deleteLinksBySurvey($iSurveyID); Quota::model()->deleteQuota(array('sid' => $iSurveyID), true); } }
function deleteLinksBySurvey($surveyId) { $query = "DELETE FROM " . SurveyLink::tableName() . " WHERE survey_id = :survey_id"; return Yii::app()->db->createCommand($query)->bindParam(":survey_id", $surveyId)->query(); }