public function attributeLabels() { $labels = array('tid' => gT('Token ID'), 'partcipant' => gt('Participant ID'), 'firstname' => gT('First name'), 'lastname' => gT('Last name'), 'email' => gT('Email address'), 'emailstatus' => gT('Email status'), 'token' => gT('Token'), 'language' => gT('Language code'), 'blacklisted' => gT('Blacklisted'), 'sent' => gT('Invitation sent date'), 'remindersent' => gT('Last reminder sent date'), 'remindercount' => gT('Total numbers of sent reminders'), 'completed' => gT('Completed'), 'usesleft' => gT('Uses left'), 'validfrom' => gT('Valid from'), 'validuntil' => gT('Valid until')); // Check if we have custom attributes. if ($this->hasAttribute('attribute_1')) { foreach (decodeTokenAttributes($this->survey->attributedescriptions) as $key => $info) { $labels[$key] = $info['description']; } } return $labels; }
function upgradeSurveys177() { $oDB = Yii::app()->db; $sSurveyQuery = "SELECT surveyls_attributecaptions,surveyls_survey_id,surveyls_language FROM {{surveys_languagesettings}}"; $oSurveyResult = $oDB->createCommand($sSurveyQuery)->queryAll(); $sSurveyLSUpdateQuery = "update {{surveys_languagesettings}} set surveyls_attributecaptions=:attributecaptions where surveyls_survey_id=:surveyid and surveyls_language=:language"; foreach ($oSurveyResult as $aSurveyRow) { $aAttributeDescriptions = decodeTokenAttributes($aSurveyRow['surveyls_attributecaptions']); if (!$aAttributeDescriptions) { $aAttributeDescriptions = array(); } $oDB->createCommand($sSurveyLSUpdateQuery)->execute(array(':language' => $aSurveyRow['surveyls_language'], ':surveyid' => $aSurveyRow['surveyls_survey_id'], ':attributecaptions' => json_encode($aAttributeDescriptions))); } $sSurveyQuery = "SELECT sid,attributedescriptions FROM {{surveys}}"; $oSurveyResult = $oDB->createCommand($sSurveyQuery)->queryAll(); $sSurveyUpdateQuery = "update {{surveys}} set attributedescriptions=:attributedescriptions where sid=:surveyid"; foreach ($oSurveyResult as $aSurveyRow) { $aAttributeDescriptions = decodeTokenAttributes($aSurveyRow['attributedescriptions']); if (!$aAttributeDescriptions) { $aAttributeDescriptions = array(); } $oDB->createCommand($sSurveyUpdateQuery)->execute(array(':attributedescriptions' => json_encode($aAttributeDescriptions), ':surveyid' => $aSurveyRow['sid'])); } }
function copyCPBDAttributesToTokens($surveyid, $mapped, $newcreate, $participantid, $overwriteauto = false, $overwriteman = false, $overwritest = false, $createautomap = true) { Yii::app()->loadHelper('common'); $duplicate = 0; $sucessfull = 0; $iBlacklistSkipped = 0; $participantid = explode(",", $participantid); //List of participant ids to add to tokens table if ($participantid[0] == "") { $participantid = array_slice($participantid, 1); } $number2add = sanitize_int(count($newcreate)); //Number of tokens being created $tokenattributefieldnames = array(); //Will contain descriptions of existing token attribute fields $tokenfieldnames = array(); //Will contain the actual field names of existing token attribute fields $attributesadded = array(); //Will contain the actual field name of any new token attribute fields $attributeidadded = array(); //Will contain the description of any new token attribute fields $fieldcontents = array(); //Will contain serialised info for the surveys.attributedescriptions field $surveyinfo = getSurveyInfo($surveyid); $defaultsurveylang = $surveyinfo['surveyls_language']; $arr = Yii::app()->db->createCommand()->select('*')->from("{{tokens_{$surveyid}}}")->queryRow(); if (is_array($arr)) { $tokenfieldnames = array_keys($arr); $tokenattributefieldnames = array_filter($tokenfieldnames, 'filterForAttributes'); } // If automapping is enabled then update the token field properties with the mapped CPDB field ID if ($createautomap == "true") { foreach ($mapped as $key => $iIDAttributeCPDB) { if (is_numeric($iIDAttributeCPDB)) { /* Update the attributedescriptions info */ $aTokenAttributes = Survey::model()->findByPk($surveyid)->tokenattributes; $aTokenAttributes[$key]['cpdbmap'] = $iIDAttributeCPDB; Yii::app()->db->createCommand()->update('{{surveys}}', array("attributedescriptions" => json_encode($aAttributes)), 'sid = ' . $surveyid); } } } foreach ($tokenattributefieldnames as $key => $value) { $mapped[$key] = $value; // $value can be 'attribute_1', which will clash with postgres } if (!empty($newcreate)) { foreach ($newcreate as $key => $value) { $newfieldname = 'attribute_' . $value; $fields[$newfieldname] = array('type' => 'string'); $attname = Yii::app()->db->createCommand()->select('{{participant_attribute_names_lang}}.attribute_name, {{participant_attribute_names_lang}}.lang')->from('{{participant_attribute_names}}')->join('{{participant_attribute_names_lang}}', '{{participant_attribute_names}}.attribute_id = {{participant_attribute_names_lang}}.attribute_id')->where('{{participant_attribute_names}}.attribute_id = :attrid ')->bindParam(":attrid", $value, PDO::PARAM_INT); $attributename = $attname->queryAll(); foreach ($attributename as $att) { $languages[$att['lang']] = $att['attribute_name']; } //Check first for the default survey language if (isset($languages[$defaultsurveylang])) { $newname = $languages[$defaultsurveylang]; } elseif (isset($language[Yii::app()->session['adminlang']])) { $newname = $languages[Yii::app()->session['adminlang']]; } else { $newname = $attributename[0]['attribute_name']; //Choose the first item in the list } $tokenattributefieldnames[] = $newfieldname; $fieldcontents[$newfieldname] = array("description" => $newname, "mandatory" => "N", "show_register" => "N"); array_push($attributeidadded, 'attribute_' . $value); array_push($attributesadded, $value); } //Update the attributedescriptions in the survey table to include the newly created attributes $previousatt = Yii::app()->db->createCommand()->select('attributedescriptions')->where("sid = :sid")->from('{{surveys}}')->bindParam(":sid", $surveyid, PDO::PARAM_INT); $aTokenAttributes = $previousatt->queryRow(); $aTokenAttributes = decodeTokenAttributes($aTokenAttributes['attributedescriptions']); foreach ($fieldcontents as $key => $iIDAttributeCPDB) { $aTokenAttributes[$key] = $iIDAttributeCPDB; } $aTokenAttributes = serialize($aTokenAttributes); Yii::app()->db->createCommand()->update('{{surveys}}', array("attributedescriptions" => $aTokenAttributes), 'sid = ' . intval($surveyid)); // load description in the surveys table //Actually create the fields in the tokens table Yii::app()->loadHelper('update/updatedb'); foreach ($fields as $key => $value) { addColumn("{{tokens_{$surveyid}}}", $key, $value['type']); } Yii::app()->db->schema->getTable("{{tokens_{$surveyid}}}", true); // Refresh schema cache just } //Write each participant to the survey token table foreach ($participantid as $key => $sParticipantUID) { $writearray = array(); $participantdata = Yii::app()->db->createCommand()->select('firstname,lastname,email,language,blacklisted')->where('participant_id = :pid')->from('{{participants}}')->bindParam(":pid", $sParticipantUID, PDO::PARAM_INT); $tobeinserted = $participantdata->queryRow(); if (Yii::app()->getConfig('blockaddingtosurveys') == 'Y' && $tobeinserted == 'Y') { $iBlacklistSkipped++; continue; } /* Search for matching participant name/email in the survey token table */ $sQuery = Yii::app()->db->createCommand()->select('*')->from('{{tokens_' . $surveyid . '}}')->where('firstname = :firstname AND lastname = :lastname AND email = :email AND participant_id = :participant_id')->bindParam(":firstname", $tobeinserted['firstname'], PDO::PARAM_STR)->bindParam(":lastname", $tobeinserted['lastname'], PDO::PARAM_STR)->bindParam(":email", $tobeinserted['email'], PDO::PARAM_STR)->bindParam(":participant_id", $sParticipantUID, PDO::PARAM_STR)->queryAll(); if (count($sQuery) > 0) { //Participant already exists in token table - don't copy $duplicate++; // Here is where we can put code for overwriting the attribute data if so required if ($overwriteauto == "true") { //If there are new attributes created, add those values to the token entry for this participant if (!empty($newcreate)) { $numberofattributes = count($attributesadded); for ($a = 0; $a < $numberofattributes; $a++) { Participant::model()->updateTokenAttributeValue($surveyid, $sParticipantUID, $attributesadded[$a], $attributeidadded[$a]); } } //If there are automapped attributes, add those values to the token entry for this participant if (!empty($mapped)) { foreach ($mapped as $key => $value) { if ($key[10] == 'c') { //We know it's automapped because the 11th letter is 'c' Participant::model()->updateTokenAttributeValue($surveyid, $sParticipantUID, $value, $key); } } } } if ($overwriteman == "true") { //If there are any manually mapped attributes, add those values to the token entry for this participant if (!empty($mapped)) { foreach ($mapped as $key => $value) { if ($key[10] != 'c' && $key[9] == '_') { //It's not an auto field because it's 11th character isn't 'c' Participant::model()->updateTokenAttributeValue($surveyid, $sParticipantUID, $value, $key); } } } } if ($overwritest == "true") { if (!empty($mapped)) { foreach ($mapped as $key => $value) { if (strlen($key) > 8 && $key[10] != 'c' && $key[9] != '_' || strlen($key) < 9) { Participant::model()->updateTokenAttributeValue($surveyid, $sParticipantUID, $value, $key); } } } } } else { //Create a new token entry for this participant $writearray = array('participant_id' => $sParticipantUID, 'firstname' => $tobeinserted['firstname'], 'lastname' => $tobeinserted['lastname'], 'email' => $tobeinserted['email'], 'emailstatus' => 'OK', 'language' => $tobeinserted['language']); Yii::app()->db->createCommand()->insert('{{tokens_' . $surveyid . '}}', $writearray); $insertedtokenid = getLastInsertID('{{tokens_' . $surveyid . '}}'); $time = time(); //Create a survey link for the new token entry $data = array('participant_id' => $sParticipantUID, 'token_id' => $insertedtokenid, 'survey_id' => $surveyid, 'date_created' => date('Y-m-d H:i:s', $time)); Yii::app()->db->createCommand()->insert('{{survey_links}}', $data); //If there are new attributes created, add those values to the token entry for this participant if (!empty($newcreate)) { $numberofattributes = count($attributesadded); for ($a = 0; $a < $numberofattributes; $a++) { try { Participant::model()->updateTokenAttributeValue($surveyid, $sParticipantUID, $attributesadded[$a], $attributeidadded[$a]); } catch (Exception $e) { throw new Exception(gT("Could not update token attribute value")); } } } //If there are any automatically mapped attributes, add those values to the token entry for this participant if (!empty($mapped)) { foreach ($mapped as $key => $value) { try { Participant::model()->updateTokenAttributeValue($surveyid, $sParticipantUID, $value, $key); } catch (Exception $e) { throw new Exception(gT("Could not update token attribute value")); } } } $sucessfull++; } } $returndata = array('success' => $sucessfull, 'duplicate' => $duplicate, 'blacklistskipped' => $iBlacklistSkipped, 'overwriteauto' => $overwriteauto, 'overwriteman' => $overwriteman); return $returndata; }
/** * Create new "fields"? in which table? * * @param int $surveyId * @param array $newAttributes * @return array [addedAttributes, addedAttributeIds] */ private function createColumnsInTokenTable($surveyId, array $newAttributes) { // Get default language $surveyInfo = getSurveyInfo($surveyId); $defaultsurveylang = $surveyInfo['surveyls_language']; //Will contain serialised info for the surveys.attributedescriptions field $fieldcontents = array(); // ?? $fields = array(); //Will contain the actual field name of any new token attribute fields $addedAttributes = array(); //Will contain the description of any new token attribute fields $addedAttributeIds = array(); foreach ($newAttributes as $value) { $newfieldname = 'attribute_' . $value; $fields[$newfieldname] = array('type' => 'string'); // TODO: Always string?? $attname = Yii::app()->db->createCommand()->select('{{participant_attribute_names_lang}}.attribute_name, {{participant_attribute_names_lang}}.lang')->from('{{participant_attribute_names}}')->join('{{participant_attribute_names_lang}}', '{{participant_attribute_names}}.attribute_id = {{participant_attribute_names_lang}}.attribute_id')->where('{{participant_attribute_names}}.attribute_id = :attrid ')->bindParam(":attrid", $value, PDO::PARAM_INT); $attributename = $attname->queryAll(); foreach ($attributename as $att) { $languages[$att['lang']] = $att['attribute_name']; } //Check first for the default survey language if (isset($languages[$defaultsurveylang])) { $newname = $languages[$defaultsurveylang]; } elseif (isset($language[Yii::app()->session['adminlang']])) { $newname = $languages[Yii::app()->session['adminlang']]; } else { $newname = $attributename[0]['attribute_name']; //Choose the first item in the list } $tokenAttributeFieldNames[] = $newfieldname; $fieldcontents[$newfieldname] = array("description" => $newname, "mandatory" => "N", "show_register" => "N"); array_push($addedAttributeIds, 'attribute_' . $value); array_push($addedAttributes, $value); } //Update the attributedescriptions in the survey table to include the newly created attributes $previousatt = Yii::app()->db->createCommand()->select('attributedescriptions')->where("sid = :sid")->from('{{surveys}}')->bindParam(":sid", $surveyId, PDO::PARAM_INT); $aTokenAttributes = $previousatt->queryRow(); $aTokenAttributes = decodeTokenAttributes($aTokenAttributes['attributedescriptions']); foreach ($fieldcontents as $key => $iIDAttributeCPDB) { $aTokenAttributes[$key] = $iIDAttributeCPDB; } $aTokenAttributes = serialize($aTokenAttributes); Yii::app()->db->createCommand()->update('{{surveys}}', array("attributedescriptions" => $aTokenAttributes), 'sid = ' . intval($surveyId)); // load description in the surveys table //Actually create the fields in the tokens table Yii::app()->loadHelper('update/updatedb'); foreach ($fields as $key => $value) { addColumn("{{tokens_{$surveyId}}}", $key, $value['type']); } Yii::app()->db->schema->getTable("{{tokens_{$surveyId}}}", true); // Refresh schema cache just return array($addedAttributes, $addedAttributeIds); }
/** * Returns the additional token attributes * * @access public * @return array */ public function getTokenAttributes() { $attdescriptiondata = decodeTokenAttributes($this->attributedescriptions); // checked for invalid data if ($attdescriptiondata == null) { return array(); } // Catches malformed data if ($attdescriptiondata && strpos(key(reset($attdescriptiondata)), 'attribute_') === false) { // don't know why yet but this breaks normal tokenAttributes functionning //$attdescriptiondata=array_flip(GetAttributeFieldNames($this->sid)); } elseif (is_null($attdescriptiondata)) { $attdescriptiondata = array(); } // Legacy records support if ($attdescriptiondata === false) { $attdescriptiondata = explode("\n", $this->attributedescriptions); $fields = array(); $languagesettings = array(); foreach ($attdescriptiondata as $attdescription) { if (trim($attdescription) != '') { $fieldname = substr($attdescription, 0, strpos($attdescription, '=')); $desc = substr($attdescription, strpos($attdescription, '=') + 1); $fields[$fieldname] = array('description' => $desc, 'mandatory' => 'N', 'show_register' => 'N', 'cpdbmap' => ''); $languagesettings[$fieldname] = $desc; } } $ls = SurveyLanguageSetting::model()->findByAttributes(array('surveyls_survey_id' => $this->sid, 'surveyls_language' => $this->language)); self::model()->updateByPk($this->sid, array('attributedescriptions' => json_encode($fields))); $ls->surveyls_attributecaptions = json_encode($languagesettings); $ls->save(); $attdescriptiondata = $fields; } $aCompleteData = array(); foreach ($attdescriptiondata as $sKey => $aValues) { if (!is_array($aValues)) { $aValues = array(); } $aCompleteData[$sKey] = array_merge(array('description' => '', 'mandatory' => 'N', 'show_register' => 'N', 'cpdbmap' => ''), $aValues); } return $aCompleteData; }
/** * Delete token attributes */ public function deletetokenattributes($iSurveyId) { $iSurveyId = sanitize_int($iSurveyId); // CHECK TO SEE IF A TOKEN TABLE EXISTS FOR THIS SURVEY $bTokenExists = tableExists('{{tokens_' . $iSurveyId . '}}'); if (!$bTokenExists) { Yii::app()->session['flashmessage'] = gT("No token table."); $this->getController()->redirect($this->getController()->createUrl("/admin/survey/sa/view/surveyid/{$iSurveyId}")); } if (!Permission::model()->hasSurveyPermission($iSurveyId, 'tokens', 'update') && !Permission::model()->hasSurveyPermission($iSurveyId, 'surveysettings', 'update')) { Yii::app()->session['flashmessage'] = gT("You do not have permission to access this page."); $this->getController()->redirect($this->getController()->createUrl("/admin/survey/sa/view/surveyid/{$iSurveyId}")); } $aData['thissurvey'] = getSurveyInfo($iSurveyId); $aData['surveyid'] = $iSurveyId; $confirm = Yii::app()->request->getPost('confirm', ''); $cancel = Yii::app()->request->getPost('cancel', ''); $tokenfields = getAttributeFieldNames($iSurveyId); $sAttributeToDelete = Yii::app()->request->getPost('deleteattribute', ''); if (!in_array($sAttributeToDelete, $tokenfields)) { $sAttributeToDelete = false; } if ($cancel == 'cancel') { Yii::app()->getController()->redirect(Yii::app()->getController()->createUrl("/admin/tokens/sa/managetokenattributes/surveyid/{$iSurveyId}")); } elseif ($confirm != 'confirm' && $sAttributeToDelete) { $aData['sidemenu']['state'] = false; $this->_renderWrappedTemplate('token', array('message' => array('title' => sprintf(gT("Delete token attribute %s"), $sAttributeToDelete), 'message' => "<p>" . gT("If you remove this attribute, you will lose all information.") . "</p>\n" . CHtml::form(array("admin/tokens/sa/deletetokenattributes/surveyid/{$iSurveyId}"), 'post', array('id' => 'attributenumber')) . CHtml::hiddenField('deleteattribute', $sAttributeToDelete) . CHtml::hiddenField('sid', $iSurveyId) . CHtml::htmlButton(gT('Delete attribute'), array('type' => 'submit', 'value' => 'confirm', 'name' => 'confirm', 'class' => 'btn btn-default btn-lg')) . CHtml::htmlButton(gT('Cancel'), array('type' => 'submit', 'value' => 'cancel', 'name' => 'cancel', 'class' => 'btn btn-default btn-lg')) . CHtml::endForm())), $aData); } elseif ($sAttributeToDelete) { // Update field attributedescriptions in survey table $aTokenAttributeDescriptions = decodeTokenAttributes(Survey::model()->findByPk($iSurveyId)->attributedescriptions); unset($aTokenAttributeDescriptions[$sAttributeToDelete]); Survey::model()->updateByPk($iSurveyId, array('attributedescriptions' => json_encode($aTokenAttributeDescriptions))); $sTableName = "{{tokens_" . intval($iSurveyId) . "}}"; Yii::app()->db->createCommand(Yii::app()->db->getSchema()->dropColumn($sTableName, $sAttributeToDelete))->execute(); Yii::app()->db->schema->getTable($sTableName, true); // Refresh schema cache LimeExpressionManager::SetDirtyFlag(); Yii::app()->session['flashmessage'] = sprintf(gT("Attribute %s was deleted."), $sAttributeToDelete); Yii::app()->getController()->redirect(Yii::app()->getController()->createUrl("/admin/tokens/sa/managetokenattributes/surveyid/{$iSurveyId}")); } else { Yii::app()->session['flashmessage'] = gT("The selected attribute was invalid."); Yii::app()->getController()->redirect(Yii::app()->getController()->createUrl("/admin/tokens/sa/managetokenattributes/surveyid/{$iSurveyId}")); } }
public function rules() { $aRules = array(array('token', 'unique', 'allowEmpty' => true), array('firstname', 'LSYii_Validators'), array('lastname', 'LSYii_Validators'), array(implode(',', $this->tableSchema->columnNames), 'safe'), array('remindercount', 'numerical', 'integerOnly' => true, 'allowEmpty' => true), array('email', 'filter', 'filter' => 'trim'), array('email', 'LSYii_EmailIDNAValidator', 'allowEmpty' => true, 'allowMultiple' => true, 'except' => 'allowinvalidemail'), array('usesleft', 'numerical', 'integerOnly' => true, 'allowEmpty' => true), array('mpid', 'numerical', 'integerOnly' => true, 'allowEmpty' => true), array('blacklisted', 'in', 'range' => array('Y', 'N'), 'allowEmpty' => true), array('emailstatus', 'default', 'value' => 'OK')); foreach (decodeTokenAttributes($this->survey->attributedescriptions) as $key => $info) { $aRules[] = array($key, 'LSYii_Validators'); } return $aRules; }