/** * 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">×</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(); }
/** * Save properties of the user profile * @return [JSON] Success or error message */ public static function saveProfile() { if (!Flight::has('currentUser')) { Flight::json(['Error' => 'No Access']); } $currentUser = Flight::get('currentUser'); if (isset(Flight::request()->query->bio)) { $currentUser->bio = Flight::request()->data->bio; } else { if (isset(Flight::request()->query->password)) { if (!isset(Flight::request()->data->passwordold) || !isset(Flight::request()->data->passwordnew1) || !isset(Flight::request()->data->passwordnew2)) { Flight::json(['success' => false, 'exception' => 'Empty fields']); } if ($currentUser->password === hash("sha256", Flight::request()->data->passwordold)) { if (Flight::request()->data->passwordnew1 == Flight::request()->data->passwordnew2) { $currentUser->password = hash("sha256", Flight::request()->data->passwordnew1); } else { Flight::json(['success' => false, 'exception' => 'New passwords are not the same']); } } else { Flight::json(['success' => false, 'exception' => 'Old password is not correct ']); } } } $result = $currentUser->update(); if ($result != false) { $_SESSION['user'] = Flight::users()->getUserWithId(Flight::get('currentUser')->id); Flight::json(['success' => true]); } else { Flight::json(['sucess' => false, 'exception' => 'An error']); } }
public function deleteAbsence($id) { Flight::auth()->check(); $absence = Flight::absence()->getAbsenceWithId($id); $absence->delete(); Flight::redirect(Flight::request()->referrer); }
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 random() { $request = Flight::request(); if (!empty($_SESSION['user_id'])) { $movies_viewed = $_SESSION['movies_viewed']; $dbname = 'predictionio_appdata'; $mdb = Flight::mdb(); $db = $mdb->{$dbname}; $skip = mt_rand(1, 2000); $items = $db->items; $cursor = $items->find(array('itypes' => '1'))->skip($skip)->limit(1); $data = array_values(iterator_to_array($cursor)); $movie = $data[0]; if (!empty($request->data['movie_id'])) { $params = $request->data; $client = Flight::prediction_client(); $user_id = $_SESSION['user_id']; $movie_id = substr($params['movie_id'], strpos($params['movie_id'], '_') + 1); $action = $params['action']; $client->identify($user_id); $user_action = $client->getCommand('record_action_on_item', array('pio_action' => $action, 'pio_iid' => $movie_id)); $client->execute($user_action); $movies_viewed += 1; if ($movies_viewed == 20) { $movie['has_recommended'] = true; } $_SESSION['movies_viewed'] = $movies_viewed; } Flight::json($movie); } }
/** * Login POST verification (authentication) */ public function access() { $pass = F::request()->data->password; # captcha if (!empty(F::get('config')['recaptcha']['public'])) { $captcha = F::request()->data['g-recaptcha-response']; if (!Verif::okCaptcha($captcha)) { $_SESSION['flashbag'] = '<div class="alert alert-danger">Wrong security captcha.</div>'; $this->index(); exit; } } # password if (Verif::okPassword($pass)) { $_SESSION['admin'] = 1; $_SESSION['flashbag'] = ' <div class="alert alert-success alert-dismissible"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button> You are now logged in. </div>'; F::redirect('/'); } else { $_SESSION['flashbag'] = '<div class="alert alert-danger">Wrong password.</div>'; } $this->index(); }
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); }
/** * getBasePath * * @return string */ function getBasePath() { if (strlen(Flight::request()->base) == 1) { return getWebsiteUrl() . '/'; } return getWebsiteUrl() . Flight::request()->base . '/'; }
static function snippet() { $data = Flight::request()->data; $mode = $data["mode"]; if ($mode === "get") { $sql = "SELECT * FROM snippets WHERE LOWER(identifier) LIKE LOWER(?)"; $sth = Flight::db()->prepare($sql); $sth->bindParam(1, $data["identifier"]); $sth->execute(); $res = $sth->fetchAll(PDO::FETCH_ASSOC); if (count($res) == 0) { Flight::error(); } echo Flight::json($res[0]); } elseif ($mode === "exists") { $sql = "SELECT * FROM snippets WHERE LOWER(identifier) LIKE LOWER(?)"; $sth = Flight::db()->prepare($sql); $sth->bindParam(1, $data["identifier"]); $sth->execute(); $res = $sth->fetchAll(PDO::FETCH_ASSOC); if (count($res) !== 0) { Flight::error(); } else { echo ""; } } elseif ($mode === "new") { $sql = "SELECT * FROM snippets WHERE LOWER(identifier) LIKE LOWER(?)"; $sth = Flight::db()->prepare($sql); $sth->bindParam(1, $data["identifier"]); $sth->execute(); $res = $sth->fetchAll(); if (count($res) !== 0) { Flight::error(); } $jwt = JWTHelper::authenticate(apache_request_headers()); $sql = "INSERT INTO snippets(identifier,name,author,version,code) VALUES(?,?,?,?,?)"; $sth = Flight::db()->prepare($sql); $sth->bindParam(1, $data["identifier"]); $sth->bindParam(2, $data["name"]); $sth->bindParam(3, $jwt->data->userName); $sth->bindParam(4, $data["version"]); $sth->bindParam(5, $data["code"]); $sth->execute(); } elseif ($mode === "delete") { $sql = "SELECT * FROM snippets WHERE LOWER(identfier) LIKE LOWER(?)"; $sth = Flight::db()->prepare($sql); $sth->bindParam(1, $data["identifier"]); $sth->execute(); $res = $sth->fetchAll(); if (count($res) !== 1) { Flight::error(); } $jwt = JWTHelper::authenticate(apache_request_headers()); $sql = "DELETE FROM snippets WHERE LOWER(identifier) LIKE LOWER(?)"; $sth = Flight::db()->prepare($sql); $sth->bindParam(1, $data["identifier"]); $sth->execute(); } }
/** * Create a post */ public static function createPost() { if (!Flight::has('currentUser')) { Flight::redirect('/'); } $post = new post(['user' => Flight::get('currentUser')->id, 'title' => Flight::request()->data->title, 'content' => Flight::request()->data->content]); $post->store(); }
static function act($client_name, $api_name, $api_version, $request_json) { try { require_once MODELS_DIR . '/client.php'; require_once MODELS_DIR . '/exceptioner.php'; $client = new Client($client_name); $api_name_low_case = strtolower($api_name); $method_name_low_case = strtolower(Flight::request()->method); //cek adanya user Exceptioner::thrower(!$client->getClientExistenceBool(), "{$client_name} is not registered"); //Cek adanya API Exceptioner::thrower(!file_exists(APIS_DIR . "/{$api_name_low_case}"), "{$api_name} API not available"); //Cek adanya API buatnya Exceptioner::thrower(!$client->getClientAPIAvailibilityBool($api_name_low_case), "{$api_name} API is exist but not available for {$client_name} client"); //Cek adanya versi api Exceptioner::thrower(!file_exists(APIS_DIR . "/{$api_name_low_case}/{$api_version}"), "{$api_version} of {$api_name} API not available"); // Cek REST method Exceptioner::thrower(!file_exists(APIS_DIR . "/{$api_name_low_case}/{$api_version}/controllers/{$method_name_low_case}.php"), Flight::request()->method . " REST Method in {$api_version} of {$api_name} API not available"); //Include require_once APIS_DIR . "/{$api_name_low_case}/{$api_version}/includes.php"; //decrypt request, ubah request jadi array $request_array = DECRYPT_REQUEST ? $client->requestDecrypt($request_json) : json_decode(base64_decode(urldecode($request_json)), TRUE); $object_method = $request_array['method']; $request_params = $request_array['parameters']; //buat object $controller_name = $method_name_low_case . "Controller"; $object = new $controller_name($request_params); //Check adanya object_method Exceptioner::thrower(!$object_method, "Method in request is NULL, or Decrypting Failed"); //Check adanya method Exceptioner::thrower(!method_exists($object, "{$object_method}"), "{$object_method} object method in {$api_name} API {$api_version} not available"); //Buat result, lihat toggle enkripsi ENCRYPT_RESPONSE ? $result['encrypted_data'] = $client->respondEncrypt($object->{$object_method}()) : ($result['decrypted_data'] = $object->{$object_method}()); $result['success'] = true; } catch (Exception $e) { //catch any exceptions and report the problem $result = array(); $result['errormsg'] = $e->getMessage(); $result['success'] = false; } // Return Type Based o if (DEBUG_MODE) { echo "<pre>"; echo "<br>DEBUG_MODE : " . DEBUG_MODE . "<br>"; echo "<br>METHOD : " . Flight::request()->method . "<br>"; echo "<br>ENCRYPT_RESPONSE : " . ENCRYPT_RESPONSE . "<br>"; echo "<br>DECRYPT_REQUEST : " . DECRYPT_REQUEST . "<br>"; echo '<br>$request_array : '; print_r($request_array); echo '<br>$result : '; print_r($result); echo "</pre>"; } else { echo json_encode($result); } }
public function initByCookie() { $hash = Flight::request()->cookies[Auth::COOKIE_INDETIFICATION]; if ($hash) { $User = User::find_by_auth_hash($hash); if ($User instanceof User) { $this->authorize($User); } } }
public function getProducts() { # code... $pid = new getproduct(); $post = json_decode(Flight::request()->getBody()); DuoWorldCommon::mapToObject($post, $pid); $client = ObjectStoreClient::WithNamespace(DuoWorldCommon::GetHost(), "Products", "123"); $respond = $client->get()->byKey($post->productId); echo json_encode($respond); }
private function uploadMedia($namespace, $class, $id) { $filepath = STORAGE_PATH . "/" . $namespace . "/" . $class; if (file_exists($filepath) == false) { echo json_encode(STORAGE_PATH); mkdir(STORAGE_PATH . "/" . $namespace); mkdir(STORAGE_PATH . "/" . $namespace . "/" . $class); } echo json_encode(file_put_contents($filepath . "/" . "{$id}.jpg", Flight::request()->getBody())); }
function real_remote_addr() { $ip = Flight::request()->ip; $proxy = Flight::request()->proxy_ip; if ('' != $proxy && Flight::get('proxies')->match($ip)) { return $proxy; } else { return $ip; } }
function dump_request($exit = true) { $request = Flight::request(); echo '<pre>'; print_r($request); echo '</pre>'; if ($exit) { exit; } }
function testDefaultComponents() { $request = Flight::request(); $response = Flight::response(); $router = Flight::router(); $view = Flight::view(); $this->assertEquals('flight\\net\\Request', get_class($request)); $this->assertEquals('flight\\net\\Response', get_class($response)); $this->assertEquals('flight\\net\\Router', get_class($router)); $this->assertEquals('flight\\template\\View', get_class($view)); }
public function saveNewEvent() { Flight::auth()->check(); $response = Flight::util()->validate('event', Flight::request()->data); if (is_array($response)) { Flight::util()->render('newEvent', array('team_id' => Flight::request()->data->team, 'error' => $response)); return; } $event = new event(Flight::request()->data); $id = $event->store(); Flight::redirect('/event/' . $id); }
public function updatePlayer($id) { Flight::auth()->check(); $response = Flight::util()->validate('player', Flight::request()->data); if (is_array($response)) { Flight::util()->render('editPlayer', array('player' => Flight::players()->getPlayerWithId($id), 'teams' => Flight::teams()->getAllTeams(), 'error' => $response)); return; } $player = new player(Flight::request()->data); $player->update(); Flight::redirect('/player/' . $id); }
public function saveNewTeam() { Flight::auth()->check(20); $response = Flight::util()->validate('team', Flight::request()->data); if (is_array($response)) { Flight::util()->render('newTeam', array("error" => $response)); return; } $team = new team(Flight::request()->data); $last_id = $team->store(); Flight::redirect('/team/' . $last_id); }
public function removeUserFromGroup() { $post = json_decode(Flight::request()->getBody()); $client = ObjectStoreClient::WithNamespace(DuoWorldCommon::GetHost(), "UserGroup", "123"); $respond = $client->get()->byKey($post->groupId); if (($key = array_search($post->users, $respond->users)) !== false) { unset($respond->users[$key]); $Inrespond = $client->store()->byKeyField("groupId")->andStore($respond); echo json_encode($Inrespond); } else { echo json_encode("user not found..."); } }
public function register() { Flight::auth()->check(20); $response = Flight::util()->validate("user", Flight::request()->data); if (is_array($response)) { Flight::util()->render('newUser', array('error' => $response, "teams" => Flight::teams()->getAllTeams())); return; } $data = Flight::request()->data; $user = new user($data); $user->teams = Flight::request()->data->teams; $user->store(); Flight::redirect("/createUser"); }
public function createUSer() { $data = json_decode(Flight::request()->getBody()); $user = new User(); $user->UserID = $data->UserID; $user->EmailAddress = $data->EmailAddress; $user->Name = $data->EmailAddress; $user->Password = $data->EmailAddress; $user->ConfirmPassword = $data->EmailAddress; $user->Active = false; $authproxyobj = new AuthProxy(); $respond = $authproxyobj->AddUser($user); echo json_encode($respond); }
public static function init($config = 'config/config.php') { //set up our autoloader spl_autoload_register(array('PhpReports', 'loader'), true, true); if (!file_exists($config)) { throw new Exception("Cannot find config file"); } // The config.php.sample is used to populate default values should the config.php be incomplete. // As a result, we require it be there. if (!file_exists('config/config.php.sample')) { throw new Exception("Cannot find sample config. Please leave config/config.php.sample in place for default values."); } $default_config = (include 'config/config.php.sample'); $config = (include $config); self::$config = array_merge($default_config, $config); self::$request = Flight::request(); $path = self::$request->base; if (isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1) || isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') { $protocol = 'https://'; } else { $protocol = 'http://'; } self::$request->base = $protocol . rtrim($_SERVER['HTTP_HOST'] . self::$request->base, '/'); //the load order for templates is: "templates/local", "templates/default", "templates" //this means loading the template "html/report.twig" will load the local first and then the default //if you want to extend a default template from within a local template, you can do {% extends "default/html/report.twig" %} and it will fall back to the last loader $template_dirs = array('templates/default', 'templates'); if (file_exists('templates/local')) { array_unshift($template_dirs, 'templates/local'); } $loader = new Twig_Loader_Chain(array(new Twig_Loader_Filesystem($template_dirs), new Twig_Loader_String())); self::$twig = new Twig_Environment($loader); self::$twig->addFunction(new Twig_SimpleFunction('dbdate', 'PhpReports::dbdate')); self::$twig->addFunction(new Twig_SimpleFunction('sqlin', 'PhpReports::generateSqlIN')); if (isset($_COOKIE['reports-theme']) && $_COOKIE['reports-theme']) { $theme = $_COOKIE['reports-theme']; } else { $theme = self::$config['bootstrap_theme']; } self::$twig->addGlobal('theme', $theme); self::$twig->addGlobal('path', $path); self::$twig->addFilter('var_dump', new Twig_Filter_Function('var_dump')); self::$twig_string = new Twig_Environment(new Twig_Loader_String(), array('autoescape' => false)); self::$twig_string->addFunction(new Twig_SimpleFunction('sqlin', 'PhpReports::generateSqlIN')); FileSystemCache::$cacheDir = self::$config['cacheDir']; if (!isset($_SESSION['environment']) || !isset(self::$config['environments'][$_SESSION['environment']])) { $_SESSION['environment'] = array_shift(array_keys(self::$config['environments'])); } }
public static function index() { $req = explode('/', Flight::request()->url); $app = isset($req[1]) ? $req[1] : ''; $act = isset($req[2]) ? $req[2] : ''; if (!in_array("{$app}.{$act}", self::$no_login_array)) { if (!Session::get('is_login')) { User::login(); return false; } else { return true; } } return true; }
/** * Login with email and password */ public static function login() { $email = Flight::request()->data->email; $password = Flight::request()->data->password; $user = Flight::users()->getUserWithEmail($email); if ($user == false) { Flight::util()->render('login', ['error' => 'login']); } else { if (hash("sha256", $password) == $user->password) { $_SESSION['user'] = $user; Flight::redirect("/"); } else { Flight::util()->render('login', ['error' => 'login']); } } }
public static function getMyWages() { $req = Flight::request()->query; $limit = $req['limit'] ? $req['limit'] : 10; $offset = $req['offset'] ? $req['offset'] : 0; $search = $req['search'] ? $req['search'] : ''; $ser_id = Session::get('ser_id'); $db = Flight::get('db'); $cond = array("ORDER" => "add_time DESC", "LIMIT" => array($offset, $limit)); if ($search) { $cond['AND'] = array("ser_name" => $search); } $cond['AND']['ser_id'] = $ser_id; $data = $db->select("wages", array("[>]services" => "ser_id"), "*", $cond); $total = $db->count("wages"); Flight::json(array("total" => $total, 'rows' => $data)); }
/** * bootstrap * for framework bootstrap. */ public static function bootstrap() { //route require APP_PATH . '/routes.php'; //set timezone $timezone = env('APP_TIMEZONE', 'Asia/Shanghai'); date_default_timezone_set($timezone); //filters if (get_magic_quotes_gpc()) { $_GET = self::stripslashesDeep($_GET); $_POST = self::stripslashesDeep($_POST); $_COOKIE = self::stripslashesDeep($_COOKIE); } $_REQUEST = array_merge($_GET, $_POST, $_COOKIE); /*-- Flight maps start --*/ //log Flight::map('log', [__CLASS__, 'log']); //db : database Flight::map('db', [__CLASS__, 'db']); //model Flight::map('model', [__CLASS__, 'getModel']); //cache Flight::map('cache', [__CLASS__, 'cache']); //get controller Flight::map('controller', [__CLASS__, 'getController']); //halt response Flight::map("halt", array(__CLASS__, "halt")); //404 error Flight::map('notFound', function () { //Flight::log()->error(Flight::request()->ip.': '.Flight::request()->method.' '.Flight::request()->url.' not Found !'); Flight::log()->error('404 NOT FOUND !', json_decode(json_encode(Flight::request()), true)); return self::halt(Flight::view()->fetch('404'), '404'); }); /* Flight::map('error', function(Exception $ex){ // Handle error Flight::log()->error('500 Error : '.$ex->getTraceAsString()); echo $ex->getTraceAsString(); }); */ /*-- Flight maps end --*/ }
public function saveUserSettings() { Flight::auth()->check(); if (Flight::request()->data->id != Flight::auth()->currentUser->id) { Flight::auth()->check(20); } $user = Flight::users()->getUserWithId(Flight::request()->data->id); $response = Flight::util()->validate('user', Flight::request()->data, true); if (is_array($response)) { Flight::util()->render('editUser', array("teams" => Flight::teams()->getAllTeams(), "user" => $user, "error" => $response)); return; } $user = new user(Flight::request()->data); $user->teams = Flight::request()->data->teams; if ($user->update()) { Flight::util()->render('editUser', array("teams" => Flight::teams()->getAllTeams(), "user" => $user, "flash" => array("word" => "User", "action" => "updated"))); } }
/** * Reading / Editing page */ public function page($params) { $mode = $params[0]; $pageinfos = F::get('pageinfos'); if (empty($pageinfos['cat'])) { $pageTitle = F::get('config')['document']; $url_view = '{$root}'; $url_edit = '{$root}.edit'; $path = 'docs/.home'; } else { $pageTitle = Files::getPageTitle($pageinfos['cat'], $pageinfos['page']); $url_view = '{$root}' . $pageinfos['cat'] . '/' . $pageinfos['page']; $url_edit = '{$root}' . $pageinfos['cat'] . '/' . $pageinfos['page'] . '.edit'; $path = 'docs/' . $pageinfos['cat'] . '/' . $pageinfos['page']; } if (file_exists($path) && is_file($path) && is_readable($path)) { $pageContent = file_get_contents($path); # Edit mode if ($mode == 'edit' && F::has('admin')) { # Content submited if (F::request()->method == 'POST') { $pageContent = F::request()->data->pageContent; file_put_contents($path, $pageContent); $_SESSION['flashbag'] = ' <div class="alert alert-success alert-dismissible"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button> The page has been saved </div>'; F::redirect('/' . $pageinfos['cat'] . '/' . $pageinfos['page']); } else { $pageContent = file_get_contents($path); F::render('Doc/page-edit.html', array('page_edit_url' => $url_edit, 'page_view_url' => $url_view, 'page_title' => $pageTitle, 'page_content' => $pageContent, 'edition_mode' => true)); } } else { F::render('Doc/page-view.html', array('page_edit_url' => $url_edit, 'page_title' => $pageTitle, 'page_content' => $pageContent, 'page_last_modif' => date('Y-m-d H:i:s', filemtime($path)))); } } else { F::render('Core/404.html'); } }