Example #1
0
 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) ) {
     						
     					}
     				}
     		    }
     	    }
     */
 }
 /**
  * @return void
  */
 public function setUp()
 {
     parent::setUp();
     Configure::write('App.namespace', 'TestApp');
     $this->Comments = TableRegistry::get('BitmaskedComments');
     $this->Comments->addBehavior('Tools.Bitmasked', ['mappedField' => 'statuses']);
 }
 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);
     }
 }
Example #4
0
 /**
  * setUp
  *
  * @return void
  */
 public function setUp()
 {
     parent::setUp();
     Configure::write('Acl.classname', 'DbAcl');
     Configure::write('Acl.database', 'test');
     $this->Task = $this->getMock('Acl\\AclExtras', ['in', 'out', 'hr', 'createFile', 'error', 'err', 'clear', 'getControllerList']);
 }
Example #5
0
 /**
  * setUp method
  *
  * @return void
  */
 public function setUp()
 {
     parent::setUp();
     Plugin::load('TestPlugin');
     Configure::write('App.namespace', 'TestApp');
     $this->dispatcher = $this->getMockBuilder('Cake\\Console\\ShellDispatcher')->setMethods(['_stop'])->getMock();
 }
    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;
        }
    }
 public function initialize()
 {
     if (!Configure::read('Users.defaultController')) {
         $this->redirect($this->referer());
     }
     parent::initialize();
 }
 /**
  * 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.');
     }
 }
 /**
  * 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;
                 }
             }
         }
     }
 }
Example #10
0
 /**
  * setUp method
  *
  * @return void
  */
 public function setUp()
 {
     parent::setUp();
     Configure::write('Acl.classname', __NAMESPACE__ . '\\CachedDbAclTwoTest');
     $this->CachedDb = new CachedDbAclTwoTest();
     Cache::config('tests', ['engine' => 'File', 'path' => TMP, 'prefix' => 'test_']);
 }
Example #11
0
 /**
  * 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();
     }
 }
Example #12
0
 function __construct()
 {
     Configure::load('amazon', 'default');
     $this->awsAccessKey = Configure::read('AwsAccessKey');
     $this->awsSecretKey = Configure::read('AwsSecretKey');
     $this->associateTag = Configure::read('AssociateTag');
 }
Example #13
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;
 }
 /**
  * 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;
 }
    /**
     * 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;
    }
 /**
  * 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);
     }
 }
 /**
  * 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();
     }
 }
Example #18
0
 /**
  * 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;
 }
Example #19
0
 /**
  * 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');
 }
Example #20
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')));
 }
Example #21
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);
 }
 /**
  * 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();
     }
 }
 /**
  * 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);
 }
Example #24
0
 /**
  * Test generating code.
  *
  * @return void
  */
 public function testBake()
 {
     Configure::write('App.namespace', 'Bake\\Test\\App');
     $this->Task->expects($this->once())->method('createFile')->with($this->_normalizePath(APP . 'Model/Behavior/ExampleBehavior.php'), $this->stringContains('class ExampleBehavior extends Behavior'));
     $result = $this->Task->bake('Example');
     $this->assertSameAsFile(__FUNCTION__ . '.php', $result);
 }
 /**
  * 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 setUp()
 {
     parent::setUp();
     Configure::write('App.namespace', 'Spekkoek\\Test\\TestApp');
     $this->factory = new ControllerFactory();
     $this->response = $this->getMock('Cake\\Network\\Response');
 }
Example #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;
     }]);
 }
Example #28
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']);
 }
 /**
  * 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]];
 }
Example #30
0
 /**
  * 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);
 }