Ejemplo n.º 1
0
 public function getPluginControllerName($ctrlName = null)
 {
     $arr = String::tokenize($ctrlName, '/');
     if (count($arr) == 2) {
         return $arr[1];
     } else {
         return false;
     }
 }
Ejemplo n.º 2
0
 /**
  * Main execution function to indent a folder recursivly
  *
  * @return int|null
  */
 public function folder()
 {
     if (!empty($this->params['extensions'])) {
         $this->settings['files'] = String::tokenize($this->params['extensions']);
     }
     if (!empty($this->params['again'])) {
         $this->settings['againWithHalf'] = true;
     }
     if (!empty($this->args)) {
         if (!empty($this->args[0]) && $this->args[0] !== 'app') {
             $folder = $this->args[0];
             if ($folder === '/') {
                 $folder = APP;
             }
             $folder = realpath($folder);
             if (!file_exists($folder)) {
                 return $this->error('folder not exists: ' . $folder . '');
             }
             $this->_paths[] = $folder;
         } elseif ($this->args[0] === 'app') {
             $this->_paths[] = APP;
         }
         if (!empty($this->params['files'])) {
             $this->settings['files'] = explode(',', $this->params['files']);
         }
         $this->out($folder);
         $this->out('searching...');
         $this->_searchFiles();
         $this->out('found: ' . count($this->_files));
         if (!empty($this->params['dry-run'])) {
             $this->out('TEST DONE');
         } else {
             $continue = $this->in('Modifying files! Continue?', ['y', 'n'], 'n');
             if (strtolower($continue) !== 'y' && strtolower($continue) !== 'yes') {
                 return $this->error('...aborted');
             }
             $this->_correctFiles();
             $this->out('DONE');
         }
     } else {
         $this->out('Usage: cake intend folder');
         $this->out('"folder" is then intended recursivly');
         $this->out('default file types are');
         $this->out('[' . implode(', ', $this->settings['files']) . ']');
         $this->out('');
         $this->out('Specify file types manually:');
         $this->out('-files php,js,css');
     }
 }
Ejemplo n.º 3
0
 /**
  * Admin Index
  *
  * @access public
  */
 function admin_index()
 {
     // Carrega Model
     $this->loadModel($this->AclCaching->getAroModel());
     // Seleciona todos os grupos de usuários
     $roles = $this->{$this->AclCaching->getAroModel()}->find('all', array('order' => array(sprintf('%s.%s', $this->AclCaching->getAroModel(), $this->AclCaching->getAroDisplayField()) => 'ASC')));
     // Seleciona todas as actions do sistema
     $actions = $this->AclCaching->get_all_actions();
     /**
      * Carrega as permissões
      */
     $permissions = array();
     $methods = array();
     foreach ($actions as $full_action) {
         $url = String::tokenize($full_action, '/');
         if (count($url) == 2) {
             $plugin_name = null;
             $controller_name = $url[0];
             $action = $url[1];
         } elseif (count($url) == 3) {
             $plugin_name = $url[0];
             $controller_name = $url[1];
             $action = $url[2];
         }
         foreach ($roles as $role) {
             $aro_node = $this->AclCaching->Aro->node($role);
             if (!empty($aro_node)) {
                 $aco_node = $this->AclCaching->Aco->node($full_action);
                 if (!empty($aco_node)) {
                     $authorized = $this->AclCaching->checkDB($role, $full_action);
                     $permissions[$role[$this->AclCaching->getAroModel()][$this->AclCaching->getAroPrimaryKey()]] = $authorized ? 1 : 0;
                 }
             } else {
                 /*
                  * Não conseguiu verificar a permissão
                  */
                 $permissions[$role[$this->AclCaching->getAroModel()][$this->AclCaching->getAroPrimaryKey()]] = -1;
             }
         }
         if (isset($plugin_name)) {
             $methods['plugin'][$plugin_name][$controller_name][] = array('name' => $action, 'permissions' => $permissions);
         } else {
             $methods['app'][$controller_name][] = array('name' => $action, 'permissions' => $permissions);
         }
     }
     // Envia variáveis para a View
     $this->set(compact(array('roles', 'methods')));
 }
Ejemplo n.º 4
0
 public static function extract(array $data, $path)
 {
     if (empty($path)) {
         return $data;
     }
     // Simple paths.
     if (!preg_match('/[{\\[]/', $path)) {
         return (array) self::get($data, $path);
     }
     if (strpos($path, '[') === false) {
         $tokens = explode('.', $path);
     } else {
         $tokens = String::tokenize($path, '.', '[', ']');
     }
     $_key = '__set_item__';
     $context = array($_key => array($data));
     foreach ($tokens as $token) {
         $next = array();
         $conditions = false;
         $position = strpos($token, '[');
         if ($position !== false) {
             $conditions = substr($token, $position);
             $token = substr($token, 0, $position);
         }
         foreach ($context[$_key] as $item) {
             foreach ((array) $item as $k => $v) {
                 if (self::_matchToken($k, $token)) {
                     $next[] = $v;
                 }
             }
         }
         // Filter for attributes.
         if ($conditions) {
             $filter = array();
             foreach ($next as $item) {
                 if (is_array($item) && self::_matches($item, $conditions)) {
                     $filter[] = $item;
                 }
             }
             $next = $filter;
         }
         $context = array($_key => $next);
     }
     return $context[$_key];
 }
 function acoslist()
 {
     $roles = $this->Role->find('all', array('order' => 'name', 'contain' => false, 'recursive' => -1));
     $actions = $this->AclReflector->get_all_actions();
     $permissions = array();
     $methods = array();
     foreach ($actions as $full_action) {
         $arr = String::tokenize($full_action, '/');
         if (count($arr) == 2) {
             $plugin_name = null;
             $controller_name = $arr[0];
             $action = $arr[1];
         } elseif (count($arr) == 3) {
             $plugin_name = $arr[0];
             $controller_name = $arr[1];
             $action = $arr[2];
         }
         foreach ($roles as $role) {
             $aro_node = $this->Acl->Aro->node($role);
             if (!empty($aro_node)) {
                 $aco_node = $this->Acl->Aco->node($full_action);
                 if (!empty($aco_node)) {
                     $authorized = $this->Acl->check($role, $full_action);
                     $permissions[$role['Role']['id']] = $authorized ? 1 : 0;
                 }
             } else {
                 /*
                  * No check could be done as the ARO is missing
                  */
                 $permissions[$role['Role']['id']] = -1;
             }
         }
         if (isset($plugin_name)) {
             $methods['plugin'][$plugin_name][$controller_name][] = array('name' => $action, 'permissions' => $permissions);
         } else {
             $methods['app'][$controller_name][] = array('name' => $action, 'permissions' => $permissions);
         }
     }
     $this->set('roles', $roles);
     $this->set('actions', $methods);
 }
Ejemplo n.º 6
0
 function saveSection($data)
 {
     $this->set($data);
     $success = false;
     if ($success = $this->validates()) {
         $tokens = String::tokenize($data[$this->name]['match_route']);
         foreach ($tokens as $token) {
             // There are three different cases
             // 1- :param => value
             // 2- pass => array('value1', 'value2')
             // 3- named => array('param1' => 'value1', 'param2' => 'value2')
             switch (true) {
                 // Case 1 - :param => value
                 case count($param = explode('=>', $token)) > 1:
                     $param = MenuItemRoute::cleanParam($param);
                     MenuItemRoute::getInstance()->route[$param['name']] = $param['value'];
                     break;
                     // Case 2 - named => array('param1' => 'value1', 'param2' => 'value2', ...)
                 // Case 2 - named => array('param1' => 'value1', 'param2' => 'value2', ...)
                 case count($param = explode(':', $token)) > 1:
                     $param = MenuItemRoute::cleanParam($param);
                     MenuItemRoute::getInstance()->route[] = $param['name'] . ':' . $param['value'];
                     break;
                     // Case 3 - pass => array('value1', 'value2', ...)
                 // Case 3 - pass => array('value1', 'value2', ...)
                 default:
                     $param = MenuItemRoute::cleanParam($token);
                     MenuItemRoute::getInstance()->route[] = $param;
                     break;
             }
         }
         $this->data[$this->name]['match_route'] = serialize(MenuItemRoute::getInstance());
         $succes = $this->save(null, false);
     }
     return $success;
 }
Ejemplo n.º 7
0
 /**
  * Generates the fields list of an SQL query.
  *
  * @param Model $model
  * @param string $alias Alias tablename
  * @param mixed $fields
  * @param boolean $quote If false, returns fields array unquoted
  * @return array
  */
 public function fields(&$model, $alias = null, $fields = array(), $quote = true)
 {
     if (empty($alias)) {
         $alias = $model->alias;
     }
     if (empty($fields)) {
         $fields = array_keys($model->schema());
     } elseif (!is_array($fields)) {
         $fields = String::tokenize($fields);
     }
     $fields = array_values(array_filter($fields));
     if (!$quote) {
         return $fields;
     }
     $count = count($fields);
     if ($count >= 1 && !in_array($fields[0], array('*', 'COUNT(*)'))) {
         for ($i = 0; $i < $count; $i++) {
             if (preg_match('/^\\(.*\\)\\s' . $this->alias . '.*/i', $fields[$i])) {
                 continue;
             } elseif (!preg_match('/^.+\\(.*\\)/', $fields[$i])) {
                 $prepend = '';
                 if (strpos($fields[$i], 'DISTINCT') !== false) {
                     $prepend = 'DISTINCT ';
                     $fields[$i] = trim(str_replace('DISTINCT', '', $fields[$i]));
                 }
                 $dot = strpos($fields[$i], '.');
                 if ($dot === false) {
                     $prefix = !(strpos($fields[$i], ' ') !== false || strpos($fields[$i], '(') !== false);
                     $fields[$i] = $this->name(($prefix ? $alias . '.' : '') . $fields[$i]);
                 } else {
                     $value = array();
                     $comma = strpos($fields[$i], ',');
                     if ($comma === false) {
                         $build = explode('.', $fields[$i]);
                         if (!Set::numeric($build)) {
                             $fields[$i] = $this->name($build[0] . '.' . $build[1]);
                         }
                         $comma = String::tokenize($fields[$i]);
                         foreach ($comma as $string) {
                             if (preg_match('/^[0-9]+\\.[0-9]+$/', $string)) {
                                 $value[] = $string;
                             } else {
                                 $build = explode('.', $string);
                                 $value[] = $this->name(trim($build[0]) . '.' . trim($build[1]));
                             }
                         }
                         $fields[$i] = implode(', ', $value);
                     }
                 }
                 $fields[$i] = $prepend . $fields[$i];
             } elseif (preg_match('/\\(([\\.\\w]+)\\)/', $fields[$i], $field)) {
                 if (isset($field[1])) {
                     if (strpos($field[1], '.') === false) {
                         $field[1] = $this->name($alias . '.' . $field[1]);
                     } else {
                         $field[0] = explode('.', $field[1]);
                         if (!Set::numeric($field[0])) {
                             $field[0] = implode('.', array_map(array($this, 'name'), $field[0]));
                             $fields[$i] = preg_replace('/\\(' . $field[1] . '\\)/', '(' . $field[0] . ')', $fields[$i], 1);
                         }
                     }
                 }
             }
         }
     }
     return array_unique($fields);
 }
Ejemplo n.º 8
0
 function extractPath($data, $path = null)
 {
     if (empty($path)) {
         return $data;
     }
     if (is_object($data)) {
         $data = get_object_vars($data);
     }
     if (!is_array($path)) {
         if (!class_exists('String')) {
             App::import('Core', 'String');
         }
         $parts = String::tokenize($path, '.', '{', '}');
     } else {
         $parts = $path;
     }
     if (!is_array($data)) {
         return array();
     }
     $tmp = array();
     if (empty($parts) || !is_array($parts)) {
         return array();
     }
     $key = reset($parts);
     $tmpPath = array_slice($parts, 1);
     if (is_numeric($key) && intval($key) > 0 || $key === '0') {
         if (isset($data[intval($key)])) {
             $tmp[intval($key)] = $data[intval($key)];
         } else {
             return array();
         }
     } elseif ($key === '{n}') {
         foreach ($data as $j => $val) {
             if (is_int($j)) {
                 $tmp[$j] = $val;
             }
         }
     } elseif ($key === '{s}') {
         foreach ($data as $j => $val) {
             if (is_string($j)) {
                 $tmp[$j] = $val;
             }
         }
     } elseif (false !== strpos($key, '{') && false !== strpos($key, '}')) {
         $pattern = substr($key, 1, -1);
         foreach ($data as $j => $val) {
             if (preg_match('/^' . $pattern . '/s', $j) !== 0) {
                 $tmp[$j] = $val;
             }
         }
     } else {
         if (isset($data[$key])) {
             $tmp[$key] = $data[$key];
         } else {
             return array();
         }
     }
     $res = array();
     if (!empty($tmpPath)) {
         foreach ($tmp as $key => $val) {
             $res2 = Migration::extractPath($val, $tmpPath);
             foreach ($res2 as $key2 => $val2) {
                 $res[$key . '.' . $key2] = $val2;
             }
         }
     } else {
         return $tmp;
     }
     return $res;
 }
Ejemplo n.º 9
0
 /**
  * Form AND/OR query array using String::tokenize to separate
  * search terms by or/and connectors.
  *
  * @param mixed $value
  * @param array $field
  * @param string $fieldName
  * @return array Conditions
  */
 protected function _connectedLike($value, $field, $fieldName, $likeMethod = 'LIKE')
 {
     $or = array();
     $orValues = String::tokenize($value, $field['connectorOr']);
     foreach ($orValues as $orValue) {
         $andValues = String::tokenize($orValue, $field['connectorAnd']);
         $and = array();
         foreach ($andValues as $andValue) {
             $and[] = array($fieldName . " " . $likeMethod => $field['before'] . $andValue . $field['after']);
         }
         $or[] = array('AND' => $and);
     }
     return array('OR' => $or);
 }
Ejemplo n.º 10
0
 /**
  * Insert $values into an array with the given $path. You can use
  * `{n}` and `{s}` elements to insert $data multiple times.
  *
  * @param array $data The data to insert into.
  * @param string $path The path to insert at.
  * @param array $values The values to insert.
  * @return array The data with $values inserted.
  */
 public static function insert(array $data, $path, $values = null)
 {
     if (strpos($path, '[') === false) {
         $tokens = explode('.', $path);
     } else {
         $tokens = String::tokenize($path, '.', '[', ']');
     }
     if (strpos($path, '{') === false && strpos($path, '[') === false) {
         return self::_simpleOp('insert', $data, $tokens, $values);
     }
     $token = array_shift($tokens);
     $nextPath = implode('.', $tokens);
     list($token, $conditions) = self::_splitConditions($token);
     foreach ($data as $k => $v) {
         if (self::_matchToken($k, $token)) {
             if ($conditions && self::_matches($v, $conditions)) {
                 $data[$k] = array_merge($v, $values);
                 continue;
             }
             if (!$conditions) {
                 $data[$k] = self::insert($v, $nextPath, $values);
             }
         }
     }
     return $data;
 }
Ejemplo n.º 11
0
 /**
  * Generates the fields list of an SQL query.
  *
  * @param Model $model
  * @param string $alias Alias tablename
  * @param mixed $fields
  * @param boolean $quote If false, returns fields array unquoted
  * @return array
  * @access public
  */
 function fields(&$model, $alias = null, $fields = array(), $quote = true)
 {
     if (empty($alias)) {
         $alias = $model->alias;
     }
     $cacheKey = array($model->useDbConfig, $model->table, array_keys($model->schema()), $model->name, $model->getVirtualField(), $alias, $fields, $quote);
     $cacheKey = crc32(serialize($cacheKey));
     if ($return = $this->cacheMethod(__FUNCTION__, $cacheKey)) {
         return $return;
     }
     $allFields = empty($fields);
     if ($allFields) {
         $fields = array_keys($model->schema());
     } elseif (!is_array($fields)) {
         $fields = String::tokenize($fields);
     }
     $fields = array_values(array_filter($fields));
     $allFields = $allFields || in_array('*', $fields) || in_array($model->alias . '.*', $fields);
     $virtual = array();
     $virtualFields = $model->getVirtualField();
     if (!empty($virtualFields)) {
         $virtualKeys = array_keys($virtualFields);
         foreach ($virtualKeys as $field) {
             $virtualKeys[] = $model->alias . '.' . $field;
         }
         $virtual = $allFields ? $virtualKeys : array_intersect($virtualKeys, $fields);
         foreach ($virtual as $i => $field) {
             if (strpos($field, '.') !== false) {
                 $virtual[$i] = str_replace($model->alias . '.', '', $field);
             }
             $fields = array_diff($fields, array($field));
         }
         $fields = array_values($fields);
     }
     if (!$quote) {
         if (!empty($virtual)) {
             $fields = array_merge($fields, $this->_constructVirtualFields($model, $alias, $virtual));
         }
         return $fields;
     }
     $count = count($fields);
     if ($count >= 1 && !in_array($fields[0], array('*', 'COUNT(*)'))) {
         for ($i = 0; $i < $count; $i++) {
             if (is_string($fields[$i]) && in_array($fields[$i], $virtual)) {
                 unset($fields[$i]);
                 continue;
             }
             if (is_object($fields[$i]) && isset($fields[$i]->type) && $fields[$i]->type === 'expression') {
                 $fields[$i] = $fields[$i]->value;
             } elseif (preg_match('/^\\(.*\\)\\s' . $this->alias . '.*/i', $fields[$i])) {
                 continue;
             } elseif (!preg_match('/^.+\\(.*\\)/', $fields[$i])) {
                 $prepend = '';
                 if (strpos($fields[$i], 'DISTINCT') !== false) {
                     $prepend = 'DISTINCT ';
                     $fields[$i] = trim(str_replace('DISTINCT', '', $fields[$i]));
                 }
                 $dot = strpos($fields[$i], '.');
                 if ($dot === false) {
                     $prefix = !(strpos($fields[$i], ' ') !== false || strpos($fields[$i], '(') !== false);
                     $fields[$i] = $this->name(($prefix ? $alias . '.' : '') . $fields[$i]);
                 } else {
                     $value = array();
                     $comma = strpos($fields[$i], ',');
                     if ($comma === false) {
                         $build = explode('.', $fields[$i]);
                         if (!Set::numeric($build)) {
                             $fields[$i] = $this->name(implode('.', $build));
                         }
                     }
                 }
                 $fields[$i] = $prepend . $fields[$i];
             } elseif (preg_match('/\\(([\\.\\w]+)\\)/', $fields[$i], $field)) {
                 if (isset($field[1])) {
                     if (strpos($field[1], '.') === false) {
                         $field[1] = $this->name($alias . '.' . $field[1]);
                     } else {
                         $field[0] = explode('.', $field[1]);
                         if (!Set::numeric($field[0])) {
                             $field[0] = implode('.', array_map(array(&$this, 'name'), $field[0]));
                             $fields[$i] = preg_replace('/\\(' . $field[1] . '\\)/', '(' . $field[0] . ')', $fields[$i], 1);
                         }
                     }
                 }
             }
         }
     }
     if (!empty($virtual)) {
         $fields = array_merge($fields, $this->_constructVirtualFields($model, $alias, $virtual));
     }
     return $this->cacheMethod(__FUNCTION__, $cacheKey, array_unique($fields));
 }
Ejemplo n.º 12
0
 /**
  * testTokenize method
  *
  * @return void
  */
 public function testTokenize()
 {
     $result = String::tokenize('A,(short,boring test)');
     $expected = array('A', '(short,boring test)');
     $this->assertEquals($expected, $result);
     $result = String::tokenize('A,(short,more interesting( test)');
     $expected = array('A', '(short,more interesting( test)');
     $this->assertEquals($expected, $result);
     $result = String::tokenize('A,(short,very interesting( test))');
     $expected = array('A', '(short,very interesting( test))');
     $this->assertEquals($expected, $result);
     $result = String::tokenize('"single tag"', ' ', '"', '"');
     $expected = array('"single tag"');
     $this->assertEquals($expected, $result);
     $result = String::tokenize('tagA "single tag" tagB', ' ', '"', '"');
     $expected = array('tagA', '"single tag"', 'tagB');
     $this->assertEquals($expected, $result);
 }
Ejemplo n.º 13
0
 /**
  * Gets a value from an array or object that is contained in a given path using an array path syntax, i.e.:
  * "{n}.Person.{[a-z]+}" - Where "{n}" represents a numeric key, "Person" represents a string literal,
  * and "{[a-z]+}" (i.e. any string literal enclosed in brackets besides {n} and {s}) is interpreted as
  * a regular expression.
  *
  * @param array $data Array from where to extract
  * @param mixed $path As an array, or as a dot-separated string.
  * @return array Extracted data
  * @access public
  * @static
  */
 function classicExtract($data, $path = null)
 {
     if (empty($path)) {
         return $data;
     }
     if (is_object($data)) {
         $data = get_object_vars($data);
     }
     if (!is_array($data)) {
         return $data;
     }
     if (!is_array($path)) {
         if (!class_exists('String')) {
             App::import('Core', 'String');
         }
         $path = String::tokenize($path, '.', '{', '}');
     }
     $tmp = array();
     if (!is_array($path) || empty($path)) {
         return null;
     }
     foreach ($path as $i => $key) {
         if (is_numeric($key) && intval($key) > 0 || $key === '0') {
             if (isset($data[intval($key)])) {
                 $data = $data[intval($key)];
             } else {
                 return null;
             }
         } elseif ($key === '{n}') {
             foreach ($data as $j => $val) {
                 if (is_int($j)) {
                     $tmpPath = array_slice($path, $i + 1);
                     if (empty($tmpPath)) {
                         $tmp[] = $val;
                     } else {
                         $tmp[] = Set::classicExtract($val, $tmpPath);
                     }
                 }
             }
             return $tmp;
         } elseif ($key === '{s}') {
             foreach ($data as $j => $val) {
                 if (is_string($j)) {
                     $tmpPath = array_slice($path, $i + 1);
                     if (empty($tmpPath)) {
                         $tmp[] = $val;
                     } else {
                         $tmp[] = Set::classicExtract($val, $tmpPath);
                     }
                 }
             }
             return $tmp;
         } elseif (false !== strpos($key, '{') && false !== strpos($key, '}')) {
             $pattern = substr($key, 1, -1);
             foreach ($data as $j => $val) {
                 if (preg_match('/^' . $pattern . '/s', $j) !== 0) {
                     $tmpPath = array_slice($path, $i + 1);
                     if (empty($tmpPath)) {
                         $tmp[$j] = $val;
                     } else {
                         $tmp[$j] = Set::classicExtract($val, $tmpPath);
                     }
                 }
             }
             return $tmp;
         } else {
             if (isset($data[$key])) {
                 $data = $data[$key];
             } else {
                 return null;
             }
         }
     }
     return $data;
 }
Ejemplo n.º 14
0
 /**
  * beforeFind Callback
  *
  * @param Model $Model Model find is being run on.
  * @param array $query Array of Query parameters.
  * @return array Modified query
  */
 public function beforeFind(Model $Model, $query)
 {
     $this->runtime[$Model->alias]['virtualFields'] = $Model->virtualFields;
     $locale = $this->_getLocale($Model);
     if (empty($locale)) {
         return $query;
     }
     $db = $Model->getDataSource();
     $RuntimeModel = $this->translateModel($Model);
     if (!empty($RuntimeModel->tablePrefix)) {
         $tablePrefix = $RuntimeModel->tablePrefix;
     } else {
         $tablePrefix = $db->config['prefix'];
     }
     $joinTable = new StdClass();
     $joinTable->tablePrefix = $tablePrefix;
     $joinTable->table = $RuntimeModel->table;
     $joinTable->schemaName = $RuntimeModel->getDataSource()->getSchemaName();
     $this->_joinTable = $joinTable;
     $this->_runtimeModel = $RuntimeModel;
     if (is_string($query['fields']) && $query['fields'] === "COUNT(*) AS {$db->name('count')}") {
         $query['fields'] = "COUNT(DISTINCT({$db->name($Model->escapeField())})) {$db->alias}count";
         $query['joins'][] = array('type' => 'INNER', 'alias' => $RuntimeModel->alias, 'table' => $joinTable, 'conditions' => array($Model->escapeField() => $db->identifier($RuntimeModel->escapeField('foreign_key')), $RuntimeModel->escapeField('model') => $Model->name, $RuntimeModel->escapeField('locale') => $locale));
         $conditionFields = $this->_checkConditions($Model, $query);
         foreach ($conditionFields as $field) {
             $query = $this->_addJoin($Model, $query, $field, $field, $locale);
         }
         unset($this->_joinTable, $this->_runtimeModel);
         return $query;
     } elseif (is_string($query['fields'])) {
         $query['fields'] = String::tokenize($query['fields']);
     }
     $fields = array_merge($this->settings[$Model->alias], $this->runtime[$Model->alias]['fields']);
     $addFields = array();
     if (empty($query['fields'])) {
         $addFields = $fields;
     } elseif (is_array($query['fields'])) {
         $isAllFields = in_array($Model->alias . '.' . '*', $query['fields']) || in_array($Model->escapeField('*'), $query['fields']);
         foreach ($fields as $key => $value) {
             $field = is_numeric($key) ? $value : $key;
             if ($isAllFields || in_array($Model->alias . '.' . $field, $query['fields']) || in_array($field, $query['fields'])) {
                 $addFields[] = $field;
             }
         }
     }
     $this->runtime[$Model->alias]['virtualFields'] = $Model->virtualFields;
     if ($addFields) {
         foreach ($addFields as $_f => $field) {
             $aliasField = is_numeric($_f) ? $field : $_f;
             foreach (array($aliasField, $Model->alias . '.' . $aliasField) as $_field) {
                 $key = array_search($_field, (array) $query['fields']);
                 if ($key !== false) {
                     unset($query['fields'][$key]);
                 }
             }
             $query = $this->_addJoin($Model, $query, $field, $aliasField, $locale);
         }
     }
     $this->runtime[$Model->alias]['beforeFind'] = $addFields;
     unset($this->_joinTable, $this->_runtimeModel);
     return $query;
 }
Ejemplo n.º 15
0
 private function __parseEventName($eventName)
 {
     App::import('Core', 'String');
     $eventTokens = String::tokenize($eventName, '.');
     $scope = 'Global';
     $event = $eventTokens[0];
     if (count($eventTokens) > 1) {
         list($scope, $event) = $eventTokens;
     }
     return compact('scope', 'event');
 }
Ejemplo n.º 16
0
 /**
  * takes list of items and transforms it into an array
  * + cleaning (trim, no empty parts, etc)
  * @param string $string containing the parts
  * @param string $separator (defaults to ',')
  * @param boolean $camelize (true/false): problems with äöüß etc!
  *
  * @return array $results as array list
  * @static
  * //TODO: 3.4. parameter as array, move to Lib
  * 2009-08-13 ms
  */
 public function parseList($string, $separator = null, $camelize = false, $capitalize = true)
 {
     if (empty($separator)) {
         $separator = ',';
     }
     # parses the list, but leaves tokens untouched inside () brackets
     $string_array = String::tokenize($string, $separator);
     //explode($separator, $string);
     $return_array = array();
     if (empty($string_array)) {
         return array();
     }
     foreach ($string_array as $t) {
         $t = trim($t);
         if (!empty($t)) {
             if ($camelize === true) {
                 $t = mb_strtolower($t);
                 $t = Inflector::camelize(Inflector::underscore($t));
                 # problems with non-alpha chars!!
             } elseif ($capitalize === true) {
                 $t = ucwords($t);
             }
             $return_array[] = $t;
         }
     }
     return $return_array;
 }
Ejemplo n.º 17
0
 /**
  * Overwrite the schema.php file
  *
  * @return void
  */
 protected function _overwriteSchema()
 {
     $options = array();
     if ($this->params['force']) {
         $options['models'] = false;
     } elseif (!empty($this->params['models'])) {
         $options['models'] = String::tokenize($this->params['models']);
     }
     $cacheDisable = Configure::read('Cache.disable');
     Configure::write('Cache.disable', true);
     $content = $this->Schema->read($options);
     $file = 'schema.php';
     Configure::write('Cache.disable', $cacheDisable);
     if (!empty($this->params['exclude']) && !empty($content)) {
         $excluded = String::tokenize($this->params['exclude']);
         foreach ($excluded as $table) {
             unset($content['tables'][$table]);
         }
     }
     if ($this->Schema->write($content)) {
         $this->out(__d('cake_console', 'Schema file: %s generated', $file));
         return $this->_stop();
     }
     $this->err(__d('cake_console', 'Schema file: %s generated'));
     return $this->_stop();
 }
 /**
  * Read database and Write schema object
  * accepts a connection as first arg or path to save as second arg
  *
  * @return void
  */
 public function generate()
 {
     $this->out(__d('cake_console', 'Generating Schema...'));
     $options = array();
     if ($this->params['force']) {
         $options['models'] = false;
     } elseif (!empty($this->params['models'])) {
         $options['models'] = String::tokenize($this->params['models']);
     }
     $snapshot = false;
     if (isset($this->args[0]) && $this->args[0] === 'snapshot') {
         $snapshot = true;
     }
     if (!$snapshot && file_exists($this->Schema->path . DS . $this->params['file'])) {
         $snapshot = true;
         $prompt = __d('cake_console', "Schema file exists.\n [O]verwrite\n [S]napshot\n [Q]uit\nWould you like to do?");
         $result = strtolower($this->in($prompt, array('o', 's', 'q'), 's'));
         if ($result === 'q') {
             return $this->_stop();
         }
         if ($result === 'o') {
             $snapshot = false;
         }
     }
     $cacheDisable = Configure::read('Cache.disable');
     Configure::write('Cache.disable', true);
     $content = $this->Schema->read($options);
     $content['file'] = $this->params['file'];
     Configure::write('Cache.disable', $cacheDisable);
     if ($snapshot === true) {
         $fileName = rtrim($this->params['file'], '.php');
         $Folder = new Folder($this->Schema->path);
         $result = $Folder->read();
         $numToUse = false;
         if (isset($this->params['snapshot'])) {
             $numToUse = $this->params['snapshot'];
         }
         $count = 0;
         if (!empty($result[1])) {
             foreach ($result[1] as $file) {
                 if (preg_match('/' . preg_quote($fileName) . '(?:[_\\d]*)?\\.php$/', $file)) {
                     $count++;
                 }
             }
         }
         if ($numToUse !== false) {
             if ($numToUse > $count) {
                 $count = $numToUse;
             }
         }
         $content['file'] = $fileName . '_' . $count . '.php';
     }
     if ($this->Schema->write($content)) {
         $this->out(__d('cake_console', 'Schema file: %s generated', $content['file']));
         $this->_stop();
     } else {
         $this->err(__d('cake_console', 'Schema file: %s generated'));
         $this->_stop();
     }
 }
Ejemplo n.º 19
0
 public function _fromList(Model $Model, $val)
 {
     extract($this->settings[$Model->alias]);
     return String::tokenize($val, $separator, $leftBound, $rightBound);
 }
Ejemplo n.º 20
0
 /**
  * Gets a value from an array or object that is contained in a given path using an array path syntax, i.e.:
  * "{n}.Person.{[a-z]+}" - Where "{n}" represents a numeric key, "Person" represents a string literal,
  * and "{[a-z]+}" (i.e. any string literal enclosed in brackets besides {n} and {s}) is interpreted as
  * a regular expression.
  *
  * @param array $data Array from where to extract
  * @param string|array $path As an array, or as a dot-separated string.
  * @return array Extracted data
  * @link http://book.cakephp.org/2.0/en/core-utility-libraries/set.html#Set::classicExtract
  */
 public static function classicExtract($data, $path = null)
 {
     if (empty($path)) {
         return $data;
     }
     if (is_object($data)) {
         if (!($data instanceof ArrayAccess || $data instanceof Traversable)) {
             $data = get_object_vars($data);
         }
     }
     if (empty($data)) {
         return null;
     }
     if (is_string($path) && strpos($path, '{') !== false) {
         $path = String::tokenize($path, '.', '{', '}');
     } elseif (is_string($path)) {
         $path = explode('.', $path);
     }
     $tmp = array();
     if (empty($path)) {
         return null;
     }
     foreach ($path as $i => $key) {
         if (is_numeric($key) && intval($key) > 0 || $key === '0') {
             if (isset($data[$key])) {
                 $data = $data[$key];
             } else {
                 return null;
             }
         } elseif ($key === '{n}') {
             foreach ($data as $j => $val) {
                 if (is_int($j)) {
                     $tmpPath = array_slice($path, $i + 1);
                     if (empty($tmpPath)) {
                         $tmp[] = $val;
                     } else {
                         $tmp[] = Set::classicExtract($val, $tmpPath);
                     }
                 }
             }
             return $tmp;
         } elseif ($key === '{s}') {
             foreach ($data as $j => $val) {
                 if (is_string($j)) {
                     $tmpPath = array_slice($path, $i + 1);
                     if (empty($tmpPath)) {
                         $tmp[] = $val;
                     } else {
                         $tmp[] = Set::classicExtract($val, $tmpPath);
                     }
                 }
             }
             return $tmp;
         } elseif (false !== strpos($key, '{') && false !== strpos($key, '}')) {
             $pattern = substr($key, 1, -1);
             foreach ($data as $j => $val) {
                 if (preg_match('/^' . $pattern . '/s', $j) !== 0) {
                     $tmpPath = array_slice($path, $i + 1);
                     if (empty($tmpPath)) {
                         $tmp[$j] = $val;
                     } else {
                         $tmp[$j] = Set::classicExtract($val, $tmpPath);
                     }
                 }
             }
             return $tmp;
         } else {
             if (isset($data[$key])) {
                 $data = $data[$key];
             } else {
                 return null;
             }
         }
     }
     return $data;
 }
Ejemplo n.º 21
0
 /**
  * Find attached file data from binded model
  *
  * @param &$Model $model
  * @param mixed $modelId The model id
  * @param mixed $fields The fields that searches in string or array
  * @return array
  * @access protected
  */
 function _findBindedFields(&$model, $modelId, $fields = array())
 {
     $query = array('conditions' => array('model' => $model->alias, 'model_id' => $modelId), 'fields' => array('id', 'model', 'model_id', 'field_name', 'file_name', 'file_content_type', 'file_size', 'created', 'modified'), 'recursive' => -1);
     if ($fields) {
         if (is_string($fields)) {
             App::import('Core', 'String');
             $fields = String::tokenize($fields);
         }
         $query['conditions']['field_name'] = $fields;
     }
     $data = $this->runtime[$model->alias]['bindedModel']->find('all', $query);
     if ($data) {
         $data = Set::combine($data, '{n}.' . $this->runtime[$model->alias]['bindedModel']->alias . '.field_name', '{n}.' . $this->runtime[$model->alias]['bindedModel']->alias);
     }
     return $data;
 }
Ejemplo n.º 22
0
 /**
  * Generate ResultSet
  *
  * @param mixed $results The results to modify.
  * @return void
  */
 public function resultSet($results)
 {
     $this->results = $results;
     $this->map = array();
     $numFields = $results->columnCount();
     $index = 0;
     $j = 0;
     // PDO::getColumnMeta is experimental and does not work with sqlite3,
     // so try to figure it out based on the querystring
     $querystring = $results->queryString;
     if (stripos($querystring, 'SELECT') === 0) {
         $last = strripos($querystring, 'FROM');
         if ($last !== false) {
             $selectpart = substr($querystring, 7, $last - 8);
             $selects = String::tokenize($selectpart, ',', '(', ')');
         }
     } elseif (strpos($querystring, 'PRAGMA table_info') === 0) {
         $selects = array('cid', 'name', 'type', 'notnull', 'dflt_value', 'pk');
     } elseif (strpos($querystring, 'PRAGMA index_list') === 0) {
         $selects = array('seq', 'name', 'unique');
     } elseif (strpos($querystring, 'PRAGMA index_info') === 0) {
         $selects = array('seqno', 'cid', 'name');
     }
     while ($j < $numFields) {
         if (!isset($selects[$j])) {
             $j++;
             continue;
         }
         if (preg_match('/\\bAS\\s+(.*)/i', $selects[$j], $matches)) {
             $columnName = trim($matches[1], '"');
         } else {
             $columnName = trim(str_replace('"', '', $selects[$j]));
         }
         if (strpos($selects[$j], 'DISTINCT') === 0) {
             $columnName = str_ireplace('DISTINCT', '', $columnName);
         }
         $metaType = false;
         try {
             $metaData = (array) $results->getColumnMeta($j);
             if (!empty($metaData['sqlite:decl_type'])) {
                 $metaType = trim($metaData['sqlite:decl_type']);
             }
         } catch (Exception $e) {
         }
         if (strpos($columnName, '.')) {
             $parts = explode('.', $columnName);
             $this->map[$index++] = array(trim($parts[0]), trim($parts[1]), $metaType);
         } else {
             $this->map[$index++] = array(0, $columnName, $metaType);
         }
         $j++;
     }
 }
Ejemplo n.º 23
0
 /**
  * Remove data matching $path from the $data array.
  * You can use `{n}` and `{s}` to remove multiple elements
  * from $data.
  *
  * @param array $data The data to operate on
  * @param string $path A path expression to use to remove.
  * @return array The modified array.
  * @link http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::remove
  */
 public static function remove(array $data, $path)
 {
     if (strpos($path, '[') === false) {
         $tokens = explode('.', $path);
     } else {
         $tokens = String::tokenize($path, '.', '[', ']');
     }
     if (strpos($path, '{') === false && strpos($path, '[') === false) {
         return self::_simpleOp('remove', $data, $tokens);
     }
     $token = array_shift($tokens);
     $nextPath = implode('.', $tokens);
     list($token, $conditions) = self::_splitConditions($token);
     foreach ($data as $k => $v) {
         $match = self::_matchToken($k, $token);
         if ($match && is_array($v)) {
             if ($conditions && self::_matches($v, $conditions)) {
                 unset($data[$k]);
                 continue;
             }
             $data[$k] = self::remove($v, $nextPath);
             if (empty($data[$k])) {
                 unset($data[$k]);
             }
         } elseif ($match) {
             unset($data[$k]);
         }
     }
     return $data;
 }
Ejemplo n.º 24
0
 /**
  * Handles the before/after filter logic for find('list') operations.  Only called by Model::find().
  *
  * @param string $state Either "before" or "after"
  * @param array $query
  * @param array $results
  * @return array Key/value pairs of primary keys/display field values of all records found
  * @see Model::find()
  */
 protected function _findList($state, $query, $results = array())
 {
     if ($state === 'before') {
         if (empty($query['fields'])) {
             $query['fields'] = array("{$this->alias}.{$this->primaryKey}", "{$this->alias}.{$this->displayField}");
             $list = array("{n}.{$this->alias}.{$this->primaryKey}", "{n}.{$this->alias}.{$this->displayField}", null);
         } else {
             if (!is_array($query['fields'])) {
                 $query['fields'] = String::tokenize($query['fields']);
             }
             if (count($query['fields']) === 1) {
                 if (strpos($query['fields'][0], '.') === false) {
                     $query['fields'][0] = $this->alias . '.' . $query['fields'][0];
                 }
                 $list = array("{n}.{$this->alias}.{$this->primaryKey}", '{n}.' . $query['fields'][0], null);
                 $query['fields'] = array("{$this->alias}.{$this->primaryKey}", $query['fields'][0]);
             } elseif (count($query['fields']) === 3) {
                 for ($i = 0; $i < 3; $i++) {
                     if (strpos($query['fields'][$i], '.') === false) {
                         $query['fields'][$i] = $this->alias . '.' . $query['fields'][$i];
                     }
                 }
                 $list = array('{n}.' . $query['fields'][0], '{n}.' . $query['fields'][1], '{n}.' . $query['fields'][2]);
             } else {
                 for ($i = 0; $i < 2; $i++) {
                     if (strpos($query['fields'][$i], '.') === false) {
                         $query['fields'][$i] = $this->alias . '.' . $query['fields'][$i];
                     }
                 }
                 $list = array('{n}.' . $query['fields'][0], '{n}.' . $query['fields'][1], null);
             }
         }
         if (!isset($query['recursive']) || $query['recursive'] === null) {
             $query['recursive'] = -1;
         }
         list($query['list']['keyPath'], $query['list']['valuePath'], $query['list']['groupPath']) = $list;
         return $query;
     } elseif ($state === 'after') {
         if (empty($results)) {
             return array();
         }
         $lst = $query['list'];
         return Set::combine($results, $lst['keyPath'], $lst['valuePath'], $lst['groupPath']);
     }
 }
Ejemplo n.º 25
0
 function _savePermission($data, $checked)
 {
     $model = 'GroupPermission';
     App::import('Model', 'UserManagement.' . $model);
     $this->model = new $model();
     $arr = String::tokenize($data, ',');
     $conditions = array();
     if (count($arr) > 3) {
         $plugin = $arr[0];
         $controller = $arr[1];
         $action = $arr[2];
         $code = $arr[3];
     } else {
         $plugin = '';
         $controller = $arr[0];
         $action = $arr[1];
         $code = $arr[2];
     }
     $conditions = array('plugin' => $plugin, 'controller' => $controller, 'action' => $action);
     $exists = $this->model->find('first', array('conditions' => $conditions));
     if (empty($exists)) {
         $data = array($model => array('plugin' => $plugin, 'controller' => $controller, 'action' => $action, 'sum_of_group_access_code' => $code));
         $this->model->create();
         $this->model->save($data);
     } else {
         $ac_code = $this->getAccessCodes($exists[$model]['sum_of_group_access_code']);
         if ($checked === "true" && !in_array($code, $ac_code)) {
             $code = $code + $exists[$model]['sum_of_group_access_code'];
         } else {
             $code = $exists[$model]['sum_of_group_access_code'] - $code;
         }
         $data = array($model => array('plugin' => $plugin, 'controller' => $controller, 'action' => $action, 'sum_of_group_access_code' => $code));
         $this->model->id = $exists[$model]['id'];
         $this->model->save($data);
     }
     return true;
 }
Ejemplo n.º 26
0
 function admin_user_permissions($user_id = null)
 {
     $user_model_name = Configure::read('acl.aro.user.model');
     $role_model_name = Configure::read('acl.aro.role.model');
     $user_display_field = $this->AclManager->set_display_name($user_model_name, Configure::read('acl.user.display_name'));
     $this->paginate['order'] = array($user_display_field => 'asc');
     $this->set('user_display_field', $user_display_field);
     if (empty($user_id)) {
         if (isset($this->request->data['User'][$user_display_field]) || $this->Session->check('acl.aros.user_permissions.filter')) {
             if (!isset($this->request->data['User'][$user_display_field])) {
                 $this->request->data['User'][$user_display_field] = $this->Session->read('acl.aros.user_permissions.filter');
             } else {
                 $this->Session->write('acl.aros.user_permissions.filter', $this->request->data['User'][$user_display_field]);
             }
             $filter = array($user_model_name . '.' . $user_display_field . ' LIKE' => '%' . $this->request->data['User'][$user_display_field] . '%');
         } else {
             $filter = array();
         }
         $users = $this->paginate($user_model_name, $filter);
         $this->set('users', $users);
     } else {
         $role_display_field = $this->AclManager->set_display_name($role_model_name, Configure::read('acl.aro.role.display_field'));
         $this->set('role_display_field', $role_display_field);
         $this->{$role_model_name}->recursive = -1;
         $roles = $this->{$role_model_name}->find('all', array('order' => $role_display_field, 'contain' => false, 'recursive' => -1));
         $this->{$user_model_name}->recursive = -1;
         $user = $this->{$user_model_name}->read(null, $user_id);
         $permissions = array();
         $methods = array();
         /*
          * Check if the user exists in the ARO table
          */
         $user_aro = $this->Acl->Aro->node($user);
         if (empty($user_aro)) {
             $display_user = $this->{$user_model_name}->find('first', array('conditions' => array($user_model_name . '.id' => $user_id, 'contain' => false, 'recursive' => -1)));
             $this->Session->setFlash(sprintf(__d('acl', "The user '%s' does not exist in the ARO table"), $display_user[$user_model_name][$user_display_field]), 'flash_error', null, 'plugin_acl');
         } else {
             $actions = $this->AclReflector->get_all_actions();
             foreach ($actions as $full_action) {
                 $arr = String::tokenize($full_action, '/');
                 if (count($arr) == 2) {
                     $plugin_name = null;
                     $controller_name = $arr[0];
                     $action = $arr[1];
                 } elseif (count($arr) == 3) {
                     $plugin_name = $arr[0];
                     $controller_name = $arr[1];
                     $action = $arr[2];
                 }
                 if ($controller_name != 'App') {
                     if (!isset($this->params['named']['ajax'])) {
                         $aco_node = $this->Acl->Aco->node('controllers/' . $full_action);
                         if (!empty($aco_node)) {
                             $authorized = $this->Acl->check($user, 'controllers/' . $full_action);
                             $permissions[$user[$user_model_name][$this->_get_user_primary_key_name()]] = $authorized ? 1 : 0;
                         }
                     }
                     if (isset($plugin_name)) {
                         $methods['plugin'][$plugin_name][$controller_name][] = array('name' => $action, 'permissions' => $permissions);
                     } else {
                         $methods['app'][$controller_name][] = array('name' => $action, 'permissions' => $permissions);
                     }
                 }
             }
             /*
              * Check if the user has specific permissions
              */
             $count = $this->Aro->Permission->find('count', array('conditions' => array('Aro.id' => $user_aro[0]['Aro']['id'])));
             if ($count != 0) {
                 $this->set('user_has_specific_permissions', true);
             } else {
                 $this->set('user_has_specific_permissions', false);
             }
         }
         $this->set('user', $user);
         $this->set('roles', $roles);
         $this->set('actions', $methods);
         if (isset($this->params['named']['ajax'])) {
             $this->render('admin_ajax_user_permissions');
         }
     }
 }
Ejemplo n.º 27
0
 /**
  * takes the event name and breaks it down into the different parts setting
  * some defaults for gloabl events. results are cached to avoid importing
  * and alling the string class to much.
  *
  * @param string $eventName the name of the event
  * @return array the scope + event name
  */
 protected function _parseEventName($eventName)
 {
     $_this = EventCore::getInstance();
     if (!isset($_this->eventNameCache->{$eventName})) {
         $eventTokens = String::tokenize($eventName, '.');
         $scope = 'Global';
         $event = $eventTokens[0];
         if (count($eventTokens) > 1) {
             list($scope, $event) = $eventTokens;
             if ($scope != Inflector::camelize($scope)) {
                 user_error(sprintf('%s.%s is not valid, camelized plugins required', $scope, $event));
                 $scope = Inflector::camelize($scope, E_USER_NOTICE);
             }
         }
         $_this->eventNameCache->{$eventName} = array('scope' => $scope, 'event' => $event);
     }
     return $_this->eventNameCache->{$eventName};
 }