/**
  * Whitelist specific IPs. Each argument is a single IP.
  * Not passing any argument will output the current whitelist.
  *
  * @return int|null|void
  */
 public function whitelist()
 {
     if ($this->params['remove']) {
         $this->Maintenance->clearWhitelist();
     }
     $ips = $this->args;
     if (!empty($ips)) {
         foreach ($ips as $ip) {
             if (!Validation::ip($ip)) {
                 $this->abort($ip . ' is not a valid IP address.');
             }
         }
         if ($this->params['remove']) {
             $this->Maintenance->clearWhitelist($ips);
         } else {
             $this->Maintenance->whitelist($ips, $this->params['debug']);
         }
         $this->out('Done!', 2);
     }
     $this->out('Current whitelist:');
     $ips = $this->Maintenance->whitelist();
     if (!$ips) {
         $this->out('n/a');
     } else {
         $this->out($ips);
     }
 }
 public function edit($countryId = null)
 {
     if (!\Cake\Validation\Validation::naturalNumber($countryId)) {
         $this->Flash->error(__('Invalid country ID'));
         return $this->redirect(['action' => 'index']);
     }
     $this->loadModel('Countries');
     $country = $this->Countries->getCountryById($countryId);
     if (!$country) {
         $this->Flash->error(__('Oups. Country with this ID not exist.'));
         return $this->redirect(['action' => 'index']);
     }
     if ($this->request->is(['post', 'put', 'patch'])) {
         if ($this->Countries->updateCountry($country, $this->request->data)) {
             $this->Flash->success(__('Country was updated.'));
             return $this->redirect(['controller' => 'index', 'action' => 'index']);
         } else {
             $this->Flash->error(__('Oups. Country wasn\'t updated.'));
         }
     }
     $this->loadModel('Languages');
     $languages = $this->Languages->getAllLanguagesList();
     $this->set(compact('country', 'languages'));
     $this->render('add');
 }
Esempio n. 3
0
 /**
  * Performs the count check
  *
  * @param \Cake\Datasource\EntityInterface $entity The entity from where to extract the fields.
  * @param array $options Options passed to the check.
  * @return bool True if successful, else false.
  */
 public function __invoke(EntityInterface $entity, array $options)
 {
     $value = $entity->{$this->_field};
     if (!is_array($value) && !$value instanceof Countable) {
         return false;
     }
     return Validation::comparison(count($value), $options['operator'], $options['count']);
 }
Esempio n. 4
0
 public static function height($check, $operator = null, $check2 = null)
 {
     if (is_array($check) && isset($check['tmp_name'])) {
         $check = $check['tmp_name'];
     }
     $imagine = new Imagine();
     $image = $imagine->open($check);
     $size = $image->getSize();
     $height = $size->getHeight();
     return \Cake\Validation\Validation::comparison($height, $operator, $check2);
 }
Esempio n. 5
0
 /**
  * Custom validation rules
  * Validate the array of links
  * @param $value
  * @param $context
  * @return boolean
  */
 public static function validateLinksArray($value, $context)
 {
     $patten = '/[\\s|\\,]+/';
     // replace all delineter simbols
     $value = preg_replace($patten, '|', $value);
     // split all links in arra
     $links = preg_split('/\\|/', $value);
     foreach ($links as $link) {
         if (!Validation::url($link)) {
             return false;
         }
     }
     return true;
 }
 /**
  * Check for file size. Only difference is that it is possible to upload multiple files
  * @param $files
  * @param null $operator
  * @param $maxSize
  * @return bool
  */
 public static function fileSize($files, $operator = null, $maxSize)
 {
     $valid = false;
     if (isset($files[0]['tmp_name'])) {
         foreach ($files as $file) {
             if (Validation::fileSize($file, $operator, $maxSize) === false) {
                 return false;
             }
             $valid = true;
         }
     } else {
         $valid = Validation::fileSize($files, $operator, $maxSize);
     }
     return $valid;
 }
 /**
  * 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'));
         }
     }
 }
Esempio n. 8
0
 /**
  * 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['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']);
 }
Esempio n. 10
0
 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']);
     }
 }
Esempio n. 11
0
 /**
  * Default validation rules set.
  *
  * @param \Cake\Validation\Validator $validator The validator object
  * @return \Cake\Validation\Validator
  */
 public function validationDefault(Validator $validator)
 {
     $validator->allowEmpty('url')->add('url', 'checkUrl', ['rule' => function ($url, $context) {
         $plainString = strpos($url, 'javascript:') === 0 || strpos($url, 'mailto:') === 0 || strpos($url, 'tel:') === 0 || strpos($url, 'sms:') === 0 || strpos($url, '#') === 0 || strpos($url, '?') === 0 || strpos($url, '//') === 0 || strpos($url, '://') !== false;
         if ($plainString) {
             return true;
         } else {
             $full = Validation::url($url);
             $internal = str_starts_with($url, '/');
             return $full || $internal;
         }
     }, 'message' => __d('menu', 'Invalid URL. Internal links must start with "/", e.g. "/article-my-first-article{0}"', CONTENT_EXTENSION), 'provider' => 'table'])->requirePresence('title')->add('title', ['notBlank' => ['rule' => 'notBlank', 'message' => __d('menu', 'You need to provide a title.')], 'length' => ['rule' => ['minLength', 3], 'message' => __d('menu', 'Title need to be at least 3 characters long.')]])->add('activation', 'validActivation', ['rule' => function ($value, $context) {
         return in_array($value, ['auto', 'any', 'none', 'php']);
     }, 'message' => __d('menu', 'Please select an activation method.'), 'provider' => 'table'])->allowEmpty('active')->add('active', 'validPHP', ['rule' => function ($value, $context) {
         if (!empty($context['data']['activation']) && $context['data']['activation'] === 'php') {
             return strpos($value, '<?php') !== false && strpos($value, '?>') !== false;
         }
         return true;
     }, 'message' => __d('menu', 'Invalid PHP code, make sure that tags "&lt;?php" & "?&gt;" are present.')]);
     return $validator;
 }
Esempio n. 12
0
 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']);
 }
Esempio n. 13
0
 /**
  * Add a validation rule to ensure that a field is an array containing at most
  * the specified amount of elements
  *
  * @param string $field The field you want to apply the rule to.
  * @param int $count The number maximum amount of elements the field should have
  * @param string|null $message The error message when the rule fails.
  * @param string|callable|null $when Either 'create' or 'update' or a callable that returns
  *   true when the validation rule should be applied.
  * @see \Cake\Validation\Validation::numElements()
  * @return $this
  */
 public function hasAtMost($field, $count, $message = null, $when = null)
 {
     $extra = array_filter(['on' => $when, 'message' => $message]);
     return $this->add($field, 'hasAtMost', $extra + ['rule' => function ($value) use($count) {
         if (is_array($value) && isset($value['_ids'])) {
             $value = $value['_ids'];
         }
         return Validation::numElements($value, '<=', $count);
     }]);
 }
 /**
  * Prepares this task and the package to be installed.
  *
  * @return bool True on success
  */
 protected function _init()
 {
     $this->params['source'] = str_replace('"', '', $this->params['source']);
     if (function_exists('ini_set')) {
         ini_set('max_execution_time', 300);
     } elseif (function_exists('set_time_limit')) {
         set_time_limit(300);
     }
     if (is_readable($this->params['source']) && is_dir($this->params['source'])) {
         $this->_sourceType = self::TYPE_DIR;
         return $this->_getFromDirectory();
     } elseif (is_readable($this->params['source']) && !is_dir($this->params['source'])) {
         $this->_sourceType = self::TYPE_ZIP;
         return $this->_getFromFile();
     } elseif (Validation::url($this->params['source'])) {
         $this->_sourceType = self::TYPE_URL;
         return $this->_getFromUrl();
     }
     $this->err(__d('installer', 'Unable to resolve the given source ({0}).', [$this->params['source']]));
     return false;
 }
Esempio n. 15
0
 /**
  * naturalNumber
  * 数値チェック
  * integerなどの上限チェックを同時に行う
  *
  * @access public
  * @author hagiwara
  * @param array $check
  * @param boolean $allowZero
  * @param integer $limit
  * @return boolean
  */
 public static function naturalNumber($check, $allowZero = false, $limit = 2147483647)
 {
     //providersが間違いなく$contextの内容と考えられるので初期値を入力しなおす
     if (is_array($allowZero) && isset($allowZero['providers'])) {
         $allowZero = false;
     }
     if (is_array($limit) && isset($limit['providers'])) {
         $limit = 2147483647;
     }
     //coreのチェックを先に行う
     if (!parent::naturalNumber($check, $allowZero)) {
         return false;
     }
     return abs($check) <= $limit;
 }
Esempio n. 16
0
 /**
  * Sanitize the options array
  *
  * @param array $options Array of options, keyed from default settings
  * @return array Clean options array
  */
 protected function _cleanOptions($options)
 {
     if (!isset($options['size']) || empty($options['size']) || !is_numeric($options['size'])) {
         unset($options['size']);
     } else {
         $options['size'] = min(max($options['size'], 1), 512);
     }
     if (!$options['rating'] || !in_array(mb_strtolower($options['rating']), $this->_allowedRatings)) {
         unset($options['rating']);
     }
     if (!$options['default']) {
         unset($options['default']);
     } else {
         if (!in_array($options['default'], $this->_defaultIcons) && !Validation::url($options['default'])) {
             unset($options['default']);
         }
     }
     return $options;
 }
Esempio n. 17
0
 /**
  * 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'));
 }
Esempio n. 18
0
 /**
  * Test the compareWith method.
  *
  * @return void
  */
 public function testCompareWith()
 {
     $context = ['data' => ['other' => 'a value']];
     $this->assertTrue(Validation::compareWith('a value', 'other', $context));
     $context = ['data' => ['other' => 'different']];
     $this->assertFalse(Validation::compareWith('a value', 'other', $context));
     $context = [];
     $this->assertFalse(Validation::compareWith('a value', 'other', $context));
 }
Esempio n. 19
0
 /**
  * dataExist
  * @param Integer $id
  */
 private function dataExist($id)
 {
     //数値などのチェック
     if (!$id || !Validation::naturalNumber($id)) {
         return false;
     }
     $data = $this->_table->find()->where([$this->_table->alias() . '.' . $this->_table->primaryKey() => $id])->first();
     return !empty($data);
 }
Esempio n. 20
0
 /**
  * Validation of Time fields
  *
  * @param mixed $value
  * @param array $options
  * - timeFormat (defaults to 'hms')
  * - allowEmpty
  * - after/before (fieldName to validate against)
  * - min/max (defaults to >= 1 - at least 1 minute apart)
  * @param array $context
  * @return bool Success
  */
 public function validateTime($value, $options = [], array $context = [])
 {
     if (!$value) {
         return false;
     }
     $dateTime = explode(' ', $value, 2);
     $value = array_pop($dateTime);
     if (Validation::time($value)) {
         // after/before?
         if (!empty($options['after']) && isset($context['data'][$options['after']])) {
             if ($context['data'][$options['after']] >= $value) {
                 return false;
             }
         }
         if (!empty($options['before']) && isset($context['data'][$options['before']])) {
             if ($context['data'][$options['before']] <= $value) {
                 return false;
             }
         }
         return true;
     }
     return false;
 }
Esempio n. 21
0
 /**
  * Test utf8 extended
  *
  * @return void
  */
 public function testUtf8Extended()
 {
     $this->assertFalse(Validation::utf8([], ['extended' => true]));
     $this->assertFalse(Validation::utf8(1001, ['extended' => true]));
     $this->assertFalse(Validation::utf8(3.14, ['extended' => true]));
     $this->assertFalse(Validation::utf8(new \StdClass(), ['extended' => true]));
     $this->assertTrue(Validation::utf8('1 big blue bus.', ['extended' => true]));
     $this->assertTrue(Validation::utf8(',.<>[]{;/?\\)()', ['extended' => true]));
     // Latin-1 supplement
     $this->assertTrue(Validation::utf8('some' . "‚" . 'value', ['extended' => true]));
     $this->assertTrue(Validation::utf8('some' . "ÿ" . 'value', ['extended' => true]));
     // End of BMP
     $this->assertTrue(Validation::utf8('some' . "�" . 'value', ['extended' => true]));
     // Start of supplementary multilingual plane
     $this->assertTrue(Validation::utf8('some' . "𐀀" . 'value', ['extended' => true]));
     // Grinning face
     $this->assertTrue(Validation::utf8('some' . "😀" . 'value', ['extended' => true]));
 }
Esempio n. 22
0
 /**
  * Test numElements
  *
  * @return void
  */
 public function testNumElements()
 {
     $array = ['cake', 'php'];
     $this->assertTrue(Validation::numElements($array, '==', 2));
     $this->assertFalse(Validation::numElements($array, '>', 3));
     $this->assertFalse(Validation::numElements($array, '<', 1));
     $callable = function () {
         return '';
     };
     $this->assertFalse(Validation::numElements(null, '==', 0));
     $this->assertFalse(Validation::numElements(new \stdClass(), '==', 0));
     $this->assertFalse(Validation::numElements($callable, '==', 0));
     $this->assertFalse(Validation::numElements(false, '==', 0));
     $this->assertFalse(Validation::numElements(true, '==', 0));
 }
Esempio n. 23
0
 /**
  * Test uploaded file validation.
  *
  * @return void
  */
 public function testUploadedFileWithDifferentFileParametersOrder()
 {
     $file = ['name' => 'cake.power.gif', 'error' => UPLOAD_ERR_OK, 'tmp_name' => TEST_APP . 'webroot/img/cake.power.gif', 'type' => 'text/plain', 'size' => 201];
     $options = [];
     $this->assertTrue(Validation::uploadedFile($file, $options), 'Wrong order');
 }
Esempio n. 24
0
 /**
  * testFileSize method
  *
  * @return void
  */
 public function testFileSize()
 {
     $image = TEST_APP . 'webroot/img/cake.power.gif';
     $this->assertTrue(Validation::fileSize($image, '<', 1024));
     $this->assertTrue(Validation::fileSize(array('tmp_name' => $image), 'isless', 1024));
     $this->assertTrue(Validation::fileSize($image, '<', '1KB'));
     $this->assertTrue(Validation::fileSize($image, '>=', 200));
     $this->assertTrue(Validation::fileSize($image, '==', 201));
     $this->assertTrue(Validation::fileSize($image, '==', '201B'));
     $this->assertFalse(Validation::fileSize($image, 'isgreater', 1024));
     $this->assertFalse(Validation::fileSize(array('tmp_name' => $image), '>', '1KB'));
 }
Esempio n. 25
0
 public function southFour()
 {
     // Init table
     $resultsTable = TableRegistry::get('Results');
     // Prepare
     $year1 = Hash::get($this->request->query, 'search_year1');
     $month1 = Hash::get($this->request->query, 'search_month1');
     $year2 = Hash::get($this->request->query, 'search_year2');
     $month2 = Hash::get($this->request->query, 'search_month2');
     $head = Hash::get($this->request->query, 'search_head');
     $trail = Hash::get($this->request->query, 'search_trail');
     $startFormat = "";
     $endFormat = "";
     $startFormatValue = "";
     $endFormatValue = "";
     $conditions = ['area' => Configure::read('Area.south.code'), 'level IN' => [1, 9]];
     // Setting get data by year, month
     if (Validation::notBlank($year1)) {
         $startFormat .= '%Y';
         $startFormatValue .= $year1;
     }
     if (Validation::notBlank($month1)) {
         $startFormat .= '%m';
         $startFormatValue .= $month1;
     }
     if (Validation::notBlank($year2)) {
         $endFormat .= '%Y';
         $endFormatValue .= $year2;
     }
     if (Validation::notBlank($month2)) {
         $endFormat .= '%m';
         $endFormatValue .= $month2;
     }
     if ($startFormat) {
         $conditions[] = "DATE_FORMAT(date_result, '{$startFormat}') >= {$startFormatValue}";
     }
     if ($endFormat) {
         $conditions[] = "DATE_FORMAT(date_result, '{$endFormat}') <= {$endFormatValue}";
     }
     // Setting get data by head, trail
     if (Validation::notBlank($head)) {
         $conditions[] = "MID(content, -2, 1) = {$head}";
     }
     if (Validation::notBlank($trail)) {
         $conditions[] = "MID(content, -1) = {$trail}";
     }
     $query = $resultsTable->find('all');
     $trailTwo = $query->func()->mid(['content' => 'literal', '-2']);
     $query->select(['id', 'date_result', 'trail' => $trailTwo, 'city', 'level'])->where($conditions)->order(['date_result' => 'DESC', 'city' => 'ASC', 'level' => 'DESC']);
     // process space
     $htmlSpace = [];
     $htmlSpaceHead = [];
     if (Validation::notBlank($head)) {
         $sorted = $query->sortBy(function ($trail) {
             return $trail->date_result->i18nFormat('yyyyMMdd');
         }, SORT_ASC);
         foreach ($sorted as $key => $value) {
             $date = new \DateTime($value->date_result->i18nFormat('yyyy-MM-dd'));
             $line = in_array($value->city, Configure::read('COMMAND.CHANNEL.line1')) ? 1 : 2;
             $line = $line . "_" . ($value->level == 9 ? 1 : 2);
             $prevDate = isset($htmlSpace[$line]) ? $htmlSpace[$line]['prev_date'] : $date;
             $space = $prevDate->diff($date)->format("%a");
             // Check is space greater two month
             $spaceMonth = $date->format('Ym') - $prevDate->format('Ym');
             if ($space > 30 && $spaceMonth != 1 && $spaceMonth != 89) {
                 continue;
             }
             if ($prevDate->format('Y-m-d') != $date->format('Y-m-d')) {
                 $htmlSpace[$line][$space][] = $prevDate->format('Y-m-d') . " - " . $date->format('Y-m-d');
                 $htmlSpace[$line]["{$space}_count"] = count($htmlSpace[$line][$space]);
             }
             $htmlSpace[$line]['prev_date'] = $date;
             krsort($htmlSpace[$line]);
             if (!in_array($space, $htmlSpaceHead)) {
                 $htmlSpaceHead[] = $space;
             }
         }
         ksort($htmlSpace);
         rsort($htmlSpaceHead);
         $htmlSpace = Hash::flatten($htmlSpace);
         //var_dump($htmlSpaceHead);
         //var_dump($htmlSpace);exit;
     }
     $this->set('trails', $query);
     $this->set('htmlSpace', $htmlSpace);
     $this->set('htmlSpaceHead', $htmlSpaceHead);
 }
 /**
  * Validates the image size.
  *
  * @param array $value
  * @param array $options
  * @return boolean
  */
 public function imageSize($value, $options)
 {
     if (!isset($options['height']) && !isset($options['width'])) {
         throw new \InvalidArgumentException(__d('file_storage', 'Invalid image size validation parameters!'));
     }
     list($width, $height) = getimagesize($value['tmp_name']);
     if (isset($options['height'])) {
         $validHeight = Validation::comparison($height, $options['height'][1], $options['height'][0]);
     }
     if (isset($options['width'])) {
         $validWidth = Validation::comparison($width, $options['width'][1], $options['width'][0]);
     }
     if (isset($validHeight) && isset($validWidth)) {
         return $validHeight && $validWidth;
     }
     if (isset($validHeight)) {
         return $validHeight;
     }
     if (isset($validWidth)) {
         return $validWidth;
     }
     throw new \InvalidArgumentException('The 2nd argument is missing one or more configuration keyes.');
 }
Esempio n. 27
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;
 }
Esempio n. 28
0
 /**
  * Get all IP addresses associated with the current connection.
  *
  * @return array IP addresses
  */
 public function addresses()
 {
     if (Validation::ip($this->_config['host'])) {
         return [$this->_config['host']];
     }
     return gethostbynamel($this->_config['host']);
 }
 /**
  * Image size validation method
  *
  * @param mixed $check
  * @param array $options is an array with key width or height and a value of array
  *    with two options, operator and value. For example:
  *    array('height' => array('==', 100)) will only be true if the image has a
  *    height of exactly 100px. See the CakePHP core class and method
  *    Validation::comparison for all operators.
  * @return boolean true
  * @see Validation::comparison()
  * @throws \InvalidArgumentException
  */
 public function validateImageSize($check, array $options = [])
 {
     if (!isset($options['height']) && !isset($options['width'])) {
         throw new \InvalidArgumentException('Missing image size validation options! You must provide a hight and / or width.');
     }
     if (is_string($check)) {
         $imageFile = $check;
     } else {
         $check = array_values($check);
         $check = $check[0];
         if (is_array($check) && isset($check['tmp_name'])) {
             $imageFile = $check['tmp_name'];
         } else {
             $imageFile = $check;
         }
     }
     $imageSizes = $this->getImageSize($imageFile);
     if (isset($options['height'])) {
         $height = Validation::comparison($imageSizes[1], $options['height'][0], $options['height'][1]);
     } else {
         $height = true;
     }
     if (isset($options['width'])) {
         $width = Validation::comparison($imageSizes[0], $options['width'][0], $options['width'][1]);
     } else {
         $width = true;
     }
     if ($height === false || $width === false) {
         return false;
     }
     return true;
 }