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[6]<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 < 156 && 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[7]<br />");
                }
            } else {
                $result = Question_attributes::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data[8]<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[9]<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[10]<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
            unset($insertdata['id']);
            // now translate any links
            $result = Assessment::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data[11]<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[12]<br />");
            $aQuotaReplacements[$oldid] = 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[13]<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[14]<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
 /**
  * dataentry::insert()
  * insert new dataentry
  * @return
  */
 public function insert()
 {
     $subaction = Yii::app()->request->getPost('subaction');
     $surveyid = Yii::app()->request->getPost('sid');
     $lang = isset($_POST['lang']) ? Yii::app()->request->getPost('lang') : NULL;
     $aData = array('surveyid' => $surveyid, 'lang' => $lang);
     if (Permission::model()->hasSurveyPermission($surveyid, 'responses', 'create')) {
         if ($subaction == "insert" && Permission::model()->hasSurveyPermission($surveyid, 'responses', 'create')) {
             $surveytable = "{{survey_{$surveyid}}}";
             $thissurvey = getSurveyInfo($surveyid);
             $errormsg = "";
             Yii::app()->loadHelper("database");
             $aViewUrls['display']['menu_bars']['browse'] = gT("Data entry");
             $aDataentryoutput = '';
             $aDataentrymsgs = array();
             $hiddenfields = '';
             $lastanswfortoken = '';
             // check if a previous answer has been submitted or saved
             $rlanguage = '';
             if (Yii::app()->request->getPost('token') && Permission::model()->hasSurveyPermission($surveyid, 'tokens', 'update')) {
                 $tokencompleted = "";
                 $tcquery = "SELECT completed from {{tokens_{$surveyid}}} WHERE token=" . dbQuoteAll($_POST['token']);
                 $tcresult = dbExecuteAssoc($tcquery);
                 $tcresult = $tcresult->readAll();
                 $tccount = count($tcresult);
                 foreach ($tcresult as $tcrow) {
                     $tokencompleted = $tcrow['completed'];
                 }
                 if ($tccount < 1) {
                     // token doesn't exist in token table
                     $lastanswfortoken = 'UnknownToken';
                 } elseif ($thissurvey['anonymized'] == "Y") {
                     // token exist but survey is anonymous, check completed state
                     if ($tokencompleted != "" && $tokencompleted != "N") {
                         // token is completed
                         $lastanswfortoken = 'PrivacyProtected';
                     }
                 } else {
                     // token is valid, survey not anonymous, try to get last recorded response id
                     $aquery = "SELECT id,startlanguage FROM {$surveytable} WHERE token=" . dbQuoteAll($_POST['token']);
                     $aresult = dbExecuteAssoc($aquery);
                     foreach ($aresult->readAll() as $arow) {
                         if ($tokencompleted != "N") {
                             $lastanswfortoken = $arow['id'];
                         }
                         $rlanguage = $arow['startlanguage'];
                     }
                 }
             }
             // First Check if the survey uses tokens and if a token has been provided
             if (tableExists('{{tokens_' . $thissurvey['sid'] . '}}') && !$_POST['token']) {
                 $errormsg = CHtml::tag('div', array('class' => 'warningheader'), gT("Error"));
                 $errormsg .= CHtml::tag('p', array(), gT("This is a closed-access survey, so you must supply a valid token.  Please contact the administrator for assistance."));
             } elseif (tableExists('{{tokens_' . $thissurvey['sid'] . '}}') && $lastanswfortoken == 'UnknownToken') {
                 $errormsg = CHtml::tag('div', array('class' => 'warningheader'), gT("Error"));
                 $errormsg .= CHtml::tag('p', array(), gT("The token you have provided is not valid or has already been used."));
             } elseif (tableExists('{{tokens_' . $thissurvey['sid'] . '}}') && $lastanswfortoken != '') {
                 $errormsg = CHtml::tag('div', array('class' => 'warningheader'), gT("Error"));
                 $errormsg .= CHtml::tag('p', array(), gT("There is already a recorded answer for this token"));
                 if ($lastanswfortoken != 'PrivacyProtected') {
                     $errormsg .= "<br /><br />" . gT("Follow the following link to update it") . ":\n";
                     $errormsg .= CHtml::link("[id:{$lastanswfortoken}]", $this->getController()->createUrl('/admin/dataentry/sa/editdata/subaction/edit/id/' . $lastanswfortoken . '/surveyid/' . $surveyid . '/lang/' . $rlanguage), array('title' => gT("Edit this entry")));
                     $errormsg .= "<br/><br/>";
                 } else {
                     $errormsg .= "<br /><br />" . gT("This surveys uses anonymized responses, so you can't update your response.") . "\n";
                 }
             } else {
                 $last_db_id = 0;
                 if (isset($_POST['save']) && $_POST['save'] == "on") {
                     $aData['save'] = TRUE;
                     $saver['identifier'] = $_POST['save_identifier'];
                     $saver['language'] = $_POST['save_language'];
                     $saver['password'] = $_POST['save_password'];
                     $saver['passwordconfirm'] = $_POST['save_confirmpassword'];
                     $saver['email'] = $_POST['save_email'];
                     if (!returnGlobal('redo')) {
                         $password = md5($saver['password']);
                     } else {
                         $password = $saver['password'];
                     }
                     $errormsg = "";
                     if (!$saver['identifier']) {
                         $errormsg .= gT("Error") . ": " . gT("You must supply a name for this saved session.");
                     }
                     if (!$saver['password']) {
                         $errormsg .= gT("Error") . ": " . gT("You must supply a password for this saved session.");
                     }
                     if ($saver['password'] != $saver['passwordconfirm']) {
                         $errormsg .= gT("Error") . ": " . gT("Your passwords do not match.");
                     }
                     $aData['errormsg'] = $errormsg;
                     if ($errormsg) {
                         foreach ($_POST as $key => $val) {
                             if (substr($key, 0, 4) != "save" && $key != "action" && $key != "sid" && $key != "datestamp" && $key != "ipaddr") {
                                 $hiddenfields .= CHtml::hiddenField($key, $val);
                                 //$aDataentryoutput .= "<input type='hidden' name='$key' value='$val' />\n";
                             }
                         }
                     }
                 }
                 //BUILD THE SQL TO INSERT RESPONSES
                 $baselang = Survey::model()->findByPk($surveyid)->language;
                 $fieldmap = createFieldMap($surveyid, 'full', false, false, getBaseLanguageFromSurveyID($surveyid));
                 $insert_data = array();
                 $_POST['startlanguage'] = $baselang;
                 if ($thissurvey['datestamp'] == "Y") {
                     $_POST['startdate'] = $_POST['datestamp'];
                 }
                 if (isset($_POST['closerecord'])) {
                     if ($thissurvey['datestamp'] == "Y") {
                         $_POST['submitdate'] = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", Yii::app()->getConfig('timeadjust'));
                     } else {
                         $_POST['submitdate'] = date("Y-m-d H:i:s", mktime(0, 0, 0, 1, 1, 1980));
                     }
                 }
                 foreach ($fieldmap as $irow) {
                     $fieldname = $irow['fieldname'];
                     if (isset($_POST[$fieldname])) {
                         if ($_POST[$fieldname] == "" && ($irow['type'] == 'D' || $irow['type'] == 'N' || $irow['type'] == 'K')) {
                             // can't add '' in Date column
                             // Do nothing
                         } else {
                             if ($irow['type'] == '|') {
                                 if (!strpos($irow['fieldname'], "_filecount")) {
                                     $json = $_POST[$fieldname];
                                     $phparray = json_decode(stripslashes($json));
                                     $filecount = 0;
                                     for ($i = 0; $filecount < count($phparray); $i++) {
                                         if ($_FILES[$fieldname . "_file_" . $i]['error'] != 4) {
                                             $target = Yii::app()->getConfig('uploaddir') . "/surveys/" . $thissurvey['sid'] . "/files/" . randomChars(20);
                                             $size = 0.001 * $_FILES[$fieldname . "_file_" . $i]['size'];
                                             $name = rawurlencode($_FILES[$fieldname . "_file_" . $i]['name']);
                                             if (move_uploaded_file($_FILES[$fieldname . "_file_" . $i]['tmp_name'], $target)) {
                                                 $phparray[$filecount]->filename = basename($target);
                                                 $phparray[$filecount]->name = $name;
                                                 $phparray[$filecount]->size = $size;
                                                 $pathinfo = pathinfo($_FILES[$fieldname . "_file_" . $i]['name']);
                                                 $phparray[$filecount]->ext = $pathinfo['extension'];
                                                 $filecount++;
                                             }
                                         }
                                     }
                                     $insert_data[$fieldname] = ls_json_encode($phparray);
                                 } else {
                                     $insert_data[$fieldname] = count($phparray);
                                 }
                             } elseif ($irow['type'] == 'D') {
                                 Yii::app()->loadLibrary('Date_Time_Converter');
                                 $qidattributes = getQuestionAttributeValues($irow['qid']);
                                 $dateformatdetails = getDateFormatDataForQID($qidattributes, $thissurvey);
                                 $datetimeobj = new Date_Time_Converter($_POST[$fieldname], $dateformatdetails['phpdate']);
                                 $insert_data[$fieldname] = $datetimeobj->convert("Y-m-d H:i:s");
                             } else {
                                 $insert_data[$fieldname] = $_POST[$fieldname];
                             }
                         }
                     }
                 }
                 SurveyDynamic::sid($surveyid);
                 $new_response = new SurveyDynamic();
                 foreach ($insert_data as $column => $value) {
                     $new_response->{$column} = $value;
                 }
                 $new_response->save();
                 $last_db_id = $new_response->getPrimaryKey();
                 if (isset($_POST['closerecord']) && isset($_POST['token']) && $_POST['token'] != '') {
                     // get submit date
                     if (isset($_POST['closedate'])) {
                         $submitdate = $_POST['closedate'];
                     } else {
                         $submitdate = dateShift(date("Y-m-d H:i:s"), "Y-m-d", $timeadjust);
                     }
                     // check how many uses the token has left
                     $usesquery = "SELECT usesleft FROM {{tokens_}}{$surveyid} WHERE token=" . dbQuoteAll($_POST['token']);
                     $usesresult = dbExecuteAssoc($usesquery);
                     $usesrow = $usesresult->readAll();
                     //$usesresult->row_array()
                     if (isset($usesrow)) {
                         $usesleft = $usesrow[0]['usesleft'];
                     }
                     // query for updating tokens
                     $utquery = "UPDATE {{tokens_{$surveyid}}}\n";
                     if (isTokenCompletedDatestamped($thissurvey)) {
                         if (isset($usesleft) && $usesleft <= 1) {
                             $utquery .= "SET usesleft=usesleft-1, completed=" . dbQuoteAll($submitdate);
                         } else {
                             $utquery .= "SET usesleft=usesleft-1\n";
                         }
                     } else {
                         if (isset($usesleft) && $usesleft <= 1) {
                             $utquery .= "SET usesleft=usesleft-1, completed='Y'\n";
                         } else {
                             $utquery .= "SET usesleft=usesleft-1\n";
                         }
                     }
                     $utquery .= "WHERE token=" . dbQuoteAll($_POST['token']);
                     $utresult = dbExecuteAssoc($utquery);
                     //Yii::app()->db->Execute($utquery) or safeDie ("Couldn't update tokens table!<br />\n$utquery<br />\n".Yii::app()->db->ErrorMsg());
                     // save submitdate into survey table
                     $sdquery = "UPDATE {{survey_{$surveyid}}} SET submitdate='" . $submitdate . "' WHERE id={$last_db_id}\n";
                     $sdresult = dbExecuteAssoc($sdquery) or safeDie("Couldn't set submitdate response in survey table!<br />\n{$sdquery}<br />\n");
                 }
                 if (isset($_POST['save']) && $_POST['save'] == "on") {
                     $srid = $last_db_id;
                     $aUserData = Yii::app()->session;
                     //CREATE ENTRY INTO "saved_control"
                     $saved_control_table = '{{saved_control}}';
                     $columns = array("sid", "srid", "identifier", "access_code", "email", "ip", "refurl", 'saved_thisstep', "status", "saved_date");
                     $values = array("'" . $surveyid . "'", "'" . $srid . "'", "'" . $saver['identifier'] . "'", "'" . $password . "'", "'" . $saver['email'] . "'", "'" . $aUserData['ip_address'] . "'", "'" . getenv("HTTP_REFERER") . "'", 0, "'" . "S" . "'", "'" . dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", "'" . Yii::app()->getConfig('timeadjust')) . "'");
                     $SQL = "INSERT INTO {$saved_control_table}\n                        (" . implode(',', $columns) . ")\n                        VALUES\n                        (" . implode(',', $values) . ")";
                     /*$scdata = array("sid"=>$surveyid,
                       "srid"=>$srid,
                       "identifier"=>$saver['identifier'],
                       "access_code"=>$password,
                       "email"=>$saver['email'],
                       "ip"=>$aUserData['ip_address'],
                       "refurl"=>getenv("HTTP_REFERER"),
                       'saved_thisstep' => 0,
                       "status"=>"S",
                       "saved_date"=>dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", Yii::app()->getConfig('timeadjust')));
                       $this->load->model('saved_control_model');*/
                     if (dbExecuteAssoc($SQL)) {
                         $scid = getLastInsertID('{{saved_control}}');
                         $aDataentrymsgs[] = CHtml::tag('font', array('class' => 'successtitle'), gT("Your survey responses have been saved successfully.  You will be sent a confirmation e-mail. Please make sure to save your password, since we will not be able to retrieve it for you."));
                         //$aDataentryoutput .= "<font class='successtitle'></font><br />\n";
                         $tokens_table = "{{tokens_{$surveyid}}}";
                         if (tableExists($tokens_table)) {
                             $tkquery = "SELECT * FROM {$tokens_table}";
                             $tkresult = dbExecuteAssoc($tkquery);
                             /*$tokendata = array (
                               "firstname"=> $saver['identifier'],
                               "lastname"=> $saver['identifier'],
                               "email"=>$saver['email'],
                               "token"=>randomChars(15),
                               "language"=>$saver['language'],
                               "sent"=>dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i", $timeadjust),
                               "completed"=>"N");*/
                             $columns = array("firstname", "lastname", "email", "token", "language", "sent", "completed");
                             $values = array("'" . $saver['identifier'] . "'", "'" . $saver['identifier'] . "'", "'" . $saver['email'] . "'", "'" . $password . "'", "'" . randomChars(15) . "'", "'" . $saver['language'] . "'", "'" . "N" . "'");
                             $SQL = "INSERT INTO {$token_table}\n                                (" . implode(',', $columns) . ")\n                                VALUES\n                                (" . implode(',', $values) . ")";
                             dbExecuteAssoc($SQL);
                             $aDataentrymsgs[] = CHtml::tag('font', array('class' => 'successtitle'), gT("A token entry for the saved survey has been created too."));
                             //$aDataentryoutput .= "<font class='successtitle'></font><br />\n";
                         }
                         if ($saver['email']) {
                             //Send email
                             if (validateEmailAddress($saver['email']) && !returnGlobal('redo')) {
                                 $subject = gT("Saved Survey Details");
                                 $message = gT("Thank you for saving your survey in progress.  The following details can be used to return to this survey and continue where you left off.  Please keep this e-mail for your reference - we cannot retrieve the password for you.");
                                 $message .= "\n\n" . $thissurvey['name'] . "\n\n";
                                 $message .= gT("Name") . ": " . $saver['identifier'] . "\n";
                                 $message .= gT("Password") . ": " . $saver['password'] . "\n\n";
                                 $message .= gT("Reload your survey by clicking on the following link (or pasting it into your browser):") . "\n";
                                 $message .= Yii::app()->getController()->createAbsoluteUrl("/survey/index/sid/{$iSurveyID}/loadall/reload/scid/{$scid}/loadname/" . rawurlencode($saver['identifier']) . "/loadpass/" . rawurlencode($saver['password']) . "/lang/" . rawurlencode($saver['language']));
                                 if (isset($tokendata['token'])) {
                                     $message .= "/token/" . rawurlencode($tokendata['token']);
                                 }
                                 $from = $thissurvey['adminemail'];
                                 if (SendEmailMessage($message, $subject, $saver['email'], $from, $sitename, false, getBounceEmail($surveyid))) {
                                     $emailsent = "Y";
                                     $aDataentrymsgs[] = CHtml::tag('font', array('class' => 'successtitle'), gT("An email has been sent with details about your saved survey"));
                                 }
                             }
                         }
                     } else {
                         safeDie("Unable to insert record into saved_control table.<br /><br />");
                     }
                 }
                 $aData['thisid'] = $last_db_id;
             }
             $aData['errormsg'] = $errormsg;
             $aData['dataentrymsgs'] = $aDataentrymsgs;
             $aData['sidemenu']['state'] = false;
             $this->_renderWrappedTemplate('dataentry', 'insert', $aData);
         }
     }
 }
<?php

require_once "libreria.php";
$mode = "";
$titulo = "";
$producto = array("prdcod" => 0, "prddsc" => "", "ctgcod" => 0, "prdprc" => 0, "prdest" => "ACT", "prdstk" => 0);
if (isset($_POST["txtPrdCod"])) {
    $mode = $_GET["mode"];
    $producto = array("prdcod" => intval($_POST["txtPrdCod"]), "prddsc" => $_POST["txtPrdDsc"], "ctgcod" => intval($_POST["txtCtgCod"]), "prdprc" => floatval($_POST["txtPrdPrc"]), "prdest" => $_POST["cmbPrdEst"], "prdstk" => intval($_POST["txtPrdStk"]));
    //Aqui validar la data
    if ($mode == "INS") {
        insertarProducto($producto["prddsc"], $producto["ctgcod"], $producto["prdprc"], $producto["prdstk"], $producto["prdest"]);
        $_GET["mode"] = "UPD";
        $_GET["prdcod"] = getLastInsertID();
    }
    if ($mode == "UPD") {
        updateProducto($producto["prdcod"], $producto["prddsc"], $producto["ctgcod"], $producto["prdprc"], $producto["prdstk"], $producto["prdest"]);
    }
    if ($mode == "DEL") {
        deleteProducto($producto["prdcod"]);
        header("location:listadoProductos.php");
        die;
    }
}
if (isset($_GET["mode"])) {
    $mode = $_GET["mode"];
    switch ($mode) {
        case "INS":
            $titulo = "Nuevo Producto";
            break;
        case "UPD":
Example #4
0
 public function ajaxSets()
 {
     $lid = Yii::app()->getRequest()->getPost('lid');
     $answers = Yii::app()->getRequest()->getPost('answers');
     $code = Yii::app()->getRequest()->getPost('code');
     $aAssessmentValues = Yii::app()->getRequest()->getPost('assessmentvalues', array());
     //Create new label set
     $language = "";
     foreach ($answers as $lang => $answer) {
         $language .= $lang . " ";
     }
     $language = trim($language);
     if ($lid == 0) {
         $lset = new LabelSet();
         $lset->label_name = Yii::app()->getRequest()->getPost('laname');
         $lset->languages = $language;
         $lset->save();
         $lid = getLastInsertID($lset->tableName());
     } else {
         Label::model()->deleteAll('lid = :lid', array(':lid' => $lid));
     }
     $res = 'ok';
     //optimistic
     foreach ($answers as $lang => $answer) {
         foreach ($answer as $key => $ans) {
             $label = new Label();
             $label->lid = $lid;
             $label->code = $code[$key];
             $label->title = $ans;
             $label->sortorder = $key;
             $label->language = $lang;
             $label->assessment_value = isset($aAssessmentValues[$key]) ? $aAssessmentValues[$key] : 0;
             if (!$label->save()) {
                 $res = 'fail';
             }
         }
     }
     echo ls_json_encode($res);
 }
Example #5
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, $bConvertInvalidQuestionCodes = true)
{
    Yii::app()->loadHelper('database');
    $clang = Yii::app()->lang;
    $aGIDReplacements = array();
    if ($sXMLdata == NULL) {
        $sXMLdata = file_get_contents($sFullFilePath);
    }
    $xml = @simplexml_load_string($sXMLdata, 'SimpleXMLElement', LIBXML_NONET);
    if (!$xml || $xml->LimeSurveyDocType != 'Survey') {
        $results['error'] = $clang->gT("This is not a valid LimeSurvey survey structure XML file.");
        return $results;
    }
    $pre_personal_characteristics = "";
    $question_groups['R'] = array();
    $question_groups['I'] = array();
    $question_groups['O'] = array();
    $iDBVersion = (int) $xml->DBVersion;
    $aQIDReplacements = array();
    $aQuestionCodeReplacements = 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);
        } else {
            $insertdata['wishSID'] = $iOldSID;
        }
        if ($iDBVersion < 145) {
            if (isset($insertdata['private'])) {
                $insertdata['anonymized'] = $insertdata['private'];
            }
            unset($insertdata['private']);
            unset($insertdata['notification']);
        }
        //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']);
        }
        // Special code to set javascript in
        Yii::app()->loadHelper('admin/template');
        $newname = "watson_" . time();
        $newdirname = Yii::app()->getConfig('usertemplaterootdir') . "/" . $newname;
        $copydirname = getTemplatePath("watson_personal_constructs_copy_me");
        $oFileHelper = new CFileHelper();
        $mkdirresult = mkdir_p($newdirname);
        if ($mkdirresult == 1) {
            $oFileHelper->copyDirectory($copydirname, $newdirname);
            $templatename = $newname;
            //$this->index("startpage.pstpl", "welcome", $templatename);
        } elseif ($mkdirresult == 2) {
            $results['Error'] = sprintf($clang->gT("Directory with the name `%s` already exists - choose another name", "js"), $newname);
        } else {
            $results['Error'] = sprintf($clang->gT("Unable to create directory `%s`.", "js"), $newname) . " " . $clang->gT("Please check the directory permissions.", "js");
        }
        $insertdata['template'] = $newname;
        // End special copy code (taken from templates.php templatecopy() method
        if (isset($insertdata['googleAnalyticsStyle'])) {
            $insertdata['googleanalyticsstyle'] = $insertdata['googleAnalyticsStyle'];
            unset($insertdata['googleAnalyticsStyle']);
        }
        if (isset($insertdata['googleAnalyticsAPIKey'])) {
            $insertdata['googleanalyticsapikey'] = $insertdata['googleAnalyticsAPIKey'];
            unset($insertdata['googleAnalyticsAPIKey']);
        }
        if (isset($insertdata['allowjumps'])) {
            $insertdata['questionindex'] = $insertdata['allowjumps'] == "Y" ? 1 : 0;
            unset($insertdata['allowjumps']);
        }
        /* Remove unknow column */
        $aSurveyModelsColumns = Survey::model()->attributes;
        $aSurveyModelsColumns['wishSID'] = null;
        // To force a sid surely
        $aBadData = array_diff_key($insertdata, $aSurveyModelsColumns);
        $insertdata = array_intersect_key($insertdata, $aSurveyModelsColumns);
        // Fill a optionnal array of error
        foreach ($aBadData as $key => $value) {
            $results['importwarnings'][] = sprintf($clang->gT("This survey setting has not been imported: %s => %s"), $key, $value);
        }
        $iNewSID = $results['newsid'] = Survey::model()->insertNewSurvey($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data [1]<br />");
        $pre_personal_characteristics = file_get_contents($newdirname . "/question.pstpl");
        $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;
        }
        // Assign new survey ID
        $insertdata['surveyls_survey_id'] = $iNewSID;
        // Assign new survey name (if a copy)
        if ($sNewSurveyName != NULL) {
            $insertdata['surveyls_title'] = $sNewSurveyName;
        }
        if ($bTranslateInsertansTags) {
            $insertdata['surveyls_title'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['surveyls_title']);
            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']);
            }
        }
        if (isset($insertdata['surveyls_attributecaptions']) && substr($insertdata['surveyls_attributecaptions'], 0, 1) != '{') {
            unset($insertdata['surveyls_attributecaptions']);
        }
        $result = SurveyLanguageSetting::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 = QuestionGroup::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data [3]<br />");
            if ($insertdata['group_name'] == 'Real Characteristics' || $insertdata['group_name'] == 'PC - Real Characteristics') {
                $question_groups['R'][] = $newgid;
            } else {
                if ($insertdata['group_name'] == 'Ideal Characteristics' || $insertdata['group_name'] == 'PC - Ideal Characteristics') {
                    $question_groups['I'][] = $newgid;
                } else {
                    if ($insertdata['group_name'] == 'Ought Characteristics' || $insertdata['group_name'] == 'PC - Ought Characteristics') {
                        $question_groups['O'][] = $newgid;
                    }
                }
            }
            $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);
            }
            if (!$bConvertInvalidQuestionCodes) {
                $sScenario = 'archiveimport';
            } else {
                $sScenario = 'import';
            }
            $oQuestion = new Question($sScenario);
            $oQuestion->setAttributes($insertdata, false);
            // Try to fix question title for valid question code enforcement
            if (!$oQuestion->validate(array('title'))) {
                $sOldTitle = $oQuestion->title;
                $sNewTitle = preg_replace("/[^A-Za-z0-9]/", '', $sOldTitle);
                if (is_numeric(substr($sNewTitle, 0, 1))) {
                    $sNewTitle = 'q' . $sNewTitle;
                }
                $oQuestion->title = $sNewTitle;
            }
            $attempts = 0;
            // Try to fix question title for unique question code enforcement
            while (!$oQuestion->validate(array('title'))) {
                if (!isset($index)) {
                    $index = 0;
                    $rand = mt_rand(0, 1024);
                } else {
                    $index++;
                }
                $sNewTitle = 'r' . $rand . 'q' . $index;
                $oQuestion->title = $sNewTitle;
                $attempts++;
                if ($attempts > 10) {
                    safeDie($clang->gT("Error") . ": Failed to resolve question code problems after 10 attempts.<br />");
                }
            }
            if (!$oQuestion->save()) {
                // safeDie($clang->gT("Error while saving: "). print_r($oQuestion->errors, true));
                //
                // In PHP 5.2.10 a bug is triggered that resets the foreach loop when inserting a record
                // Problem is that it is the default PHP version on Ubuntu 12.04 LTS (which is currently very common in use)
                // For this reason we ignore insertion errors (because it is most likely a duplicate)
                // and continue with the next one
                continue;
            }
            // Set a warning if question title was updated
            if (isset($sNewTitle)) {
                $results['importwarnings'][] = sprintf($clang->gT("Question code %s was updated to %s."), $sOldTitle, $sNewTitle);
                $aQuestionCodeReplacements[$sOldTitle] = $sNewTitle;
                unset($sNewTitle);
                unset($sOldTitle);
            }
            $newqid = $oQuestion->qid;
            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);
            }
            if (!$bConvertInvalidQuestionCodes) {
                $sScenario = 'archiveimport';
            } else {
                $sScenario = 'import';
            }
            $question = new Question($sScenario);
            $question->setAttributes($insertdata, false);
            // Try to fix question title for valid question code enforcement
            if (!$question->validate(array('title'))) {
                $sOldTitle = $question->title;
                $sNewTitle = preg_replace("/[^A-Za-z0-9]/", '', $sOldTitle);
                if (is_numeric(substr($sNewTitle, 0, 1))) {
                    $sNewTitle = 'sq' . $sNewTitle;
                }
                $question->title = $sNewTitle;
            }
            $attempts = 0;
            // Try to fix question title for unique question code enforcement
            while (!$question->validate(array('title'))) {
                if (!isset($index)) {
                    $index = 0;
                    $rand = mt_rand(0, 1024);
                } else {
                    $index++;
                }
                $sNewTitle = 'r' . $rand . 'sq' . $index;
                $question->title = $sNewTitle;
                $attempts++;
                if ($attempts > 10) {
                    safeDie($clang->gT("Error") . ": Failed to resolve question code problems after 10 attempts.<br />");
                }
            }
            if (!$question->save()) {
                // safeDie($clang->gT("Error while saving: "). print_r($question->errors, true));
                //
                // In PHP 5.2.10 a bug is triggered that resets the foreach loop when inserting a record
                // Problem is that it is the default PHP version on Ubuntu 12.04 LTS (which is currently very common in use)
                // For this reason we ignore insertion errors (because it is most likely a duplicate)
                // and continue with the next one
                continue;
            }
            // Set a warning if question title was updated
            if (isset($sNewTitle)) {
                $results['importwarnings'][] = sprintf($clang->gT("Title of subquestion %s was updated to %s."), $sOldTitle, $sNewTitle);
                // Maybe add the question title ?
                $aQuestionCodeReplacements[$sOldTitle] = $sNewTitle;
                unset($sNewTitle);
                unset($sOldTitle);
            }
            $newsqid = $question->qid;
            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);
            }
            if (Answer::model()->insertRecords($insertdata)) {
                $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;
            }
            // take care of renaming of date min/max adv. attributes fields
            if ($iDBVersion < 170) {
                if (isset($insertdata['attribute'])) {
                    if ($insertdata['attribute'] == 'dropdown_dates_year_max') {
                        $insertdata['attribute'] = 'date_max';
                    }
                    if ($insertdata['attribute'] == 'dropdown_dates_year_min') {
                        $insertdata['attribute'] = 'date_min';
                    }
                }
            }
            unset($insertdata['qaid']);
            if (!isset($aQIDReplacements[(int) $insertdata['qid']])) {
                continue;
            }
            $insertdata['qid'] = $aQIDReplacements[(int) $insertdata['qid']];
            // remap the qid
            if ($iDBVersion < 156 && isset($aAllAttributes[$insertdata['attribute']]['i18n']) && $aAllAttributes[$insertdata['attribute']]['i18n']) {
                foreach ($aLanguagesSupported as $sLanguage) {
                    $insertdata['language'] = $sLanguage;
                    if ($insertdata) {
                        XSSFilterArray($insertdata);
                    }
                    $result = QuestionAttribute::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data[7]<br />");
                }
            } else {
                $result = QuestionAttribute::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data[8]<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 = DefaultValue::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data[9]<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 = Condition::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data[10]<br />");
            $results['conditions']++;
        }
    }
    // TMSW Condition->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
            unset($insertdata['id']);
            // now translate any links
            $result = Assessment::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data[11]<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[12]<br />");
            $aQuotaReplacements[$oldid] = 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 = QuotaMember::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data[13]<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 = QuotaLanguageSetting::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'] = $aQIDReplacements[(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 = SurveyURLParameter::model()->insertRecord($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data[14]<br />");
            $results['survey_url_parameters']++;
        }
    }
    // Set survey rights
    Permission::model()->giveAllSurveyPermissions(Yii::app()->session['loginID'], $iNewSID);
    $aOldNewFieldmap = reverseTranslateFieldNames($iOldSID, $iNewSID, $aGIDReplacements, $aQIDReplacements);
    $results['FieldReMap'] = $aOldNewFieldmap;
    LimeExpressionManager::SetSurveyId($iNewSID);
    translateInsertansTags($iNewSID, $iOldSID, $aOldNewFieldmap);
    replaceExpressionCodes($iNewSID, $aQuestionCodeReplacements);
    if (count($aQuestionCodeReplacements)) {
        array_unshift($results['importwarnings'], "<span class='warningtitle'>" . $clang->gT('Attention: Several question codes were updated. Please check these carefully as the update  may not be perfect with customized expressions.') . '</span)>');
    }
    LimeExpressionManager::RevertUpgradeConditionsToRelevance($iNewSID);
    LimeExpressionManager::UpgradeConditionsToRelevance($iNewSID);
    $js_variables = array();
    if (!empty($question_groups['R'])) {
        $real_count = 1;
        $ideal_count = 1;
        $ought_count = 1;
        foreach ($results['FieldReMap'] as $code) {
            $value = explode('X', $code);
            if (isset($value[1]) && in_array($value[1], $question_groups['R'])) {
                if (!array_key_exists((int) $value[1], $js_variables)) {
                    $int = substr($value[2], 0, strpos($value[2], 'PC'));
                    $js_variables[$value[1]] = "var realGroupId" . $real_count . " = " . $value[1] . ";";
                    $js_variables[$value[1] . "-q"] = "var realQuestionId" . $real_count . " = " . $int . ";";
                    $real_count++;
                }
            } else {
                if (isset($value[1]) && in_array($value[1], $question_groups['I'])) {
                    if (!array_key_exists((int) $value[1], $js_variables)) {
                        $int = substr($value[2], 0, strpos($value[2], 'PC'));
                        $js_variables[$value[1]] = "var idealGroupId" . $ideal_count . " = " . $value[1] . ";";
                        $js_variables[$value[1] . "-q"] = "var idealQuestionId" . $ideal_count . " = " . $int . ";";
                        $ideal_count++;
                    }
                } else {
                    if (isset($value[1]) && in_array($value[1], $question_groups['O'])) {
                        if (!array_key_exists((int) $value[1], $js_variables)) {
                            $int = substr($value[2], 0, strpos($value[2], 'PC'));
                            $js_variables[$value[1]] = "var oughtGroupId" . $ought_count . " = " . $value[1] . ";";
                            $js_variables[$value[1] . "-q"] = "var oughtQuestionId" . $ought_count . " = " . $int . ";";
                            $ought_count++;
                        }
                    }
                }
            }
        }
        $js_variables[] = "var surveyId = " . $value[0] . ";";
    }
    if (!empty($js_variables)) {
        $pre_personal_characteristics = str_replace("[REPLACE_ME]", implode(PHP_EOL, $js_variables), $pre_personal_characteristics);
    } else {
        $pre_personal_characteristics = '<div {QUESTION_ESSENTIALS} class="{QUESTION_CLASS}{QUESTION_MAN_CLASS}{QUESTION_INPUT_ERROR_CLASS}">
          <div class="survey-question">
            <div class="survey-question-text">
                  <span class="asterisk">{QUESTION_MANDATORY}</span><span class="qnumcode"> {QUESTION_NUMBER} {QUESTION_CODE} </span>{QUESTION_TEXT}<br /><span class="questionhelp">{QUESTION_HELP}</span>
              {QUESTION_MAN_MESSAGE}
              {QUESTION_VALID_MESSAGE}
              {QUESTION_FILE_VALID_MESSAGE}
            </div>
            <div class="survey-question-answer">{ANSWER}</div>
            <div class="survey-question-help">{QUESTIONHELP}</div>
          </div>
          <div class="survey-question-space"></div>
        </div>';
    }
    file_put_contents($newdirname . "/question.pstpl", $pre_personal_characteristics);
    return $results;
}
 /**
  * register::index()
  * Process register form data and take appropriate action
  * @return
  */
 function actionIndex($surveyid = null)
 {
     Yii::app()->loadHelper('database');
     Yii::app()->loadHelper('replacements');
     $postlang = Yii::app()->request->getPost('lang');
     if ($surveyid == null) {
         $surveyid = Yii::app()->request->getPost('sid');
     }
     if (!$surveyid) {
         Yii::app()->request->redirect(Yii::app()->baseUrl);
     }
     // Get passed language from form, so that we dont loose this!
     if (!isset($postlang) || $postlang == "" || !$postlang) {
         $baselang = Survey::model()->findByPk($surveyid)->language;
         Yii::import('application.libraries.Limesurvey_lang');
         Yii::app()->lang = new Limesurvey_lang($baselang);
         $clang = Yii::app()->lang;
     } else {
         Yii::import('application.libraries.Limesurvey_lang');
         Yii::app()->lang = new Limesurvey_lang($postlang);
         $clang = Yii::app()->lang;
         $baselang = $postlang;
     }
     $thissurvey = getSurveyInfo($surveyid, $baselang);
     $register_errormsg = "";
     // Check the security question's answer
     if (function_exists("ImageCreate") && isCaptchaEnabled('registrationscreen', $thissurvey['usecaptcha'])) {
         if (!isset($_POST['loadsecurity']) || !isset($_SESSION['survey_' . $surveyid]['secanswer']) || Yii::app()->request->getPost('loadsecurity') != $_SESSION['survey_' . $surveyid]['secanswer']) {
             $register_errormsg .= $clang->gT("The answer to the security question is incorrect.") . "<br />\n";
         }
     }
     //Check that the email is a valid style address
     if (!validateEmailAddress(Yii::app()->request->getPost('register_email'))) {
         $register_errormsg .= $clang->gT("The email you used is not valid. Please try again.");
     }
     // Check for additional fields
     $attributeinsertdata = array();
     foreach (GetParticipantAttributes($surveyid) as $field => $data) {
         if (empty($data['show_register']) || $data['show_register'] != 'Y') {
             continue;
         }
         $value = sanitize_xss_string(Yii::app()->request->getPost('register_' . $field));
         if (trim($value) == '' && $data['mandatory'] == 'Y') {
             $register_errormsg .= sprintf($clang->gT("%s cannot be left empty"), $thissurvey['attributecaptions'][$field]);
         }
         $attributeinsertdata[$field] = $value;
     }
     if ($register_errormsg != "") {
         $_SESSION['survey_' . $surveyid]['register_errormsg'] = $register_errormsg;
         Yii::app()->request->redirect(Yii::app()->createUrl('survey/index/sid/' . $surveyid));
     }
     //Check if this email already exists in token database
     $query = "SELECT email FROM {{tokens_{$surveyid}}}\n" . "WHERE email = '" . sanitize_email(Yii::app()->request->getPost('register_email')) . "'";
     $usrow = Yii::app()->db->createCommand($query)->queryRow();
     if ($usrow) {
         $register_errormsg = $clang->gT("The email you used has already been registered.");
         $_SESSION['survey_' . $surveyid]['register_errormsg'] = $register_errormsg;
         Yii::app()->request->redirect(Yii::app()->createUrl('survey/index/sid/' . $surveyid));
         //include "index.php";
         //exit;
     }
     $mayinsert = false;
     // Get the survey settings for token length
     //$this->load->model("surveys_model");
     $tlresult = Survey::model()->findAllByAttributes(array("sid" => $surveyid));
     if (isset($tlresult[0])) {
         $tlrow = $tlresult[0];
     } else {
         $tlrow = $tlresult;
     }
     $tokenlength = $tlrow['tokenlength'];
     //if tokenlength is not set or there are other problems use the default value (15)
     if (!isset($tokenlength) || $tokenlength == '') {
         $tokenlength = 15;
     }
     while ($mayinsert != true) {
         $newtoken = randomChars($tokenlength);
         $ntquery = "SELECT * FROM {{tokens_{$surveyid}}} WHERE token='{$newtoken}'";
         $usrow = Yii::app()->db->createCommand($ntquery)->queryRow();
         if (!$usrow) {
             $mayinsert = true;
         }
     }
     $postfirstname = sanitize_xss_string(strip_tags(Yii::app()->request->getPost('register_firstname')));
     $postlastname = sanitize_xss_string(strip_tags(Yii::app()->request->getPost('register_lastname')));
     $starttime = sanitize_xss_string(Yii::app()->request->getPost('startdate'));
     $endtime = sanitize_xss_string(Yii::app()->request->getPost('enddate'));
     /*$postattribute1=sanitize_xss_string(strip_tags(returnGlobal('register_attribute1')));
       $postattribute2=sanitize_xss_string(strip_tags(returnGlobal('register_attribute2')));   */
     // Insert new entry into tokens db
     Tokens_dynamic::sid($thissurvey['sid']);
     $token = new Tokens_dynamic();
     $token->firstname = $postfirstname;
     $token->lastname = $postlastname;
     $token->email = Yii::app()->request->getPost('register_email');
     $token->emailstatus = 'OK';
     $token->token = $newtoken;
     if ($starttime && $endtime) {
         $token->validfrom = $starttime;
         $token->validuntil = $endtime;
     }
     foreach ($attributeinsertdata as $k => $v) {
         $token->{$k} = $v;
     }
     $result = $token->save();
     /**
     $result = $connect->Execute($query, array($postfirstname,
     $postlastname,
     returnGlobal('register_email'),
     'OK',
     $newtoken)
     
     //                             $postattribute1,   $postattribute2)
     ) or safeDie ($query."<br />".$connect->ErrorMsg());  //Checked - According to adodb docs the bound variables are quoted automatically
     */
     $tid = getLastInsertID($token->tableName());
     $fieldsarray["{ADMINNAME}"] = $thissurvey['adminname'];
     $fieldsarray["{ADMINEMAIL}"] = $thissurvey['adminemail'];
     $fieldsarray["{SURVEYNAME}"] = $thissurvey['name'];
     $fieldsarray["{SURVEYDESCRIPTION}"] = $thissurvey['description'];
     $fieldsarray["{FIRSTNAME}"] = $postfirstname;
     $fieldsarray["{LASTNAME}"] = $postlastname;
     $fieldsarray["{EXPIRY}"] = $thissurvey["expiry"];
     $message = $thissurvey['email_register'];
     $subject = $thissurvey['email_register_subj'];
     $from = "{$thissurvey['adminname']} <{$thissurvey['adminemail']}>";
     if (getEmailFormat($surveyid) == 'html') {
         $useHtmlEmail = true;
         $surveylink = $this->createAbsoluteUrl($surveyid . '/lang-' . $baselang . '/tk-' . $newtoken);
         $optoutlink = $this->createAbsoluteUrl('optout/local/' . $surveyid . '/' . $baselang . '/' . $newtoken);
         $optinlink = $this->createAbsoluteUrl('optin/local/' . $surveyid . '/' . $baselang . '/' . $newtoken);
         $fieldsarray["{SURVEYURL}"] = "<a href='{$surveylink}'>" . $surveylink . "</a>";
         $fieldsarray["{OPTOUTURL}"] = "<a href='{$optoutlink}'>" . $optoutlink . "</a>";
         $fieldsarray["{OPTINURL}"] = "<a href='{$optinlink}'>" . $optinlink . "</a>";
     } else {
         $useHtmlEmail = false;
         $fieldsarray["{SURVEYURL}"] = $this->createAbsoluteUrl('' . $surveyid . '/lang-' . $baselang . '/tk-' . $newtoken);
         $fieldsarray["{OPTOUTURL}"] = $this->createAbsoluteUrl('optout/local/' . $surveyid . '/' . $baselang . '/' . $newtoken);
         $fieldsarray["{OPTINURL}"] = $this->createAbsoluteUrl('optin/local/' . $surveyid . '/' . $baselang . '/' . $newtoken);
     }
     $message = ReplaceFields($message, $fieldsarray);
     $subject = ReplaceFields($subject, $fieldsarray);
     $html = "";
     //Set variable
     $sitename = Yii::app()->getConfig('sitename');
     if (SendEmailMessage($message, $subject, Yii::app()->request->getPost('register_email'), $from, $sitename, $useHtmlEmail, getBounceEmail($surveyid))) {
         // TLR change to put date into sent
         $today = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i", Yii::app()->getConfig('timeadjust'));
         $query = "UPDATE {{tokens_{$surveyid}}}\n" . "SET sent='{$today}' WHERE tid={$tid}";
         $result = dbExecuteAssoc($query) or show_error("Unable to execute this query : {$query}<br />");
         //Checked
         $html = "<center>" . $clang->gT("Thank you for registering to participate in this survey.") . "<br /><br />\n" . $clang->gT("An email has been sent to the address you provided with access details for this survey. Please follow the link in that email to proceed.") . "<br /><br />\n" . $clang->gT("Survey administrator") . " {ADMINNAME} ({ADMINEMAIL})";
         $html = ReplaceFields($html, $fieldsarray);
         $html .= "<br /><br /></center>\n";
     } else {
         $html = "Email Error";
     }
     //PRINT COMPLETED PAGE
     if (!$thissurvey['template']) {
         $thistpl = getTemplatePath(validateTemplateDir('default'));
     } else {
         $thistpl = getTemplatePath(validateTemplateDir($thissurvey['template']));
     }
     sendCacheHeaders();
     doHeader();
     Yii::app()->lang = $clang;
     // fetch the defined variables and pass it to the header footer templates.
     $redata = compact(array_keys(get_defined_vars()));
     $this->_printTemplateContent($thistpl . '/startpage.pstpl', $redata, __LINE__);
     $this->_printTemplateContent($thistpl . '/survey.pstpl', $redata, __LINE__);
     echo $html;
     $this->_printTemplateContent($thistpl . '/endpage.pstpl', $redata, __LINE__);
     doFooter();
 }
Example #7
0
 function copyToCentral($surveyid, $aAttributesToBeCreated, $aMapped, $overwriteauto = false, $overwriteman = false, $createautomap = true)
 {
     $tokenid = Yii::app()->session['participantid'];
     //List of token_id's to add to participants table
     $duplicate = 0;
     $sucessfull = 0;
     $writearray = array();
     $attid = array();
     //Will store the CPDB attribute_id of new or existing attributes keyed by CPDB at
     $pid = "";
     /* Grab all the existing attribute field names from the tokens table */
     $arr = Yii::app()->db->createCommand()->select('*')->from("{{tokens_{$surveyid}}}")->queryRow();
     if (is_array($arr)) {
         $tokenfieldnames = array_keys($arr);
         $tokenattributefieldnames = array_filter($tokenfieldnames, 'filterForAttributes');
     } else {
         $tokenattributefieldnames = array();
     }
     /* Create CPDB attributes */
     if (!empty($aAttributesToBeCreated)) {
         foreach ($aAttributesToBeCreated as $key => $value) {
             /* $key is the fieldname from the token table (ie "attribute_1")
              * $value is the 'friendly name' for the attribute (ie "Gender")
              */
             $insertnames = array('attribute_type' => 'TB', 'visible' => 'Y', 'defaultname' => $value);
             Yii::app()->db->createCommand()->insert('{{participant_attribute_names}}', $insertnames);
             $attid[$key] = $aAttributesToBeCreated[$key] = getLastInsertID('{{participant_attribute_names}}');
             /* eg $attid['attribute_1']='8372' */
             $insertnameslang = array('attribute_id' => $attid[$key], 'attribute_name' => urldecode($value), 'lang' => Yii::app()->session['adminlang']);
             Yii::app()->db->createCommand()->insert('{{participant_attribute_names_lang}}', $insertnameslang);
         }
     }
     /* Add the participants to the CPDB = Iterate through each $tokenid and create the new CPDB id*/
     foreach ($tokenid as $key => $tid) {
         if (is_numeric($tid) && $tid != "") {
             /* Get the data for this participant from the tokens table */
             $tobeinserted = Yii::app()->db->createCommand()->select('participant_id,firstname,lastname,email,language')->where('tid = :tid')->from('{{tokens_' . intval($surveyid) . '}}')->bindParam(":tid", $tid, PDO::PARAM_INT)->queryRow();
             /* See if there are any existing CPDB entries that match on firstname,lastname and email */
             $query = Yii::app()->db->createCommand()->select('*')->from('{{participants}}')->where('firstname = :firstname AND lastname = :lastname AND email = :email')->bindParam(":firstname", $tobeinserted['firstname'], PDO::PARAM_STR)->bindParam(":lastname", $tobeinserted['lastname'], PDO::PARAM_STR)->bindParam(":email", $tobeinserted['email'], PDO::PARAM_STR)->queryAll();
             /* If there is already an existing entry, add to the duplicate count */
             if (count($query) > 0) {
                 $duplicate++;
                 if ($overwriteman == "true" && !empty($aMapped)) {
                     foreach ($aMapped as $cpdbatt => $tatt) {
                         Participant::model()->updateAttributeValueToken($surveyid, $query[0]['participant_id'], $cpdbatt, $tatt);
                     }
                 }
             } else {
                 /* Create entry in participants table */
                 $black = !empty($tobeinserted['blacklisted']) ? $tobeinserted['blacklisted'] : 'N';
                 $pid = !empty($tobeinserted['participant_id']) ? $tobeinserted['participant_id'] : $this->gen_uuid();
                 $writearray = array('participant_id' => $pid, 'firstname' => $tobeinserted['firstname'], 'lastname' => $tobeinserted['lastname'], 'email' => $tobeinserted['email'], 'language' => $tobeinserted['language'], 'blacklisted' => $black, 'owner_uid' => Yii::app()->session['loginID'], 'created_by' => Yii::app()->session['loginID'], 'created' => date('Y-m-d H:i:s', time()));
                 Yii::app()->db->createCommand()->insert('{{participants}}', $writearray);
                 //Update token table and insert the new UUID
                 $data = array("participant_id" => $pid);
                 Yii::app()->db->createCommand()->update('{{tokens_' . intval($surveyid) . '}}', $data, "tid = {$tid}");
                 /* Now add any new attribute values */
                 if (!empty($aAttributesToBeCreated)) {
                     foreach ($aAttributesToBeCreated as $key => $value) {
                         Participant::model()->updateAttributeValueToken($surveyid, $pid, $attid[$key], $key);
                     }
                 }
                 /* Now add mapped attribute values */
                 if (!empty($aMapped)) {
                     foreach ($aMapped as $cpdbatt => $tatt) {
                         Participant::model()->updateAttributeValueToken($surveyid, $pid, $cpdbatt, $tatt);
                     }
                 }
                 $sucessfull++;
                 /* Create a survey_link */
                 $data = array('participant_id' => $pid, 'token_id' => $tid, 'survey_id' => $surveyid, 'date_created' => date('Y-m-d H:i:s', time()));
                 Yii::app()->db->createCommand()->insert('{{survey_links}}', $data);
             }
         }
     }
     if ($createautomap == "true") {
         $aAttributes = Survey::model()->findByPk($surveyid)->tokenattributes;
         if (!empty($aAttributesToBeCreated)) {
             // If automapping is enabled then update the token field properties with the mapped CPDB field ID
             foreach ($aAttributesToBeCreated as $tatt => $cpdbatt) {
                 $aAttributes[$tatt]['cpdbmap'] = $cpdbatt;
             }
             Yii::app()->db->createCommand()->update('{{surveys}}', array("attributedescriptions" => json_encode($aAttributes)), 'sid = ' . $surveyid);
         }
         if (!empty($aMapped)) {
             foreach ($aMapped as $cpdbatt => $tatt) {
                 // Update the attributedescriptions so future mapping can be done automatically
                 $aAttributes[$tatt]['cpdbmap'] = $cpdbatt;
             }
             Yii::app()->db->createCommand()->update('{{surveys}}', array("attributedescriptions" => json_encode($aAttributes)), 'sid = ' . $surveyid);
         }
     }
     $returndata = array('success' => $sucessfull, 'duplicate' => $duplicate, 'overwriteauto' => $overwriteauto, 'overwriteman' => $overwriteman);
     return $returndata;
 }
Example #8
0
 function savedcontrol()
 {
     //This data will be saved to the "saved_control" table with one row per response.
     // - a unique "saved_id" value (autoincremented)
     // - the "sid" for this survey
     // - the "srid" for the survey_x row id
     // - "saved_thisstep" which is the step the user is up to in this survey
     // - "saved_ip" which is the ip address of the submitter
     // - "saved_date" which is the date ofthe saved response
     // - an "identifier" which is like a username
     // - a "password"
     // - "fieldname" which is the fieldname of the saved response
     // - "value" which is the value of the response
     //We start by generating the first 5 values which are consistent for all rows.
     global $surveyid, $thissurvey, $errormsg, $publicurl, $sitename, $clang, $clienttoken, $thisstep;
     $timeadjust = getGlobalSetting('timeadjust');
     //Check that the required fields have been completed.
     $errormsg = '';
     if (empty($_POST['savename'])) {
         $errormsg .= $clang->gT("You must supply a name for this saved session.") . "<br />\n";
     }
     if (empty($_POST['savepass'])) {
         $errormsg .= $clang->gT("You must supply a password for this saved session.") . "<br />\n";
     }
     if (empty($_POST['savepass']) || empty($_POST['savepass2']) || $_POST['savepass'] != $_POST['savepass2']) {
         $errormsg .= $clang->gT("Your passwords do not match.") . "<br />\n";
     }
     // if security question asnwer is incorrect
     if (function_exists("ImageCreate") && isCaptchaEnabled('saveandloadscreen', $thissurvey['usecaptcha'])) {
         if (empty($_POST['loadsecurity']) || !isset($_SESSION['survey_' . $surveyid]['secanswer']) || $_POST['loadsecurity'] != $_SESSION['survey_' . $surveyid]['secanswer']) {
             $errormsg .= $clang->gT("The answer to the security question is incorrect.") . "<br />\n";
         }
     }
     if (!empty($errormsg)) {
         return;
     }
     $duplicate = SavedControl::model()->findByAttributes(array('sid' => $surveyid, 'identifier' => $_POST['savename']));
     if (!empty($duplicate) && $duplicate->count() > 0) {
         $errormsg .= $clang->gT("This name has already been used for this survey. You must use a unique save name.") . "<br />\n";
         return;
     } else {
         //INSERT BLANK RECORD INTO "survey_x" if one doesn't already exist
         if (!isset($_SESSION['survey_' . $surveyid]['srid'])) {
             $today = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust);
             $sdata = array("datestamp" => $today, "ipaddr" => getIPAddress(), "startlanguage" => $_SESSION['survey_' . $surveyid]['s_lang'], "refurl" => getenv("HTTP_REFERER"));
             if (SurveyDynamic::model($thissurvey['sid'])->insert($sdata)) {
                 $srid = getLastInsertID('{{survey_' . $surveyid . '}}');
                 $_SESSION['survey_' . $surveyid]['srid'] = $srid;
             } else {
                 safeDie("Unable to insert record into survey table.<br /><br />");
             }
         }
         //CREATE ENTRY INTO "saved_control"
         $today = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust);
         $saved_control = new SavedControl();
         $saved_control->sid = $surveyid;
         $saved_control->srid = $_SESSION['survey_' . $surveyid]['srid'];
         $saved_control->identifier = $_POST['savename'];
         // Binding does escape, so no quoting/escaping necessary
         $saved_control->access_code = md5($_POST['savepass']);
         $saved_control->email = $_POST['saveemail'];
         $saved_control->ip = getIPAddress();
         $saved_control->saved_thisstep = $thisstep;
         $saved_control->status = 'S';
         $saved_control->saved_date = $today;
         $saved_control->refurl = getenv('HTTP_REFERER');
         if ($saved_control->save()) {
             $scid = getLastInsertID('{{saved_control}}');
             $_SESSION['survey_' . $surveyid]['scid'] = $scid;
         } else {
             safeDie("Unable to insert record into saved_control table.<br /><br />");
         }
         $_SESSION['survey_' . $surveyid]['holdname'] = $_POST['savename'];
         //Session variable used to load answers every page. Unsafe - so it has to be taken care of on output
         $_SESSION['survey_' . $surveyid]['holdpass'] = $_POST['savepass'];
         //Session variable used to load answers every page. Unsafe - so it has to be taken care of on output
         //Email if needed
         if (isset($_POST['saveemail']) && validateEmailAddress($_POST['saveemail'])) {
             $subject = $clang->gT("Saved Survey Details") . " - " . $thissurvey['name'];
             $message = $clang->gT("Thank you for saving your survey in progress.  The following details can be used to return to this survey and continue where you left off.  Please keep this e-mail for your reference - we cannot retrieve the password for you.");
             $message .= "\n\n" . $thissurvey['name'] . "\n\n";
             $message .= $clang->gT("Name") . ": " . $_POST['savename'] . "\n";
             $message .= $clang->gT("Password") . ": " . $_POST['savepass'] . "\n\n";
             $message .= $clang->gT("Reload your survey by clicking on the following link (or pasting it into your browser):") . "\n";
             $message .= Yii::app()->getController()->createAbsoluteUrl("/survey/index/sid/{$surveyid}/loadall/reload/scid/{$scid}/loadname/" . rawurlencode($_POST['savename']) . "/loadpass/" . rawurlencode($_POST['savepass']) . "/lang/" . rawurlencode($clang->langcode));
             if ($clienttoken) {
                 $message .= "/token/" . rawurlencode($clienttoken);
             }
             $from = "{$thissurvey['adminname']} <{$thissurvey['adminemail']}>";
             if (SendEmailMessage($message, $subject, $_POST['saveemail'], $from, $sitename, false, getBounceEmail($surveyid))) {
                 $emailsent = "Y";
             } else {
                 $errormsg .= $clang->gT('Error: Email failed, this may indicate a PHP Mail Setup problem on the server. Your survey details have still been saved, however you will not get an email with the details. You should note the "name" and "password" you just used for future reference.');
                 if (trim($thissurvey['adminemail']) == '') {
                     $errormsg .= $clang->gT('(Reason: Admin email address empty)');
                 }
             }
         }
         return $clang->gT('Your survey was successfully saved.');
     }
 }
 function storeAttributeCSV($data)
 {
     $insertnames = array('attribute_type' => $data['attribute_type'], 'visible' => $data['visible']);
     Yii::app()->db->createCommand()->insert('{{participant_attribute_names}}', $insertnames);
     $insertid = getLastInsertID($this->tableName());
     $insertnameslang = array('attribute_id' => $insertid, 'attribute_name' => $data['attribute_name'], 'lang' => Yii::app()->session['adminlang']);
     Yii::app()->db->createCommand()->insert('{{participant_attribute_names_lang}}', $insertnameslang);
     return $insertid;
 }
 function addGroup($group_name, $group_description)
 {
     $iLoginID = intval(Yii::app()->session['loginID']);
     $iquery = "INSERT INTO {{user_groups}} (name, description, owner_id) VALUES(:group_name, :group_desc, :loginID)";
     $command = Yii::app()->db->createCommand($iquery)->bindParam(":group_name", $group_name, PDO::PARAM_STR)->bindParam(":group_desc", $group_description, PDO::PARAM_STR)->bindParam(":loginID", $iLoginID, PDO::PARAM_INT);
     $result = $command->query();
     if ($result) {
         //Checked
         $id = getLastInsertID($this->tableName());
         //Yii::app()->db->Insert_Id(db_table_name_nq('user_groups'),'ugid');
         if ($id > 0) {
             $user_in_groups_query = 'INSERT INTO {{user_in_groups}} (ugid, uid) VALUES (:ugid, :uid)';
             $command = Yii::app()->db->createCommand($user_in_groups_query)->bindParam(":ugid", $id, PDO::PARAM_INT)->bindParam(":uid", $iLoginID, PDO::PARAM_INT)->query();
         }
         return $id;
     } else {
         return -1;
     }
 }
Example #11
0
 function copyToCentral($surveyid, $newarr, $mapped, $overwriteauto = false, $overwriteman = false, $createautomap = true)
 {
     $tokenid = Yii::app()->session['participantid'];
     //List of token_id's to add to participants table
     $duplicate = 0;
     $sucessfull = 0;
     $writearray = array();
     $attid = array();
     //Will store the CPDB attribute_id of new or existing attributes keyed by CPDB at
     $pid = "";
     /* Grab all the existing attribute field names from the tokens table */
     $arr = Yii::app()->db->createCommand()->select('*')->from("{{tokens_{$surveyid}}}")->queryRow();
     if (is_array($arr)) {
         $tokenfieldnames = array_keys($arr);
         $tokenattributefieldnames = array_filter($tokenfieldnames, 'filterForAttributes');
     } else {
         $tokenattributefieldnames = array();
     }
     /* Automatically mapped attribute names are named "attribute_cpdb_[some_number]" */
     foreach ($tokenattributefieldnames as $key => $value) {
         if ($value[10] == 'c') {
             $autoattid = substr($value, 15);
             $mapped[$autoattid] = $value;
         }
     }
     /* Create new CPDB attributes */
     if (!empty($newarr)) {
         foreach ($newarr as $key => $value) {
             /* $key is the fieldname from the token table (ie "attribute_1")
              * $value is the 'friendly name' for the attribute (ie "Gender")
              */
             $insertnames = array('attribute_type' => 'TB', 'visible' => 'Y');
             Yii::app()->db->createCommand()->insert('{{participant_attribute_names}}', $insertnames);
             $attid[$key] = getLastInsertID('{{participant_attribute_names}}');
             /* eg $attid['attribute_1']='8372' */
             $insertnameslang = array('attribute_id' => $attid[$key], 'attribute_name' => urldecode($value), 'lang' => Yii::app()->session['adminlang']);
             Yii::app()->db->createCommand()->insert('{{participant_attribute_names_lang}}', $insertnameslang);
         }
     }
     /* Add the participants to the CPDB = Iterate through each $tokenid and create the new CPDB id*/
     foreach ($tokenid as $key => $tid) {
         if (is_numeric($tid) && $tid != "") {
             /* Get the data for this participant from the tokens table */
             $tobeinserted = Yii::app()->db->createCommand()->select('participant_id,firstname,lastname,email,language')->where('tid = :tid')->from('{{tokens_' . intval($surveyid) . '}}')->bindParam(":tid", $tid, PDO::PARAM_INT)->queryRow();
             /* See if there are any existing CPDB entries that match on firstname,lastname and email */
             $query = Yii::app()->db->createCommand()->select('*')->from('{{participants}}')->where('firstname = :firstname AND lastname = :lastname AND email = :email')->bindParam(":firstname", $tobeinserted['firstname'], PDO::PARAM_STR)->bindParam(":lastname", $tobeinserted['lastname'], PDO::PARAM_STR)->bindParam(":email", $tobeinserted['email'], PDO::PARAM_STR)->queryAll();
             /* If there is already an existing entry, add to the duplicate count */
             if (count($query) > 0) {
                 $duplicate++;
                 //HERE is where we can add "overwrite" feature to update attribute values for existing participants
                 if ($overwriteauto == "true") {
                     if (!empty($newarr)) {
                         foreach ($newarr as $key => $value) {
                             Participants::model()->updateAttributeValueToken($surveyid, $query[0]['participant_id'], $attid[$key], $key);
                         }
                     }
                 }
                 if ($overwriteman == "true") {
                     /* Now add mapped attribute values */
                     if (!empty($mapped)) {
                         foreach ($mapped as $cpdbatt => $tatt) {
                             Participants::model()->updateAttributeValueToken($surveyid, $query[0]['participant_id'], $cpdbatt, $tatt);
                         }
                     }
                 }
             } else {
                 /* Create entry in participants table */
                 $black = !empty($tobeinserted['blacklisted']) ? $tobeinserted['blacklised'] : 'N';
                 $pid = !empty($tobeinserted['participant_id']) ? $tobeinserted['participant_id'] : $this->gen_uuid();
                 $writearray = array('participant_id' => $pid, 'firstname' => $tobeinserted['firstname'], 'lastname' => $tobeinserted['lastname'], 'email' => $tobeinserted['email'], 'language' => $tobeinserted['language'], 'blacklisted' => $black, 'owner_uid' => Yii::app()->session['loginID']);
                 Yii::app()->db->createCommand()->insert('{{participants}}', $writearray);
                 //Update token table and insert the new UUID
                 $data = array("participant_id" => $pid);
                 Yii::app()->db->createCommand()->update('{{tokens_' . intval($surveyid) . '}}', $data, "tid = {$tid}");
                 /* Now add any new attribute values */
                 if (!empty($newarr)) {
                     foreach ($newarr as $key => $value) {
                         Participants::model()->updateAttributeValueToken($surveyid, $pid, $attid[$key], $key);
                     }
                 }
                 /* Now add mapped attribute values */
                 if (!empty($mapped)) {
                     foreach ($mapped as $cpdbatt => $tatt) {
                         Participants::model()->updateAttributeValueToken($surveyid, $pid, $cpdbatt, $tatt);
                     }
                 }
                 $sucessfull++;
                 /* Create a survey_link */
                 $data = array('participant_id' => $pid, 'token_id' => $tid, 'survey_id' => $surveyid, 'date_created' => date('Y-m-d H:i:s', time()));
                 Yii::app()->db->createCommand()->insert('{{survey_links}}', $data);
             }
         }
     }
     if (!empty($newarr)) {
         /* Rename the token attribute fields to a cpdb field, so in future
          * we know that it belongs to a CPDB field */
         foreach ($newarr as $key => $value) {
             $newname = 'attribute_cpdb_' . intval($attid[$key]);
             $fields = array($value => array('name' => $newname, 'type' => 'TEXT'));
             //Rename the field in the tokens_[sid] table
             Yii::app()->db->createCommand()->renameColumn('{{tokens_' . intval($surveyid) . '}}', $key, $newname);
             //Make the field a TEXT field
             Yii::app()->db->createCommand()->alterColumn('{{tokens_' . intval($surveyid) . '}}', $newname, 'TEXT');
             $previousatt = Yii::app()->db->createCommand()->select('attributedescriptions')->from('{{surveys}}')->where("sid = " . $surveyid);
             $patt = $previousatt->queryRow();
             $previousattribute = unserialize($patt['attributedescriptions']);
             $previousattribute[$newname] = $previousattribute[$key];
             unset($previousattribute[$key]);
             $previousattribute = serialize($previousattribute);
             Yii::app()->db->createCommand()->update('{{surveys}}', array("attributedescriptions" => $previousattribute), 'sid = ' . $surveyid);
             //load description in the surveys table
         }
     }
     if (!empty($mapped)) {
         foreach ($mapped as $cpdbatt => $tatt) {
             if ($tatt[10] != 'c' && $createautomap == "true") {
                 // Change the fieldname in the token table to attribute_cpdb_[participant_attribute_id]
                 // so future mapping is done automatically
                 $newname = 'attribute_cpdb_' . $cpdbatt;
                 $fields = array($tatt => array('name' => $newname, 'type' => 'TEXT'));
                 Yii::app()->db->createCommand()->renameColumn('{{tokens_' . intval($surveyid) . '}}', $tatt, $newname);
                 Yii::app()->db->createCommand()->alterColumn('{{tokens_' . intval($surveyid) . '}}', $newname, 'TEXT');
                 $previousatt = Yii::app()->db->createCommand()->select('attributedescriptions')->from('{{surveys}}')->where("sid = :sid")->bindParam(":sid", $surveyid, PDO::PARAM_INT);
                 $previousattribute = $previousatt->queryRow();
                 $previousattribute = unserialize($previousattribute['attributedescriptions']);
                 $previousattribute[$newname] = $previousattribute[$tatt];
                 unset($previousattribute[$tatt]);
                 //Rename the token field the name of the participant_attribute
                 $attributedetails = ParticipantAttributeNames::model()->getAttributeNames($cpdbatt);
                 $previousattribute[$newname]['description'] = $attributedetails[0]['attribute_name'];
                 $previousattribute = serialize($previousattribute);
                 //$newstring = str_replace($tatt, $newname, $previousattribute['attributedescriptions']);
                 Yii::app()->db->createCommand()->update('{{surveys}}', array("attributedescriptions" => $previousattribute), 'sid = ' . $surveyid);
             }
         }
     }
     $returndata = array('success' => $sucessfull, 'duplicate' => $duplicate, 'overwriteauto' => $overwriteauto, 'overwriteman' => $overwriteman);
     return $returndata;
 }