/**
  * Setup the config based on either the Configure::read() values
  * or the PaypalIpnConfig in config/paypal_ipn_config.php
  *
  * Will attempt to read configuration in the following order:
  *   Configure::read('PaypalIpn')
  *   App::import() of config/paypal_ipn_config.php
  *   App::import() of plugin's config/paypal_ipn_config.php
  */
 function __construct()
 {
     $this->config = Configure::read('PaypalIpn');
     if (empty($this->config)) {
         $importConfig = array('type' => 'File', 'name' => 'PaypalIpn.PaypalIpnConfig', 'file' => CONFIGS . 'paypal_ipn_config.php');
         if (!class_exists('PaypalIpnConfig')) {
             App::import($importConfig);
         }
         if (!class_exists('PaypalIpnConfig')) {
             // Import from paypal plugin configuration
             $importConfig['file'] = 'config' . DS . 'paypal_ipn_config.php';
             App::import($importConfig);
         }
         if (!class_exists('PaypalIpnConfig')) {
             trigger_error(__d('paypal_ipn', 'PaypalIpnConfig: The configuration could not be loaded.', true), E_USER_ERROR);
         }
         if (!PHP5) {
             $config =& new PaypalIpnConfig();
         } else {
             $config = new PaypalIpnConfig();
         }
         $vars = get_object_vars($config);
         foreach ($vars as $property => $configuration) {
             if (strpos($property, 'encryption_') === 0) {
                 $name = substr($property, 11);
                 $this->encryption[$name] = $configuration;
             } else {
                 $this->config[$property] = $configuration;
             }
         }
     }
     parent::__construct();
 }
 /**
  * Overide before validate of UploadBehavior plugin processing.
  *
  * @param Model $model Model instance
  * @param array $options Options passed from Model::save().
  * @return bool
  */
 public function beforeValidate(Model $model, $options = array())
 {
     // only run in step validate
     if (!isset($model->data[$model->alias]['upload_flag'])) {
         return parent::beforeValidate($model, $options);
     }
     foreach ($this->settings[$model->alias] as $field => $options) {
         if (!empty($model->data[$model->alias][$field]) && $this->_isUrl($model->data[$model->alias][$field])) {
             $uri = $model->data[$model->alias][$field];
             if (!$this->_grab($model, $field, $uri)) {
                 $model->invalidate($field, __d('upload', 'File was not downloaded.', true));
                 return false;
             }
         }
         // unset if uploaded
         if (empty($model->data[$model->alias][$field]['name']) && !empty($model->data[$model->alias][$field . '_uploaded'])) {
             // if field is empty, don't delete/nullify existing file
             unset($model->data[$model->alias][$field]);
             continue;
         }
         // set data to validate
         $this->runtime[$model->alias][$field] = $model->data[$model->alias][$field];
     }
     return true;
 }
Example #3
0
 public function beforeSave($options = array())
 {
     //when password field
     if (isset($this->data[$this->alias]['password']) && isset($this->data[$this->alias]['password2'])) {
         if (empty($this->data[$this->alias]['password']) && empty($this->data[$this->alias]['password2'])) {
             unset($this->data[$this->alias]['password']);
             unset($this->data[$this->alias]['password2']);
         } elseif (!empty($this->data[$this->alias]['password'])) {
             if ($this->data[$this->alias]['password'] != $this->data[$this->alias]['password2']) {
                 $this->invalidate('password', __d('backend', "The passwords do not match"));
                 $this->invalidate('password2', __d('backend', "The passwords do not match"));
                 $this->data[$this->alias]['password2'] = null;
                 return false;
             }
         }
     } elseif (isset($this->data[$this->alias]['password'])) {
         $this->invalidate('password', __d('backend', 'Password verification not submitted'));
         $this->invalidate('password2', __d('backend', 'Password verification not submitted'));
         return false;
     }
     if (isset($this->data[$this->alias]['password']) && !empty($this->data[$this->alias]['password'])) {
         $this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']);
     }
     return true;
 }
Example #4
0
 public function createDatabaseFile($data)
 {
     App::uses('File', 'Utility');
     App::uses('ConnectionManager', 'Model');
     $config = $this->defaultConfig;
     foreach ($data['Install'] as $key => $value) {
         if (isset($data['Install'][$key])) {
             $config[$key] = $value;
         }
     }
     $result = copy(APP . 'Config' . DS . 'database.php.install', APP . 'Config' . DS . 'database.php');
     if (!$result) {
         return __d('croogo', 'Could not copy database.php file.');
     }
     $file = new File(APP . 'Config' . DS . 'database.php', true);
     $content = $file->read();
     foreach ($config as $configKey => $configValue) {
         $content = str_replace('{default_' . $configKey . '}', $configValue, $content);
     }
     if (!$file->write($content)) {
         return __d('croogo', 'Could not write database.php file.');
     }
     try {
         ConnectionManager::create('default', $config);
         $db = ConnectionManager::getDataSource('default');
     } catch (MissingConnectionException $e) {
         return __d('croogo', 'Could not connect to database: ') . $e->getMessage();
     }
     if (!$db->isConnected()) {
         return __d('croogo', 'Could not connect to database.');
     }
     return true;
 }
 /**
  * ConfirmableBehaviorTest::testBasicValidation()
  *
  * @return void
  */
 public function testValidationThatHasBeenModifiedBefore()
 {
     $this->Articles = TableRegistry::get('SluggedArticles');
     /*
     $this->Articles->validator()->add('confirm', 'notBlank', [
     		'rule' => function ($value, $context) {
     			return !empty($value);
     		},
     		'message' => __('Please select checkbox to continue.'),
     		'requirePresence' => true,
     		'allowEmpty' => false,
     		'last' => true,
     	]);
     $this->Articles->validator()->remove('confirm');
     */
     $this->Articles->addBehavior('Tools.Confirmable');
     $animal = $this->Articles->newEntity();
     $data = ['name' => 'FooBar', 'confirm' => '0'];
     $animal = $this->Articles->patchEntity($animal, $data);
     $this->assertNotEmpty($animal->errors());
     $this->assertSame(['confirm' => ['notBlank' => __d('tools', 'Please confirm the checkbox')]], $animal->errors());
     $data = ['name' => 'FooBar', 'confirm' => '1'];
     $animal = $this->Articles->patchEntity($animal, $data);
     $this->assertEmpty($animal->errors());
 }
Example #6
0
 /**
  * Initializes git, makes tmp folders writeable, and adds the core submodules (or specified group)
  *
  * @return void
  */
 public function init($working)
 {
     $this->out(__d('baking_plate', "\n<info>Making temp folders writeable...</info>"));
     $tmp = array('tmp' . DS . 'cache', 'tmp' . DS . 'cache' . DS . 'models', 'tmp' . DS . 'cache' . DS . 'persistent', 'tmp' . DS . 'cache' . DS . 'views', 'tmp' . DS . 'logs', 'tmp' . DS . 'sessions', 'tmp' . DS . 'tests', 'webroot' . DS . 'ccss', 'webroot' . DS . 'cjs', 'webroot' . DS . 'uploads');
     foreach ($tmp as $dir) {
         if (!is_dir($working . DS . $dir)) {
             $this->out(__d('baking_plate', "\n<info>Creating Directory %s with permissions 0777</info>", $dir));
             mkdir($working . DS . $dir, 0777);
         } else {
             $this->out(__d('baking_plate', "\n<info>Setting Permissions of %s to 0777</info>", $dir));
             chmod($working . DS . $dir, 0777);
         }
     }
     $this->nl();
     chdir($working);
     $this->out();
     $this->out(passthru('git init'));
     $this->all();
     $this->args = null;
     if (!file_exists($working . 'Config' . DS . 'database.php')) {
         $this->DbConfig->path = $working . 'Config' . DS;
         $this->out();
         $this->out(__d('baking_plate', '<warning>Your database configuration was not found. Take a moment to create one.</warning>'));
         $this->DbConfig->execute();
     }
 }
 /**
  * Getter
  *
  * @param string $name
  * @throws RuntimeException
  * @return void
  */
 public function __get($name)
 {
     if ($name === 'createVersions') {
         throw new \RuntimeException(__d('file_storage', 'createVersions was removed, see the change log'));
     }
     parent::__get($name);
 }
Example #8
0
 /**
  * Adds or drops the specified column.
  *
  * @return bool
  */
 public function main()
 {
     $options = (array) $this->params;
     $options['bundle'] = empty($options['bundle']) ? null : $options['bundle'];
     if (empty($options['use'])) {
         $this->err(__d('eav', 'You must indicate a table alias name using the "--use" option. Example: "Articles.Users"'));
         return false;
     }
     try {
         $table = TableRegistry::get($options['use']);
     } catch (\Exception $ex) {
         $table = false;
     }
     if (!$table) {
         $this->err(__d('eav', 'The specified table does not exists.'));
         return false;
     } elseif (!$table->behaviors()->has('Eav')) {
         $this->err(__d('eav', 'The specified table is not using EAV behavior.'));
         return false;
     }
     $columns = $table->listColumns($options['bundle']);
     ksort($columns, SORT_LOCALE_STRING);
     $rows = [[__d('eav', 'Column Name'), __d('eav', 'Data Type'), __d('eav', 'Bundle'), __d('eav', 'Searchable')]];
     foreach ($columns as $name => $info) {
         $rows[] = [$name, $info['type'], !empty($info['bundle']) ? $info['bundle'] : '---', !empty($info['searchable']) ? 'no' : 'yes'];
     }
     $this->out();
     $this->out(__d('eav', 'EAV information for table "{0}":', $options['use']));
     $this->out();
     $this->helper('table')->output($rows);
     return true;
 }
Example #9
0
 /**
  * Return an array of events to listen to.
  *
  * @return array
  */
 public function implementedEvents()
 {
     $before = function ($name) {
         return function () use($name) {
             DebugTimer::start($name, __d('debug_kit', $name));
         };
     };
     $after = function ($name) {
         return function () use($name) {
             DebugTimer::stop($name);
         };
     };
     $both = function ($name) use($before, $after) {
         return [['priority' => 0, 'callable' => $before('Event: ' . $name)], ['priority' => 999, 'callable' => $after('Event: ' . $name)]];
     };
     return ['Controller.initialize' => [['priority' => 0, 'callable' => function () {
         DebugMemory::record(__d('debug_kit', 'Controller initialization'));
     }], ['priority' => 0, 'callable' => $before('Event: Controller.initialize')], ['priority' => 999, 'callable' => $after('Event: Controller.initialize')]], 'Controller.startup' => [['priority' => 0, 'callable' => $before('Event: Controller.startup')], ['priority' => 999, 'callable' => $after('Event: Controller.startup')], ['priority' => 999, 'callable' => function () {
         DebugMemory::record(__d('debug_kit', 'Controller action start'));
         DebugTimer::start(__d('debug_kit', 'Controller action'));
     }]], 'Controller.beforeRender' => [['priority' => 0, 'callable' => function () {
         DebugTimer::stop(__d('debug_kit', 'Controller action'));
     }], ['priority' => 0, 'callable' => $before('Event: Controller.beforeRender')], ['priority' => 999, 'callable' => $after('Event: Controller.beforeRender')], ['priority' => 999, 'callable' => function () {
         DebugMemory::record(__d('debug_kit', 'View Render start'));
         DebugTimer::start(__d('debug_kit', 'View Render start'));
     }]], 'View.beforeRender' => $both('View.beforeRender'), 'View.afterRender' => $both('View.afterRender'), 'View.beforeLayout' => $both('View.beforeLayout'), 'View.afterLayout' => $both('View.afterLayout'), 'View.beforeRenderFile' => [['priority' => 0, 'callable' => function ($event, $filename) {
         DebugTimer::start(__d('debug_kit', 'Render {0}', $filename));
     }]], 'View.afterRenderFile' => [['priority' => 0, 'callable' => function ($event, $filename) {
         DebugTimer::stop(__d('debug_kit', 'Render {0}', $filename));
     }]], 'Controller.shutdown' => [['priority' => 0, 'callable' => $before('Event: Controller.shutdown')], ['priority' => 0, 'callable' => function () {
         DebugTimer::stop(__d('debug_kit', 'View Render start'));
         DebugMemory::record(__d('debug_kit', 'Controller shutdown'));
     }], ['priority' => 999, 'callable' => $after('Event: Controller.shutdown')]]];
 }
Example #10
0
 /**
  * {@inheritdoc}
  */
 public function beforeValidate(Model $Model, $options = array())
 {
     $ModelValidator = $Model->validator();
     foreach ($Model->data[$Model->alias] as $field => $value) {
         if (!preg_match('/^([a-z0-9_]+)_confirm$/i', $field, $match)) {
             continue;
         }
         if (!array_key_exists($match[1], $Model->data[$Model->alias])) {
             continue;
         }
         if (!($Ruleset = $ModelValidator->getField($match[1]))) {
             $Ruleset = new CakeValidationSet($match[1], array());
         }
         $ruleset = array();
         foreach ($Ruleset->getRules() as $name => $Rule) {
             $ruleset[$name] = (array) $Rule;
             foreach (array_keys($ruleset[$name]) as $key) {
                 if (!preg_match('/^[a-z]/i', $key)) {
                     unset($ruleset[$name][$key]);
                 }
             }
         }
         $ModelValidator->add($field, new CakeValidationSet($field, array()));
         $ModelValidator->getField($field)->setRule('confirmed', array('rule' => 'isConfirmed', 'message' => __d('common', "No match.")));
     }
     return true;
 }
 /**
  * Default validation rules.
  *
  * @param \Cake\Validation\Validator $validator Validator instance.
  * @return \Cake\Validation\Validator
  */
 public function validationDefault(Validator $validator)
 {
     $validator->add('id', 'valid', ['rule' => 'numeric'])->allowEmpty('id', 'create');
     $validator->add('email', 'valid', ['rule' => 'email'])->notEmpty('email');
     $validator->notEmpty('password');
     $validator->allowEmpty('new_password');
     $validator->allowEmpty('confirm_password');
     $validator->add('new_password', 'custom', ['rule' => function ($value, $context) {
         if (!array_key_exists('confirm_password', $context['data'])) {
             return false;
         }
         if ($value !== $context['data']['confirm_password']) {
             return false;
         }
         return true;
     }, 'message' => __d('CakeAdmin', 'Passwords are not equal.')]);
     $validator->add('confirm_password', 'custom', ['rule' => function ($value, $context) {
         if (!array_key_exists('new_password', $context['data'])) {
             return false;
         }
         if ($value !== $context['data']['new_password']) {
             return false;
         }
         return true;
     }, 'message' => __d('CakeAdmin', 'Passwords are not equal.')]);
     return $validator;
 }
 /**
  * @param \Cake\ORM\Table $table
  * @param array $config
  */
 public function __construct(Table $table, array $config = [])
 {
     parent::__construct($table, $config);
     if (!$this->_config['message']) {
         $this->_config['message'] = __d('tools', 'Please confirm the checkbox');
     }
 }
 /**
  * __construct callback
  *
  * @param \Cake\View\View $View : View
  * @param array $config : Config
  * @throws Cake\Error\NotFoundException
  */
 public function __construct(\Cake\View\View $View, array $config = [])
 {
     parent::__construct($View, $config);
     if (!$this->_isSupportedFramework($fw = $this->config('assets.framework'))) {
         throw new NotFoundException(sprintf(__d('bootstrap', 'Configured JavaScript framework "{0}" is not supported. Only "{1}" are valid options.', $fw, implode(', ', $this->_authorizedJsLibs))));
     }
 }
 /**
  * Perform check before field create.
  *
  * @param string $table Table to look in
  * @param string $field Field to look for
  * @throws MigrationException
  * @return bool
  */
 public function checkAddField($table, $field)
 {
     if ($this->tableExists($table) && $this->fieldExists($table, $field)) {
         throw new MigrationException($this->_migration, sprintf(__d('migrations', 'Field "%s" already exists in "%s".'), $field, $table));
     }
     return true;
 }
Example #15
0
 public function __call($methodName, $params)
 {
     if (!method_exists($this->_service, $methodName)) {
         throw new BadMethodCallException(sprintf(__d('ninja', 'The method %s is not defined in %s class.', true), $methodName, get_class($this->_service)));
     }
     return $this->_dispatchService(array($this->_service, $methodName), $params);
 }
Example #16
0
 function getAdresses($options = array())
 {
     $defaultOptions = array('aro' => null);
     $options = array_merge($defaultOptions, $options);
     if (empty($options['aro'])) {
         $aroProvider = Configure::read('Shop.address.ACL.aroProvider');
         //debug($aroProvider);
         if (isset($aroProvider['component']) && isset($aroProvider['component'])) {
             $aro = $this->ShopFunct->callExternalfunction($aroProvider);
         }
         if (empty($aro)) {
             $aro = Configure::read('Shop.address.ACL.defaultAro');
         }
     } else {
         $aro = $options['aro'];
     }
     if (!$this->ShopAddress) {
         App::import('ShopAddress', 'Shop.ShopAddress');
         $this->ShopAddress = new ShopAddress();
     }
     //!!!!!!! Méthode trop lente quand il y a beaucoup d'élémemts. !!!!!!!
     $this->ShopAddress->recursive = -1;
     $allAdresses = $this->ShopAddress->find('all', array('conditions' => array('active' => 1)));
     if (count($allAdresses) > 250) {
         trigger_error(__d('shop', "Too many entries for the current analysing method. May be slow.", true), E_USER_NOTICE);
     }
     $adresses = true();
     foreach ($allAdresses as $adress) {
         if (!$this->Acl->check($aro, array('model' => $this->ShopAddress->alias, 'foreign_key' => $adress['ShopAddress']['id']))) {
             $adresses[] = $adress;
         }
     }
     return $adresses;
 }
 /**
  * Delete-insert circular notice choices
  *
  * @param array $data input data
  * @return bool
  * @throws InternalErrorException
  */
 public function replaceCircularNoticeChoices($data)
 {
     $contentId = $data['CircularNoticeContent']['id'];
     // 残す選択肢の条件を生成
     $deleteConditions = array('CircularNoticeChoice.circular_notice_content_id' => $contentId);
     $extractIds = Hash::filter(Hash::extract($data['CircularNoticeChoices'], '{n}.CircularNoticeChoice.id'));
     if (count($extractIds) > 0) {
         $deleteConditions['CircularNoticeChoice.id NOT'] = $extractIds;
     }
     // 選択肢を一旦削除
     if (!$this->deleteAll($deleteConditions, false)) {
         throw new InternalErrorException(__d('net_commons', 'Internal Server Error'));
     }
     // 1件ずつ保存
     foreach ($data['CircularNoticeChoices'] as $choice) {
         $choice['CircularNoticeChoice']['circular_notice_content_id'] = $contentId;
         if (!$this->validateCircularChoice($choice)) {
             return false;
         }
         if (!$this->save(null, false)) {
             throw new InternalErrorException(__d('net_commons', 'Internal Server Error'));
         }
     }
     return true;
 }
 /**
  * Stop timers for rendering.
  *
  * @param string $layoutFile
  */
 public function afterLayout($layoutFile)
 {
     DebugTimer::stop('viewRender');
     DebugTimer::stop('controllerRender');
     DebugMemory::record(__d('debug_kit', 'View render complete'));
     $this->_renderComplete = true;
 }
Example #19
0
 /**
  * Save link settings
  *
  * @param array $data received post data
  * @return bool True on success, false on failure
  * @throws InternalErrorException
  */
 public function saveLinkSetting($data)
 {
     $this->loadModels(['LinkSetting' => 'Links.LinkSetting', 'BlockRolePermission' => 'Blocks.BlockRolePermission']);
     //トランザクションBegin
     $this->setDataSource('master');
     $dataSource = $this->getDataSource();
     $dataSource->begin();
     try {
         if (!$this->validateLinkSetting($data)) {
             return false;
         }
         foreach ($data[$this->BlockRolePermission->alias] as $value) {
             if (!$this->BlockRolePermission->validateBlockRolePermissions($value)) {
                 $this->validationErrors = Hash::merge($this->validationErrors, $this->BlockRolePermission->validationErrors);
                 return false;
             }
         }
         if (!$this->save(null, false)) {
             throw new InternalErrorException(__d('net_commons', 'Internal Server Error'));
         }
         foreach ($data[$this->BlockRolePermission->alias] as $value) {
             if (!$this->BlockRolePermission->saveMany($value, ['validate' => false])) {
                 throw new InternalErrorException(__d('net_commons', 'Internal Server Error'));
             }
         }
         //トランザクションCommit
         $dataSource->commit();
     } catch (Exception $ex) {
         //トランザクションRollback
         $dataSource->rollback();
         CakeLog::error($ex);
         throw $ex;
     }
     return true;
 }
Example #20
0
 /**
  * List of options
  *
  * @param null|string $prefix
  */
 public function admin_prefix($prefix = null)
 {
     $prefix_name = ['general' => __d('hurad', 'General'), 'comment' => __d('hurad', 'Comment'), 'permalink' => __d('hurad', 'Permalink'), 'read' => __d('hurad', 'Read')];
     $this->set('title_for_layout', sprintf(__d('hurad', '%s Option'), $prefix_name[$prefix]));
     if (!array_key_exists($prefix, $prefix_name)) {
         $this->Session->setFlash(__d('hurad', 'Invalid Option name'), 'flash_message', ['class' => 'danger']);
         /* @todo Set admin prefix config */
         $this->redirect('/admin');
     }
     if ($this->request->is('post') || $this->request->is('put')) {
         switch ($this->request->param('pass')[0]) {
             case 'general':
                 $this->request->data['Option']['site_url'] = rtrim($this->request->data['Option']['site_url'], "/");
                 break;
         }
         $opt = [];
         foreach ($this->request->data as $optionArray) {
             foreach ($optionArray as $option => $value) {
                 $opt[Inflector::humanize($prefix) . '.' . $option] = $value;
             }
         }
         $optionData['Option'] = $opt;
         if ($this->Option->update($optionData)) {
             $this->Session->setFlash(__d('hurad', 'Options have been updated!'), 'flash_message', ['class' => 'success']);
         } else {
             $this->Session->setFlash(__d('hurad', 'Unable to update ' . $prefix . ' options.'), 'error-option', ['errors' => $this->Option->validationErrors]);
         }
     } else {
         $this->request->data['Option'] = Configure::read(Inflector::humanize($prefix));
     }
     $this->set('errors', $this->Option->validationErrors);
     $this->set(compact('prefix'));
 }
Example #21
0
 public function store()
 {
     // Validate the Input data.
     $input = Input::all();
     $validator = $this->validate($input);
     if ($validator->passes()) {
         // The Application.
         Config::set('app.name', $input['siteName']);
         Config::set('app.color_scheme', $input['siteSkin']);
         // The Mailer
         Config::set('mail.driver', $input['mailDriver']);
         Config::set('mail.host', $input['mailHost']);
         Config::set('mail.port', $input['mailPort']);
         Config::set('mail.from.address', $input['mailFromAddress']);
         Config::set('mail.from.name', $input['mailFromName']);
         Config::set('mail.encryption', $input['mailEncryption']);
         Config::set('mail.username', $input['mailUsername']);
         Config::set('mail.password', $input['mailPassword']);
         // Prepare the flash message.
         $status = __d('settings', 'The Settings was successfully updated.');
         return Redirect::to('admin/settings')->withStatus($status);
     }
     // Errors occurred on Validation.
     $status = $validator->errors();
     return Redirect::back()->withInput()->withStatus($status, 'danger');
 }
Example #22
0
File: Init.php Project: shama/oven
 /**
  * initCore
  * Setup your Config/core.php
  *
  * @param array $config 
  * @return boolean
  * @throws CakeException
  */
 public function initCore($config = array())
 {
     $path = $this->appPath . 'Config' . DS . 'core.php';
     if (!file_exists($path)) {
         throw new CakeException(__d('oven', 'Core config file could not be found.'));
     }
     if (!is_writable($path)) {
         throw new CakeException(__d('oven', 'Core config is not writable.'));
     }
     $config = Set::merge(array('salt' => substr(str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'), 0, 40), 'cipherSeed' => str_shuffle(str_repeat('0123456789', 3))), $config);
     // READ FILE
     $file = new File($path);
     $contents = $file->read();
     // CHANGE SALT
     $replace = "Configure::write('Security.salt', 'DYhG93b0qyJfIxfs2guVoUubWwvniR2G0FgaC9mi');";
     $with = "Configure::write('Security.salt', '" . $config['salt'] . "');";
     $contents = str_replace($replace, $with, $contents);
     // CHANGE CIPHERSEED
     $replace = "Configure::write('Security.cipherSeed', '76859309657453542496749683645');";
     $with = "Configure::write('Security.cipherSeed', '" . $config['cipherSeed'] . "');";
     $contents = str_replace($replace, $with, $contents);
     // TURN ON ADMIN ROUTING
     $replace = "//Configure::write('Routing.prefixes', array('admin'));";
     $with = "Configure::write('Routing.prefixes', array('admin'));";
     $contents = str_replace($replace, $with, $contents);
     // WRITE FILE
     $file->write($contents);
     $file->close();
     return true;
 }
 /**
  * Add method
  *
  * @return void Redirects on successful add, renders view otherwise.
  */
 public function add()
 {
     $plugin = $this->Plugins->newEntity();
     if ($this->request->is('post')) {
         $file = $this->request->data['file'];
         unset($this->request->data['file']);
         $pluginInstaller = new PluginInstaller();
         try {
             $pluginInfo = $pluginInstaller->install($file['tmp_name']);
             $query = $this->Plugins->find();
             $query->select(['max_weight' => $query->func()->max('weight')]);
             $pluginInfo['weight'] = $query->first()->max_weight + 1;
             $plugin = $this->Plugins->patchEntity($plugin, $pluginInfo);
             if ($this->Plugins->save($plugin)) {
                 $this->Flash->success(__d('plugin_manager', 'The plugin has been saved.'));
                 return $this->redirect(['action' => 'index']);
             } else {
                 $this->Flash->error(__d('plugin_manager', 'The plugin could not be saved. Please, try again.'));
             }
         } catch (Exception $e) {
             $this->Flash->error($e->getMessage());
             return $this->redirect(array('action' => 'add'));
         }
     }
     $this->set(compact('plugin'));
     $this->set('_serialize', ['plugin']);
 }
Example #24
0
 /**
  * Read a config file and return its contents.
  *
  * Files with `.` in the name will be treated as values in plugins.  Instead of reading from
  * the initialized path, plugin keys will be located using App::pluginPath().
  *
  * @param string $key The identifier to read from.  If the key has a . it will be treated
  *  as a plugin prefix.
  * @return array Parsed configuration values.
  * @throws ConfigureException when files don't exist or they don't contain `$config`.
  *  Or when files contain '..' as this could lead to abusive reads.
  */
 public function read($key)
 {
     if (strpos($key, '..') !== false) {
         throw new ConfigureException(__d('cake_dev', 'Cannot load configuration files with ../ in them.'));
     }
     if (substr($key, -4) === '.php') {
         $key = substr($key, 0, -4);
     }
     list($plugin, $key) = pluginSplit($key);
     if ($plugin) {
         $file = App::pluginPath($plugin) . 'Config' . DS . $key;
     } else {
         $file = $this->_path . $key;
     }
     $file .= '.php';
     if (!is_file($file)) {
         if (!is_file(substr($file, 0, -4))) {
             throw new ConfigureException(__d('cake_dev', 'Could not load configuration files: %s or %s', $file, substr($file, 0, -4)));
         }
     }
     include $file;
     if (!isset($config)) {
         throw new ConfigureException(sprintf(__d('cake_dev', 'No variable $config found in %s.php'), $file));
     }
     return $config;
 }
Example #25
0
 /**
  * Renders the Thumbnail for given source
  * 
  * 
  * @param string $source Absolute path to source imagefile
  * @param string $target Absolute thumbnail filepath
  * @param array $params Phpthumb params
  * @throws NotFoundException
  * @throws CakeException
  */
 public static function createThumbnail($source, $target = null, $params = array())
 {
     if (!file_exists($source)) {
         throw new NotFoundException(__d('media', "File %s not found", $source));
     }
     //@todo use dependency injection
     $phpThumb = new phpthumb();
     $params = array_merge(array('watermark' => null, 'useImageMagick' => false, 'imageMagickPath' => '/usr/bin/convert', 'config_temp_directory' => MEDIA_CACHE_DIR, 'config_cache_directory' => MEDIA_CACHE_DIR, 'config_output_format' => 'jpg', 'config_error_die_on_error' => false, 'config_document_root' => ROOT, 'config_allow_src_above_docroot' => true, 'config_cache_disable_warning' => true, 'config_disable_debug' => true, 'config_cache_prefix' => 'phpthumb_', 'sia' => "thumbnail"), $params);
     // Configuring thumbnail settings
     self::_applyParams($phpThumb, $params);
     // Set source path
     $phpThumb->setSourceFilename($source);
     // Creating thumbnail
     if ($phpThumb->GenerateThumbnail()) {
         //@todo Duplicate code. See getThumbnail()
         $target = self::target($source, $target, $params);
         if (!$phpThumb->RenderToFile($target)) {
             throw new CakeException('Could not render image to: ' . $target);
         }
         @chmod($target, 0644);
         //TODO check if this is necessary
     }
     //debug($phpThumb->phpThumbDebug());
     return $target;
 }
Example #26
0
 public function login()
 {
     //redirect if user empty
     $this->_redirectIfNoUsers();
     /*
      * form submitted
      */
     if ($this->request->is('post')) {
         if ($this->Auth->login()) {
             //if user loggedIn
             /*
              * > set user id
              * > set user last login time
              * > set user login
              * > redirect to dashboard
              */
             $this->_userId = $this->Auth->user('id');
             $this->CloggyUser->setUserLastLogin($this->_userId);
             $this->CloggyUserLogin->setLogin($this->_userId);
             $this->redirect($this->Auth->loginRedirect);
         } else {
             $this->Auth->flash(__d('cloggy', 'Wrong username or password'));
             $this->redirect($this->Auth->loginAction);
         }
     }
     $this->set('title_for_layout', __d('cloggy', 'Cloggy - Administrator Login'));
 }
Example #27
0
 /**
  * Meta field: with key/value fields
  *
  * @param string $key (optional) key
  * @param string $value (optional) value
  * @param integer $id (optional) ID of Meta
  * @param array $options (optional) options
  * @return string
  */
 public function field($key = '', $value = null, $id = null, $options = array())
 {
     $_options = array('key' => array('label' => __d('croogo', 'Key'), 'value' => $key, 'class' => 'span12'), 'value' => array('label' => __d('croogo', 'Value'), 'value' => $value, 'class' => 'span12', 'type' => 'textarea', 'rows' => 2));
     $options = Hash::merge($_options, $options);
     $uuid = String::uuid();
     $fields = '';
     if ($id != null) {
         $fields .= $this->Form->input('Meta.' . $uuid . '.id', array('type' => 'hidden', 'value' => $id));
         $this->Form->unlockField('Meta.' . $uuid . '.id');
     }
     $fields .= $this->Form->input('Meta.' . $uuid . '.key', $options['key']);
     $fields .= $this->Form->input('Meta.' . $uuid . '.value', $options['value']);
     $this->Form->unlockField('Meta.' . $uuid . '.key');
     $this->Form->unlockField('Meta.' . $uuid . '.value');
     $fields = $this->Html->tag('div', $fields, array('class' => 'fields'));
     $id = is_null($id) ? $uuid : $id;
     $deleteUrl = array_intersect_key($this->request->params, array('admin' => null, 'plugin' => null, 'controller' => null, 'named' => null));
     $deleteUrl['action'] = 'delete_meta';
     $deleteUrl[] = $id;
     $deleteUrl = $this->url($deleteUrl);
     $actions = $this->Html->link(__d('croogo', 'Remove'), $deleteUrl, array('class' => 'remove-meta', 'rel' => $id));
     $actions = $this->Html->tag('div', $actions, array('class' => 'actions'));
     $output = $this->Html->tag('div', $actions . $fields, array('class' => 'meta'));
     return $output;
 }
 /**
  * Constructor
  *
  * @param ComponentCollection $collection The Component collection used on this request.
  * @param array $settings Array of settings to use.
  * @throws CakeException
  */
 public function __construct(ComponentCollection $collection, $settings)
 {
     parent::__construct($collection, $settings);
     if (empty($this->settings['parameter']) && empty($this->settings['header'])) {
         throw new CakeException(__d('bz_utils', 'You need to specify token parameter and/or header'));
     }
 }
Example #29
0
 public function generate_menu($pos = 0, $parent_id = null)
 {
     $this->processed[$pos] = true;
     if ($this->hasChild($this->menu[$pos])) {
         if (!isset($html)) {
             $html = null;
         }
         $mother_node = $this->menu[$pos];
         $children = $this->generate_menu($pos + 1, $mother_node['Menu']['id']);
         $html .= '<li class="treeview">' . $this->Html->link(__d('dkmadmin', $mother_node['Menu']['name']), $mother_node['Menu']['link']) . '<ul class="treeview-menu">' . $children;
     } else {
         if (!isset($html)) {
             $html = null;
         }
         if (strstr($this->menu[$pos]['Menu']['link'], $this->urlActive)) {
             $html .= '<li class="active">' . $this->Html->link(__d('dkmadmin', $this->menu[$pos]['Menu']['name']), $this->menu[$pos]['Menu']['link']) . '</li>';
         } else {
             $html .= '<li>' . $this->Html->link(__d('dkmadmin', $this->menu[$pos]['Menu']['name']), $this->menu[$pos]['Menu']['link']) . '</li>';
         }
         if (isset($this->menu[$pos + 1])) {
             if ($this->menu[$pos + 1]['Menu']['parent_id'] != $parent_id) {
                 $html .= '</ul></li>';
             } else {
                 $html .= '</li>';
             }
         } else {
             $html .= '</ul></li>';
         }
     }
     if (isset($this->menu[$pos + 1]) && !isset($this->processed[$pos + 1])) {
         $html .= $this->generate_menu($pos + 1, $this->menu[$pos + 1]['Menu']['parent_id']);
     }
     return $html;
 }
Example #30
0
 /**
  * Displays a correct link to add / remove an item from a given favorite list
  *
  * If the current user already added the item to the list, the generated link will allow him to
  * remove it from the list otherwise it will generate an add link
  *
  * @param string $type Favorite type
  * @param string $id Item id
  * @param string $addText Text to use for "add" type links
  * @param string $removeText Text to use for "remove" type links
  * @param array $options Options for the Html->link method
  * @return string Correct Html link
  */
 public function toggleFavorite($type, $id, $addText = null, $removeText = null, $options = array())
 {
     $_defaultTexts = Configure::read('Favorites.defaultTexts');
     $link = '';
     $type = strtolower($type);
     if (!array_key_exists($type, $_defaultTexts)) {
         throw new InvalidArgumentException(sprintf(__d('favorites', 'Incorrect favorite type "%s".'), $type));
     } else {
         foreach (array('addText', 'removeText') as $textVarName) {
             if (is_null(${$textVarName})) {
                 ${$textVarName} = $_defaultTexts[$type];
             }
         }
         if (empty($options['class'])) {
             $options['class'] = '';
         }
         $options['class'] = $type . ' ' . $options['class'];
         $remove = $this->isFavorite($type, $id);
         if ($remove) {
             $url = array_merge($this->favoriteLinkBase, array('action' => 'delete', array_search($id, $this->_userFavorites[$type])));
             $linkText = $removeText;
             $options['class'] = 'remove-favorite ' . $options['class'];
         } else {
             $url = array_merge($this->favoriteLinkBase, array('action' => 'add', $type, $id));
             $linkText = $addText;
             $options['class'] = 'add-favorite ' . $options['class'];
         }
         $options['class'] = trim($options['class']);
         $link = $this->Html->link($linkText, $url, $options);
     }
     return $link;
 }