public function __construct() { $view = new \Slim\Views\Twig(); $app = new \Slim\Slim(array('debug' => DEBUG, 'view' => $view, 'templates.path' => HOME . '/' . APP . '/View')); $app->notFound(function () use($app) { $app->render('errors/404.html'); }); $controllerFactory = new \Core\ControllerFactory($app); // the class that builds the controllers $view->parserExtensions = array(new \MyTwigExtension($controllerFactory)); $mainRoute = '/'; if (!empty(SUB_FOLDER)) { // is the whole site in a subdirectory? $mainRoute .= SUB_FOLDER . '(/)'; } $checkQueries = function ($q) { // our queries must be numerical for security's sake if (!empty($q)) { if (!is_numeric($q)) { return false; } if ($q <= 0) { return false; } } return true; }; $app->group($mainRoute, function () use($app, $checkQueries, $controllerFactory) { // the admin route $app->map(ADMIN_FOLDER . '(/)(:controller)(/)(:action)(/)(:query)(/)', function ($controller = '', $action = '', $query = '') use($app, $checkQueries, $controllerFactory) { if (false === $checkQueries($query)) { $app->notFound(); } else { $controllerFactory->buildController($controller, $action, true, $query); } })->via('POST', 'GET'); // front end routing $app->map('(:controller)(/)(:action)(/)(:query)(/)(:query2)(/)', function ($controller = '', $action = '', $query = '', $query2 = '') use($app, $checkQueries, $controllerFactory) { if (false === $checkQueries($query) || false === $checkQueries($query2)) { $app->notFound(); } else { $controllerFactory->buildController($controller, $action, false, $query, $query2); } })->via('POST', 'GET'); }); $app->run(); // run Slim Application }
} catch (myPreviewException $e) { echo $e; } MyPreviewThumbnail::sendHeader(MyPreviewThumbnail::getType()); readfile($brandNewPic); } }); $app->get('/f/:id', function ($id) use($app) { session_start(); $flash = $_SESSION['slim.flash']; $file = $app->FileGateway->getData($id); $comments = $app->CommentGateway->getAllFileComments($id); if ($file) { $app->render('details.phtml', array('file' => $file, 'title' => $file->name, 'comments' => $comments, 'app' => $app, 'flash' => $flash)); } else { $app->notFound(); } }); $app->get('/files(/:page)', function ($page = 1) use($app) { $num = 100; $files = $app->FileGateway->getLatestFiles($num); $app->render('latestFiles.phtml', array('files' => $files, 'title' => 'Последние файлы', 'active' => 'files')); }); $app->get('/about', function () use($app) { $app->render('about.phtml', array('title' => 'О нас', 'active' => 'about')); }); $app->post('/comment', function () use($app) { $requestVars = $app->request->post(); $commentHandler = new CommentsController($app->CommentGateway, $requestVars); $comments = $commentHandler->addComment(); if (!$comments) {
<?php ini_set("display_errors", "1"); ini_set("error_reporting", E_ALL & ~(defined('E_STRICT') ? E_STRICT : 0)); require '../vendor/autoload.php'; require '../config.php'; // Setup custom Twig view $twigView = new \Slim\Views\Twig(array('debug' => true)); $app = new \Slim\Slim(array('debug' => true, 'view' => $twigView, 'templates.path' => '../templates/')); $app->notFound(function () use($app) { $app->render('404.html'); }); // Automatically load router files $routers = glob('../routers/*.router.php'); foreach ($routers as $router) { require $router; } $app->run();
case "/api/getNRPEPlugin": case "/api/getSupNRPEPlugin": case "/api/getRouterVM": case "/api/getNagiosPlugin": case "/api/getNagiosPlugins": require_once BASE_PATH . "/routes/apiv1.route.php"; break; default: break; } }); $app->contentType('application/json'); $app->notFound(function () use($app) { $request = $app->request(); $headers = $request->headers(); $uri = $request->getResourceUri(); $apiResponse = new APIViewData(1, false, "The page you are looking for could not be found. Check the address to ensure your URL is spelled correctly..."); $apiResponse->setExtraResponseData('url', $request->headers('X_FORWARDED_PROTO') . '://' . $request->headers('HOST') . $request->getRootUri() . $request->getResourceUri()); $app->halt('404', $apiResponse->returnJson()); }); // Initial Dummy Routes // Leave the / on the end of /sapi/ due to rewrite engine, otherwise requests to /sapi break $app->get('/sapi/', function () use($app) { $msg = "Welcome to /sapi/ ... What can we help you with?"; $apiResponse = new APIViewData(0, false, $msg); $apiResponse->printJson(); })->name('saigon-api'); $app->get('/sapi/version', function () use($app) { $apiResponse = new APIViewData(0, false, API_VERSION . " (alpha/beta/charlie/delta/echo/use at your own risk)"); $apiResponse->printJson(); })->name('saigon-api-version'); $app->run();
return $log; }); /** * Register handlers */ \Monolog\ErrorHandler::register($app->log); /** * Error handle */ $app->error(function (\Exception $e) use($app) { $app->applyHook('log.request.info', $e->getMessage()); $app->log->error($e); $app->render('error.php'); }); $app->notFound(function () use($app) { $app->applyHook('log.request.info', 'Page not found'); $app->render('404.php'); }); // throw new \Exception('test error'); /** * Define hooks */ if (file_exists(APPPATH . 'hooks.php')) { require APPPATH . 'hooks.php'; } /** * Define routes */ if (file_exists(APPPATH . 'routes.php')) { require APPPATH . 'routes.php'; } /**
<?php require_once '../vendor/autoload.php'; require_once '../src/RatingsDAO.php'; require_once '../src/JsonResponse.php'; // Prepare app $app = new \Slim\Slim(); $corsOptions = array("origin" => "*", "maxAge" => 1728000); $app->add(new \CorsSlim\CorsSlim($corsOptions)); $app->add(new JsonResponse()); $app->notFound(function () use($app) { $app->log->error('Not Found', array('path' => $app->request()->getPath())); $app->halt(404, json_encode(array('status' => 404, 'message' => 'not found'))); }); // Create monolog logger and store logger in container as singleton $app->container->singleton('log', function () { $log = new \Monolog\Logger('ss-rating'); $log->pushHandler(new \Monolog\Handler\StreamHandler('../logs/app.log', \Monolog\Logger::DEBUG)); return $log; }); function getAllRatings() { $app = \Slim\Slim::getInstance(); try { $app->response->write(json_encode(RatingsDAO::getAll(), JSON_FORCE_OBJECT)); return json_encode($app->response->getBody()); } catch (Exception $e) { $app->response->setStatus(404); $app->response->setBody(getErrorMessage($e)); return json_encode($app->response->getBody()); }
<?php ini_set('display_errors', 1); define('BASE_DIR', __DIR__ . "/.."); require BASE_DIR . '/vendor/autoload.php'; // Slim application instance $app = new \Slim\Slim(array('view' => new \Slim\Views\Twig(), 'templates.path' => BASE_DIR . '/app/views/')); $app->setName('gumaz/slim-base-mvc-json'); // Handling 404 error $app->notFound(function () use($app) { $message = ['message' => 'My custom error message!']; $app->render('not-found.html', $message); }); // Automatically load router files $routers = glob(BASE_DIR . '/routers/*.router.php'); foreach ($routers as $router) { require $router; } $app->run();
$history = $fcache->get('hash_history'); if (!$history) { $history = array(); } if (array_key_exists($chars, $history)) { return array_keys($history); } if (count($history) > $max) { $key_del = array_rand($history, 1); unset($history[$key_del]); } $history[$chars] = ''; $fcache->add('hash_history', $history); return array_keys($history); } // GET route $app->get('/', function () use($app) { $chars = 'DigHash'; $random = get_randoms(20); $history = do_history($chars); $app->render('hash.html', array('chars' => $chars, 'hash_rst' => cal_hash($chars), 'random' => $random, 'history' => $history)); }); $app->get('/:chars.html', function ($chars) use($app) { $random = get_randoms(20); $history = do_history($chars); $app->render('hash.html', array('chars' => $chars, 'hash_rst' => cal_hash($chars), 'random' => $random, 'history' => $history)); }); $app->notFound(function () use($app) { $app->redirect('/', 301); }); $app->run();
<?php require '../vendor/autoload.php'; use Pkj\Raspberry\PiFace\PiFaceDigital; if (!class_exists('\\Spi')) { die("Spi extension must be installed (https://github.com/frak/php_spi)"); } $app = new \Slim\Slim(array('debug' => false)); // Exception handler (make sure debug is false above) $app->error(function (\Exception $e) use($app) { print json_encode(array('status' => '500', 'exception' => array('code' => $e->getCode(), 'message' => $e->getMessage()))); }); $app->notFound(function () use($app) { print json_encode(array('status' => '404', 'message' => 'Route not found')); }); $pi = PiFaceDigital::create(); // Defining min/max values \Slim\Route::setDefaultConditions(array('input' => '[0-' . (count($pi->getInputPins()) - 1) . ']', 'led' => '[0-' . (count($pi->getLeds()) - 1) . ']', 'output' => '[0-' . (count($pi->getOutputPins()) - 1) . ']', 'relay' => '[0-' . (count($pi->getRelays()) - 1) . ']', 'switch' => '[0-' . (count($pi->getSwitches()) - 1) . ']', 'value' => '[0-1]')); // Begin read only devices // Input $app->get('/input/', function () use($app, $pi) { responseSuccess(outputAll($pi->getInputPins())); }); $app->get('/input/:input', function ($input) use($app, $pi) { responseSuccess($pi->getInputPins()[$input]->getValue()); }); // Switch $app->get('/switch/', function () use($app, $pi) { responseSuccess(outputAll($pi->getSwitches())); }); $app->get('/switch/:switch', function ($switch) use($app, $pi) {
$app->redirect("/".$app->request->getRootUri()); }else{ $app->render("front/error/500.twig"); } */ }); $app->get("/user/social/login/twitter/callback", function () use($app, $util) { $app->render("front/error/500.twig"); }); $app->get("/user/captcha", function () use($app, $util) { $captcha = new SimpleCaptcha(); $captcha->wordsFile = 'words/en.php'; $captcha->session_var = 'secretword'; $captcha->imageFormat = 'png'; $captcha->lineWidth = 3; $captcha->scale = 3; $captcha->blur = true; $captcha->resourcesPath = "../app/util/captcha"; $app->contentType("image/png"); $im = $captcha->CreateImage(); echo $im; }); //#################################################### ERROR #################################################### $app->notFound(function () use($app) { $app->render("front/error/404.twig"); }); $app->error(function (\Exception $e) use($app) { $app->render("front/error/500.twig"); }); /******************************************* RUN THE APP *******************************************************/ $app->run();
} # # new Slim() $app = new \Slim\Slim(); $app->config('debug', false); # config/init template [twig] $app->container->singleton('twig', function () { $twig = new \Slim\Views\Twig(); $twig->parserExtensions = array(new \Slim\Views\TwigExtension()); $templatePath = __DIR__ . '/api/templates'; $twig->setTemplatesDirectory($templatePath); return $twig; }); # 404 handler inside app() $app->notFound(function () use($app) { $app->twig->display('error.php'); }); # Exception handler inside app() $app->error(function (\Exception $e) use($app) { $app->twig->display('error.php'); }); # auth if (!isset($_GET['client-id'])) { # Basic Authentication /vassarapi # use an authenticator() ? github/tuupola/slim-basic-auth $user_array = array("user-acct2" => "user-acct2", "user-acct1" => "user-acct1"); $users = array("users" => $user_array); $app->add(new \Slim\Middleware\HttpBasicAuthentication(["path" => "/vassarapi", "realm" => "Protected", "authenticator" => new ArrayAuthenticator($users)])); } else { if (!sigValidate::validSignature(consumer::$clientId, $_GET['client-signature'], $_GET['timestamp'])) { throw new Exception('invalid login attempt');
require 'require.php'; // load db settings $settings = decodeJsonOrFail(file_get_contents('../app/db.json')); // set up eloquent use Illuminate\Database\Capsule\Manager as Capsule; $capsule = new Capsule(); $capsule->addConnection($settings); $capsule->setAsGlobal(); $capsule->bootEloquent(); // set up slim $app = new Slim\Slim(array('debug' => true)); $app->response->headers->set('Content-Type', 'application/json'); $app->get('/users', 'listUsers'); $app->get('/users/:id', 'getUser'); $app->put('/users/:id/:password', 'updateUser'); $app->put('/users/:id/status/:password', 'updateStatus'); //$app->post('/users', 'createUser'); $app->post('/login', 'login'); $app->get('/groups', 'listGroups'); $app->get('/groups/:id', 'getGroup'); $app->put('/groups/:id', 'updateGroup'); $app->get('/users/:id/messages', 'listMessagesForUser'); $app->get('/users/:id/messages/:password', 'listMessagesForUser'); $app->post('/users/:id/messages', 'sendMessageToUser'); //$app->get('/groups/:id/messages', 'listMessagesForGroup'); //$app->post('/groups/:id/messages', 'sendMessageToGroup'); $app->get('/statuses', 'listStatuses'); $app->get('/urgencies', 'listUrgencies'); $app->notFound('showNotFound'); $app->error('showError'); $app->run();
require 'paris.php'; require 'Slim/Slim.php'; // Initialize http://j4mie.github.io/idiormandparis/ if (defined("AMTC_PDOSTRING")) { ORM::configure(AMTC_PDOSTRING); ORM::configure('username', AMTC_DBUSER); ORM::configure('password', AMTC_DBPASS); } // Initialize http://www.slimframework.com/ \Slim\Slim::registerAutoloader(); $app = new \Slim\Slim(); $app->config('debug', false); // false enables custom error handler below $app->response()->header('Content-Type', 'application/json;charset=utf-8'); $app->notFound(function () { echo json_encode(array('error' => 'Not found')); }); $app->error(function (\Exception $e) { echo strlen($e->getMessage()) > 128 ? substr($e->getMessage(), 0, 128) . '...' : $e->getMessage(); }); class SlimUtil { function getSubmit(Slim\Slim $_app, $key) { $ret = null; $data = get_object_vars(json_decode($_app->request()->getBody())); if (isset($data[$key])) { $ret = get_object_vars($data[$key]); } return $ret; }
<?php require_once 'loading.inc'; require_once '../vendor/autoload.php'; $app = new \Slim\Slim(); //OAuth stuff if (session_status() == PHP_SESSION_NONE) { session_start(); } #custom 4xx and 5xx $app->notFound(function () { header("HTTP/1.0 404 Not Found"); include "pages/notfound.inc"; }); $app->error(function () { header("HTTP/1.0 500 Internal Server Error"); include "pages/error.inc"; }); #routing $app->get('/', function () { include 'pages/landing.inc'; }); #api #gameinfo $app->get('/api/gameinfo/name/:name', function ($name) { $return = new Game('name', $name); header('Content-Type: application/json'); echo $return->toJSON(); }); $app->get('/api/gameinfo/id/:name', function ($name) { $return = new Game('id', $name);
$registry->set('conf', $conf); $db = new MyPdoProxy(); $db->addMaster($conf['db']['host'], $conf['db']['user'], $conf['db']['pass'], $conf['db']['name']); $db->addSlave($conf['db']['host'], $conf['db']['user'], $conf['db']['pass'], $conf['db']['name']); $registry->set('db', $db); ///////////////////////// ///// Important, process to include controller file ///This is the main different with LITPI framework core //Parsing route information to include module/controller $route = isset($_GET['route']) ? trim($_GET['route'], '/\\') : ''; $parts = explode('/', $route); for ($i = 0; $i < count($parts); $i++) { $parts[$i] = htmlspecialchars($parts[$i]); } $module = array_shift($parts); $controller = array_shift($parts); $registry->set('module', $module); $registry->set('controller', $controller); $class = '\\controller\\' . $module . '\\' . $controller; //Init slim object $app = new \Slim\Slim(); //check if valid controller if (classmap($class) != '') { $myControllerObj = new $class($registry, $app); $myControllerObj->run(); } else { $app->notFound(function () use($app) { echo file_get_contents('404.html'); }); } $app->run();
// Homepage $app->get('/', function () use($app, $db) { $recent = $db->query("SELECT *, COUNT( decorrespondent_id ) as count FROM posts GROUP BY decorrespondent_id ORDER BY id desc LIMIT 15"); $populair = $db->query("SELECT *, COUNT( decorrespondent_id ) as count FROM posts GROUP BY decorrespondent_id ORDER BY count desc LIMIT 15"); $app->render('static/home.php', ['recent' => $recent, 'populair' => $populair], 200); })->name('home'); // Page with articles $app->get('/article', $article = function ($id = 1) use($db, $app) { $pages = $db->query("SELECT COUNT( * ) as aggregate FROM posts GROUP BY decorrespondent_id"); // Information about the paginator $page_info = ['all_pages' => $pages->rowCount(), 'current_page' => $id, 'max_pages' => (int) floor($pages->rowCount() / 15), 'next_page' => $id + 1, 'prev_page' => $id - 1]; $articles = $db->prepare("SELECT *, COUNT( decorrespondent_id ) as count FROM posts GROUP BY decorrespondent_id ORDER BY decorrespondent_id desc LIMIT 15 OFFSET :offset"); $articles->bindValue(':offset', (int) ($page_info['current_page'] - 1) * 15, PDO::PARAM_INT); $articles->execute(); $app->render('articles/index.php', ['articles' => $articles, 'pages' => $pages, 'page_info' => $page_info], 200); })->name('articles'); // Support for multiple pages for the articles $app->get('/article/page/:id', $article)->conditions(['id' => '[0-9]+']); // Show the Article $app->get('/article/:id', function ($id) use($db, $app) { $links = $db->prepare("SELECT * FROM posts WHERE decorrespondent_id = :id ORDER BY url ASC"); $links->bindValue(':id', (int) $id, PDO::PARAM_INT); $links->execute(); $app->render('articles/article.php', ['links' => $links], 200); })->conditions(['id' => '[0-9]+']); // 404! $app->notFound(function () use($app) { $app->render('errors/404.php', [], 404); }); // Run the app! $app->run();
return $r->respond(400, 'BAD REQUEST', true); } $data = R::findOne($tableName, 'id = ?', array($id)); if ($data) { $existingSyncMeta = R::findOne('syncmeta', 'where row_id = ? and tableName = ?', array($id, $tableName)); if ($existingSyncMeta) { $existingSyncMeta->type = 'remove'; $existingSyncMeta->timestamp = date('Y-m-d H:i:s'); R::store($existingSyncMeta); } if ($r->fireHookIfExists($package, $name, 'beforeRemove', $r->unserialize(array($data->export()))[0])) { R::trash($data); $r->fireHookIfExists($package, $name, 'afterRemove', $r->unserialize(array($data->export()))[0]); return $r->respond(200, 'DELETED'); } return $r->respond(403, 'FORBIDDEN:HOOK', true); } return $r->respond(404, 'NOT FOUND', true); }); /* Handle Options Route */ $app->options('/:any+', 'API', function () use($app, $r) { return $r->respond(200); }); /* default 404 and Error Handler */ $app->error('API', function (\Exception $e) use($app) { return $r->respond(500, $e, true); }); $app->notFound('API', function () use($r) { return $r->respond(404, 'NOT FOUND', true); }); $app->run();
$app->redirect($app->config('static_path')); } else { throw new RuntimeException('メールアドレスまたはパスワードに誤りがあります'); } } catch (RuntimeException $e) { $app->flash('error', $e->getMessage()); $app->redirect($app->config('static_path') . 'login'); } }); $app->map('/logout', function () use($app) { if (isset($_SESSION['user'])) { $app->getLog()->info('ユーザー名「' . $_SESSION['user']['username'] . '」(メールアドレス"' . $_SESSION['user']['email'] . '")がログアウトしました。'); } session_destroy(); session_regenerate_id(true); session_start(); $app->flash('info', 'ログアウトしました。'); $app->redirect($app->config('static_path')); })->via('GET', 'POST'); require_once __DIR__ . '/../app/routes/project.php'; require_once __DIR__ . '/../app/routes/api.php'; }); $app->notFound(function () use($app) { $app->log->debug('Result(404):REQUEST_URI=' . $_SERVER['REQUEST_URI']); $app->render('404.php'); }); $app->error(function () use($app) { $app->log->debug('Error(500):REQUEST_URI=' . $_SERVER['REQUEST_URI']); $app->render('error.php'); }); $app->run();
<?php session_start(); require 'vendor/autoload.php'; require 'rb.php'; R::setup('sqlite:subscribers.sqlite'); $twig_vars = lib\SlimCMS::getTwigVars(); $config = $twig_vars['config']; // Setup custom Twig view $twigView = new \Slim\Views\Twig(); $app = new \Slim\Slim(array('debug' => true, 'view' => $twigView, 'templates.path' => "themes/" . $config["theme"] . "/", 'twigVars' => $twig_vars)); $app->view->parserOptions = array('charset' => 'utf-8', 'auto_reload' => true, 'autoescape' => false); $app->view->parserExtensions = array(new \Slim\Views\TwigExtension()); $app->notFound(function () use($app) { $twig_vars = lib\SlimCMS::getTwigVars(); $app->render('404.html.twig', $twig_vars); }); $authenticate = function ($app) { return function () use($app) { if (!isset($_SESSION['user'])) { $app->flash('error', 'Login required'); $app->redirect('/admin'); } }; }; /*********************************************************************************************************************** * ADMIN BLOCK **********************************************************************************************************************/ // Admin $app->get('/admin/', function () use($app) { $twig_vars = $app->config('twigVars');
$feeHome = $app->request()->put('fee_home'); settype($feeHome, "integer"); $feeRemote = $app->request()->put('fee_remote'); settype($feeRemote, "integer"); #-- $event->setFeeHome($feeHome); $event->setFeeRemote($feeRemote); $event->setLocation($app->request()->put('location')); $event->setEventHeadName($app->request()->put('event_head_name')); $event->setEventHeadContact($app->request()->put('event_head_contact')); $event->setAward($app->request()->put('award')); $event->setEquipmentProvided($app->request()->put('equipments_provided')); if ($eventMapper->updateEvent($event)) { $status = 200; $response["code"] = $status; $response["message"] = "Event {$event->getId()} updated successfully."; } else { $status = 200; $response["code"] = $status; $response["message"] = "Some error occured while updating event {$event->getId()}."; } print json_encode($response); }); $app->notFound(function () { $status = 404; $response["code"] = $status; $response["error"] = 1; $response["error_message"] = "Page or URL not found"; print json_encode($response); }); $app->run();
$app = new \Slim\Slim(); require 'config.php'; require 'rest_dao.php'; require 'ta_mailer.php'; require 'help_classes.php'; $app->config('debug', false); $app->response->headers->set('Content-Type', 'application/json'); $app->error(function ($e) use($app) { echo '{"error":{ "text":"' . $e->getMessage() . '", "file":"' . $e->getFile() . '", "line":"' . $e->getLine() . "\"\n }}\n"; // file_put_contents(__DIR__.'/deb.txt', $deb); }); $app->notFound(function () use($app) { echo '{"error": 404 }'; }); $dao = new RestDAO(); $help = new Helper(); $mailer = new TA_Mailer(); $mailer->setTemplateDirectory('emails'); $auth = function () { $app = \Slim\Slim::getInstance(); $auth = new Auth(); $tokenAuth = $app->request->headers->get('Auth'); if (empty($tokenAuth) or !$auth->tokenOk($tokenAuth)) { $app->response->setStatus(401); $app->stop(); } }; $app->group('/back', $auth, function () use($app, $dao, $help) {
/** * Test custom Not Found handler */ public function testNotFound() { $s = new \Slim\Slim(); $s->notFound(function () { echo "Not Found"; }); $s->get('/foo', function () { }); $s->call(); list($status, $header, $body) = $s->response()->finalize(); $this->assertEquals(404, $status); $this->assertEquals('Not Found', $body); }
$app->add(new \JsonApiMiddleware()); $response = $app->response(); $response->header('Access-Control-Allow-Origin', '*'); } /** * View pages */ $app->get('/', function () use($app) { $app->render('shortener.php', array('revision' => 4)); }); $app->get('/:id+', function ($id) use($app) { $result = $app->api->getLinkById($id); if ($result != null) { $app->render('redirect.php', array('urlShortened' => $result['urlShortened'])); } else { $app->notFound(); } })->conditions(array('id' => '\\d+')); $app->get('/api', function () use($app) { $app->render('docs.php'); }); /** * API Methods */ $app->group('/api', 'APIRequest', function () use($app) { $app->get('/getLink/:id', function ($id) use($app) { $result = $app->api->getLinkById($id); if ($result != null) { $app->render(200, $result); } else { $app->render(404, array('error' => true, 'msg' => 'Link has not been found'));
<?php /** * Inicia e configura o Slim para lidar com json e reportar erros */ $app = new \Slim\Slim(); $app->config(['debug' => true, 'view' => new WebDevBr\Mvc\View\Json()]); $app->response->headers->set('Access-Control-Allow-Origin', '*'); $app->response->headers->set('Content-Type', 'application/json'); $app->error(function () use($app) { require __DIR__ . '/slim_error.php'; }); $app->notFound(function () use($app) { $app->render(null, [['message' => 'Page Not Found']]); }); /** * Inicia o objeto que carrega os controllers */ $loader = new WebDevBr\Mvc\Loader(); /** * Configura as rotas padrão para os controllers */ $routes_controller = ['controller' => '[a-zA-Z]+', 'id' => '[0-9]+']; $app->get('/:controller', function ($controller) use($app, $loader) { $app->render(null, [$loader->getController($app, $controller, 'viewAll')]); })->conditions($routes_controller); $app->get('/:controller/:id', function ($controller, $id) use($app, $loader) { $app->render(null, [$loader->getController($app, $controller, 'viewOne', $id)]); })->conditions($routes_controller); $app->post('/:controller', function ($controller) use($app, $loader) { $app->render(null, [$loader->getController($app, $controller, 'create')]);
$app->setName('Talententest Admin'); // Include Wordpress header for authentication if ($app->request->getResourceUri() == '/login') { define('WP_USE_THEMES', false); // Do not show themes require $_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'wp-blog-header.php'; } $view = $app->view(); $view->parserOptions = array('debug' => true, 'cache' => dirname(__FILE__) . '/cache'); $view->parserExtensions = array(new \Slim\Views\TwigExtension(), new Twig_Extension_Debug()); $data = array(); $data['base_url'] = '/admin/'; $data['current_url'] = rtrim($data['base_url'], '/') . $app->request->getResourceUri(); $data['mainmenu'] = array(array('title' => 'Dashboard', 'url' => 'dashboard', 'icon' => 'fa-dashboard'), array('title' => 'Gebruikers', 'url' => 'users_overview', 'icon' => 'fa-users'), array('title' => 'Scholen', 'url' => 'schools_overview', 'icon' => 'fa-university'), array('title' => 'Talenten', 'url' => 'talents_overview', 'icon' => 'fa-tasks'), array('title' => 'Vaardigheden', 'url' => 'skills_overview', 'icon' => 'fa-sliders'), array('title' => 'Beroepen', 'url' => 'occupations_overview', 'icon' => 'fa-briefcase'), array('title' => 'Uitloggen', 'url' => 'logout', 'icon' => 'fa-lock')); $app->notFound(function () use($app, $data) { $app->render('404.html', $data); }); $app->get('/dashboard(/:school_id)', function ($school_id = null) use($app, $data) { $data['active_school_id'] = $school_id; if ($school_id == null) { $users = User::with('talents', 'skills', 'educationLevel')->get(); } else { $users = User::with('talents', 'skills', 'educationLevel')->where('school_id', '=', (int) $school_id)->get(); } $occupations = Occupation::all(); $schools = School::orderBy('name', 'ASC')->get(); $talents = Talent::all(); $data['schools'] = $schools->toArray(); $data['total_occupations'] = $occupations->count(); $data['total_users'] = $users->count(); $users_male = $users->filter(function ($user) {
require 'vendor/autoload.php'; require 'site-config.php'; date_default_timezone_set('Europe/Paris'); mb_internal_encoding('UTF-8'); ORM::configure('mysql:host=' . MYSQL_HOSTNAME . ';dbname=' . MYSQL_DATABASENAME); ORM::configure('username', MYSQL_USERNAME); ORM::configure('password', MYSQL_PASSWORD); ORM::configure('driver_options', array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8')); ORM::configure('return_result_sets', true); $app = new \Slim\Slim(array('mode' => MODE, 'debug' => MODE != MODE_PROD)); $app->hook('slim.after.router', function () use($app) { header_remove("X-Powered-By"); }); $app->notFound(function () use($app) { echo "404 Not found"; }); $app->error(function (\Exception $e) use($app) { echo "500 Server error"; // var_dump($e); }); $app->group('/services', function () use($app) { $app->get('/data/:id/:in/:out', function ($id, $in, $out) use($app) { $json = array(); if (preg_match("/^[0-9]+\$/", $id) && preg_match("/^[0-9\\-\\ \\:]+\$/", $in) && preg_match("/^[0-9\\-\\ \\:]+\$/", $out)) { $surveys = ORM::ForTable('lime_survey_' . $id)->where_gte('submitdate', $in)->where_lte('submitdate', $out)->order_by_asc('id')->find_many(); foreach ($surveys as $survey) { $date = DateTime::createFromFormat('Y-m-d H:i:s', $survey->submitdate); $survey->submitdts = $date->format('U'); // TODO: should considerate Paris Time array_push($json, $survey->as_array());
/** * Slim should throw a Slim_Exception_Stop if NotFound callback is not callable */ public function testNotFoundHandlerIfNotCallable() { $this->setExpectedException('\\Slim\\Exception\\Stop'); $s = new \Slim\Slim(); $notFoundCallback = 'foo'; $s->notFound($notFoundCallback); }
$app = new \Slim\Slim(array('mode' => 'production', 'debug' => True, 'log.level' => \Slim\Log::WARN, 'log.enabled' => True, 'log.writer' => new \Slim\LogWriter(fopen('/opt/unetlab/data/Logs/api.txt', 'a')))); $app->hook('slim.after.router', function () use($app) { // Log all requests and responses $request = $app->request; $response = $app->response; $app->log->debug('Request path: ' . $request->getPathInfo()); $app->log->debug('Response status: ' . $response->getStatus()); }); $app->response->headers->set('Content-Type', 'application/json'); $app->response->headers->set('X-Powered-By', 'Unified Networking Lab API'); $app->response->headers->set('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0'); $app->response->headers->set('Cache-Control', 'post-check=0, pre-check=0'); $app->response->headers->set('Pragma', 'no-cache'); $app->notFound(function () use($app) { $output['code'] = 404; $output['status'] = 'fail'; $output['message'] = $GLOBALS['messages']['60038']; $app->halt($output['code'], json_encode($output)); }); class ResourceNotFoundException extends Exception { } class AuthenticateFailedException extends Exception { } $db = checkDatabase(); if ($db === False) { // Database is not available $app->map('/api/(:path+)', function () use($app) { $output['code'] = 500; $output['status'] = 'fail'; $output['message'] = $GLOBALS['messages']['90003'];
<?php require __DIR__ . '/utility.php'; \Slim\Slim::registerAutoloader(); $app = new \Slim\Slim(); $app->notFound(function () use($dati, $app) { $app->render('shared/404.php', array('dati' => $dati)); }); $app->get('/', function () use($dati, $app) { $app->render('index.php', array('dati' => $dati)); })->name('index'); $app->map('/contattaci', function () use($dati, $app) { $app->render('email.php', array('dati' => $dati)); if (fatto()) { $app->redirect($app->urlFor('index')); } })->via('GET', 'POST'); $app->map('/templates(/:name+)', function ($name) use($dati, $app) { $app->render('shared/404.php', array('dati' => $dati)); })->via('GET', 'POST'); $app->get('/guida/:id', function ($id) use($dati, $app) { $app->render('index.php', array('dati' => $dati, 'guida' => $id)); }); $app->get('/logout', function () use($dati, $app) { $app->render('login/logout.php', array('dati' => $dati)); $app->redirect($app->urlFor('index')); }); if (!$dati['debug'] || isAdminUserAutenticate()) { $app->map('/login', function () use($dati, $app) { $app->render('login/index.php', array('dati' => $dati)); if (isUserAutenticate()) {
<?php require 'vendor/autoload.php'; $app = new \Slim\Slim(); $app->notFound(function () use($app) { $app = \Slim\Slim::getInstance(); $app->response->setStatus(404); echo "<body><center>\n\t\t<img src='http://i.imgur.com/33vDXBr.png'><br/>\n\t\t<br/>404 not found - plz go away now\n\t</center></body></html>"; }); $app->get('/', function () { echo "<pre>" . "\n _______ _______ _______ ______ _______ __ \n | | |_ _|_ _| __ \\______| | |.--.--.-----.| |_.-----.----.\n | | | | | | | __/______| || | | || _| -__| _|\n |___|___| |___| |___| |___| |___|___||_____|__|__||____|_____|__|\n\n @xxxx[{::::::::::::::::::::::::::::::::::>\n\tThe API :)" . "</pre><br/>\n<u><h3>Methods:</h3></u>\n/version - check version<br/>\n/search/ip/{ip} - search for documents matching an IP address<br/>\n/get/ips - get all IPs in the database. argument not required. Includes GeoIP data<br/>\n/count - total number of records in the HTTP-Hunter database"; }); $app->get('/version', function () { $app = \Slim\Slim::getInstance(); $app->response()->headers->set('Content-Type', 'application/json'); print json_encode(array('version' => 'beta-0.1'), JSON_PRETTY_PRINT); }); $app->get('/search/ip/:ip', function ($ip) { $app = \Slim\Slim::getInstance(); $app->response()->headers->set('Content-Type', 'application/json'); require_once 'inc/db.php'; $cursor = $collection->find(array('ip' => "{$ip}"), array('_id' => 0)); foreach ($cursor as $result) { print json_encode($result, JSON_PRETTY_PRINT); } }); $app->get('/get/ips', function () use($app) { $app->response()->headers->set('Content-Type', 'application/json'); require_once 'inc/db.php'; $cursor = $collection->find(array(), array('_id' => 0, 'ip' => 1, 'SSL' => 1, 'GeoIP' => 1)); $out = array();