Example #1
0
/**
 * Created by Svyatoslav Svitlychnyi.
 * Date: 21.07.2015
 * Time: 11:34
 */
require_once __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/models/Records.php';
$klein = new \Klein\Klein();
//$app = new \Models\Records();
// lazy services
$klein->respond(function ($request, $response, $service, $app) {
    $app->register('db', function () {
        try {
            $connection = new PDO("mysql:host=localhost;dbname=kievdevel_zam", 'kievdevel_zam', 'zaq12wsx');
        } catch (PDOException $exception) {
            echo "Connection error: " . $exception->getMessage();
        }
        return $connection;
    });
    // todo: register validators
});
// index
$klein->respond('GET', '/', function ($request, $response, $service, $app) {
    /**@var \PDO $db  PDO Object */
    $db = $app->db;
    $query = "SELECT * FROM notes";
    $stmt = $db->prepare($query);
    $stmt->execute();
    $num = $stmt->rowCount();
    $html = '';
    if ($num > 0) {
Example #2
0
<?php

require_once $_SERVER['DOCUMENT_ROOT'] . "/includes.php";
$klein = new \Klein\Klein();
$klein->respond("/?", function ($request, $response, $service) {
    $response->header("X-PJAX-URL", $request->pathname());
    disableCache($response);
    $data = array('pageTitle' => 'OpenCTF Test Page', 'viewName' => "test", "path" => $request->pathname(), "current" => "test");
    if ($request->headers()['X-PJAX']) {
        $service->layout('views/pjax-wrapper.phtml');
    } else {
        $service->layout('views/layout-wrapper.phtml');
    }
    $service->render('views/' . $data['viewName'] . '.phtml', $data);
});
$klein->respond("/login/?", function ($request, $response, $service) {
    $response->header("X-PJAX-URL", $request->pathname());
    disableCache($response);
    $data = array('pageTitle' => 'OpenCTF Test Page', 'viewName' => "login", "path" => $request->pathname(), "current" => "login");
    if ($request->headers()['X-PJAX']) {
        $service->layout('views/pjax-wrapper.phtml');
    } else {
        $service->layout('views/layout-wrapper.phtml');
    }
    $service->render('views/' . $data['viewName'] . '.phtml', $data);
});
$klein->respond("/register/[verify-email|team-pick:extra]?/?", function ($request, $response, $service) {
    $response->header("X-PJAX-URL", $request->pathname());
    disableCache($response);
    if ($request->extra == "team-pick") {
        $teamPick = true;
Example #3
0
<?php

$router = new \Klein\Klein();
// Главная страница
$router->respond('GET', '/', function () {
    $controller = new Controller_Main();
    return $controller->action_index();
});
// Страница каталога
$router->respond(array('GET', 'POST'), '/products/?', function ($request, $response) {
    $controller = new Controller_Products();
    $messages = ['success_message' => '', 'error_message' => ''];
    $action = $request->action;
    switch ($action) {
        case 'new':
            if (!empty($_POST['title'])) {
                $messages = $controller->addCategory($request->title);
            } else {
                $messages['error_message'] = 'Укажите имя категории';
            }
            break;
        case 'edit':
            if (!empty($_POST['title'])) {
                $messages = $controller->editCategory($request->id, $request->title);
            } else {
                $messages['error_message'] = 'Укажите имя категории';
            }
            break;
        case 'delete':
            $messages = $controller->deleteCategory($request->id);
            break;
Example #4
0
 /**
  * Старт приложения
  *
  * @return null
  *
  * @version 11.11.2016
  * @author Дмитрий Щербаков <*****@*****.**>
  */
 public function start()
 {
     //
     //                                     ,,
     //                       mm     mm     db
     //                       MM     MM
     //     ,pP"Ybd  .gP"Ya mmMMmm mmMMmm `7MM  `7MMpMMMb.  .P"Ybmmm ,pP"Ybd
     //     8I   `" ,M'   Yb  MM     MM     MM    MM    MM :MI  I8   8I   `"
     //     `YMMMa. 8M""""""  MM     MM     MM    MM    MM  WmmmP"   `YMMMa.
     //     L.   I8 YM.    ,  MM     MM     MM    MM    MM 8M        L.   I8
     //     M9mmmP'  `Mbmmd'  `Mbmo  `Mbmo.JMML..JMML  JMML.YMMMMMb  M9mmmP'
     //                                                    6'     dP
     //                                                    Ybmmmd'
     // Устанавливаем часовой пояс по Гринвичу
     date_default_timezone_set('UTC');
     // Где будут хранится php сессии (в файлах или в БД)
     if (Settings::PHP_SESSION === 'DB') {
         $session = new \Zebra_Session(mysqli_connect(Settings::DB_HOST, Settings::DB_USER, Settings::DB_PASSWORD, Settings::DB_DATABASE, Settings::DB_PORT), 'AVuVqYR6uwgEuhV79tln0tlKk');
     } else {
         session_start();
     }
     // Включим страницу с ошибками, если включен режим DEBUG
     if (Settings::DEBUG === true) {
         $whoops = new \Whoops\Run();
         $whoops->pushHandler(new \Whoops\Handler\PrettyPageHandler());
         $whoops->register();
     }
     // Настраиваем соединение с БД
     \ORM::configure(['connection_string' => 'mysql:host=' . Settings::DB_HOST . ';port=' . Settings::DB_PORT . ';dbname=' . Settings::DB_DATABASE, 'username' => Settings::DB_USER, 'password' => Settings::DB_PASSWORD, 'logging' => Settings::DEBUG, 'driver_options' => [\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION, \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC, \PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8']]);
     // Инициализируем CSRF-токен
     $csrf = new \DimNS\SimpleCSRF();
     $this->csrf_token = $csrf->getToken();
     // Определим корневую папку, если переменная не пустая
     if (Settings::PATH_SHORT_ROOT != '/') {
         $_SERVER['REQUEST_URI'] = substr($_SERVER['REQUEST_URI'], strlen(Settings::PATH_SHORT_ROOT));
     }
     // Инициируем роутер
     $klein = new \Klein\Klein();
     //
     //
     //     `7MM"""Yb. `7MMF'
     //       MM    `Yb. MM
     //       MM     `Mb MM
     //       MM      MM MM
     //       MM     ,MP MM
     //       MM    ,dP' MM
     //     .JMMmmmdP' .JMML.
     //
     //
     // Создаем DI
     $klein->respond(function ($request, $response, $service, $di) use($csrf) {
         // Регистрируем доступ к настройкам
         $di->register('cfg', function () {
             return new \MFLPHP\Configs\Config();
         });
         // Регистрируем доступ к управлению пользователем
         $di->register('auth', function () {
             $dbh = new \PDO('mysql:host=' . Settings::DB_HOST . ';port=' . Settings::DB_PORT . ';dbname=' . Settings::DB_DATABASE, Settings::DB_USER, Settings::DB_PASSWORD, [\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION, \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC, \PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8']);
             return new \PHPAuth\Auth($dbh, new \PHPAuth\Config($dbh, 'phpauth_config'), 'ru_RU');
         });
         // Регистрируем доступ к информации о пользователе
         $di->register('userinfo', function () use($di) {
             if ($di->auth->isLogged()) {
                 $user_id = $di->auth->getSessionUID($di->auth->getSessionHash());
                 $user_info = \ORM::for_table('users')->join('users_info', array('users.id', '=', 'users_info.uid'))->where_equal('id', $user_id)->find_one();
                 if (is_object($user_info)) {
                     return $user_info;
                 }
             }
             return false;
         });
         // Регистрируем доступ к PHPMailer
         $di->register('phpmailer', function () use($di) {
             $phpmailer = new \PHPMailer();
             $phpmailer->setLanguage('ru', $di->cfg->abs_root_path . 'vendor/phpmailer/phpmailer/language/');
             $phpmailer->IsHTML(true);
             $phpmailer->CharSet = 'windows-1251';
             $phpmailer->From = $di->auth->config->site_email;
             $phpmailer->FromName = iconv('utf-8', 'windows-1251', $di->auth->config->site_name);
             if ('1' == $di->auth->config->smtp) {
                 $phpmailer->IsSMTP();
                 $phpmailer->SMTPDebug = 0;
                 $phpmailer->SMTPAuth = true;
                 $phpmailer->SMTPSecure = $di->auth->config->smtp_security;
                 $phpmailer->Host = $di->auth->config->smtp_host;
                 $phpmailer->Port = $di->auth->config->smtp_port;
                 $phpmailer->Username = $di->auth->config->smtp_username;
                 $phpmailer->Password = $di->auth->config->smtp_password;
             }
             return $phpmailer;
         });
         // Регистрируем доступ к отправке почты
         $di->register('mail', function () use($di) {
             return new \MFLPHP\Helpers\EmailSender($di);
         });
         // Регистрируем доступ к логгеру Monolog
         $di->register('log', function () use($di) {
             $log = new \Monolog\Logger('MainLog');
             $log->pushHandler(new \Monolog\Handler\StreamHandler($di->cfg->abs_root_path . 'errors.log', \Monolog\Logger::WARNING));
             return $log;
         });
         // Регистрируем доступ к проверке CSRF-токена
         $di->register('csrf', function () use($csrf) {
             return $csrf;
         });
         $views_path = $_SERVER['DOCUMENT_ROOT'] . Settings::PATH_SHORT_ROOT . 'app/Views/';
         $service->layout($views_path . 'layout-default.php');
         $service->csrf_token = $this->csrf_token;
         $service->path = Settings::PATH_SHORT_ROOT;
         $service->app_root_path = $_SERVER['DOCUMENT_ROOT'] . Settings::PATH_SHORT_ROOT . 'app';
     });
     //
     //
     //                                  mm
     //                                  MM
     //     `7Mb,od8 ,pW"Wq.`7MM  `7MM mmMMmm .gP"Ya  ,pP"Ybd
     //       MM' "'6W'   `Wb MM    MM   MM  ,M'   Yb 8I   `"
     //       MM    8M     M8 MM    MM   MM  8M"""""" `YMMMa.
     //       MM    YA.   ,A9 MM    MM   MM  YM.    , L.   I8
     //     .JMML.   `Ybmd9'  `Mbod"YML. `Mbmo`Mbmmd' M9mmmP'
     //
     //
     require_once $_SERVER['DOCUMENT_ROOT'] . Settings::PATH_SHORT_ROOT . 'app/Routes.php';
     //
     //
     //
     //
     //     `7Mb,od8 `7MM  `7MM  `7MMpMMMb.
     //       MM' "'   MM    MM    MM    MM
     //       MM       MM    MM    MM    MM
     //       MM       MM    MM    MM    MM
     //     .JMML.     `Mbod"YML..JMML  JMML.
     //
     //
     $klein->dispatch();
 }
Example #5
0
<?php

$klein = new \Klein\Klein();
$klein->respond('GET', '/', function () {
    return 'Hello World!';
});
$klein->dispatch();
Example #6
0
<?php

require_once __DIR__ . '/../vendor/autoload.php';
// Templating engine
$loader = new Twig_Loader_Filesystem('../templates/');
$twig = new Twig_Environment($loader);
//Router
$klein = new \Klein\Klein();
$klein->respond('GET', '/', function () {
    global $twig;
    return $twig->render('index.html', array('name' => 'nemanjan00'));
});
$klein->respond('GET', '/app/[*]', function () {
    global $twig;
    return $twig->render('index.html', array('name' => 'nemanjan00'));
});
// Handle errors
$klein->onHttpError(function ($code, $router) {
    switch ($code) {
        case 404:
            $router->response()->body('Y U so lost?!');
            break;
        case 405:
            $router->response()->body('You can\'t do that!');
            break;
        default:
            $router->response()->body('Oh no, a bad error happened that caused a ' . $code);
    }
});
$klein->dispatch();
Example #7
0
    $class = basename($file, '.php');
    if ($class != 'Model') {
        array_push($models, $class);
    }
}
$klein = new \Klein\Klein();
// This is where RESTful routes are mapped by Klein
foreach ($models as $model) {
    $modelName = strtolower($model);
    $mainUrl = '/' . $modelName;
    $resourceUrl = '/' . $modelName . '/' . '[:id]';
    $controllerName = $model . 'Controller';
    $controller = new $controllerName();
    if ($model::$get_all_enabled) {
        $klein->respond('get', $mainUrl, function ($request) use($controller) {
            $controller->getAll();
        });
    }
    if ($model::$get_enabled) {
        $klein->respond('get', $resourceUrl, function ($request) use($controller) {
            $controller->get($request->id);
        });
    }
    if ($model::$create_enabled) {
        $klein->respond('post', $mainUrl, function ($request) use($controller) {
            $postParams = json_decode(file_get_contents('php://input'));
            $controller->create($postParams);
        });
    }
    if ($model::$delete_enabled) {
        $klein->respond('delete', $resourceUrl, function ($request) use($controller) {
Example #8
0
$router = new \Klein\Klein();
// перенаправление по url с помощью виртуального "роутера"
$templater = Templater::getInstance();
// привязка шаблонизатора к этому роутеру
$config = (include_once 'config/config.php');
// подключение файла конфигурации
// Перенаправление на страницы по ссылкам
$router->respond('GET', '/?', function () use($templater, $config) {
    $data = array();
    $data['config'] = $config;
    // импорт настроек из файла конфигурации
    $data['sitename'] = 'Здоровый образ жизни';
    $data['pagename'] = 'Главная страница';
    $data['title'] = $data['pagename'] . ' | ' . $data['sitename'];
    $data['current'] = 'index';
    // название текущей страницы, чтобы переключать классы в пунктах меню
    // Получение данных из БД с помощью библиотеки Idiorm
    // Подключение к БД
    ORM::configure(array('connection_string' => 'mysql:host=' . $config['database']['host'] . ';dbname=' . $config['database']['dbname'], 'username' => $config['database']['user'], 'password' => $config['database']['password']));
    // Сбор значений таблицы
    $newsItems = ORM::for_table('news')->find_many();
    $data['newsitems'] = $newsItems;
    return $templater->display('_pages/index', $data);
});
$router->respond('GET', '/areas/?', function () use($templater, $config) {
    $data = array();
    $data['config'] = $config;
    // импорт настроек из файла конфигурации
    $data['sitename'] = 'Здоровый образ жизни';
    $data['pagename'] = 'Площадки';
    $data['title'] = $data['pagename'] . ' | ' . $data['sitename'];
Example #9
0
       $_POST['action']='listStation';
       if(isset($request->stationcode)) $_POST['station_code']=$request->stationcode;
   });
   
   $router->respond('POST', '/[:action]/[:stationcode]', function ($request, $response) {
       if(isset($request->action)) $_POST['action']=$request->action;
       if(isset($request->stationcode)) $_POST['station_code']=$request->stationcode;
   });
   //
   include './controllers/stations.php';
});
* 
*/
$router->respond('GET', '/users', function () {
    //listado de todos los usuarios
    $_POST['action'] = 'listUsers';
    include './controllers/users.php';
});
$router->respond('POST', '/users/[:action]?/[:userid]?', function ($request, $response) {
    //editar usuario
    if (isset($request->action)) {
        $_POST['action'] = $request->action;
    }
    if (isset($request->userid)) {
        $_POST['userid'] = $request->userid;
    }
    include './controllers/users.php';
});
$router->respond('GET', '/stations', function () {
    //listado de todos los usuarios
    $_POST['action'] = 'listStations';
Example #10
0
//
$klein = new \Klein\Klein();
// load the artist routes
require_once 'routes/artist.php';
// load the album routes
require_once 'routes/album.php';
// load the genre routes
require_once 'routes/genre.php';
// load the song routes
require_once 'routes/song.php';
// load the playlist routes
require_once 'routes/playlist.php';
// load the "now playing" routes
require_once 'routes/now-playing.php';
$klein->respond('GET', '/show-tables', function () {
    Kint::dump(Database::query("SELECT name FROM sqlite_master WHERE type='table';"));
});
$klein->respond('GET', '/nuke-db', function () {
    $tables = Database::query("SELECT name FROM sqlite_master WHERE type='table';");
    Kint::dump($tables);
    foreach ($tables as $t) {
        Kint::dump("dropping {$t['name']}");
        Database::execute("drop table if exists {$t['name']};");
    }
    Kint::dump("database nuked");
});
$klein->respond('GET', '/empty-db', function () {
    Database::execute("delete from artists;");
    Database::execute("delete from albums;");
    Database::execute("delete from genres;");
    Database::execute("delete from songs;");
        if (preg_match('#' . $pattern . '#', $path)) {
            return $route;
        }
    }
}
$bench->iterate('php array', function () use($phparray) {
    $route = phparray_dispatch('/hello');
});
$mux = (require 'pux/hello_mux.php');
$bench->iterate('pux', function () use($mux) {
    $route = $mux->match('/hello');
});
// klein
$klein = new \Klein\Klein();
$klein->respond('GET', '/hello', function () {
    return 'hello';
});
$bench->iterate('klein', function () use($klein) {
    $klein->dispatch();
});
// ham
$_SERVER['REQUEST_URI'] = '/hello';
$ham = new Ham('example');
$ham->route('/hello', function ($ham) {
});
$bench->iterate('ham', function () use($ham) {
    $ham->run();
});
// aura
$aura = (require 'aura/aura/scripts/instance.php');
$aura->add('hello', '/hello');
Example #12
0
<?php

require_once '../vendor/autoload.php';
$router = new Klein\Klein();
$router->respond(function ($request, $response, $service, $app) {
    $app->html = function ($view, $parameters = []) use($response) {
        $twig = new Twig_Environment(new Twig_Loader_Filesystem('../html'));
        return $twig->render("{$view}.html", $parameters);
    };
    $app->json = function ($view, $parameters) use($response) {
        return $response->json($parameters);
    };
});
$router->respond('GET', '/[*:identifier].[json:format]?', function ($request, $response, $service, $app) {
    $curse = new Widget\Curse(new Widget\CurseCrawler(), new Widget\MemcacheCache(new Memcache()));
    $identifier = $request->param('identifier');
    $version = $request->param('version', 'latest');
    $format = $request->param('format', 'html');
    $theme = $request->param('theme', 'default');
    if (is_numeric($identifier)) {
        $identifier = "project/{$identifier}";
    }
    if (!$curse->isValid($identifier)) {
        $response->code(400);
        return $app->{$format}('error', ['code' => '400', 'error' => 'No Project Specified', 'message' => 'Please provide a project identifier']);
    }
    $properties = $curse->project($identifier);
    if (!$properties) {
        $response->code(404);
        return $app->{$format}('error', ['code' => '404', 'error' => 'Project Not Found', 'message' => "{$identifier} cannot be found on curse.com"]);
    }
Example #13
0
<?php

require_once 'vendor/autoload.php';
$title = 'Group and shorten links with Linkadept.com';
$announcement = \Linkadept\LocalData::getAnnouncement();
$stylesheet = \Linkadept\Misc::getCorrespondingStylesheet();
$popularLinks = \Linkadept\Misc::getPopularLinks();
$pageVars = array('title' => $title, 'announcement' => $announcement, 'stylesheet' => $stylesheet, 'popularLinks' => $popularLinks);
//Set up Twig Templating Engine
$loader = new Twig_Loader_Filesystem('views');
$twig = new Twig_Environment($loader, array('cache' => 'views/cache', 'debug' => true));
$klein = new \Klein\Klein();
$klein->respond('GET', '/', function () use($twig, $pageVars) {
    $pageVars['stylesheet'] = 'index.css';
    return $twig->render('View.indexInputs.php', ['pageVars' => $pageVars]);
});
$klein->respond('GET', '/[:groupKey]', function () use($twig, $pageVars) {
    $linksObj = new \Linkadept\Links();
    $links = $linksObj->getLinks();
    return $twig->render('View.indexOutputs.php', ['pageVars' => $pageVars, 'links' => $links, 'groupKey' => $linksObj->groupKey]);
});
$klein->respond('POST', '/', function ($request, $response) use($twig, $pageVars) {
    $pageVars['stylesheet'] = 'index.css';
    $links = new \Linkadept\Links();
    $upload = $links->uploadLink();
    if ($upload['error']) {
        return $twig->render('View.indexInputs.php', ['pageVars' => $pageVars, 'errors' => $upload['messages']]);
    }
    $response->redirect($links->groupKey, 302);
});
$klein->respond('GET', '/page/tos', function () use($twig, $pageVars) {
Example #14
0
<?php

// Include the Smarty Templating Engine
define('SMARTY_DIR', __DIR__ . '/Smarty-3.1.14/libs/');
require_once SMARTY_DIR . 'Smarty.class.php';
$smarty = new Smarty();
$smarty->setTemplateDir(__DIR__ . '/templates/templates/');
$smarty->setCompileDir(__DIR__ . '/templates/templates_c/');
$smarty->setConfigDir(__DIR__ . '/templates/configs/');
$smarty->setCacheDir(__DIR__ . '/templates/cache/');
// Notice how you can set variables here in the PHP that will get carried into the template files
$smarty->assign('title', "EECS485");
// Setup the Routing Framework
require_once __DIR__ . '/vendor/autoload.php';
$klein = new \Klein\Klein();
/* Define routes here */
$klein->respond('GET', '/', function ($request, $response, $service) use($smarty) {
    $smarty->display('index.tpl');
});
$klein->respond('GET', '/pic[:id]?', function ($request, $response, $service) use($smarty) {
    // Notice how you can set variables here in the PHP that will get carried into the template files
    $smarty->assign('picid', $request->id);
    $smarty->display('pic.tpl');
});
$klein->respond('GET', '/album', function ($request, $response, $service) use($smarty) {
    $smarty->display('album.tpl');
});
$klein->respond('GET', '/albums', function ($request, $response, $service) use($smarty) {
    $smarty->display('albums.tpl');
});
$klein->dispatch();
Example #15
0
     */
    $base = dirname($_SERVER['PHP_SELF']);
    // Update request when we have a subdirectory
    if (ltrim($base, '/')) {
        $base = str_replace(' ', '%20', $base);
        $_SERVER['REQUEST_URI'] = substr($_SERVER['REQUEST_URI'], strlen($base));
    }
}
// Dispatch as always
$klein = new \Klein\Klein();
/**
 * Default controller & method
 */
$klein->respond('/', function () {
    //forward to home/index
    $controller = new Krikke\SlackEvent\Controller\Home();
    $controller->index();
});
/**
 * Fetch custom controller & method
 *
 * http://symfony.com/doc/current/components/routing/introduction.html (dynamische controller)
 */
$klein->respond('/[:controller]/[:method]?/[:action]?/[:value]?/?', function ($request) {
    $class = '\\Krikke\\SlackEvent\\Controller\\' . ucfirst($request->controller);
    if (class_exists(ucfirst($class))) {
        $controller = new $class();
        if (isset($request->method) && !empty($request->method) && method_exists($controller, $request->method)) {
            $method = $request->method;
            return $controller->{$method}($request->action, $request->value);
        } else {
Example #16
0
require_once './lib/Model/queries.php';
Bootstrap::start();
// FIXME: apis use PDO in some case which requires a different connection
// object than the one instantiated by Database::obtain.
require_once 'lib/Model/PDOConnection.php';
PDOConnection::connectINIT();
$db = Database::obtain(INIT::$DB_SERVER, INIT::$DB_USER, INIT::$DB_PASS, INIT::$DB_DATABASE);
$db->connect();
Log::$uniqID = uniqid();
$klein = new \Klein\Klein();
// This is unreleased APIs. I'm no longer fond of the [i:id_job] in the path,
// so before releasing change it use a querystring.
//
$klein->respond('GET', '/api/v2/jobs/[i:id_job]/revision-data', function () {
    $reflect = new ReflectionClass('API_V2_JobRevisionData');
    $instance = $reflect->newInstanceArgs(func_get_args());
    $instance->respond('revisionData');
});
$klein->respond('GET', '/api/v2/jobs/[i:id_job]/revision-data/segments', function () {
    $reflect = new ReflectionClass('API_V2_JobRevisionData');
    $instance = $reflect->newInstanceArgs(func_get_args());
    $instance->respond('segments');
});
$klein->respond('GET', '/api/v2/project-completion-status/[i:id_project]', function () {
    $reflect = new ReflectionClass('API_V2_ProjectCompletionStatus');
    $instance = $reflect->newInstanceArgs(func_get_args());
    $instance->respond('status');
});
$klein->respond('GET', '/api/v2/project-translation/[i:id_project]', function () {
    $reflect = new ReflectionClass('API_V2_ProjectTranslation');
    $instance = $reflect->newInstanceArgs(func_get_args());
Example #17
0
<?php

require_once 'vendor/autoload.php';
$klein = new Klein\Klein();
date_default_timezone_set('Europe/Dublin');
$klein->respond(function ($request, $response, $service) {
    $service->layout('layouts/base.php');
});
$klein->respond('/api/popular/destinationProfits', function () {
    $f = new \AriesAir\Finance();
    return $f->getDestinationProfits();
});
$klein->respond('/api/popular/averageTicketPrice', function () {
    $f = new \AriesAir\Finance();
    return $f->getAverageTicketPrice();
});
$klein->respond('/api/popular/averageMonthlyTicketPrice', function () {
    $f = new \AriesAir\Finance();
    return $f->getAverageMonthlyTicketPrice();
});
$klein->respond('/api/popular/averageYearlyTicketCompare', function () {
    $f = new \AriesAir\Finance();
    return $f->getAverageYearlyTicketCompare();
});
$klein->respond('/api/ratings', function () {
    $cs = new \AriesAir\CustomerService();
    return $cs->customerRatings();
});
$klein->respond('/api/aoi', function () {
    $cs = new \AriesAir\CustomerService();
    return $cs->customerSuggestions();
Example #18
0
require_once __DIR__ . '/class/loader.php';
require_once __DIR__ . '/data.php';
$klein = new \Klein\Klein();
$klein->app()->renderer = new MustacheTemplateRenderer('templates', 'templates/partials', ['page' => 'templates/partials/pages']);
$routes = $klein->app()->routeData = json_decode(file_get_contents('routes.json'), true);
$klein->app()->prg = new FormPersister();
$klein->app()->mailer = Swift_Mailer::newInstance(Swift_SendmailTransport::newInstance());
$klein->app()->moddates = ['css' => filemtime('css/main.css'), 'js' => filemtime('js/main.js')];
$klein->app()->data = $data;
$klein->app()->production = !!apache_getenv('PRODUCTION');
/////////////////
//BASIC ROUTES //
/////////////////
$klein->respond('GET', '/', function ($req, $resp, $service, $app) {
    $routeData = $app->routeData;
    $routeData['about']['active'] = true;
    return $app->renderer->render('about', ['routes' => $routeData, 'moddates' => $app->moddates, 'production' => $app->production, 'data' => $app->data]);
});
foreach ($routes as $id => $data) {
    $klein->respond('GET', $data['url'], function ($req, $resp, $service, $app) use($id, $data) {
        $routeData = $app->routeData;
        $routeData[$id]['active'] = true;
        $errors = $app->prg->getErrors();
        $renderData = ['routes' => $routeData, 'data' => $data, 'formerrors' => $errors, 'formsuccess' => $app->prg->getSuccess(), 'formdata' => count($errors) ? $app->prg->getData() : [], 'moddates' => $app->moddates, 'production' => $app->production, 'data' => $app->data];
        $app->prg->reset();
        return $app->renderer->render($id, $renderData);
    });
}
////////////////
//ERROR PAGES //
////////////////
Example #19
0
// here I'm "tricking" the routing system into routing a non-HTTP request
$request = new \Klein\Request(array(), array(), array(), array('REQUEST_URI' => '/' . implode('/', $args)));
// instantiate the Klein router
$klein = new \Klein\Klein();
// now add the commands to the router
foreach ($commands as $value => $method) {
    // set up a responder
    // This responder will handle any URI of the form /$value/x/y/z/.... and
    // will pass any arguments to the specified method.
    $klein->respond('GET', "/{$value}/[*]?", function ($request, $response) use($method) {
        // get the arguments
        $args = array();
        if ($request->uri()) {
            // explode the arguments
            $args = explode('/', $request->uri());
            // remove any empty values
            $args = array_values(array_filter($args));
            // remove the first element (which is the command)
            array_shift($args);
        }
        // call the requested method with any arguments that were passed
        call_user_func_array($method, $args);
    });
}
// add a "not found" response in case it's an invalid command
$klein->respond('404', function ($request) {
    // explode the arguments
    $args = explode('/', $request->uri());
    // remove any empty values
    $args = array_values(array_filter($args));
    // output the error message
    echo "\nCommand not found: {$args[0]}\n";
Example #20
0
$core->twig->addGlobal('fversion', trim(file_get_contents(SRC_DIR . 'versions/current')));
$core->twig->addGlobal('admin', (bool) $core->user->getData('root_admin'));
$core->twig->addGlobal('version', Version::get());
//Check if panel is completely installed.
//If no settings are found, then we should load configuration setup and skip anything else
if (ORM::for_table("acp_settings")->count() == 0) {
    include BASE_DIR . 'install/configure.php';
    $klein->dispatch();
    return;
}
$klein->respond('!@^(/auth/|/language/|/api/|/assets/)', function ($request, $response, $service, $app, $klein) use($core) {
    if (!$core->auth->isLoggedIn()) {
        if (!strpos($request->pathname(), "/ajax/")) {
            $service->flash('<div class="alert alert-danger">You must be logged in to access that page.</div>');
            $response->redirect('/auth/login')->send();
        } else {
            $response->code(403);
            $response->body('Not Authenticated.')->send();
        }
        $klein->skipRemaining();
    }
});
$klein->respond('@^/auth/', function ($request, $response, $service, $app, $klein) use($core) {
    if ($core->auth->isLoggedIn()) {
        // Redirect /auth/* requests to /index if they are logged in
        // Skips redirect on requests to /auth/logout and /auth/remote/*
        if (0 !== strpos($request->pathname(), "/auth/logout") && 0 !== strpos($request->pathname(), "/auth/remote/")) {
            $response->redirect('/index')->send();
            $klein->skipRemaining();
        }
    }
});
Example #21
0
        $_SERVER['REQUEST_URI'] = substr($_SERVER['REQUEST_URI'], strlen($base));
    }
}
// Dispatch as always
$klein = new \Klein\Klein();
if (ENVIRONMENT == 'production') {
    $basePath = '/crawler_tool/';
} else {
    $basePath = '/';
}
/**
 * Default controller & method
 */
$klein->respond($basePath, function () {
    //forward to home/index
    $controller = new Krikke\Crawler\Controller\Home();
    $controller->index();
});
/**
 * Fetch custom controller & method
 *
 */
$klein->respond($basePath . '[:controller]/[:method]?/[:action]?/[:value]?/?', function ($request) {
    $class = '\\Krikke\\Crawler\\Controller\\' . ucfirst($request->controller);
    if (class_exists($class)) {
        $controller = new $class();
        if (isset($request->method) && !empty($request->method) && method_exists($controller, $request->method)) {
            $method = $request->method;
            return $controller->{$method}($request->action, $request->value);
        } else {
            return $controller->index();
Example #22
0
    $_SERVER['REQUEST_URI'] = substr($_SERVER['REQUEST_URI'], strlen($base));
}
// Init Klein router
$klein = new Klein\Klein();
// Init Twig template engine
$loader = new Twig_Loader_Filesystem('templates');
$twig = new Twig_Environment($loader);
// Add global URL
$twig->addGlobal('baseURL', BASE_URL);
// Initialise database.
init();
//================================================================================
// Index page.
//================================================================================
$klein->respond('GET', '/', function () use($twig) {
    $blogs = R::findAll('blog', 'ORDER BY id DESC LIMIT 5');
    displayPage('index.twig', array('posts' => $blogs));
});
//================================================================================
// Blog View page.
//================================================================================
$klein->respond('GET', '/view/[i:id]', function ($request, $response, $service) {
    $blog = R::findOne('blog', 'id = ?', array($request->id));
    $posts = R::findAll('post', 'blog_id = ? ORDER BY id DESC', array($blog->id));
    displayPage('view.twig', array('blog' => $blog, 'posts' => $posts));
});
//================================================================================
// Posting page.
//================================================================================
$klein->respond('POST', '/post/[i:id]', function ($request, $response, $service) {
    // Create a new post bean and populate its contents from the form.
    $post = R::dispense('post');
<?php

/**
 * Created by IntelliJ IDEA.
 * User: david
 * Date: 10/9/15
 * Time: 8:31 PM
 */
$klein = new \Klein\Klein();
$klein->respond('GET', '/', function ($request, $response, $service, $app) {
    $service->render("view/main.php");
});
$klein->respond('POST', '/create_from_jsonpost/', function ($request, $response, $service, $app) {
    $c = new Creator();
    $c->createFromJson(file_get_contents('php://input'));
    global $errors;
    $errors = array_merge_recursive($errors, $c->getErrors());
    if (empty($errors)) {
        $c->flush();
    } else {
        return json_encode($errors);
    }
});
$klein->respond('POST', '/create/', function ($request, $response, $service, $app) {
    $c = new Creator();
    $c->createFromJson($_POST["data"]);
    global $errors;
    $errors = array_merge_recursive($errors, $c->getErrors());
    if (empty($errors)) {
        $c->flush();
    } else {
<?php

require_once __DIR__ . '/include/php/autoload.php';
require_once __DIR__ . '/api/v1/init.php';
$klein = new \Klein\Klein();
$klein->respond(array('GET', 'POST'), $GLOBALS['config']['serverRoot'], function () {
    return "<h2>Welcome to the Cloud Compiler API</h2><p>Check out the documentation for the API <a href='docs/'>here</a></p>";
});
$klein->respond(array('GET', 'POST'), $GLOBALS['config']['serverRoot'] . 'docs/', function () {
    return file_get_contents(__DIR__ . '/docs/index.html');
});
$klein->respond(array('GET', 'POST'), $GLOBALS['config']['serverRoot'] . 'api/languages[/]?', function ($request, $response) {
    $responseData = \API\Languages\Response();
    $response->code($responseData['code']);
    $response->json($responseData['body']);
});
$klein->respond(array('GET', 'POST'), $GLOBALS['config']['serverRoot'] . 'api/languages/template/[i:id][/]?', function ($request, $response) {
    $responseData = \API\Languages\Template\Response($request->id);
    $response->code($responseData['code']);
    $response->json($responseData['body']);
});
$klein->respond(array('GET', 'POST'), $GLOBALS['config']['serverRoot'] . 'api/languages/sample/[i:id][/]?', function ($request, $response) {
    $responseData = \API\Languages\Sample\Response($request->id);
    $response->code($responseData['code']);
    $response->json($responseData['body']);
});
$klein->respond(array('GET', 'POST'), $GLOBALS['config']['serverRoot'] . 'api/maintain[/]?', function ($request, $response) {
    $responseData = \API\Maintain\Response();
    $response->code($responseData['code']);
    $response->json($responseData['body']);
});
Example #25
0
<?php

$route = new \Klein\Klein();
$config = new config();
$backend = $config->system->evany->backend;
define('BACKEND', $backend);
$route->respond(function ($request, $response, $service, $app) {
    $app->register('isUser', function () {
        $render = new render();
        $config = new config();
        if (!isset($_SESSION['user'])) {
            $render->render("admin.notice", ["system" => $config->system]);
            die;
        }
    });
});
//Error
$route->onHttpError(function ($code, $router) {
    /*
     * HttpError doesn't have access to
     * vars outside of here.
     */
    $render = new render();
    $config = new config();
    $build = new page();
    $pages = new db("pages");
    $request = $_SERVER['REQUEST_URI'];
    $found = false;
    foreach ($pages->all() as $page) {
        $component = array_keys($page)[0];
        if ($page["endpoint"] != "/") {
Example #26
0
<?php

require 'vendor/autoload.php';
require 'lib/Httpstatuses/Httpstatuses.php';
$klein = new \Klein\Klein();
$httpstatuses = new \Httpstatuses\httpstatuses();
$klein->respond('GET', '/', function ($request, $response, $service) use($httpstatuses) {
    $class_list = $httpstatuses->statuses();
    $service->render('views/index.php', array("class_list" => $class_list));
});
$klein->respond('GET', '/[i:id]', function ($request, $response, $service) use($httpstatuses) {
    $status_code = $request->param('id');
    $code = $httpstatuses->status($status_code);
    if (!$code) {
        $service->render('views/404.php');
    }
    $service->render('views/status_code.php', $code);
});
$klein->respond('GET', '404', function ($request, $response, $service) {
    $service->render('views/404.php');
});
$klein->dispatch();
Example #27
0
$klein->respond(function ($request, $response, $service, $app) use($klein) {
    $klein->onError(function ($klein, $err_msg) {
        $klein->service()->flash($err_msg);
        if ($err_msg === 'robot') {
            //TODO: Log and blacklist spambot IPs
        }
        if ($err_msg === 'submission') {
            $klein->response()->redirect('/submit/incomplete');
        }
        if ($err_msg !== 'api' && $err_msg !== 'submission') {
            $klein->service()->back();
        }
    });
    $modlist_mtime = filemtime('data/modlist.json');
    $modlist_fsize = filesize('data/modlist.json');
    $modlist_cache = "data/cache/{$modlist_mtime}-{$modlist_fsize}.json";
    if (!file_exists($modlist_cache)) {
        //Clear cache folder
        $obsolete = glob('data/cache/*');
        array_map('unlink', $obsolete);
        //Start saving new cache
        $mod_list = json_decode(file_get_contents('data/modlist.json'), 1);
        $versions = array();
        $versions_count = array();
        foreach ($mod_list as $mod) {
            foreach ($mod['versions'] as $version) {
                if (!isset($versions_count[$version])) {
                    $versions_count[$version] = 0;
                }
                $versions_count[$version] += 1;
                if (!in_array($version, $versions, true)) {
                    array_push($versions, $version);
                }
            }
        }
        usort($versions, 'version_compare');
        foreach ($versions as $version) {
            $point = explode(".", $version);
            $major = $point[0] . '.' . $point[1];
            $versions_grouped[$major][$version] = $versions_count[$version];
        }
        foreach ($versions_grouped as $major => $verss) {
            $versions_grouped[$major] = array_reverse($verss);
        }
        $data = array("versions" => $versions, "versions_grouped" => $versions_grouped, "versions_count" => $versions_count);
        $encoded_data = json_encode($data, JSON_PRETTY_PRINT);
        file_put_contents($modlist_cache, $encoded_data);
    } else {
        $data = json_decode(file_get_contents($modlist_cache), true);
    }
    $service->versions = array_reverse($data['versions']);
    $service->versions_grouped = array_reverse($data['versions_grouped']);
    $service->versions_count = $data['versions_count'];
    $service->uri = $request->uri();
    if ($request->cookies()->theme === 'dark') {
        $service->themed = true;
    } else {
        $service->themed = false;
    }
    $service->cssVer = filemtime('public/resources/stylesheets/modlist.css');
    $service->cssPanelVer = filemtime('public/resources/stylesheets/panel.css');
    $service->layout('html/layouts/modlist.phtml');
});
Example #28
0
    // Extra Vars
    $_SERVER['REDIRECT_PAGE'] = "/{$loc}";
    include docRoot . "/source/{$loc}.php";
}
function idPage($file, $request)
{
    if (is_numeric($request->id)) {
        $_GET['id'] = $request->id;
    }
    $GLOBALS['itsMyPage'] = true;
    makeSource("{$file}");
}
/* The default 404 pages */
$router->respond('*', function ($request, $response) use($OP) {
    if ($response->status() == "400") {
        $OP->ser();
    }
});
/* Routing Pages */
$router->respond("/", function () {
    makeSource("index");
    $GLOBALS['itsMyPage'] = true;
});
$router->respond("/me", function () {
    makeSource("me/index");
    $GLOBALS['itsMyPage'] = true;
});
/* START - Recurring Dynamic Pages */
$router->respond("/?[a:ID]?/[a:page]?", function ($request, $response) {
    if (is_numeric($request->ID) || $request->ID == "profile") {
        $_GET['part'] = $request->page;
Example #29
0
<?php

if (!defined('MAIN')) {
    die('No way!');
}
$klein = new \Klein\Klein();
$klein->respond(function ($request, $response, $service) {
    $service->hashTag = getenv('HASHTAG');
    $service->siteName = getenv('SITENAME');
    $service->production = getenv('PRODUCTION');
    $service->siteURL = getenv('SITE_URL');
    $service->templatePath = 'templates/' . getenv('TEMPLATE') . '/';
    $service->layout($service->templatePath . 'layouts/default.php');
});
//Index page
$klein->respond('GET', '/', function ($request, $response, $service) {
    $time = time();
    $items = ORM::for_table('photos')->where_gt('created_time', $time - 86400)->where('banned', 0)->order_by_desc('likes')->limit(10)->find_many();
    $service->items = $items;
    $service->code = 'index';
    $service->render($service->templatePath . 'views/best.php');
});
//Topweek page
$klein->respond('GET', '/topweek', function ($request, $response, $service) {
    $time = time();
    $items = ORM::for_table('photos')->where_gt('created_time', $time - 86400 * 7)->where('banned', 0)->order_by_desc('likes')->limit(10)->find_many();
    $service->code = 'topweek';
    $service->items = $items;
    $service->render($service->templatePath . 'views/best.php');
});
//Best-ever page
Example #30
-1
    //throwUnauth());
} else {
    if (!verifyHash($_GET['hash'])) {
        //throwUnauth());
    }
}
function respond($result)
{
    return json_encode($result);
}
function verifyAuth($response)
{
    if (!Session::isValid($response)) {
        throwUnauth();
    }
}
$klein = new \Klein\Klein();
$requestType = array("POST", "GET");
$klein->respond($requestType, '/', function () {
    sleep(1);
    $result = array("status" => "incorrect", "time" => time());
    return json_encode($result);
});
$klein->onHttpError(function ($code, $router) {
    if ($code >= 400 && $code < 500) {
        $router->response()->body(throwErrorCode($code));
    } elseif ($code >= 500 && $code <= 599) {
        $router->response()->body(throwErrorCode($code));
    }
});
$klein->dispatch();