예제 #1
0
 function admin_edit($id = null)
 {
     if (!empty($this->request->data)) {
         App::uses('Set', 'Utility');
         if (empty($this->request->data['Role']['alias'])) {
             App::uses('Inflector', 'Utility');
             $this->request->data['Role']['alias'] = Inflector::slug($this->request->data['Role']['name'], '-');
         }
         $dataCapabilities = Set::flatten($this->request->data['RoleCapability']);
         $this->Role->save($this->request->data);
         $defaultCapabilities = $this->Role->Capability->find('list', array('conditions' => array('role_id' => $this->Role->id, 'args' => null), 'fields' => array('id', 'capability')));
         $delete = array();
         foreach ($defaultCapabilities as $id => $capability) {
             if (empty($dataCapabilities[$capability])) {
                 $delete[] = $id;
             }
         }
         foreach ($dataCapabilities as $capability => $ok) {
             if ($ok && !in_array($capability, array_values($defaultCapabilities))) {
                 $this->Role->Capability->create();
                 $this->Role->Capability->save(array('capability' => $capability, 'role_id' => $this->Role->id));
             }
         }
         if (!empty($delete)) {
             $this->Role->Capability->deleteAll(array('Capability.id' => $delete));
         }
         $this->redirect(array($this->Role->id));
     }
     $this->request->data = $this->Role->findById($id);
 }
예제 #2
0
 public function checkNewMail($account)
 {
     $mails = $this->find('all', array('conditions' => Set::flatten(array($this->alias => $account))));
     // @todo save to the db here
     // @todo delete messages from server here
     return $mails;
 }
예제 #3
0
 public function frontend_css()
 {
     $this->layout = 'ajax';
     $this->response->type('css');
     $css = $this->Event->trigger('requireCssToLoad');
     $this->set('css', array_filter(array_values(Set::flatten($css))));
 }
 private function importElements()
 {
     App::import('Core', 'GummFolder');
     $Folder = new GummFolder(GUMM_LAYOUT_ELEMENTS);
     $elementFiles = $Folder->findRecursive('.*\\.php');
     $Folder->cd(GUMM_LAYOUT_ELEMENTS_SINGLE);
     $elementFiles = array_merge($elementFiles, $Folder->findRecursive('.*\\.php'));
     $availableElements = Set::flatten(Set::classicExtract(array_values(Configure::read('Data.BuilderElements')), '{n}.elements'));
     $elementsAvaialbleMap = array();
     foreach ($elementFiles as $layoutElementFullPath) {
         $basename = basename($layoutElementFullPath, '.php');
         if (in_array($basename, $availableElements)) {
             $elementsAvaialbleMap[$basename] = $layoutElementFullPath;
         }
     }
     foreach ($availableElements as $basename) {
         if (isset($elementsAvaialbleMap[$basename])) {
             require_once $elementsAvaialbleMap[$basename];
             $className = Inflector::camelize($basename) . 'LayoutElement';
             $settings = array();
             if ($this->post) {
                 $settings['postId'] = $this->post->ID;
             }
             $obj = new $className($settings);
             $this->elementsAvailable[Inflector::underscore($basename)] = $obj;
         }
     }
 }
 /**
  * We only need to change the bind if the HABTM model is present
  * somewhere in the conditions.
  * To make array keys easier to search for a match, we flatten
  * and implode the keys it into a string.
  */
 private function checkHabtmConditions($Model, $query)
 {
     if (empty($query['conditions'])) {
         $query['conditions'] = array();
     }
     $searchableConditions = implode('.', Set::flatten(array_keys($query['conditions'])));
     return (bool) strpos($searchableConditions, $this->settings[$Model->alias]['habtmModel']);
 }
예제 #6
0
 /**
  * checkHabtmConditions
  * We only need to change the bind if the HABTM model is present
  * somewhere in the conditions.
  * To make array keys easier to search for a match, we flatten
  * and implode the keys it into a string.
  *
  * @param mixed $model_name model
  * @param mixed $query      query
  *
  * @access private
  * @return void
  */
 private function checkHabtmConditions($model_name, $query)
 {
     if (empty($query['conditions'])) {
         return false;
     }
     $searchableConditions = implode('.', Set::flatten(array_keys($query['conditions'])));
     return strpos($searchableConditions, $model_name) !== false;
 }
예제 #7
0
 public function getFontsVendor($fontFamily)
 {
     $vendor = 'browser';
     $browserFonts = Set::flatten(Set::reverse($this->getBrowserFontsList()->items));
     if (!in_array($fontFamily, $browserFonts)) {
         $vendor = 'google';
     }
     return $vendor;
 }
 /**
  * Finds all targets that match a query.
  *
  * @param string $query
  * @param integer $collection_id
  * @return array
  */
 public function findTargetsWith($query = '', $collection_id = null)
 {
     $conditions = array();
     $conditions['Target.collection_id'] = $collection_id;
     $query = trim($query);
     if (mb_strlen($query) > 0) {
         $conditions['OR'] = Set::flatten(array('Target' => array('display_name LIKE' => "%{$query}%", 'display_description LIKE' => "%{$query}%")));
     }
     $result = $this->Target->find('all', array('conditions' => $conditions, 'recursive' => -1));
     return $result;
 }
예제 #9
0
 /**
  * Test Validation
  *
  * @return void
  */
 public function testValidation()
 {
     $data1 = array('empty' => '', 'garbage' => 'trash', 'postal' => 'abcd', 'dimensions' => array('inches' => array('height' => 42.5, 'width' => 11.75, 'depth' => 3.25, 'girth' => 'a')));
     $data2 = array('dimensions' => array('inches' => array('height' => 42.23)));
     $this->MetaThing->id = 1;
     $result1 = $this->MetaThing->invalidMeta($data1);
     $this->assertCount(5, Set::flatten($result1));
     $this->assertFalse($this->MetaThing->setMeta($data1));
     $this->assertTrue($this->MetaThing->setMeta($data2));
     $this->assertFalse($this->MetaThing->setMeta('dimensions.inches.height', 'forty-two'));
     $this->assertCount(1, $this->MetaThing->validationErrorsMeta());
 }
예제 #10
0
 /**
  * Tạo thông báo lỗi ở form
  * 
  * @param mixed $validationErrs Mảng lỗi
  * @param string $class Class thẻ sẽ chứa thông báo
  * @return string HTML thông báo lỗi
  */
 public static function formErrorSummary($validationErrs = NULL, $class = "n_error")
 {
     $html = "";
     if (is_array($validationErrs) && !empty($validationErrs)) {
         $_validationErrs = Set::flatten($validationErrs);
         $html .= '<div class="' . $class . '">';
         foreach ($_validationErrs as $err) {
             $html .= "<p>{$err}</p>";
         }
         $html .= '</div>';
     }
     return $html;
 }
예제 #11
0
 function test_global_activity()
 {
     $User =& ClassRegistry::init('User');
     $user = $User->find_by_id_logged(2);
     $events = $this->Issue->find_events('issues', $user, false, false, array());
     # Issue of a private project
     $this->assertTrue(in_array(1, Set::flatten(Set::extract('{n}.{n}.{n}.Issue.id', $events))));
     $this->assertTrue(in_array(2, Set::flatten(Set::extract('{n}.{n}.{n}.Issue.id', $events))));
     $this->assertTrue(in_array(3, Set::flatten(Set::extract('{n}.{n}.{n}.Issue.id', $events))));
     $this->assertTrue(in_array(4, Set::flatten(Set::extract('{n}.{n}.{n}.Issue.id', $events))));
     $this->assertTrue(in_array(5, Set::flatten(Set::extract('{n}.{n}.{n}.Issue.id', $events))));
     $this->assertTrue(in_array(6, Set::flatten(Set::extract('{n}.{n}.{n}.Issue.id', $events))));
     $this->assertTrue(in_array(7, Set::flatten(Set::extract('{n}.{n}.{n}.Issue.id', $events))));
 }
 public function conferenceValid($confdata)
 {
     //$this->loadModel('Conference');
     $conf = ClassRegistry::init('Conference');
     if (!$conf->validates($confdata)) {
         //debug($this->Conference->validationErrors); //displays array info
         foreach (Set::flatten($conf->validationErrors) as $field => $message) {
             //debug("field: ".$field." message: ".$message);
             $conf->invalidate($field, $message);
         }
         return false;
     } else {
         return true;
     }
 }
예제 #13
0
파일: debug.php 프로젝트: Galvanio/Kinspir
 /**
  * Displays a handful of useful debugging messages
  * 
  * @param Mailer_Transport $transport
  * @return null
  * @access public
  */
 public function transport(Mailer_Transport $transport)
 {
     if ($this->debug) {
         $this->out("\r\nTransport");
         $this->hr();
         $this->debug('Class: ' . get_class($transport));
         $this->out("\r\nSettings");
         $this->hr();
         foreach (Set::flatten($transport->settings) as $key => $value) {
             $this->debug($key . ': ' . $value);
         }
         $this->out('');
         $this->in('Press enter to continue...');
     }
 }
예제 #14
0
 /**
  * Before find callback
  *
  * @param object $model Model using this behavior
  * @param array $query Data used to execute this query, i.e. conditions, order, etc.
  * @return bool True if the operation should continue, false if it should abort
  */
 public function beforeFind($model, $query)
 {
     $result = parent::beforeFind($model, $query);
     if (empty($this->settings[$model->alias]['find']) || isset($query['defaultable']) && $query['defaultable'] === false || $result === false) {
         return $result;
     } else {
         if (is_array($result)) {
             $query = $result;
         }
     }
     $Db = ConnectionManager::getDataSource($model->useDbConfig);
     $defaultConditions = array();
     foreach ($this->settings[$model->alias]['find'] as $field => $fieldValue) {
         $fields = array($Db->name($model->alias) . '.' . $Db->name($field), $Db->name($field), $model->alias . '.' . $field, $field);
         $include = true;
         if (!empty($query['conditions'])) {
             foreach (Set::flatten((array) $query['conditions']) as $key => $value) {
                 $condition = is_numeric($key) ? $value : $key;
                 foreach ($fields as $field) {
                     if (preg_match('/^((not|or)\\.)?' . preg_quote($field) . '/i', $condition) || preg_match('/^((not|or)\\.)?' . preg_quote($model->alias . '.' . $field) . '/i', $condition) || preg_match('/[^A-Z0-9_]+' . preg_quote($field) . '[^A-Z0-9_]+/i', $condition) || preg_match('/[^A-Z0-9_]+' . preg_quote($model->alias . '.' . $field) . '[^A-Z0-9_]+/i', $condition)) {
                         $include = false;
                         break;
                     }
                 }
                 if (!$include) {
                     break;
                 }
             }
         }
         if ($include) {
             $defaultConditions[$model->alias . '.' . $field] = $fieldValue;
         }
     }
     if (!empty($defaultConditions)) {
         if (empty($query['conditions'])) {
             $query['conditions'] = array();
         } else {
             if (!is_array($query['conditions'])) {
                 $query['conditions'] = (array) $query['conditions'];
             }
         }
         $query['conditions'] = array_merge($query['conditions'], $defaultConditions);
         $result = $query;
     }
     return $result;
 }
예제 #15
0
 function __construct()
 {
     App::import('Lib', 'SparkForm.SparkFormConfig');
     $preprocessors = SparkFormConfig::load('preprocessors');
     $preprocessors = array_merge($this->preprocessors, (array) $preprocessors);
     $customTypes = SparkFormConfig::load('customTypes');
     $customTypes = array_merge($this->customTypes, (array) $customTypes);
     $callbacklists = array(&$customTypes, &$preprocessors);
     foreach ($callbacklists as &$list) {
         $flat = Set::flatten($list, '.');
         $final = array();
         foreach ($flat as $key => $funct) {
             if (!is_array($funct)) {
                 $keys = array_filter(explode('.', $key), array($this, '_notNumeric'));
                 $helper = null;
                 $plugin = null;
                 if (count($keys) == 1) {
                     $helper = $keys[0];
                 } elseif (count($keys) > 1) {
                     $plugin = array_shift($keys);
                     $helper = array_shift($keys);
                 }
                 $callback = array('funct' => $funct);
                 if ($helper) {
                     $fullName = $helper;
                     $callback['helper'] = $helper;
                     if ($plugin) {
                         $callback['plugin'] = $plugin;
                         $fullName = $plugin . '.' . $helper;
                     }
                     if (!in_array($fullName, $this->helpers)) {
                         $this->helpers[] = $fullName;
                     }
                 }
                 $final[$funct] = $callback;
             } elseif (is_numeric($key)) {
                 $final[$funct['funct']] = $funct;
             } else {
                 $final[$key] = $funct;
             }
         }
         $list = $final;
     }
     $this->preprocessors = $preprocessors;
     $this->customTypes = $customTypes;
 }
예제 #16
0
 public function formatDateFields($results, $dates, $format = "%d/%m/%Y")
 {
     if (!empty($dates)) {
         $setResult = function ($val, $key) use(&$results, $format) {
             $innerKey = explode("/", $key);
             $results[$innerKey[0]][$innerKey[1]][$innerKey[2]] = CakeTime::format($val, $format);
         };
         $extracted = Set::extract($results, "/{$this->alias}");
         $dateExtracted = Set::classicExtract($extracted, '{\\w+}.{\\w+}.{' . implode("|", $dates) . '}');
         $applied = Set::apply("/", $dateExtracted, function ($val) {
             return count(Set::filter($val)) > 0 ? $val : null;
         });
         if ($applied) {
             $flatten = Set::flatten($applied, "/");
             array_walk($flatten, $setResult);
         }
     }
     return $results;
 }
예제 #17
0
파일: CsvView.php 프로젝트: ayaou/Zuha
 private function _array_to_csv($array)
 {
     $csv = array();
     // Flatten the given array
     foreach ($array as $k => $item) {
         $csv[$k] = is_array($item) ? Set::flatten($item) : $item;
     }
     // Create the Column names.
     // This has to be done seperate because we don't have all of them beforehand.
     $csvString = array('headers' => array());
     foreach ($csv as $h => $lines) {
         foreach ($lines as $header => $line) {
             if (array_search($header, $csvString['headers']) === false && !empty($header)) {
                 $csvString['headers'][] = $header;
             }
         }
     }
     // Create the values this will also check for commas in the values
     foreach ($csv as $c => $lines) {
         $csvString['values'][$c] = '';
         foreach ($csvString['headers'] as $h) {
             if (isset($lines[$h])) {
                 if (is_array($lines[$h])) {
                     Hash::flatten($lines[$h], '|');
                 }
                 $csvString['values'][$c] .= is_int($lines[$h]) ? $lines[$h] . ',' : '"' . $this->_stipIllegalChars($lines[$h]) . '",';
                 // was a conflict, can probably delete // $csvString['values'][$c] .= is_int($lines[$h]) ? $lines[$h] . ',' : '"' . str_replace(',', '' , $lines[$h]) . '",';
             } else {
                 $csvString['values'][$c] .= ',';
             }
         }
     }
     $output = '';
     foreach ($csvString['headers'] as $i => $header) {
         $csvString['headers'][$i] = '"' . $header . '"';
     }
     $output .= implode(',', str_replace('.', '_', $csvString['headers'])) . "\r\n";
     $output .= implode("\r\n", $csvString['values']);
     return $output;
 }
예제 #18
0
파일: misc.php 프로젝트: amad4biz/invoices
/**
 * Returns configuration errors
 * @param array $config
 * @return array 
 */
function find_configuration_errors($config)
{
    // create ruleset
    $v = new Validation();
    //$v->addRule('base_url', Validation::NOT_EMPTY, 'Base URL must not be empty');
    //$v->addRule('base_url', Validation::URL, 'Base URL must be a valid URL');
    $v->addRule('db.host', Validation::NOT_EMPTY, 'Database Host must not be empty');
    $v->addRule('db.host', Validation::STRING, 'Database Host must be a string');
    $v->addRule('db.name', Validation::NOT_EMPTY, 'Database Name must not be empty');
    $v->addRule('db.name', Validation::STRING, 'Database Name must be a string');
    $v->addRule('db.username', Validation::NOT_EMPTY, 'Database Username must not be empty');
    $v->addRule('db.username', Validation::STRING, 'Database Username must be a string');
    //$v->addRule('db.password', Validation::NOT_EMPTY, 'Database Password must not be empty');
    $v->addRule('db.password', Validation::STRING, 'Database Password must be a string');
    $v->addRule('user.name', Validation::NOT_EMPTY, 'User Name must not be empty');
    $v->addRule('user.name', Validation::STRING, 'User Name must be a string');
    $v->addRule('user.email', Validation::NOT_EMPTY, 'E-mail must not be empty');
    $v->addRule('user.email', Validation::STRING, 'E-mail must be a string');
    $v->addRule('user.email', Validation::EMAIL, 'E-mail must be a valid e-mail address');
    $v->addRule('user.address1', Validation::STRING, 'Address 1 must be a string');
    $v->addRule('user.address2', Validation::STRING, 'Address 2 must be a string');
    $v->addRule('user.city', Validation::STRING, 'City must be a string');
    $v->addRule('user.state', Validation::STRING, 'State/Province must be a string');
    $v->addRule('user.zip', Validation::STRING, 'Postal Code must be a string');
    $v->addRule('user.country', Validation::STRING, 'Country must be a string');
    $v->addRule('default_invoice_theme', Validation::STRING, 'Default Invoice Theme must be a string');
    $v->addRule('default_receipt_theme', Validation::STRING, 'Default Receipt Theme must be a string');
    $v->addRule('default_wage', Validation::NUMERIC, 'Default Wage must be a decimal number');
    // get errors
    $errors = $v->validateList(Set::flatten($config));
    // test database connnection
    try {
        get_database($config);
    } catch (Exception $e) {
        $errors[] = 'Could not connect to database with the given database information';
    }
    // return
    return Set::flatten($errors);
}
예제 #19
0
 /**
  * Mapped method to find invalid metadata for an attached model.
  *
  * @param   Model   $Model
  * @param   array   $data
  * @return  mixed
  */
 public function invalidMeta(Model $Model, $data = array())
 {
     extract($this->settings[$Model->alias]);
     $this->_validationErrors[$Model->name] = $errors = array();
     if (isset($validate) && !empty($validate)) {
         App::uses('Validation', 'Utility');
         $methods = array_map('strtolower', get_class_methods($Model));
         foreach (Set::flatten($data, '/') as $k => $v) {
             $rules = Set::extract("/{$k}/.", $validate);
             if (!empty($rules)) {
                 foreach ($rules as $ruleSet) {
                     if (!Set::numeric(array_keys($ruleSet))) {
                         $ruleSet = array($ruleSet);
                     }
                     foreach ($ruleSet as $rule) {
                         if (isset($rule['allowEmpty']) && $rule['allowEmpty'] === true && $v == '') {
                             break 2;
                         }
                         if (is_array($rule['rule'])) {
                             $ruleName = array_shift($rule['rule']);
                             $ruleParams = $rule['rule'];
                             array_unshift($ruleParams, $v);
                         } else {
                             $ruleName = $rule['rule'];
                             $ruleParams = array($v);
                         }
                         $valid = true;
                         if (in_array(strtolower($ruleName), $methods)) {
                             $valid = $Model->dispatchMethod($ruleName, $ruleParams);
                         } elseif (method_exists('Validation', $ruleName)) {
                             $valid = call_user_func_array("Validation::{$ruleName}", $ruleParams);
                         }
                         if (!$valid) {
                             $ruleMessage = isset($rule['message']) && !empty($rule['message']) ? $rule['message'] : sprintf('%s %s', 'Not', $rule);
                             $errors[] = $this->_unflatten($k, $ruleMessage, '/');
                             if (isset($rule['last']) && $rule['last'] === true) {
                                 break 3;
                             }
                         }
                     }
                 }
             }
         }
     }
     if (empty($errors)) {
         return false;
     }
     $tmp_errors = array();
     foreach ($errors as $error) {
         foreach ($error as $field => $message) {
             $tmp_errors[$field] = $message;
         }
     }
     $this->_validationErrors[$Model->name] = $tmp_errors;
     $Model->validationErrors = array_merge($Model->validationErrors, array('Metadatum' => $tmp_errors));
     return $errors;
 }
 /**
  * Tests Set::flatten
  *
  * @return void
  */
 public function testFlatten()
 {
     $data = array('Larry', 'Curly', 'Moe');
     $result = Set::flatten($data);
     $this->assertEquals($data, $result);
     $data[9] = 'Shemp';
     $result = Set::flatten($data);
     $this->assertEquals($data, $result);
     $data = array(array('Post' => array('id' => '1', 'author_id' => '1', 'title' => 'First Post'), 'Author' => array('id' => '1', 'user' => 'nate', 'password' => 'foo')), array('Post' => array('id' => '2', 'author_id' => '3', 'title' => 'Second Post', 'body' => 'Second Post Body'), 'Author' => array('id' => '3', 'user' => 'larry', 'password' => null)));
     $result = Set::flatten($data);
     $expected = array('0.Post.id' => '1', '0.Post.author_id' => '1', '0.Post.title' => 'First Post', '0.Author.id' => '1', '0.Author.user' => 'nate', '0.Author.password' => 'foo', '1.Post.id' => '2', '1.Post.author_id' => '3', '1.Post.title' => 'Second Post', '1.Post.body' => 'Second Post Body', '1.Author.id' => '3', '1.Author.user' => 'larry', '1.Author.password' => null);
     $this->assertEquals($expected, $result);
 }
예제 #21
0
 /**
  * Validate submitted form
  *
  * @param object $controller Instantiating controller
  * @return bool true if submitted form is valid
  * @access protected
  */
 function _validatePost(&$controller)
 {
     if (empty($controller->data)) {
         return true;
     }
     $data = $controller->data;
     if (!isset($data['_Token']) || !isset($data['_Token']['fields']) || !isset($data['_Token']['key'])) {
         return false;
     }
     $token = $data['_Token']['key'];
     if ($this->Session->check('_Token')) {
         $tokenData = unserialize($this->Session->read('_Token'));
         if ($tokenData['expires'] < time() || $tokenData['key'] !== $token) {
             return false;
         }
     }
     $locked = null;
     $check = $controller->data;
     $token = urldecode($check['_Token']['fields']);
     if (strpos($token, ':')) {
         list($token, $locked) = explode(':', $token, 2);
     }
     unset($check['_Token']);
     $lockedFields = array();
     $fields = Set::flatten($check);
     $fieldList = array_keys($fields);
     $locked = unserialize(str_rot13($locked));
     $multi = array();
     foreach ($fieldList as $i => $key) {
         if (preg_match('/\\.\\d+$/', $key)) {
             $multi[$i] = preg_replace('/\\.\\d+$/', '', $key);
             unset($fieldList[$i]);
         }
     }
     if (!empty($multi)) {
         $fieldList += array_unique($multi);
     }
     foreach ($fieldList as $i => $key) {
         $isDisabled = false;
         $isLocked = is_array($locked) && in_array($key, $locked);
         if (!empty($this->disabledFields)) {
             foreach ((array) $this->disabledFields as $disabled) {
                 $disabled = explode('.', $disabled);
                 $field = array_values(array_intersect(explode('.', $key), $disabled));
                 $isDisabled = $field === $disabled;
                 if ($isDisabled) {
                     break;
                 }
             }
         }
         if ($isDisabled || $isLocked) {
             unset($fieldList[$i]);
             if ($isLocked) {
                 $lockedFields[$key] = $fields[$key];
             }
         }
     }
     sort($fieldList, SORT_STRING);
     ksort($lockedFields, SORT_STRING);
     $fieldList += $lockedFields;
     $check = Security::hash(serialize($fieldList) . Configure::read('Security.salt'));
     return $token === $check;
 }
예제 #22
0
 /**
  * Collapses a multi-dimensional array into a single dimension, using a delimited array path for
  * each array element's key, i.e. array(array('Foo' => array('Bar' => 'Far'))) becomes
  * array('0.Foo.Bar' => 'Far').
  *
  * @param array $data Array to flatten
  * @param string $separator String used to separate array key elements in a path, defaults to '.'
  * @return array
  * @access public
  * @static
  */
 function flatten($data, $separator = '.')
 {
     $result = array();
     $path = null;
     if (is_array($separator)) {
         extract($separator, EXTR_OVERWRITE);
     }
     if (!is_null($path)) {
         $path .= $separator;
     }
     foreach ($data as $key => $val) {
         if (is_array($val)) {
             $result += (array) Set::flatten($val, array('separator' => $separator, 'path' => $path . $key));
         } else {
             $result[$path . $key] = $val;
         }
     }
     return $result;
 }
예제 #23
0
 function breadcrumb($args)
 {
     $elements = Set::flatten($args);
     return count($elements) > 0 ? $this->Html->tag('p', join(' &#187; ', $args) . ' &#187; ', array('class' => 'breadcrumb')) : '';
 }
예제 #24
0
파일: router.php 프로젝트: asairoha/pj01
 /**
  * A special fallback method that handles url arrays that cannot match
  * any defined routes.
  *
  * @param array $url A url that didn't match any routes
  * @return string A generated url for the array
  * @access protected
  * @see Router::url()
  */
 function _handleNoRoute($url)
 {
     $named = $args = array();
     $skip = array_merge(array('bare', 'action', 'controller', 'plugin', 'prefix'), $this->__prefixes);
     $keys = array_values(array_diff(array_keys($url), $skip));
     $count = count($keys);
     // Remove this once parsed URL parameters can be inserted into 'pass'
     for ($i = 0; $i < $count; $i++) {
         if (is_numeric($keys[$i])) {
             $args[] = $url[$keys[$i]];
         } else {
             $named[$keys[$i]] = $url[$keys[$i]];
         }
     }
     list($args, $named) = array(Set::filter($args, true), Set::filter($named, true));
     foreach ($this->__prefixes as $prefix) {
         if (!empty($url[$prefix])) {
             $url['action'] = str_replace($prefix . '_', '', $url['action']);
             break;
         }
     }
     if (empty($named) && empty($args) && (!isset($url['action']) || $url['action'] === 'index')) {
         $url['action'] = null;
     }
     $urlOut = array_filter(array($url['controller'], $url['action']));
     if (isset($url['plugin'])) {
         array_unshift($urlOut, $url['plugin']);
     }
     foreach ($this->__prefixes as $prefix) {
         if (isset($url[$prefix])) {
             array_unshift($urlOut, $prefix);
             break;
         }
     }
     $output = implode('/', $urlOut);
     if (!empty($args)) {
         $output .= '/' . implode('/', $args);
     }
     if (!empty($named)) {
         foreach ($named as $name => $value) {
             if (is_array($value)) {
                 $flattend = Set::flatten($value, '][');
                 foreach ($flattend as $namedKey => $namedValue) {
                     $output .= '/' . $name . "[{$namedKey}]" . $this->named['separator'] . $namedValue;
                 }
             } else {
                 $output .= '/' . $name . $this->named['separator'] . $value;
             }
         }
     }
     return $output;
 }
예제 #25
0
 function _constructResponse($rows)
 {
     $response = array();
     for ($i = 0, $row_count = count($rows); $i < $row_count; $i++) {
         $row =& $rows[$i];
         $response['rows'][$i] = Set::flatten($row);
     }
     return $response;
 }
예제 #26
0
 /**
  * Converts a matching route array into a url string. Composes the string url using the template
  * used to create the route.
  *
  * @param array $params The params to convert to a string url.
  * @return string Composed route string.
  */
 protected function _writeUrl($params)
 {
     if (isset($params['prefix'], $params['action'])) {
         $params['action'] = str_replace($params['prefix'] . '_', '', $params['action']);
         unset($params['prefix']);
     }
     if (is_array($params['pass'])) {
         $params['pass'] = implode('/', array_map('rawurlencode', $params['pass']));
     }
     $namedConfig = Router::namedConfig();
     $separator = $namedConfig['separator'];
     if (!empty($params['named']) && is_array($params['named'])) {
         $named = array();
         foreach ($params['named'] as $key => $value) {
             if (is_array($value)) {
                 $flat = Set::flatten($value, '][');
                 foreach ($flat as $namedKey => $namedValue) {
                     $named[] = $key . "[{$namedKey}]" . $separator . rawurlencode($namedValue);
                 }
             } else {
                 $named[] = $key . $separator . rawurlencode($value);
             }
         }
         $params['pass'] = $params['pass'] . '/' . implode('/', $named);
     }
     $out = $this->template;
     $search = $replace = array();
     foreach ($this->keys as $key) {
         $string = null;
         if (isset($params[$key])) {
             $string = $params[$key];
         } elseif (strpos($out, $key) != strlen($out) - strlen($key)) {
             $key .= '/';
         }
         $search[] = ':' . $key;
         $replace[] = $string;
     }
     $out = str_replace($search, $replace, $out);
     if (strpos($this->template, '*')) {
         $out = str_replace('*', $params['pass'], $out);
     }
     $out = str_replace('//', '/', $out);
     return $out;
 }
예제 #27
0
 public function processInstall($data)
 {
     if (empty($data['Plugin']['file']['name'])) {
         unset($data['Plugin']['file']);
     }
     if (empty($data['Theme']['file']['name'])) {
         unset($data['Theme']['file']);
     }
     $data = array_filter(Set::flatten($data));
     if (!$data) {
         throw new Exception(__d('installer', 'Nothing selected to install'));
     }
     switch (current(array_keys($data))) {
         case 'Theme.local':
             return InstallerLib::localTheme(current($data));
             break;
     }
     throw new Exception(__d('installer', 'Could not complete installation'));
 }
 /**
  * Validate submitted form
  *
  * @param Controller $controller Instantiating controller
  * @return boolean true if submitted form is valid
  */
 protected function _validatePost(Controller $controller)
 {
     if (empty($controller->request->data)) {
         return true;
     }
     $data = $controller->request->data;
     if (!isset($data['_Token']) || !isset($data['_Token']['fields']) || !isset($data['_Token']['unlocked'])) {
         return false;
     }
     $locked = '';
     $check = $controller->request->data;
     $token = urldecode($check['_Token']['fields']);
     $unlocked = urldecode($check['_Token']['unlocked']);
     if (strpos($token, ':')) {
         list($token, $locked) = explode(':', $token, 2);
     }
     unset($check['_Token']);
     $locked = explode('|', $locked);
     $unlocked = explode('|', $unlocked);
     $lockedFields = array();
     $fields = Set::flatten($check);
     $fieldList = array_keys($fields);
     $multi = array();
     foreach ($fieldList as $i => $key) {
         if (preg_match('/(\\.\\d+)+$/', $key)) {
             $multi[$i] = preg_replace('/(\\.\\d+)+$/', '', $key);
             unset($fieldList[$i]);
         }
     }
     if (!empty($multi)) {
         $fieldList += array_unique($multi);
     }
     $unlockedFields = array_unique(array_merge((array) $this->disabledFields, (array) $this->unlockedFields, $unlocked));
     foreach ($fieldList as $i => $key) {
         $isLocked = is_array($locked) && in_array($key, $locked);
         if (!empty($unlockedFields)) {
             foreach ($unlockedFields as $off) {
                 $off = explode('.', $off);
                 $field = array_values(array_intersect(explode('.', $key), $off));
                 $isUnlocked = $field === $off;
                 if ($isUnlocked) {
                     break;
                 }
             }
         }
         if ($isUnlocked || $isLocked) {
             unset($fieldList[$i]);
             if ($isLocked) {
                 $lockedFields[$key] = $fields[$key];
             }
         }
     }
     sort($unlocked, SORT_STRING);
     sort($fieldList, SORT_STRING);
     ksort($lockedFields, SORT_STRING);
     $fieldList += $lockedFields;
     $unlocked = implode('|', $unlocked);
     $check = Security::hash(serialize($fieldList) . $unlocked . Configure::read('Security.salt'));
     return $token === $check;
 }
예제 #29
0
 /**
  * Tests Set::expand
  *
  * @return void
  */
 public function testExpand()
 {
     $data = array('My', 'Array', 'To', 'Flatten');
     $flat = Set::flatten($data);
     $result = Set::expand($flat);
     $this->assertEquals($data, $result);
 }
예제 #30
0
 /**
  * Assertion Shortcut
  *   assert that all of the keys provided in $expect
  *   match keys/values in $result
  *
  * Flexible:
  *   order doesn't matter
  *   extra keys in $result don't matter
  *
  * so just pass into $expect the keys you care about, and the others will
  *   be ignored (useful for UUIDs, autoids, timestampes, etc)
  *
  * @param array $expect
  * @param array $result
  */
 public function assertArrayCompare($expect, $result, $message = 'sorry, the arrays did not match')
 {
     $expect = Set::flatten($expect);
     $result = Set::flatten($result);
     $compare = array_intersect_key($result, $expect);
     asort($expect);
     asort($compare);
     return $this->assertEquals($expect, $compare, $message);
 }