Example #1
0
 protected function execute_create(InputInterface $input, OutputInterface $output)
 {
     $client = $input->getOption('client');
     if (!$client) {
         // We can't use the generic `get_client()` for **creation**,
         // because we need to verify that the user does **not** exist.
         $clients = Arr::pluck(Ushahidi_Console_OAuth_Client::db_list(), 'client_id');
         $ask = function ($client) use($clients) {
             if (in_array($client, $clients)) {
                 throw new RuntimeException('Client "' . $client . '" already exists, try another name');
             }
             return $client;
         };
         $client = $this->getHelperSet()->get('dialog')->askAndValidate($output, 'Enter name of new client: ', $ask, FALSE);
     }
     $secret = $input->getOption('secret');
     $redirect = $input->getOption('redirect');
     if (!$secret) {
         $secret = Text::random('distinct', 24);
     }
     if (!$redirect) {
         $redirect = '/';
     }
     static::db_create(['client_id' => $client, 'client_secret' => $secret, 'redirect_uri' => $redirect]);
     $input->setOption('client', $client);
     return $this->execute_list($input, $output);
 }
 public function clear_all()
 {
     $tables = array_diff(Arr::pluck($this->pdo->query('SHOW TABLES'), '0'), array(Migration_Driver_Mysql_Versions::SCHEMA_TABLE));
     if (count($tables)) {
         $this->execute("DROP TABLE " . join(', ', $tables));
     }
     return $this;
 }
Example #3
0
 public static function getTypeaheadList($col)
 {
     if (Auth::check() === false) {
         return json_encode(array());
     }
     $user_id = Auth::get_user_id();
     $res = DB::select($col)->from('posts')->where('user_id', '=', $user_id[1])->group_by($col)->execute()->as_array();
     return json_encode(\Arr::pluck($res, $col));
 }
Example #4
0
 public static function get_enum_options($enum)
 {
     $options = static::query()->related('default')->related('items')->related('items.meta')->where('slug', $enum)->get_one();
     if (is_null($options)) {
         $options = array();
     } else {
         $options = $options->to_array();
         $options = \Arr::pluck($options['items'], 'name', 'item_id');
     }
     return $options;
 }
Example #5
0
 public function render_answer_partial()
 {
     $view = View::factory('question/matching/partial_view')->bind('lefts', $lefts)->bind('rights', $rights);
     $attributes = $this->_orm !== null ? $this->_orm->attributes_as_array() : array();
     $attribute = $attributes[0];
     $pairs = unserialize($attribute['attribute_value']);
     $lefts = Arr::pluck($pairs, 0);
     $rights = Arr::pluck($pairs, 1);
     shuffle($rights);
     // var_dump($lefts, $rights, $pairs); exit;
     return $view->render();
 }
Example #6
0
 /**
  * Method to find out the possible correct answers
  * for the question
  * @param Array $attributes
  * @return String unique|multiple
  */
 public function choice_type($attributes)
 {
     $correct_status = Arr::pluck($attributes, 'correctness');
     $only_correct = array_filter($correct_status);
     $num_correct = count($only_correct);
     if ($num_correct > 1) {
         return 'multiple';
     } else {
         if ($num_correct == 1) {
             return 'unique';
         } else {
             throw new Exception('Set of answers without atleast 1 correct answer');
         }
     }
 }
Example #7
0
 protected function getClient(InputInterface $input, OutputInterface $output = NULL)
 {
     $client = $input->getOption('client');
     if (!$client and $output) {
         // If no client was given, and `$output` is passed, we can ask for
         // the user interactively and validate it against the known clients.
         $clients = Arr::pluck(self::db_list(), 'id');
         $ask = function ($client) use($clients) {
             if (!in_array($client, $clients)) {
                 throw new RuntimeException('Unknown client "' . $client . '", valid options are: ' . implode(', ', $clients));
             }
             return $client;
         };
         $client = $this->getHelperSet()->get('dialog')->askAndValidate($output, 'For which client? ', $ask, FALSE, NULL, $clients);
     }
     return $client;
 }
Example #8
0
 /**
  * Returns all models as JSON
  */
 public function action_read()
 {
     try {
         $id = $this->request->param('id', Arr::get($this->_input, 'id'));
         //Kohana::$log->add(Log::DEBUG,$this->chart->as_array());
         if (empty($id)) {
             $data = $this->chart->read_all();
         } else {
             $data = $this->chart->as_array();
             if (!is_null($this->time)) {
                 $url = sprintf('chart/series/%s/%s', $id, date('Y/m/d', $this->time));
                 $request = Request::factory($url)->execute();
                 $series = json_decode($request->body(), true);
                 Arr::set_path($data, "options.series", Arr::pluck($series, 'options'));
                 Arr::set_path($data, "options.subtitle.text", utf8_encode(strftime("%#d. %B %Y", $this->time)));
             }
         }
         $this->response->body(json_encode($data));
     } catch (Kohana_Exception $e) {
         // Return HTTP 400: Bad Request
         $this->response->status(400);
     }
 }
Example #9
0
 /**
  * Combined Setter/Getter method for questions_attempted array
  * @param Array $ques (optional (default null))
  * As a sideeffect, it will also set the $_questions_answers and
  * $_questions_results arrays
  */
 public function questions_attempted($ques = null)
 {
     if ($ques != null) {
         $this->_questions_attempted = $ques;
         $question_ids = array_keys($this->_questions_attempted);
         $answers = Arr::pluck($this->_questions_attempted, 'answer');
         $results = Arr::pluck($this->_questions_attempted, 'result');
         $this->_questions_answers = array_combine($question_ids, $answers);
         $this->_questions_results = array_combine($question_ids, $results);
         return null;
     }
     return $this->_questions_attempted;
 }
Example #10
0
 /**
  * Pluck an array of values from an array.
  *
  * @param  array   $array
  * @param  string  $value
  * @param  string  $key
  * @return array
  */
 function array_pluck($array, $value, $key = null)
 {
     return Arr::pluck($array, $value, $key);
 }
Example #11
0
 public function test_as_array()
 {
     // Test with no keys or values
     $array = $this->collection->as_array();
     $this->assertInternalType('array', $array);
     foreach ($array as $offset => $model) {
         $this->assertInstanceOf('Jam_Model', $model);
         $this->assertEquals($this->data[$offset], $model->as_array());
     }
     // Test with keys
     $array = $this->collection->as_array('name');
     $this->assertInternalType('array', $array);
     $offset = 0;
     foreach ($array as $name => $model) {
         $this->assertInstanceOf('Jam_Model', $model);
         $this->assertEquals($this->data[$offset]['name'], $name);
         $this->assertEquals($this->data[$offset], $model->as_array());
         $offset += 1;
     }
     // Test with keys as meta aliases
     $array = $this->collection->as_array(':primary_key');
     $this->assertInternalType('array', $array);
     $offset = 0;
     foreach ($array as $name => $model) {
         $this->assertInstanceOf('Jam_Model', $model);
         $this->assertEquals($this->data[$offset]['id'], $name);
         $this->assertEquals($this->data[$offset], $model->as_array());
         $offset += 1;
     }
     // Test with values
     $array = $this->collection->as_array(NULL, 'name');
     $this->assertEquals(Arr::pluck($this->data, 'name'), $array);
     // Test with values as aliases
     $array = $this->collection->as_array(NULL, ':primary_key');
     $this->assertEquals(Arr::pluck($this->data, 'id'), $array);
     // Test with keys and values as aliases
     $array = $this->collection->as_array(':name_key', ':primary_key');
     $this->assertEquals(array_combine(Arr::pluck($this->data, 'name'), Arr::pluck($this->data, 'id')), $array);
 }
Example #12
0
 /**
  * Method to check if the question contains math expressions
  * so that Mathjax typesetting can be triggered for the new dom tree
  */
 public function has_math()
 {
     $pattern = '/\\$\\$.+\\$\\$/';
     $to_check = array($this->question, $this->extra);
     $attrs = Arr::pluck($this->attributes_as_array(), 'attribute_value');
     $to_check = array_merge($to_check, $attrs);
     foreach ($to_check as $i) {
         $match = preg_match($pattern, $i);
         if ($match) {
             return true;
         }
     }
     return false;
 }
Example #13
0
 /**
  * Test Arr::pluck()
  *
  * @test
  * @dataProvider collection_provider
  */
 public function test_pluck_with_index($collection)
 {
     $output = \Arr::pluck($collection, 'name', 'id');
     $expected = array(2 => 'Bill', 5 => 'Chris', 7 => 'Bert');
     $this->assertEquals($expected, $output);
 }
Example #14
0
 /**
  * Find and format a bunch of logs between two dates
  * @return array The log data, ready for conversion into CSV or something similar
  */
 public static function report($start_date = null, $end_date = null, $filters = array(), $group_by = null, $callback = null)
 {
     $qb = \CMF\Model\Log::findBy($filters);
     $has_filters = count($filters) > 0;
     // Filter from start date
     if ($start_date !== null) {
         if (is_string($start_date)) {
             $start_date = date('Y-m-d H:i:s', strtotime(str_replace('/', '-', $start_date)));
             $start_date = \DateTime::createFromFormat('Y-m-d H:i:s', $start_date);
         }
         if ($has_filters) {
             $qb->andWhere("item.date >= ?1")->setParameter(1, $start_date);
         } else {
             $qb->where("item.date >= ?1")->setParameter(1, $start_date);
         }
         $has_filters = true;
     }
     // Filter to end date
     if ($end_date !== null) {
         if (is_string($end_date)) {
             $end_date = date('Y-m-d H:i:s', strtotime(str_replace('/', '-', $end_date)));
             $end_date = \DateTime::createFromFormat('Y-m-d H:i:s', $end_date);
         }
         if ($has_filters) {
             $qb->andWhere("item.date < ?2")->setParameter(2, $end_date);
         } else {
             $qb->where("item.date < ?2")->setParameter(2, $end_date);
         }
     }
     // Get the log entries
     $entries = $qb->orderBy('item.date', 'ASC')->getQuery()->getArrayResult();
     $types = array_values(array_unique(array_merge(array_unique(\Arr::pluck($entries, 'item_type')), array_unique(\Arr::pluck($entries, 'user_type')))));
     $actions = array_values(array_unique(\Arr::pluck($entries, 'action')));
     $types_ids = array();
     $output = array();
     // Normalize the group_by parameter
     if ($group_by == 'user') {
         $group_by = 'user_id';
     } else {
         if ($group_by == 'item') {
             $group_by = 'item_id';
         }
     }
     // Find the ids of the related users and items
     foreach ($entries as $entry) {
         // The user
         if ($entry['has_user'] = isset($entry['user_type']) && isset($entry['user_id'])) {
             $type = $entry['user_type'];
             $ids = isset($types_ids[$type]) ? $types_ids[$type] : array();
             if (!in_array($entry['user_id'], $ids)) {
                 $ids[] = $entry['user_id'];
                 $types_ids[$type] = $ids;
             }
         }
         // The item
         if ($entry['has_item'] = isset($entry['item_type']) && isset($entry['item_id'])) {
             $type = $entry['item_type'];
             $ids = isset($types_ids[$type]) ? $types_ids[$type] : array();
             if (!in_array($entry['item_id'], $ids)) {
                 $ids[] = $entry['item_id'];
                 $types_ids[$type] = $ids;
             }
         }
         // Add to the stats for this group if we're grouping
         if ($group_by !== null) {
             $group_value = $entry['item_type'] . '_' . $entry[$group_by];
             if (!isset($output[$group_value])) {
                 $group = $entry;
                 foreach ($actions as $action) {
                     $group[$action . '_count'] = 0;
                 }
             } else {
                 $group = $output[$group_value];
             }
             $group[$entry['action'] . '_count'] += 1;
             $group['last_' . $action] = $entry['date']->format('d/m/Y H:i:s');
             $output[$group_value] = $group;
         } else {
             $output[] = $entry;
         }
     }
     // Now construct queries for each of the types, so we can grab them all in one swipe
     foreach ($types as $type) {
         if (!isset($types_ids[$type]) || count($types_ids[$type]) === 0) {
             continue;
         }
         $ids = $types_ids[$type];
         $types_ids[$type] = $type::select('item', 'item', 'item.id')->where('item.id IN(?1)')->setParameter(1, $ids)->getQuery()->getResult();
     }
     // Put the items into the log entries
     foreach ($output as &$entry) {
         // The user
         if ($entry['has_user']) {
             $user_type = $entry['user_type'];
             $entry['user'] = \Arr::get($types_ids, $user_type . '.' . $entry['user_id'], null);
             $entry['user_type_label'] = $user_type::singular();
         }
         // The item
         if ($entry['has_item']) {
             $item_type = $entry['item_type'];
             $entry['item'] = \Arr::get($types_ids, $item_type . '.' . $entry['item_id'], null);
             $entry['item_type_label'] = $item_type::singular();
         }
     }
     if ($callback !== null) {
         return array_values(array_filter($output, $callback));
     }
     return $output;
 }
Example #15
0
 /**
  * Tests Arr::pluck()
  *
  * @test
  * @dataProvider provider_pluck
  * @param array $array
  * @param string $key
  * @param array $expected
  */
 public function test_pluck(array $array, $key, $expected)
 {
     $array = Arr::pluck($array, $key);
     $this->assertSame(count($expected), count($array));
     $this->assertSame($expected, $array);
 }
Example #16
0
 public static function getList()
 {
     return json_encode(\Arr::pluck(Model_Creature::find('all', array('select' => 'name')), 'name'));
 }
Example #17
0
 private function _get_nomenclature($orm)
 {
     $nomenclature_element = new Nomenclature_Element();
     $nom_list = $nomenclature_element->get_list($orm->id);
     $nom_properties = $nomenclature_element->get_properties($nom_list);
     $request = $this->request->current();
     $query_array = array_intersect_key($request->query(), array_filter(array('no_cache' => TRUE, 'p' => FALSE)));
     $query_string = Helper_Page::make_query_string($query_array);
     $query_string = empty($query_string) ? '' : '?' . $query_string;
     $link_tpl = $request->url() . $query_string . '#item-';
     $result = array();
     foreach ($nom_list as $_orm) {
         $_props = Arr::get($nom_properties, $_orm->id, array());
         $_size_name = Arr::path($_props, 'Size.value.Name.value');
         $_duvet_cover = Arr::path($_props, 'Size.value.DuvetCover.value');
         $_bedsheet = Arr::path($_props, 'Size.value.Bedsheet.value');
         $_pillowslip = Arr::path($_props, 'Size.value.Pillowslip.value');
         $_price = Arr::path($_props, 'Price.value');
         $_discount = Arr::path($_props, 'Discount.value');
         $result[] = array('id' => $_orm->id, 'name' => "{$orm->title} ({$_size_name})", 'link' => $link_tpl . $_orm->id, 'price' => $_price, 'discount' => $_discount, 'size' => array('name' => $_size_name, 'duvet_cover' => implode(', ', Arr::pluck($_duvet_cover, 'value')), 'bedsheet' => implode(', ', Arr::pluck($_bedsheet, 'value')), 'pillowslip' => implode(', ', Arr::pluck($_pillowslip, 'value'))));
     }
     usort($result, function ($elm_1, $elm_2) {
         if ($elm_1['price'] == $elm_2['price']) {
             return 0;
         }
         return $elm_1['price'] > $elm_2['price'] ? -1 : 1;
     });
     return $result;
 }
Example #18
0
 public function set($id, $qty = 1, array $options = array())
 {
     if (Arr::is_array($id)) {
         $products = $this->_get_product(Arr::pluck($id, 'id'), Arr::pluck($id, 'qty'), Arr::pluck($id, 'options'));
         // $products = $this->_get_product($id, $qty, $options);
         $products = $this->_get_product($id, $qty, $options);
     } else {
         $qty = max(1, $qty);
         $products[0] = $this->_get_product($id, $qty, $options);
     }
     foreach ($products as $product) {
         $product['options'] = Arr::get($product, 'options', array());
         // Composite identifier
         $mix_id = $this->_get_mix_id($product['id'], $product['options']);
         if (isset($this->_content['products'][$mix_id])) {
             if ($product['qty'] >= $this->_content['products'][$mix_id]['qty'] + $qty) {
                 $this->_content['products'][$mix_id]['qty'] += $qty;
             } else {
                 throw new Kohana_Exception('In stock only :qty items', array(':qty' => $product['qty']));
                 // return FALSE;
             }
         } else {
             //$product['qty'] = $qty;
             $this->_content['products'][$mix_id] = $product;
         }
     }
     return $this->_save();
 }
 /**
  * Translate a single string
  */
 private function translateArray($array, $from, $to)
 {
     $apiKey = \Config::get('cmf.languages.google_translate.api_key');
     if (!$apiKey) {
         return null;
     }
     // Build the url
     $url = \Config::get('cmf.languages.google_translate.base_url');
     $query = 'key=' . $apiKey . '&source=' . $from . '&target=' . $to;
     foreach ($array as $item) {
         $query .= '&q=' . urlencode($item);
     }
     // Execute the request
     $handle = curl_init($url);
     curl_setopt($handle, CURLOPT_POST, 1);
     curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
     curl_setopt($handle, CURLOPT_SSL_VERIFYHOST, false);
     curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);
     curl_setopt($handle, CURLOPT_HTTPHEADER, array('X-HTTP-Method-Override: GET'));
     curl_setopt($handle, CURLOPT_POSTFIELDS, $query);
     $response = curl_exec($handle);
     // Handle errors
     if (FALSE === $response) {
         logger('error', @curl_errno($handle) . " : " . @curl_error($handle));
         return null;
     }
     curl_close($handle);
     // Decode the response and set each field back to the entity
     $responseDecoded = json_decode($response, true);
     $result = null;
     if (isset($responseDecoded['data'])) {
         try {
             $translated = \Arr::pluck($responseDecoded['data']['translations'], 'translatedText');
             if (count($translated) === count($array)) {
                 $result = array_combine(array_keys($array), array_values($translated));
             }
         } catch (\Exception $e) {
             // Nothing
         }
     } else {
         // An error response has been returned
         logger('error', 'An error was returned from the translate API: ' . print_r($responseDecoded, true));
     }
     return $result;
 }
Example #20
0
 /**
  * Get the values of a given key.
  *
  * @param  string  $value
  * @param  string|null  $key
  * @return static
  */
 public function pluck($value, $key = null)
 {
     return new static(Arr::pluck($this->items, $value, $key));
 }
 public static function get_manufacturers()
 {
     $manufacturers = static::query()->where('status', 1)->get();
     return \Arr::pluck($manufacturers, 'name', 'id');
 }
Example #22
0
 /**
  * Sets the groups for the given user. Any groups assigned to the user but
  * not in the given list of groups will be removed and any groups that are
  * in the list but not assigned will be assigned to the user.
  * 
  * @param int|Ethanol\Model_User $user The user to modify
  * @param array(int) $groups The groups to set
  */
 public function set_user_groups($user, $groups)
 {
     if (is_numeric($user)) {
         $user = $this->get_user($user);
     }
     $existing_groups = \Arr::pluck($user->groups, 'id');
     //Use array diff to work out which groups need to be added and deleted
     $to_add = array_diff($groups, $existing_groups);
     $to_delete = array_diff($existing_groups, $groups);
     //Delete any groups needed
     foreach ($to_delete as $id) {
         unset($user->groups[$id]);
     }
     //Now add any that need to be added
     foreach ($to_add as $id) {
         //Get the group
         $group = $this->get_group($id);
         $user->groups[] = $group;
     }
     //Finally save the changes
     $user->save();
     return $this;
 }
Example #23
0
 /**
  * Get an item from an array or object using "dot" notation.
  *
  * @param  mixed   $target
  * @param  string|array  $key
  * @param  mixed   $default
  * @return mixed
  */
 function data_get($target, $key, $default = null)
 {
     if (is_null($key)) {
         return $target;
     }
     $key = is_array($key) ? $key : explode('.', $key);
     while (($segment = array_shift($key)) !== null) {
         if ($segment === '*') {
             if ($target instanceof Collection) {
                 $target = $target->all();
             } elseif (!is_array($target)) {
                 return value($default);
             }
             $result = Arr::pluck($target, $key);
             return in_array('*', $key) ? Arr::collapse($result) : $result;
         }
         if (Arr::accessible($target) && Arr::exists($target, $segment)) {
             $target = $target[$segment];
         } elseif (is_object($target) && isset($target->{$segment})) {
             $target = $target->{$segment};
         } else {
             return value($default);
         }
     }
     return $target;
 }