Example #1
1
<?php

error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once 'flight/flight/Flight.php';
require_once 'ipsp-php/autoload.php';
Flight::set('flight.views.path', 'templates');
Flight::set('layout', 'layout/default');
Flight::set('appname', 'IPSP PHP Examples');
Flight::set('apptitle', 'Api');
Flight::register('ipsp', 'Ipsp_Api', array(new Ipsp_Client(1000, 'test', 'api.oplata.com')));
Flight::map('output', function ($content = NULL) {
    Flight::view()->set('ipsp', Flight::ipsp());
    Flight::render($content, array(), 'content');
    Flight::render(Flight::get('layout'));
});
Flight::route('/', function () {
    Flight::output('pages/frontpage');
});
Flight::route('/page/@page(/@order_id)', function ($page = 'notfound', $order_id = NULL) {
    Flight::view()->set('order_id', $order_id);
    Flight::output(sprintf('pages/%s', $page));
});
Flight::route('/modal/@page', function ($page = 'notfound') {
    Flight::view()->set('ipsp', Flight::ipsp());
    Flight::render(sprintf('modal/%s', $page));
});
Flight::route('/api/checkout', function () {
    $data = Flight::request()->data;
});
Flight::start();
 public static function init()
 {
     date_default_timezone_set("Etc/GMT");
     if (get_magic_quotes_gpc()) {
         $_GET = self::stripslashesDeep($_GET);
         $_POST = self::stripslashesDeep($_POST);
         $_COOKIE = self::stripslashesDeep($_COOKIE);
     }
     $_REQUEST = array_merge($_GET, $_POST, $_COOKIE);
     Flight::map("db", array(__CLASS__, "db"));
     //Flight::map("cache", array(__CLASS__, "cache"));
     Flight::map("log", array(__CLASS__, "log"));
     Flight::map("curl", array(__CLASS__, "curl"));
     Flight::map("halt", array(__CLASS__, "halt"));
     Flight::map("getRunTime", array(__CLASS__, "getRunTime"));
     Flight::map("returnJson", array(__CLASS__, "returnJson"));
     Flight::map("controller", array(__CLASS__, "getController"));
     Flight::map("model", array(__CLASS__, "getModel"));
     Flight::map("url", array(__CLASS__, "url"));
     Flight::map("connectMysqlDB", array(__CLASS__, "connectMysqlDB"));
     Flight::map("closeMysqlDB", array(__CLASS__, "closeMysqlDB"));
     Flight::map("connectMongoDB", array(__CLASS__, "connectMongoDB"));
     Flight::map("closeMongoDB", array(__CLASS__, "closeMongoDB"));
     Flight::map("connectRedis", array(__CLASS__, "connectRedis"));
     Flight::set('flight.log_errors', true);
     //写一个日志
     //if(Flight::request()->method == "POST") {
     // Flight::log("post-".date("Ymd"))->info(print_r($_POST, TRUE));
     //}
     self::initRoute();
 }
Example #3
0
 function testMap()
 {
     Flight::map('map1', function () {
         return 'hello';
     });
     $result = Flight::map1();
     $this->assertEquals('hello', $result);
 }
Example #4
0
 /**
  * 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
       --*/
 }
Example #5
0
    Flight::result(401, $result);
});
//forbidden
Flight::map('forbidden', function ($message) {
    $result = new Result();
    $result->Status = Result::ERROR;
    $result->Message = $message;
    Flight::result(403, $result);
});
//notFound
Flight::map('notFound', function ($message) {
    $result = new Result();
    $result->Status = Result::NOTFOUND;
    $result->Message = $message;
    Flight::result(404, $result);
});
// Flight::map('noContent', function($message){
// 	$result = new Result();
// 	$result->Status = Result::ERROR;
// 	$result->Message = $message;
// 	Flight::result(204,$result);
// });
Flight::map('error', function (Exception $exception) {
    $result = new Result();
    $result->Status = Result::ERROR;
    $result->Message = $exception->getMessage();
    Flight::result(501, $result);
});
Flight::map('result', function ($status, $result) {
    Flight::response()->status($status)->header('Access-Control-Allow-Origin', '*')->header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS,PATCH')->header('Access-Control-Allow-Headers', 'Content-Type')->header('Content-Type', 'application/json')->write(utf8_decode(json_encode($result)))->send();
});
Example #6
0
File: routes.php Project: npk/Ourls
            $id = Flight::get('hash')->decode($hash);
            if (!$id) {
                Flight::json(['status' => 0, 'msg' => '短址无法解析']);
            } else {
                $store = Flight::get('db')->select('urls', ['url'], ['id' => $id]);
                if (!$store) {
                    Flight::json(['status' => 0, 'msg' => '地址不存在']);
                } else {
                    Flight::json(['status' => 1, 'url' => $store[0]['url']]);
                }
            }
        }
    }
});
Flight::route('/@hash', function ($hash) {
    $id = Flight::get('hash')->decode($hash);
    if (!$id) {
        Flight::notFound('短址无法解析');
    } else {
        $store = Flight::get('db')->select('urls', ['url'], ['id' => $id]);
        if (!$store) {
            Flight::notFound('地址不存在');
        } else {
            Flight::get('db')->update('urls', ['count[+]' => 1], ['id' => $id]);
            Flight::redirect($store[0]['url'], 302);
        }
    }
});
Flight::map('notFound', function ($message) {
    Flight::response()->status(404)->header('content-type', 'text/html; charset=utf-8')->write('<h1>404 页面未找到</h1>' . "<h3>{$message}</h3>" . '<p><a href="' . Flight::get('flight.base_url') . '">回到首页</a></p>' . str_repeat(' ', 512))->send();
});
Example #7
0
<?php

if (!function_exists('avg')) {
    function avg(array $data)
    {
        return array_sum($data) / count($data);
    }
}
/**
 * Registers a class and set a variable to framework method.
 *
 * @param string $name Method name
 * @param string $class Class name
 * @param array $params Class initialization parameters
 * @param callback $callback Function to call after object instantiation
 * @throws \Exception If trying to map over a framework method
 */
Flight::map('instance', function ($name, $class, array $params = array(), $callback = null) {
    Flight::register($name, $class, $params, $callback);
    Flight::set($name, Flight::$name());
});
Example #8
0
<?php

require dirname(__DIR__) . '/vendor/autoload.php';
Flight::route('/', function () {
    echo "OK Route: /";
});
Flight::route('/something', function () {
    echo "OK Route: /something";
});
Flight::map('notFound', function () {
    echo "KO";
});
Flight::start();
Example #9
0
<?php

Flight::route('/', array('welcomeController', 'welcome'));
\Flight::map('notFound', function () {
    \Flight::render('404', array());
});
Example #10
0
    if (!($plugins = plugins_get_by_tag($tag))) {
        Flight::notFound();
    }
    Flight::render($view, array('tag' => $tag, 'plugins' => $plugins));
});
/**
 * 404
 */
Flight::map('notFound', function () {
    site_title('404 - not found :(');
    $request = Flight::request();
    // see if a page exists
    if ($page_info = page_exists($request->url)) {
        site_title($page_info['title']);
        if (null !== $page_info['description']) {
            site_description($page_info['description']);
        }
        Flight::render($page_info['view']);
        die;
    }
    // see if there's a valid permanent redirect, and if there is send the user to the new location
    if ($redirect_url = redirect_destination($request->url)) {
        Flight::redirect($redirect_url, 301);
        die;
    }
    header('HTTP/1.0 404 Not Found');
    site_header_title('404 :(');
    site_description('<a href="' . path() . '">Visit the homepage <i class="fa fa-arrow-right"></i></a>');
    Flight::render('404.php');
    die;
});
Example #11
0
// Registering Smarty as template engine
Flight::register('view', 'Smarty', array(), function ($smarty) {
    $smarty->template_dir = Flight::get('flight.views.path') . '/';
    $smarty->compile_dir = __DIR__ . '/../app/cache/smarty_compile/';
    $smarty->config_dir = __DIR__ . '/../app/config/smarty/';
    $smarty->cache_dir = __DIR__ . '/../app/cache/smarty_cache/';
});
Flight::map('render', function ($template, $data) {
    Flight::view()->assign($data);
    Flight::view()->display($template);
});
//personnalizing errors
Flight::map('notFound', function () {
    if (file_exists(Flight::get('flight.views.path') . '/Errors/404.tpl')) {
        Flight::render('Errors/404.tpl', array());
    } else {
        Flight::_notFound();
    }
});
Flight::map('error', function (\Exception $e) {
    $code = http_response_code();
    if ($code == 200) {
        $code = 500;
    }
    if (file_exists(Flight::get('flight.views.path') . '/Errors/' . $code . '.tpl')) {
        Flight::render('Errors/' . $code . '.tpl', array('message' => $e->getMessage(), 'code' => $e->getCode(), 'line' => $e->getLine(), 'file' => $e->getFile(), 'traceString' => $e->getTraceAsString(), 'trace' => $e->getTrace()));
    } else {
        Flight::_error($e);
    }
});
Flight::start();
Example #12
0
            $patternSrv->report($id, 1);
            break;
        case '2':
            // view
            echo 2;
            break;
        case '3':
            // report
            echo 3;
            break;
    }
});
// 404 not found Handling
Flight::map('notFound', function () {
    $error = array();
    $error[] = ERROR_404;
    $_SESSION[ERROR] = $error;
    Flight::redirect('/error');
});
// Error Handling
// 	Flight::map('error', function(Exception $ex){
// 		// Handle error
// 		$error = array();
// 		$error[] = SYSTEM_ERROR;
// 		if(OUT_ERROR) {
// 			$error[] = '<pre>'.$ex->getTraceAsString().'</pre>';
// 		}
// 		$_SESSION[ERROR] = $error;
// 		Flight::redirect('/error');
// 	});
Flight::route('/create', function () {
    // 			echo 'create';
Example #13
0
<?php

require_once 'vendor/flight/flight/autoload.php';
require_once 'vendor/flight/flight/Flight.php';
//Connect to database
$dbinfo = array('mysql:host=localhost;dbname=benchmarked', 'root', '');
Flight::register('db', 'PDO', $dbinfo, function ($db) {
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
});
//Error message
Flight::map('errmsg', function ($msg, $show = true) {
    if ($show) {
        return $msg;
    } else {
        return;
    }
});
//Home page
Flight::route('/', function () {
    echo 'Welcome from Flight!';
});
//Put a new result in database
Flight::route('PUT /api/result', function () {
    //Array of named parameters
    $body = Flight::request()->getBody();
    $values = array();
    $nv_strings = explode('&', $body);
    foreach ($nv_strings as $s) {
        $nv = explode('=', $s, 2);
        $name = urldecode($nv[0]);
        $value = isset($nv[1]) ? urldecode($nv[1]) : null;
Example #14
0
<?php

require_once 'Config.php';
require_once 'flight/Flight.php';
require_once 'Controller.php';
Controller::connectDB();
Flight::map('error', function (Exception $ex) {
    // Handle error
    echo $ex->getTraceAsString();
});
Flight::route('POST *', function () {
    //Every POST request goes trought a check of the api key
    Controller::check_api_key_post();
    return true;
});
Flight::route('POST /user/create', function () {
    $data = Controller::collect_post_value('email', true);
    $data = Controller::collect_post_value('password', true, $data);
    $data = Controller::collect_post_value('type', false, $data, 'int');
    $data = Controller::collect_post_value('name', false, $data);
    $data = Controller::collect_post_image('avatar', false, $data);
    $data = Controller::collect_post_value('statistics', false, $data, 'json');
    $data = Controller::collect_post_image('photo_1', false, $data);
    $data = Controller::collect_post_image('photo_2', false, $data);
    $data = Controller::collect_post_image('photo_3', false, $data);
    $data = Controller::collect_post_value('founders', false, $data);
    $data = Controller::collect_post_value('website', false, $data);
    $data = Controller::collect_post_value('video', false, $data);
    $data = Controller::collect_post_value('activity', false, $data);
    $data = Controller::collect_post_value('sector_activity', false, $data);
    $data = Controller::collect_post_value('type_activity', false, $data);
Example #15
0
<?php

include "vendor/autoload.php";
use calebdre\ApiSugar\Api;
use LikeAPro\Controllers\SubmissionsController;
use LikeAPro\Controllers\UserController;
$api = new Api();
$api->configureDB(['driver' => "mysql", "host" => "localhost", "database" => "likeapro", "username" => "root", "password" => "", "charset" => "utf8", "collation" => "utf8_unicode_ci", "prefix" => ""]);
$api->addClass(new SubmissionsController());
$api->addClass(new UserController());
Flight::map('notFound', function () {
    header("Location " . substr(parse_url($_SERVER['REQUEST_URI'])['path'], 1));
});
$api->execute();
Example #16
0
Flight::map('checkIP', function ($ip) {
    // query db for ip first
    $db = Flight::db();
    // If localhost set a real IP
    // live hosting should erase this below!
    if ($ip === '::1') {
        $ip = '24.105.250.46';
    }
    $dbquery = "SELECT * FROM geo WHERE ip IS '" . $ip . "'";
    $result = $db->query($dbquery);
    // does it exist in db?
    if ($result->fetch(PDO::FETCH_NUM) > 0) {
        $result = $db->query($dbquery);
        foreach ($result as $row) {
            // set geo information into globals
            if (strlen($row['ip']) > 0) {
                Flight::set('ip', $row['ip']);
            }
            if (strlen($row['geoplugin_city']) > 0) {
                Flight::set('city', $row['geoplugin_city']);
            }
            if (strlen($row['geoplugin_region']) > 0) {
                Flight::set('region', $row['geoplugin_region']);
            }
            if (strlen($row['geoplugin_areaCode']) > 0) {
                Flight::set('areaCode', $row['geoplugin_areaCode']);
            }
            if (strlen($row['geoplugin_dmaCode']) > 0) {
                Flight::set('dmaCode', $row['geoplugin_dmaCode']);
            }
            if (strlen($row['geoplugin_countryCode']) > 0) {
                Flight::set('countryCode', $row['geoplugin_countryCode']);
            }
            if (strlen($row['geoplugin_countryName']) > 0) {
                Flight::set('countryName', $row['geoplugin_countryName']);
            }
            if (strlen($row['geoplugin_continentCode']) > 0) {
                Flight::set('continentCode', $row['geoplugin_continentCode']);
            }
            if (strlen($row['geoplugin_latitude']) > 0) {
                Flight::set('latitude', $row['geoplugin_latitude']);
            }
            if (strlen($row['geoplugin_longitude']) > 0) {
                Flight::set('longitude', $row['geoplugin_longitude']);
            }
            if (strlen($row['geoplugin_regionCode']) > 0) {
                Flight::set('regionCode', $row['geoplugin_regionCode']);
            }
            if (strlen($row['geoplugin_regionName']) > 0) {
                Flight::set('regionName', $row['geoplugin_regionName']);
            }
        }
        Flight::set('geoinfo', true);
    } else {
        require 'includes/geoplugin.class.php';
        $geoplugin = new geoPlugin();
        $geoplugin->locate($ip);
        // geoplugin.com API up?
        if (strlen($geoplugin->ip) > 0) {
            $ipquery = "INSERT INTO geo (ip, geoplugin_city, geoplugin_region, geoplugin_areaCode, geoplugin_dmaCode, geoplugin_countryCode, geoplugin_countryName, geoplugin_continentCode, geoplugin_latitude, geoplugin_longitude, geoplugin_regionCode, geoplugin_regionName) VALUES(:ip, :geoplugin_city, :geoplugin_region, :geoplugin_areaCode, :geoplugin_dmaCode, :geoplugin_countryCode, :geoplugin_countryName, :geoplugin_continentCode, :geoplugin_latitude, :geoplugin_longitude, :geoplugin_regionCode, :geoplugin_regionName)";
            $stmt = $db->prepare($ipquery);
            $stmt->bindParam(':ip', $geoplugin->ip);
            $stmt->bindParam(':geoplugin_city', $geoplugin->city);
            $stmt->bindParam(':geoplugin_region', $geoplugin->region);
            $stmt->bindParam(':geoplugin_areaCode', $geoplugin->areaCode);
            $stmt->bindParam(':geoplugin_dmaCode', $geoplugin->dmaCode);
            $stmt->bindParam(':geoplugin_countryCode', $geoplugin->countryCode);
            $stmt->bindParam(':geoplugin_countryName', $geoplugin->countryName);
            $stmt->bindParam(':geoplugin_continentCode', $geoplugin->continentCode);
            $stmt->bindParam(':geoplugin_latitude', $geoplugin->latitude);
            $stmt->bindParam(':geoplugin_longitude', $geoplugin->longitude);
            $stmt->bindParam(':geoplugin_regionCode', $geoplugin->regionCode);
            $stmt->bindParam(':geoplugin_regionName', $geoplugin->regionName);
            $stmt->execute();
            // globals
            if (strlen($geoplugin->ip) > 0) {
                Flight::set('ip', $geoplugin->ip);
            }
            if (strlen($geoplugin->city) > 0) {
                Flight::set('city', $geoplugin->city);
            }
            if (strlen($geoplugin->region) > 0) {
                Flight::set('region', $geoplugin->region);
            }
            if (strlen($geoplugin->areaCode) > 0) {
                Flight::set('areaCode', $geoplugin->areaCode);
            }
            if (strlen($geoplugin->dmaCode) > 0) {
                Flight::set('dmaCode', $geoplugin->dmaCode);
            }
            if (strlen($geoplugin->countryCode) > 0) {
                Flight::set('countryCode', $geoplugin->countryCode);
            }
            if (strlen($geoplugin->countryName) > 0) {
                Flight::set('countryName', $geoplugin->countryName);
            }
            if (strlen($geoplugin->continentCode) > 0) {
                Flight::set('continentCode', $geoplugin->continentCode);
            }
            if (strlen($geoplugin->latitude) > 0) {
                Flight::set('latitude', $geoplugin->latitude);
            }
            if (strlen($geoplugin->longitude) > 0) {
                Flight::set('longitude', $geoplugin->longitude);
            }
            if (strlen($geoplugin->regionCode) > 0) {
                Flight::set('regionCode', $geoplugin->regionCode);
            }
            if (strlen($geoplugin->regionName) > 0) {
                Flight::set('regionName', $geoplugin->regionName);
            }
            Flight::set('geoinfo', true);
        } else {
            // geoplugin.com not responding
            Flight::set('geoinfo', false);
        }
    }
});
Example #17
0
    require_once $path . '/config.php';
} elseif (is_file($path . '/../config.php')) {
    require_once $path . '/../config.php';
} else {
    echo "Invalid config file.";
    die;
}
// Register classes with Flight
Flight::register('artmoiController', 'ArtMoi_Controller');
Flight::register('artmoiRequest', 'ArtMoi_Request');
Flight::register('artmoiResponse', 'ArtMoi_Response');
Flight::register('artmoiContact', 'ArtMoi_Controller_Contact');
// 404 Error page
Flight::map('notFound', function () {
    Flight::view()->set('errorCode', "404");
    Flight::view()->set('message', "Sorry! 404 Page not Found");
    Flight::view()->set('pageTitle', "404 Page not Found");
    Flight::render('404');
});
// Contact Page
Flight::route('/contact', function () {
    // TODO:: We will need to include the form validation as optional because anyone downloading this project will need to obtain thier own license...
    $js = array("https://v1.artmoi.me/vendor/formvalidation/dist/js/formValidation.min.js", "https://v1.artmoi.me/vendor/formvalidation/dist/js/framework/bootstrap.min.js", "//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.min.js", "/scripts/contact.js");
    $css = array("https://v1.artmoi.me/vendor/formvalidation/dist/css/formValidation.min.css", "//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.min.css");
    $contact = Flight::artmoiContact()->action_contactPoints();
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        if (MANDRILL_API_KEY != null) {
            Flight::artmoiContact()->action_mandrill();
        } else {
            Flight::artmoiContact()->action_sendMail();
        }
    }
Example #18
0
            }
            $channels = empty($postJson->params->channels) ? array('nightly') : $postJson->params->channels;
            $limit = empty($postJson->params->limit) ? 25 : intval($postJson->params->limit);
            $tokens = new TokenCollection($channels, $devicePath, $device);
            $ret['result'] = $tokens->getUpdateList($limit);
        }
    }
    Flight::json($ret);
});
// Deltas
Flight::route('/api/v1/build/get_delta', function () {
    $ret = array();
    $req = Flight::request();
    $postJson = json_decode($req->body);
    if ($postJson != NULL && !empty($postJson->source_incremental) && !empty($postJson->target_incremental)) {
        $source_incremental = $postJson->source_incremental;
        $target_incremental = $postJson->target_incremental;
        if ($source_incremental != $target_incremental) {
            $ret = Delta::find($source_incremental, $target_incremental);
        }
    }
    if (empty($ret)) {
        $ret['errors'] = array('message' => 'Unable to find delta');
    }
    Flight::json($ret);
});
Flight::map('notFound', function () {
    // Display custom 404 page
    echo 'Sorry, 404!';
});
Flight::start();
Example #19
0
<?php

Flight::set("organizer.settings.path", "config/settings.json");
Flight::map("read_settings", function () {
    if (($settings = file_get_contents(Flight::get("organizer.settings.path"))) !== false) {
        return json_decode($settings, true);
    } else {
        return false;
    }
});
Flight::map("load_settings", function () {
    $settings = Flight::read_settings();
    Flight::set("organizer.settings", $settings);
    return $settings;
});
Flight::map("setting", function ($path) {
    $settings = Flight::get("organizer.settings");
    foreach (explode(".", $path) as $key) {
        $settings = $settings[$key];
    }
    return $settings;
});
Flight::map("write_settings", function ($settings) {
    $settings = json_encode($settings);
    return file_put_contents(Flight::get("organizer.settings.path"), $settings);
});
Flight::map("dump_settings", function () {
    return Flight::write_settings(Flight::get("organizer.settings"));
});
Example #20
0
<?php

Flight::path("model/");
Flight::path("controller/");
Flight::register('db', 'mysqli', [$config['db']['host'], $config['db']['username'], $config['db']['password'], $config['db']['databasename']]);
Flight::register("util", "util");
Flight::register("auth", "authController");
Flight::register("posts", "postController");
Flight::register("users", "userController");
Flight::set("flight.base_url", $config['web']['base_url']);
Flight::map('link', function ($url) {
    echo Flight::get('flight.base_url') . $url;
});
Example #21
0
Flight::route('/', function () {
    return Flight::view()->display('index.php', Flight::get('config')->getTemplateData());
});
// ! --- ROUTE: About ---------------------------
Flight::route('/we', function () {
    return Flight::get('config')->renderPage('about');
});
// ! --- ROUTE: Sitemap -------------------------
/**
 * Publishes all routes in the /sitemap.xml
 */
Flight::route('/sitemap.xml', function () {
    $items = Flight::get('navigation.loader')->getNavigationItems();
    $sitemap = array();
    foreach ($items as $item) {
        $sitemap[] = array('Url' => $item->get('Url'), 'DateTime' => $item->get('DateTime'));
    }
    Flight::response()->header('Content-Type', 'application/xml');
    Flight::view()->display('sitemap.php', array('Sitemap' => $sitemap));
});
// ! --- ROUTE: Project -------------------------
Flight::route('/@name', function ($name) {
    return Flight::get('config')->renderPage($name);
});
// ! --- ROUTE: 404 - Not Found -----------------
Flight::map('notFound', function () {
    Flight::view()->display('404.php', Flight::get('config')->getTemplateData());
    Flight::stop(404);
});
// ! --- Kick things off! -----------------------
Flight::start();
Example #22
0
<?php

session_start();
require 'vendor/autoload.php';
use PredictionIO\PredictionIOClient;
Flight::register('mdb', 'Mongo', array('mongodb://localhost'));
Flight::register('prediction', 'PredictionIO\\PredictionIOClient');
Flight::register('guzzle', 'GuzzleHttp\\Client');
Flight::map('prediction_client', function () {
    $client = Flight::prediction()->factory(array("appkey" => "YOUR_PREDICTIONIO_APP_KEY"));
    return $client;
});
Flight::route('GET /', array('Home', 'index'));
Flight::route('GET /movies/recommended', array('Home', 'recommended'));
Flight::route('POST /movie/random', array('Home', 'random'));
Flight::route('/movies/import', array('Admin', 'import'));
Flight::start();
Example #23
0
                $store = Flight::get('db_read')->select('urls', ['url'], ['id' => $id]);
                if (!$store) {
                    Flight::json(['status' => 0, 'msg' => '地址不存在']);
                } else {
                    Flight::json(['status' => 1, 'url' => $store[0]['url']]);
                }
            }
        }
    }
});
Flight::route('/@hash', function ($hash) {
    $id = Flight::get('hash')->decode($hash);
    if (!$id) {
        Flight::notFound('短址无法解析');
    } else {
        $store = Flight::get('db_read')->select('urls', ['url'], ['id' => $id]);
        if (!$store) {
            Flight::notFound('地址不存在');
        } else {
            Flight::get('db')->update('urls', ['count[+]' => 1], ['id' => $id]);
            Flight::redirect($store[0]['url'], 302);
        }
    }
});
Flight::map('notFound', function ($message) {
    Flight::response()->status(404)->header('content-type', 'text/html; charset=utf-8')->write('<h1>404 页面未找到</h1>' . "<h3>{$message}</h3>" . '<p><a href="' . Flight::get('flight.base_url') . '">回到首页</a></p>' . str_repeat(' ', 512))->send();
});
Flight::map('error', function (Exception $ex) {
    $message = Flight::get('flight.log_errors') ? $ex->getTraceAsString() : '出错了';
    Flight::response()->status(500)->header('content-type', 'text/html; charset=utf-8')->write('<h1>500 服务器内部错误</h1>' . "<h3>{$message}</h3>" . '<p><a href="' . Flight::get('flight.base_url') . '">回到首页</a></p>' . str_repeat(' ', 512))->send();
});
Example #24
0
    } else {
        $call = Flight::auth()->logout(Flight::request()->cookies->{Flight::config()->cookie_name});
        setcookie(Flight::config()->cookie_name, "", time() - 3600, Flight::config()->cookie_path, Flight::config()->cookie_domain, Flight::config()->cookie_secure, Flight::config()->cookie_http);
        $call['message'] = Flight::get('lang')['logged_out'];
        $call['code'] = 200;
    }
    Flight::json($call, $call['code']);
});
Flight::route('GET /auth', function () {
    if (Flight::get('loggedin') == false) {
        $call['loggedin'] = false;
    } else {
        $call['loggedin'] = true;
        $call['userdata'] = Flight::get('userdata');
        unset($call['userdata']['id']);
        unset($call['userdata']['password']);
        unset($call['userdata']['salt']);
        unset($call['userdata']['isactive']);
    }
    $call['code'] = 200;
    Flight::json($call, $call['code']);
});
// Error mapping
Flight::map('error', function (Exception $ex) {
    Flight::render('500', array('message' => $ex->getMessage(), 'file' => $ex->getFile(), 'line' => $ex->getLine()));
});
Flight::map('notFound', function () {
    Flight::render('404');
});
// Execute Framework
Flight::start();
<?php

/**
 * Renders $page using the 'default' layout.
 */
Flight::map('render_page', function ($page, $data = null, $key = null) {
    Flight::render('layouts/header', $data, 'header');
    Flight::render($page, $data, 'body');
    Flight::render('layouts/footer', $data, 'footer');
    Flight::render('layouts/default', $data);
});
/**
 * Creates the HTML for displaying a project's meta information (title/date).
 * @param $project array An array containing a project's information
 * @return string An HTML string
 */
function render_project_meta($project)
{
    $p = '<h3 class="title">';
    !$project['link'] ?: ($p .= '<a href="' . $project['link'] . '">');
    $p .= $project['title'];
    !$project['link'] ?: ($p .= '</a>');
    $p .= '</h3><span class="date">';
    $p .= date('F Y', strtotime($project['date']));
    $p .= '</span>';
    return $p;
}
/**
 * Creates the HTML for displaying a project's tags.
 * @param $project array An array containing a project's information
 * @return string An HTML string
Example #26
0
$tables = Presenter::listTables($data);
Flight::set('tables', $tables);
if (false !== strpos($_SERVER['REQUEST_URI'], '/table')) {
    $currentTableKey = array_search(Flight::get('lastSegment'), $data, true);
    unset($data[$currentTableKey]);
    // remove current table
    // make dropdown options
    Flight::set('tablesOptions', getOptions($data));
}
// get an array of databases
$stmt = $db->query("SHOW DATABASES");
$data = $stmt->fetchAll(PDO::FETCH_NUM);
$data = arrayFlatten($data);
Flight::set('databaseOptions', getOptions($data, true, null, $database));
// setup custom 404 page
Flight::map('notFound', function () {
    //include 'errors/404.html';
    header("HTTP/1.0 404 Not Found");
    exit('404 Not Found');
});
// set global variables
Flight::set('appname', $config['appname']);
///////// setup routes /////////////
require_once 'routes.php';
// auto-logout after inactivity for 10 minutes
timeoutLogout(60);
// flight now
Flight::start();
//TODO: dropdown in header to select a different database
//TODO: ability to edit recordset in place
//TODO: tutorial of VisualQuery
Example #27
0
$nav = file_get_contents('./content/nav.md', FILE_USE_INCLUDE_PATH);
if ($nav === FALSE) {
    $nav = 'Navigation file missing';
}
Flight::set('nav_contents', Markdown($nav));
//Site Title
Flight::set('site_title', 'Markdown Directory');
//ROUTES
Flight::route('/', function () {
    $listing_content = file_get_contents("./content/home.md", FILE_USE_INCLUDE_PATH);
    Flight::display('Welcome to Markdown Directory', $listing_content);
});
Flight::route('/@listing', function ($listing) {
    $listing_content = file_get_contents("./content/listings/{$listing}.md", FILE_USE_INCLUDE_PATH);
    $title = ucwords(str_replace("_", " ", $listing));
    Flight::display($title, $listing_content);
});
//Render
Flight::map('display', function ($title, $list_content) {
    $siteTitle = Flight::get('site_title');
    $title = $title . ' - ' . $siteTitle;
    if ($list_content === FALSE) {
        $list_content = '<p>Listing cannot be found</p>';
    } else {
        $list_content = Markdown($list_content);
    }
    Flight::render('header', array('title' => $title), 'header_content');
    Flight::render('footer', array(), 'footer_content');
    Flight::render('layout', array('nav' => Flight::get('nav_contents'), 'listing' => $list_content, 'site_title' => $siteTitle));
});
Flight::start();
Example #28
0
    // manage
    
    Flight::route('/manage/division', array('DivisionController', '_manage_division'));
    Flight::route('/manage/loas', array('DivisionController', '_manage_loas'));
    
    
    // admin
    Flight::route('/admin', array('AdminController', '_show'));
    */
    // update user activity
    if (isset($_SESSION['userid'])) {
        User::updateActivityStatus($_SESSION['userid']);
    }
}
// 404 redirect
Flight::map('notFound', array('ApplicationController', '_404'));
// error handler
Flight::route('/error', array('ApplicationController', '_error'));
// graphics
Flight::route('/stats/@division/top10.png', array('GraphicsController', '_generateDivisionTop10'));
// authenticate
Flight::route('GET /authenticate', array('UserController', '_authenticate'));
Flight::route('POST /do/authenticate', array('UserController', '_doAuthenticate'));
Flight::route('POST /do/reset-authentication', array('UserController', '_doResetAuthentication'));
/*// handle errors privately unless localhost
if(!in_array($_SERVER['REMOTE_ADDR'], array( '127.0.0.1', '::1' ))){
    Flight::set('flight.log_errors', true);
    Flight::map('error', function(Exception $ex){
        Flight::redirect('/error', 500);
    });
}
Example #29
0
<?php

require_once '../Lib/flight/Flight.php';
require_once 'config.php';
require_once 'Helper/easy.class.php';
require_once 'RESTServiceClient.php';
/**
** Home
**/
Flight::map('notFound', function () {
    include 'views/404.html';
});
// ADD new album
Flight::route('GET|POST /album/create', function () {
    $request = Flight::request();
    if ($request->method == "GET") {
        Flight::render('createAlbum', array(), 'body_content');
        Flight::render('layout', array('Titre' => 'Ajouter un album'));
    }
    if ($request->method == "POST") {
        $album = json_encode($_POST);
        $result = json_decode(addAlbum($album));
        if (isset($result->IDalbum)) {
            Flight::redirect('http://localhost/php/App/track/' . $result->IDalbum . '/create');
        } else {
            Flight::render('createAlbum', array("flash" => $result), 'body_content');
            Flight::render('layout', array('Titre' => 'Ajouter un album'));
        }
    }
});
Flight::route('/', function () {
Example #30
-1
<?php

session_start();
require 'vendor/autoload.php';
use predictionio\EventClient;
Flight::register('mdb', 'Mongo', array('mongodb://localhost'));
//Flight::register('prediction', 'predictionio\EventClient');
Flight::register('guzzle', 'GuzzleHttp\\Client');
Flight::map('prediction_client', function () {
    //$accessKey = 'GJBuFYODWTwFBVQ2D2nbBFW5C0iKClNLEMbYGGhDGoZGEtLre62BLwLJlioTEeJP';
    //$client = new EventClient($accessKey, 'http://localhost:7070');
    $predictionio_appkey = "sD13KDmvVn8RVWaxlkuVUS0wxropKJTdUPbm6vWD7BvheZsqmrW0FJHdZa2y7wR2";
    $predictionio_eventserver = "http://127.0.0.1:7070";
    $client = new EventClient($predictionio_appkey, $predictionio_eventserver);
    return $client;
});
Flight::route('GET /', array('Home', 'index'));
Flight::route('GET /movies/recommended', array('Home', 'recommended'));
Flight::route('POST /movie/random', array('Home', 'random'));
Flight::route('/movies/import', array('Admin', 'import'));
Flight::route('/test', function () {
    $accessKey = 'sD13KDmvVn8RVWaxlkuVUS0wxropKJTdUPbm6vWD7BvheZsqmrW0FJHdZa2y7wR2';
    $client = new EventClient($accessKey, 'http://127.0.0.1:7070');
    $response = $client->setUser(2);
    echo 'a';
    print_r($response);
});
Flight::start();