/** * Show dialogs and create a new tokens table */ function _newtokentable($iSurveyId) { $clang = $this->getController()->lang; $aSurveyInfo = getSurveyInfo($iSurveyId); if (!Permission::model()->hasSurveyPermission($iSurveyId, 'surveysettings', 'update') && !Permission::model()->hasSurveyPermission($iSurveyId, 'tokens', 'create')) { Yii::app()->session['flashmessage'] = $clang->gT("Tokens have not been initialised for this survey."); $this->getController()->redirect(array("/admin/survey/sa/view/surveyid/{$iSurveyId}")); } $bTokenExists = tableExists('{{tokens_' . $iSurveyId . '}}'); if ($bTokenExists) { Yii::app()->session['flashmessage'] = $clang->gT("Tokens already exist for this survey."); $this->getController()->redirect(array("/admin/survey/sa/view/surveyid/{$iSurveyId}")); } // The user have rigth to create token, then don't test right after Yii::import('application.helpers.admin.token_helper', true); if (Yii::app()->request->getQuery('createtable') == "Y") { createTokenTable($iSurveyId); LimeExpressionManager::SetDirtyFlag(); // LimeExpressionManager needs to know about the new token table $this->_renderWrappedTemplate('token', array('message' => array('title' => $clang->gT("Token control"), 'message' => $clang->gT("A token table has been created for this survey.") . " (\"" . Yii::app()->db->tablePrefix . "tokens_{$iSurveyId}\")<br /><br />\n" . "<input type='submit' value='" . $clang->gT("Continue") . "' onclick=\"window.open('" . $this->getController()->createUrl("admin/tokens/sa/index/surveyid/{$iSurveyId}") . "', '_top')\" />\n"))); } elseif (returnGlobal('restoretable') == "Y" && Yii::app()->request->getPost('oldtable')) { //Rebuild attributedescription value for the surveys table $table = Yii::app()->db->schema->getTable(Yii::app()->request->getPost('oldtable')); $fields = array_filter(array_keys($table->columns), 'filterForAttributes'); $fieldcontents = $aSurveyInfo['attributedescriptions']; if (!is_array($fieldcontents)) { $fieldcontents = array(); } foreach ($fields as $fieldname) { $name = $fieldname; if ($fieldname[10] == 'c') { //This belongs to a cpdb attribute $cpdbattid = substr($fieldname, 15); $data = ParticipantAttributeName::model()->getAttributeName($cpdbattid, Yii::app()->session['adminlang']); $name = $data['attribute_name']; } if (!isset($fieldcontents[$fieldname])) { $fieldcontents[$fieldname] = array('description' => $name, 'mandatory' => 'N', 'show_register' => 'N'); } } Survey::model()->updateByPk($iSurveyId, array('attributedescriptions' => serialize($fieldcontents))); Yii::app()->db->createCommand()->renameTable(Yii::app()->request->getPost('oldtable'), Yii::app()->db->tablePrefix . "tokens_" . intval($iSurveyId)); Yii::app()->db->schema->getTable(Yii::app()->db->tablePrefix . "tokens_" . intval($iSurveyId), true); // Refresh schema cache just in case the table existed in the past //Check that the tokens table has the required fields TokenDynamic::model($iSurveyId)->checkColumns(); //Add any survey_links from the renamed table SurveyLink::model()->rebuildLinksFromTokenTable($iSurveyId); $this->_renderWrappedTemplate('token', array('message' => array('title' => $clang->gT("Import old tokens"), 'message' => $clang->gT("A token table has been created for this survey and the old tokens were imported.") . " (\"" . Yii::app()->db->tablePrefix . "tokens_{$iSurveyId}" . "\")<br /><br />\n" . "<input type='submit' value='" . $clang->gT("Continue") . "' onclick=\"window.open('" . $this->getController()->createUrl("admin/tokens/sa/index/surveyid/{$iSurveyId}") . "', '_top')\" />\n"))); LimeExpressionManager::SetDirtyFlag(); // so that knows that token tables have changed } else { $this->getController()->loadHelper('database'); $result = Yii::app()->db->createCommand(dbSelectTablesLike("{{old_tokens_" . intval($iSurveyId) . "_%}}"))->queryAll(); $tcount = count($result); if ($tcount > 0) { foreach ($result as $rows) { $oldlist[] = reset($rows); } $aData['oldlist'] = $oldlist; } $thissurvey = getSurveyInfo($iSurveyId); $aData['thissurvey'] = $thissurvey; $aData['surveyid'] = $iSurveyId; $aData['tcount'] = $tcount; $aData['databasetype'] = Yii::app()->db->getDriverName(); $this->_renderWrappedTemplate('token', 'tokenwarning', $aData); } }
function attributeMapToken() { Yii::app()->loadHelper('common'); App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('adminscripts') . "attributeMapToken.js"); App()->getClientScript()->registerCssFile(Yii::app()->getConfig('adminstyleurl') . "attributeMapToken.css"); $iSurveyID = (int) Yii::app()->request->getQuery('sid'); $aCPDBAttributes = ParticipantAttributeName::model()->getCPDBAttributes(); $aTokenAttributes = getTokenFieldsAndNames($iSurveyID, TRUE); $selectedattribute = array(); $selectedcentralattribute = array(); $alreadymappedattid = array(); $alreadymappedattdisplay = array(); $alreadymappedattnames = array(); $i = 0; $j = 0; foreach ($aTokenAttributes as $key => $value) { if ($value['cpdbmap'] == '') { $selectedattribute[$value['description']] = $key; } else { $attributeid = $value['cpdbmap']; $continue = false; foreach ($aCPDBAttributes as $attribute) { if ($attribute['attribute_id'] == $attributeid) { $continue = true; } } if ($continue) { $alreadymappedattid[] = $attributeid; $alreadymappedattdisplay[] = $key; $alreadymappedattnames[$key] = $value['description']; } else { $selectedattribute[$value['description']] = $key; } } } foreach ($aCPDBAttributes as $row) { if (!in_array($row['attribute_id'], $alreadymappedattid)) { $selectedcentralattribute[$row['attribute_id']] = $row['attribute_name']; } } $aData = array('attribute' => $selectedcentralattribute, 'tokenattribute' => $selectedattribute, 'alreadymappedattributename' => $alreadymappedattdisplay, 'alreadymappedattdescription' => $alreadymappedattnames); $this->_renderWrappedTemplate('participants', 'attributeMapToken', $aData); }
private function getParticipantsSelectCommand($count = false, $attid, $search = null, $userid = null, $page = null, $limit = null, $order = null) { $selectValue = array(); $joinValue = array(); $selectValue[] = "p.*"; $selectValue[] = "luser.full_name as ownername"; $selectValue[] = "luser.users_name as username"; $aAllAttributes = ParticipantAttributeName::model()->getAllAttributes(); foreach ($aAllAttributes as $aAttribute) { if (!is_null($search) && strpos($search->condition, 'attribute' . $aAttribute['attribute_id']) !== false) { $attid[$aAttribute['attribute_id']] = $aAttribute; } } // Add survey count subquery $subQuery = Yii::app()->db->createCommand()->select('count(*) survey')->from('{{survey_links}} sl')->where('sl.participant_id = p.participant_id'); $selectValue[] = sprintf('(%s) survey', $subQuery->getText()); array_push($joinValue, "left join {{users}} luser ON luser.uid=p.owner_uid"); foreach ($attid as $iAttributeID => $aAttributeDetails) { if ($iAttributeID == 0) { continue; } $sDatabaseType = Yii::app()->db->getDriverName(); if ($sDatabaseType == 'mssql' || $sDatabaseType == "sqlsrv" || $sDatabaseType == 'dblib') { $selectValue[] = "cast(attribute" . $iAttributeID . ".value as varchar(max)) as a" . $iAttributeID; } else { $selectValue[] = "attribute" . $iAttributeID . ".value as a" . $iAttributeID; } array_push($joinValue, "LEFT JOIN {{participant_attribute}} attribute" . $iAttributeID . " ON attribute" . $iAttributeID . ".participant_id=p.participant_id AND attribute" . $iAttributeID . ".attribute_id=" . $iAttributeID); } $aConditions = array(); // this wil hold all conditions $aParams = array(); if (!is_null($userid)) { // We are not superadmin so we need to limit to our own or shared with us $selectValue[] = '{{participant_shares}}.can_edit'; $joinValue[] = 'LEFT JOIN {{participant_shares}} ON p.participant_id={{participant_shares}}.participant_id'; $aConditions[] = 'p.owner_uid = :userid1 OR {{participant_shares}}.share_uid = :userid2 OR {{participant_shares}}.share_uid = 0'; } if ($count) { $selectValue = 'count(*) as cnt'; } $data = Yii::app()->db->createCommand()->select($selectValue)->from('{{participants}} p'); $data->setJoin($joinValue); if (!empty($search)) { /* @var $search CDbCriteria */ $aSearch = $search->toArray(); $aConditions[] = $aSearch['condition']; $aParams = $aSearch['params']; } if (Yii::app()->getConfig('hideblacklisted') == 'Y') { $aConditions[] = "blacklisted<>'Y'"; } $condition = ''; // This will be the final condition foreach ($aConditions as $idx => $newCondition) { if ($idx > 0) { $condition .= ' AND '; } $condition .= '(' . $newCondition . ')'; } if (!empty($condition)) { $data->setWhere($condition); } if (!$count) { // Apply order and limits if (!empty($order)) { $data->setOrder($order); } if ($page != 0) { $offset = ($page - 1) * $limit; $data->offset($offset)->limit($limit); } } $data->bindValues($aParams); if (!is_null($userid)) { $data->bindParam(":userid1", $userid, PDO::PARAM_INT)->bindParam(":userid2", $userid, PDO::PARAM_INT); } return $data; }
/** * Check for column duplicates from CPDB to token attributes * Throws error message if an attribute already exists; otherwise false. * * @param int $surveyId * @param string[] $newAttributes Array of CPDB attributes ids like ['42', '32', ...] * @return boolean * @throws CPDBException with error message */ private function checkColumnDuplicates($surveyId, array $newAttributes) { $tokenTableSchema = Yii::app()->db->schema->getTable("{{tokens_{$surveyId}}}"); foreach ($tokenTableSchema->columns as $columnName => $columnObject) { if (strpos($columnName, 'attribute_') !== false) { $id = substr($columnName, 10); if (in_array($id, $newAttributes)) { $name = ParticipantAttributeName::model()->getAttributeName($id, $_SESSION['adminlang']); if (empty($name)) { $name = array('attribute_name' => '[Found no name]'); } throw new CPDBException(sprintf("Token attribute already exists: %s", $name['attribute_name'])); } } } return false; }
function saveAttribute($data) { if (empty($data['attribute_id'])) { return; } $insertnames = array(); if (!empty($data['attribute_type'])) { $insertnames['attribute_type'] = $data['attribute_type']; } if (!empty($data['visible'])) { $insertnames['visible'] = $data['visible']; } if (!empty($data['defaultname'])) { $insertnames['defaultname'] = $data['defaultname']; } if (!empty($insertnames)) { $oParticipantAttributeName = ParticipantAttributeName::model()->findByPk(array('attribute_id' => $data['attribute_id'], 'attribute_type' => $data['attribute_type'])); foreach ($insertnames as $sFieldname => $sValue) { $oParticipantAttributeName->{$sFieldname} = $sValue; } $oParticipantAttributeName->save(); } if (!empty($data['attribute_name'])) { $oParticipantAttributeNameLang = ParticipantAttributeNameLang::model()->findByPk(array('attribute_id' => $data['attribute_id'], 'lang' => Yii::app()->session['adminlang'])); $oParticipantAttributeNameLang->attribute_name = $data['attribute_name']; $oParticipantAttributeNameLang->save(); } }
/** * This function is responsible for attribute mapping while copying participants from tokens to CPDB */ public function attributeMapToken() { Yii::app()->loadHelper('common'); $this->registerScriptFile('ADMIN_SCRIPT_PATH', 'attributeMapToken.js'); $this->registerCssFile('ADMIN', 'attributeMapToken.css'); $iSurveyID = (int) Yii::app()->request->getQuery('sid'); $aCPDBAttributes = ParticipantAttributeName::model()->getCPDBAttributes(); $aTokenAttributes = getTokenFieldsAndNames($iSurveyID, TRUE); $selectedattribute = array(); $selectedcentralattribute = array(); $alreadymappedattid = array(); $alreadymappedattdisplay = array(); $alreadymappedattnames = array(); foreach ($aTokenAttributes as $key => $value) { if ($value['cpdbmap'] == '') { $selectedattribute[$value['description']] = $key; } else { $attributeid = $value['cpdbmap']; $continue = false; foreach ($aCPDBAttributes as $attribute) { if ($attribute['attribute_id'] == $attributeid) { $continue = true; } } if ($continue) { $alreadymappedattid[] = $attributeid; $alreadymappedattdisplay[] = $key; $alreadymappedattnames[$key] = $value['description']; } else { $selectedattribute[$value['description']] = $key; } } } foreach ($aCPDBAttributes as $row) { if (!in_array($row['attribute_id'], $alreadymappedattid)) { $selectedcentralattribute[$row['attribute_id']] = $row['attribute_name']; } } if (count($selectedattribute) === 0) { Yii::app()->setFlashMessage(gT("There are no unmapped attributes"), 'warning'); } $aData = array('attribute' => $selectedcentralattribute, 'tokenattribute' => $selectedattribute, 'alreadymappedattributename' => $alreadymappedattdisplay, 'alreadymappedattdescription' => $alreadymappedattnames); $this->_renderWrappedTemplate('participants', 'attributeMapToken', $aData); }
/** * 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 get all the participants in the Central Participants Database * * @access public * @param string $sSessionKey - Auth credentials * @param string $search - (null is passed when searching all participants) * @param int $page - (can be empty) * * */ public function get_global_participants($sSessionKey, $search = null, $page = null, $results_per_page = 1000000) { // Check sessionkey if (!$this->_checkSessionKey($sSessionKey)) { return array('status' => 'Invalid session key'); } // this is because the JSON-RPC libary ignores variable names and just goes on the position of the variable when called if ($page == null) { $page = 1; } $number_of_rows = $results_per_page; // Cut'n'pate from > applications/controllers/admin/participantsaction.php //$page = $page; $limit = $number_of_rows; $limit = isset($limit) ? $limit : 50; //Stop division by zero errors (don't know if this is still needed if it is populated in the function call) // adds additional user attributes to the end of the array $attid = ParticipantAttributeName::model()->getVisibleAttributes(); $participantfields = array('participant_id', 'can_edit', 'firstname', 'lastname', 'email', 'blacklisted', 'survey', 'language', 'owner_uid'); foreach ($attid as $key => $value) { array_push($participantfields, $value['attribute_id']); } // sorts the array // TODO: $sidx = Yii::app()->request->getPost('sidx'); $sidx = !empty($sidx) ? $sidx : "lastname"; $sord = Yii::app()->request->getPost('sord'); $sord = !empty($sord) ? $sord : "asc"; $order = $sidx . " " . $sord; $aData = new stdClass(); //If super admin all the participants will be visible if (Permission::model()->hasGlobalPermission('superadmin', 'read')) { $iUserID = null; } else { $iUserID = Yii::app()->session['loginID']; } $aData->records = Participant::model()->getParticipantsCount($attid, $search, $iUserID); $aData->total = ceil($aData->records / $limit); if ($page > $aData->total) { $page = $aData->total; } $aData->page = $page; $records = Participant::model()->getParticipants($page, $limit, $attid, $order, $search, $iUserID); $aRowToAdd = array(); foreach ($records as $key => $row) { if (array_key_exists('can_edit', $row)) { $sCanEdit = $row['can_edit']; if (is_null($sCanEdit)) { $sCanEdit = 'true'; } // Super admin } else { $sCanEdit = "true"; } if (trim($row['ownername']) == '') { $row['ownername'] = $row['username']; } $aRowToAdd['cell'] = array($row['participant_id'], $sCanEdit, htmlspecialchars($row['firstname']), htmlspecialchars($row['lastname']), htmlspecialchars($row['email']), $row['blacklisted'], $row['survey'], $row['language'], $row['ownername']); $aRowToAdd['id'] = $row['participant_id']; // add attribute values foreach ($row as $key => $attvalue) { if (preg_match('/^a\\d+$/', $key)) { $aRowToAdd['cell'][] = $attvalue; } } $aData->rows[] = $aRowToAdd; } return $aData; }
function getnotaddedAttributes($attributeid) { $output = array(); $notin = array(); foreach ($attributeid as $row) { $notin[] = $row; } $criteria = new CDbCriteria(); $alias = $this->getTableAlias(); $criteria->addNotInCondition("{$alias}.attribute_id", $attributeid); $records = ParticipantAttributeName::model()->with('participant_attribute_names_lang')->findAll($criteria); foreach ($records as $row) { //Iterate through each attribute $thisname = ""; $thislang = ""; foreach ($row->participant_attribute_names_lang as $names) { //Iterate through each language version of this attribute if ($thisname == "") { $thisname = $names->attribute_name; $thislang = $names->lang; } //Choose the first item by default if ($names->lang == Yii::app()->session['adminlang']) { $thisname = $names->attribute_name; $thislang = $names->lang; } //Override the default with the admin language version if found } $output[] = array('attribute_id' => $row->attribute_id, 'attribute_type' => $row->attribute_type, 'attribute_display' => $row->visible, 'attribute_name' => $thisname, 'lang' => $thislang); } return $output; }
/** * Adds the data for a new attribute * * @param mixed $data */ function storeAttribute($data) { $insertnames = array('attribute_type' => $data['attribute_type'], 'defaultname' => $data['defaultname'], 'visible' => $data['visible']); // Do not allow more than 60 attributes because queries will break because of too many joins if (ParticipantAttributeName::model()->count() > 59) { return false; } Yii::app()->db->createCommand()->insert('{{participant_attribute_names}}', $insertnames); $attribute_id = getLastInsertID($this->tableName()); $insertnameslang = array('attribute_id' => intval($attribute_id), 'attribute_name' => $data['attribute_name'], 'lang' => Yii::app()->session['adminlang']); Yii::app()->db->createCommand()->insert('{{participant_attribute_names_lang}}', $insertnameslang); return $attribute_id; }