Ejemplo n.º 1
0
 public function get_user_info(Token_Access $token)
 {
     $url = 'https://identity.x.com/xidentity/resources/profile/me?' . http_build_query(array('oauth_token' => $token->access_token));
     $user = json_decode(file_get_contents($url));
     $user = $user->identity;
     return array('uid' => $user['userId'], 'nickname' => \Inflector::friendly_title($user['fullName'], '_', true), 'name' => $user['fullName'], 'first_name' => $user['firstName'], 'last_name' => $user['lastName'], 'email' => $user['emails'][0], 'location' => $user->addresses[0], 'image' => null, 'description' => null, 'urls' => array('PayPal' => null));
 }
Ejemplo n.º 2
0
 /**
  * Sets site specific stuff for admin, 
  * @param  array $settings Settings to enter into config
  * @return bool success or fail 
  */
 public static function initialSetup($title = null, $identifier = null)
 {
     static::ensureMinimumSetup();
     if (\Fuel::$is_cli) {
         while (empty($title)) {
             $title = \Cli::prompt('Website Title');
             if (empty($title)) {
                 \Cli::error('You must enter a site title');
             }
         }
         while (empty($identifier)) {
             $identifier = \Cli::prompt('Unique Identifier', str_replace('_', '', \Inflector::friendly_title($title, '_', true)));
             if (empty($identifier)) {
                 \Cli::error('You must enter a unique identifier for this site');
             }
         }
     }
     $config_path = APPPATH . 'config/cmf.php';
     $db_config_path = APPPATH . 'config/db.php';
     $config = \Config::load($config_path, false, true);
     $db_config = \Config::load($db_config_path, false, true);
     $config['install'] = false;
     $config['admin']['title'] = $title;
     $db_config['doctrine2']['cache_namespace'] = $identifier;
     if ($config_saved = \Config::save($config_path, $config)) {
         \Config::load('cmf', true, true);
     }
     if ($db_config_saved = \Config::save($db_config_path, $db_config)) {
         \Config::load('db', true, true);
     }
     static::cleanUpConfig($config_path);
     static::cleanUpConfig($db_config_path);
     return $config_saved && $db_config_saved;
 }
Ejemplo n.º 3
0
 public static function displayForm($value, &$settings, $model)
 {
     $settings = static::settings($settings);
     if (!is_array($value)) {
         $value = array();
     }
     // Search input or
     $searchInput = \Form::input($settings['mapping']['fieldName'] . '[search]', null, array('class' => 'input input-xxlarge search-input', 'placeholder' => \Lang::get('admin.common.map_search_placeholder')));
     $searchButton = \Form::button('mapsearch', \Lang::get('admin.verbs.search'), array('class' => 'btn btn-primary'));
     $searchInput = html_tag('div', array('class' => 'form form-inline search-form'), $searchInput . $searchButton);
     // Hidden inputs
     $latInput = \Form::hidden($settings['mapping']['fieldName'] . '[lat]', \Arr::get($value, 'lat'), array('class' => 'lat'));
     $lngInput = \Form::hidden($settings['mapping']['fieldName'] . '[lng]', \Arr::get($value, 'lng'), array('class' => 'lng'));
     $zoomInput = \Form::hidden($settings['mapping']['fieldName'] . '[zoom]', \Arr::get($value, 'zoom'), array('class' => 'zoom'));
     // Other elements
     $required = isset($settings['required']) ? $settings['required'] : false;
     $label_text = $settings['title'] . ($required ? ' *' : '');
     $label = \Form::label($label_text);
     $mapDiv = html_tag('div', array('class' => 'map', 'id' => \Inflector::friendly_title($settings['mapping']['fieldName'], '-', true) . '-bing-map'), ' ');
     // Check that we have an API key
     if (empty($settings['api_key'])) {
         $content = $label . '<div class="well"><p>' . \Lang::get('admin.bing.api_key_not_set') . '</p></div>';
     } else {
         $content = $label . $searchInput . $latInput . $lngInput . $zoomInput . $mapDiv;
     }
     $content = html_tag('div', array('class' => 'controls control-group field-type-bing-map', 'data-field-name' => $settings['mapping']['fieldName']), $content);
     return array('content' => $content, 'js_data' => $settings);
 }
Ejemplo n.º 4
0
 public function get_user_info(Token_Access $token)
 {
     // define the get user information token
     $url = 'https://apis.live.net/v5.0/me?' . http_build_query(array('access_token' => $token->access_token));
     // perform network request
     $user = json_decode(file_get_contents($url));
     // create a response from the request and return it
     return array('uid' => $user->id, 'name' => $user->name, 'email' => isset($user->emails->preferred) ? $user->emails->preferred : null, 'nickname' => \Inflector::friendly_title($user->name, '-', true), 'locale' => $user->locale, 'urls' => array('Windows Live' => $user->link));
 }
Ejemplo n.º 5
0
 public function action_add($id = null)
 {
     $this->data['isUpdate'] = $isUpdate = $id !== null ? true : false;
     // Prepare form fieldset
     $form = \Fieldset::forge('category_form', array('form_attributes' => array('class' => 'form-horizontal special')));
     $form->add_model('Blog\\Model_Category');
     $form->add('add', '', array('type' => 'submit', 'value' => $isUpdate ? __('backend.edit') : __('backend.add'), 'class' => 'btn btn-primary'));
     // Get or create the post
     if ($isUpdate) {
         $this->data['category'] = $category = Model_Category::find($id);
         $this->dataGlobal['pageTitle'] = __('backend.category.edit');
     } else {
         $this->data['category'] = $category = Model_Category::forge();
         $this->dataGlobal['pageTitle'] = __('backend.category.add');
     }
     $form->populate($category);
     // If POST submit
     if (\Input::post('add')) {
         $form->validation()->run();
         if (!$form->validation()->error()) {
             // Populate the category
             $category->from_array(array('name' => $form->validated('name'), 'slug' => $form->validated('slug') != '' ? \Inflector::friendly_title($form->validated('slug'), '-', true) : \Inflector::friendly_title($form->validated('name'), '-', true), 'parent_id' => $form->validated('parent_id')));
             if ($category->save()) {
                 // Delete cache
                 \Cache::delete('sidebar');
                 // Category Post count update
                 foreach (Model_Category::find('all') as $category) {
                     $category->post_count = count($category->posts);
                     $category->save();
                 }
                 if ($isUpdate) {
                     //						\Messages::success(__('backend.category.edited'));
                     \Session::set_flash('success', __('backend.category.edited'));
                 } else {
                     //						\Messages::success(__('backend.category.added'));
                     \Session::set_flash('success', __('backend.category.added'));
                 }
                 \Response::redirect_back(\Router::get('admin_category'));
             } else {
                 //					\Messages::error(__('error'));
                 \Session::set_flash('error', __('error'));
             }
         } else {
             // Output validation errors
             foreach ($form->validation()->error() as $error) {
                 echo $error;
                 //					\Messages::error($error);
                 \Session::set_flash('error', $error);
             }
         }
     }
     $form->repopulate();
     $this->data['form'] = $form;
     return \Response::forge(\View::forge('backend/category/add')->set($this->data, null, false));
 }
Ejemplo n.º 6
0
 /**
  * Creates a new unique slug and update the object
  *
  * @param   Model  The object
  * @return  void
  */
 public function before_update(Model $obj)
 {
     // determine the slug
     $properties = (array) $this->_source;
     $source = '';
     foreach ($properties as $property) {
         $source .= '-' . $obj->{$property};
     }
     $slug = \Inflector::friendly_title(substr($source, 1), '-', true);
     // update it if it's different from the current one
     $obj->{$this->_property} === $slug or $this->before_insert($obj);
 }
Ejemplo n.º 7
0
 public function get_user_info(OAuth_Consumer $consumer, OAuth_Token $token)
 {
     // Create a new GET request with the required parameters
     $request = Request::forge('resource', 'GET', 'https://www.google.com/m8/feeds/contacts/default/full?max-results=1&alt=json', array('oauth_consumer_key' => $consumer->key, 'oauth_token' => $token->access_token));
     // Sign the request using the consumer and token
     $request->sign($this->signature, $consumer, $token);
     $response = json_decode($request->execute(), true);
     // Fetch data parts
     $email = \Arr::get($response, 'feed.id.$t');
     $name = \Arr::get($response, 'feed.author.0.name.$t');
     $name == '(unknown)' and $name = $email;
     return array('uid' => $email, 'nickname' => \Inflector::friendly_title($name), 'name' => $name, 'email' => $email, 'location' => null, 'image' => null, 'description' => null, 'urls' => array());
 }
Ejemplo n.º 8
0
 public function action_add($id = null)
 {
     $this->data['isUpdate'] = $isUpdate = $id !== null ? true : false;
     // Prepare form fieldset
     $form = \Fieldset::forge('post_form', array('form_attributes' => array('class' => 'form-horizontal')));
     $form->add_model('Model_Post');
     $form->add('add', '', array('type' => 'submit', 'value' => $isUpdate ? __('backend.edit') : __('backend.add'), 'class' => 'btn btn-primary'));
     // Get or create the post
     if ($isUpdate) {
         $this->data['post'] = $post = \Model_Post::find($id);
         $this->dataGlobal['pageTitle'] = __('backend.post.edit');
     } else {
         $this->data['post'] = $post = \Model_Post::forge();
         $this->dataGlobal['pageTitle'] = __('backend.post.add');
     }
     $form->populate($post);
     // If POST submit
     if (\Input::post('add')) {
         $form->validation()->run();
         if (!$form->validation()->error()) {
             // Populate the post
             $post->from_array(array('name' => $form->validated('name'), 'slug' => $form->validated('slug') != '' ? \Inflector::friendly_title($form->validated('slug')) : \Inflector::friendly_title($form->validated('name')), 'category_id' => $form->validated('category_id'), 'user_id' => $form->validated('user_id'), 'content' => $form->validated('content')));
             if ($post->save()) {
                 // Delete cache
                 \Cache::delete('sidebar');
                 // Category Post count update
                 foreach (\Model_Category::find('all') as $category) {
                     $category->post_count = count($category->posts);
                     $category->save();
                 }
                 if ($isUpdate) {
                     \Messages::success(__('backend.post.edited'));
                 } else {
                     \Messages::success(__('backend.post.added'));
                 }
                 \Response::redirect_back(\Router::get('admin_post'));
             } else {
                 \Messages::error(__('error'));
             }
         } else {
             // Output validation errors
             foreach ($form->validation()->error() as $error) {
                 \Messages::error($error);
             }
         }
     }
     $form->repopulate();
     $this->data['form'] = $form;
     $this->theme->set_partial('content', 'backend/post/add')->set($this->data, null, false);
 }
Ejemplo n.º 9
0
 /**
  * Generates sellers.
  *
  * @return void
  */
 protected static function sellers()
 {
     $date = date("Y-m-d H:i:s", self::BEGIN_DATETIME);
     $companies = array('Stella Labs, Inc', 'Star Point Industries');
     foreach ($companies as $company) {
         $seller = \Service_Seller::create($company, array('contact' => array('company_name' => $company, 'email' => 'support@' . \Inflector::friendly_title($company) . '.com', 'address' => mt_rand(1, 5000) . ' Quail Springs Pkwy', 'city' => 'Oklahoma City', 'state' => 'Oklahoma', 'zip' => mt_rand(10000, 99999), 'country' => 'US'), 'created_at' => $date));
         if ($seller) {
             self::$sellers[] = $seller;
             // Link the seller to the gateway.
             \Service_Gateway::link(self::$gateway, $seller);
         }
     }
     \Cli::write('Seller Simulation Complete', 'green');
 }
Ejemplo n.º 10
0
 protected function _get_slug()
 {
     $slug = \Inflector::friendly_title($this->name, '_', true);
     $same = $this->query()->where('slug', 'LIKE', $slug . '%')->where('enum_id', $this->enum_id)->get();
     // make sure our slug is unique
     if (!empty($same)) {
         $max = -1;
         foreach ($same as $record) {
             if (preg_match('/^' . $slug . '(?:_([0-9]+))?$/', $record->slug, $matches)) {
                 $index = isset($matches[1]) ? (int) $matches[1] : 0;
                 $max < $index and $max = $index;
             }
         }
         $max < 0 or $slug .= '_' . ($max + 1);
     }
     return $slug;
 }
Ejemplo n.º 11
0
 public static function findOne($username)
 {
     $collection = MongoConnection::instance()->collection('owners');
     $user = $collection->findOne(function ($query) use($username) {
         /** @var \League\Monga\Query\Find $query */
         $query->where('_id', $username);
     });
     $petResult = MongoConnection::instance()->collection('pets')->find(function ($query) use($user) {
         /** @var \League\Monga\Query\Find $query */
         $query->andWhereIn('_id', $user['pets']);
     });
     $pets = [];
     foreach ($petResult as $pet) {
         $petInfo = $pet;
         $petInfo['name_slug'] = \Inflector::friendly_title($pet['name']);
         $pets[] = $petInfo;
     }
     $user['pets'] = $pets;
     return $user;
 }
Ejemplo n.º 12
0
 /**
  * Creates a unique slug and adds it to the object
  *
  * @param   Model  The object
  * @return  void
  */
 public function before_insert(Model $obj)
 {
     $properties = (array) $this->_source;
     $source = '';
     foreach ($properties as $property) {
         $source .= '-' . $obj->{$property};
     }
     $slug = \Inflector::friendly_title(substr($source, 1), '-', true);
     $same = $obj->query()->where($this->_property, 'like', $slug . '%')->get();
     if (!empty($same)) {
         $max = -1;
         foreach ($same as $record) {
             if (preg_match('/^' . $slug . '(?:-([0-9]+))?$/', $record->{$this->_property}, $matches)) {
                 $index = isset($matches[1]) ? (int) $matches[1] : 0;
                 $max < $index and $max = $index;
             }
         }
         $max < 0 or $slug .= '-' . ($max + 1);
     }
     $obj->{$this->_property} = $slug;
 }
Ejemplo n.º 13
0
 public function get()
 {
     if ($this->video_id) {
         try {
             // If value exists in cache ve just return it
             $content = \Cache::get(\Inflector::friendly_title($this->video_id));
             return $content;
         } catch (\CacheNotFoundException $e) {
             // Value not in cache
             $request = \App\Curl::forge();
             $request->cUrl(false);
             $response = $request->get($this->url['first_part'] . $this->video_id . $this->url['second_part']);
             if ($array = $request->is_json($response, true)) {
                 $return = array('id' => $this->video_id, 'link' => $array->entry->link[0]->href, 'title' => $array->entry->title->{'$t'}, 'description' => $array->entry->{'media$group'}->{'media$description'}->{'$t'}, 'duration' => $array->entry->{'media$group'}->{'media$content'}[0]->duration, 'thumbnail' => array('small' => $array->entry->{'media$group'}->{'media$thumbnail'}[0]->url, 'middle' => $array->entry->{'media$group'}->{'media$thumbnail'}[1]->url, 'large' => $array->entry->{'media$group'}->{'media$thumbnail'}[2]->url));
                 // Save value in cache for future use
                 \Cache::set(\Inflector::friendly_title($this->video_id), $return, 3600 * 24);
                 return $return;
             }
         }
     }
     return false;
 }
Ejemplo n.º 14
0
 public function action_create($id = null)
 {
     if (Input::method() == 'POST') {
         $val = Model_Post::validate('create');
         if ($val->run()) {
             $post = Model_Post::forge(array('title' => Input::post('title'), 'slug' => Inflector::friendly_title(Input::post('title'), '-', true), 'summary' => Input::post('summary'), 'body' => Input::post('body'), 'user_id' => Input::post('user_id')));
             if ($post and $post->save()) {
                 Session::set_flash('success', 'Added post #' . $post->id . '.');
                 Response::redirect('admin/posts');
             } else {
                 Session::set_flash('error', 'Could not save post.');
             }
         } else {
             Session::set_flash('error', $val->show_errors());
         }
     }
     $this->template->title = "Create Post";
     $view = View::forge('admin/posts/create');
     // Set some data
     $view->set_global('users', Arr::assoc_to_keyval(Model_User::find('all'), 'id', 'username'));
     $this->template->content = $view;
 }
Ejemplo n.º 15
0
 public function action_base64_encode_image()
 {
     if ($_POST) {
         $asciiFormat = Inflector::ascii(Input::post('filename'));
         $webSafeName = Inflector::friendly_title($asciiFormat, '_', true);
         $uploadLocation = 'assets/img/upload/';
         $config = array('auto_process' => 'false', 'path' => DOCROOT . $uploadLocation, 'ext_whitelist' => array('img', 'jpg', 'jpeg', 'gif', 'png'), 'new_name' => $webSafeName, 'normalize' => true, 'change_case' => 'lower', 'auto_rename' => false, 'overwrite' => true);
         // process the uploaded files in $_FILES
         Upload::process($config);
         // if there are any valid files
         if (Upload::is_valid()) {
             // save them according to the config
             Upload::save();
             // Grab the file extension
             $uploadedFile = Upload::get_files(0);
             $filename = $webSafeName . '.' . $uploadedFile['extension'];
             $input_file = $uploadedFile['saved_to'] . $uploadedFile['saved_as'];
             $image64Encoded = $this->_base64_encode_image($input_file, $uploadedFile['extension']);
             $asset = Model_Asset::forge(array('name' => $uploadedFile['saved_as'], 'uri' => $uploadLocation, 'type' => $uploadedFile['extension']));
             $asset->save();
             return '<img src="' . $image64Encoded . '" />';
         } else {
             // and process any errors
             foreach (Upload::get_errors() as $key => $file) {
                 // $file is an array with all file information,
                 // $file['errors'] contains an array of all error occurred
                 // each array element is an an array containing 'error' and 'message'
                 //                Session::set_flash('error', $file['errors'] );
                 echo 'Error ' . $key . ' - ';
                 print_r($file['errors']);
                 echo ' <br />';
             }
             die;
         }
     }
     return;
 }
Ejemplo n.º 16
0
 public function test_friendly_title_allow_non_ascii()
 {
     $output = Inflector::friendly_title('وقود هو مجتمع مدفوعة إطار شبكة الإنترنت', '-', false, true);
     $expected = 'وقود-هو-مجتمع-مدفوعة-إطار-شبكة-الإنترنت';
     $this->assertEquals($expected, $output);
 }
Ejemplo n.º 17
0
 /**
  * Decides which fields the query should select based on params
  *
  * @return void
  */
 protected function buildQuerySelect($alias = 'item', $target_class = null)
 {
     $target_class = $target_class ?: $this->class;
     $builder = $this->getQueryBuilder();
     $metadata = $target_class::metadata();
     // If it's just one field we need, select only the bare essentials
     if ($this->field) {
         $partial_fields = array('id');
         if ($metadata->hasField($this->field)) {
             $partial_fields[] = $this->field;
         } else {
             $builder->leftJoin("{$alias}." . $this->field, $this->field)->addSelect($this->field);
         }
         $builder->addSelect("PARTIAL {$alias}.{" . implode(',', $partial_fields) . "}");
         return;
     }
     // Select the root item
     $builder->addSelect($alias);
     // Select its associations
     foreach ($metadata->getAssociationNames() as $assoc) {
         if ($metadata->isSingleValuedAssociation($assoc)) {
             // If it's a single association, join it and select it
             $assoc_class = $metadata->getAssociationTargetClass($assoc);
             $assoc_alias = \Inflector::friendly_title("{$target_class} {$assoc}", '_', true);
             // Only join if it hasn't been done already
             if (!in_array($assoc_alias, $this->joined)) {
                 $builder->leftJoin("{$alias}.{$assoc}", $assoc_alias);
                 $this->joined[] = $assoc_alias;
                 $this->buildQuerySelect($assoc_alias, $assoc_class);
                 $this->hydrateCollectionsForClass($assoc_class);
             }
         }
     }
     // Schedule hydration to happen for collections in this class - it's faster than joining and selecting them
     $this->hydrateCollectionsForClass($target_class);
 }
Ejemplo n.º 18
0
 public function action_create()
 {
     \View::set_global('title', 'Add New');
     if (\Input::post()) {
         $val = Model_Team::validate('create');
         // Upload image and display errors if there are any
         $image = $this->upload_image();
         if (!$image['exists'] && \Config::get('details.image.required', false) && empty($item->image)) {
             // No previous images and image is not selected and it is required
             \Messages::error('<strong>There was an error while trying to upload member image</strong>');
             \Messages::error('You have to select image');
         } elseif ($image['errors']) {
             \Messages::error('<strong>There was an error while trying to upload member image</strong>');
             foreach ($image['errors'] as $error) {
                 \Messages::error($error);
             }
         }
         if ($val->run() && $image['is_valid'] && !(!$image['exists'] && \Config::get('details.image.required', false))) {
             // Get POST values
             $insert = \Input::post();
             // Prepare some values
             $insert['published_at'] = !empty($insert['published_at']) ? strtotime($insert['published_at']) : \Date::forge()->get_timestamp();
             $insert['active_from'] = !empty($insert['active_from']) ? strtotime($insert['active_from']) : NULL;
             $insert['active_to'] = !empty($insert['active_to']) ? strtotime($insert['active_to']) : NULL;
             if ($insert['status'] != 2) {
                 unset($insert['active_from']);
                 unset($insert['active_to']);
             }
             $item = Model_Team::forge($insert);
             try {
                 $item->save();
                 // Validate and insert team slug into SEO database table
                 $val_seo = Model_Seo::validate('create_seo');
                 $insert_seo = array('content_id' => $item->id, 'slug' => \Inflector::friendly_title($item->name, '-', true));
                 while (!$val_seo->run($insert_seo)) {
                     $insert_seo['slug'] = \Str::increment($insert_seo['slug'], 1, '-');
                 }
                 $item_seo = Model_Seo::forge($insert_seo);
                 $item_seo->save();
                 // END OF: SEO
                 // Insert team images
                 if ($this->_image_data) {
                     $item_image = array(array('id' => 0, 'data' => array('content_id' => $item->id, 'image' => $this->_image_data[0]['saved_as'], 'alt_text' => \Input::post('alt_text', ''), 'cover' => 1, 'sort' => 1)));
                     Model_Team::bind_images($item_image);
                 }
                 \Messages::success('Member successfully created.');
                 \Response::redirect(\Input::post('update', false) ? \Uri::create('admin/team/update/' . $item->id) : \Uri::admin('current'));
             } catch (\Database_Exception $e) {
                 // show validation errors
                 \Messages::error('<strong>There was an error while trying to create member</strong>');
                 // Uncomment lines below to show database errors
                 $errors = $e->getMessage();
                 \Messages::error($errors);
             }
         } else {
             if ($val->error() != array()) {
                 // show validation errors
                 \Messages::error('<strong>There was an error while trying to create member</strong>');
                 foreach ($val->error() as $e) {
                     \Messages::error($e->get_message());
                 }
             }
         }
         // Delete uploaded image if there is team saving error
         if (isset($this->_image_data)) {
             $this->delete_image($this->_image_data[0]['saved_as']);
         }
     }
     \Theme::instance()->set_partial('content', $this->view_dir . 'create');
 }
Ejemplo n.º 19
0
 /**
  * Takes a resource name, works out whether it is a model and determines if it's singular or plural
  */
 public function action_render($name = null, $id = null, $action = null)
 {
     if (!$name) {
         throw new \HttpException('No resource was specified', \HttpException::BAD_REQUEST);
     }
     // Get singular and plural versions of the resource name
     $name = \Inflector::friendly_title($name, '_');
     $singular = \Inflector::singularize($name);
     $plural = \Inflector::pluralize($singular);
     $model = \Admin::getClassForTable($name);
     if (empty($model)) {
         $model = \Admin::getClassForTable($plural);
     }
     $controller = null;
     // If there isn't a custom controller for this, it must be a model, no?
     if (!class_exists($controller = 'Api\\Controller_' . \Inflector::classify($singular))) {
         if ($model) {
             $controller = 'Api\\Controller_Model';
         } else {
             throw new \HttpException('No resource named "' . $plural . '" could be found', \HttpException::NOT_FOUND);
         }
     }
     // Create an instance of the controller
     $controller = new $controller($this->request);
     $controller_refl = new \ReflectionClass($controller);
     // Authorise if necessary
     if ($controller_refl->hasProperty('secret') && $controller->secret) {
         $this->authorise();
     }
     // Execute the action on the controller, including calls to 'before' and 'after'
     $controller_refl->hasMethod('before') and $controller_refl->getMethod('before')->invoke($controller);
     // Treat model controllers a little bit differently...
     if ($controller instanceof Controller_Model) {
         $response = $controller_refl->getMethod('router')->invoke($controller, $action, array('name' => $name, 'singular' => $singular, 'plural' => $plural, 'model' => $model, 'id' => $id));
     } else {
         $response = $controller_refl->getMethod('router')->invoke($controller, $action, array($id));
     }
     $controller_refl->hasMethod('after') and $response = $controller_refl->getMethod('after')->invoke($controller, $response);
     //if There is a language add set header language
     if (!empty(\Config::get('language'))) {
         if ($response instanceof \Fuel\Core\Response) {
             $response->set_header('Content-Language', \Config::get('language'), true);
         } else {
             $this->response->set_header('Content-Language', \Config::get('language'), true);
         }
     }
     return $response;
 }
Ejemplo n.º 20
0
 /**
  * Creates a new slug (unique by default) and update the object
  *
  * @param  Model  Model object subject of this observer method
  */
 public function before_update(Model $obj)
 {
     // determine the slug
     $properties = (array) $this->_source;
     $source = '';
     foreach ($properties as $property) {
         $source .= $this->_separator . $obj->{$property};
     }
     $slug = \Inflector::friendly_title(substr($source, 1), $this->_separator, true);
     // update it if it's different from the current one
     // and is not manually assigned
     if ($obj->{$this->_property} !== $slug) {
         $overwrite = $this->_overwrite;
         if ($overwrite === false and !$obj->is_changed($this->_property)) {
             $this->_overwrite = true;
         }
         $this->before_insert($obj);
         $this->_overwrite = $overwrite;
     }
 }
Ejemplo n.º 21
0
 /**
  * Assign single or multiple $roles + $resources to have $type access
  * 
  * @static
  * @access	public
  * @param	mixed	$roles
  * @param	mixed	$resources
  * @param	string	$type
  * @return	bool
  * @throws	\Fuel_Exception
  */
 public static function allow($roles, $resources, $type = 'view')
 {
     if (!in_array($type, static::$_types)) {
         return false;
     }
     if (!is_array($roles)) {
         $roles = array($roles);
     }
     if (!is_array($resources)) {
         $resources = array($resources);
     }
     foreach ($roles as $role) {
         $role = \Inflector::friendly_title($role, '-', true);
         if (!in_array($role, static::$_roles)) {
             throw new \Fuel_Exception("Role {$role} does not exist.");
             continue;
         }
         foreach ($resources as $resource) {
             $resource = \Inflector::friendly_title($resource, '-', true);
             if (!in_array($resource, static::$_resources)) {
                 throw new \Fuel_Exception("Resource {$resource} does not exist.");
                 continue;
             }
             $id = $role . '/' . $resource;
             static::$_acl[$id] = $type;
         }
     }
     return true;
 }
Ejemplo n.º 22
0
 /**
  * A string stating the field's type
  * @return string
  */
 public static function type($settings = array())
 {
     return \Inflector::friendly_title(str_replace('CMF\\Field', '', get_called_class()), '-', true);
 }
Ejemplo n.º 23
0
 public function getOptionsSelect($model, $field = null, $values = array(), $attributes = array())
 {
     $options = \CMF::getOptions($model, $field);
     $field = \Arr::get($attributes, 'name', $field !== null ? $field : \Inflector::friendly_title($model));
     return \Form::select($field, $values, $options, $attributes);
 }
Ejemplo n.º 24
0
 protected function getFormTab($tab_index)
 {
     if (isset($this->content[$tab_index])) {
         return $this->content[$tab_index];
     }
     $tab_title = isset($this->tabs[$tab_index]) ? $this->tabs[$tab_index] : ucfirst($tab_index);
     return $this->content[$tab_index] = array('title' => $tab_title, 'slug' => \Inflector::friendly_title($tab_title, '-', true), 'groups' => array());
 }
Ejemplo n.º 25
0
 /**
  * renders the navigation
  *
  * @param   array   array with tag attribute settings
  * @access	public
  * @return	void
  */
 public static function render($type = 'default', array $attributes = array(), $header = false)
 {
     if (empty($type)) {
         return;
     }
     $links = \Config::get('navigation.' . $type, false);
     if (empty($links)) {
         throw new BootstrapException('Missing navigation links in config');
         return;
     }
     $callback = \Config::get('bootstrap.navigation_links_callback', null);
     if ($callback != null) {
         $links = $callback($links);
     }
     foreach ($links as $key => &$link) {
         if (empty($link['url'])) {
             $link['url'] = \Inflector::friendly_title($link['title'], '-', true);
         }
         // Set link to active if it matches the current page URI.
         if (!isset($link['active'])) {
             $link['active'] = $link['url'] == ltrim(\Input::uri(), '/');
         }
         if (empty($link['attributes'])) {
             $link['attributes'] = array();
         }
         $anchor_classs = \Config::get('bootstrap.navigation.anchor_class', true);
         if ($anchor_classs) {
             if (!isset($link['attributes']['class'])) {
                 $link['class'] = \Inflector::friendly_title($link['title'], '-', true);
             }
             $anchor_prefix = \Config::get('bootstrap.navigation.anchor_prefix', 'nav-');
             if (!empty($anchor_prefix)) {
                 $link['class'] = $anchor_prefix . $link['class'];
             }
         }
         if (!empty($link['class'])) {
             $link['attributes']['class'] = $link['class'];
         }
     }
     if (isset($attributes['class'])) {
         $attributes['class'] = 'nav ' . $attributes['class'];
     } else {
         $attributes['class'] = 'nav';
     }
     echo \View::forge('navigation', array('header' => $header, 'links' => $links, 'attributes' => array_to_attr($attributes)))->render();
 }
Ejemplo n.º 26
0
 /**
  * save uploaded file(s)
  *
  * @param	mixed	if int, $files element to move. if array, list of elements to move, if none, move all elements
  * @param	string	path to move to
  * @return	void
  */
 public static function save()
 {
     // path to save the files to
     $path = static::$config['path'];
     // files to save
     $files = array();
     // check for parameters
     if (func_num_args()) {
         foreach (func_get_args() as $param) {
             // string => new path to save to
             if (is_string($param)) {
                 $path = $param;
             } elseif (is_array($param)) {
                 $files = array();
                 foreach ($param as $key) {
                     if (isset(static::$files[(int) $key])) {
                         $files[(int) $key] = static::$files[(int) $key];
                     }
                 }
             } elseif (is_numeric($param)) {
                 if (isset(static::$files[$param])) {
                     $files = array(static::$files[$param]);
                 }
             }
         }
     } else {
         // save all files
         $files = static::$files;
     }
     // anything to save?
     if (empty($files)) {
         throw new Exception('No uploaded files are selected.');
     }
     // make sure we have a valid path
     $path = rtrim($path, DS) . DS;
     if (!is_dir($path) and (bool) static::$config['create_path']) {
         $oldumask = umask(0);
         @mkdir($path, static::$config['path_chmod'], true);
         umask($oldumask);
     }
     if (!is_dir($path)) {
         throw new Exception('Can\'t move the uploaded file. Destination path specified does not exist.');
     }
     // now that we have a path, let's save the files
     $oldumask = umask(0);
     foreach ($files as $key => $file) {
         // skip all files in error
         if ($file['error'] != 0) {
             continue;
         }
         // do we need to generate a random filename?
         if ((bool) static::$config['randomize']) {
             $filename = md5(serialize($file));
         } else {
             $filename = $file['filename'];
             if ((bool) static::$config['normalize']) {
                 $filename = \Inflector::friendly_title($filename, '_');
             }
         }
         // array with the final filename
         $save_as = array(static::$config['prefix'], $filename, static::$config['suffix'], '', '.', empty(static::$config['extension']) ? $file['extension'] : static::$config['extension']);
         // remove the dot if no extension is present
         if (empty($save_as[5])) {
             $save_as[4] = '';
         }
         // need to modify case?
         switch (static::$config['change_case']) {
             case 'upper':
                 $save_as = array_map(function ($var) {
                     return strtoupper($var);
                 }, $save_as);
                 break;
             case 'lower':
                 $save_as = array_map(function ($var) {
                     return strtolower($var);
                 }, $save_as);
                 break;
             default:
                 break;
         }
         // check if the file already exists
         if (file_exists($path . implode('', $save_as))) {
             if ((bool) static::$config['auto_rename']) {
                 $counter = 0;
                 do {
                     $save_as[3] = '_' . ++$counter;
                 } while (file_exists($path . implode('', $save_as)));
             } else {
                 if (!(bool) static::$config['overwrite']) {
                     static::$files[$key]['error'] = static::UPLOAD_ERR_DUPLICATE_FILE;
                     continue;
                 }
             }
         }
         // no need to store it as an array anymore
         $save_as = implode('', $save_as);
         // does the filename exceed the maximum length?
         if (!empty(static::$config['max_length']) and strlen($save_as) > static::$config['max_length']) {
             static::$files[$key]['error'] = static::UPLOAD_ERR_MAX_FILENAME_LENGTH;
             continue;
         }
         // if no error was detected, move the file
         if (static::$files[$key]['error'] == UPLOAD_ERR_OK) {
             // save the additional information
             static::$files[$key]['saved_to'] = $path;
             static::$files[$key]['saved_as'] = $save_as;
             // before callback defined?
             if (array_key_exists('before', static::$callbacks) and !is_null(static::$callbacks['before'])) {
                 // get the callback method
                 $callback = static::$callbacks['before'][0];
                 // call the callback
                 if (is_callable($callback)) {
                     $result = call_user_func_array($callback, array(&static::$files[$key]));
                     if (is_numeric($result)) {
                         static::$files[$key]['error'] = $result;
                     }
                 }
             }
             // move the uploaded file
             if (static::$files[$key]['error'] == UPLOAD_ERR_OK) {
                 if (!@move_uploaded_file($file['file'], $path . $save_as)) {
                     static::$files[$key]['error'] = static::UPLOAD_ERR_MOVE_FAILED;
                 } else {
                     @chmod($path . $save_as, static::$config['file_chmod']);
                 }
                 // after callback defined?
                 if (array_key_exists('after', static::$callbacks) and !is_null(static::$callbacks['after'])) {
                     // get the callback method
                     $callback = static::$callbacks['after'][0];
                     // call the callback
                     if (is_callable($callback)) {
                         $result = call_user_func_array($callback, array(&static::$files[$key]));
                         if (is_numeric($result)) {
                             static::$files[$key]['error'] = $result;
                         }
                     }
                 }
             }
         }
     }
     umask($oldumask);
 }
Ejemplo n.º 27
0
 /**
  * Uses Fuel's Inflector::friendly_title(), but also replaces a few extra characters
  * to make URLs more readable
  * 
  * @param string $input The string to transform
  * @return string The URL friendly slug
  */
 public static function slug($input, $lowercase = true, $allow_non_ascii = false)
 {
     $input = str_replace(array(".", ",", "'", '"'), "", $input);
     return \Inflector::friendly_title($input, '-', $lowercase, $allow_non_ascii);
 }
Ejemplo n.º 28
0
 /**
  * Attempts to parse a file containing data for import
  */
 public static function parseImportFile($path)
 {
     $data = null;
     $columns = null;
     $output = array();
     // Work out some basic config settings
     \Config::load('format', true);
     // Work out the format from the extension
     $pathinfo = pathinfo($path);
     $format = strtolower($pathinfo['extension']);
     // Stop if we don't support the format
     if (!static::supportsFormat($format)) {
         throw new \Exception(\Lang::get('admin.errors.import.file_format_unknown'));
     }
     // Work out how to parse the data
     switch ($format) {
         case 'xls':
         case 'xlsx':
             $data = \Format::forge($path, 'xls')->to_array();
             $first = array_shift($data);
             $columns = is_array($first) ? array_filter(array_map(function ($key) {
                 return \Inflector::friendly_title($key, '_', true);
             }, array_values($first))) : array();
             break;
         default:
             $data = @file_get_contents($path);
             if (strpos($data, "\n") !== false) {
                 \Config::set('format.csv.regex_newline', "\n");
             } else {
                 if (strpos($data, "\r") !== false) {
                     \Config::set('format.csv.regex_newline', "\r");
                 }
             }
             $data = \Format::forge($data, $format)->to_array();
             // Find out some stuff...
             $first = \Arr::get($data, '0');
             $columns = is_array($first) ? array_map(function ($key) {
                 return \Inflector::friendly_title($key, '_', true);
             }, array_keys($first)) : array();
             break;
     }
     if (count($columns) > 0) {
         foreach ($data as $num => $row) {
             $values = array_values($row);
             $filtered = array_filter($values);
             if (count($values) > count($columns)) {
                 $values = array_slice($values, 0, count($columns));
             } else {
                 if (count($values) < count($columns)) {
                     while (count($values) < count($columns)) {
                         $values[] = null;
                     }
                 }
             }
             if (!empty($filtered)) {
                 $output[] = array_combine($columns, $values);
             }
         }
     } else {
         $columns = $data = $output = null;
     }
     // Stop if there's no data by this point
     if (!$data) {
         throw new \Exception(\Lang::get('admin.errors.import.file_parse_error'));
     }
     return array('columns' => $columns, 'data' => $output);
 }
Ejemplo n.º 29
0
 /**
  * Test for Inflector::friendly_title()
  *
  * @test
  */
 public function test_friendly_title()
 {
     $output = Inflector::friendly_title('Fuel is a community driven PHP 5 web framework.', '-', true);
     $expected = 'fuel-is-a-community-driven-php-5-web-framework';
     $this->assertEquals($expected, $output);
 }
Ejemplo n.º 30
0
 public function action_create()
 {
     \View::set_global('title', 'Add New');
     if (\Input::post()) {
         $val = Model_Product::validate('create');
         // Upload image and display errors if there are any
         $image = $this->upload_image();
         if (!$image['exists'] && \Config::get('details.image.required', false) && empty($item->image)) {
             // No previous images and image is not selected and it is required
             \Messages::error('<strong>There was an error while trying to upload product image</strong>');
             \Messages::error('You have to select image');
         } elseif ($image['errors']) {
             \Messages::error('<strong>There was an error while trying to upload product image</strong>');
             foreach ($image['errors'] as $error) {
                 \Messages::error($error);
             }
         }
         if ($val->run() && $image['is_valid'] && !(!$image['exists'] && \Config::get('details.image.required', false))) {
             // Get POST values
             $insert = \Input::post();
             // Prepare some values
             //				$insert['published_at'] = !empty($insert['published_at']) ? strtotime($insert['published_at']) : \Date::forge()->get_timestamp();
             $insert['active_from'] = !empty($insert['active_from']) ? strtotime($insert['active_from']) : NULL;
             $insert['active_to'] = !empty($insert['active_to']) ? strtotime($insert['active_to']) : NULL;
             if ($insert['status'] != 2) {
                 unset($insert['active_from']);
                 unset($insert['active_to']);
             }
             $item = Model_Product::forge($insert);
             try {
                 $item->save();
                 // Validate and insert product slug into SEO database table
                 $val_seo = Model_Product_Seo::validate('create_seo');
                 $insert_seo = array('content_id' => $item->id, 'slug' => \Inflector::friendly_title($item->title, '-', true));
                 while (!$val_seo->run($insert_seo)) {
                     $insert_seo['slug'] = \Str::increment($insert_seo['slug'], 1, '-');
                 }
                 $item_seo = Model_Product_Seo::forge($insert_seo);
                 $item_seo->save();
                 // END OF: SEO
                 // Insert product categories
                 foreach ($insert['cat_ids'] as $parent_category) {
                     $item_categories = Model_Product_To_Categories::forge(array('product_id' => $item->id, 'category_id' => $parent_category));
                     $item_categories->save();
                 }
                 /**  PROPERTY GROUPS  **/
                 // First delete old groups
                 $tmp_categories = \Product\Model_Product_To_Groups::find_by_product_id($item->id);
                 if ($tmp_categories) {
                     foreach ($tmp_categories as $tmp_cat) {
                         $tmp_cat->delete();
                     }
                 }
                 // Insert product property groups
                 if (isset($insert['group_ids'])) {
                     foreach ($insert['group_ids'] as $parent_group) {
                         $related = \Product\Model_Product_To_Groups::forge(array('group_id' => $parent_group, 'product_id' => $item->id));
                         $related->save();
                     }
                 }
                 /**  END OF: PROPERTY GROUPS  **/
                 /**  PRICING GROUPS  **/
                 // Insert product pricing group
                 if (\Input::post('group', false)) {
                     $pricing = \Product\Model_Product_To_Groups::forge(array('group_id' => \Input::post('group'), 'product_id' => $item->id));
                     $pricing->save();
                 }
                 /**  END OF: PRICING GROUPS  **/
                 // Insert product images
                 if ($this->_image_data) {
                     chmod($this->_image_data[0]['saved_to'] . $this->_image_data[0]['saved_as'], 0755);
                     chmod($this->_image_data[0]['saved_to'] . 'large/' . $this->_image_data[0]['saved_as'], 0755);
                     chmod($this->_image_data[0]['saved_to'] . 'medium/' . $this->_image_data[0]['saved_as'], 0755);
                     chmod($this->_image_data[0]['saved_to'] . 'thumbs/' . $this->_image_data[0]['saved_as'], 0755);
                     $item_image = array(array('id' => 0, 'data' => array('content_id' => $item->id, 'image' => $this->_image_data[0]['saved_as'], 'alt_text' => \Input::post('alt_text', ''), 'cover' => 1, 'sort' => 1)));
                     Model_Product::bind_images($item_image);
                 }
                 \Messages::success('Product successfully created.');
                 \Response::redirect(\Input::post('update', false) ? \Uri::create('admin/product/update/' . $item->id) : \Uri::create('admin/product/create/' . $item_categories->category_id));
             } catch (\Database_Exception $e) {
                 // show validation errors
                 \Messages::error('<strong>There was an error while trying to create product</strong>');
                 // Uncomment lines below to show database errors
                 $errors = $e->getMessage();
                 \Messages::error($errors);
             }
         } else {
             if ($val->error() != array()) {
                 // show validation errors
                 \Messages::error('<strong>There was an error while trying to create product</strong>');
                 foreach ($val->error() as $e) {
                     \Messages::error($e->get_message());
                 }
             }
         }
         // Delete uploaded image if there is product saving error
         if (isset($this->_image_data)) {
             $this->delete_image($this->_image_data[0]['saved_as']);
         }
     }
     \Theme::instance()->set_partial('content', $this->view_dir . 'create');
 }