/**
  * Capture a message via sentry
  *
  * @param string $message The message (primary description) for the event.
  * @param array $params params to use when formatting the message.
  * @param array $data Additional attributes to pass with this event (see Sentry docs).
  * @param bool $stack Print stack trace
  * @param null $vars Variables
  * @return bool
  */
 public function captureMessage($message, $params = [], $data = [], $stack = false, $vars = null)
 {
     if (!Configure::read('CakeMonitor.Sentry.enabled') || error_reporting() === 0) {
         return false;
     }
     return $this->_ravenClient->captureMessage($message, $params, $data, $stack, $vars);
 }
 /**
  * Initialization hook method.
  *
  * For e.g. use this method to load a helper for all views:
  * `$this->loadHelper('Html');`
  *
  * @return void
  */
 public function initialize()
 {
     parent::initialize();
     if (Configure::read('Facebook.app_id')) {
         $this->loadHelper('JorgeFacebook.Facebook');
     }
 }
 public function view($reportId)
 {
     if (!$reportId) {
         throw new NotFoundException(__('Invalid Report'));
     }
     $report = $this->Reports->findById($reportId)->toArray();
     if (!$report) {
         throw new NotFoundException(__('Invalid Report'));
     }
     $this->set('report', $report);
     $this->set('project_name', Configure::read('GithubRepoPath'));
     $this->Reports->id = $reportId;
     $this->set('incidents', $this->Reports->getIncidents()->toArray());
     $this->set('incidents_with_description', $this->Reports->getIncidentsWithDescription());
     $this->set('incidents_with_stacktrace', $this->Reports->getIncidentsWithDifferentStacktrace());
     $this->set('related_reports', $this->Reports->getRelatedReports());
     $this->set('status', $this->Reports->status);
     $this->_setSimilarFields($reportId);
     // if there is an unread notification for this report, then mark it as read
     $current_developer = TableRegistry::get('Developers')->findById($this->request->session()->read('Developer.id'))->all()->first();
     //$current_developer = Sanitize::clean($current_developer);
     if ($current_developer) {
         TableRegistry::get('Notifications')->deleteAll(array('developer_id' => $current_developer['Developer']['id'], 'report_id' => $reportId), false);
     }
 }
 /**
  * testRequestAction method
  *
  * @return void
  */
 public function testRequestAction()
 {
     $this->assertNull(Router::getRequest(), 'request stack should be empty.');
     $result = $this->object->requestAction('');
     $this->assertFalse($result);
     $result = $this->object->requestAction('/request_action/test_request_action');
     $expected = 'This is a test';
     $this->assertEquals($expected, $result);
     $result = $this->object->requestAction(Configure::read('App.fullBaseUrl') . '/request_action/test_request_action');
     $expected = 'This is a test';
     $this->assertEquals($expected, $result);
     $result = $this->object->requestAction('/request_action/another_ra_test/2/5');
     $expected = 7;
     $this->assertEquals($expected, $result);
     $result = $this->object->requestAction('/tests_apps/index', ['return']);
     $expected = 'This is the TestsAppsController index view ';
     $this->assertEquals($expected, $result);
     $result = $this->object->requestAction('/tests_apps/some_method');
     $expected = 5;
     $this->assertEquals($expected, $result);
     $result = $this->object->requestAction('/request_action/paginate_request_action');
     $this->assertNull($result);
     $result = $this->object->requestAction('/request_action/normal_request_action');
     $expected = 'Hello World';
     $this->assertEquals($expected, $result);
     $this->assertNull(Router::getRequest(), 'requests were not popped off the stack, this will break url generation');
 }
Exemple #5
0
 /**
  * Get active theme name.
  *
  * @param bool $isSite
  * @return mixed
  */
 function activeTheme($isSite = true)
 {
     if ($isSite) {
         return Configure::read('Theme.' . Theme::CLIENT_FRONT_END);
     }
     return Configure::read('Theme.' . Theme::CLIENT_BACK_END);
 }
 /**
  * Displays a view
  *
  * @param mixed What page to display
  * @return void
  * @throws Cake\Error\NotFoundException When the view file could not be found
  *	or Cake\View\Error\MissingViewException in debug mode.
  */
 public function display()
 {
     $path = func_get_args();
     $count = count($path);
     if (!$count) {
         return $this->redirect('/');
     }
     $page = $subpage = $titleForLayout = null;
     if (!empty($path[0])) {
         $page = $path[0];
     }
     if (!empty($path[1])) {
         $subpage = $path[1];
     }
     if (!empty($path[$count - 1])) {
         $titleForLayout = Inflector::humanize($path[$count - 1]);
     }
     $this->set(array('page' => $page, 'subpage' => $subpage, 'title_for_layout' => $titleForLayout));
     try {
         $this->render(implode('/', $path));
     } catch (MissingViewException $e) {
         if (Configure::read('debug')) {
             throw $e;
         }
         throw new Error\NotFoundException();
     }
 }
 /**
  * setUp method
  *
  * @return void
  */
 public function setUp()
 {
     parent::setUp();
     $this->View = new View();
     $this->_appNamespace = Configure::read('App.namespace');
     Configure::write('App.namespace', 'TestApp');
 }
Exemple #8
0
 public function getModelClass()
 {
     $parts = explode('\\', get_class($this));
     $factory = array_pop($parts);
     $entity = preg_replace('/Factory$/', '', $factory);
     return Configure::read('App.namespace') . '\\Model\\Entity\\' . $entity;
 }
 function __construct()
 {
     Configure::load('amazon', 'default');
     $this->awsAccessKey = Configure::read('AwsAccessKey');
     $this->awsSecretKey = Configure::read('AwsSecretKey');
     $this->associateTag = Configure::read('AssociateTag');
 }
 public function beforeDelete(Event $event, Entity $entity)
 {
     $upload_root_offset = Configure::read('UPLOAD_ROOT_OFFSET');
     $upload_root = Configure::read('UPLOAD_ROOT');
     $id = $entity->id;
     $job_id = $entity->job_id;
     // delete creative folder and all its contents
     AppController::delete_folder($upload_root_offset . DS . $upload_root . DS . $job_id . DS . $id);
     /*
     		$Files = TableRegistry::get('Files');
     		$files = $Files->find('all',['conditions'=>['creative_id'=>$id]])->toArray();
     		if( !empty($files) ) {
     	    	foreach($files as $row){
     			    $file_path = $upload_root_offset . $row['file'];
     			    if( file_exists($file_path) ) {
     					if ( is_dir($file_path) ){
     						if( AppController::delete_folder($file_path) ) {
     							
     						}
     					} else if( unlink($file_path) ) {
     						
     					}
     				}
     		    }
     	    }
     */
 }
 /**
  * Method that generates and returns thumbnails html markup.
  *
  * @param ResultSet $entities File Entities
  * @param FileUploadsUtils $fileUploadsUtils fileUploadsUtils class object
  * @param array $options for default thumbs versions and other setttings
  *
  * @return string
  */
 protected function _thumbnailsHtml($entities, FileUploadsUtils $fileUploadsUtils, $options = [])
 {
     $result = null;
     $colWidth = static::GRID_COUNT / static::THUMBNAIL_LIMIT;
     $thumbnailUrl = 'CsvMigrations.thumbnails/' . static::NO_THUMBNAIL_FILE;
     $hashes = Configure::read('FileStorage.imageHashes.file_storage');
     $extensions = $fileUploadsUtils->getImgExtensions();
     foreach ($entities as $k => $entity) {
         if ($k >= static::THUMBNAIL_LIMIT) {
             break;
         }
         if (in_array($entity->extension, $extensions)) {
             $thumbnailUrl = $entity->path;
             if (isset($hashes[$options['imageSize']])) {
                 $version = $hashes[$options['imageSize']];
                 $exists = $this->_checkThumbnail($entity, $version, $fileUploadsUtils);
                 if ($exists) {
                     $path = dirname($entity->path) . '/' . basename($entity->path, $entity->extension);
                     $path .= $version . '.' . $entity->extension;
                     $thumbnailUrl = $path;
                 }
             }
         }
         $thumbnail = sprintf(static::THUMBNAIL_HTML, $this->cakeView->Html->image($thumbnailUrl, ['title' => $entity->filename]));
         $thumbnail = $this->cakeView->Html->link($thumbnail, $entity->path, ['escape' => false, 'target' => '_blank']);
         $result .= sprintf(static::GRID_COL_HTML, $colWidth, $colWidth, $colWidth, $colWidth, $thumbnail);
     }
     $result = sprintf(static::GRID_ROW_HTML, $result);
     return $result;
 }
 /**
  * Get the comment content purified with HTMLPurifier.
  *
  * @return string
  */
 protected function _getContentEmpty()
 {
     $config = HTMLPurifier_Config::createDefault();
     $config->loadArray(Configure::read('HtmlPurifier.Blog.comment_empty'));
     $HTMLPurifier = new HTMLPurifier($config);
     return $HTMLPurifier->purify($this->content);
 }
 /**
  * Builds asset file path based on the provided $url.
  *
  * @param string $url Asset URL
  * @return string|void Absolute path for asset file
  */
 protected function _getAssetFile($url)
 {
     $parts = explode('/', $url);
     $pluginPart = [];
     $plugin = false;
     for ($i = 0; $i < 2; $i++) {
         if (!isset($parts[$i])) {
             break;
         }
         $pluginPart[] = Inflector::camelize($parts[$i]);
         $possiblePlugin = implode('/', $pluginPart);
         if ($possiblePlugin && Plugin::loaded($possiblePlugin)) {
             $plugin = $possiblePlugin;
             $parts = array_slice($parts, $i + 1);
             break;
         }
     }
     $isAssetRequest = isset($parts[0]) && $parts[0] === 'ASSETS';
     if ($isAssetRequest && Configure::read('debug')) {
         $parts = array_slice($parts, 1);
     } else {
         $isAssetRequest = false;
     }
     if ($plugin && Plugin::loaded($plugin)) {
         return $this->_getPluginAsset($plugin, $parts, $isAssetRequest);
     } else {
         return $this->_getAppAsset($parts, $isAssetRequest);
     }
 }
 /**
  * Search the elastic search index.
  *
  * @return void
  */
 public function search()
 {
     $domains = Configure::read('AccessControlAllowOrigin');
     $this->response->cors($this->request)->allowOrigin($domains)->allowMethods(['GET'])->allowHeaders(['X-CSRF-Token'])->maxAge(300)->build();
     $version = '2-2';
     if (!empty($this->request->query['version'])) {
         $version = $this->request->query['version'];
     }
     if (empty($this->request->query['lang'])) {
         throw new BadRequestException();
     }
     $lang = $this->request->query['lang'];
     $page = 1;
     if (!empty($this->request->query['page'])) {
         $page = $this->request->query['page'];
     }
     $page = max($page, 1);
     if (count(array_filter(explode(' ', $this->request->query['q']))) === 1) {
         $this->request->query['q'] .= '~';
     }
     $options = ['query' => $this->request->query('q'), 'page' => $page];
     $this->loadModel('Search', 'Elastic');
     $results = $this->Search->search($lang, $version, $options);
     $this->viewBuilder()->className('Json');
     $this->set('results', $results);
     $this->set('_serialize', 'results');
 }
Exemple #15
0
 /**
  * Register method
  *
  * @return void (Redirection)
  */
 public function register()
 {
     $user = $this->Users->newEntity();
     if ($this->request->is('post')) {
         //Adding defaults
         $this->request->data['see_nsfw'] = Configure::read('cms.defaultSeeNSFW');
         $this->request->data['role'] = Configure::read('cms.defaultRole');
         $this->request->data['status'] = Configure::read('cms.defaultUserStatus');
         $this->request->data['locked'] = Configure::read('cms.defaultLockedUser');
         $this->request->data['file_count'] = 0;
         $this->request->data['note_count'] = 0;
         $this->request->data['post_count'] = 0;
         $this->request->data['project_count'] = 0;
         $this->request->data['preferences'] = json_encode(Configure::read('cms.defaultPreferences'));
         $user = $this->Users->patchEntity($user, $this->request->data);
         if ($this->Users->save($user)) {
             $this->Flash->success(__d('elabs', 'Your account has been created. An email will be sent to you when active'));
             $this->redirect(['action' => 'index']);
         } else {
             $errors = $user->errors();
             $errorMessages = [];
             array_walk_recursive($errors, function ($a) use(&$errorMessages) {
                 $errorMessages[] = $a;
             });
             $this->Flash->error(__d('elabs', 'Some errors occured. Please, try again.'), ['params' => ['errors' => $errorMessages]]);
         }
     }
     $this->set(compact('user'));
     $this->set('_serialize', ['user']);
 }
 /**
  * Displays a view
  *
  * @return void|\Cake\Network\Response
  * @throws \Cake\Network\Exception\NotFoundException When the view file could not
  *   be found or \Cake\View\Exception\MissingTemplateException in debug mode.
  */
 public function display()
 {
     $path = func_get_args();
     $count = count($path);
     if (!$count) {
         return $this->redirect('/');
     }
     $page = $subpage = null;
     if (!empty($path[0])) {
         $page = $path[0];
     }
     if (!empty($path[1])) {
         $subpage = $path[1];
     }
     $data = $this->getHeadquartersData();
     $this->set('data', $data);
     $this->set(compact('page', 'subpage'));
     try {
         $this->render(implode('/', $path));
     } catch (MissingTemplateException $e) {
         if (Configure::read('debug')) {
             throw $e;
         }
         throw new NotFoundException();
     }
 }
    /**
     * Renders a date time widget.
     *
     * @param array $data Data to render with.
     * @param \Cake\View\Form\ContextInterface $context The current form context.
     * @return string A generated select box.
     * @throws \RuntimeException When option data is invalid.
     */
    public function render(array $data, ContextInterface $context)
    {
        $id = $data['id'];
        $name = $data['name'];
        $val = $data['val'];
        $type = $data['type'];
        $required = $data['required'] ? 'required' : '';
        $disabled = isset($data['disabled']) && $data['disabled'] ? 'disabled' : '';
        $role = isset($data['role']) ? $data['role'] : 'datetime-picker';
        $format = null;
        $locale = isset($data['locale']) ? $data['locale'] : I18n::locale();
        $timezoneAware = Configure::read('CrudView.timezoneAwareDateTimeWidget');
        $timestamp = null;
        $timezoneOffset = null;
        if (isset($data['data-format'])) {
            $format = $this->_convertPHPToMomentFormat($data['data-format']);
        }
        if (!$val instanceof DateTimeInterface && !empty($val)) {
            $val = $type === 'date' ? Time::parseDate($val) : Time::parseDateTime($val);
        }
        if ($val) {
            if ($timezoneAware) {
                $timestamp = $val->format('U');
                $dateTimeZone = new DateTimeZone(date_default_timezone_get());
                $timezoneOffset = $dateTimeZone->getOffset($val) / 60;
            }
            $val = $val->format($type === 'date' ? 'Y-m-d' : 'Y-m-d H:i:s');
        }
        if (!$format) {
            $format = $type === 'date' ? 'L' : 'L LT';
        }
        $widget = <<<html
            <div class="input-group {$type}">
                <input
                    type="text"
                    class="form-control"
                    name="{$name}"
                    value="{$val}"
                    id="{$id}"
                    role="{$role}"
                    data-locale="{$locale}"
                    data-format="{$format}"
html;
        if ($timezoneAware && isset($timestamp, $timezoneOffset)) {
            $widget .= <<<html
                    data-timestamp="{$timestamp}"
                    data-timezone-offset="{$timezoneOffset}"
html;
        }
        $widget .= <<<html
                    {$required}
                    {$disabled}
                />
                <label for="{$id}" class="input-group-addon">
                    <span class="glyphicon glyphicon-calendar"></span>
                </label>
            </div>
html;
        return $widget;
    }
 /**
  * Main
  *
  * @return void
  */
 public function main()
 {
     $batchSize = 10;
     if (is_numeric(Configure::read('Notifications.batch_size'))) {
         $batchSize = Configure::read('Notifications.batch_size');
     }
     $this->loadModel('Notifications.NotificationQueue');
     $batch = $this->NotificationQueue->getBatch($batchSize);
     if (!empty($batch)) {
         $batchIds = [];
         $sent = 0;
         $failed = 0;
         foreach ($batch as $notification) {
             $batchIds[] = $notification->id;
             if ($this->NotificationQueue->send($notification)) {
                 $this->NotificationQueue->success($notification->id);
                 $sent++;
             } else {
                 $this->NotificationQueue->fail($notification->id);
                 $failed++;
             }
         }
         $this->NotificationQueue->releaseLocks($batchIds);
         $this->out("Batch Size: " . count($batch) . " - Successes: {$sent} - Failures: {$failed}");
     } else {
         $this->out('Notification Queue Batch is empty.');
     }
 }
 /**
  * setUp method
  *
  * @return void
  */
 public function setUp()
 {
     parent::setUp();
     $this->_appEncoding = Configure::read('App.encoding');
     $this->locale = Locale::getDefault();
     Locale::setDefault('en_US');
 }
 /**
  * Builds asset file path based off url
  *
  * @param string $url Asset URL
  * @return string Absolute path for asset file
  */
 protected function _getAssetFile($url)
 {
     //Brood unload hack cause vendor plugin loaded for some reason
     Plugin::unload('Garderobe');
     $parts = explode('/', $url);
     $fileType = array_shift($parts);
     $fileFragment = implode(DS, $parts);
     $allowedExtensions = ComponentInstallerConfigureTrait::getSupportedExtensions();
     $registeredComponents = (require ROOT . DS . 'vendor' . DS . 'cakephp-components.php');
     foreach ($registeredComponents as $component) {
         $extensions = implode('|', $allowedExtensions);
         if (preg_match("/({$extensions})\$/i", $fileFragment)) {
             foreach ($component as $type => $chunk) {
                 if ($fileType != $type) {
                     continue;
                 }
                 $path = ROOT . DS . Configure::read('App.webroot') . DS . $chunk . DS;
                 if (Configure::read('debug') == false && !strpos($fileFragment, 'min')) {
                     $fileFragment = preg_replace("/(css|js)\$/i", "min.\$1", $fileFragment);
                 }
                 if (file_exists($path . $fileFragment)) {
                     return $path . $fileFragment;
                 }
             }
         }
     }
 }
    public function defineElfinderBrowser($return = false)
    {
        $url = Router::url('/cakephp-tinymce-elfinder/Elfinders/elfinder');
        $clientOptions = Configure::read('TinymceElfinder.client_options');
        $title = Configure::read('TinymceElfinder.title');
        $str = '
		<script type="text/javascript">
		function elFinderBrowser (field_name, url, type, win) {
			  tinymce.activeEditor.windowManager.open({
			    file: "' . $url . '",
			    title: "' . $title . '",
			    width: ' . ($clientOptions['width'] + 20) . ',  
			    height: ' . ($clientOptions['height'] + 50) . ',
			    resizable: "' . $clientOptions['resizable'] . '"
			  }, {
			    setUrl: function (url) {
			      win.document.getElementById(field_name).value = url;
			    }
			  });
			  return false;
			}
		</script>';
        if ($return) {
            return $str;
        } else {
            echo $str;
        }
    }
 /**
  * Initialize behavior configuration
  * @param array $config Configuration passed to the behavior
  * @throws \Cake\Core\Exception\Exception
  * @return void
  */
 public function initialize(array $config)
 {
     $fields = $this->config('fields');
     if (empty($fields)) {
         throw new \Cake\Core\Exception\Exception('Empty fields in CipherBehavior');
     }
     foreach ($this->config('fields') as $fieldName => $fieldType) {
         if (!is_string($fieldName) || !is_string($fieldType) || empty($fieldName) || empty($fieldType)) {
             throw new \Cake\Core\Exception\Exception('Field type need to be specified in CypherBehavior fields');
         }
         try {
             // Throws exception if type is not valid
             Type::build($fieldType);
         } catch (\InvalidArgumentException $ex) {
             throw new \Cake\Core\Exception\Exception(sprintf('Field type %s not valid for field %s', $fieldType, $fieldName));
         }
     }
     $key = $this->config('key');
     if (empty($key)) {
         $key = Configure::read('App.Encrypt.key');
         if (empty($key)) {
             throw new \Cake\Core\Exception\Exception('App.Encrypt.key config value is empty');
         }
         $this->config('key', $key);
     }
     $salt = $this->config('salt');
     if (empty($salt)) {
         $salt = Configure::read('App.Encrypt.salt');
         if (empty($salt)) {
             throw new \Cake\Core\Exception\Exception('App.Encrypt.salt config value is empty');
         }
         $this->config('salt', $salt);
     }
 }
 public function initialize()
 {
     if (!Configure::read('Users.defaultController')) {
         $this->redirect($this->referer());
     }
     parent::initialize();
 }
 /**
  * Displays a view
  *
  * @return void|\Cake\Network\Response
  * @throws \Cake\Network\Exception\NotFoundException When the view file could not
  *   be found or \Cake\View\Exception\MissingTemplateException in debug mode.
  */
 public function display()
 {
     $this->request->allowMethod(['get']);
     // Should not accept any query string params.
     if (count($this->request->query) > 0) {
         throw new BadRequestException(self::THAT_QUERY_PARAMETER_NOT_ALLOWED);
     }
     $path = func_get_args();
     $count = count($path);
     if (!$count) {
         return $this->redirect('/');
     }
     $page = $subpage = null;
     if (!empty($path[0])) {
         $page = $path[0];
     }
     if (!empty($path[1])) {
         $subpage = $path[1];
     }
     $this->set(compact('page', 'subpage'));
     try {
         $this->render(implode('/', $path));
     } catch (MissingTemplateException $e) {
         if (Configure::read('debug')) {
             throw $e;
         }
         throw new NotFoundException();
     }
     return null;
 }
 /**
  * Constructor. Parses the accepted content types accepted by the client using HTTP_ACCEPT
  *
  * @param ComponentRegistry $registry ComponentRegistry object.
  * @param array $config Config options array
  */
 public function __construct(ComponentRegistry $registry, $config = [])
 {
     $this->_defaultConfig = Hash::merge($this->_defaultConfig, $this->_translateConfigMessages(), (array) Configure::read('UserTools.Component'));
     $this->_controller = $registry->getController();
     $this->response = $this->_controller->response;
     parent::__construct($registry, $config);
 }
Exemple #26
0
 /**
  * Marshalls request data into PHP strings.
  *
  * @param mixed $value The value to convert.
  * @return mixed Converted value.
  */
 public function marshal($value)
 {
     if ($value === null) {
         return $value;
     }
     return base64_encode(Security::encrypt($value, Configure::read('Security.key')));
 }
Exemple #27
0
 /**
  * Default validation rules.
  *
  * @param Validator $validator The validator to customize.
  * @return Validator
  */
 public function validationDefault(Validator $validator)
 {
     return $validator->notEmpty('username', __d('wasabi_core', 'Please enter a username.'))->notEmpty('email', __d('wasabi_core', 'Please enter an email address.'))->add('email', ['email' => ['rule' => 'email', 'message' => __d('wasabi_core', 'Please enter a valid email address.')]])->notEmpty('group_id', __d('wasabi_core', 'Please select a group this user belongs to.'))->notEmpty('password', __d('wasabi_core', 'Please enter a password.'), 'create')->add('password', ['length' => ['rule' => ['minLength', 6], 'message' => __d('wasabi_core', 'Ensure your password consists of at least 6 characters.')]])->notEmpty('password_confirmation', __d('wasabi_core', 'Please repeat your Password.'), function ($context) {
         if ($context['newRecord'] === true) {
             return true;
         }
         if (isset($context['data']['password']) && !empty($context['data']['password'])) {
             return true;
         }
         return false;
     })->add('password_confirmation', 'equalsPassword', ['rule' => function ($passwordConfirmation, $provider) {
         if ($passwordConfirmation !== $provider['data']['password']) {
             return __d('wasabi_core', 'The Password Confirmation does not match the Password field.');
         }
         return true;
     }])->add('language_id', 'isValid', ['rule' => function ($languageId) {
         $languageIds = Hash::map(Configure::read('languages.backend'), '{n}', function ($language) {
             return $language->id;
         });
         if (!in_array($languageId, $languageIds)) {
             return __d('wasabi_core', 'Invalid language selected.');
         }
         return true;
     }])->add('timezone', 'isValid', ['rule' => function ($timezone) {
         if (!in_array($timezone, DateTimeZone::listIdentifiers())) {
             return __d('wasabi_core', 'Invalid timezone selected.');
         }
         return true;
     }]);
 }
 /**
  * Before filter handler.
  *
  * @param \Cake\Event\Event $event The event.
  * @return void
  * @throws \Cake\Network\Exception\NotFoundException
  */
 public function beforeFilter(Event $event)
 {
     // TODO add config override.
     if (!Configure::read('debug')) {
         throw new NotFoundException();
     }
 }
 /**
  * Authenticate users based on their JWT. This is inspired by
  * the method _findUser in admads JWT plugin
  *
  * @see https://github.com/ADmad/cakephp-jwt-auth/blob/master/src/Auth/JwtAuthenticate.php
  * @param string $token The token identifier.
  * @param mixed $extra Unused
  * @return array
  */
 public function processAuthenticate($token, $extra = null)
 {
     try {
         $token = JWT::decode($token, Security::salt(), Configure::read('Websockets.allowedAlgs'));
     } catch (Exception $e) {
         if (Configure::read('debug')) {
             throw $e;
         }
         return ["FAILURE"];
     }
     if ($token->id == 'server') {
         return ["SUCCESS", ["authid" => $token->id]];
     }
     $fields = Configure::read('Websockets.fields');
     $table = TableRegistry::get(Configure::read('Websockets.userModel'));
     $conditions = [$table->aliasField($fields['id']) => $token->id];
     if (!empty(Configure::read('Websockets.scope'))) {
         $conditions = array_merge($conditions, Configure::read('Websockets.scope'));
     }
     $result = $table->find('all')->where($conditions)->first();
     if (empty($result)) {
         return ["FAILURE"];
     }
     return ["SUCCESS", ["authid" => $result->id]];
 }
 public function edit($id = null)
 {
     if (empty($id) || !($address = $this->Address->find('first', ['conditions' => ['Address.id' => $id]]))) {
         $this->Flash->error(__('invalid record'));
         return $this->Common->autoRedirect(['action' => 'index']);
     }
     if ($this->Common->isPosted()) {
         if ($this->Address->save($this->request->data)) {
             $var = $this->request->data['Address']['formatted_address'];
             $this->Flash->success(__('record edit {0} saved', h($var)));
             return $this->redirect(['action' => 'index']);
         }
         $this->Flash->error(__('formContainsErrors'));
     }
     if (empty($this->request->data)) {
         $this->request->data = $address;
         $belongsTo = ['' => ' - keine Auswahl - '];
         foreach ($this->Address->belongsTo as $b => $content) {
             if ($b === 'Country') {
                 continue;
             }
             $belongsTo[$b] = $b;
         }
         if (!empty($belongsTo)) {
             $this->set('models', $belongsTo);
         }
     }
     $countries = $this->Address->Country->find('list');
     $countryProvinces = [];
     if (Configure::read('Address.CountryProvince')) {
         $countryProvinces = $this->Address->CountryProvince->find('list');
     }
     $this->set(compact('countries', 'countryProvinces'));
 }