private function addAward() { $success = true; $errors = array(); $data = Arr::merge($this->sanitize($_POST), $_FILES); Upload::$default_directory = Kohana::config('myshot.basePath'); if ($stage_path = Upload::save($data['photo'])) { $award = $this->site->createAward($this->sanitize($data['name']), $data); foreach ($this->site->imageTypes as $imageType) { $name = $imageType->name; if ($name == self::FULL) { Library_Akamai::factory()->addToDir($stage_path, Kohana::config('akamai.honordir')); $award->addImage(self::FULL, $this->webPath($stage_path)); } else { if (ImageTypes::types()->{$name}) { $resized = $this->resizeHonor($stage_path, ImageTypes::types()->{$name}->size); $award->addImage($name, $this->webPath($resized)); } } } } else { $success = false; $errors[] = "Image failed to load."; } if ($success) { Message::set(Message::SUCCESS, 'You have successfully added an award.'); Request::instance()->redirect('admin/awards'); } else { Message::set(Message::ERROR, Arr::flatten($errors)); } }
private function add_category() { $category = ORM::factory('category'); if ($category->values($_POST)->check()) { $category->save(); Message::set(Message::SUCCESS, 'You have successfully added a category.'); Request::instance()->redirect('admin/categories'); } else { Message::set(Message::ERROR, Arr::flatten($category->validate()->errors('admin/category'))); } }
public static function flatten($array) { $flat = array(); foreach ($array as $key => $value) { if (is_array($value)) { $flat += Arr::flatten($value); } else { $flat[$key] = $value; } } return $flat; }
public static function server_local(array $params = array()) { $validation = Validation::factory($params)->rule('path', 'not_empty')->rule('path', 'is_dir')->rule('web', 'not_empty')->rule('url_type', 'in_array', array(':value', array(Flex\Storage\Server::URL_HTTP, Flex\Storage\Server::URL_SSL, Flex\Storage\Server::URL_STREAMING))); if (!$validation->check()) { throw new Kohana_Exception('Upload server local params had errors: :errors', array(':errors' => join(', ', Arr::flatten($validation->errors())))); } $server = new Flex\Storage\Server_Local($validation['path'], $validation['web']); if (isset($validation['url_type'])) { $server->url_type($validation['url_type']); } return $server; }
/** * Method to merge resources * It finds out all the controllers and adds the basenames to the acl config array * as resources only if the key doesnot already exists */ private function merge_resources() { $controllers = Kohana::list_files('classes/controller'); // controllers can also be nested, so just flatten the array $controllers = Arr::flatten($controllers); foreach ($controllers as $controller) { $resource = basename($controller, '.php'); if (self::is_resource_ignored($resource) || array_key_exists($resource, $this->_acl)) { continue; } $this->_acl[$resource] = array(); } ksort($this->_acl); return $this; }
/** * @param bool $parseActions * @param bool $forced */ static function routes($parseActions = TRUE, $forced = FALSE) { if ($forced || !static::$_routes) { $pathPrefix = 'classes' . DIRECTORY_SEPARATOR; $directoryPrefix = self::config('directory_prefix'); $path = rtrim($pathPrefix . 'Controller' . DIRECTORY_SEPARATOR . $directoryPrefix, DIRECTORY_SEPARATOR); $controllers = array_keys(Arr::flatten(Kohana::list_files($path))); $urlBase = self::config('route.url.base', 'api'); $urlPrefix = $urlBase . self::config('route.url.version', '/v{version}'); foreach ($controllers as $controller) { $className = str_replace([$pathPrefix, DIRECTORY_SEPARATOR, EXT], ['', '_', ''], $controller); self::getClassRoutes($className, $directoryPrefix, $urlPrefix, $parseActions); } Route::set('RestfulAPI\\Error', $urlBase . '(/<unknown>)', ['unknown' => '.*'])->filter([get_class(), 'error404']); static::$_routes = TRUE; } }
/** * Receive Messages From data provider * * @param string type Message type * @param string from From contact * @param string message Received Message * @param string to To contact * @param string title Received Message title * @param string data_provider_message_id Message ID * @return void */ public function receive($type, $from, $message, $to = NULL, $title = NULL, $data_provider_message_id = NULL) { $data_provider = $this->provider_name(); $contact_type = $this->contact_type; $usecase = service('factory.usecase')->get('messages', 'receive'); try { $usecase->setPayload(compact(['type', 'from', 'message', 'to', 'title', 'data_provider_message_id', 'data_provider', 'contact_type']))->interact(); } catch (Ushahidi\Core\Exception\NotFoundException $e) { throw new HTTP_Exception_404($e->getMessage()); } catch (Ushahidi\Core\Exception\AuthorizerException $e) { throw new HTTP_Exception_403($e->getMessage()); } catch (Ushahidi\Core\Exception\ValidatorException $e) { throw new HTTP_Exception_400('Validation Error: \':errors\'', array(':errors' => implode(', ', Arr::flatten($e->getErrors())))); } catch (\InvalidArgumentException $e) { throw new HTTP_Exception_400('Bad request: :error', array(':error' => $e->getMessage())); } }
/** * Gets list of instances of [CLI_Task] class. * * $catalog = CLI_Task_Info::get_list(); * * @param string $path path to root directory of tasks * @return array */ public static function get_list($path = CLI_Tasker::DIR_ROOT) { if (Kohana::$caching) { // Create cache key\tag for find task list $cache_key = __METHOD__ . '(' . $path . ')'; // Try load list from cache if ($catalog = Kohana::cache($cache_key)) { return $catalog; } } $catalog = Kohana::list_files($path); $catalog = Arr::flatten($catalog); $catalog = array_keys($catalog); if (Kohana::$caching) { // Cache task information Kohana::cache($cache_key, $catalog, 3600); } return $catalog; }
public function __construct(Request $req) { parent::__construct($req); $auth = Auth::instance(); if (!$auth->logged_in()) { $curr_url = URL::curr(); $this->redirect('auth/login?return_url=' . urlencode($curr_url)); } else { $this->user = $auth->get_user(); $menu = Kohana::config('menu'); $allmenu = Arr::flatten($menu); /*/ $this->permission = array_values($allmenu); $this->user_permission = $this->permission; /*/ $m_permit = Model::factory('permit'); $permission = $m_permit->getAll()->as_array(null, 'url'); $permission = array_merge($permission, array_values($allmenu)); $this->permission = array_unique($permission); $m_role = Model::factory('role'); $role_ids = explode(',', $this->user['role_id']); $permit_ids = $m_role->getAll(array('status' => 'normal', 'id' => array('in' => $role_ids)))->as_array(null, 'permit_ids'); if (!empty($permit_ids)) { $permit_ids = implode(',', $permit_ids); if ($permit_ids == '*') { $this->user_permission = $this->permission; } else { $permit_ids = array_unique(array_filter(explode(',', $permit_ids))); $this->user_permission = $m_permit->getAll(array('id' => array('in' => $permit_ids)))->as_array(null, 'url'); } } //*/ foreach ($menu as $name => $items) { foreach ($items as $sub_name => $url) { if (!in_array($url, $this->user_permission)) { unset($menu[$name][$sub_name]); } } } $this->user_menu = $menu; } }
/** * Retrieve a basic information about the API * * GET /api * * @return void */ public function action_get_index_collection() { $path = 'classes/Controller/Api'; $files = Arr::flatten(Kohana::list_files($path)); $trim = strlen($path); $endpoints = []; foreach ($files as $file => $path) { if (__FILE__ === $path) { continue; // skip the index } // remove the base path (up to Api/) and the .php extension $file = substr($file, $trim + 1, -4); // @todo this would be much more awesome if it gave back a URI $endpoints[] = strtolower($file); } sort($endpoints); $user = service('session.user'); $this->_response_payload = ['now' => date(DateTime::W3C), 'version' => static::$version, 'endpoints' => $endpoints, 'user' => ['id' => $user->id, 'username' => $user->username]]; }
public function action_save() { if (count($_POST) > 0) { $errors = NULL; try { $user = Auth::instance()->get_user(); $user = $user->update_user($_POST, array('password', 'email')); $user->save(); EmailHelper::notify($user, $this->request->post('password')); $this->redirect_to_albums(); } catch (ORM_Validation_Exception $e) { // todo: specify a real messages file here... // external errors are still in a sub-array, so we have to flatten // also the message is wrong - bug #3896 $errors = Arr::flatten($e->errors('hack')); } $this->show_profile_form($user, $errors); } else { $this->redirect_to_albums(); } }
public static function generate_tables() { $models = Kohana::list_files('classes/model'); $models = array_keys(Arr::flatten($models)); $tables = array(); $throughs = array(); foreach ($models as $name) { $name = str_replace(array('classes/model' . DIRECTORY_SEPARATOR, EXT), '', $name); $name = str_replace(DIRECTORY_SEPARATOR, '_', $name); $reflection = new ReflectionClass('Model_' . $name); if (preg_match('/^Base_/', $name)) { continue; } if ($reflection->isAbstract() or $name === 'App' or preg_match('/^(Auth_|User_Token)/', $name)) { continue; } $object_name = ORM::get_model_name($name); $model = ORM::factory($name); $labels = $model->labels(); $rules = $model->rules(); $belongs_to = $model->belongs_to(); $has_many = $model->has_many(); $table_name = $model->table_name(); $tables[$table_name] = $model->table_columns(); // through foreach ($has_many as $key => $values) { $through = Arr::get($values, 'through'); if ($through and !Arr::get($through, $tables) and preg_match('/^' . $table_name . '_/', $through)) { $farkey = ORM::get_model_name(str_replace($table_name . '_', '', $through)); $tables[$through] = array(strtolower($farkey) . '_id' => array('type' => 'int', 'data_type' => 'int', 'is_nullable' => FALSE), strtolower($object_name) . '_id' => array('type' => 'int', 'data_type' => 'int', 'is_nullable' => FALSE)); $throughs[] = $through; } } } foreach ($tables as $name => $value) { self::save_tables($name, $value, $throughs); } }
public function action_edit() { $contra = $_GET['contra']; //$contra = $this->request->param('contra'); $content = View::factory('contextoedit')->set('values', $_POST)->bind('errors', $errors)->bind('id', $id)->bind('contextos', $contextos)->bind('data', $data); $contextos = ORM::factory('contextos')->where('id', '=', $contra)->find(); $data = $contextos->as_array(); // if(!$contextos->loaded()){HTTP::redirect('contextos');} $contextos = ORM::factory('contextos')->find_all()->as_array(); //$categories = $categories->find_all()->as_array(); if (isset($_POST['submit'])) { $data[] = Arr::extract($_POST, array('nomModalidad', 'modaDescripcion', 'modaDescripcion', 'template')); $data = Arr::flatten($data); $contextos->values($data); try { $contextos->save(); HTTP::redirect('contextos'); } catch (ORM_Validation_Exception $e) { $errors = $e->errors('validation'); } } $this->template->page_title = 'contextos'; $this->template->content = $content; }
/** * Flatten a multi-dimensional array into a single level. * * @param array $array * @return array */ function array_flatten($array) { return Arr::flatten($array); }
/** * Get a flattened array of the items in the collection. * * @param int $depth * @return static */ public function flatten($depth = INF) { return new static(Arr::flatten($this->items, $depth)); }
private function validate_tags() { // Tag validation $errors = array(); $tags = ORM::factory('tag'); $tags_input = empty($_POST['tags']) ? array() : explode(',', $_POST['tags']); foreach ($tags_input as $tag) { $tag_array = array('tag' => $tag); $validate_tags = $tags->validate_create($tag_array); if (!$validate_tags->check()) { array_push($errors, $validate_tags->errors('tag')); } } return Arr::flatten($errors); }
/** * * @test * @dataProvider provider_flatten */ public function test_flatten($source, $expected) { $this->assertSame($expected, Arr::flatten($source)); }
public static function tests() { $files = Kohana::list_files('tests/tests', Functest_Tests::module_directories()); $files = Arr::flatten($files); return array_values(array_filter($files, function ($file) { return substr($file, -8) === 'Test.php'; })); }
/** * Returns the error messages. If no file is specified, the error message * will be the name of the rule that failed. When a file is specified, the * message will be loaded from "field/rule", or if no rule-specific message * exists, "field/default" will be used. If neither is set, the returned * message will be "file/field/rule". * * By default all messages are translated using the default language. * A string can be used as the second parameter to specified the language * that the message was written in. * * // Get errors from messages/forms/login.php * $errors = $Validation->errors('forms/login'); * * @uses JsonApiApplication::message * @param string $file file to load error messages from * @param mixed $translate translate the message * @return array */ public function errors($file = NULL, $translate = TRUE) { if ($file === NULL) { return $this->_errors; } $messages = array(); foreach ($this->_errors as $field => $set) { list($error, $params) = $set; $label = $this->_labels[$field]; if ($translate) { if (is_string($translate)) { $label = __($label, NULL, $translate); } else { $label = __($label); } } $values = array(':field' => $label, ':value' => Arr::get($this, $field)); if (is_array($values[':value'])) { $values[':value'] = implode(', ', Arr::flatten($values[':value'])); } if ($params) { foreach ($params as $key => $value) { if (is_array($value)) { $value = implode(', ', Arr::flatten($value)); } elseif (is_object($value)) { continue; } if (isset($this->_labels[$value])) { $value = $this->_labels[$value]; if ($translate) { if (is_string($translate)) { $value = __($value, NULL, $translate); } else { $value = __($value); } } } $values[':param' . ($key + 1)] = $value; } } if ($message = JsonApiApplication::message($file, "{$field}.{$error}") and is_string($message)) { } elseif ($message = JsonApiApplication::message($file, "{$field}.default") and is_string($message)) { } elseif ($message = JsonApiApplication::message($file, $error) and is_string($message)) { // Found a default message for this error } elseif ($message = JsonApiApplication::message('validation', $error) and is_string($message)) { // Found a default message for this error } else { // No message exists, display the path expected $message = "{$file}.{$field}.{$error}"; } if ($translate) { if (is_string($translate)) { $message = __($message, $values, $translate); } else { $message = __($message, $values); } } else { $message = strtr($message, $values); } $messages[$field] = $message; } return $messages; }
/** * Adds 'where' comparisons to the query based on params * * @return void */ protected function buildQueryWhere() { $builder = $this->getQueryBuilder(); $metadata = $this->getMetadata(); $fields = \Arr::flatten($this->param(), '->'); foreach ($fields as $field => $value) { if (in_array($field, $this->reserved_names)) { continue; } $alias = 'item'; $is_field = $is_association = false; // Check for NOT if ($negative = substr($value, 0, 1) == '!') { $value = substr($value, 1); } // Check for LIKE if ($like = substr($value, 0, 1) == '~') { $value = substr($value, 1); } // Check whether we're using an association if (strpos($field, '->') !== false) { // Attempt to process as a join field $parts = $this->parseJoinField($this->class, $field, $alias, '->'); if (is_array($parts)) { $is_field = true; $alias = $parts[0]; $field = $parts[1]; } } else { // Check the field exists $is_association = $metadata->hasAssociation($field); $is_field = $metadata->hasField($field); if (!$is_field && !$is_association) { // This might be a plural version of a field, in which case we can make it an "in array" $field = \Inflector::singularize($field); $is_association = $metadata->hasAssociation($field); $is_field = $metadata->hasField($field); $values = $this->expand($value); $value = count($values) == 1 ? $values[0] : implode(',', $values); } } if (!$is_field && !$is_association) { continue; } // Set up a field name to use for our parameter $fieldname = substr($alias, 1) . '_' . $field; // Support for "LIKE" if ($like && !$is_association) { $operator = $negative ? 'NOT LIKE' : 'LIKE'; // Check if it's a literal comparison (wrapped in double quotes) if ($literal = substr($value, 0, 1) == '"' && substr($value, -1) == '"') { $value = substr($value, 1, -1); } if (!$literal) { $values = explode(' ', trim($value)); foreach ($values as $num => $_value) { $_fieldname = $fieldname . '_' . $num; $builder->setParameter($_fieldname, "%{$_value}%")->andWhere("{$alias}.{$field} {$operator} :{$_fieldname}"); } } else { $builder->setParameter($fieldname, "%{$value}%")->andWhere("{$alias}.{$field} {$operator} :{$fieldname}"); } continue; } // Support for "in array" if (is_array($value) || strpos($value, ',') !== false) { $values = $this->expand($value); $operator = $negative ? 'NOT IN' : 'IN'; $builder->setParameter($fieldname, $values)->andWhere("{$alias}.{$field} {$operator}(:{$fieldname})"); continue; } // Standard comparison $operator = $negative ? '!=' : '='; $builder->setParameter($fieldname, $value)->andWhere("{$alias}.{$field} {$operator} :{$fieldname}"); } return $builder; }
/** * Tests Arr::flatten_assoc() with recursive arrays * * @test */ public function test_flatten_recursive_index() { $people = array(array("name" => "Jack", "age" => 21, "children" => array(array("name" => "Johnny", "age" => 4), array("name" => "Jimmy", "age" => 3))), array("name" => "Jill", "age" => 23)); $expected = array("0:name" => "Jack", "0:age" => 21, "0:children:0:name" => "Johnny", "0:children:0:age" => 4, "0:children:1:name" => "Jimmy", "0:children:1:age" => 3, "1:name" => "Jill", "1:age" => 23); $output = Arr::flatten($people, ':'); $this->assertEquals($expected, $output); }
/** * @return array */ protected function get_cfs_entity_files() { $files = array(); foreach (Kohana::$config->load('doctrine.entity_paths') as $path => $should_search) { if ($should_search) { $files = $files + Kohana::list_files('classes/' . $path, $this->getPaths()); } } return Arr::flatten($files); }
/** * Convert a multi-dimensional array into a single-dimensional array. * * $array = array('set' => array('one' => 'something'), 'two' => 'other'); * * // Flatten the array * $array = Arr::flatten($array); * * // The array will now be * array('one' => 'something', 'two' => 'other'); * * [!!] The keys of array values will be discarded. * * @param array $array array to flatten * @return array */ public static function flatten($array) { $is_assoc = Arr::is_assoc($array); $flat = array(); foreach ($array as $key => $value) { if (is_array($value)) { $flat = array_merge($flat, Arr::flatten($value)); } else { if ($is_assoc) { $flat[$key] = $value; } else { $flat[] = $value; } } } return $flat; }
/** * Normalize the $_FILES array and store the result in $files * * @return void */ public static function process($config = array()) { // process runtime config if (is_array($config)) { static::$config = array_merge(static::$config, $config); } // processed files array's static::$files = array(); $files = array(); // any files uploaded? if (empty($_FILES)) { throw new \FuelException('No file upload was initiated. Did you specify "enctype" in your <form> tag?'); } // normalize the multidimensional fields in the $_FILES array foreach ($_FILES as $name => $value) { if (is_array($value['name'])) { foreach ($value as $field => $content) { foreach (\Arr::flatten($content) as $element => $data) { $_FILES[$name . ':' . $element][$field] = $data; } } unset($_FILES[$name]); } } // normalize the $_FILES array foreach ($_FILES as $name => $value) { // store the file data $file = array('field' => $name, 'file' => $value['tmp_name']); if ($value['error']) { $file['error'] = true; $file['errors'][] = array('error' => $value['error']); } else { $file['error'] = false; $file['errors'] = array(); } unset($value['tmp_name']); $files[] = array_merge($value, $file); } // verify and augment the files data foreach ($files as $key => $value) { // add some filename details (pathinfo can't be trusted with utf-8 filenames!) $files[$key]['extension'] = ltrim(strrchr(ltrim($files[$key]['name'], '.'), '.'), '.'); if (empty($files[$key]['extension'])) { $files[$key]['filename'] = $files[$key]['name']; } else { $files[$key]['filename'] = substr($files[$key]['name'], 0, strlen($files[$key]['name']) - (strlen($files[$key]['extension']) + 1)); } // does this upload exceed the maximum size? if (!empty(static::$config['max_size']) and $files[$key]['size'] > static::$config['max_size']) { $files[$key]['error'] = true; $files[$key]['errors'][] = array('error' => static::UPLOAD_ERR_MAX_SIZE); } // add mimetype information if (!$files[$key]['error']) { $handle = finfo_open(FILEINFO_MIME_TYPE); $files[$key]['mimetype'] = finfo_file($handle, $value['file']); finfo_close($handle); if ($files[$key]['mimetype'] == 'application/octet-stream' and $files[$key]['type'] != $files[$key]['mimetype']) { $files[$key]['mimetype'] = $files[$key]['type']; } // make sure it contains something valid if (empty($files[$key]['mimetype'])) { $files[$key]['mimetype'] = 'application/octet-stream'; } } // check the file extension black- and whitelists if (!$files[$key]['error']) { if (in_array(strtolower($files[$key]['extension']), (array) static::$config['ext_blacklist'])) { $files[$key]['error'] = true; $files[$key]['errors'][] = array('error' => static::UPLOAD_ERR_EXT_BLACKLISTED); } elseif (!empty(static::$config['ext_whitelist']) and !in_array(strtolower($files[$key]['extension']), (array) static::$config['ext_whitelist'])) { $files[$key]['error'] = true; $files[$key]['errors'][] = array('error' => static::UPLOAD_ERR_EXT_NOT_WHITELISTED); } } // check the file type black- and whitelists if (!$files[$key]['error']) { // split the mimetype info so we can run some tests preg_match('|^(.*)/(.*)|', $files[$key]['mimetype'], $mimeinfo); if (in_array($mimeinfo[1], (array) static::$config['type_blacklist'])) { $files[$key]['error'] = true; $files[$key]['errors'][] = array('error' => static::UPLOAD_ERR_TYPE_BLACKLISTED); } if (!empty(static::$config['type_whitelist']) and !in_array($mimeinfo[1], (array) static::$config['type_whitelist'])) { $files[$key]['error'] = true; $files[$key]['errors'][] = array('error' => static::UPLOAD_ERR_TYPE_NOT_WHITELISTED); } } // check the file mimetype black- and whitelists if (!$files[$key]['error']) { if (in_array($files[$key]['mimetype'], (array) static::$config['mime_blacklist'])) { $files[$key]['error'] = true; $files[$key]['errors'][] = array('error' => static::UPLOAD_ERR_MIME_BLACKLISTED); } elseif (!empty(static::$config['mime_whitelist']) and !in_array($files[$key]['mimetype'], (array) static::$config['mime_whitelist'])) { $files[$key]['error'] = true; $files[$key]['errors'][] = array('error' => static::UPLOAD_ERR_MIME_NOT_WHITELISTED); } } // store the normalized and validated result static::$files[$key] = $files[$key]; // validation callback defined? if (array_key_exists('validate', static::$callbacks) and !is_null(static::$callbacks['validate'])) { // get the callback method $callback = static::$callbacks['validate'][0]; // call the callback if (is_callable($callback)) { $result = call_user_func_array($callback, array(&static::$files[$key])); if (is_numeric($result) and $result) { static::$files[$key]['error'] = true; static::$files[$key]['errors'][] = array('error' => $result); } } } // and add the message texts foreach (static::$files[$key]['errors'] as $e => $error) { empty(static::$files[$key]['errors'][$e]['message']) and static::$files[$key]['errors'][$e]['message'] = \Lang::get('upload.error_' . $error['error']); } } // determine the validate status of at least one uploaded file $valid = false; foreach (static::$files as $key => $value) { if ($value['error'] === false) { $valid = true; break; } } static::$valid = $valid; }
/** * Convert an error returned from the Validation object to a formatted message * * @access protected * @param array $errors_array (default: NULL) * @return string */ protected function _error_to_msg(array $errors_array = NULL) { $file = $this->config('validation_message_file'); $translate = $this->config('translate', FALSE); $errors = $errors_array !== NULL ? $errors_array : $this->_errors; if ($set = Arr::get($errors, $this->alias())) { $field = $this->alias(); list($error, $params) = $set; $label = $this->label(); if (!$label) { if ($title = $this->driver('get_title')) { $label = $title; } } if ($message = $this->get("error_messages.{$error}")) { // Found a locally-defined message for this error in this field } elseif ($file === FALSE) { // No message found in this field and no external message file $message = $error; } else { if ($message = Kohana::message($file, "{$field}.{$error}")) { // Found a message for this field and error } elseif ($message = Kohana::message($file, "{$field}.default")) { // Found a default message for this field } elseif ($message = Kohana::message($file, $error)) { // Found a default message for this error } else { // No message exists, display the path expected $message = "{$file}.{$field}.{$error}"; } // Start the translation values list $values = array(':field' => $label, ':value' => $this->val()); if ($params) { foreach ($params as $key => $value) { if (is_array($value)) { // All values must be strings $value = implode(', ', Arr::flatten($value)); } elseif (is_object($value)) { // Objects cannot be used in message files continue; } if ($field = $this->parent(TRUE)->find($value, TRUE)) { // Use a field's label if we're referencing a field $value = $field->label(); } // Add each parameter as a numbered value, starting from 1 $values[':param' . ($key + 1)] = $value; } } $tr_vals = $values; // Fix problem that occurs when :value is an array // by creating :value, :value1, :value2, etc. params if (is_array(Arr::get($values, ':value'))) { $i = 1; foreach ($values[':value'] as $tr_val) { $key = $i === 1 ? ':value' : ':value' . $i; $tr_vals[$key] = $tr_val; $i++; } } // Send the message through strtr $message = strtr($message, $tr_vals); } return $translate === TRUE ? __($message) : $message; } return FALSE; }
/** * Return the html for the errors for a given field * @param string $name * @return string */ public function errors($name) { $errors = join(', ', Arr::flatten((array) $this->object()->errors($name))); return $errors ? "<span style=\"display:inline-block;\" class=\"text-error\">{$errors}</span>" : ''; }
/** * Tests Arr::flatten() * * @test */ public function test_flatten() { $indexed = array(array('a'), array('b'), array('c')); $expected = array("0_0" => "a", "1_0" => "b", "2_0" => "c"); $output = Arr::flatten($indexed, '_'); $this->assertEquals($expected, $output); }
/** * Execute the usecase that the controller prepared. * @throws HTTP_Exception_400 * @throws HTTP_Exception_403 * @throws HTTP_Exception_404 * @return void */ protected function _execute_usecase() { try { // Attempt to execute the usecase to get the response $this->_response_payload = $this->_usecase->interact(); } catch (Ushahidi\Core\Exception\NotFoundException $e) { throw new HTTP_Exception_404($e->getMessage()); } catch (Ushahidi\Core\Exception\AuthorizerException $e) { throw new HTTP_Exception_403($e->getMessage()); } catch (Ushahidi\Core\Exception\ValidatorException $e) { throw new HTTP_Exception_400('Validation Error: \':errors\'', [':errors' => implode(', ', Arr::flatten($e->getErrors()))]); } catch (\InvalidArgumentException $e) { throw new HTTP_Exception_400('Bad request: :error', [':error' => $e->getMessage()]); } }
/** * Returns the error messages. If no file is specified, the error message * will be the name of the rule that failed. When a file is specified, the * message will be loaded from "field/rule", or if no rule-specific message * exists, "field/default" will be used. If neither is set, the returned * message will be "file/field/rule". * * By default all messages are translated using the default language. * A string can be used as the second parameter to specified the language * that the message was written in. * * // Get errors from messages/forms/login.php * $errors = $Validation->errors('forms/login'); * * @uses Kohana::message * @param string file to load error messages from * @param mixed translate the message * @return array */ public function errors($file = NULL, $translate = TRUE) { if ($file === NULL) { // Return the error list return $this->_errors; } // Create a new message list $messages = array(); foreach ($this->_errors as $field => $set) { list($error, $params) = $set; // Get the label for this field $label = $this->_labels[$field]; if ($translate) { if (is_string($translate)) { // Translate the label using the specified language $label = __($label, NULL, $translate); } else { // Translate the label $label = __($label); } } // Start the translation values list $values = array(':field' => $label, ':value' => Arr::get($this, $field)); if (is_array($values[':value'])) { // All values must be strings $values[':value'] = implode(', ', Arr::flatten($values[':value'])); } if ($params) { foreach ($params as $key => $value) { if (is_array($value)) { // All values must be strings $value = implode(', ', Arr::flatten($value)); } elseif (is_object($value)) { // Objects cannot be used in message files continue; } // Check if a label for this parameter exists if (isset($this->_labels[$value])) { // Use the label as the value, eg: related field name for "matches" $value = $this->_labels[$value]; if ($translate) { if (is_string($translate)) { // Translate the value using the specified language $value = __($value, NULL, $translate); } else { // Translate the value $value = __($value); } } } // Add each parameter as a numbered value, starting from 1 $values[':param' . ($key + 1)] = $value; } } if ($message = Kohana::message($file, "{$field}.{$error}")) { // Found a message for this field and error } elseif ($message = Kohana::message($file, "{$field}.default")) { // Found a default message for this field } elseif ($message = Kohana::message($file, $error)) { // Found a default message for this error } elseif ($message = Kohana::message('validation', $error)) { // Found a default message for this error } else { // No message exists, display the path expected $message = "{$file}.{$field}.{$error}"; } if ($translate) { if (is_string($translate)) { // Translate the message using specified language $message = __($message, $values, $translate); } else { // Translate the message using the default language $message = __($message, $values); } } else { // Do not translate, just replace the values $message = strtr($message, $values); } // Set the message for this field $messages[$field] = $message; } return $messages; }
/** * Parses HTTP Header values and creating an appropriate object * depending on type; i.e. accept-type, accept-char, cache-control etc. * * $header_values_array = HTTP_Header::parse_header_values(array('cache-control' => 'max-age=200; public')); * * @param array $header_values Values to parse * @param array $header_commas_allowed Header values where commas are not delimiters (usually date) * @return array */ public static function parse_header_values(array $header_values, array $header_commas_allowed = array('user-agent', 'date', 'expires')) { /** * @see http://www.w3.org/Protocols/rfc2616/rfc2616.html * * HTTP header declarations should be treated as case-insensitive */ $header_values = array_change_key_case($header_values, CASE_LOWER); // Foreach of the header values applied foreach ($header_values as $key => $value) { if (is_array($value)) { $values = array(); if (Arr::is_assoc($value)) { foreach ($value as $k => $v) { $values[] = HTTP_Header::parse_header_values($v); } } else { // RFC 2616 allows multiple headers with same name if they can be // concatinated using commas without altering the original message. // This usually occurs with multiple Set-Cookie: headers $array = array(); foreach ($value as $k => $v) { // Break value into component parts $v = explode(';', $v); // Do some nasty parsing to flattern the array into components, // parsing key values $array = Arr::flatten(array_map('HTTP_Header_Value::parse_key_value', $v)); // Get the K/V component and extract the first element $key_value_component = array_slice($array, 0, 1, TRUE); array_shift($array); // Create the HTTP_Header_Value component array $http_header['key'] = key($key_value_component); $http_header['value'] = current($key_value_component); $http_header['properties'] = $array; // Create the HTTP_Header_Value $values[] = new HTTP_Header_Value($http_header); } } // Assign HTTP_Header_Value array to the header $header_values[$key] = $values; continue; } // If the key allows commas or no commas are found if (in_array($key, $header_commas_allowed) or strpos($value, ',') === FALSE) { // If the key is user-agent, we don't want to parse the string if ($key === 'user-agent') { $header_values[$key] = new HTTP_Header_Value($value, TRUE); } else { $header_values[$key] = new HTTP_Header_Value($value); } // Move to next header continue; } // Create an array of the values and clear any whitespace $value = array_map('trim', explode(',', $value)); $parsed_values = array(); // Foreach value foreach ($value as $v) { $v = new HTTP_Header_Value($v); // Convert the value string into an object if ($v->key === NULL) { $parsed_values[] = $v; } else { $parsed_values[$v->key] = $v; } } // Apply parsed value to the header $header_values[$key] = $parsed_values; } // Return the parsed header values return $header_values; }