Example #1
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;
}
Example #2
0
 function deleteFinalUser($result, $transfer_surveys_to)
 {
     $clang = Yii::app()->lang;
     $postuserid = Yii::app()->request->getPost("uid");
     $postuser = Yii::app()->request->getPost("user");
     if (isset($_POST['transfer_surveys_to'])) {
         $transfer_surveys_to = sanitize_int($_POST['transfer_surveys_to']);
     }
     if ($transfer_surveys_to > 0) {
         $iSurveysTransferred = Survey::model()->updateAll(array('owner_id' => $transfer_surveys_to), 'owner_id=' . $postuserid);
     }
     $sresult = User::model()->findByAttributes(array('uid' => $postuserid));
     $fields = $sresult;
     if (isset($fields['parent_id'])) {
         $uresult = User::model()->updateAll(array('parent_id' => $fields['parent_id']), 'parent_id=' . $postuserid);
     }
     //DELETE USER FROM TABLE
     $dresult = User::model()->deleteUser($postuserid);
     // Delete user rights
     $dresult = Survey_permissions::model()->deleteAllByAttributes(array('uid' => $postuserid));
     if ($postuserid == Yii::app()->session['loginID']) {
         session_destroy;
         // user deleted himself
         $this->redirect($this->getController()->createUrl('/admin'));
         die;
     }
     $extra = "<br />" . sprintf($clang->gT("User '%s' was successfully deleted."), $postuser) . "<br /><br />\n";
     if ($transfer_surveys_to > 0 && $iSurveysTransferred > 0) {
         $user = User::model()->findByPk($transfer_surveys_to);
         $sTransferred_to = $user->users_name;
         //$sTransferred_to = $this->getController()->_getUserNameFromUid($transfer_surveys_to);
         $extra = sprintf($clang->gT("All of the user's surveys were transferred to %s."), $sTransferred_to);
     }
     $aViewUrls['mboxwithredirect'][] = $this->_messageBoxWithRedirect("", $clang->gT("Success!"), "successheader", $extra);
     $this->_renderWrappedTemplate('user', $aViewUrls);
 }
 /**
  * surveypermission::surveyright()
  * Function responsible to process setting of permission of a user/usergroup.
  * @param mixed $surveyid
  * @return void
  */
 function surveyright($surveyid)
 {
     $aData['surveyid'] = $surveyid = sanitize_int($surveyid);
     $aViewUrls = array();
     $action = $_POST['action'];
     $clang = Yii::app()->lang;
     $imageurl = Yii::app()->getConfig('imageurl');
     $postuserid = !empty($_POST['uid']) ? $_POST['uid'] : false;
     $postusergroupid = !empty($_POST['ugid']) ? $_POST['ugid'] : false;
     if ($action == "surveyrights") {
         $addsummary = "<div class='header ui-widget-header'>" . $clang->gT("Edit survey permissions") . "</div>\n";
         $addsummary .= "<div class='messagebox ui-corner-all'>\n";
         $where = ' ';
         if ($postuserid) {
             if (Yii::app()->session['USER_RIGHT_SUPERADMIN'] != 1) {
                 $where .= "sid = :surveyid AND owner_id != :postuserid AND owner_id = :owner_id";
                 $resrow = Survey::model()->find($where, array(':sid' => $surveyid, ':owner_id' => Yii::app()->session['loginID'], ':postuserid' => $postuserid));
             }
         } else {
             $where .= "sid = :sid";
             $resrow = Survey::model()->find($where, array(':sid' => $surveyid));
             $iOwnerID = $resrow['owner_id'];
         }
         $aBaseSurveyPermissions = Survey_permissions::model()->getBasePermissions();
         $aPermissions = array();
         foreach ($aBaseSurveyPermissions as $sPermissionKey => $aCRUDPermissions) {
             foreach ($aCRUDPermissions as $sCRUDKey => $CRUDValue) {
                 if (!in_array($sCRUDKey, array('create', 'read', 'update', 'delete', 'import', 'export'))) {
                     continue;
                 }
                 if ($CRUDValue) {
                     if (isset($_POST["perm_{$sPermissionKey}_{$sCRUDKey}"])) {
                         $aPermissions[$sPermissionKey][$sCRUDKey] = 1;
                     } else {
                         $aPermissions[$sPermissionKey][$sCRUDKey] = 0;
                     }
                 }
             }
         }
         if (isset($postusergroupid) && $postusergroupid > 0) {
             $oResult = User_in_groups::model()->findAll('ugid = :ugid AND uid <> :uid AND uid <> :iOwnerID', array(':ugid' => $postusergroupid, ':uid' => Yii::app()->session['loginID'], ':iOwnerID' => $iOwnerID));
             if (count($oResult) > 0) {
                 foreach ($oResult as $aRow) {
                     Survey_permissions::model()->setPermission($aRow->uid, $surveyid, $aPermissions);
                 }
                 $addsummary .= "<div class=\"successheader\">" . $clang->gT("Survey permissions for all users in this group were successfully updated.") . "</div>\n";
             }
         } else {
             if (Survey_permissions::model()->setPermission($postuserid, $surveyid, $aPermissions)) {
                 $addsummary .= "<div class=\"successheader\">" . $clang->gT("Survey permissions were successfully updated.") . "</div>\n";
             } else {
                 $addsummary .= "<div class=\"warningheader\">" . $clang->gT("Failed to update survey permissions!") . "</div>\n";
             }
         }
         $addsummary .= "<br/><input type=\"submit\" onclick=\"window.open('" . $this->getController()->createUrl('admin/surveypermission/sa/view/surveyid/' . $surveyid) . "', '_top')\" value=\"" . $clang->gT("Continue") . "\"/>\n";
         $addsummary .= "</div>\n";
         $aViewUrls['output'] = $addsummary;
     }
     $this->_renderWrappedTemplate('authentication', $aViewUrls, $aData);
 }
Example #4
0
 /**
  * RPC Routine to add an empty survey with minimum details.
  * Used as a placeholder for importing groups and/or questions.
  *
  * @access public
  * @param string $sSessionKey Auth credentials
  * @param int $iSurveyID The wish id of the Survey to add
  * @param string $sSurveyTitle Title of the new Survey
  * @param string $sSurveyLanguage	Default language of the Survey 
  * @param string $sformat Question appearance format
  * @return array|string|int 
  */
 public function add_survey($sSessionKey, $iSurveyID, $sSurveyTitle, $sSurveyLanguage, $sformat = 'G')
 {
     Yii::app()->loadHelper("surveytranslator");
     if ($this->_checkSessionKey($sSessionKey)) {
         if (Yii::app()->session['USER_RIGHT_CREATE_SURVEY']) {
             if ($sSurveyTitle == '' || $sSurveyLanguage == '' || !array_key_exists($sSurveyLanguage, getLanguageDataRestricted()) || !in_array($sformat, array('A', 'G', 'S'))) {
                 return array('status' => 'Faulty parameters');
             }
             $aInsertData = array('template' => 'default', 'owner_id' => Yii::app()->session['loginID'], 'active' => 'N', 'language' => $sSurveyLanguage, 'format' => $sformat);
             if (!is_null($iSurveyID)) {
                 $aInsertData['wishSID'] = $iSurveyID;
             }
             try {
                 $iNewSurveyid = Survey::model()->insertNewSurvey($aInsertData);
                 if (!$iNewSurveyid) {
                     return array('status' => 'Creation Failed');
                 }
                 $sTitle = html_entity_decode($sSurveyTitle, ENT_QUOTES, "UTF-8");
                 // Load default email templates for the chosen language
                 $oLanguage = new Limesurvey_lang($sSurveyLanguage);
                 $aDefaultTexts = templateDefaultTexts($oLanguage, 'unescaped');
                 unset($oLanguage);
                 $bIsHTMLEmail = false;
                 $aInsertData = array('surveyls_survey_id' => $iNewSurveyid, 'surveyls_title' => $sTitle, 'surveyls_language' => $sSurveyLanguage);
                 $langsettings = new Surveys_languagesettings();
                 $langsettings->insertNewSurvey($aInsertData);
                 Survey_permissions::model()->giveAllSurveyPermissions(Yii::app()->session['loginID'], $iNewSurveyid);
                 return (int) $iNewSurveyid;
             } catch (Exception $e) {
                 return array('status' => $e->getmessage());
             }
         } else {
             return array('status' => 'No permission');
         }
     } else {
         return array('status' => 'Invalid session key');
     }
 }
Example #5
0
/**
* Returns true if a user has permissions in the particular survey
*
* @param $iSID The survey ID
* @param $sPermission
* @param $sCRUD
* @param $iUID User ID - if not given the one of the current user is used
* @return bool
*/
function hasSurveyPermission($iSID, $sPermission, $sCRUD, $iUID = null)
{
    if (!in_array($sCRUD, array('create', 'read', 'update', 'delete', 'import', 'export'))) {
        return false;
    }
    $sCRUD = $sCRUD . '_p';
    $iSID = (int) $iSID;
    if ($iSID == 0) {
        return false;
    }
    $aSurveyPermissionCache = Yii::app()->getConfig("aSurveyPermissionCache");
    if (is_null($iUID)) {
        if (!Yii::app()->user->getIsGuest()) {
            $iUID = Yii::app()->session['loginID'];
        } else {
            return false;
        }
        if (Yii::app()->session['USER_RIGHT_SUPERADMIN'] == 1) {
            return true;
        }
        //Superadmin has access to all
    }
    if (!isset($aSurveyPermissionCache[$iSID][$iUID][$sPermission][$sCRUD])) {
        //!!! Convert this model
        $query = Survey_permissions::model()->findByAttributes(array("sid" => $iSID, "uid" => $iUID, "permission" => $sPermission));
        //$sSQL = "SELECT {$sCRUD} FROM " . db_table_name('survey_permissions') . "
        //        WHERE sid={$iSID} AND uid = {$iUID}
        //        and permission=".dbQuoteAll($sPermission); //Getting rights for this survey
        $bPermission = is_null($query) ? array() : $query->attributes;
        if (!isset($bPermission[$sCRUD]) || $bPermission[$sCRUD] == 0) {
            $bPermission = false;
        } else {
            $bPermission = true;
        }
        $aSurveyPermissionCache[$iSID][$iUID][$sPermission][$sCRUD] = $bPermission;
    }
    Yii::app()->setConfig("aSurveyPermissionCache", $aSurveyPermissionCache);
    return $aSurveyPermissionCache[$iSID][$iUID][$sPermission][$sCRUD];
}
Example #6
0
 /**
  * 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 = Questions::model()->findAllByAttributes(array('sid' => $iSurveyID));
         foreach ($oResult as $aRow) {
             Answers::model()->deleteAllByAttributes(array('qid' => $aRow['qid']));
             Conditions::model()->deleteAllByAttributes(array('qid' => $aRow['qid']));
             Question_attributes::model()->deleteAllByAttributes(array('qid' => $aRow['qid']));
             Defaultvalues::model()->deleteAllByAttributes(array('qid' => $aRow['qid']));
         }
         Questions::model()->deleteAllByAttributes(array('sid' => $iSurveyID));
         Assessment::model()->deleteAllByAttributes(array('sid' => $iSurveyID));
         Groups::model()->deleteAllByAttributes(array('sid' => $iSurveyID));
         Surveys_languagesettings::model()->deleteAllByAttributes(array('surveyls_survey_id' => $iSurveyID));
         Survey_permissions::model()->deleteAllByAttributes(array('sid' => $iSurveyID));
         Saved_control::model()->deleteAllByAttributes(array('sid' => $iSurveyID));
         Survey_url_parameters::model()->deleteAllByAttributes(array('sid' => $iSurveyID));
         Quota::model()->deleteQuota(array('sid' => $iSurveyID), true);
     }
 }
 /**
  * Saves the new survey after the creation screen is submitted
  *
  * @param $iSurveyID  The survey id to be used for the new survey. If already taken a new random one will be used.
  */
 function insert($iSurveyID = null)
 {
     if (Yii::app()->session['USER_RIGHT_CREATE_SURVEY']) {
         // Check if survey title was set
         if (!$_POST['surveyls_title']) {
             Yii::app()->session['flashmessage'] = $clang->gT("Survey could not be created because it did not have a title");
             redirect($this->getController()->createUrl('admin'));
             return;
         }
         // Check if template may be used
         $sTemplate = $_POST['template'];
         if (!$sTemplate || Yii::app()->session['USER_RIGHT_SUPERADMIN'] != 1 && Yii::app()->session['USER_RIGHT_MANAGE_TEMPLATE'] != 1 && !hasTemplateManageRights(Yii::app()->session['loginID'], $_POST['template'])) {
             $sTemplate = "default";
         }
         Yii::app()->loadHelper("surveytranslator");
         // If start date supplied convert it to the right format
         $aDateFormatData = getDateFormatData(Yii::app()->session['dateformat']);
         $sStartDate = $_POST['startdate'];
         if (trim($sStartDate) != '') {
             Yii::import('application.libraries.Date_Time_Converter');
             $converter = new Date_Time_Converter($sStartDate, $aDateFormatData['phpdate'] . ' H:i:s');
             $sStartDate = $converter->convert("Y-m-d H:i:s");
         }
         // If expiry date supplied convert it to the right format
         $sExpiryDate = $_POST['expires'];
         if (trim($sExpiryDate) != '') {
             Yii::import('application.libraries.Date_Time_Converter');
             $converter = new Date_Time_Converter($sExpiryDate, $aDateFormatData['phpdate'] . ' H:i:s');
             $sExpiryDate = $converter->convert("Y-m-d H:i:s");
         }
         // Insert base settings into surveys table
         $aInsertData = array('expires' => $sExpiryDate, 'startdate' => $sStartDate, 'template' => $sTemplate, 'owner_id' => Yii::app()->session['loginID'], 'admin' => $_POST['admin'], 'active' => 'N', 'adminemail' => $_POST['adminemail'], 'bounce_email' => $_POST['bounce_email'], 'anonymized' => $_POST['anonymized'], 'faxto' => $_POST['faxto'], 'format' => $_POST['format'], 'savetimings' => $_POST['savetimings'], 'language' => $_POST['language'], 'datestamp' => $_POST['datestamp'], 'ipaddr' => $_POST['ipaddr'], 'refurl' => $_POST['refurl'], 'usecookie' => $_POST['usecookie'], 'emailnotificationto' => $_POST['emailnotificationto'], 'allowregister' => $_POST['allowregister'], 'allowsave' => $_POST['allowsave'], 'navigationdelay' => $_POST['navigationdelay'], 'autoredirect' => $_POST['autoredirect'], 'showxquestions' => $_POST['showxquestions'], 'showgroupinfo' => $_POST['showgroupinfo'], 'showqnumcode' => $_POST['showqnumcode'], 'shownoanswer' => $_POST['shownoanswer'], 'showwelcome' => $_POST['showwelcome'], 'allowprev' => $_POST['allowprev'], 'allowjumps' => $_POST['allowjumps'], 'nokeyboard' => $_POST['nokeyboard'], 'showprogress' => $_POST['showprogress'], 'printanswers' => $_POST['printanswers'], 'listpublic' => $_POST['public'], 'htmlemail' => $_POST['htmlemail'], 'sendconfirmation' => $_POST['sendconfirmation'], 'tokenanswerspersistence' => $_POST['tokenanswerspersistence'], 'alloweditaftercompletion' => $_POST['alloweditaftercompletion'], 'usecaptcha' => $_POST['usecaptcha'], 'publicstatistics' => $_POST['publicstatistics'], 'publicgraphs' => $_POST['publicgraphs'], 'assessments' => $_POST['assessments'], 'emailresponseto' => $_POST['emailresponseto'], 'tokenlength' => $_POST['tokenlength']);
         if (!is_null($iSurveyID)) {
             $aInsertData['wishSID'] = $iSurveyID;
         }
         $iNewSurveyid = Survey::model()->insertNewSurvey($aInsertData);
         if (!$iNewSurveyid) {
             die('Survey could not be created.');
         }
         // Prepare locale data for surveys_language_settings table
         $sTitle = $_POST['surveyls_title'];
         $sDescription = $_POST['description'];
         $sWelcome = $_POST['welcome'];
         $sURLDescription = $_POST['urldescrip'];
         if (Yii::app()->getConfig('filterxsshtml')) {
             //$p = new CHtmlPurifier();
             //$p->options = array('URI.AllowedSchemes'=>array('http' => true,  'https' => true));
             //$sTitle=$p->purify($sTitle);
             //$sDescription=$p->purify($sDescription);
             //$sWelcome=$p->purify($sWelcome);
             //$sURLDescription=$p->purify($sURLDescription);
         }
         $sTitle = html_entity_decode($sTitle, ENT_QUOTES, "UTF-8");
         $sDescription = html_entity_decode($sDescription, ENT_QUOTES, "UTF-8");
         $sWelcome = html_entity_decode($sWelcome, ENT_QUOTES, "UTF-8");
         $sURLDescription = html_entity_decode($sURLDescription, ENT_QUOTES, "UTF-8");
         // Fix bug with FCKEditor saving strange BR types
         $sTitle = fixCKeditorText($sTitle);
         $sDescription = fixCKeditorText($sDescription);
         $sWelcome = fixCKeditorText($sWelcome);
         // Insert base language into surveys_language_settings table
         $aInsertData = array('surveyls_survey_id' => $iNewSurveyid, 'surveyls_title' => $sTitle, 'surveyls_description' => $sDescription, 'surveyls_welcometext' => $sWelcome, 'surveyls_language' => $_POST['language'], 'surveyls_urldescription' => $_POST['urldescrip'], 'surveyls_endtext' => $_POST['endtext'], 'surveyls_url' => $_POST['url'], 'surveyls_dateformat' => (int) $_POST['dateformat'], 'surveyls_numberformat' => (int) $_POST['numberformat']);
         $langsettings = new Surveys_languagesettings();
         $langsettings->insertNewSurvey($aInsertData);
         Yii::app()->session['flashmessage'] = $this->getController()->lang->gT("Survey was successfully added.");
         // Update survey permissions
         Survey_permissions::model()->giveAllSurveyPermissions(Yii::app()->session['loginID'], $iNewSurveyid);
         $this->getController()->redirect($this->getController()->createUrl('admin/survey/sa/view/surveyid/' . $iNewSurveyid));
     }
 }
 /**
  * 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;
 }
/**
* Returns true if a user has permissions in the particular survey
*
* @param $iSID The survey ID
* @param $sPermission
* @param $sCRUD
* @param $iUID User ID - if not given the one of the current user is used
* @return bool
*/
function hasSurveyPermission($iSID, $sPermission, $sCRUD, $iUID = null)
{
    if (!in_array($sCRUD, array('create', 'read', 'update', 'delete', 'import', 'export'))) {
        return false;
    }
    $sCRUD = $sCRUD . '_p';
    $thissurvey = getSurveyInfo($iSID);
    if (!$thissurvey) {
        return false;
    }
    $aSurveyPermissionCache = Yii::app()->getConfig("aSurveyPermissionCache");
    if (is_null($iUID)) {
        if (!Yii::app()->user->getIsGuest()) {
            $iUID = Yii::app()->session['loginID'];
        } else {
            return false;
        }
        // Some user have acces to whole survey settings
        if (Yii::app()->session['USER_RIGHT_SUPERADMIN'] == 1) {
            return true;
        }
        if ($thissurvey && $iUID == $thissurvey['owner_id']) {
            return true;
        }
    }
    if (!isset($aSurveyPermissionCache[$iSID][$iUID][$sPermission][$sCRUD])) {
        $query = Survey_permissions::model()->findByAttributes(array("sid" => $iSID, "uid" => $iUID, "permission" => $sPermission));
        $bPermission = is_null($query) ? array() : $query->attributes;
        if (!isset($bPermission[$sCRUD]) || $bPermission[$sCRUD] == 0) {
            $bPermission = false;
        } else {
            $bPermission = true;
        }
        $aSurveyPermissionCache[$iSID][$iUID][$sPermission][$sCRUD] = $bPermission;
    }
    Yii::app()->setConfig("aSurveyPermissionCache", $aSurveyPermissionCache);
    return $aSurveyPermissionCache[$iSID][$iUID][$sPermission][$sCRUD];
}