Example #1
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;
 }
 function addToTokenattmap()
 {
     $iParticipantId = Yii::app()->request->getPost('participant_id');
     $iSurveyId = Yii::app()->request->getPost('surveyid');
     $mapped = Yii::app()->request->getPost('mapped');
     $newcreate = Yii::app()->request->getPost('newarr');
     $overwriteauto = Yii::app()->request->getPost('overwrite');
     $overwriteman = Yii::app()->request->getPost('overwriteman');
     $overwritest = Yii::app()->request->getPost('overwritest');
     $createautomap = Yii::app()->request->getPost('createautomap');
     $clang = $this->getController()->lang;
     if (empty($newcreate[0])) {
         $newcreate = array();
     }
     $response = Participant::model()->copyCPBDAttributesToTokens($iSurveyId, $mapped, $newcreate, $iParticipantId, $overwriteauto, $overwriteman, $overwritest, $createautomap);
     printf($clang->gT("%s participants have been copied to the survey token table"), $response['success']);
     if ($response['duplicate'] > 0) {
         echo "\r\n";
         printf($clang->gT("%s entries were not copied because they already existed"), $response['duplicate']);
     }
     if ($response['overwriteauto'] == "true" || $response['overwriteman'] == "true") {
         echo "\r\n";
         $clang->eT("Attribute values for existing participants have been updated from the participants records");
     }
 }
 /**
  * Retrieves Participant data
  * @param $iParticipantID int The Participant ID
  * Returns null if the user does not exist anymore for some reason (should not really happen)
  * @return User
  */
 public function getParticipant($iParticipantID)
 {
     return Participant::model()->findByPk($iParticipantID);
 }
 /**
  * Responsible for adding the participant to the specified survey with attribute mapping
  * Used when mapping CPDB participants to survey tokens with attributes.
  * Called when user clicks "Continue" in that form.
  *
  * Echoes a result message witch will be displayed as a bootstrap modal
  *
  * @return void
  */
 public function addToTokenattmap()
 {
     $participantIdsString = Yii::app()->request->getPost('participant_id');
     // TODO: This is a comma separated string of ids
     $participantIds = explode(",", $participantIdsString);
     $surveyId = Yii::app()->request->getPost('surveyid');
     /**
      * mapped can take values like
      *   mapped[attribute_38] = 39
      * meaning that an attribute is mapped onto another.
      */
     $mappedAttributes = Yii::app()->request->getPost('mapped');
     /**
      * newarr takes values like
      *   newarr[] = 39
      */
     $newAttributes = Yii::app()->request->getPost('newarr');
     $options = array();
     $options['overwriteauto'] = Yii::app()->request->getPost('overwrite') === 'true';
     $options['overwriteman'] = Yii::app()->request->getPost('overwriteman') === 'true';
     $options['overwritest'] = Yii::app()->request->getPost('overwritest') === 'true';
     $options['createautomap'] = Yii::app()->request->getPost('createautomap') === 'true';
     // TODO: Why?
     if (empty($newAttributes[0])) {
         $newAttributes = array();
     }
     if (empty($mappedAttributes)) {
         $mappedAttributes = array();
     }
     try {
         $response = Participant::model()->copyCPDBAttributesToTokens($surveyId, $participantIds, $mappedAttributes, $newAttributes, $options);
     } catch (CPDBException $e) {
         echo $e->getMessage();
         return;
     } catch (Exception $e) {
         printf("Error: Could not copy attributes to tokens: file %s, line %s; %s", $e->getFile(), $e->getLine(), $e->getMessage());
         return;
     }
     echo "<p>";
     printf(gT("%s participants have been copied to the survey token table"), "<span class='badge alert-success'>" . $response['success'] . "</span>");
     echo "</p>";
     if ($response['duplicate'] > 0) {
         echo "<p>";
         printf(gT("%s entries were not copied because they already existed"), "<span class='badge alert-warning'>" . $response['duplicate'] . "</span>");
         echo "</p>";
     }
     if ($response['blacklistskipped'] > 0) {
         echo "<p>";
         printf(gT("%s entries were skipped because they are blacklisted"), "<span class='badge alert-danger'>" . $response['blacklistskipped'] . "</span>");
         echo "</p>";
     }
     if ($response['overwriteauto'] == "true" || $response['overwriteman'] == "true") {
         echo "<p>";
         eT("Attribute values for existing participants have been updated from the participants records");
         echo "</p>";
     }
 }
 function actionparticipants()
 {
     $iSurveyID = Yii::app()->request->getQuery('surveyid');
     $sLanguageCode = Yii::app()->request->getQuery('langcode');
     $sToken = sanitize_token(Yii::app()->request->getQuery('token'));
     Yii::app()->loadHelper('database');
     Yii::app()->loadHelper('sanitize');
     if (!$iSurveyID) {
         $this->redirect(array('/'));
     }
     $iSurveyID = (int) $iSurveyID;
     //Make sure it's an integer (protect from SQL injects)
     //Check that there is a SID
     // Get passed language from form, so that we dont lose this!
     if (!isset($sLanguageCode) || $sLanguageCode == "" || !$sLanguageCode) {
         $sBaseLanguage = Survey::model()->findByPk($iSurveyID)->language;
     } else {
         $sBaseLanguage = sanitize_languagecode($sLanguageCode);
     }
     Yii::app()->setLanguage($sBaseLanguage);
     $aSurveyInfo = getSurveyInfo($iSurveyID, $sBaseLanguage);
     if ($aSurveyInfo == false || !tableExists("{{tokens_{$iSurveyID}}}")) {
         throw new CHttpException(404, "The survey in which you are trying to participate does not seem to exist. It may have been deleted or the link you were given is outdated or incorrect.");
     } else {
         LimeExpressionManager::singleton()->loadTokenInformation($iSurveyID, $sToken, false);
         $oToken = Token::model($iSurveyID)->findByAttributes(array('token' => $sToken));
         if (!isset($oToken)) {
             $sMessage = gT('You are not a participant in this survey.');
         } else {
             if (substr($oToken->emailstatus, 0, strlen('OptOut')) !== 'OptOut') {
                 $oToken->emailstatus = 'OptOut';
                 $oToken->save();
                 $sMessage = gT('You have been successfully removed from this survey.');
             } else {
                 $sMessage = gT('You have been already removed from this survey.');
             }
             if (!empty($oToken->participant_id)) {
                 //Participant also exists in central db
                 $oParticipant = Participant::model()->findByPk($oToken->participant_id);
                 if ($oParticipant->blacklisted == "Y") {
                     $sMessage .= "<br />";
                     $sMessage .= gT("You have already been removed from the central participants list for this site");
                 } else {
                     $oParticipant->blacklisted = 'Y';
                     $oParticipant->save();
                     $sMessage .= "<br />";
                     $sMessage .= gT("You have been removed from the central participants list for this site");
                 }
             }
         }
     }
     //PRINT COMPLETED PAGE
     if (!$aSurveyInfo['templatedir']) {
         $sTemplate = getTemplatePath(Yii::app()->getConfig("defaulttemplate"));
     } else {
         $sTemplate = getTemplatePath($aSurveyInfo['templatedir']);
     }
     $this->_renderHtml($sMessage, $sTemplate, $aSurveyInfo);
 }
 function actionparticipants()
 {
     $iSurveyID = Yii::app()->request->getQuery('surveyid');
     $sLanguageCode = Yii::app()->request->getQuery('langcode');
     $sToken = sanitize_token(Yii::app()->request->getQuery('token'));
     Yii::app()->loadHelper('database');
     Yii::app()->loadHelper('sanitize');
     if (!$iSurveyID) {
         $this->redirect(array('/'));
     }
     $iSurveyID = (int) $iSurveyID;
     //Make sure it's an integer (protect from SQL injects)
     //Check that there is a SID
     // Get passed language from form, so that we dont lose this!
     if (!isset($sLanguageCode) || $sLanguageCode == "" || !$sLanguageCode) {
         $sBaseLanguage = Survey::model()->findByPk($iSurveyID)->language;
         Yii::import('application.libraries.Limesurvey_lang', true);
         $clang = new Limesurvey_lang($sBaseLanguage);
     } else {
         $sLanguageCode = sanitize_languagecode($sLanguageCode);
         Yii::import('application.libraries.Limesurvey_lang', true);
         $clang = new Limesurvey_lang($sLanguageCode);
         $sBaseLanguage = $sLanguageCode;
     }
     Yii::app()->lang = $clang;
     $aSurveyInfo = getSurveyInfo($iSurveyID, $sBaseLanguage);
     if ($aSurveyInfo == false || !tableExists("{{tokens_{$iSurveyID}}}")) {
         $sMessage = $clang->gT('This survey does not seem to exist.');
     } else {
         $oToken = Token::model($iSurveyID)->findByAttributes(array('token' => $sToken));
         if (!isset($oToken)) {
             $sMessage = $clang->gT('You are not a participant in this survey.');
         } else {
             if (substr($oToken->emailstatus, 0, strlen('OptOut')) !== 'OptOut') {
                 $oToken->emailstatus = 'OptOut';
                 $oToken->save();
                 $sMessage = $clang->gT('You have been successfully removed from this survey.');
             } else {
                 $sMessage = $clang->gT('You have been already removed from this survey.');
             }
             if (!empty($oToken->participant_id)) {
                 //Participant also exists in central db
                 $oParticipant = Participant::model()->findByPk($oToken->participant_id);
                 if ($oParticipant->blacklisted == "Y") {
                     $sMessage .= "<br />";
                     $sMessage .= $clang->gT("You have already been removed from the central participants list for this site");
                 } else {
                     $oParticipant->blacklisted = 'Y';
                     $oParticipant->save();
                     $sMessage .= "<br />";
                     $sMessage .= $clang->gT("You have been removed from the central participants list for this site");
                 }
             }
         }
     }
     //PRINT COMPLETED PAGE
     if (!$aSurveyInfo['templatedir']) {
         $sTemplate = getTemplatePath(Yii::app()->getConfig("defaulttemplate"));
     } else {
         $sTemplate = getTemplatePath($aSurveyInfo['templatedir']);
     }
     $this->_renderHtml($sMessage, $sTemplate, $aSurveyInfo);
 }
Example #7
0
 /**
  * Returns all participant models for this event and all the related events for a meeting.
  * 
  * @return Participant
  */
 public function getRelatedParticipants()
 {
     //update all participants with this user and event uuid in the system
     $findParams = \GO\Base\Db\FindParams::newInstance();
     $findParams->joinModel(array('model' => 'GO\\Calendar\\Model\\Event', 'localTableAlias' => 't', 'localField' => 'event_id', 'foreignField' => 'id', 'tableAlias' => 'e'));
     $findParams->getCriteria()->addCondition('id', $this->id, '!=')->addCondition('email', $this->email)->addCondition('uuid', $this->event->uuid, '=', 'e')->addCondition('start_time', $this->event->start_time, '=', 'e')->addCondition("exception_for_event_id", 0, $this->event->exception_for_event_id == 0 ? '=' : '!=', 'e');
     //the master event or a single occurrence can start at the same time. Therefore we must check if exception event has a value or is 0.
     return Participant::model()->find($findParams);
 }
 /**
  * This function import a participant to the LimeSurvey cpd. It stores attributes as well, if they are registered before within ui
  *
  * Call the function with $response = $myJSONRPCClient->cpd_importParticipants( $sessionKey, $aParticipants);
  *
  * @param int $sSessionKey
  * @param array $aParticipants
  * [[0] => ["email"=>"*****@*****.**","firstname"=>"max","lastname"=>"mustermann"]]
  * @return array with status
  */
 public function cpd_importParticipants($sSessionKey, $aParticipants)
 {
     if (!$this->_checkSessionKey($sSessionKey)) {
         return array('status' => 'Invalid session key');
     }
     $aResponse = array();
     $aAttributeData = array();
     $aAttributes = array();
     $aDefaultFields = array('participant_id', 'firstname', 'lastname', 'email', 'language', 'blacklisted');
     $bIsValidEmail = true;
     $bDoImport = true;
     $sMandatory = 0;
     $sAttribCount = 0;
     $aResponse = array();
     $aResponse['ImportCount'] = 0;
     // get all attributes for mapping
     $oFindCriteria = new CDbCriteria();
     $oFindCriteria->offset = -1;
     $oFindCriteria->limit = -1;
     $aAttributeRecords = ParticipantAttributeName::model()->with('participant_attribute_names_lang')->findAll($oFindCriteria);
     foreach ($aParticipants as $sKey => $aParticipantData) {
         $aData = array('firstname' => $aParticipantData['firstname'], 'lastname' => $aParticipantData['lastname'], 'email' => $aParticipantData['email'], 'owner_uid' => Yii::app()->session['loginID']);
         //Check for duplicate participants
         $arRecordExists = Participant::model()->exists('firstname = :firstname AND lastname = :lastname AND email = :email AND owner_uid = :owner_uid', array(':firstname' => $aData['firstname'], ':lastname' => $aData['lastname'], ':email' => $aData['email'], ':owner_uid' => $aData['owner_uid']));
         // check if email is valid
         $this->_checkEmailFormat($aData['email']);
         if ($bIsValidEmail == true) {
             //First, process the known fields
             if (!isset($aData['participant_id']) || $aData['participant_id'] == "") {
                 //  $arParticipantModel = new Participant();
                 $aData['participant_id'] = Participant::gen_uuid();
             }
             if (isset($aData['emailstatus']) && trim($aData['emailstatus'] == '')) {
                 unset($aData['emailstatus']);
             }
             if (!isset($aData['language']) || $aData['language'] == "") {
                 $aData['language'] = "en";
             }
             if (!isset($aData['blacklisted']) || $aData['blacklisted'] == "") {
                 $aData['blacklisted'] = "N";
             }
             $aData['owner_uid'] = Yii::app()->session['loginID'];
             if (isset($aData['validfrom']) && trim($aData['validfrom'] == '')) {
                 unset($aData['validfrom']);
             }
             if (isset($aData['validuntil']) && trim($aData['validuntil'] == '')) {
                 unset($aData['validuntil']);
             }
             if (!empty($aData['email'])) {
                 //The mandatory fields of email, firstname and lastname
                 $sMandatory++;
                 $bDoImport = false;
             }
             // Write to database if record not exists
             if (empty($arRecordExists)) {
                 // save participant to database
                 Participant::model()->insertParticipantCSV($aData);
                 // Prepare atrribute values to store in db . Iterate through our values
                 foreach ($aParticipantData as $sLabel => $sAttributeValue) {
                     // skip default fields
                     if (!in_array($sLabel, $aDefaultFields)) {
                         foreach ($aAttributeRecords as $sKey => $arValue) {
                             $aAttributes = $arValue->getAttributes();
                             if ($aAttributes['defaultname'] == $sLabel) {
                                 $aAttributeData['participant_id'] = $aData['participant_id'];
                                 $aAttributeData['attribute_id'] = $aAttributes['attribute_id'];
                                 $aAttributeData['value'] = $sAttributeValue;
                                 $sAttribCount++;
                                 // save attributes values for participant
                                 ParticipantAttributeName::model()->saveParticipantAttributeValue($aAttributeData);
                             }
                         }
                     }
                 }
                 $aResponse['ImportCount']++;
             }
         }
     }
     return $aResponse;
 }
 /**
  * RPC Routine to add participants to the Central Participants Database
  * (only deletes them from the CPD and not from surveys or token tables)
  *
  * @access public
  * @param string $sSessionKey - Auth credentials
  * @param int $userName - the user to whom the participant belongs to
  * @param string $email - Participants email
  * 
  * */
 public function delete_global_participant($sSessionKey, $participantID)
 {
     // Check sessionkey
     if (!$this->_checkSessionKey($sSessionKey)) {
         return array('status' => 'Invalid session key');
     }
     if (Participant::model()->deleteParticipants($participantID)) {
         return array('status' => 'Success participant deleted');
     } else {
         return array('status' => 'Error: Failed to delete participant');
     }
 }
 function addToTokenattmap()
 {
     $iParticipantId = Yii::app()->request->getPost('participant_id');
     $iSurveyId = Yii::app()->request->getPost('surveyid');
     $mapped = Yii::app()->request->getPost('mapped');
     $newcreate = Yii::app()->request->getPost('newarr');
     $overwriteauto = Yii::app()->request->getPost('overwrite');
     $overwriteman = Yii::app()->request->getPost('overwriteman');
     $overwritest = Yii::app()->request->getPost('overwritest');
     $createautomap = Yii::app()->request->getPost('createautomap');
     if (empty($newcreate[0])) {
         $newcreate = array();
     }
     try {
         $response = Participant::model()->copyCPBDAttributesToTokens($iSurveyId, $mapped, $newcreate, $iParticipantId, $overwriteauto, $overwriteman, $overwritest, $createautomap);
     } catch (Exception $e) {
         printf("Error: Could not copy attributes to tokens: file %s, line %s; %s", $e->getFile(), $e->getLine(), $e->getMessage());
         return;
     }
     echo "<p>";
     printf(gT("%s participants have been copied to the survey token table"), "<span class='badge alert-success'>" . $response['success'] . "</span>");
     echo "</p>";
     if ($response['duplicate'] > 0) {
         echo "<p>";
         printf(gT("%s entries were not copied because they already existed"), "<span class='badge alert-warning'>" . $response['duplicate'] . "</span>");
         echo "</p>";
     }
     if ($response['blacklistskipped'] > 0) {
         echo "<p>";
         printf(gT("%s entries were skipped because they are blacklisted"), "<span class='badge alert-danger'>" . $response['blacklistskipped'] . "</span>");
         echo "</p>";
     }
     if ($response['overwriteauto'] == "true" || $response['overwriteman'] == "true") {
         echo "<p>";
         eT("Attribute values for existing participants have been updated from the participants records");
         echo "</p>";
     }
 }