当前位置: 首页>>代码示例>>PHP>>正文


PHP Token::create方法代码示例

本文整理汇总了PHP中Token::create方法的典型用法代码示例。如果您正苦于以下问题:PHP Token::create方法的具体用法?PHP Token::create怎么用?PHP Token::create使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Token的用法示例。


在下文中一共展示了Token::create方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。

示例1: preDispatch

 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');
             }
         }
     }
 }
开发者ID:stevenli,项目名称:360ic.net.cn,代码行数:32,代码来源:AuthPlugin.php

示例2: testRetrieve

 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);
 }
开发者ID:payjp,项目名称:payjp-php,代码行数:7,代码来源:TokenTest.php

示例3: __construct

 public function __construct()
 {
     $this->_setup();
     Token::create();
     if (!isset($_SESSION['current_num'])) {
         $this->_initSession();
     }
 }
开发者ID:Sylphy0052,项目名称:Sylphy,代码行数:8,代码来源:Quiz.php

示例4: testTokenCreate

 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);
 }
开发者ID:everypay,项目名称:everypay_prestashop_1_4_x,代码行数:9,代码来源:TokenTest.php

示例5: testVerify

 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());
 }
开发者ID:BenComicGraphics,项目名称:stripe-php,代码行数:12,代码来源:ExternalAccountTest.php

示例6: __construct

 /**
  * 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');
 }
开发者ID:vdanelia,项目名称:GeniXCMS,代码行数:20,代码来源:System.class.php

示例7: testRecipientDeleteCard

 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);
 }
开发者ID:Enflick,项目名称:stripe-php,代码行数:16,代码来源:RecipientTest.php

示例8: authAction

 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');
 }
开发者ID:stevenli,项目名称:360ic.net.cn,代码行数:42,代码来源:AuthController.php

示例9: testCustomerDeleteSource

 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);
 }
开发者ID:andrewkrug,项目名称:repucaution,代码行数:17,代码来源:CustomerTest.php

示例10: actionIndex

 /**
  * 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;
//.........这里部分代码省略.........
开发者ID:jdbaltazar,项目名称:survey-office,代码行数:101,代码来源:RegisterController.php

示例11:



<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>
开发者ID:browar777,项目名称:MVC,代码行数:29,代码来源:create.php

示例12: googleLogin

 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);
 }
开发者ID:diegomjasso,项目名称:UPASystem2,代码行数:76,代码来源:PersonaController.php

示例13: json_decode

         $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)) {
开发者ID:4534-WiredWizards,项目名称:ScoutingApp,代码行数:31,代码来源:auth.php

示例14: import


//.........这里部分代码省略.........
                                         $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;
开发者ID:mfavetti,项目名称:LimeSurvey,代码行数:67,代码来源:tokens.php

示例15: addDummies

 /**
  * 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);
     }
 }
开发者ID:jdbaltazar,项目名称:survey-office,代码行数:95,代码来源:tokens.php


注:本文中的Token::create方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。