/**
  * new password for users
  *
  * @return \Cake\Network\Response|void Redirects when email was passed, renders view otherwise.
  */
 public function forgotPassword()
 {
     $this->viewBuilder()->layout('plain');
     if ($this->request->is('post')) {
         if (!empty($this->request->data['email']) && Validation::email($this->request->data['email'])) {
             $user = $this->Users->getUserByEmail($this->request->data['email']);
             if (!empty($user)) {
                 $this->Users->sendForgotPasswordEmail($user);
             }
             $this->Flash->default(__('login.restore_password_email_sent'), true);
             return $this->redirect(['plugin' => null, 'controller' => 'login', 'action' => 'login']);
         } else {
             return $this->Flash->error(__('login.email_required'));
         }
     }
 }
 /**
  * Resets all emails - e.g. to your admin email (for local development).
  *
  * @param string|null $email
  * @return void
  */
 public function email($email = null)
 {
     $this->out('Email:');
     while (empty($email) || !Validation::email($email)) {
         $email = $this->in('New email address (must have a valid form at least)');
     }
     $this->Users = TableRegistry::get(CLASS_USERS);
     if (!$this->Users->hasField('email')) {
         $this->abort(CLASS_USERS . ' table doesnt have an email field!');
     }
     $this->hr();
     $this->out('Resetting...');
     if (empty($this->params['dry-run'])) {
         $count = $this->Users->updateAll(['email' => $email . ''], ['email !=' => $email]);
     } else {
         $count = $this->Users->find('all', ['conditions' => [CLASS_USERS . '.email !=' => $email]])->count();
     }
     $this->out($count . ' emails resetted - DONE');
 }
 public function login()
 {
     if ($this->request->is('post')) {
         if (Validation::email($this->request->data['username'])) {
             $this->Auth->config('authenticate', ['Form' => ['fields' => ['username' => 'email']]]);
             $this->Auth->constructAuthenticate();
             $this->request->data['email'] = $this->request->data['username'];
             unset($this->request->data['username']);
         }
         $user = $this->Auth->identify();
         if ($user) {
             $this->Auth->setUser($user);
             $this->set('loginSucceeded', true);
             $this->set('redirectUrl', $this->Auth->redirectUrl());
         } else {
             $this->set('loginSucceeded', false);
             $this->set('redirectUrl', null);
         }
         $this->set('_serialize', ['loginSucceeded', 'redirectUrl']);
     }
 }
 public function initialize()
 {
     parent::initialize();
     //加载组件
     //加载用户认证组件
     $this->loadComponent('Auth', ['storage' => ['className' => 'Session', 'key' => Configure::read('Settings.session.key')], 'loginAction' => ['controller' => 'Accounts', 'action' => 'login'], 'authError' => '您访问的地址需要登陆', 'authenticate' => ['Form' => ['userModel' => 'Accounts', 'passwordHasher' => ['className' => 'Poplus']]]]);
     //此项放在login方法中无效。具体原因未知
     if ($this->request->is('post') && $this->request->params['action'] == 'login') {
         //支持用户名/邮箱/手机号登陆
         if (Validation::email($this->request->data['username'])) {
             $this->Auth->config('authenticate', ['Form' => ['fields' => ['username' => 'email']]]);
             $this->request->data['email'] = $this->request->data['username'];
             unset($this->request->data['username']);
         } elseif (preg_match("/^(\\+?86-?)?(18|15|13|17)[0-9]{9}\$/", $this->request->data['username'])) {
             $this->Auth->config('authenticate', ['Form' => ['fields' => ['username' => 'mobile']]]);
             $this->request->data['mobile'] = $this->request->data['username'];
             unset($this->request->data['username']);
         }
     }
     $this->Auth->allow(['regist']);
 }
 public function login()
 {
     if ($this->request->is('post')) {
         if (Validation::email($this->request->data['email'])) {
             $this->Auth->config('authenticate', ['Form' => ['fields' => ['username' => 'email']]]);
             $this->Auth->constructAuthenticate();
         }
         $user = $this->Auth->identify();
         if ($user) {
             $this->Auth->setUser($user);
             return $this->redirect($this->Auth->redirectUrl());
         }
         $this->Flash->error(__('Invalid email or password, try again'));
     }
     $user = $this->Users->newEntity();
     $this->set('title', 'login');
     $this->set('subtitle', 'login_description');
     $this->set('page', 'login');
     $this->set(compact('user'));
     $this->set('_serialize', ['user']);
 }
 /**
  * testEmailCustomRegex method
  *
  * @return void
  */
 public function testEmailCustomRegex()
 {
     $this->assertTrue(Validation::email('*****@*****.**', null, '/^[A-Z0-9._%-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}$/i'));
     $this->assertFalse(Validation::email('*****@*****.**', null, '/^[A-Z0-9._%-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}$/i'));
 }
Beispiel #7
0
 /**
  * Returns an array with values for 'name' and 'email'
  *
  * @param array $response Response array
  * @return array
  */
 public function extractRespondentInfo($response)
 {
     $retval = ['name' => '', 'email' => ''];
     // Assume the first field contains the respondent's name
     if (isset($response[0]['answers'][0]['text'])) {
         $retval['name'] = $response[0]['answers'][0]['text'];
     }
     // Search for the first response that's a valid email address
     foreach ($response as $section) {
         foreach ($section['answers'] as $answer) {
             if (!isset($answer['text'])) {
                 continue;
             }
             $answer = trim($answer['text']);
             if (Validation::email($answer)) {
                 $retval['email'] = strtolower($answer);
                 break;
             }
         }
     }
     return $retval;
 }
 /**
  * Method for /surveys/import
  *
  * @param null|int $surveyId Survey ID
  * @return \Cake\Network\Response
  */
 public function import($surveyId = null)
 {
     $this->viewBuilder()->layout('blank');
     $importedCount = 0;
     // Disallow import if survey is inactive
     $survey = $this->Surveys->get($surveyId);
     if (!$survey->active) {
         $this->response->statusCode(403);
         $this->set('message', 'This questionnaire is currently inactive. New responses cannot be imported.');
         return $this->render('import');
     }
     // Collect respondents
     $respondentsTable = TableRegistry::get('Respondents');
     list($success, $respondents) = $respondentsTable->getNewFromSurveyMonkey($surveyId);
     if (!$success) {
         return $this->renderImportError($respondents);
     }
     // Convert IDs from integers to strings (the SurveyMonkey API is particular about this)
     $smRespondentIds = array_keys($respondents);
     foreach ($smRespondentIds as &$smRId) {
         $smRId = (string) $smRId;
     }
     // Collect responses
     $responsesTable = TableRegistry::get('Responses');
     list($success, $responses) = $responsesTable->getFromSurveyMonkeyForRespondents($surveyId, $smRespondentIds);
     if (!$success) {
         return $this->renderImportError($responses);
     }
     // Loop through each response and add to / update records
     $areasTable = TableRegistry::get('Areas');
     $usersTable = TableRegistry::get('Users');
     $errorMsgs = [];
     if (is_array($responses)) {
         foreach ($responses as $smRespondentId => $response) {
             $respondent = $responsesTable->extractRespondentInfo($response);
             $name = $respondent['name'] ?: '(no name)';
             $respondentRecord = $respondentsTable->getMatching($surveyId, $respondent, $smRespondentId);
             $serializedResponse = base64_encode(serialize($response));
             // Ignore response if it doesn't include all PWRRR ranks
             $responseRanks = $responsesTable->getResponseRanks($serializedResponse, $survey);
             if (!$responseRanks) {
                 $errorMsgs[] = "Response from {$name} did not contain all PWR<sup>3</sup> rankings.";
                 continue;
             }
             // Ignore responses if email address is missing or invalid
             if (empty($respondent['email'])) {
                 $errorMsgs[] = "Response from {$name} is missing an email address.";
                 continue;
             }
             if (!Validation::email($respondent['email'])) {
                 $errorMsgs[] = "Response from {$name} has an invalid email address: {$respondent['email']}.";
                 continue;
             }
             // Add new respondent
             if (empty($respondentRecord)) {
                 $approved = $respondentsTable->isAutoApproved($survey, $respondent['email']);
                 $newRespondent = $respondentsTable->newEntity(['email' => $respondent['email'], 'name' => $name, 'survey_id' => $surveyId, 'sm_respondent_id' => $smRespondentId, 'invited' => false, 'approved' => $approved ? 1 : 0]);
                 $errors = $newRespondent->errors();
                 if (empty($errors)) {
                     $respondentsTable->save($newRespondent);
                     $respondentId = $newRespondent->id;
                 } else {
                     /* Don't record anything for this response
                      * (this condition should theoretically never happen,
                      * since any validation errors should have been caught above) */
                     continue;
                 }
                 // Update existing respondent
             } else {
                 $newData = [];
                 if (empty($respondentRecord->smRespondentId)) {
                     $newData['sm_respondent_id'] = $smRespondentId;
                 }
                 if (empty($respondentRecord->name)) {
                     $newData['name'] = $respondent['name'];
                 }
                 if (!empty($newData)) {
                     $respondentRecord = $respondentsTable->patchEntity($respondentRecord, $newData);
                     $errors = $respondentRecord->errors();
                     if (empty($errors)) {
                         $respondentsTable->save($respondentRecord);
                     } else {
                         /* Don't record anything for this response
                          * (this condition should theoretically never happen,
                          * since any validation errors should have been caught above) */
                         continue;
                     }
                 }
                 $respondentId = $respondentRecord->id;
             }
             // Skip recording response if it's already recorded
             if ($responsesTable->isRecorded($respondentId, $survey, $serializedResponse)) {
                 continue;
             }
             // Calculate alignment
             $communitiesTable = TableRegistry::get('Communities');
             $community = $communitiesTable->get($survey->community_id);
             $actualRanksLocal = $areasTable->getPwrrrRanks($community->local_area_id);
             $actualRanksParent = $areasTable->getPwrrrRanks($community->parent_area_id);
             $alignmentVsLocal = $responsesTable->calculateAlignment($actualRanksLocal, $responseRanks);
             $alignmentVsParent = $responsesTable->calculateAlignment($actualRanksParent, $responseRanks);
             // Save response
             $responseFields = ['respondent_id' => $respondentId, 'survey_id' => $surveyId, 'response' => $serializedResponse, 'local_area_pwrrr_alignment' => $alignmentVsLocal, 'parent_area_pwrrr_alignment' => $alignmentVsParent, 'response_date' => new Time($respondents[$smRespondentId])];
             foreach ($responseRanks as $sector => $rank) {
                 $responseFields["{$sector}_rank"] = $rank;
             }
             $newResponse = $responsesTable->newEntity($responseFields);
             $errors = $newResponse->errors();
             if (empty($errors)) {
                 $responsesTable->save($newResponse);
                 $importedCount++;
             } else {
                 $errorMsgs[] = "Response from {$name} is missing required data.";
                 continue;
             }
         }
         /* Set new last_modified_date if there are no errors
          * (if this set of responses contains errors, advancing the last_modified_date
          * would prevent those responses from being imported after those errors are corrected) */
         if (empty($errorMsgs)) {
             $dates = array_values($respondents);
             $survey->respondents_last_modified_date = new Time(max($dates));
         }
         $survey->import_errors = $errorMsgs ? serialize($errorMsgs) : null;
         $this->Surveys->save($survey);
     }
     // Finalize
     $this->Surveys->setChecked($surveyId);
     if (empty($errorMsgs)) {
         if ($importedCount) {
             $message = $importedCount . __n(' response', ' responses', $importedCount) . ' imported';
         } else {
             $message = 'No new responses to import';
         }
     } else {
         if ($importedCount) {
             $message = $importedCount . __n(' response', ' responses', $importedCount) . ' imported<br />';
         } else {
             $message = '';
         }
         $message .= 'Errors prevented the following ' . __n('response', 'responses', count($errorMsgs)) . ' from being imported:' . '<ul>';
         foreach ($errorMsgs as $errorMsg) {
             $message .= '<li>' . $errorMsg . '</li>';
         }
         $message .= '</ul>';
         $this->response->statusCode(500);
     }
     $this->set(compact('message'));
 }