function deleteQuota($condition = false, $recursive = true)
 {
     if ($recursive == true) {
         $oResult = Quota::model()->findAllByAttributes($condition);
         foreach ($oResult as $aRow) {
             Quota_languagesettings::model()->deleteAllByAttributes(array('quotals_quota_id' => $aRow['id']));
             Quota_members::model()->deleteAllByAttributes(array('quota_id' => $aRow['id']));
         }
     }
     Quota::model()->deleteAllByAttributes($condition);
 }
Beispiel #2
0
/**
* This function imports a LimeSurvey .lss survey XML file
*
* @param mixed $sFullFilepath  The full filepath of the uploaded file
*/
function XMLImportSurvey($sFullFilepath, $sXMLdata = NULL, $sNewSurveyName = NULL, $iDesiredSurveyId = NULL, $bTranslateInsertansTags = true)
{
    Yii::app()->loadHelper('database');
    $clang = Yii::app()->lang;
    $aGIDReplacements = array();
    if ($sXMLdata == NULL) {
        $xml = simplexml_load_file($sFullFilepath);
    } else {
        $xml = simplexml_load_string($sXMLdata);
    }
    if ($xml->LimeSurveyDocType != 'Survey') {
        $results['error'] = $clang->gT("This is not a valid LimeSurvey survey structure XML file.");
        return $results;
    }
    $iDBVersion = (int) $xml->DBVersion;
    $aQIDReplacements = array();
    $aQuotaReplacements = array();
    $results['defaultvalues'] = 0;
    $results['answers'] = 0;
    $results['surveys'] = 0;
    $results['questions'] = 0;
    $results['subquestions'] = 0;
    $results['question_attributes'] = 0;
    $results['groups'] = 0;
    $results['assessments'] = 0;
    $results['quota'] = 0;
    $results['quotals'] = 0;
    $results['quotamembers'] = 0;
    $results['survey_url_parameters'] = 0;
    $results['importwarnings'] = array();
    $aLanguagesSupported = array();
    foreach ($xml->languages->language as $language) {
        $aLanguagesSupported[] = (string) $language;
    }
    $results['languages'] = count($aLanguagesSupported);
    // Import surveys table ====================================================
    foreach ($xml->surveys->rows->row as $row) {
        $insertdata = array();
        foreach ($row as $key => $value) {
            $insertdata[(string) $key] = (string) $value;
        }
        $iOldSID = $results['oldsid'] = $insertdata['sid'];
        if ($iDesiredSurveyId != NULL) {
            $insertdata['wishSID'] = GetNewSurveyID($iDesiredSurveyId);
        }
        if ($iDBVersion <= 143) {
            if (isset($insertdata['private'])) {
                $insertdata['anonymized'] = $insertdata['private'];
            }
            unset($insertdata['private']);
            unset($insertdata['notification']);
        }
        unset($insertdata['expires']);
        unset($insertdata['startdate']);
        //Make sure it is not set active
        $insertdata['active'] = 'N';
        //Set current user to be the owner
        $insertdata['owner_id'] = Yii::app()->session['loginID'];
        if (isset($insertdata['bouncetime']) && $insertdata['bouncetime'] == '') {
            $insertdata['bouncetime'] = NULL;
        }
        if (isset($insertdata['showXquestions'])) {
            $insertdata['showxquestions'] = $insertdata['showXquestions'];
            unset($insertdata['showXquestions']);
        }
        $iNewSID = $results['newsid'] = Survey::model()->insertNewSurvey($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data [1]<br />");
        $results['surveys']++;
    }
    // Import survey languagesettings table ===================================================================================
    foreach ($xml->surveys_languagesettings->rows->row as $row) {
        $insertdata = array();
        foreach ($row as $key => $value) {
            $insertdata[(string) $key] = (string) $value;
        }
        if (!in_array($insertdata['surveyls_language'], $aLanguagesSupported)) {
            continue;
        }
        $insertdata['surveyls_survey_id'] = $iNewSID;
        if ($bTranslateInsertansTags) {
            if ($sNewSurveyName == NULL) {
                $insertdata['surveyls_title'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['surveyls_title']);
            } else {
                $insertdata['surveyls_title'] = translateLinks('survey', $iOldSID, $iNewSID, $sNewSurveyName);
            }
            if (isset($insertdata['surveyls_description'])) {
                $insertdata['surveyls_description'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['surveyls_description']);
            }
            if (isset($insertdata['surveyls_welcometext'])) {
                $insertdata['surveyls_welcometext'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['surveyls_welcometext']);
            }
            if (isset($insertdata['surveyls_urldescription'])) {
                $insertdata['surveyls_urldescription'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['surveyls_urldescription']);
            }
            if (isset($insertdata['surveyls_email_invite'])) {
                $insertdata['surveyls_email_invite'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['surveyls_email_invite']);
            }
            if (isset($insertdata['surveyls_email_remind'])) {
                $insertdata['surveyls_email_remind'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['surveyls_email_remind']);
            }
            if (isset($insertdata['surveyls_email_register'])) {
                $insertdata['surveyls_email_register'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['surveyls_email_register']);
            }
            if (isset($insertdata['surveyls_email_confirm'])) {
                $insertdata['surveyls_email_confirm'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['surveyls_email_confirm']);
            }
        }
        $result = Surveys_languagesettings::model()->insertNewSurvey($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data [2]<br />");
    }
    // Import groups table ===================================================================================
    if (isset($xml->groups->rows->row)) {
        foreach ($xml->groups->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            if (!in_array($insertdata['language'], $aLanguagesSupported)) {
                continue;
            }
            $iOldSID = $insertdata['sid'];
            $insertdata['sid'] = $iNewSID;
            $oldgid = $insertdata['gid'];
            unset($insertdata['gid']);
            // save the old qid
            // now translate any links
            if ($bTranslateInsertansTags) {
                $insertdata['group_name'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['group_name']);
                $insertdata['description'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['description']);
            }
            // Insert the new group
            if (isset($aGIDReplacements[$oldgid])) {
                switchMSSQLIdentityInsert('groups', true);
                $insertdata['gid'] = $aGIDReplacements[$oldgid];
            }
            $newgid = Groups::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data [3]<br />");
            $results['groups']++;
            if (!isset($aGIDReplacements[$oldgid])) {
                $aGIDReplacements[$oldgid] = $newgid;
                // add old and new qid to the mapping array
            } else {
                switchMSSQLIdentityInsert('groups', false);
            }
        }
    }
    // Import questions table ===================================================================================
    // We have to run the question table data two times - first to find all main questions
    // then for subquestions (because we need to determine the new qids for the main questions first)
    if (isset($xml->questions)) {
        foreach ($xml->questions->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            if (!in_array($insertdata['language'], $aLanguagesSupported) || $insertdata['gid'] == 0) {
                continue;
            }
            $iOldSID = $insertdata['sid'];
            $insertdata['sid'] = $iNewSID;
            $insertdata['gid'] = $aGIDReplacements[$insertdata['gid']];
            $oldqid = $insertdata['qid'];
            unset($insertdata['qid']);
            // save the old qid
            // now translate any links
            if ($bTranslateInsertansTags) {
                $insertdata['question'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['question']);
                $insertdata['help'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['help']);
            }
            // Insert the new question
            if (isset($aQIDReplacements[$oldqid])) {
                $insertdata['qid'] = $aQIDReplacements[$oldqid];
                switchMSSQLIdentityInsert('questions', true);
            }
            if ($insertdata) {
                XSSFilterArray($insertdata);
            }
            $newqid = Questions::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data [4]<br />");
            if (!isset($aQIDReplacements[$oldqid])) {
                $aQIDReplacements[$oldqid] = $newqid;
                $results['questions']++;
            } else {
                switchMSSQLIdentityInsert('questions', false);
            }
        }
    }
    // Import subquestions -------------------------------------------------------
    if (isset($xml->subquestions)) {
        foreach ($xml->subquestions->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            if (!in_array($insertdata['language'], $aLanguagesSupported) || $insertdata['gid'] == 0) {
                continue;
            }
            if (!isset($insertdata['mandatory']) || trim($insertdata['mandatory']) == '') {
                $insertdata['mandatory'] = 'N';
            }
            $insertdata['sid'] = $iNewSID;
            $insertdata['gid'] = $aGIDReplacements[(int) $insertdata['gid']];
            $oldsqid = (int) $insertdata['qid'];
            unset($insertdata['qid']);
            // save the old qid
            $insertdata['parent_qid'] = $aQIDReplacements[(int) $insertdata['parent_qid']];
            // remap the parent_qid
            // now translate any links
            if ($bTranslateInsertansTags) {
                $insertdata['question'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['question']);
                if (isset($insertdata['help'])) {
                    $insertdata['help'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['help']);
                }
            }
            if (isset($aQIDReplacements[$oldsqid])) {
                $insertdata['qid'] = $aQIDReplacements[$oldsqid];
                switchMSSQLIdentityInsert('questions', true);
            }
            if ($insertdata) {
                XSSFilterArray($insertdata);
            }
            $newsqid = Questions::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data [5]<br />");
            if (!isset($insertdata['qid'])) {
                $aQIDReplacements[$oldsqid] = $newsqid;
                // add old and new qid to the mapping array
            } else {
                switchMSSQLIdentityInsert('questions', false);
            }
            $results['subquestions']++;
        }
    }
    // Import answers ------------------------------------------------------------
    if (isset($xml->answers)) {
        foreach ($xml->answers->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            if (!in_array($insertdata['language'], $aLanguagesSupported) || !isset($aQIDReplacements[(int) $insertdata['qid']])) {
                continue;
            }
            $insertdata['qid'] = $aQIDReplacements[(int) $insertdata['qid']];
            // remap the parent_qid
            // now translate any links
            if ($bTranslateInsertansTags) {
                $insertdata['answer'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['answer']);
            }
            if ($insertdata) {
                XSSFilterArray($insertdata);
            }
            $result = Answers::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data<br />");
            $results['answers']++;
        }
    }
    // Import questionattributes -------------------------------------------------
    if (isset($xml->question_attributes)) {
        $aAllAttributes = questionAttributes(true);
        foreach ($xml->question_attributes->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            unset($insertdata['qaid']);
            if (!isset($aQIDReplacements[(int) $insertdata['qid']])) {
                continue;
            }
            $insertdata['qid'] = $aQIDReplacements[(int) $insertdata['qid']];
            // remap the qid
            if ($iDBVersion < 148 && isset($aAllAttributes[$insertdata['attribute']]['i18n']) && $aAllAttributes[$insertdata['attribute']]['i18n']) {
                foreach ($aLanguagesSupported as $sLanguage) {
                    $insertdata['language'] = $sLanguage;
                    if ($insertdata) {
                        XSSFilterArray($insertdata);
                    }
                    $result = Question_attributes::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data<br />");
                }
            } else {
                $result = Question_attributes::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data<br />");
            }
            $results['question_attributes']++;
        }
    }
    // Import defaultvalues ------------------------------------------------------
    if (isset($xml->defaultvalues)) {
        $results['defaultvalues'] = 0;
        foreach ($xml->defaultvalues->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            $insertdata['qid'] = $aQIDReplacements[(int) $insertdata['qid']];
            // remap the qid
            if (isset($aQIDReplacements[(int) $insertdata['sqid']])) {
                $insertdata['sqid'] = $aQIDReplacements[(int) $insertdata['sqid']];
            }
            // remap the subquestion id
            if ($insertdata) {
                XSSFilterArray($insertdata);
            }
            // now translate any links
            $result = Defaultvalues::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data<br />");
            $results['defaultvalues']++;
        }
    }
    $aOldNewFieldmap = reverseTranslateFieldNames($iOldSID, $iNewSID, $aGIDReplacements, $aQIDReplacements);
    // Import conditions ---------------------------------------------------------
    if (isset($xml->conditions)) {
        $results['conditions'] = 0;
        foreach ($xml->conditions->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            // replace the qid for the new one (if there is no new qid in the $aQIDReplacements array it mean that this condition is orphan -> error, skip this record)
            if (isset($aQIDReplacements[$insertdata['qid']])) {
                $insertdata['qid'] = $aQIDReplacements[$insertdata['qid']];
                // remap the qid
            } else {
                continue;
            }
            // a problem with this answer record -> don't consider
            if ($insertdata['cqid'] != 0) {
                if (isset($aQIDReplacements[$insertdata['cqid']])) {
                    $oldcqid = $insertdata['cqid'];
                    //Save for cfield transformation
                    $insertdata['cqid'] = $aQIDReplacements[$insertdata['cqid']];
                    // remap the qid
                } else {
                    continue;
                }
                // a problem with this answer record -> don't consider
                list($oldcsid, $oldcgid, $oldqidanscode) = explode("X", $insertdata["cfieldname"], 3);
                // replace the gid for the new one in the cfieldname(if there is no new gid in the $aGIDReplacements array it means that this condition is orphan -> error, skip this record)
                if (!isset($aGIDReplacements[$oldcgid])) {
                    continue;
                }
            }
            unset($insertdata["cid"]);
            // recreate the cfieldname with the new IDs
            if ($insertdata['cqid'] != 0) {
                if (preg_match("/^\\+/", $oldcsid)) {
                    $newcfieldname = '+' . $iNewSID . "X" . $aGIDReplacements[$oldcgid] . "X" . $insertdata["cqid"] . substr($oldqidanscode, strlen($oldcqid));
                } else {
                    $newcfieldname = $iNewSID . "X" . $aGIDReplacements[$oldcgid] . "X" . $insertdata["cqid"] . substr($oldqidanscode, strlen($oldcqid));
                }
            } else {
                // The cfieldname is a not a previous question cfield but a {XXXX} replacement field
                $newcfieldname = $insertdata["cfieldname"];
            }
            $insertdata["cfieldname"] = $newcfieldname;
            if (trim($insertdata["method"]) == '') {
                $insertdata["method"] = '==';
            }
            // Now process the value and replace @sgqa@ codes
            if (preg_match("/^@(.*)@\$/", $insertdata["value"], $cfieldnameInCondValue)) {
                if (isset($aOldNewFieldmap[$cfieldnameInCondValue[1]])) {
                    $newvalue = '@' . $aOldNewFieldmap[$cfieldnameInCondValue[1]] . '@';
                    $insertdata["value"] = $newvalue;
                }
            }
            // now translate any links
            $result = Conditions::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data<br />");
            $results['conditions']++;
        }
    }
    // TMSW Conditions->Relevance:  Call  LEM->ConvertConditionsToRelevance
    // Import assessments --------------------------------------------------------
    if (isset($xml->assessments)) {
        foreach ($xml->assessments->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            if ($insertdata['gid'] > 0) {
                $insertdata['gid'] = $aGIDReplacements[(int) $insertdata['gid']];
                // remap the qid
            }
            $insertdata['sid'] = $iNewSID;
            // remap the survey id
            // now translate any links
            $result = Assessment::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data<br />");
            $results['assessments']++;
        }
    }
    // Import quota --------------------------------------------------------------
    if (isset($xml->quota)) {
        foreach ($xml->quota->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            $insertdata['sid'] = $iNewSID;
            // remap the survey id
            $oldid = $insertdata['id'];
            unset($insertdata['id']);
            // now translate any links
            $result = Quota::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data<br />");
            $aQuotaReplacements[$oldid] = Yii::app()->db->getCommandBuilder()->getLastInsertID('{{quota}}');
            $results['quota']++;
        }
    }
    // Import quota_members ------------------------------------------------------
    if (isset($xml->quota_members)) {
        foreach ($xml->quota_members->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            $insertdata['sid'] = $iNewSID;
            // remap the survey id
            $insertdata['qid'] = $aQIDReplacements[(int) $insertdata['qid']];
            // remap the qid
            $insertdata['quota_id'] = $aQuotaReplacements[(int) $insertdata['quota_id']];
            // remap the qid
            unset($insertdata['id']);
            // now translate any links
            $result = Quota_members::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data<br />");
            $results['quotamembers']++;
        }
    }
    // Import quota_languagesettings----------------------------------------------
    if (isset($xml->quota_languagesettings)) {
        foreach ($xml->quota_languagesettings->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            $insertdata['quotals_quota_id'] = $aQuotaReplacements[(int) $insertdata['quotals_quota_id']];
            // remap the qid
            unset($insertdata['quotals_id']);
            $result = Quota_languagesettings::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data<br />");
            $results['quotals']++;
        }
    }
    // Import survey_url_parameters ----------------------------------------------
    if (isset($xml->survey_url_parameters)) {
        foreach ($xml->survey_url_parameters->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            $insertdata['sid'] = $iNewSID;
            // remap the survey id
            if (isset($insertdata['targetsqid']) && $insertdata['targetsqid'] != '') {
                $insertdata['targetsqid'] = $aSQIDReplacements[(int) $insertdata['targetsqid']];
                // remap the qid
            }
            if (isset($insertdata['targetqid']) && $insertdata['targetqid'] != '') {
                $insertdata['targetqid'] = $aQIDReplacements[(int) $insertdata['targetqid']];
                // remap the qid
            }
            unset($insertdata['id']);
            $result = Survey_url_parameters::model()->insertRecord($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data<br />");
            $results['survey_url_parameters']++;
        }
    }
    // Set survey rights
    Survey_permissions::model()->giveAllSurveyPermissions(Yii::app()->session['loginID'], $iNewSID);
    $aOldNewFieldmap = reverseTranslateFieldNames($iOldSID, $iNewSID, $aGIDReplacements, $aQIDReplacements);
    $results['FieldReMap'] = $aOldNewFieldmap;
    LimeExpressionManager::SetSurveyId($iNewSID);
    translateInsertansTags($iNewSID, $iOldSID, $aOldNewFieldmap);
    LimeExpressionManager::RevertUpgradeConditionsToRelevance($iNewSID);
    LimeExpressionManager::UpgradeConditionsToRelevance($iNewSID);
    return $results;
}
 function editquota($iSurveyId)
 {
     $iSurveyId = sanitize_int($iSurveyId);
     $this->_checkPermissions($iSurveyId, 'update');
     $aData = $this->_getData($iSurveyId);
     $aLangs = $aData['aLangs'];
     $clang = $aData['clang'];
     $aViewUrls = array();
     $aQuotaInfo = Quota::model()->findByPk(Yii::app()->request->getPost('quota_id'));
     $aData['quotainfo'] = $aQuotaInfo;
     $aViewUrls[] = 'editquota_view';
     $first = true;
     foreach ($aLangs as $sLanguage) {
         $aTabTitles[$sLanguage] = getLanguageNameFromCode($sLanguage, false);
         if ($first) {
             $aTabTitles[$sLanguage] .= ' (' . $clang->gT("Base language") . ')';
             $first = false;
         }
         $aData['langquotainfo'] = Quota_languagesettings::model()->findByAttributes(array('quotals_quota_id' => Yii::app()->request->getPost('quota_id'), 'quotals_language' => $sLanguage));
         $aData['lang'] = $sLanguage;
         $aViewUrls['editquotalang_view'][] = $aData;
     }
     $aData['aTabTitles'] = $aTabTitles;
     $aViewUrls[] = 'editquotafooter_view';
     $this->_renderWrappedTemplate('quotas', $aViewUrls, $aData);
 }
 /**
  * This function checks the LimeSurvey database for logical consistency and returns an according array
  * containing all issues in the particular tables.
  * @returns Array with all found issues.
  */
 protected function _checkintegrity()
 {
     $clang = Yii::app()->lang;
     /*** Plainly delete survey permissions if the survey or user does not exist ***/
     $users = User::model()->findAll();
     $uids = array();
     foreach ($users as $user) {
         $uids[] = $user['uid'];
     }
     $criteria = new CDbCriteria();
     $criteria->addNotInCondition('uid', $uids, 'OR');
     $surveys = Survey::model()->findAll();
     $sids = array();
     foreach ($surveys as $survey) {
         $sids[] = $survey['sid'];
     }
     $criteria->addNotInCondition('sid', $sids, 'OR');
     Survey_permissions::model()->deleteAll($criteria);
     // Deactivate surveys that have a missing response table
     foreach ($surveys as $survey) {
         if ($survey['active'] == 'Y' && !tableExists("{{survey_{$survey['sid']}}}")) {
             Survey::model()->updateByPk($survey['sid'], array('active' => 'N'));
         }
     }
     // Fix subquestions
     fixSubquestions();
     /*** Check for active survey tables with missing survey entry and rename them ***/
     $sDBPrefix = Yii::app()->db->tablePrefix;
     $sQuery = dbSelectTablesLike('{{survey}}\\_%');
     $aResult = dbQueryOrFalse($sQuery) or safeDie("Couldn't get list of conditions from database<br />{$sQuery}<br />");
     foreach ($aResult->readAll() as $aRow) {
         $sTableName = substr(reset($aRow), strlen($sDBPrefix));
         if ($sTableName == 'survey_permissions' || $sTableName == 'survey_links' || $sTableName == 'survey_url_parameters') {
             continue;
         }
         $aTableName = explode('_', $sTableName);
         if (isset($aTableName[1]) && ctype_digit($aTableName[1])) {
             $iSurveyID = $aTableName[1];
             if (!in_array($iSurveyID, $sids)) {
                 $sDate = date('YmdHis') . rand(1, 1000);
                 $sOldTable = "survey_{$iSurveyID}";
                 $sNewTable = "old_survey_{$iSurveyID}_{$sDate}";
                 try {
                     $deactivateresult = Yii::app()->db->createCommand()->renameTable("{{{$sOldTable}}}", "{{{$sNewTable}}}");
                 } catch (CDbException $e) {
                     die('Couldn\'t make backup of the survey table. Please try again. The database reported the following error:<br />' . htmlspecialchars($e) . '<br />');
                 }
             }
         }
     }
     /*** Check for active token tables with missing survey entry ***/
     $aResult = dbQueryOrFalse(dbSelectTablesLike('{{tokens}}\\_%')) or safeDie("Couldn't get list of conditions from database<br />{$sQuery}<br />");
     foreach ($aResult->readAll() as $aRow) {
         $sTableName = substr(reset($aRow), strlen($sDBPrefix));
         $iSurveyID = substr($sTableName, strpos($sTableName, '_') + 1);
         if (!in_array($iSurveyID, $sids)) {
             $sDate = date('YmdHis') . rand(1, 1000);
             $sOldTable = "tokens_{$iSurveyID}";
             $sNewTable = "old_tokens_{$iSurveyID}_{$sDate}";
             try {
                 $deactivateresult = Yii::app()->db->createCommand()->renameTable("{{{$sOldTable}}}", "{{{$sNewTable}}}");
             } catch (CDbException $e) {
                 die('Couldn\'t make backup of the survey table. Please try again. The database reported the following error:<br />' . htmlspecialchars($e) . '<br />');
             }
         }
     }
     /**********************************************************************/
     /*     Check conditions                                               */
     /**********************************************************************/
     // TMSW Conditions->Relevance:  Replace this with analysis of relevance
     $conditions = Conditions::model()->findAll();
     if (Conditions::model()->hasErrors()) {
         safeDie(Conditions::model()->getError());
     }
     $okQuestion = array();
     foreach ($conditions as $condition) {
         if ($condition['cqid'] != 0) {
             // skip case with cqid=0 for codnitions on {TOKEN:EMAIL} for instance
             if (!array_key_exists($condition['cqid'], $okQuestion)) {
                 $iRowCount = Questions::model()->countByAttributes(array('qid' => $condition['cqid']));
                 if (Questions::model()->hasErrors()) {
                     safeDie(Questions::model()->getError());
                 }
                 if (!$iRowCount) {
                     $aDelete['conditions'][] = array('cid' => $condition['cid'], 'reason' => $clang->gT('No matching CQID'));
                 } else {
                     $okQuestion[$condition['cqid']] = $condition['cqid'];
                 }
             }
         }
         if ($condition['cfieldname']) {
             if (preg_match('/^\\+{0,1}[0-9]+X[0-9]+X*$/', $condition['cfieldname'])) {
                 // only if cfieldname isn't Tag such as {TOKEN:EMAIL} or any other token
                 list($surveyid, $gid, $rest) = explode('X', $condition['cfieldname']);
                 $iRowCount = count(Groups::model()->findAllByAttributes(array('gid' => $gid)));
                 if (Groups::model()->hasErrors()) {
                     safeDie(Groups::model()->getError());
                 }
                 if (!$iRowCount) {
                     $aDelete['conditions'][] = array('cid' => $condition['cid'], 'reason' => $clang->gT('No matching CFIELDNAME group!') . " ({$gid}) ({$condition['cfieldname']})");
                 }
             }
         } elseif (!$condition['cfieldname']) {
             $aDelete['conditions'][] = array('cid' => $condition['cid'], 'reason' => $clang->gT('No CFIELDNAME field set!') . " ({$condition['cfieldname']})");
         }
     }
     /**********************************************************************/
     /*     Check question attributes                                      */
     /**********************************************************************/
     $question_attributes = Question_attributes::model()->findAllBySql('select qid from {{question_attributes}} where qid not in (select qid from {{questions}})');
     if (Question_attributes::model()->hasErrors()) {
         safeDie(Question_attributes::model()->getError());
     }
     foreach ($question_attributes as $question_attribute) {
         $aDelete['questionattributes'][] = array('qid' => $question_attribute['qid']);
     }
     // foreach
     /**********************************************************************/
     /*     Check default values                                           */
     /**********************************************************************/
     $questions = Questions::model()->findAll();
     if (Questions::model()->hasErrors()) {
         safeDie(Questions::model()->getError());
     }
     $qids = array();
     foreach ($questions as $question) {
         $qids[] = $question['qid'];
     }
     $criteria = new CDbCriteria();
     $criteria->addNotInCondition('qid', $qids);
     $aDelete['defaultvalues'] = count(Defaultvalues::model()->findAll($criteria));
     if (Defaultvalues::model()->hasErrors()) {
         safeDie(Defaultvalues::model()->getError());
     }
     /**********************************************************************/
     /*     Check quotas                                                   */
     /**********************************************************************/
     $surveys = Survey::model()->findAll();
     if (Survey::model()->hasErrors()) {
         safeDie(Survey::model()->getError());
     }
     $sids = array();
     foreach ($surveys as $survey) {
         $sids[] = $survey['sid'];
     }
     $criteria = new CDbCriteria();
     $criteria->addNotInCondition('sid', $sids);
     $aDelete['quotas'] = count(Quota::model()->findAll($criteria));
     if (Quota::model()->hasErrors()) {
         safeDie(Quota::model()->getError());
     }
     /**********************************************************************/
     /*     Check quota languagesettings                                   */
     /**********************************************************************/
     $quotas = Quota::model()->findAll();
     if (Quota::model()->hasErrors()) {
         safeDie(Quota::model()->getError());
     }
     $ids = array();
     foreach ($quotas as $quota) {
         $ids[] = $quota['id'];
     }
     $criteria = new CDbCriteria();
     $criteria->addNotInCondition('quotals_quota_id', $ids);
     $aDelete['quotals'] = count(Quota_languagesettings::model()->findAll($criteria));
     if (Quota_languagesettings::model()->hasErrors()) {
         safeDie(Quota_languagesettings::model()->getError());
     }
     /**********************************************************************/
     /*     Check quota members                                   */
     /**********************************************************************/
     $quotas = Quota::model()->findAll();
     $quota_ids = array();
     foreach ($quotas as $quota) {
         $quota_ids[] = $quota['id'];
     }
     $criteria = new CDbCriteria();
     $criteria->addNotInCondition('quota_id', $quota_ids);
     $questions = Questions::model()->findAll();
     $qids = array();
     foreach ($questions as $question) {
         $qids[] = $question['qid'];
     }
     $criteria->addNotInCondition('qid', $qids, 'OR');
     $surveys = Survey::model()->findAll();
     $sids = array();
     foreach ($surveys as $survey) {
         $sids[] = $survey['sid'];
     }
     $criteria->addNotInCondition('sid', $sids, 'OR');
     $aDelete['quotamembers'] = count(Quota_members::model()->findAll($criteria));
     if (Quota_members::model()->hasErrors()) {
         safeDie(Quota_members::model()->getError());
     }
     /**********************************************************************/
     /*     Check assessments                                              */
     /**********************************************************************/
     $criteria = new CDbCriteria();
     $criteria->compare('scope', 'T');
     $assessments = Assessment::model()->findAll($criteria);
     if (Assessment::model()->hasErrors()) {
         safeDie(Assessment::model()->getError());
     }
     foreach ($assessments as $assessment) {
         $iAssessmentCount = count(Survey::model()->findAllByPk($assessment['sid']));
         if (Survey::model()->hasErrors()) {
             safeDie(Survey::model()->getError());
         }
         if (!$iAssessmentCount) {
             $aDelete['assessments'][] = array('id' => $assessment['id'], 'assessment' => $assessment['name'], 'reason' => $clang->gT('No matching survey'));
         }
     }
     $criteria = new CDbCriteria();
     $criteria->compare('scope', 'G');
     $assessments = Assessment::model()->findAll($criteria);
     if (Assessment::model()->hasErrors()) {
         safeDie(Assessment::model()->getError());
     }
     foreach ($assessments as $assessment) {
         $iAssessmentCount = count(Groups::model()->findAllByPk(array('gid' => $assessment['gid'], 'language' => $assessment['language'])));
         if (Groups::model()->hasErrors()) {
             safeDie(Groups::model()->getError());
         }
         if (!$iAssessmentCount) {
             $aDelete['assessments'][] = array('id' => $assessment['id'], 'assessment' => $assessment['name'], 'reason' => $clang->gT('No matching group'));
         }
     }
     /**********************************************************************/
     /*     Check answers                                                  */
     /**********************************************************************/
     $answers = Answers::model()->findAll();
     if (Answers::model()->hasErrors()) {
         safeDie(Answers::model()->getError());
     }
     $okQuestion = array();
     foreach ($answers as $answer) {
         if (!array_key_exists($answer['qid'], $okQuestion)) {
             $iAnswerCount = Questions::model()->countByAttributes(array('qid' => $answer['qid']));
             if (Questions::model()->hasErrors()) {
                 safeDie(Questions::model()->getError());
             }
             if (!$iAnswerCount) {
                 $aDelete['answers'][] = array('qid' => $answer['qid'], 'code' => $answer['code'], 'reason' => $clang->gT('No matching question'));
             } else {
                 $okQuestion[$answer['qid']] = $answer['qid'];
             }
         }
     }
     /***************************************************************************/
     /*   Check survey languagesettings and restore them if they don't exist    */
     /***************************************************************************/
     $surveys = Survey::model()->findAll();
     foreach ($surveys as $survey) {
         $aLanguages = $survey->additionalLanguages;
         $aLanguages[] = $survey->language;
         foreach ($aLanguages as $langname) {
             if ($langname) {
                 $oLanguageSettings = Surveys_languagesettings::model()->find('surveyls_survey_id=:surveyid AND surveyls_language=:langname', array(':surveyid' => $survey->sid, ':langname' => $langname));
                 if (!$oLanguageSettings) {
                     $oLanguageSettings = new Surveys_languagesettings();
                     $languagedetails = getLanguageDetails($langname);
                     $insertdata = array('surveyls_survey_id' => $survey->sid, 'surveyls_language' => $langname, 'surveyls_title' => '', 'surveyls_dateformat' => $languagedetails['dateformat']);
                     foreach ($insertdata as $k => $v) {
                         $oLanguageSettings->{$k} = $v;
                     }
                     $usresult = $oLanguageSettings->save();
                 }
             }
         }
     }
     /**********************************************************************/
     /*     Check survey language settings                                 */
     /**********************************************************************/
     $surveys = Survey::model()->findAll();
     if (Survey::model()->hasErrors()) {
         safeDie(Survey::model()->getError());
     }
     $sids = array();
     foreach ($surveys as $survey) {
         $sids[] = $survey['sid'];
     }
     $criteria = new CDbCriteria();
     $criteria->addNotInCondition('surveyls_survey_id', $sids);
     $surveys_languagesettings = Surveys_languagesettings::model()->findAll($criteria);
     if (Surveys_languagesettings::model()->hasErrors()) {
         safeDie(Surveys_languagesettings::model()->getError());
     }
     foreach ($surveys_languagesettings as $surveys_languagesetting) {
         $aDelete['surveylanguagesettings'][] = array('slid' => $surveys_languagesetting['surveyls_survey_id'], 'reason' => $clang->gT('The related survey is missing.'));
     }
     /**********************************************************************/
     /*     Check questions                                                */
     /**********************************************************************/
     $questions = Questions::model()->findAll();
     if (Questions::model()->hasErrors()) {
         safeDie(Questions::model()->getError());
     }
     $groups = Groups::model()->findAll();
     if (Groups::model()->hasErrors()) {
         safeDie(Groups::model()->getError());
     }
     $gids = array();
     foreach ($groups as $group) {
         $gids[] = $group['gid'];
     }
     foreach ($questions as $question) {
         //Make sure the group exists
         if (!in_array($question['gid'], $gids)) {
             $aDelete['questions'][] = array('qid' => $question['qid'], 'reason' => $clang->gT('No matching group') . " ({$question['gid']})");
         }
         //Make sure survey exists
         if (!in_array($question['sid'], $sids)) {
             $aDelete['questions'][] = array('qid' => $question['qid'], 'reason' => $clang->gT('There is no matching survey.') . " ({$question['sid']})");
         }
     }
     /**********************************************************************/
     /*     Check groups                                                   */
     /**********************************************************************/
     $surveys = Survey::model()->findAll();
     if (Survey::model()->hasErrors()) {
         safeDie(Survey::model()->getError());
     }
     $sids = array();
     foreach ($surveys as $survey) {
         $sids[] = $survey['sid'];
     }
     $criteria = new CDbCriteria();
     $criteria->addNotInCondition('sid', $sids);
     $groups = Groups::model()->findAll($criteria);
     foreach ($groups as $group) {
         $aDelete['groups'][] = array('gid' => $group['gid'], 'reason' => $clang->gT('There is no matching survey.') . ' SID:' . $group['sid']);
     }
     /**********************************************************************/
     /*     Check old survey tables                                        */
     /**********************************************************************/
     //1: Get list of 'old_survey' tables and extract the survey id
     //2: Check if that survey id still exists
     //3: If it doesn't offer it for deletion
     $sQuery = dbSelectTablesLike('{{old_survey}}%');
     $aResult = dbQueryOrFalse($sQuery) or safeDie("Couldn't get list of conditions from database<br />{$sQuery}<br />");
     $aTables = $aResult->readAll();
     $aOldSIDs = array();
     $aSIDs = array();
     foreach ($aTables as $sTable) {
         $sTable = reset($sTable);
         list($sOldText, $SurveyText, $iSurveyID, $sDate) = explode('_', substr($sTable, strlen($sDBPrefix)));
         $aOldSIDs[] = $iSurveyID;
         $aFullOldSIDs[$iSurveyID][] = $sTable;
     }
     $aOldSIDs = array_unique($aOldSIDs);
     //$sQuery = 'SELECT sid FROM {{surveys}} ORDER BY sid';
     //$oResult = dbExecuteAssoc($sQuery) or safeDie('Couldn\'t get unique survey ids');
     $surveys = Survey::model()->findAll();
     if (Survey::model()->hasErrors()) {
         safeDie(Survey::model()->getError());
     }
     $aSIDs = array();
     foreach ($surveys as $survey) {
         $aSIDs[] = $survey['sid'];
     }
     foreach ($aOldSIDs as $iOldSID) {
         if (!in_array($iOldSID, $aSIDs)) {
             foreach ($aFullOldSIDs[$iOldSID] as $sTableName) {
                 $aDelete['orphansurveytables'][] = $sTableName;
             }
         } else {
             foreach ($aFullOldSIDs[$iOldSID] as $sTableName) {
                 $aTableParts = explode('_', substr($sTableName, strlen($sDBPrefix)));
                 if (count($aTableParts) == 4) {
                     $sOldText = $aTableParts[0];
                     $SurveyText = $aTableParts[1];
                     $iSurveyID = $aTableParts[2];
                     $sDateTime = $aTableParts[3];
                     $sType = $clang->gT('responses');
                 } elseif (count($aTableParts) == 5) {
                     //This is a timings table (
                     $sOldText = $aTableParts[0];
                     $SurveyText = $aTableParts[1];
                     $iSurveyID = $aTableParts[2];
                     $sDateTime = $aTableParts[4];
                     $sType = $clang->gT('timings');
                 }
                 $iYear = substr($sDateTime, 0, 4);
                 $iMonth = substr($sDateTime, 4, 2);
                 $iDay = substr($sDateTime, 6, 2);
                 $iHour = substr($sDateTime, 8, 2);
                 $iMinute = substr($sDateTime, 10, 2);
                 $sDate = date('d M Y  H:i', mktime($iHour, $iMinute, 0, $iMonth, $iDay, $iYear));
                 $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
                     $aDelete['orphansurveytables'][] = $sTableName;
                 } else {
                     $aOldSurveyTableAsk[] = array('table' => $sTableName, 'details' => sprintf($clang->gT('Survey ID %d saved at %s containing %d record(s) (%s)'), $iSurveyID, $sDate, $aFirstRow['recordcount'], $sType));
                 }
             }
         }
     }
     /**********************************************************************/
     /*     CHECK OLD TOKEN  TABLES                                        */
     /**********************************************************************/
     //1: Get list of 'old_token' tables and extract the survey id
     //2: Check if that survey id still exists
     //3: If it doesn't offer it for deletion
     $aResult = dbQueryOrFalse(dbSelectTablesLike('{{old_token}}%')) or safeDie("Couldn't get list of conditions from database<br />{$sQuery}<br />");
     $aTables = $aResult->readAll();
     $aOldTokenSIDs = array();
     $aTokenSIDs = array();
     $aFullOldTokenSIDs = array();
     foreach ($aTables as $sTable) {
         $sTable = reset($sTable);
         list($sOldText, $SurveyText, $iSurveyID, $sDateTime) = explode('_', substr($sTable, strlen($sDBPrefix)));
         $aTokenSIDs[] = $iSurveyID;
         $aFullOldTokenSIDs[$iSurveyID][] = $sTable;
     }
     $aOldTokenSIDs = array_unique($aTokenSIDs);
     $surveys = Survey::model()->findAll();
     if (Survey::model()->hasErrors()) {
         safeDie(Survey::model()->getError());
     }
     $aSIDs = array();
     foreach ($surveys as $survey) {
         $aSIDs[] = $survey['sid'];
     }
     foreach ($aOldTokenSIDs as $iOldTokenSID) {
         if (!in_array($iOldTokenSID, $aOldTokenSIDs)) {
             foreach ($aFullOldTokenSIDs[$iOldTokenSID] as $sTableName) {
                 $aDelete['orphantokentables'][] = $sTableName;
             }
         } else {
             foreach ($aFullOldTokenSIDs[$iOldTokenSID] as $sTableName) {
                 list($sOldText, $sTokensText, $iSurveyID, $sDateTime) = explode('_', substr($sTableName, strlen($sDBPrefix)));
                 $iYear = substr($sDateTime, 0, 4);
                 $iMonth = substr($sDateTime, 4, 2);
                 $iDay = substr($sDateTime, 6, 2);
                 $iHour = substr($sDateTime, 8, 2);
                 $iMinute = substr($sDateTime, 10, 2);
                 $sDate = date('D, d M Y  h:i a', mktime($iHour, $iMinute, 0, $iMonth, $iDay, $iYear));
                 $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
                     $aDelete['orphantokentables'][] = $sTableName;
                 } else {
                     $aOldTokenTableAsk[] = array('table' => $sTableName, 'details' => sprintf($clang->gT('Survey ID %d saved at %s containing %d record(s)'), $iSurveyID, $sDate, $aFirstRow['recordcount']));
                 }
             }
         }
     }
     if ($aDelete['defaultvalues'] == 0 && $aDelete['quotamembers'] == 0 && $aDelete['quotas'] == 0 && $aDelete['quotals'] == 0 && count($aDelete) == 4) {
         $aDelete['integrityok'] = true;
     } else {
         $aDelete['integrityok'] = false;
     }
     if (!isset($aOldTokenTableAsk) && !isset($aOldSurveyTableAsk)) {
         $aDelete['redundancyok'] = true;
     } else {
         $aDelete['redundancyok'] = false;
         $aDelete['redundanttokentables'] = array();
         $aDelete['redundantsurveytables'] = array();
         if (isset($aOldTokenTableAsk)) {
             $aDelete['redundanttokentables'] = $aOldTokenTableAsk;
         }
         if (isset($aOldSurveyTableAsk)) {
             $aDelete['redundantsurveytables'] = $aOldSurveyTableAsk;
         }
     }
     /**********************************************************************/
     /*     CHECK CPDB SURVEY_LINKS TABLE FOR REDUNDENT TOKEN TABLES       */
     /**********************************************************************/
     //1: Get distinct list of survey_link survey ids, check if tokens
     //   table still exists for each one, and remove if not
     /* TODO */
     /**********************************************************************/
     /*     CHECK CPDB SURVEY_LINKS TABLE FOR REDUNDENT TOKEN ENTRIES      */
     /**********************************************************************/
     //1: For each survey_link, see if the matching entry still exists in
     //   the token table and remove if it doesn't.
     /* TODO */
     return $aDelete;
 }