Inheritance: extends Eloquent
Exemplo n.º 1
1
 /**
  * Save chosen password
  */
 public function save_pass()
 {
     $pass = F::request()->data->password;
     $pass2 = F::request()->data->password2;
     if ($pass === $pass2) {
         if (!empty($pass)) {
             if (Action::savePassword($pass)) {
                 $_SESSION['flashbag'] = '
                 <div class="alert alert-success alert-dismissible">
                     <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                     Your password has successfully been set.
                 </div>';
                 $_SESSION['admin'] = 1;
                 F::redirect('/settings');
                 exit;
             } else {
                 $_SESSION['flashbag'] = '<div class="alert alert-danger">An error occured. Please verify that the app/ and src/ folder are writable.</div>';
             }
         } else {
             $_SESSION['flashbag'] = '<div class="alert alert-warning">No password ? Are you serious ? Put at least some letters.</div>';
         }
     } else {
         $_SESSION['flashbag'] = '<div class="alert alert-danger">You must enter the same password twice.</div>';
     }
     $this->index();
 }
Exemplo n.º 2
1
 private function find_routes($org, $dest, &$flights)
 {
     $result = array();
     $queue = new SplPriorityQueue();
     foreach ($flights as $flight) {
         if ($flight['org_id'] == $org) {
             $route = new Route($this->route_opts);
             $num_seats = Flight::get_open_seats_on_flight($flight['flight_id'], $this->user);
             $route->add_flight($flight, $num_seats);
             $queue->insert($route, $route->get_joy());
         }
     }
     //BFS to find all routes that take < 10 hours
     $count = 0;
     while ($queue->count() > 0 && $count < $this->opts['max_results']) {
         $cur_route = $queue->extract();
         if ($cur_route->get_dest() == $dest) {
             $result[] = $cur_route;
             $count++;
             continue;
         }
         foreach ($flights as $flight) {
             if (!array_key_exists($flight['dest_id'], $cur_route->visited) && $flight['org_id'] == $cur_route->get_dest() && $flight['e_depart_time'] > 30 * 60 + $cur_route->get_arrival_time()) {
                 $new_route = $cur_route->copy();
                 $num_seats = Flight::get_open_seats_on_flight($flight['flight_id'], $this->user);
                 $new_route->add_flight($flight, $num_seats);
                 if ($new_route->get_trip_time() < 24 * 60 * 60 && $new_route->seats >= $this->opts['passengers']) {
                     $queue->insert($new_route, $new_route->get_joy());
                 }
             }
         }
     }
     return $result;
 }
Exemplo n.º 3
0
 /**
  * @param $configdepart
  * @return bool
  */
 private function saveFlights(Configdepart $configdepart)
 {
     // Combien de flights à créer
     $nbFlights = ceil($configdepart->nbjoueurs / $configdepart->slotbyflight) + $configdepart->startergap;
     // Met a jour Configdepart->slotcount : nombre de places disponibes créees
     $configdepart->slotcount = $nbFlights * $configdepart->slotbyflight;
     $configdepart->save();
     // Supprimer les Flight de cette config
     $configdepart->flights()->delete();
     // Boucle tous les flight à créer
     for ($i = 1; $i <= $nbFlights; $i++) {
         $addMinutes = ($i - 1) * $configdepart->interval;
         $newheure = Carbon::createFromFormat('H:i', $configdepart->startheure)->addMinutes($addMinutes);
         // New Flight
         $flight = new Flight();
         $flight->configdepart_id = $configdepart->id;
         $flight->num = $i;
         $flight->heure = $newheure;
         $flight->save();
         // Cree les slots
         for ($slotnum = 1; $slotnum <= $configdepart->slotbyflight; $slotnum++) {
             $slot = new Slot();
             $slot->flight_id = $flight->id;
             $slot->num = $slotnum;
             $slot->entree_id = 0;
             $slot->save();
         }
     }
     return true;
 }
 public function start()
 {
     $timetableItems = $this->timetableRepo->getTimetableItemsBeyondFlightBorad();
     $flights = array();
     foreach ($timetableItems as $item) {
         $newFlight = new \Flight();
         $departure_time = $this->makeDepartureTimestamp($item->departure_day_of_week, $item->departure_hour);
         $arrival_time = clone $departure_time;
         $arrival_time->addSeconds($item->flight_duration);
         $newFlight->fill(['timetable_id' => $item->id, 'airline_id' => $item->airline_id, 'airplane_id' => $item->airplane_id, 'origin_airport_id' => $item->origin_airport_id, 'destination_airport_id' => $item->destination_airport_id, 'departure_time' => $departure_time, 'arrival_time' => $arrival_time, 'distance' => great_circle_distance($item->origin->lat, $item->origin->lng, $item->destination->lat, $item->destination->lng), 'flight_number' => $item->flight_number]);
         array_push($flights, $newFlight);
     }
     $this->addedFlights = count($flights);
     $this->flightRepo->saveMany($flights);
 }
 public static function getIdsPerfisAutorizadosByModulo($id_modulo, $id_empreendimento, $associativo)
 {
     $associativo = empty($associativo) ? false : ($associativo == 'true' ? true : false);
     $FuncionalidadeDao = new FuncionalidadeDao();
     $aux = $FuncionalidadeDao->getIdsPerfisAutorizadosByModulo($id_modulo, $id_empreendimento);
     if ($aux) {
         $aux = $aux ? $aux : array();
         $perfis = array();
         foreach ($aux as $perfil) {
             if ($associativo) {
                 if (!isset($perfis[$perfil['cod_funcionalidade']])) {
                     $perfis[$perfil['cod_funcionalidade']] = [];
                 }
                 $perfis[$perfil['cod_funcionalidade']][] = (int) $perfil['id_perfil'];
             } else {
                 if (!isset($perfis[$perfil['id_funcionalidade']])) {
                     $perfis[$perfil['id_funcionalidade']] = [];
                 }
                 $perfis[$perfil['id_funcionalidade']][] = (int) $perfil['id_perfil'];
             }
         }
         Flight::json($perfis);
     } else {
         Flight::halt(404, 'Não há resultado para a busca');
     }
 }
Exemplo n.º 6
0
 public function __construct()
 {
     new Model_Test();
     include "test.html";
     $tmp = Flight::get('test');
     echo "Controller_Test" . $tmp;
 }
Exemplo n.º 7
0
 /**
  * getBasePath
  *
  * @return string
  */
 function getBasePath()
 {
     if (strlen(Flight::request()->base) == 1) {
         return getWebsiteUrl() . '/';
     }
     return getWebsiteUrl() . Flight::request()->base . '/';
 }
Exemplo n.º 8
0
 public function deleteAbsence($id)
 {
     Flight::auth()->check();
     $absence = Flight::absence()->getAbsenceWithId($id);
     $absence->delete();
     Flight::redirect(Flight::request()->referrer);
 }
Exemplo n.º 9
0
 public static function recommended()
 {
     $dbname = 'predictionio_appdata';
     $mdb = Flight::mdb();
     $db = $mdb->{$dbname};
     $items = $db->items;
     $client = Flight::prediction_client();
     $recommended_movies = array();
     try {
         $user_id = $_SESSION['user_id'];
         $client = new EngineClient('http://localhost:8000');
         $recommended_movies_raw = $client->sendQuery(array('user' => $user_id, 'num' => 9));
         $movie_iids = array_map(function ($item) {
             return $item['item'];
         }, $recommended_movies_raw['itemScores']);
         $cursor = $items->find(array('itypes' => '1', '_id' => array('$in' => $movie_iids)));
         $recommended_movies = array_values(iterator_to_array($cursor));
     } catch (Exception $e) {
         echo 'Caught exception: ', $e->getMessage(), "\n";
     }
     $_SESSION['movies_viewed'] = 0;
     $_SESSION['user_id'] = '';
     Flight::render('recommended', array('recommended_movies' => $recommended_movies), 'content');
     Flight::render('layout', array('title' => 'Recommended', 'base_path' => '/movie_recommender'));
 }
Exemplo n.º 10
0
 public static function recommended()
 {
     $dbname = 'predictionio_appdata';
     $mdb = Flight::mdb();
     $db = $mdb->{$dbname};
     $items = $db->items;
     $client = Flight::prediction_client();
     $recommended_movies = array();
     try {
         $user_id = $_SESSION['user_id'];
         $client->identify($user_id);
         $command = $client->getCommand('itemrec_get_top_n', array('pio_engine' => 'movie-recommender', 'pio_n' => 9));
         $recommended_movies_raw = $client->execute($command);
         $movie_iids = $recommended_movies_raw['pio_iids'];
         array_walk($movie_iids, function (&$movie_iid) {
             $movie_iid = '4_' . $movie_iid;
         });
         $cursor = $items->find(array('itypes' => '1', '_id' => array('$in' => $movie_iids)));
         $recommended_movies = array_values(iterator_to_array($cursor));
     } catch (Exception $e) {
         echo 'Caught exception: ', $e->getMessage(), "\n";
     }
     $_SESSION['movies_viewed'] = 0;
     $_SESSION['user_id'] = '';
     Flight::render('recommended', array('recommended_movies' => $recommended_movies), 'content');
     Flight::render('layout', array('title' => 'Recommended', 'base_path' => '/movie_recommender'));
 }
Exemplo n.º 11
0
 private function mcCacheProps($filePath, $device, $channel)
 {
     $mc = Flight::mc();
     $cache = $mc->get($filePath);
     if (!$cache && Memcached::RES_NOTFOUND == $mc->getResultCode()) {
         $buildpropArray = explode("\n", file_get_contents('zip://' . $filePath . '#system/build.prop'));
         if ($device == $this->getBuildPropValue($buildpropArray, 'ro.product.device')) {
             $api_level = intval($this->getBuildPropValue($buildpropArray, 'ro.build.version.sdk'));
             $incremental = $this->getBuildPropValue($buildpropArray, 'ro.build.version.incremental');
             $timestamp = intval($this->getBuildPropValue($buildpropArray, 'ro.build.date.utc'));
             $url = $this->getBuildPropValue($buildpropArray, 'ro.build.ota.url');
             $cache = array($device, $api_level, $incremental, $timestamp, Utils::getMD5($filePath), $url);
             $mc->set($filePath, $cache);
             $mc->set($incremental, array($device, $channel, $filePath));
         } else {
             throw new Exception("{$device}: {$filePath} is in invalid path");
         }
     }
     assert($cache[0] == $device);
     $this->api_level = $cache[1];
     $this->incremental = $cache[2];
     $this->timestamp = $cache[3];
     $this->md5sum = $cache[4];
     $this->url = $cache[5];
 }
Exemplo n.º 12
0
 /**
  * AssetsManager constructor.
  * @param array $conf
  */
 public function __construct($conf = [])
 {
     if (!$conf) {
         $conf = \Flight::get('config')->get('assets');
     }
     $this->loadConfig($conf);
 }
Exemplo n.º 13
0
 /**
  * PRedis constructor.
  *
  * @param array $conf
  * @param $options
  */
 public function __construct($conf = [], $options = null)
 {
     if (!$conf) {
         $conf = \Flight::get('config')->get('redis');
     }
     parent::__construct($conf, $options);
 }
Exemplo n.º 14
0
 public function init()
 {
     $data = $_REQUEST;
     if (isset($data[Profile::GET_CHANGE_PASSWORD_BUTTON])) {
         $user = Auth::getInstance()->getUser();
         if (strlen(trim($data[Profile::GET_CHANGE_MAIL])) > 0) {
             if ($user->email != trim($data[Profile::GET_CHANGE_MAIL])) {
                 if (User::validEmail(trim(strip_tags($data[Profile::GET_CHANGE_MAIL])))) {
                     $user->email = trim(strip_tags($data[Profile::GET_CHANGE_MAIL]));
                     $user->password = User::getHashPassword($user->password, strtolower($user->email));
                 } else {
                     Flight::redirect($_SERVER['REDIRECT_URL'] . '?success=2');
                 }
             }
         }
         if (strlen(trim($data[Profile::GET_CHANGE_PASSWORD])) > 0) {
             if (!User::passwordIsValid($data[Profile::GET_CHANGE_PASSWORD])) {
                 Flight::redirect($_SERVER['REDIRECT_URL'] . '?success=0');
             } else {
                 $user->password = User::getHashPassword(trim(strip_tags($data[Profile::GET_CHANGE_PASSWORD])), strtolower($user->email));
             }
         }
         $user->save();
         Flight::redirect($_SERVER['REDIRECT_URL'] . '?success=1');
         return true;
     }
 }
 public static function updateStatus($idNotaFiscal, $id_empreendimento)
 {
     try {
         $NotaFiscalDao = new NotaFiscalDao();
         $ConfiguracaoDao = new ConfiguracaoDao();
         $conf = $ConfiguracaoDao->getConfiguracoes($id_empreendimento);
         $flg_ambiente_nfe = isset($conf['flg_ambiente_nfe']) && ((int) $conf['flg_ambiente_nfe'] == 1 || (int) $conf['flg_ambiente_nfe'] == 0) ? (int) $conf['flg_ambiente_nfe'] : 0;
         $tokens['token_focus_producao'] = isset($conf['token_focus_producao']) ? $conf['token_focus_producao'] : '';
         $tokens['token_focus_homologacao'] = isset($conf['token_focus_homologacao']) ? $conf['token_focus_homologacao'] : '';
         $NfeDao = new NfeDao($flg_ambiente_nfe, $tokens);
         $NfeDao->id_ref = $idNotaFiscal;
         $retornoParceiro = $NfeDao->buscaNfe();
         $nfTO = new stdClass();
         $nfTO->cod_nota_fiscal = $idNotaFiscal;
         $nfTO->status = $retornoParceiro->status;
         $nfTO->status_sefaz = $retornoParceiro->status_sefaz;
         $nfTO->mensagem_sefaz = $retornoParceiro->mensagem_sefaz;
         $nfTO->status_sefaz_cancelamento = isset($retornoParceiro->status_sefaz_cancelamento) ? $retornoParceiro->status_sefaz_cancelamento : NULL;
         $nfTO->mensagem_sefaz_cancelamento = isset($retornoParceiro->mensagem_sefaz_cancelamento) ? $retornoParceiro->mensagem_sefaz_cancelamento : NULL;
         $nfTO->caminho_xml_cancelamento = isset($retornoParceiro->caminho_xml_cancelamento) ? substr($NfeDao->server, 0, -1) . $retornoParceiro->caminho_xml_cancelamento : NULL;
         if ($nfTO->status == 'autorizado') {
             $nfTO->serie = $retornoParceiro->serie;
             $nfTO->numero = $retornoParceiro->numero;
             $nfTO->chave_nfe = $retornoParceiro->chave_nfe;
             $nfTO->caminho_xml_nota_fiscal = substr($NfeDao->server, 0, -1) . $retornoParceiro->caminho_xml_nota_fiscal;
             $nfTO->caminho_danfe = substr($NfeDao->server, 0, -1) . $retornoParceiro->caminho_danfe;
         }
         $NotaFiscalDao->updateNota($nfTO);
         $notaAtualizada = $NotaFiscalDao->getNota($idNotaFiscal);
         Flight::json($notaAtualizada);
     } catch (Exception $e) {
         jsonException($e);
     }
 }
Exemplo n.º 16
0
 public static function findByDivision($game_id, $limit = false)
 {
     if (!$limit) {
         $limit = 10;
     }
     return arrayToObject(Flight::aod()->from(self::$table)->where(array("member.game_id" => $game_id))->limit($limit)->sortDesc('date')->join('actions', array('actions.id' => 'user_actions.type_id'))->join('member', array('member.member_id' => 'user_actions.target_id'))->select(array('date', 'user_id', 'type_id', 'target_id', 'verbage', 'icon'))->many());
 }
Exemplo n.º 17
0
 public function account()
 {
     //Spaghetti code!!!
     //TODO: Refactor this method (move all logic from controller to models!!!)
     $arrived_and_not_accounted_flights = Flight::where('arrival_time', '<', DB::raw('UTC_TIMESTAMP()'))->where('accounted', 0)->get();
     $accounted = 0;
     //TODO: Improve tickets cost, based on real flight prices:
     // http://www.pasazer.com/news/7538/raport,ile,naprawde,kosztuje,lot.html
     foreach ($arrived_and_not_accounted_flights as $flight) {
         $fuel_price_litre = 1.18;
         $fuel = -1 * ((strtotime($flight->arrival_time) - strtotime($flight->departure_time)) / 3600 * $flight->airplane->model->fuel_usage * $fuel_price_litre);
         $taxes = 0;
         echo $flight;
         foreach ($flight->airline->deals as $deal) {
             if ($deal->pivot->airport_id == $flight->origin_airport_id || $deal->pivot->airport_id == $flight->destination_airport_id) {
                 $taxes -= $deal->pivot->operation_fee;
                 $taxes -= $deal->pivot->passenger_fee * ($flight->passengers_economy + $flight->passengers_buissnes + $flight->passengers_firstclass);
             }
         }
         echo 'TAXES: ' . $taxes . '$<hr>';
         //MVC violation!!! Move this to View
         $tickets = round(($flight->passengers_economy * 0.26 + $flight->passengers_buissnes * 0.86 + $flight->passengers_firstclass * 1.59) * $flight->distance);
         $bilance = $tickets + $fuel + $taxes;
         DB::table('airlines')->where('id', $flight->airline_id)->increment('funds', $bilance);
         //Repository Pattern violation!!!
         App::make('FinanceOperationsController')->create($flight->airline_id, 'flight', $bilance);
         $flight->bilance_tickets = $tickets;
         $flight->bilance_fuel = $fuel;
         $flight->bilance_taxes = $taxes;
         $flight->accounted = 1;
         $flight->save();
         $accounted++;
     }
     return $accounted . ' flights accounted.';
 }
Exemplo n.º 18
0
 function citypair($departureId, $arrivalId)
 {
     $routes = Flight::select('id', 'route', DB::raw('COUNT(route) AS count'))->whereDepartureId($departureId)->whereArrivalId($arrivalId)->where('route', '!=', '')->whereState(2)->groupBy('route')->orderBy('count', 'desc')->get();
     $departure = Airport::whereIcao($departureId)->first();
     $arrival = Airport::whereIcao($arrivalId)->first();
     $this->autoRender(compact('departure', 'arrival', 'routes', 'airports', 'departureId', 'arrivalId'), 'Routes for ' . $departureId . ' - ' . $arrivalId);
 }
Exemplo n.º 19
0
 public function calculate_position($timestamp = 0)
 {
     /*
     	Metoda zwraca id lotniska, w którym znajduje lub będzie się znajdował samolot w danym czasie (timestamp).
     	Pozycja 0 oznacza, że samolot jest w powietrzu.
     */
     if ($timestamp == 0) {
         $timestamp = time();
     }
     $flights = Flight::where('airplane_id', $this->id)->get();
     foreach ($flights as $flight) {
         $departure_timestamp = strtotime($flight->departure_time);
         $arrival_timestamp = strtotime($flight->arrival_time);
         if ($departure_timestamp < $timestamp and $timestamp < $arrival_timestamp) {
             //Ten lot właśnie trwa
             return false;
             //samolot w powietrzu
         }
     }
     //Samolot nie jest w powietrzu, sprawdzamy więc lotnisko na którym obecnie stoi
     $last_flight = Flight::where('airplane_id', $this->id)->where('departure_time', '<', date('Y-m-d H:i:s', $timestamp))->orderBy('departure_time', 'desc')->first();
     if (!$last_flight) {
         //Ten samolot nigdy nie leciał, wiec stoi w bazie, wiec zwracamy lotnisko-bazę
         return $this->airline->headquarter;
     } else {
         return $last_flight->destination;
     }
     //dd($last_flight);
 }
Exemplo n.º 20
0
 private function mcCacheProps($filePath, $device, $channel)
 {
     $mc = Flight::mc();
     $cache = $mc->get($filePath);
     if (true) {
         $buildpropArray = explode("\n", file_get_contents($filePath . '.build.prop'));
         if ($device == $this->getBuildPropValue($buildpropArray, 'ro.product.device') || $device == $this->getBuildPropValue($buildpropArray, 'ro.cm.device')) {
             $api_level = intval($this->getBuildPropValue($buildpropArray, 'ro.build.version.sdk'));
             $incremental = $this->getBuildPropValue($buildpropArray, 'ro.build.version.incremental');
             $timestamp = intval($this->getBuildPropValue($buildpropArray, 'ro.build.date.utc'));
             if (file_exists($filePath . '.url')) {
                 $url = explode("\n", file_get_contents($filePath . '.url'))[0];
             } else {
                 $url = 'https://' . $_SERVER['HTTP_HOST'] . '/_builds/' . explode("/", $filePath)[4];
             }
             $cache = array($device, $api_level, $incremental, $timestamp, Utils::getMD5($filePath), $url);
             $mc->set($filePath, $cache);
             $mc->set($incremental, array($device, $channel, $filePath));
         } else {
             throw new Exception("{$device}: {$filePath} is in invalid path");
         }
     }
     assert($cache[0] == $device);
     $this->api_level = $cache[1];
     $this->incremental = $cache[2];
     $this->timestamp = $cache[3];
     $this->md5sum = $cache[4];
     $this->url = $cache[5];
 }
Exemplo n.º 21
0
 /**
  * Constructor
  */
 public function __construct($install)
 {
     parent::__construct($install);
     if (F::has('pageinfos')) {
         F::view()->assign(array('pageinfos' => Files::getPageInfos(F::get('pageinfos')['cat'], F::get('pageinfos')['page'])));
     }
 }
Exemplo n.º 22
0
 /**
  * Gets fields/columns from specified tables and generates dropdown options
  */
 public function getselectfields()
 {
     $tablesJSON = $_POST['tables'];
     if ($tablesJSON) {
         $html = '';
         $tables = json_decode($tablesJSON, true);
         foreach ($tables as $table) {
             // table columns
             $stmt = Flight::get('db')->query("DESCRIBE {$table}");
             $columns = $stmt->fetchAll(PDO::FETCH_ASSOC);
             //pretty_print($columns);
             $fields = array();
             foreach ($columns as $values) {
                 if (isset($values['Field'])) {
                     $fields[] = $values['Field'];
                 }
             }
             //pretty_print($fields);
             $html .= '<optgroup label="' . $table . '">' . "\n";
             $html .= getOptions($fields, false, $table);
             $html .= '</optgroup>' . "\n";
         }
         echo $html;
     }
 }
Exemplo n.º 23
0
function handle_auth()
{
    $request = Flight::request();
    //incoming=
    //outgoing=
    $stage = $request->query->stage;
    $ip = $request->query->ip;
    $mac = $request->query->mac;
    $token = $request->query->token;
    if (empty($stage) || empty($ip) || empty($mac) || empty($token)) {
        //Flight::Error('Required parameters empty!');
        write_auth_response(AUTH_ERROR);
    }
    // Do some housekeeping
    clear_old_tokens();
    // Even on STAGE_COUNTER, check token
    //if ($stage == STAGE_COUNTER) {
    //    return;
    //}
    if (is_token_valid($token)) {
        write_auth_response(AUTH_ALLOWED);
        return;
    }
    write_auth_response(AUTH_DENIED);
}
Exemplo n.º 24
0
 public function deleteTeam($id)
 {
     Flight::auth()->check(20);
     $team = Flight::teams()->getTeamWithId($id);
     $team->delete();
     Flight::redirect('/teams');
 }
Exemplo n.º 25
0
 /**
  * Check if the user is authorized
  */
 public function __construct($install, $login = false)
 {
     if (!isset($_SESSION['admin']) && !$install && !$login) {
         F::redirect('/login');
     }
     parent::__construct($install);
 }
Exemplo n.º 26
0
function query($type)
{
    if (!is_null($type)) {
        //get parameter data
        $parameters = Flight::request()->query->getData();
        $cacheKey = $type . json_encode($parameters);
        if (apc_exists($cacheKey)) {
            echo apc_fetch($cacheKey);
        } else {
            $url = 'http://localhost:8080/sparql';
            $query_string = file_get_contents('queries/' . $type . '.txt');
            foreach ($parameters as $key => $value) {
                $query_string = str_replace('{' . $key . '}', $value, $query_string);
            }
            //open connection
            $ch = curl_init();
            //set the url, number of POST vars, POST data
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/sparql-query"));
            curl_setopt($ch, CURLOPT_POSTFIELDS, $query_string);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            //execute post
            $result = curl_exec($ch);
            //close connection
            curl_close($ch);
            apc_store($cacheKey, $result);
            echo $result;
        }
    }
}
 public static function getPlanoContas()
 {
     $dao = new PlanoContaDao();
     $data = $dao->getPlanoContas($_GET);
     /*$itemsByReference = array();
     		
     		// Build array of item references:
     		foreach($data as $key => &$item) {
     			$itemsByReference[$item['cod_item']] = &$item;
     			// Children array:
     			$itemsByReference[$item['cod_item']]['children'] = array();
     			// Empty data class (so that json_encode adds "data: {}" )
     			$itemsByReference[$item['cod_item']]['data'] = new StdClass();
     		}
     
     		// Set items as children of the relevant parent item.
     		foreach($data as $key => &$item)
     			if($item['cod_item_pai'] && isset($itemsByReference[$item['cod_item_pai']]))
     				$itemsByReference [$item['cod_item_pai']]['children'][] = &$item;
     		
     		// Remove items that were added to parents elsewhere:
     		foreach($data as $key => &$item) {
     			if($item['cod_item_pai'] && isset($itemsByReference[$item['cod_item_pai']]))
     				unset($data[$key]);
     		}*/
     Flight::json($data);
 }
Exemplo n.º 28
0
 public static function read()
 {
     try {
         $Conexao = new Conexao();
         $query = $_GET['query'];
         if (is_array($query)) {
             $dados = array();
             foreach ($query as $key => $value) {
                 $fetchAll = isset($_GET['fetchAll'][$key]) ? strtolower($_GET['fetchAll'][$key]) == 'false' ? false : true : true;
                 $offset = isset($_GET['offset'][$key]) ? $_GET['offset'][$key] : null;
                 $limit = isset($_GET['limit'][$key]) ? $_GET['limit'][$key] : null;
                 $dados[$key] = $Conexao->select($value, $fetchAll, $offset, $limit);
             }
             Flight::json($dados);
         } else {
             $fetchAll = isset($_GET['fetchAll']) ? strtolower($_GET['fetchAll']) == 'false' ? false : true : true;
             $offset = isset($_GET['offset']) ? $_GET['offset'] : null;
             $limit = isset($_GET['limit']) ? $_GET['limit'] : null;
             $dados = $Conexao->select($query, $fetchAll, $offset, $limit);
             Flight::json($dados);
         }
     } catch (Exception $e) {
         $e->sql = $query;
         jsonException($e, 500);
     }
 }
Exemplo n.º 29
0
function smarty_function_res($params, &$smarty)
{
    if (empty($params['path'])) {
        return "[plugin:res] missing parameter.";
    }
    return \Flight::get('root') . 'web/' . $params['path'];
}
Exemplo n.º 30
-1
 public static function toptrack($artist_id)
 {
     $headers = array("Accept" => "application/json");
     $url = "https://api.spotify.com/v1/artists/{$artist_id}/top-tracks?country=US";
     $artist_top_track = Unirest\Request::get($url, $headers)->body;
     Flight::json($artist_top_track);
 }