/** * Add dummy tokens form */ function addDummies($iSurveyId, $subaction = '') { $iSurveyId = sanitize_int($iSurveyId); $clang = $this->getController()->lang; if (!Permission::model()->hasSurveyPermission($iSurveyId, 'tokens', 'create')) { Yii::app()->session['flashmessage'] = $clang->gT("You do not have sufficient rights to access this page."); $this->getController()->redirect(array("/admin/survey/sa/view/surveyid/{$iSurveyId}")); } $bTokenExists = tableExists('{{tokens_' . $iSurveyId . '}}'); if (!$bTokenExists) { self::_newtokentable($iSurveyId); } $this->getController()->loadHelper("surveytranslator"); if (!empty($subaction) && $subaction == 'add') { $this->getController()->loadLibrary('Date_Time_Converter'); $dateformatdetails = getDateFormatData(Yii::app()->session['dateformat']); //Fix up dates and match to database format if (trim(Yii::app()->request->getPost('validfrom')) == '') { $_POST['validfrom'] = null; } else { $datetimeobj = new Date_Time_Converter(trim(Yii::app()->request->getPost('validfrom')), $dateformatdetails['phpdate'] . ' H:i'); $_POST['validfrom'] = $datetimeobj->convert('Y-m-d H:i:s'); } if (trim(Yii::app()->request->getPost('validuntil')) == '') { $_POST['validuntil'] = null; } else { $datetimeobj = new Date_Time_Converter(trim(Yii::app()->request->getPost('validuntil')), $dateformatdetails['phpdate'] . ' H:i'); $_POST['validuntil'] = $datetimeobj->convert('Y-m-d H:i:s'); } $santitizedtoken = ''; $aData = array('firstname' => Yii::app()->request->getPost('firstname'), 'lastname' => Yii::app()->request->getPost('lastname'), 'email' => Yii::app()->request->getPost('email'), 'emailstatus' => 'OK', 'token' => $santitizedtoken, 'language' => sanitize_languagecode(Yii::app()->request->getPost('language')), 'sent' => 'N', 'remindersent' => 'N', 'completed' => 'N', 'usesleft' => Yii::app()->request->getPost('usesleft'), 'validfrom' => Yii::app()->request->getPost('validfrom'), 'validuntil' => Yii::app()->request->getPost('validuntil')); // add attributes $attrfieldnames = getTokenFieldsAndNames($iSurveyId, true); foreach ($attrfieldnames as $attr_name => $desc) { $value = Yii::app()->request->getPost($attr_name); if ($desc['mandatory'] == 'Y' && trim($value) == '') { $this->getController()->error(sprintf($clang->gT('%s cannot be left empty'), $desc['description'])); } $aData[$attr_name] = Yii::app()->request->getPost($attr_name); } $amount = sanitize_int(Yii::app()->request->getPost('amount')); $tokenlength = sanitize_int(Yii::app()->request->getPost('tokenlen')); // Fill an array with all existing tokens $existingtokens = array(); $tokenModel = Token::model($iSurveyId); $criteria = $tokenModel->getDbCriteria(); $criteria->select = 'token'; $criteria->distinct = true; $command = $tokenModel->getCommandBuilder()->createFindCommand($tokenModel->getTableSchema(), $criteria); $result = $command->query(); while ($tokenRow = $result->read()) { $existingtokens[$tokenRow['token']] = true; } $result->close(); $invalidtokencount = 0; $newDummyToken = 0; while ($newDummyToken < $amount && $invalidtokencount < 50) { $token = Token::create($iSurveyId); $token->setAttributes($aData, false); $token->firstname = str_replace('{TOKEN_COUNTER}', $newDummyToken, $token->firstname); $token->lastname = str_replace('{TOKEN_COUNTER}', $newDummyToken, $token->lastname); $token->email = str_replace('{TOKEN_COUNTER}', $newDummyToken, $token->email); $attempts = 0; do { $token->token = randomChars($tokenlength); $attempts++; } while (isset($existingtokens[$token->token]) && $attempts < 50); if ($attempts == 50) { throw new Exception('Something is wrong with your random generator.'); } $existingtokens[$token->token] = true; $token->save(); $newDummyToken++; } $aData['thissurvey'] = getSurveyInfo($iSurveyId); $aData['surveyid'] = $iSurveyId; if (!$invalidtokencount) { $aData['success'] = false; $message = array('title' => $clang->gT("Success"), 'message' => $clang->gT("New dummy tokens were added.") . "<br /><br />\n<input type='button' value='" . $clang->gT("Display tokens") . "' onclick=\"window.open('" . $this->getController()->createUrl("admin/tokens/sa/browse/surveyid/{$iSurveyId}") . "', '_top')\" />\n"); } else { $aData['success'] = true; $message = array('title' => $clang->gT("Failed"), 'message' => "<p>" . sprintf($clang->gT("Only %s new dummy tokens were added after %s trials."), $newDummyToken, $invalidtokencount) . $clang->gT("Try with a bigger token length.") . "</p>" . "\n<input type='button' value='" . $clang->gT("Display tokens") . "' onclick=\"window.open('" . $this->getController()->createUrl("admin/tokens/sa/browse/surveyid/{$iSurveyId}") . "', '_top')\" />\n"); } $this->_renderWrappedTemplate('token', array('tokenbar', 'message' => $message), $aData); } else { $tokenlength = !empty(Token::model($iSurveyId)->survey->tokenlength) ? Token::model($iSurveyId)->survey->tokenlength : 15; $thissurvey = getSurveyInfo($iSurveyId); $aData['thissurvey'] = $thissurvey; $aData['surveyid'] = $iSurveyId; $aData['tokenlength'] = $tokenlength; $aData['dateformatdetails'] = getDateFormatData(Yii::app()->session['dateformat'], $clang->langcode); $aData['aAttributeFields'] = GetParticipantAttributes($iSurveyId); $this->_renderWrappedTemplate('token', array('tokenbar', 'dummytokenform'), $aData); } }
/** * 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(); }
/** * register::index() * Process register form data and take appropriate action * @return */ function actionIndex($iSurveyID = null) { Yii::app()->loadHelper('database'); Yii::app()->loadHelper('replacements'); $sLanguage = Yii::app()->request->getParam('lang', ''); if ($iSurveyID == null) { $iSurveyID = Yii::app()->request->getPost('sid'); } if (!$iSurveyID) { $this->redirect(Yii::app()->baseUrl); } if ($sLanguage == "") { $sBaseLanguage = Survey::model()->findByPk($iSurveyID)->language; } else { $sBaseLanguage = $sLanguage; } Yii::import('application.libraries.Limesurvey_lang'); Yii::app()->lang = new Limesurvey_lang($sBaseLanguage); $clang = Yii::app()->lang; $thissurvey = getSurveyInfo($iSurveyID, $sBaseLanguage); $register_errormsg = ""; // Check the security question's answer if (function_exists("ImageCreate") && isCaptchaEnabled('registrationscreen', $thissurvey['usecaptcha'])) { if (!isset($_POST['loadsecurity']) || !isset($_SESSION['survey_' . $iSurveyID]['secanswer']) || Yii::app()->request->getPost('loadsecurity') != $_SESSION['survey_' . $iSurveyID]['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($iSurveyID) 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_' . $iSurveyID]['register_errormsg'] = $register_errormsg; $this->redirect($this->createUrl("survey/index/sid/{$iSurveyID}", array('lang' => $sBaseLanguage))); } //Check if this email already exists in token database $oToken = TokenDynamic::model($iSurveyID)->find('email=:email', array(':email' => Yii::app()->request->getPost('register_email'))); if ($oToken) { $register_errormsg = $clang->gT("The email you used has already been registered."); $_SESSION['survey_' . $iSurveyID]['register_errormsg'] = $register_errormsg; $this->redirect($this->createUrl("survey/index/sid/{$iSurveyID}", array('lang' => $sBaseLanguage))); //include "index.php"; //exit; } $mayinsert = false; // Get the survey settings for token length $tokenlength = $thissurvey['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); $oTokenExist = TokenDynamic::model($iSurveyID)->find('token=:token', array(':token' => $newtoken)); if (!$oTokenExist) { $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 $oToken = Token::create($thissurvey['sid']); $oToken->firstname = $postfirstname; $oToken->lastname = $postlastname; $oToken->email = Yii::app()->request->getPost('register_email'); $oToken->emailstatus = 'OK'; $oToken->token = $newtoken; if ($starttime && $endtime) { $oToken->validfrom = $starttime; $oToken->validuntil = $endtime; } $oToken->setAttributes($attributeinsertdata, false); $result = $oToken->save(); //$tid = $oToken->tid;// Not needed any more $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"]; $fieldsarray["{TOKEN}"] = $oToken->token; $fieldsarray["{EMAIL}"] = $oToken->email; $token = $oToken->token; $message = $thissurvey['email_register']; $subject = $thissurvey['email_register_subj']; $from = "{$thissurvey['adminname']} <{$thissurvey['adminemail']}>"; $surveylink = $this->createAbsoluteUrl("/survey/index/sid/{$iSurveyID}", array('lang' => $sBaseLanguage, 'token' => $newtoken)); $optoutlink = $this->createAbsoluteUrl("/optout/tokens/surveyid/{$iSurveyID}", array('langcode' => $sBaseLanguage, 'token' => $newtoken)); $optinlink = $this->createAbsoluteUrl("/optin/tokens/surveyid/{$iSurveyID}", array('langcode' => $sBaseLanguage, 'token' => $newtoken)); if (getEmailFormat($iSurveyID) == 'html') { $useHtmlEmail = true; $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}"] = $surveylink; $fieldsarray["{OPTOUTURL}"] = $optoutlink; $fieldsarray["{OPTINURL}"] = $optinlink; } $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($iSurveyID))) { // 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')); $oToken->sent = $today; $oToken->save(); $html = "<div id='wrapper' class='message tokenmessage'>" . "<p>" . $clang->gT("Thank you for registering to participate in this survey.") . "</p>\n" . "<p>" . $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.") . "</p>\n" . "<p>" . $clang->gT("Survey administrator") . " {ADMINNAME} ({ADMINEMAIL})</p>" . "</div>\n"; $html = ReplaceFields($html, $fieldsarray); } else { $html = "Email Error"; } //PRINT COMPLETED PAGE if (!$thissurvey['template']) { $thistpl = getTemplatePath(validateTemplateDir('default')); } else { $thistpl = getTemplatePath(validateTemplateDir($thissurvey['template'])); } // Same fix than http://bugs.limesurvey.org/view.php?id=8441 ob_start(function ($buffer, $phase) { App()->getClientScript()->render($buffer); App()->getClientScript()->reset(); return $buffer; }); ob_implicit_flush(false); 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(); ob_flush(); }
/** * import from csv */ public function import($iSurveyId) { $aData = array(); $iSurveyId = (int) $iSurveyId; if (!Permission::model()->hasSurveyPermission($iSurveyId, 'tokens', 'import')) { Yii::app()->session['flashmessage'] = gT("You do not have permission to access this page."); $this->getController()->redirect(array("/admin/survey/sa/view/surveyid/{$iSurveyId}")); } // CHECK TO SEE IF A TOKEN TABLE EXISTS FOR THIS SURVEY $bTokenExists = tableExists('{{tokens_' . $iSurveyId . '}}'); if (!$bTokenExists) { self::_newtokentable($iSurveyId); } $surveyinfo = Survey::model()->findByPk($iSurveyId)->surveyinfo; $aData['sidemenu']['state'] = false; $aData["surveyinfo"] = $surveyinfo; $aData['title_bar']['title'] = $surveyinfo['surveyls_title'] . "(" . gT("ID") . ":" . $iSurveyId . ")"; $aData['sidemenu']["token_menu"] = TRUE; $aData['token_bar']['closebutton']['url'] = 'admin/tokens/sa/index/surveyid/' . $iSurveyId; $this->registerScriptFile('ADMIN_SCRIPT_PATH', 'tokensimport.js'); $aEncodings = aEncodingsArray(); if (Yii::app()->request->isPostRequest) { $sUploadCharset = Yii::app()->request->getPost('csvcharset'); if (!array_key_exists($sUploadCharset, $aEncodings)) { $sUploadCharset = 'auto'; } $bFilterDuplicateToken = Yii::app()->request->getPost('filterduplicatetoken'); $bFilterBlankEmail = Yii::app()->request->getPost('filterblankemail'); $bAllowInvalidEmail = Yii::app()->request->getPost('allowinvalidemail'); $aAttrFieldNames = getAttributeFieldNames($iSurveyId); $aDuplicateList = array(); $aInvalidTokenList = array(); $aInvalidEmailList = array(); $aInvalidFormatList = array(); $aModelErrorList = array(); $aFirstLine = array(); $oFile = CUploadedFile::getInstanceByName("the_file"); $sPath = Yii::app()->getConfig('tempdir'); $sFileName = $sPath . '/' . randomChars(20); if ($_FILES['the_file']['error'] == 1 || $_FILES['the_file']['error'] == 2) { Yii::app()->setFlashMessage(sprintf(gT("Sorry, this file is too large. Only files up to %01.2f MB are allowed."), getMaximumFileUploadSize() / 1024 / 1024), 'error'); } elseif (strtolower($oFile->getExtensionName()) != 'csv') { Yii::app()->setFlashMessage(gT("Only CSV files are allowed."), 'error'); } elseif (!@$oFile->saveAs($sFileName)) { Yii::app()->setFlashMessage(sprintf(gT("Upload file not found. Check your permissions and path (%s) for the upload directory"), $sPath), 'error'); } else { $iRecordImported = 0; $iRecordCount = 0; $iRecordOk = 0; $iInvalidEmailCount = 0; // Count invalid email imported // This allows to read file with MAC line endings too @ini_set('auto_detect_line_endings', true); // open it and trim the ednings $aTokenListArray = file($sFileName); $sBaseLanguage = Survey::model()->findByPk($iSurveyId)->language; if (!Yii::app()->request->getPost('filterduplicatefields') || Yii::app()->request->getPost('filterduplicatefields') && count(Yii::app()->request->getPost('filterduplicatefields')) == 0) { $aFilterDuplicateFields = array('firstname', 'lastname', 'email'); } else { $aFilterDuplicateFields = Yii::app()->request->getPost('filterduplicatefields'); } $sSeparator = Yii::app()->request->getPost('separator'); $aMissingAttrFieldName = $aInvalideAttrFieldName = array(); foreach ($aTokenListArray as $buffer) { $buffer = @mb_convert_encoding($buffer, "UTF-8", $sUploadCharset); if ($iRecordCount == 0) { // Parse first line (header) from CSV $buffer = removeBOM($buffer); // We alow all field except tid because this one is really not needed. $aAllowedFieldNames = Token::model($iSurveyId)->tableSchema->getColumnNames(); if (($kTid = array_search('tid', $aAllowedFieldNames)) !== false) { unset($aAllowedFieldNames[$kTid]); } // Some header don't have same column name $aReplacedFields = array('invited' => 'sent', 'reminded' => 'remindersent'); switch ($sSeparator) { case 'comma': $sSeparator = ','; break; case 'semicolon': $sSeparator = ';'; break; default: $comma = substr_count($buffer, ','); $semicolon = substr_count($buffer, ';'); if ($semicolon > $comma) { $sSeparator = ';'; } else { $sSeparator = ','; } } $aFirstLine = str_getcsv($buffer, $sSeparator, '"'); $aFirstLine = array_map('trim', $aFirstLine); $aIgnoredColumns = array(); // Now check the first line for invalid fields foreach ($aFirstLine as $index => $sFieldname) { $aFirstLine[$index] = preg_replace("/(.*) <[^,]*>\$/", "\$1", $sFieldname); $sFieldname = $aFirstLine[$index]; if (!in_array($sFieldname, $aAllowedFieldNames)) { $aIgnoredColumns[] = $sFieldname; } if (array_key_exists($sFieldname, $aReplacedFields)) { $aFirstLine[$index] = $aReplacedFields[$sFieldname]; } // Attribute not in list if (strpos($aFirstLine[$index], 'attribute_') !== false and !in_array($aFirstLine[$index], $aAttrFieldNames) and Yii::app()->request->getPost('showwarningtoken')) { $aInvalideAttrFieldName[] = $aFirstLine[$index]; } } //compare attributes with source csv if (Yii::app()->request->getPost('showwarningtoken')) { $aMissingAttrFieldName = array_diff($aAttrFieldNames, $aFirstLine); // get list of mandatory attributes $allAttrFieldNames = GetParticipantAttributes($iSurveyId); //if it isn't mandantory field we don't need to show in warning if (!empty($aAttrFieldNames)) { if (!empty($aMissingAttrFieldName)) { foreach ($aMissingAttrFieldName as $index => $AttrFieldName) { if (isset($allAttrFieldNames[$AttrFieldName]) and strtolower($allAttrFieldNames[$AttrFieldName]["mandatory"]) != "y") { unset($aMissingAttrFieldName[$index]); } } } if (isset($aInvalideAttrFieldName) and !empty($aInvalideAttrFieldName)) { foreach ($aInvalideAttrFieldName as $index => $AttrFieldName) { if (isset($allAttrFieldNames[$AttrFieldName]) and strtolower($allAttrFieldNames[$AttrFieldName]["mandatory"]) != "y") { unset($aInvalideAttrFieldName[$index]); } } } } } } else { $line = str_getcsv($buffer, $sSeparator, '"'); if (count($aFirstLine) != count($line)) { $aInvalidFormatList[] = sprintf(gT("Line %s"), $iRecordCount); $iRecordCount++; continue; } $aWriteArray = array_combine($aFirstLine, $line); //kick out ignored columns foreach ($aIgnoredColumns as $column) { unset($aWriteArray[$column]); } $bDuplicateFound = false; $bInvalidEmail = false; $bInvalidToken = false; $aWriteArray['email'] = isset($aWriteArray['email']) ? trim($aWriteArray['email']) : ""; $aWriteArray['firstname'] = isset($aWriteArray['firstname']) ? $aWriteArray['firstname'] : ""; $aWriteArray['lastname'] = isset($aWriteArray['lastname']) ? $aWriteArray['lastname'] : ""; $aWriteArray['language'] = isset($aWriteArray['language']) ? $aWriteArray['language'] : $sBaseLanguage; if ($bFilterDuplicateToken) { $aParams = array(); $oCriteria = new CDbCriteria(); $oCriteria->condition = ""; foreach ($aFilterDuplicateFields as $field) { if (isset($aWriteArray[$field])) { $oCriteria->addCondition("{$field} = :{$field}"); $aParams[":{$field}"] = $aWriteArray[$field]; } } if (!empty($aParams)) { $oCriteria->params = $aParams; } $dupresult = TokenDynamic::model($iSurveyId)->count($oCriteria); if ($dupresult > 0) { $bDuplicateFound = true; $aDuplicateList[] = sprintf(gT("Line %s : %s %s (%s)"), $iRecordCount, $aWriteArray['firstname'], $aWriteArray['lastname'], $aWriteArray['email']); } } //treat blank emails if (!$bDuplicateFound && $bFilterBlankEmail && $aWriteArray['email'] == '') { $bInvalidEmail = true; $aInvalidEmailList[] = sprintf(gT("Line %s : %s %s"), $iRecordCount, CHtml::encode($aWriteArray['firstname']), CHtml::encode($aWriteArray['lastname'])); } if (!$bDuplicateFound && $aWriteArray['email'] != '') { $aEmailAddresses = preg_split("/(,|;)/", $aWriteArray['email']); foreach ($aEmailAddresses as $sEmailaddress) { if (!validateEmailAddress($sEmailaddress)) { if ($bAllowInvalidEmail) { $iInvalidEmailCount++; if (empty($aWriteArray['emailstatus']) || strtoupper($aWriteArray['emailstatus'] == "OK")) { $aWriteArray['emailstatus'] = "invalid"; } } else { $bInvalidEmail = true; $aInvalidEmailList[] = sprintf(gT("Line %s : %s %s (%s)"), $iRecordCount, CHtml::encode($aWriteArray['firstname']), CHtml::encode($aWriteArray['lastname']), CHtml::encode($aWriteArray['email'])); } } } } if (!$bDuplicateFound && !$bInvalidEmail && isset($aWriteArray['token']) && trim($aWriteArray['token']) != '') { if (trim($aWriteArray['token']) != sanitize_token($aWriteArray['token'])) { $aInvalidTokenList[] = sprintf(gT("Line %s : %s %s (%s) - token : %s"), $iRecordCount, CHtml::encode($aWriteArray['firstname']), CHtml::encode($aWriteArray['lastname']), CHtml::encode($aWriteArray['email']), CHtml::encode($aWriteArray['token'])); $bInvalidToken = true; } // We allways search for duplicate token (it's in model. Allow to reset or update token ? if (Token::model($iSurveyId)->count("token=:token", array(":token" => $aWriteArray['token']))) { $bDuplicateFound = true; $aDuplicateList[] = sprintf(gT("Line %s : %s %s (%s) - token : %s"), $iRecordCount, CHtml::encode($aWriteArray['firstname']), CHtml::encode($aWriteArray['lastname']), CHtml::encode($aWriteArray['email']), CHtml::encode($aWriteArray['token'])); } } if (!$bDuplicateFound && !$bInvalidEmail && !$bInvalidToken) { // unset all empty value foreach ($aWriteArray as $key => $value) { if ($aWriteArray[$key] == "") { unset($aWriteArray[$key]); } if (substr($value, 0, 1) == '"' && substr($value, -1) == '"') { // Fix CSV quote $value = substr($value, 1, -1); } } // Some default value : to be moved to Token model rules in future release ? // But think we have to accept invalid email etc ... then use specific scenario $oToken = Token::create($iSurveyId); if ($bAllowInvalidEmail) { $oToken->scenario = 'allowinvalidemail'; } foreach ($aWriteArray as $key => $value) { $oToken->{$key} = $value; } if (!$oToken->save()) { $errors = $oToken->getErrors(); $aModelErrorList[] = sprintf(gT("Line %s : %s"), $iRecordCount, print_r($errors, true)); } else { $iRecordImported++; } } $iRecordOk++; } $iRecordCount++; } $iRecordCount = $iRecordCount - 1; unlink($sFileName); $aData['aTokenListArray'] = $aTokenListArray; // Big array in memory, just for success ? $aData['iRecordImported'] = $iRecordImported; $aData['iRecordOk'] = $iRecordOk; $aData['iRecordCount'] = $iRecordCount; $aData['aFirstLine'] = $aFirstLine; // Seem not needed $aData['aDuplicateList'] = $aDuplicateList; $aData['aInvalidTokenList'] = $aInvalidTokenList; $aData['aInvalidFormatList'] = $aInvalidFormatList; $aData['aInvalidEmailList'] = $aInvalidEmailList; $aData['aModelErrorList'] = $aModelErrorList; $aData['iInvalidEmailCount'] = $iInvalidEmailCount; $aData['thissurvey'] = getSurveyInfo($iSurveyId); $aData['iSurveyId'] = $aData['surveyid'] = $iSurveyId; $aData['aInvalideAttrFieldName'] = $aInvalideAttrFieldName; $aData['aMissingAttrFieldName'] = $aMissingAttrFieldName; $this->_renderWrappedTemplate('token', array('csvimportresult'), $aData); Yii::app()->end(); } } // If there are error with file : show the form $aData['aEncodings'] = $aEncodings; asort($aData['aEncodings']); $aData['iSurveyId'] = $iSurveyId; $aData['thissurvey'] = getSurveyInfo($iSurveyId); $aData['surveyid'] = $iSurveyId; $aTokenTableFields = getTokenFieldsAndNames($iSurveyId); unset($aTokenTableFields['sent']); unset($aTokenTableFields['remindersent']); unset($aTokenTableFields['remindercount']); unset($aTokenTableFields['usesleft']); foreach ($aTokenTableFields as $sKey => $sValue) { if ($sValue['description'] != $sKey) { $sValue['description'] .= ' - ' . $sKey; } $aNewTokenTableFields[$sKey] = $sValue['description']; } $aData['aTokenTableFields'] = $aNewTokenTableFields; // Get default character set from global settings $thischaracterset = getGlobalSetting('characterset'); // If no encoding was set yet, use the old "auto" default if ($thischaracterset == "") { $thischaracterset = "auto"; } $aData['thischaracterset'] = $thischaracterset; $this->_renderWrappedTemplate('token', array('csvupload'), $aData); }
/** * Add dummy tokens form */ function addDummies($iSurveyId, $subaction = '') { // CHECK TO SEE IF A TOKEN TABLE EXISTS FOR THIS SURVEY $bTokenExists = tableExists('{{tokens_' . $iSurveyId . '}}'); if (!$bTokenExists) { self::_newtokentable($iSurveyId); } $iSurveyId = sanitize_int($iSurveyId); $clang = $this->getController()->lang; if (!hasSurveyPermission($iSurveyId, 'tokens', 'create')) { Yii::app()->session['flashmessage'] = $clang->gT("You do not have sufficient rights to access this page."); $this->getController()->redirect($this->getController()->createUrl("/admin/survey/sa/view/surveyid/{$iSurveyId}")); } $this->getController()->loadHelper("surveytranslator"); if (!empty($subaction) && $subaction == 'add') { $this->getController()->loadLibrary('Date_Time_Converter'); $dateformatdetails = getDateFormatData(Yii::app()->session['dateformat']); //Fix up dates and match to database format if (trim(Yii::app()->request->getPost('validfrom')) == '') { $_POST['validfrom'] = null; } else { $datetimeobj = new Date_Time_Converter(trim(Yii::app()->request->getPost('validfrom')), $dateformatdetails['phpdate'] . ' H:i'); $_POST['validfrom'] = $datetimeobj->convert('Y-m-d H:i:s'); } if (trim(Yii::app()->request->getPost('validuntil')) == '') { $_POST['validuntil'] = null; } else { $datetimeobj = new Date_Time_Converter(trim(Yii::app()->request->getPost('validuntil')), $dateformatdetails['phpdate'] . ' H:i'); $_POST['validuntil'] = $datetimeobj->convert('Y-m-d H:i:s'); } $santitizedtoken = ''; $aData = array('firstname' => Yii::app()->request->getPost('firstname'), 'lastname' => Yii::app()->request->getPost('lastname'), 'email' => sanitize_email(Yii::app()->request->getPost('email')), 'emailstatus' => 'OK', 'token' => $santitizedtoken, 'language' => sanitize_languagecode(Yii::app()->request->getPost('language')), 'sent' => 'N', 'remindersent' => 'N', 'completed' => 'N', 'usesleft' => Yii::app()->request->getPost('usesleft'), 'validfrom' => Yii::app()->request->getPost('validfrom'), 'validuntil' => Yii::app()->request->getPost('validuntil')); // add attributes $attrfieldnames = getTokenFieldsAndNames($iSurveyId, true); foreach ($attrfieldnames as $attr_name => $desc) { $value = Yii::app()->request->getPost($attr_name); if ($desc['mandatory'] == 'Y' && trim($value) == '') { $this->getController()->error(sprintf($clang->gT('%s cannot be left empty'), $desc['description'])); } $aData[$attr_name] = Yii::app()->request->getPost($attr_name); } $amount = sanitize_int(Yii::app()->request->getPost('amount')); $tokenlength = sanitize_int(Yii::app()->request->getPost('tokenlen')); // Fill an array with all existing tokens $criteria = Tokens_dynamic::model($iSurveyId)->getDbCriteria(); $criteria->select = 'token'; $ntresult = Tokens_dynamic::model($iSurveyId)->findAllAsArray($criteria); //Use AsArray to skip active record creation $existingtokens = array(); foreach ($ntresult as $tkrow) { $existingtokens[$tkrow['token']] = true; } $invalidtokencount = 0; $newDummyToken = 0; while ($newDummyToken < $amount && $invalidtokencount < 50) { $aDataToInsert = $aData; $aDataToInsert['firstname'] = str_replace('{TOKEN_COUNTER}', $newDummyToken, $aDataToInsert['firstname']); $aDataToInsert['lastname'] = str_replace('{TOKEN_COUNTER}', $newDummyToken, $aDataToInsert['lastname']); $aDataToInsert['email'] = str_replace('{TOKEN_COUNTER}', $newDummyToken, $aDataToInsert['email']); $isvalidtoken = false; while ($isvalidtoken == false && $invalidtokencount < 50) { $newtoken = randomChars($tokenlength); if (!isset($existingtokens[$newtoken])) { $isvalidtoken = true; $existingtokens[$newtoken] = true; $invalidtokencount = 0; } else { $invalidtokencount++; } } if ($isvalidtoken) { $aDataToInsert['token'] = $newtoken; Tokens_dynamic::model()->insertToken($iSurveyId, $aDataToInsert); $newDummyToken++; } } $aData['thissurvey'] = getSurveyInfo($iSurveyId); $aData['surveyid'] = $iSurveyId; if (!$invalidtokencount) { $aData['success'] = false; $message = array('title' => $clang->gT("Success"), 'message' => $clang->gT("New dummy tokens were added.") . "<br /><br />\n<input type='button' value='" . $clang->gT("Display tokens") . "' onclick=\"window.open('" . $this->getController()->createUrl("admin/tokens/sa/browse/surveyid/{$iSurveyId}") . "', '_top')\" />\n"); } else { $aData['success'] = true; $message = array('title' => $clang->gT("Failed"), 'message' => "<p>" . sprintf($clang->gT("Only %s new dummy tokens were added after %s trials."), $newDummyToken, $invalidtokencount) . $clang->gT("Try with a bigger token length.") . "</p>" . "\n<input type='button' value='" . $clang->gT("Display tokens") . "' onclick=\"window.open('" . $this->getController()->createUrl("admin/tokens/sa/browse/surveyid/{$iSurveyId}") . "', '_top')\" />\n"); } $this->_renderWrappedTemplate('token', array('tokenbar', 'message' => $message), $aData); } else { $tkcount = Tokens_dynamic::model($iSurveyId)->count(); $tokenlength = Yii::app()->db->createCommand()->select('tokenlength')->from('{{surveys}}')->where('sid=:sid')->bindParam(":sid", $iSurveyId, PDO::PARAM_INT)->query()->readColumn(0); if (empty($tokenlength)) { $tokenlength = 15; } $thissurvey = getSurveyInfo($iSurveyId); $aData['thissurvey'] = $thissurvey; $aData['surveyid'] = $iSurveyId; $aData['tokenlength'] = $tokenlength; $aData['dateformatdetails'] = getDateFormatData(Yii::app()->session['dateformat'], $clang->langcode); $aData['aAttributeFields'] = GetParticipantAttributes($iSurveyId); $this->_renderWrappedTemplate('token', array('tokenbar', 'dummytokenform'), $aData); } }