Example #1
1
 /**
  * Override startup of the Shell
  *
  * @return void
  */
 public function startup()
 {
     parent::startup();
     if (isset($this->params['connection'])) {
         $this->connection = $this->params['connection'];
     }
     $class = Configure::read('Acl.classname');
     list($plugin, $class) = pluginSplit($class, true);
     App::uses($class, $plugin . 'Controller/Component/Acl');
     if (!in_array($class, array('DbAcl', 'DB_ACL')) && !is_subclass_of($class, 'DbAcl')) {
         $out = "--------------------------------------------------\n";
         $out .= __d('cake_console', 'Error: Your current Cake configuration is set to an ACL implementation other than DB.') . "\n";
         $out .= __d('cake_console', 'Please change your core config to reflect your decision to use DbAcl before attempting to use this script') . "\n";
         $out .= "--------------------------------------------------\n";
         $out .= __d('cake_console', 'Current ACL Classname: %s', $class) . "\n";
         $out .= "--------------------------------------------------\n";
         $this->err($out);
         $this->_stop();
     }
     if ($this->command) {
         if (!config('database')) {
             $this->out(__d('cake_console', 'Your database configuration was not found. Take a moment to create one.'), true);
             $this->args = null;
             return $this->DbConfig->execute();
         }
         require_once APP . 'Config' . DS . 'database.php';
         if (!in_array($this->command, array('initdb'))) {
             $collection = new ComponentCollection();
             $this->Acl = new AclComponent($collection);
             $controller = new Controller();
             $this->Acl->startup($controller);
         }
     }
 }
 /**
  * Authenticates the identity contained in a request.  Will use the `settings.userModel`, and `settings.fields`
  * to find POST data that is used to find a matching record in the `settings.userModel`.  Will return false if
  * there is no post data, either username or password is missing, of if the scope conditions have not been met.
  *
  * @param CakeRequest $request The request that contains login information.
  * @param CakeResponse $response Unused response object.
  * @return mixed.  False on login failure.  An array of User data on success.
  */
 public function authenticate(CakeRequest $request, CakeResponse $response)
 {
     $userModel = $this->settings['userModel'];
     list($plugin, $model) = pluginSplit($userModel);
     if (empty($request->data[$model])) {
         return false;
     }
     if (empty($request->data[$model][$this->settings['post_key']]) || empty($request->data[$model][$this->settings['fields']['password']])) {
         return false;
     }
     $User = ClassRegistry::init($userModel);
     $password = $request->data[$model][$this->settings['fields']['password']];
     foreach ($this->settings['fields']['username'] as $username) {
         $conditions = array();
         if (!empty($this->settings['scope'])) {
             $conditions = array_merge($conditions, $this->settings['scope']);
         }
         $conditions[$model . '.' . $username] = $request->data[$model][$this->settings['post_key']];
         $conditions[$model . '.' . $this->settings['fields']['password']] = $this->_password($password);
         $result = $User->find('first', array('conditions' => $conditions, 'contain' => $this->settings['contain']));
         if (!empty($result) || !empty($result[$model])) {
             CakeSession::write(Configure::read('SessionKey'), $result);
             unset($result[$model][$this->settings['fields']['password']]);
             return $result[$model];
         }
     }
     return false;
 }
 /**
  * Get related model's properties.
  *
  * @param  mixed $table related table instance or name
  * @param  sting $data  query parameter value
  * @return mixed
  */
 protected function _getRelatedProperties($table, $data)
 {
     if (!is_object($table)) {
         $tableName = $table;
         $table = TableRegistry::get($tableName);
     } else {
         $tableName = $table->registryAlias();
     }
     $result['id'] = $data;
     if (method_exists($table, 'getConfig') && is_callable([$table, 'getConfig'])) {
         $result['config'] = $table->getConfig();
     }
     // display field
     $result['displayField'] = $table->displayField();
     // get associated entity record
     $result['entity'] = $this->_getAssociatedRecord($table, $data);
     // get related table's displayField value
     if (!empty($result['entity'])) {
         // Pass the value through related field handler
         // to properly display the user-friendly label.
         $fhf = new FieldHandlerFactory($this->cakeView);
         $result['dispFieldVal'] = $fhf->renderValue($table, $table->displayField(), $result['entity']->{$table->displayField()}, ['renderAs' => RelatedFieldHandler::RENDER_PLAIN_VALUE]);
     } else {
         $result['dispFieldVal'] = null;
     }
     // get plugin and controller names
     list($result['plugin'], $result['controller']) = pluginSplit($tableName);
     return $result;
 }
Example #4
0
 /**
  * Override startup
  *
  * @access public
  */
 function startup()
 {
     $name = $file = $path = $connection = $plugin = null;
     if (!empty($this->params['name'])) {
         $name = $this->params['name'];
     } elseif (!empty($this->args[0])) {
         $name = $this->params['name'] = $this->args[0];
     }
     if (strpos($name, '.')) {
         list($this->params['plugin'], $splitName) = pluginSplit($name);
         $name = $this->params['name'] = $splitName;
     }
     if ($name) {
         $this->params['file'] = Inflector::underscore($name);
     }
     if (empty($this->params['file'])) {
         $this->params['file'] = 'schema.php';
     }
     if (strpos($this->params['file'], '.php') === false) {
         $this->params['file'] .= '.php';
     }
     $file = $this->params['file'];
     if (!empty($this->params['path'])) {
         $path = $this->params['path'];
     }
     if (!empty($this->params['connection'])) {
         $connection = $this->params['connection'];
     }
     if (!empty($this->params['plugin'])) {
         $plugin = $this->params['plugin'];
     }
     $this->Schema = new CakeSchema(compact('name', 'path', 'file', 'connection', 'plugin'));
 }
Example #5
0
 /**
  * Find a user record using the standard options.
  *
  * The $conditions parameter can be a (string)username or an array containing conditions for Model::find('first'). If
  * the password field is not included in the conditions the password will be returned.
  *
  * @param Mixed $conditions The username/identifier, or an array of find conditions.
  * @param Mixed $password The password, only use if passing as $conditions = 'username'.
  * @return Mixed Either false on failure, or an array of user data.
  */
 protected function _findUser($conditions, $password = null)
 {
     $userModel = $this->settings['userModel'];
     list(, $model) = pluginSplit($userModel);
     $fields = $this->settings['fields'];
     if (!is_array($conditions)) {
         if (!$password) {
             return false;
         }
         $username = $conditions;
         $conditions = array($model . '.' . $fields['username'] => $username, $model . '.' . $fields['password'] => $this->_password($password));
     }
     if (!empty($this->settings['scope'])) {
         $conditions = array_merge($conditions, $this->settings['scope']);
     }
     $result = ClassRegistry::init($userModel)->find('first', array('conditions' => $conditions, 'recursive' => $this->settings['recursive'], 'contain' => $this->settings['contain']));
     if (empty($result) || empty($result[$model])) {
         return false;
     }
     $user = $result[$model];
     if (isset($conditions[$model . '.' . $fields['password']]) || isset($conditions[$fields['password']])) {
         unset($user[$fields['password']]);
     }
     unset($result[$model]);
     return array_merge($user, $result);
 }
Example #6
0
 /**
  * override core one with the following enhancements/fixes:
  * - 404s log to a different domain
  * - IP, Referer and Browser-Infos are added for better error debugging/tracing
  * 2011-12-21 ms
  */
 public static function handleException(Exception $exception)
 {
     $config = Configure::read('Exception');
     if (!empty($config['log'])) {
         $log = LOG_ERR;
         $message = sprintf("[%s] %s\n%s\n%s", get_class($exception), $exception->getMessage(), $exception->getTraceAsString(), self::traceDetails());
         if (in_array(get_class($exception), array('MissingControllerException', 'MissingActionException', 'PrivateActionException', 'NotFoundException'))) {
             $log = '404';
         }
         CakeLog::write($log, $message);
     }
     $renderer = $config['renderer'];
     if ($renderer !== 'ExceptionRenderer') {
         list($plugin, $renderer) = pluginSplit($renderer, true);
         App::uses($renderer, $plugin . 'Error');
     }
     try {
         $error = new $renderer($exception);
         $error->render();
     } catch (Exception $e) {
         set_error_handler(Configure::read('Error.handler'));
         // Should be using configured ErrorHandler
         Configure::write('Error.trace', false);
         // trace is useless here since it's internal
         $message = sprintf("[%s] %s\n%s\n%s", get_class($e), $e->getMessage(), $e->getTraceAsString(), self::traceDetails());
         trigger_error($message, E_USER_ERROR);
     }
 }
 /**
  * Loads/constructs a helper.  Will return the instance in the registry if it already exists.
  * By setting `$enable` to false you can disable callbacks for a helper.  Alternatively you
  * can set `$settings['enabled'] = false` to disable callbacks.  This alias is provided so that when
  * declaring $helpers arrays you can disable callbacks on helpers.
  *
  * You can alias your helper as an existing helper by setting the 'className' key, i.e.,
  * {{{
  * public $helpers = array(
  *   'Html' => array(
  *     'className' => 'AliasedHtml'
  *   );
  * );
  * }}}
  * All calls to the `Html` helper would use `AliasedHtml` instead.
  *
  * @param string $helper Helper name to load
  * @param array $settings Settings for the helper.
  * @return Helper A helper object, Either the existing loaded helper or a new one.
  * @throws MissingHelperException when the helper could not be found
  */
 public function load($helper, $settings = array())
 {
     if (is_array($settings) && isset($settings['className'])) {
         $alias = $helper;
         $helper = $settings['className'];
     }
     list($plugin, $name) = pluginSplit($helper, true);
     if (!isset($alias)) {
         $alias = $name;
     }
     if (isset($this->_loaded[$alias])) {
         return $this->_loaded[$alias];
     }
     $helperClass = $name . 'Helper';
     App::uses($helperClass, $plugin . 'View/Helper');
     if (!class_exists($helperClass)) {
         throw new MissingHelperException(array('class' => $helperClass, 'plugin' => substr($plugin, 0, -1)));
     }
     $this->_loaded[$alias] = new $helperClass($this->_View, $settings);
     $vars = array('request', 'theme', 'plugin');
     foreach ($vars as $var) {
         $this->_loaded[$alias]->{$var} = $this->_View->{$var};
     }
     $enable = isset($settings['enabled']) ? $settings['enabled'] : true;
     if ($enable) {
         $this->enable($alias);
     }
     return $this->_loaded[$alias];
 }
 /**
  * Loads/constructs a helper.  Will return the instance in the registry if it already exists.
  * By setting `$enable` to false you can disable callbacks for a helper.  Alternatively you 
  * can set `$settings['enabled'] = false` to disable callbacks.  This alias is provided so that when
  * declaring $helpers arrays you can disable callbacks on helpers.
  * 
  * @param string $helper Helper name to load
  * @param array $settings Settings for the helper.
  * @return Helper A helper object, Either the existing loaded helper or a new one.
  * @throws MissingHelperFileException, MissingHelperClassException when the helper could not be found
  */
 public function load($helper, $settings = array())
 {
     list($plugin, $name) = pluginSplit($helper, true);
     if (isset($this->_loaded[$name])) {
         return $this->_loaded[$name];
     }
     $helperClass = $name . 'Helper';
     if (!class_exists($helperClass)) {
         if (!App::import('Helper', $helper)) {
             throw new MissingHelperFileException(array('class' => $helperClass, 'file' => Inflector::underscore($name) . '.php'));
         }
         if (!class_exists($helperClass)) {
             throw new MissingHelperClassException(array('class' => $helperClass, 'file' => Inflector::underscore($name) . '.php'));
         }
     }
     $this->_loaded[$name] = new $helperClass($this->_View, $settings);
     $vars = array('request', 'theme', 'plugin');
     foreach ($vars as $var) {
         $this->_loaded[$name]->{$var} = $this->_View->{$var};
     }
     $enable = isset($settings['enabled']) ? $settings['enabled'] : true;
     if ($enable === true) {
         $this->_enabled[] = $name;
     }
     return $this->_loaded[$name];
 }
Example #9
0
 /**
  * Retrieve an enum list for a Models field and translate the values.
  *
  * @param string $model
  * @param string $field
  * @param mixed $value
  * @param string $domain
  * @return string|array
  */
 public function enum($model, $field, $value = null, $domain = null)
 {
     $enum = ClassRegistry::init($model)->enum($field);
     list($plugin, $model) = pluginSplit($model);
     // Set domain
     if (!$domain) {
         if ($plugin) {
             $domain = Inflector::underscore($plugin);
         } else {
             $domain = 'default';
         }
     }
     // Cache the translations
     $key = Inflector::underscore($model) . '.' . Inflector::underscore($field);
     $cache = $key . '.enum';
     if (isset($this->_cached[$cache])) {
         $enum = $this->_cached[$cache];
     } else {
         foreach ($enum as $k => &$v) {
             $message = __d($domain, $key . '.' . $k);
             // Only use message if a translation exists
             if ($message !== $key . '.' . $k) {
                 $v = $message;
             }
         }
         $this->_cached[$cache] = $enum;
     }
     // Filter down by value
     if ($value !== null) {
         return isset($enum[$value]) ? $enum[$value] : null;
     }
     return $enum;
 }
 /** 
  * Authenticate a user using Linkedin Auth Cookie.
  *
  * @param CakeRequest $request The request to authenticate with.
  * @param CakeResponse $response The response to add headers to.
  * @return mixed Either false on failure, or an array of user data on success.
  */
 public function authenticate(CakeRequest $request, CakeResponse $response)
 {
     if ($user = $this->getUser($request)) {
         $this->access_token = $user->access_token;
         $userModel = $this->settings['userModel'];
         list($plugin, $model) = pluginSplit($userModel);
         $fields = $this->settings['fields'];
         $conditions = array($model . '.' . $fields['username'] => $user->member_id);
         if (!empty($this->settings['scope'])) {
             $conditions = array_merge($conditions, $this->settings['scope']);
         }
         $result = ClassRegistry::init($userModel)->find('first', array('conditions' => $conditions, 'recursive' => 0));
         if (empty($result) || empty($result[$model])) {
             $session_name = $this->settings['session'];
             SessionComponent::write($session_name, $user);
             return false;
         }
         unset($result[$model][$fields['password']]);
         if (isset($result[$model]['linkedin'])) {
             unset($result[$model]['linkedin']);
         }
         $user->id = $result[$model]['_id'];
         $session_name = $this->settings['session'];
         SessionComponent::write($session_name, $user);
         return $result[$model];
     }
     return false;
 }
 public static function get($class)
 {
     list($plugin, $class) = pluginSplit($class, true);
     $class .= 'PaymentProvider';
     App::uses($class, $plugin . 'PaymentProvider');
     return new $class();
 }
Example #12
0
 /**
  * Load Event Handlers during bootstrap.
  *
  * Plugins can add their own custom EventHandler in Config/events.php
  * with the following format:
  *
  * $config = array(
  *     'EventHandlers' => array(
  *         'Example.ExampleEventHandler' => array(
  *             'eventKey' => null,
  *             'options' => array(
  *                 'priority' => 1,
  *                 'passParams' => false,
  *                 'className' => 'Plugin.ClassName',
  *      )));
  *
  * @return void
  */
 public static function loadListeners()
 {
     $eventManager = self::instance();
     $eventHandlers = Configure::read('EventHandlers');
     $validKeys = ['eventKey' => null, 'options' => []];
     if (!empty($eventHandlers) && is_array($eventHandlers)) {
         foreach ($eventHandlers as $eventHandler => $eventOptions) {
             if (is_numeric($eventHandler)) {
                 $eventHandler = $eventOptions;
                 $eventOptions = [];
             }
             list($plugin, $class) = pluginSplit($eventHandler);
             if (!empty($eventOptions)) {
                 extract(array_intersect_key($eventOptions, $validKeys));
             }
             if (isset($eventOptions['options']['className'])) {
                 list($plugin, $class) = pluginSplit($eventOptions['options']['className']);
             }
             $class = App::className($eventHandler, 'Event');
             if (class_exists($class)) {
                 $settings = isset($eventOptions['options']) ? $eventOptions['options'] : [];
                 $listener = new $class($settings);
                 $eventManager->on($listener);
             } else {
                 Log::notice(__d('union', 'EventHandler {0} not found in plugin {1}', $eventHandler, $plugin), 'event');
             }
         }
     }
 }
Example #13
0
 /**
  * Renders the given gizmo.
  *
  * Example:
  *
  * {{{
  * // Taxonomy\View\Gizmo\TagCloudGizmo::smallList()
  * $gizmo = $this->gizmo('Taxonomy.TagCloud::smallList', ['limit' => 10]);
  *
  * // App\View\Gizmo\TagCloudGizmo::smallList()
  * $gizmo = $this->gizmo('TagCloud::smallList', ['limit' => 10]);
  * }}}
  *
  * The `display` action will be used by default when no action is provided:
  *
  * {{{
  * // Taxonomy\View\Gizmo\TagCloudGizmo::display()
  * $gizmo = $this->gizmo('Taxonomy.TagCloud');
  * }}}
  *
  * Gizmos are not rendered until they are echoed.
  *
  * @param string $gizmo You must indicate gizmo name, and optionally a gizmo action. e.g.: `TagCloud::smallList`
  * will invoke `View\Gizmo\TagCloudGizmo::smallList()`, `display` action will be invoked by default when none is provided.
  * @param array $data Additional arguments for gizmo method. e.g.:
  *    `gizmo('TagCloud::smallList', ['a1' => 'v1', 'a2' => 'v2'])` maps to `View\Gizmo\TagCloud::smallList(v1, v2)`
  * @param array $options Options for Gizmo's constructor
  * @return \Cake\View\Gizmo The gizmo instance
  * @throws \Cake\View\Exception\MissingGizmoException If Gizmo class was not found.
  * @throws \BadMethodCallException If Gizmo class does not specified gizmo action.
  */
 public function gizmo($gizmo, array $data = [], array $options = [])
 {
     $parts = explode('::', $gizmo);
     if (count($parts) === 2) {
         list($pluginAndGizmo, $action) = [$parts[0], $parts[1]];
     } else {
         list($pluginAndGizmo, $action) = [$parts[0], 'display'];
     }
     list($plugin, $gizmoName) = pluginSplit($pluginAndGizmo);
     $className = App::className($pluginAndGizmo, 'View/Gizmo', 'Gizmo');
     if (!$className) {
         throw new Exception\MissingGizmoException(array('className' => $pluginAndGizmo . 'Gizmo'));
     }
     $gizmo = $this->_createGizmo($className, $action, $plugin, $options);
     if (!empty($data)) {
         $data = array_values($data);
     }
     try {
         $reflect = new \ReflectionMethod($gizmo, $action);
         $reflect->invokeArgs($gizmo, $data);
         return $gizmo;
     } catch (\ReflectionException $e) {
         throw new \BadMethodCallException(sprintf('Class %s does not have a "%s" method.', $className, $action));
     }
 }
 /**
  * Loads/constructs a component. Will return the instance in the registry if it already exists.
  * You can use `$settings['enabled'] = false` to disable callbacks on a component when loading it.
  * Callbacks default to on. Disabled component methods work as normal, only callbacks are disabled.
  *
  * You can alias your component as an existing component by setting the 'className' key, i.e.,
  * {{{
  * public $components = array(
  *   'Email' => array(
  *     'className' => 'AliasedEmail'
  *   );
  * );
  * }}}
  * All calls to the `Email` component would use `AliasedEmail` instead.
  *
  * @param string $component Component name to load
  * @param array $settings Settings for the component.
  *
  * @return Component A component object, Either the existing loaded component or a new one.
  * @throws MissingComponentException when the component could not be found
  */
 public function load($component, $settings = array())
 {
     if (isset($settings['className'])) {
         $alias = $component;
         $component = $settings['className'];
     }
     list($plugin, $name) = pluginSplit($component, true);
     if (!isset($alias)) {
         $alias = $name;
     }
     if (isset($this->_loaded[$alias])) {
         return $this->_loaded[$alias];
     }
     $componentClass = $name . 'Component';
     App::uses($componentClass, $plugin . 'Controller/Component');
     if (!class_exists($componentClass)) {
         throw new MissingComponentException(array('class' => $componentClass, 'plugin' => substr($plugin, 0, -1)));
     }
     $this->_loaded[$alias] = new $componentClass($this, $settings);
     $enable = isset($settings['enabled']) ? $settings['enabled'] : true;
     if ($enable) {
         $this->enable($alias);
     }
     return $this->_loaded[$alias];
 }
Example #15
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;
 }
 /**
  * Find a user record using the standard options.
  *
  * @param string $username The username/identifier.
  * @param string $password The unhashed password.
  * @return Mixed Either false on failure, or an array of user data.
  */
 protected function _findUser($conditions, $password = null)
 {
     $userModel = $this->settings['userModel'];
     list($plugin, $model) = pluginSplit($userModel);
     $fields = $this->settings['fields'];
     if (!is_array($conditions)) {
         if (!$password) {
             return false;
         }
         $username = $conditions;
         $conditions = array($model . '.' . $fields['username'] => $username);
     }
     if ($this->settings['columns'] && is_array($this->settings['columns'])) {
         $columns = array();
         foreach ($this->settings['columns'] as $column) {
             $columns[] = array($model . '.' . $column => $username);
         }
         $conditions = array('OR' => $columns);
     }
     $conditions = array_merge($conditions, array($model . '.' . $fields['password'] => $this->_password($password)));
     if (!empty($this->settings['scope'])) {
         $conditions = array_merge($conditions, $this->settings['scope']);
     }
     $result = ClassRegistry::init($userModel)->find('first', array('conditions' => $conditions, 'recursive' => 0));
     if (empty($result) || empty($result[$model])) {
         return false;
     }
     unset($result[$model][$fields['password']]);
     return $result[$model];
 }
Example #17
0
 /**
  * Take care of any minifying requests.
  * The import is not defined outside the class to avoid errors if the class is read from the console.
  *
  * @return void
  */
 public function index($type)
 {
     $files = array_unique(explode(',', $_GET['f']));
     $plugins = array();
     $symLinks = array();
     $newFiles = array();
     if (!empty($this->request->base)) {
         $symLinks['/' . $this->request->base] = WWW_ROOT;
     }
     foreach ($files as &$file) {
         if (empty($file)) {
             continue;
         }
         $plugin = false;
         list($first, $second) = pluginSplit($file);
         if (CakePlugin::loaded($first) === true) {
             $file = $second;
             $plugin = $first;
         }
         $pluginPath = !empty($plugin) ? '../Plugin/' . $plugin . '/' . WEBROOT_DIR . '/' : '';
         $file = $pluginPath . $type . '/' . $file . '.' . $type;
         $newFiles[] = $file;
         if (!empty($plugin) && !isset($plugins[$plugin])) {
             $plugins[$plugin] = true;
             $symLinks['/' . $this->request->base . '/' . Inflector::underscore($plugin)] = APP . 'Plugin/' . $plugin . '/' . WEBROOT_DIR . '/';
         }
     }
     $_GET['f'] = implode(',', $newFiles);
     $_GET['symlinks'] = $symLinks;
     App::import('Vendor', 'Minify.minify/index');
     $this->response->statusCode('304');
     exit;
 }
Example #18
0
 /**
  * Create the given shell name, and set the plugin property
  *
  * @param string $className The class name to instanciate
  * @param string $shortName The plugin-prefixed shell name
  * @return \Cake\Console\Shell A shell instance.
  */
 protected function _createShell($className, $shortName)
 {
     list($plugin) = pluginSplit($shortName);
     $instance = PipingBag::get($className);
     $instance->plugin = trim($plugin, '.');
     return $instance;
 }
Example #19
0
 /**
  * PwdShell::hash()
  *
  * @return void
  */
 public function hash()
 {
     $components = array('Tools.AuthExt', 'Auth');
     $class = null;
     foreach ($components as $component) {
         if (App::import('Component', $component)) {
             $component .= 'Component';
             list($plugin, $class) = pluginSplit($component);
             break;
         }
     }
     if (!$class || !method_exists($class, 'password')) {
         return $this->error(__('No Auth Component found'));
     }
     $this->out('Using: ' . $class);
     while (empty($pwToHash) || mb_strlen($pwToHash) < 2) {
         $pwToHash = $this->in(__('Password to Hash (2 characters at least)'));
     }
     if ($authType = Configure::read('Passwordable.authType')) {
         list($plugin, $authType) = pluginSplit($authType, true);
         $className = $authType . 'PasswordHasher';
         App::uses($className, $plugin . 'Controller/Component/Auth');
         $passwordHasher = new $className();
         $pw = $passwordHasher->hash($pwToHash);
     } else {
         $class = new $class(new ComponentCollection());
         $pw = $class->password($pwToHash);
     }
     $this->hr();
     $this->out($pw);
 }
Example #20
0
 /**
  * Loads/constructs an object instance.
  *
  * Will return the instance in the registry if it already exists.
  * If a subclass provides event support, you can use `$config['enabled'] = false`
  * to exclude constructed objects from being registered for events.
  *
  * Using Cake\Controller\Controller::$components as an example. You can alias
  * an object by setting the 'className' key, i.e.,
  *
  * ```
  * public $components = [
  *   'Email' => [
  *     'className' => '\App\Controller\Component\AliasedEmailComponent'
  *   ];
  * ];
  * ```
  *
  * All calls to the `Email` component would use `AliasedEmail` instead.
  *
  * @param string $objectName The name/class of the object to load.
  * @param array $config Additional settings to use when loading the object.
  * @return mixed
  */
 public function load($objectName, $config = [])
 {
     list(, $name) = pluginSplit($objectName);
     $loaded = isset($this->_loaded[$name]);
     if ($loaded && !empty($config)) {
         $this->_checkDuplicate($name, $config);
     }
     if ($loaded) {
         return $this->_loaded[$name];
     }
     if (is_array($config) && isset($config['className'])) {
         $objectName = $config['className'];
     }
     $className = $this->_resolveClassName($objectName);
     if (!$className || is_string($className) && !class_exists($className)) {
         list($plugin, $objectName) = pluginSplit($objectName);
         /** @var ModelMacro $modelMacro */
         $modelMacro = $this->load($objectName, ['className' => '\\Macro\\Macro\\ModelMacro', 'table' => $plugin . '.' . $objectName]);
         if (get_class($modelMacro->getTable()) !== 'Cake\\ORM\\Table') {
             return $modelMacro;
         }
         $this->_throwMissingClassError($objectName, $plugin);
     }
     $instance = $this->_create($className, $name, $config);
     $this->_loaded[$name] = $instance;
     return $instance;
 }
Example #21
0
 /**
  * Override loadTasks() to handle paths
  *
  * @access public
  */
 function loadTasks()
 {
     parent::loadTasks();
     $task = Inflector::classify($this->command);
     if (isset($this->{$task}) && !in_array($task, array('Project', 'DbConfig'))) {
         if (empty($this->{$task}->path)) {
             $path = Inflector::underscore(Inflector::pluralize($this->command));
             $this->{$task}->path = $this->params['working'] . DS . $path . DS;
         }
         if (isset($this->params['connection'])) {
             $this->{$task}->connection = $this->params['connection'];
         }
         foreach ($this->args as $i => $arg) {
             if (strpos($arg, '.')) {
                 list($this->params['plugin'], $this->args[$i]) = pluginSplit($arg);
                 break;
             }
         }
         if (isset($this->params['plugin'])) {
             $this->{$task}->plugin = $this->params['plugin'];
         }
         if (!is_dir($this->{$task}->path)) {
             $this->err(sprintf(__("%s directory could not be found.\nBe sure you have created %s", true), $task, $this->{$task}->path));
             $this->_stop();
         }
     }
 }
 public function onControllerInit(Event $event)
 {
     $controller = $event->subject();
     //Skip Auth for non app controllers. DebugKit For example
     //possible injection hole, but needed.
     if (!in_array('App\\Controller\\AppController', class_parents($controller))) {
         return;
     }
     $controller->loadComponent('Cookie');
     $loginRedirect = '/';
     if (isset($controller->request->params['prefix'])) {
         $loginRedirect .= $controller->request->params['prefix'];
     }
     $controller->loadComponent('Auth', ['loginAction' => ['plugin' => 'Passengers', 'controller' => 'Users', 'action' => 'signin'], 'loginRedirect' => $loginRedirect, 'logoutRedirect' => ['plugin' => 'Passengers', 'controller' => 'Users', 'action' => 'signin'], 'unauthorizedRedirect' => ['plugin' => 'Passengers', 'controller' => 'Users', 'action' => 'signin'], 'authenticate' => [AuthComponent::ALL => ['fields' => ['username' => 'username', 'password' => 'password'], 'userModel' => 'Passengers.Users', 'finder' => 'active'], 'Form', 'Passengers.Cookie']]);
     $authorizeConfig = [];
     if ($authorizers = Configure::read('Passengers.authorizers')) {
         foreach ($authorizers as $key => $authorizer) {
             if (isset($authorizer['className']) && ($plugin = pluginSplit($authorizer['className'])[0])) {
                 if (!Plugin::loaded($plugin)) {
                     continue;
                 }
             }
             $authorizeConfig[$key] = $authorizer;
         }
     }
     $forceAuth = Configure::read('App.force_user_auth');
     if ($forceAuth && empty($authorizeConfig)) {
         $authorizeConfig[] = 'Controller';
     }
     $controller->Auth->config('authorize', array(AuthComponent::ALL => ['actionPath' => 'controllers/']) + $authorizeConfig);
     $this->_setUser($controller);
     $controller->loadComponent('Passengers.AuthUser');
     $controller->viewBuilder()->helpers(['Passengers.AuthUser']);
 }
Example #23
0
 /**
  * Loads/constructs a component.  Will return the instance in the registry if it already exists.
  * You can use `$settings['enabled'] = false` to disable callbacks on a component when loading it.
  * Callbacks default to on.  Disabled component methods work as normal, only callbacks are disabled.
  *
  * You can alias your component as an existing component by setting the 'className' key, i.e.,
  * {{{
  * public $components = array(
  *   'Email' => array(
  *     'className' => 'AliasedEmail'
  *   );
  * );
  * }}}
  * All calls to the `Email` component would use `AliasedEmail` instead.
  * 
  * @param string $component Component name to load
  * @param array $settings Settings for the component.
  * @return Component A component object, Either the existing loaded component or a new one.
  * @throws MissingComponentFileException, MissingComponentClassException when the component could not be found
  */
 public function load($component, $settings = array())
 {
     if (is_array($settings) && isset($settings['className'])) {
         $alias = $component;
         $component = $settings['className'];
     }
     list($plugin, $name) = pluginSplit($component, true);
     if (!isset($alias)) {
         $alias = $name;
     }
     if (isset($this->_loaded[$alias])) {
         return $this->_loaded[$alias];
     }
     $componentClass = $name . 'Component';
     App::uses($componentClass, $plugin . 'Controller/Component');
     if (!class_exists($componentClass)) {
         throw new MissingComponentClassException(array('file' => Inflector::underscore($componentClass) . '.php', 'class' => $componentClass));
     }
     $this->_loaded[$alias] = new $componentClass($this, $settings);
     $enable = isset($settings['enabled']) ? $settings['enabled'] : true;
     if ($enable === true) {
         $this->_enabled[] = $alias;
     }
     return $this->_loaded[$alias];
 }
 /**
  * Find a user record using the standard options.
  *
  * @param string $username The username/identifier.
  * @param string $password The password, if not provide password checking is
  *   skipped and result of find is returned.
  * @return bool|array Either false on failure, or an array of user data.
  */
 protected function _findUser($username, $password = null)
 {
     $userModel = $this->_config['userModel'];
     list($plugin, $model) = pluginSplit($userModel);
     $fields = $this->_config['fields'];
     $conditions = [$model . '.' . $fields['username'] => $username];
     $columns = [];
     foreach ($this->_config['columns'] as $column) {
         $columns[] = [$model . '.' . $column => $username];
     }
     $conditions = ['OR' => $columns];
     if (!empty($this->_config['scope'])) {
         $conditions = array_merge($conditions, $this->_config['scope']);
     }
     $table = TableRegistry::get($userModel)->find('all');
     if ($this->_config['contain']) {
         $table = $table->contain($this->_config['contain']);
     }
     $result = $table->where($conditions)->hydrate(false)->first();
     if (empty($result)) {
         return false;
     }
     if ($password !== null) {
         $hasher = $this->passwordHasher();
         $hashedPassword = $result[$fields['password']];
         if (!$hasher->check($password, $hashedPassword)) {
             return false;
         }
         $this->_needsPasswordRehash = $hasher->needsRehash($hashedPassword);
         unset($result[$fields['password']]);
     }
     return $result;
 }
Example #25
0
 /**
  * Return list of events this behavior is interested in.
  *
  * @return array
  * @throws \InvalidArgumentException When events are configured in an invalid format.
  */
 public function implementedEvents()
 {
     $events = [];
     if ($this->config('events') === false) {
         return $events;
     }
     foreach ((array) $this->config('events') as $eventKey => $event) {
         if (is_numeric($eventKey)) {
             $eventKey = $event;
             $event = null;
         }
         if ($event === null || is_string($event)) {
             $event = ['callable' => $event];
         }
         if (!is_array($event)) {
             throw new \InvalidArgumentException('Event should be string or array');
         }
         $priority = $this->config('priority');
         if (!array_key_exists('callable', $event) || $event['callable'] === null) {
             list(, $event['callable']) = pluginSplit($eventKey);
         }
         if ($priority && !array_key_exists('priority', $event)) {
             $event['priority'] = $priority;
         }
         $events[$eventKey] = $event;
     }
     return $events;
 }
 public static function get($class)
 {
     list($plugin, $class) = pluginSplit($class, true);
     $class .= 'AccessProvider';
     App::uses($class, $plugin . 'CustomerAccessProvider');
     return new $class();
 }
Example #27
0
 /**
  * Renders the given cell.
  *
  * Example:
  *
  * ```
  * // Taxonomy\View\Cell\TagCloudCell::smallList()
  * $cell = $this->cell('Taxonomy.TagCloud::smallList', ['limit' => 10]);
  *
  * // App\View\Cell\TagCloudCell::smallList()
  * $cell = $this->cell('TagCloud::smallList', ['limit' => 10]);
  * ```
  *
  * The `display` action will be used by default when no action is provided:
  *
  * ```
  * // Taxonomy\View\Cell\TagCloudCell::display()
  * $cell = $this->cell('Taxonomy.TagCloud');
  * ```
  *
  * Cells are not rendered until they are echoed.
  *
  * @param string $cell You must indicate cell name, and optionally a cell action. e.g.: `TagCloud::smallList`
  * will invoke `View\Cell\TagCloudCell::smallList()`, `display` action will be invoked by default when none is provided.
  * @param array $data Additional arguments for cell method. e.g.:
  *    `cell('TagCloud::smallList', ['a1' => 'v1', 'a2' => 'v2'])` maps to `View\Cell\TagCloud::smallList(v1, v2)`
  * @param array $options Options for Cell's constructor
  * @return \Cake\View\Cell The cell instance
  * @throws \Cake\View\Exception\MissingCellException If Cell class was not found.
  * @throws \BadMethodCallException If Cell class does not specified cell action.
  */
 public function cell($cell, array $data = [], array $options = [])
 {
     $parts = explode('::', $cell);
     if (count($parts) === 2) {
         list($pluginAndCell, $action) = [$parts[0], $parts[1]];
     } else {
         list($pluginAndCell, $action) = [$parts[0], 'display'];
     }
     list($plugin) = pluginSplit($pluginAndCell);
     $className = App::className($pluginAndCell, 'View/Cell', 'Cell');
     if (!$className) {
         throw new Exception\MissingCellException(['className' => $pluginAndCell . 'Cell']);
     }
     $cell = $this->_createCell($className, $action, $plugin, $options);
     if (!empty($data)) {
         $data = array_values($data);
     }
     try {
         $reflect = new ReflectionMethod($cell, $action);
         $reflect->invokeArgs($cell, $data);
         return $cell;
     } catch (ReflectionException $e) {
         throw new BadMethodCallException(sprintf('Class %s does not have a "%s" method.', $className, $action));
     }
 }
Example #28
0
 /**
  * Sets up various vars/classes required
  *
  * @return null
  * @access public
  */
 function __construct($settings = array())
 {
     $sessionKey = 'Auth';
     if (is_array($settings) && isset($settings[0])) {
         $sessionKey = $settings[0];
     } elseif (is_string($settings)) {
         $sessionKey = $settings;
     }
     $this->sessionKey = $sessionKey;
     $this->userModel = 'User';
     $user = ClassRegistry::init('User');
     $this->userModelPrimary = $user->primaryKey;
     $name = Inflector::camelize(strtolower(Configure::read('Acl.classname')));
     if (!class_exists($name)) {
         if (App::import('Component', $name)) {
             list($plugin, $name) = pluginSplit($name);
             $name .= 'Component';
         } else {
             trigger_error(sprintf(__('Could not find %s.', true), $name), E_USER_WARNING);
         }
     }
     $this->_Instance =& new $name();
     $this->_Instance->initialize($this);
     parent::__construct();
 }
 public static function mapResources($controller = array(), $options = array())
 {
     $hasPrefix = isset($options['prefix']);
     $options = array_merge(array('prefix' => '/', 'id' => self::ID . '|' . self::UUID), $options);
     $prefix = $options['prefix'];
     foreach ((array) $controller as $name) {
         list($plugin, $name) = pluginSplit($name);
         $urlName = Inflector::underscore($name);
         $plugin = Inflector::underscore($plugin);
         if ($plugin && !$hasPrefix) {
             $prefix = '/' . $plugin . '/';
         }
         foreach (self::$_resourceMap as $params) {
             if ($params['action'] === 'count') {
                 $url = $prefix . $urlName . '/count';
             } else {
                 $url = $prefix . $urlName . ($params['id'] ? '/:id' : '');
             }
             if (!empty($options['controllerClass'])) {
                 $controller = $options['controllerClass'];
             } else {
                 $controller = $urlName;
             }
             Router::connect($url, array('plugin' => $plugin, 'controller' => $controller, 'action' => $params['action'], '[method]' => $params['method']), array('id' => $options['id'], 'pass' => array('id')));
         }
         self::$_resourceMapped[] = $urlName;
     }
     return self::$_resourceMapped;
 }
 public function getUser(Request $request)
 {
     if (!isset($_SESSION)) {
         return false;
     }
     $provider = Hash::get($_SESSION, 'opauth.auth.provider');
     if (!$provider) {
         return false;
     }
     $uid = Hash::get($_SESSION, 'opauth.auth.uid');
     if (!$uid) {
         return false;
     }
     $userModel = $this->_config['userModel'];
     list(, $model) = pluginSplit($userModel);
     $fields = $this->_config['fields'];
     $conditions = [$model . '.' . $fields['auth_provider'] => $provider, $model . '.' . $fields['auth_uid'] => $uid];
     $scope = $this->_config['scope'];
     if ($scope) {
         $conditions = array_merge($conditions, $scope);
     }
     $table = TableRegistry::get($userModel)->find('all');
     $contain = $this->_config['contain'];
     if ($contain) {
         $table = $table->contain($contain);
     }
     $result = $table->where($conditions)->hydrate(false)->first();
     if (empty($result)) {
         return false;
     }
     return $result;
 }