public function preDispatch(Zend_Controller_Request_Abstract $request) { if ('company' == $request->getControllerName()) { $tsn = $request->tsn ? $request->tsn : $_COOKIE['tsn']; if ($tsn) { $token = Token::create($tsn); $token->update_sync_time(); } else { $token = Token::create_abstract('123'); } if ($token->is_logined() == true) { if ($token->is_expire()) { $token->destroy(); include_once LIB_PATH . '/view_helper/BuildUrl.php'; $url_builder = new Zend_View_Helper_BuildUrl(); $referer = SearchFilter::slashes($url_builder->buildUrl($request->getActionName(), $request->getControllerName(), $request->getModuleName())); $login_url = $url_builder->buildUrl('login', 'auth', 'index', array('redirect' => $referer)); $redirector = new Zend_Controller_Action_Helper_Redirector(); $redirector->gotoUrl($login_url); return; } $token->register(); } else { if ('auth' != $request->getActionName()) { $token->destroy(); $request->setModuleName('index'); $request->setControllerName('auth'); $request->setActionName('login'); } } } }
public function testRetrieve() { self::authorizeFromEnv(); $token = Token::create(array("card" => array("number" => "4242424242424242", "exp_month" => 6, "exp_year" => date('Y') + 3, "cvc" => "314"))); $token_retrieve = Token::retrieve($token->id); $this->assertSame($token->id, $token_retrieve->id); }
public function __construct() { $this->_setup(); Token::create(); if (!isset($_SESSION['current_num'])) { $this->_initSession(); } }
public function testTokenCreate() { $params = array('card_number' => '4111111111111111', 'expiration_month' => '01', 'expiration_year' => date('Y') + 1, 'cvv' => '123', 'holder_name' => 'John Doe'); $this->mockResponse($this->success_token_create_response()); $token = Token::create($params); $this->assertObjectHasAttribute('token', $token); $this->assertFalse($token->is_used); $this->assertFalse($token->has_expired); }
public function testVerify() { self::authorizeFromEnv(); $bankAccountToken = Token::create(array('bank_account' => array('country' => 'US', 'routing_number' => '110000000', 'account_number' => '000123456789', 'name' => 'Jane Austen', 'account_holder_type' => 'company'))); $customer = Customer::create(); $externalAccount = $customer->sources->create(array('bank_account' => $bankAccountToken->id)); $verifiedAccount = $externalAccount->verify(array('amounts' => array(32, 45)), null); $base = Customer::classUrl(); $parentExtn = $externalAccount['customer']; $extn = $externalAccount['id']; $this->assertEquals("{$base}/{$parentExtn}/sources/{$extn}", $externalAccount->instanceUrl()); }
/** * System Constructor. * Initializing the system, check the config file * * @author Puguh Wijayanto (www.metalgenix.com) * @since 0.0.1 */ public function __construct() { self::config('config'); new Db(); new Hooks(); self::lang(Options::get('system_lang')); new Site(); Vendor::autoload(); Token::create(); Mod::loader(); Theme::loader(); Hooks::run('init'); }
public function testRecipientDeleteCard() { $token = Token::create(array("card" => array("number" => "4000056655665556", "exp_month" => 5, "exp_year" => date('Y') + 3, "cvc" => "314"))); $recipient = $this->createTestRecipient(); $createdCard = $recipient->cards->create(array("card" => $token->id)); $recipient->save(); $updatedRecipient = Recipient::retrieve($recipient->id); $updatedCards = $updatedRecipient->cards->all(); $this->assertSame(count($updatedCards["data"]), 1); $deleteStatus = $updatedRecipient->cards->retrieve($createdCard->id)->delete(); $this->assertTrue($deleteStatus->deleted); $updatedRecipient->save(); $postDeleteRecipient = Recipient::retrieve($recipient->id); $postDeleteCards = $postDeleteRecipient->cards->all(); $this->assertSame(count($postDeleteCards["data"]), 0); }
public function testRecipientDeleteCard() { $token = Token::create(array('card' => array('number' => '4000056655665556', 'exp_month' => 5, 'exp_year' => date('Y') + 3, 'cvc' => '314'))); $recipient = $this->createTestRecipient(); $createdCard = $recipient->cards->create(array('card' => $token->id)); $recipient->save(); $updatedRecipient = Recipient::retrieve($recipient->id); $updatedCards = $updatedRecipient->cards->all(); $this->assertSame(count($updatedCards['data']), 1); $deleteStatus = $updatedRecipient->cards->retrieve($createdCard->id)->delete(); $this->assertTrue($deleteStatus->deleted); $updatedRecipient->save(); $postDeleteRecipient = Recipient::retrieve($recipient->id); $postDeleteCards = $postDeleteRecipient->cards->all(); $this->assertSame(count($postDeleteCards['data']), 0); }
public function authAction() { $params = $this->_getAllParams(); if (empty($params['uname']) || empty($params['upwd'])) { $this->forward('login'); return; } //输入数据需要进行验证 $loginname = addslashes($params['uname']); $password = md5(trim($params['upwd'])); //生产COOKIE序列号 $snlogin = md5($loginname . $password); $snlogin = substr($snlogin, 2, 9); $token = Token::create($snlogin); if ($token->is_logined()) { setcookie('tsn', $snlogin, -1, '/'); $this->forward('index', 'company', 'index'); return; } $adapter = new Zend_Auth_Adapter_DbTable(GlobalFactory::get_db()); $adapter->setTableName(DBTables::USER)->setIdentityColumn('username')->setCredentialColumn('passwd')->setIdentity($loginname)->setCredential($password); //进行查询验证 $auth = Zend_Auth::getInstance(); $result = $auth->authenticate($adapter); //没通过验证就跳回到登录页面 if (!$result->isValid()) { $this->forward('login'); return; } //通过验证 $res_obj = $adapter->getResultRowObject(); //帐号被禁用 if (0 != $res_obj->status) { $this->forward('login'); return; } setcookie('tsn', $snlogin, -1, '/'); $fields = array('sn' => $snlogin, 'uid' => $res_obj->id, 'uname' => $res_obj->username, 'nickname' => $res_obj->nickname); $token->register($fields); //跳转到默认首页 $this->forward('index', 'company', 'index'); }
public function testCustomerDeleteSource() { self::authorizeFromEnv(); $token = Token::create(array("card" => array("number" => "4242424242424242", "exp_month" => 5, "exp_year" => date('Y') + 3, "cvc" => "314"))); $customer = $this->createTestCustomer(); $createdSource = $customer->sources->create(array("source" => $token->id)); $customer->save(); $updatedCustomer = Customer::retrieve($customer->id); $updatedSources = $updatedCustomer->sources->all(); $this->assertSame(count($updatedSources["data"]), 2); $deleteStatus = $updatedCustomer->sources->retrieve($createdSource->id)->delete(); $this->assertTrue($deleteStatus->deleted); $updatedCustomer->save(); $postDeleteCustomer = Customer::retrieve($customer->id); $postDeleteSources = $postDeleteCustomer->sources->all(); $this->assertSame(count($postDeleteSources["data"]), 1); }
/** * 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(); }
<section id="last"> <div class="container"> <div class="row"> <div class="col-lg-8 col-lg-offset-2 text-center"> <h2 class="margin-top-0 wow fadeIn">Get in Touch</h2> <hr class="primary"> <p>We love feedback. Fill out the form below and we'll get back to you as soon as possible.</p> </div> <div class="col-lg-10 col-lg-offset-1 text-center"> <form action="create" method="POST" class="contact-form row"> <input type="hidden" value="<?php echo Token::create(); ?> " name="token"> <div class="col-md-12"> <label></label> <input type="text" class="form-control" placeholder="Title" name="title"> </div> <div class="col-md-12"> <label></label> <textarea class="form-control" rows="9" placeholder="Your article here.." name="article"></textarea> </div> <div class="col-md-4 col-md-offset-4"> <label></label> <button type="submit" data-toggle="modal" data-target="#alertModal" class="btn btn-primary btn-block btn-lg">create <i class="ion-android-arrow-forward"></i></button> </div>
public function googleLogin($action = null) { try { $client = new Google_Client(); $client->setAuthConfigFile(storage_path() . "/credentials/client_secret.json"); $client->setAccessType('online'); // default: offline $client->setRedirectUri('https://api.upa.edu.mx/1/oauth2callback/auth?hauth.done=Google'); $client->setScopes(array(Google_Service_Drive::DRIVE_METADATA_READONLY, 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile')); $client->setDeveloperKey('AIzaSyARhUTSZ3VQ2wYhgqnTlSacNDOycU8_V0o'); // API key //var_dump($client->getAccessToken()); if (isset($_GET['logout'])) { // logout: destroy token unset($_SESSION['token']); die('Logged out.'); } if (isset($_GET['code'])) { // we received the positive auth callback, get the token and store it in session $client->authenticate($_GET['code']); $_SESSION['token'] = $client->getAccessToken(); $service = new Google_Service_Plus($client); $userInfo = $service->people->get("me"); $iemail = $userInfo['emails'][0]['value']; $files_service = new Google_Service_Drive($client); $pageToken = NULL; $i = 0; do { try { $parameters = array(); if ($pageToken) { $parameters['pageToken'] = $pageToken; } $files = $files_service->files->listFiles($parameters); $my_files = $files->getItems(); foreach ($my_files as $f) { // echo $i++. " - " . $f->getTitle(); // echo "<br/>"; } $pageToken = $files->getNextPageToken(); } catch (Exception $e) { print "An error occurred: " . $e->getMessage(); $pageToken = NULL; } } while ($pageToken); $persona = Persona::byEmail($iemail)->first(); if ($persona) { //var_dump($persona); $token = Token::where("idpersonas", '=', $persona->idpersonas)->where("app_id", '=', 1)->whereRaw('(updated_at + INTERVAL ' . Config::get('app.session_timeout') . ' MINUTE) > NOW()')->first(); //var_dump($token); $token = Token::create(array("idpersonas" => $persona->idpersonas, "app_id" => 1, "token" => Hash::make(uniqid() . $persona->idpersonas . str_random()))); $persona->token = $token->token; //var_dump($persona);exit(); //return Response::json(array("usuario" => array("id" => $persona->idpersonas, "iemail" => $persona->iemail, "token" => $persona->token))); return Redirect::to('https://intranet.upa.edu.mx/intra/validar_i_2.php?loginupp_i=' . $persona->idpersonas . '&token=' . $persona->token); } else { return Response::json(array('error' => "Wrong Credentials"), 404); } } if (isset($_SESSION['token'])) { // extract token from session and configure client $token = $_SESSION['token']; $client->setAccessToken($token); } if (!$client->getAccessToken()) { // auth call to google $authUrl = $client->createAuthUrl(); header("Location: " . $authUrl); die; } // $oauth = new Google_Service_Oauth2($client); } catch (Exception $e) { return $e->getMessage(); } //var_dump($profile); }
$organization["config"] = json_decode($organization["config_json"], 1); } else { $organization = array(); $errors[] = "Invalid team number"; } } if (strlen($username) && strlen($password) && count($organization)) { $users = new Auth($dbh, $organization["id"]); $user = $users->authUsernamePassword($username, $password); if (is_array($user)) { if (isset($user["error"])) { // Inactive user, etc. $errors[] = $user["error"]; } else { $success = true; $token = Token::create($dbh, $user["id"]); $sdb = new ScoutingDB($dbh, $organization["id"], 1, $user["id"]); $organization["team_numbers"] = array_map(function ($team) { return $team["team_number"]; }, $sdb->getList("team", "team_number", "up", 1, 10000, $fields = array("team_number"), 1)); } } else { $errors[] = "Invalid username/password"; } } else { $errors[] = $required_fields_err; } $output = array(); $output["success"] = $success; $output["error"] = $errors; if (strlen($token)) {
/** * 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 = '') { $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' => 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 = Token::model($iSurveyId)->getDbCriteria(); $criteria->select = 'token'; $ntresult = Token::model($iSurveyId)->findAll($criteria); $existingtokens = array(); foreach ($ntresult as $tkrow) { $existingtokens[$tkrow['token']] = true; } $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 { $tkcount = Token::model($iSurveyId)->count(); $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); } }
/** * Get the token id according to filled values * @param $iSurveyId * @return integer : the token id created */ public function getTokenId($iSurveyId) { $sLanguage = App()->language; $aSurveyInfo = getSurveyInfo($iSurveyId, $sLanguage); $aFieldValue = $this->getFieldValue($iSurveyId); // Now construct the text returned $oToken = Token::model($iSurveyId)->findByAttributes(array('email' => $aFieldValue['sEmail'])); if ($oToken) { if ($oToken->usesleft < 1 && $aSurveyInfo['alloweditaftercompletion'] != 'Y') { $this->aRegisterErrors[] = gT("The email address you have entered is already registered and the survey has been completed."); } elseif (strtolower(substr(trim($oToken->emailstatus), 0, 6)) === "optout") { $this->aRegisterErrors[] = gT("This email address cannot be used because it was opted out of this survey."); } elseif (!$oToken->emailstatus && $oToken->emailstatus != "OK") { $this->aRegisterErrors[] = gT("This email address is already registered but the email adress was bounced."); } else { $this->sMailMessage = gT("The address you have entered is already registered. An email has been sent to this address with a link that gives you access to the survey."); return $oToken->tid; } } else { // TODO : move xss filtering in model $oToken = Token::create($iSurveyId); $oToken->firstname = sanitize_xss_string($aFieldValue['sFirstName']); $oToken->lastname = sanitize_xss_string($aFieldValue['sLastName']); $oToken->email = $aFieldValue['sEmail']; $oToken->emailstatus = 'OK'; $oToken->language = $sLanguage; $aFieldValue['aAttribute'] = array_map('sanitize_xss_string', $aFieldValue['aAttribute']); $oToken->setAttributes($aFieldValue['aAttribute']); if ($aSurveyInfo['startdate']) { $oToken->validfrom = $aSurveyInfo['startdate']; } if ($aSurveyInfo['expires']) { $oToken->validuntil = $aSurveyInfo['expires']; } $oToken->generateToken(); $oToken->save(); $this->sMailMessage = 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."); return $oToken->tid; } }
function XMLImportTokens($sFullFilePath, $iSurveyID, $sCreateMissingAttributeFields = true) { Yii::app()->loadHelper('database'); $clang = Yii::app()->lang; $sXMLdata = file_get_contents($sFullFilePath); $xml = simplexml_load_string($sXMLdata, 'SimpleXMLElement', LIBXML_NONET); $results['warnings'] = array(); if ($xml->LimeSurveyDocType != 'Tokens') { $results['error'] = $clang->gT("This is not a valid token data XML file."); return $results; } if (!isset($xml->tokens->fields)) { $results['tokens'] = 0; return $results; } $results['tokens'] = 0; $results['tokenfieldscreated'] = 0; if ($sCreateMissingAttributeFields) { // Get a list with all fieldnames in the XML $aXLMFieldNames = array(); foreach ($xml->tokens->fields->fieldname as $sFieldName) { $aXLMFieldNames[] = (string) $sFieldName; } // Get a list of all fieldnames in the token table $aTokenFieldNames = Yii::app()->db->getSchema()->getTable("{{tokens_{$iSurveyID}}}", true); $aTokenFieldNames = array_keys($aTokenFieldNames->columns); $aFieldsToCreate = array_diff($aXLMFieldNames, $aTokenFieldNames); Yii::app()->loadHelper('update/updatedb'); foreach ($aFieldsToCreate as $sField) { if (strpos($sField, 'attribute') !== false) { addColumn('{{tokens_' . $iSurveyID . '}}', $sField, 'string'); } } } switchMSSQLIdentityInsert('tokens_' . $iSurveyID, true); foreach ($xml->tokens->rows->row as $row) { $insertdata = array(); foreach ($row as $key => $value) { $insertdata[(string) $key] = (string) $value; } $token = Token::create($iSurveyID); $token->setAttributes($insertdata, false); if (!$token->save()) { $results['warnings'][] = $clang->gT("Skipped tokens entry:") . ' ' . implode('. ', $token->errors['token']); } $results['tokens']++; } switchMSSQLIdentityInsert('tokens_' . $iSurveyID, false); if (Yii::app()->db->getDriverName() == 'pgsql') { try { Yii::app()->db->createCommand("SELECT pg_catalog.setval(pg_get_serial_sequence('{{tokens_" . $iSurveyID . "}}', 'tid'), (SELECT MAX(tid) FROM {{tokens_" . $iSurveyID . "}}))")->execute(); } catch (Exception $oException) { } } return $results; }
/** * RPC Routine to add participants to the tokens collection of the survey. * Returns the inserted data including additional new information like the Token entry ID and the token string. * * @access public * @param string $sSessionKey Auth credentials * @param int $iSurveyID Id of the Survey * @param struct $aParticipantData Data of the participants to be added * @param bool Optional - Defaults to true and determins if the access token automatically created * @return array The values added */ public function add_participants($sSessionKey, $iSurveyID, $aParticipantData, $bCreateToken = true) { if (!$this->_checkSessionKey($sSessionKey)) { return array('status' => 'Invalid session key'); } $oSurvey = Survey::model()->findByPk($iSurveyID); if (is_null($oSurvey)) { return array('status' => 'Error: Invalid survey ID'); } if (Permission::model()->hasSurveyPermission($iSurveyID, 'tokens', 'create')) { if (!Yii::app()->db->schema->getTable('{{tokens_' . $iSurveyID . '}}')) { return array('status' => 'No token table'); } $aDestinationFields = array_flip(Token::model($iSurveyID)->getMetaData()->tableSchema->columnNames); foreach ($aParticipantData as &$aParticipant) { $token = Token::create($iSurveyID); $token->setAttributes(array_intersect_key($aParticipant, $aDestinationFields)); if ($bCreateToken) { $token->generateToken(); } if ($token->save()) { $aParticipant = $token->getAttributes(); } else { $aParticipant["errors"] = $token->errors; } } return $aParticipantData; } else { return array('status' => 'No permission'); } }
/** * import from csv */ function import($iSurveyId) { $iSurveyId = (int) $iSurveyId; if (!Permission::model()->hasSurveyPermission($iSurveyId, 'tokens', 'import')) { Yii::app()->session['flashmessage'] = gT("You do not have sufficient rights 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); } App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('adminscripts') . '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(); $aInvalidEmailList = array(); $aInvalidFormatList = array(); $aModelErrorList = array(); $aFirstLine = array(); $oFile = CUploadedFile::getInstanceByName("the_file"); $sPath = Yii::app()->getConfig('tempdir'); $sFileName = $sPath . '/' . randomChars(20); //$sFileTmpName=$oFile->getTempName(); /* More way to validate CSV ? $aCsvMimetypes = array( 'text/csv', 'text/plain', 'application/csv', 'text/comma-separated-values', 'application/excel', 'application/vnd.ms-excel', 'application/vnd.msexcel', 'text/anytext', 'application/octet-stream', 'application/txt', ); */ if (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'); 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]; } } } 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; $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 = explode(';', $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'])) { $aWriteArray['token'] = sanitize_token($aWriteArray['token']); // 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) { // 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()) { tracevar($oToken->getErrors()); $aModelErrorList[] = sprintf(gt("Line %s : %s"), $iRecordCount, Chtml::errorSummary($oToken)); } 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['aInvalidFormatList'] = $aInvalidFormatList; $aData['aInvalidEmailList'] = $aInvalidEmailList; $aData['aModelErrorList'] = $aModelErrorList; $aData['iInvalidEmailCount'] = $iInvalidEmailCount; $aData['thissurvey'] = getSurveyInfo($iSurveyId); $aData['iSurveyId'] = $aData['surveyid'] = $iSurveyId; $this->_renderWrappedTemplate('token', array('tokenbar', 'csvpost'), $aData); Yii::app()->end(); } } // If there are error with file : show the form $aData['aEncodings'] = $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; $this->_renderWrappedTemplate('token', array('tokenbar', 'csvupload'), $aData); }
public function actionLogin() { if (!isset($_REQUEST['LoginForm'])) { echo CJSON::encode($this->statusError('form not available')); Yii::app()->end(); } $customer = Customer::model()->findByAttributes(array('username' => $_REQUEST['LoginForm']['username'])); if ($customer == null) { echo CJSON::encode($this->statusError('username error')); } elseif (!$customer->validatePassword($_REQUEST['LoginForm']['password'])) { echo CJSON::encode($this->statusError('password error')); } else { echo CJSON::encode($this->statusSuccess(array('access_token' => Token::create($customer->id), 'username' => $customer->username, 'id' => $customer->id))); } Yii::app()->end(); }
private function createCardToken() { $this->mockResponse($this->successCreateTokenResponse()); $params = array('card_number' => '4908440000000003', 'expiration_month' => '01', 'expiration_year' => date('Y') + 1, 'cvv' => '123', 'holder_name' => 'John Doe'); $response = Token::create($params); return $response; }
public function testCustomerDeleteSource() { self::authorizeFromEnv(); $token = Token::create(array('card' => array('number' => '4242424242424242', 'exp_month' => 5, 'exp_year' => date('Y') + 3, 'cvc' => '314'))); $customer = $this->createTestCustomer(); $createdSource = $customer->sources->create(array('source' => $token->id)); $customer->save(); $updatedCustomer = Customer::retrieve($customer->id); $updatedSources = $updatedCustomer->sources->all(); $this->assertSame(count($updatedSources['data']), 2); $deleteStatus = $updatedCustomer->sources->retrieve($createdSource->id)->delete(); $this->assertTrue($deleteStatus->deleted); $updatedCustomer->save(); $postDeleteCustomer = Customer::retrieve($customer->id); $postDeleteSources = $postDeleteCustomer->sources->all(); $this->assertSame(count($postDeleteSources['data']), 1); }
/** * * @group ecommerce */ public function testTokenCreateWithInvalidCvv() { $params = array('card_number' => '4111111111111111', 'expiration_month' => '01', 'expiration_year' => date('Y') + 1, 'cvv' => '11', 'holder_name' => 'John Doe'); $this->mockResponse($this->failed_token_create_response_invalid_cvv()); $response = Token::create($params); $this->assertObjectHasAttribute('error', $response); $this->assertEquals($response->error->code, 20003); }
<div class="sidebar"> <h2>Login / Register</h2> <div class="inner"> <form action="login.php" method="post"> <ul id="login"> <li> Username: <br> <input type="text" name="username"> </li> <li> Password: <br> <input type="password" name="password"> </li> <li> <input type="submit" value="Log in"> </li> <?php /* Form file */ Token::create(); ?> <center> <h3><a href="register.php">New account</a></h3> <font size="1">- Lost <a href="recovery.php?mode=username">username</a> or <a href="recovery.php?mode=password">password</a>?</font></center> </ul> </form> </div> </div>
/** * * @group ecommerce */ public function testPaymentCreateFromCardTokenProvidedNoAmount() { $this->mockResponse($this->failed_payment_create_response3()); $params = array('card_number' => '4111111111111111', 'expiration_month' => '01', 'expiration_year' => date('Y') + 1, 'cvv' => '123', 'holder_name' => 'John Doe'); if ($this->isRemote()) { $token = Token::create($params); $token_string = $token->token; } else { $token_string = 'ctn_foobar'; } $params2 = array('token' => $token_string); $payment = Payment::create($params2); $this->assertObjectHasAttribute('error', $payment); $this->assertEquals($payment->error->code, 40002); }
private function parseTokey() { if (!C("TOKEN_ON")) { return; } Token::create(); $preg = '/<\\/form>/iUs'; $content = '<input type="hidden" name="<?php echo C("TOKEN_NAME");?>" value="<?php echo $_SESSION[C("TOKEN_NAME")]?>"/></form>'; $this->content = preg_replace($preg, $content, $this->content); }
public function beforeSurveyPage() { $oEvent = $this->event; $iSurveyId = $oEvent->get('surveyId'); $bUse = $this->get('bUse', 'Survey', $iSurveyId); if ($bUse) { //Only private surveys with authsaml plugin enabled if ($this->ssp->isAuthenticated()) { //Only idp users $sLanguage = Yii::app()->request->getParam('lang'); $aSurveyInfo = getSurveyInfo($iSurveyId, $sLanguage); $aSurveyIdpAttributes = array_diff(json_decode($this->get('surveyIdpAttributes', 'Survey', $iSurveyId), true), array('none')); if ($this->checkIdpAttributes($aSurveyIdpAttributes)) { $oToken = TokenDynamic::model($iSurveyId)->find('email=:email', array(':email' => $this->getUserMail())); if ($oToken) { //Allow survey access if the token is given if (Yii::app()->request->getParam('token')) { return; } $sToken = $oToken->token; } else {//Creation of the token $oToken = Token::create($iSurveyId); $oToken->firstname = $this->getUserGivenName(); $oToken->lastname = $this->getUserSurName(); $oToken->email = $this->getUserMail(); $oToken->emailstatus = 'OK'; $oToken->language = $sLanguage; if ($aSurveyInfo['startdate']) { $oToken->validfrom = $aSurveyInfo['startdate']; } if ($aSurveyInfo['expires']) { $oToken->validuntil = $aSurveyInfo['expires']; } $oToken->save(); $iTokenId = $oToken->tid; $sToken = TokenDynamic::model($iSurveyId)->createToken($iTokenId); } if ($sToken) { $surveylink = App()->createAbsoluteUrl("/survey/index/sid/{$iSurveyId}", array('token' => $sToken)); header('Location: ' . $surveylink); } } else { $aReplacementFields = array(); $aReplacementFields["{ADMINNAME}"] = $aSurveyInfo['adminname']; $aReplacementFields["{ADMINEMAIL}"] = $aSurveyInfo['adminemail']; $sLanguage = Yii::app()->request->getParam('lang', ''); if ($sLanguage == "") { $sLanguage = Survey::model()->findByPk($iSurveyId)->language; } $aSurveyInfo = getSurveyInfo($iSurveyId, $sLanguage); $sTemplatePath = $aData['templatedir'] = getTemplatePath($aSurveyInfo['template']); $sAttributesRequired = ''; $sAttributesReceived = ''; foreach ($aSurveyIdpAttributes as $key => $value) { $sAttributesRequired .= "<li>{$key} = \"{$value}\"</li>"; } foreach (array_intersect_key($this->attributes, $aSurveyIdpAttributes) as $key => $value) { $sAttributesReceived .= "<li>{$key} = \"{$value[0]}\"</li>"; } $sReturnHtml = "<div id='wrapper' class='message tokenmessage'>" . "<h3>Acesso ao questionário não permitido!</h3>\n" . "<p>Informações de usuário necessárias:</p>\n" . "<ul>$sAttributesRequired</ul><br />" . "<p>Informações de usuário recebidas:</p>\n" . "<ul>$sAttributesReceived</ul><br />" . "<p>Entre em contato com o administrador do questionário: {ADMINNAME} ({ADMINEMAIL})</p>" . "</div>\n"; $sReturnHtml = ReplaceFields($sReturnHtml, $aReplacementFields); ob_start(function($buffer, $phase) { App()->getClientScript()->render($buffer); App()->getClientScript()->reset(); return $buffer; }); ob_implicit_flush(false); sendCacheHeaders(); doHeader(); $aData['thissurvey'] = $aSurveyInfo; $aData['thissurvey'] = $aSurveyInfo; echo templatereplace(file_get_contents($sTemplatePath . '/startpage.pstpl'), array(), $aData); echo templatereplace(file_get_contents($sTemplatePath . '/survey.pstpl'), array(), $aData); echo $sReturnHtml; echo templatereplace(file_get_contents($sTemplatePath . '/endpage.pstpl'), array(), $aData); doFooter(); ob_flush(); App()->end(); } } else {// Asks idp authentication header('Location: ' . $this->ssp->getLoginURL()); } } }
/** * import from csv */ function import($iSurveyId) { $clang = $this->getController()->lang; $iSurveyId = (int) $iSurveyId; if (!Permission::model()->hasSurveyPermission($iSurveyId, 'tokens', 'import')) { 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}")); } // CHECK TO SEE IF A TOKEN TABLE EXISTS FOR THIS SURVEY $bTokenExists = tableExists('{{tokens_' . $iSurveyId . '}}'); if (!$bTokenExists) { self::_newtokentable($iSurveyId); } App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('adminscripts') . 'tokensimport.js'); $aEncodings = aEncodingsArray(); if (Yii::app()->request->getPost('submit')) { if (Yii::app()->request->getPost('csvcharset') && Yii::app()->request->getPost('csvcharset')) { $uploadcharset = Yii::app()->request->getPost('csvcharset'); if (!array_key_exists($uploadcharset, $aEncodings)) { $uploadcharset = 'auto'; } $filterduplicatetoken = Yii::app()->request->getPost('filterduplicatetoken') && Yii::app()->request->getPost('filterduplicatetoken') == 'on'; $filterblankemail = Yii::app()->request->getPost('filterblankemail') && Yii::app()->request->getPost('filterblankemail') == 'on'; } $attrfieldnames = getAttributeFieldNames($iSurveyId); $duplicatelist = array(); $invalidemaillist = array(); $invalidformatlist = array(); $firstline = array(); $sPath = Yii::app()->getConfig('tempdir'); $sFileTmpName = $_FILES['the_file']['tmp_name']; $sFilePath = $sPath . '/' . randomChars(20); if (!@move_uploaded_file($sFileTmpName, $sFilePath)) { $aData['sError'] = $clang->gT("Upload file not found. Check your permissions and path ({$sFilePath}) for the upload directory"); $aData['aEncodings'] = $aEncodings; $aData['iSurveyId'] = $aData['surveyid'] = $iSurveyId; $aData['thissurvey'] = getSurveyInfo($iSurveyId); $this->_renderWrappedTemplate('token', array('tokenbar', 'csvupload'), $aData); } else { $xz = 0; $recordcount = 0; $xv = 0; // This allows to read file with MAC line endings too @ini_set('auto_detect_line_endings', true); // open it and trim the ednings $tokenlistarray = file($sFilePath); $sBaseLanguage = Survey::model()->findByPk($iSurveyId)->language; if (!Yii::app()->request->getPost('filterduplicatefields') || Yii::app()->request->getPost('filterduplicatefields') && count(Yii::app()->request->getPost('filterduplicatefields')) == 0) { $filterduplicatefields = array('firstname', 'lastname', 'email'); } else { $filterduplicatefields = Yii::app()->request->getPost('filterduplicatefields'); } $separator = returnGlobal('separator'); foreach ($tokenlistarray as $buffer) { $buffer = @mb_convert_encoding($buffer, "UTF-8", $uploadcharset); if ($recordcount == 0) { // Parse first line (header) from CSV $buffer = removeBOM($buffer); // We alow all field except tid because this one is really not needed. $allowedfieldnames = array('participant_id', 'firstname', 'lastname', 'email', 'emailstatus', 'token', 'language', 'blacklisted', 'sent', 'remindersent', 'remindercount', 'validfrom', 'validuntil', 'completed', 'usesleft'); $allowedfieldnames = array_merge($attrfieldnames, $allowedfieldnames); // Some header don't have same column name $aReplacedFields = array('invited' => 'sent'); switch ($separator) { case 'comma': $separator = ','; break; case 'semicolon': $separator = ';'; break; default: $comma = substr_count($buffer, ','); $semicolon = substr_count($buffer, ';'); if ($semicolon > $comma) { $separator = ';'; } else { $separator = ','; } } $firstline = str_getcsv($buffer, $separator, '"'); $firstline = array_map('trim', $firstline); $ignoredcolumns = array(); // Now check the first line for invalid fields foreach ($firstline as $index => $fieldname) { $firstline[$index] = preg_replace("/(.*) <[^,]*>\$/", "\$1", $fieldname); $fieldname = $firstline[$index]; if (!in_array($fieldname, $allowedfieldnames)) { $ignoredcolumns[] = $fieldname; } if (array_key_exists($fieldname, $aReplacedFields)) { $firstline[$index] = $aReplacedFields[$fieldname]; } } if (!in_array('firstname', $firstline) || !in_array('lastname', $firstline) || !in_array('email', $firstline)) { $recordcount = count($tokenlistarray); break; } } else { $line = str_getcsv($buffer, $separator, '"'); if (count($firstline) != count($line)) { $invalidformatlist[] = $recordcount; $recordcount++; continue; } $writearray = array_combine($firstline, $line); //kick out ignored columns foreach ($ignoredcolumns as $column) { unset($writearray[$column]); } $dupfound = false; $invalidemail = false; if ($filterduplicatetoken != false) { $dupquery = "SELECT count(tid) from {{tokens_" . intval($iSurveyId) . "}} where 1=1"; foreach ($filterduplicatefields as $field) { if (isset($writearray[$field])) { $dupquery .= " and " . Yii::app()->db->quoteColumnName($field) . " = " . Yii::app()->db->quoteValue($writearray[$field]); } } $dupresult = Yii::app()->db->createCommand($dupquery)->queryScalar(); if ($dupresult > 0) { $dupfound = true; $duplicatelist[] = Yii::app()->db->quoteValue($writearray['firstname']) . " " . Yii::app()->db->quoteValue($writearray['lastname']) . " (" . Yii::app()->db->quoteValue($writearray['email']) . ")"; } } $writearray['email'] = trim($writearray['email']); //treat blank emails if ($filterblankemail && $writearray['email'] == '') { $invalidemail = true; $invalidemaillist[] = $line[0] . " " . $line[1] . " ( )"; } if ($writearray['email'] != '') { $aEmailAddresses = explode(';', $writearray['email']); foreach ($aEmailAddresses as $sEmailaddress) { if (!validateEmailAddress($sEmailaddress)) { $invalidemail = true; $invalidemaillist[] = $line[0] . " " . $line[1] . " (" . $line[2] . ")"; } } } if (isset($writearray['token'])) { $writearray['token'] = sanitize_token($writearray['token']); } if (!$dupfound && !$invalidemail) { // unset all empty value foreach ($writearray as $key => $value) { if ($writearray[$key] == "") { unset($writearray[$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 $writearray['emailstatus'] = isset($writearray['emailstatus']) ? $writearray['emailstatus'] : "OK"; $writearray['language'] = isset($writearray['language']) ? $writearray['language'] : $sBaseLanguage; $oToken = Token::create($iSurveyId); foreach ($writearray as $key => $value) { //if(in_array($key,$oToken->attributes)) Not needed because we filter attributes before $oToken->{$key} = $value; } $ir = $oToken->save(); if (!$ir) { $duplicatelist[] = $writearray['firstname'] . " " . $writearray['lastname'] . " (" . $writearray['email'] . ")"; } else { $xz++; } } $xv++; } $recordcount++; } $recordcount = $recordcount - 1; unlink($sFilePath); $aData['tokenlistarray'] = $tokenlistarray; $aData['xz'] = $xz; $aData['xv'] = $xv; $aData['recordcount'] = $recordcount; $aData['firstline'] = $firstline; $aData['duplicatelist'] = $duplicatelist; $aData['invalidformatlist'] = $invalidformatlist; $aData['invalidemaillist'] = $invalidemaillist; $aData['thissurvey'] = getSurveyInfo($iSurveyId); $aData['iSurveyId'] = $aData['surveyid'] = $iSurveyId; $this->_renderWrappedTemplate('token', array('tokenbar', 'csvpost'), $aData); } } else { $aData['aEncodings'] = $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; $this->_renderWrappedTemplate('token', array('tokenbar', 'csvupload'), $aData); } }
public function beforeSurveyPage() { $oEvent = $this->event; $iSurveyId = $oEvent->get('surveyId'); self::__init(); $bUse=$this->get('bUse', 'Survey', $iSurveyId); if(is_null($bUse)) $bUse=$this->bUse; if(!$bUse) return; $sToken= Yii::app()->request->getParam('token'); if($iSurveyId && !$sToken)// Test invalid token ? { // Get the survey model $oSurvey=Survey::model()->find("sid=:sid",array(':sid'=>$iSurveyId)); if($oSurvey && $oSurvey->active=="Y" && $oSurvey->allowregister=="Y" && tableExists("tokens_{$iSurveyId}")) { // Fill parameters $bShowTokenForm=$this->get('bShowTokenForm', 'Survey', $iSurveyId); if(is_null($bShowTokenForm)) $bShowTokenForm=$this->bShowTokenForm; $bShowTokenForm=$this->get('use', 'Survey', $iSurveyId); if(is_null($bShowTokenForm)) $bShowTokenForm=$this->bUse; Yii::app()->getClientScript()->registerCssFile(Yii::app()->getConfig('publicurl')."plugins/replaceRegister/css/register.css"); // We can go $sLanguage = Yii::app()->request->getParam('lang',''); if ($sLanguage=="" ) { $sLanguage = Survey::model()->findByPk($iSurveyId)->language; } $aSurveyInfo=getSurveyInfo($iSurveyId,$sLanguage); $sAction= Yii::app()->request->getParam('action','view') ; $sHtmlRegistererror=""; $sHtmlRegistermessage1=gT("You must be registered to complete this survey");; $sHtmlRegistermessage2=gT("You may register for this survey if you wish to take part.")."<br />\n".gT("Enter your details below, and an email containing the link to participate in this survey will be sent immediately."); $sHtmlRegisterform=""; $sHtml=""; $bShowForm=true; $bValidMail=false; $bTokenCreate=true; $aExtraParams=array(); $aRegisterError=array(); $sR_email= Yii::app()->request->getPost('register_email'); $sR_firstname= sanitize_xss_string(Yii::app()->request->getPost('register_firstname',"")); $sR_lastname= sanitize_xss_string(Yii::app()->request->getPost('register_lastname',"")); $sR_lastname= sanitize_xss_string(Yii::app()->request->getPost('register_lastname',"")); $aR_attribute=array(); $aR_attributeGet=array(); $aExtraParams=array(); $aMail=array(); foreach ($aSurveyInfo['attributedescriptions'] as $field => $aAttribute) { if (!empty($aAttribute['show_register']) && $aAttribute['show_register'] == 'Y') { $aR_attribute[$field]= sanitize_xss_string(Yii::app()->request->getPost('register_'.$field),"");// Need to be filtered ? } elseif($aAttribute['description']==sanitize_paranoid_string($aAttribute['description']) && trim(Yii::app()->request->getQuery($aAttribute['description'],"")) ) { $aR_attributeGet[$field]= sanitize_xss_string(trim(Yii::app()->request->getQuery($aAttribute['description'],"")));// Allow prefill with URL (TODO: add an option) $aExtraParams[$aAttribute['description']]=sanitize_xss_string(trim(Yii::app()->request->getParam($aAttribute['description'],""))); } } if($sAction=='register' && !is_null($sR_email) && Yii::app()->request->getPost('changelang')!='changelang') { $bShowForm=false; // captcha $sLoadsecurity=Yii::app()->request->getPost('loadsecurity'); $sSecAnswer=(isset($_SESSION['survey_'.$iSurveyId]['secanswer']))?$_SESSION['survey_'.$iSurveyId]['secanswer']:""; $bShowForm=false; $bNoError=true; // Copy paste RegisterController if($sR_email) { //Check that the email is a valid style addressattribute_2 if (!validateEmailAddress($sR_email)) { $aRegisterError[]= gT("The email you used is not valid. Please try again."); } } else { $aRegisterError[]= gT("The email you used is not valid. Please try again.");// Empty email } // Fill and validate mandatory extra attribute foreach ($aSurveyInfo['attributedescriptions'] as $field => $aAttribute) { if (!empty($aAttribute['show_register']) && $aAttribute['show_register'] == 'Y' && $aAttribute['mandatory'] == 'Y' && ($aR_attribute[$field]=="" || is_null($aR_attribute[$field])) ) { $aRegisterError[]= sprintf(gT("%s cannot be left empty").".", $aSurveyInfo['attributecaptions'][$field]); } } // Check the security question's answer : at end because the security question is the last one if (function_exists("ImageCreate") && isCaptchaEnabled('registrationscreen',$aSurveyInfo['usecaptcha']) ) { if (!$sLoadsecurity || !$sSecAnswer || $sLoadsecurity != $sSecAnswer) { $aRegisterError[]= gT("The answer to the security question is incorrect."); } } if(count($aRegisterError)==0) { //Check if this email already exists in token database $oToken=TokenDynamic::model($iSurveyId)->find('email=:email',array(':email'=>$sR_email)); if ($oToken) { if($oToken->usesleft<1 && $aSurveyInfo['alloweditaftercompletion']!='Y') { $aRegisterError="The e-mail address you have entered is already registered an the questionnaire has been completed."; } elseif(strtolower(substr(trim($oToken->emailstatus),0,6))==="optout")// And global blacklisting ? { $aRegisterError="This email address is already registered but someone ask to don't receive new email again."; } elseif(!$oToken->emailstatus && $oToken->emailstatus!="OK") { $aRegisterError="This email address is already registered but the email adress was bounced."; } else { $iTokenId=$oToken->tid; $aMail['subject']=$aSurveyInfo['email_register_subj']; $aMail['message']=$aSurveyInfo['email_register']; $aMail['information']="The address you have entered is already registered. An email has been sent to this address with a link that gives you access to the survey."; // Did we update the token ? Setting ? } } else { $oToken= Token::create($iSurveyId); $oToken->firstname = $sR_firstname; $oToken->lastname = $sR_lastname; $oToken->email = $sR_email; $oToken->emailstatus = 'OK'; $oToken->language = $sLanguage; $oToken->setAttributes($aR_attribute); $oToken->setAttributes($aR_attributeGet);// Need an option if ($aSurveyInfo['startdate']) { $oToken->validfrom = $aSurveyInfo['startdate']; } if ($aSurveyInfo['expires']) { $oToken->validuntil = $aSurveyInfo['expires']; } $oToken->save(); $iTokenId=$oToken->tid; TokenDynamic::model($iSurveyId)->createToken($iTokenId);// Review if really create a token $aMail['subject']=$aSurveyInfo['email_register_subj']; $aMail['message']=$aSurveyInfo['email_register']; $aMail['information']=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."); } } } if($aMail && $oToken) { $aReplacementFields=array(); $aReplacementFields["{ADMINNAME}"]=$aSurveyInfo['adminname']; $aReplacementFields["{ADMINEMAIL}"]=$aSurveyInfo['adminemail']; $aReplacementFields["{SURVEYNAME}"]=$aSurveyInfo['name']; $aReplacementFields["{SURVEYDESCRIPTION}"]=$aSurveyInfo['description']; $aReplacementFields["{EXPIRY}"]=$aSurveyInfo["expiry"]; $oToken=TokenDynamic::model($iSurveyId)->findByPk($iTokenId); foreach($oToken->attributes as $attribute=>$value){ $aReplacementFields["{".strtoupper($attribute)."}"]=$value; } $sToken=$oToken->token; $aMail['subject']=preg_replace("/{TOKEN:([A-Z0-9_]+)}/","{"."$1"."}",$aMail['subject']); $aMail['message']=preg_replace("/{TOKEN:([A-Z0-9_]+)}/","{"."$1"."}",$aMail['message']); $surveylink = App()->createAbsoluteUrl("/survey/index/sid/{$iSurveyId}",array('lang'=>$sLanguage,'token'=>$sToken)); $optoutlink = App()->createAbsoluteUrl("/optout/tokens/surveyid/{$iSurveyId}",array('langcode'=>$sLanguage,'token'=>$sToken)); $optinlink = App()->createAbsoluteUrl("/optin/tokens/surveyid/{$iSurveyId}",array('langcode'=>$sLanguage,'token'=>$sToken)); if (getEmailFormat($iSurveyId) == 'html') { $useHtmlEmail = true; $aReplacementFields["{SURVEYURL}"]="<a href='$surveylink'>".$surveylink."</a>"; $aReplacementFields["{OPTOUTURL}"]="<a href='$optoutlink'>".$optoutlink."</a>"; $aReplacementFields["{OPTINURL}"]="<a href='$optinlink'>".$optinlink."</a>"; } else { $useHtmlEmail = false; $aReplacementFields["{SURVEYURL}"]= $surveylink; $aReplacementFields["{OPTOUTURL}"]= $optoutlink; $aReplacementFields["{OPTINURL}"]= $optinlink; } // Allow barebone link for all URL $aMail['message'] = str_replace("@@SURVEYURL@@", $surveylink, $aMail['message']); $aMail['message'] = str_replace("@@OPTOUTURL@@", $optoutlink, $aMail['message']); $aMail['message'] = str_replace("@@OPTINURL@@", $optinlink, $aMail['message']); // Replace the fields $aMail['subject']=ReplaceFields($aMail['subject'], $aReplacementFields); $aMail['message']=ReplaceFields($aMail['message'], $aReplacementFields); // We have it, then try to send the mail. $from = "{$aSurveyInfo['adminname']} <{$aSurveyInfo['adminemail']}>"; $sitename = Yii::app()->getConfig('sitename'); if (SendEmailMessage($aMail['message'], $aMail['subject'], $sR_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(); $sReturnHtml="<div id='wrapper' class='message tokenmessage'>" . "<p>".gT("Thank you for registering to participate in this survey.")."</p>\n" . "<p>".$aMail['information']."</p>\n" . "<p>".gT("Survey administrator")." {ADMINNAME} ({ADMINEMAIL})</p>" . "</div>\n"; } else { $sReturnHtml="<div id='wrapper' class='message tokenmessage'>" . "<p>".gT("Thank you for registering to participate in this survey.")."</p>\n" . "<p>"."We can not sent you an email actually, please contact the survey administrator"."</p>\n" . "<p>".gT("Survey administrator")." {ADMINNAME} ({ADMINEMAIL})</p>" . "</div>\n"; } $sReturnHtml=ReplaceFields($sReturnHtml, $aReplacementFields); $sTemplatePath=$aData['templatedir'] = getTemplatePath($aSurveyInfo['template']); ob_start(function($buffer, $phase) { App()->getClientScript()->render($buffer); App()->getClientScript()->reset(); return $buffer; }); ob_implicit_flush(false); sendCacheHeaders(); doHeader(); $aData['thissurvey'] = $aSurveyInfo; $aData['thissurvey'] = $aSurveyInfo; echo templatereplace(file_get_contents($sTemplatePath.'/startpage.pstpl'),array(), $aData); echo templatereplace(file_get_contents($sTemplatePath.'/survey.pstpl'),array(), $aData); echo $sReturnHtml; echo templatereplace(file_get_contents($sTemplatePath.'/endpage.pstpl'),array(), $aData); doFooter(); ob_flush(); App()->end(); } if($bShowForm || count($aRegisterError)) { // Language ? if(count($aRegisterError)==1){ $sHtmlRegistererror="<p class='error error-register'><strong>{$aRegisterError[0]}</strong></p>"; }elseif(count($aRegisterError)>1){ $sHtmlRegistererror="<ul class='error error-register error-list'>"; foreach ($aRegisterError as $sRegisterError) $sHtmlRegistererror.="<li><strong>{$sRegisterError}</strong></li>"; $sHtmlRegistererror.="</ul>"; } $aExtraParams['action']='register'; $aExtraParams['lang']=$sLanguage; $sHtmlRegisterform = CHtml::form(Yii::app()->createUrl("/survey/index/sid/{$iSurveyId}",$aExtraParams), 'post'); $sHtmlRegisterform.="<table class='register'><tbody>\n"; $sHtmlRegisterform.= "<tr><th><label for='register_firstname'>".gT("First name") . "</label></th><td>".CHtml::textField('register_firstname',htmlentities($sR_firstname, ENT_QUOTES, 'UTF-8'),array('class'=>'text'))."</td></tr>\n"; $sHtmlRegisterform.= "<tr><th><label for='register_lastname'>".gT("Last name") . "</label></th><td>".CHtml::textField('register_lastname',htmlentities($sR_lastname, ENT_QUOTES, 'UTF-8'),array('class'=>'text'))."</td></tr>\n"; $sHtmlRegisterform.= "<tr class='mandatory'><th><label for='register_email'>".gT("Email address") . "</label></th><td>".CHtml::textField('register_email',htmlentities($sR_email, ENT_QUOTES, 'UTF-8'),array('class'=>'text'))."</td></tr>\n"; // Extra attribute foreach ($aSurveyInfo['attributedescriptions'] as $field => $aAttribute) { if (!empty($aAttribute['show_register']) && $aAttribute['show_register'] == 'Y') { $sHtmlRegisterform.= "<tr".($aAttribute['mandatory'] == 'Y' ? " class='mandatory'" : '')."><th><label for='register_{$field}'>".$aSurveyInfo['attributecaptions'][$field].($aAttribute['mandatory'] == 'Y' ? ' *' : '')."</label></th><td>".CHtml::textField('register_'.$field,htmlentities($aR_attribute[$field], ENT_QUOTES, 'UTF-8'),array('class'=>'text'))."</td></tr>\n"; } } if (function_exists("ImageCreate") && isCaptchaEnabled('registrationscreen', $aSurveyInfo['usecaptcha'])) $sHtmlRegisterform.= "<tr><th><label for='loadsecurity'>" . gT("Security question") . "</label></th><td><img src='".Yii::app()->getController()->createUrl("/verification/image/sid/{$iSurveyId}")."' alt='' /><input type='text' size='5' maxlength='3' name='loadsecurity' id='loadsecurity' value='' /></td></tr>\n"; $sHtmlRegisterform.= "<tr><td></td><td>".CHtml::submitButton(gT("Continue"))."</td></tr>"; $sHtmlRegisterform.= "</tbody></table>\n"; $sHtmlRegisterform.= makeLanguageChangerSurvey($sLanguage);// Need to be inside the form $sHtmlRegisterform.= CHtml::endForm(); } $sTemplatePath=$aData['templatedir'] = getTemplatePath($aSurveyInfo['template']); ob_start(function($buffer, $phase) { App()->getClientScript()->render($buffer); App()->getClientScript()->reset(); return $buffer; }); ob_implicit_flush(false); sendCacheHeaders(); doHeader(); // Get the register.pstpl file content, but remplace default by own string $sHtmlRegister=file_get_contents($sTemplatePath.'/register.pstpl'); $sHtmlRegister= str_replace("{REGISTERERROR}",$sHtmlRegistererror,$sHtmlRegister); $sHtmlRegister= str_replace("{REGISTERMESSAGE1}",$sHtmlRegistermessage1,$sHtmlRegister); $sHtmlRegister= str_replace("{REGISTERMESSAGE2}",$sHtmlRegistermessage2,$sHtmlRegister); $sHtmlRegister= str_replace("{REGISTERFORM}",$sHtmlRegisterform,$sHtmlRegister); $aData['thissurvey'] = $aSurveyInfo; echo templatereplace(file_get_contents($sTemplatePath.'/startpage.pstpl'),array(), $aData); echo templatereplace(file_get_contents($sTemplatePath.'/survey.pstpl'),array(), $aData); echo templatereplace($sHtmlRegister); echo templatereplace(file_get_contents($sTemplatePath.'/endpage.pstpl'),array(), $aData); doFooter(); ob_flush(); App()->end(); } } }