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 }
/** * @dataProvider authenticationDataProvider */ public function testRouteAuthentication($requestMethod, $path, $location, $hasIdentity, $identity, $httpStatus) { \Slim\Environment::mock(array('REQUEST_METHOD' => $requestMethod, 'PATH_INFO' => $path)); $this->auth->expects($this->once())->method('hasIdentity')->will($this->returnValue($hasIdentity)); $this->auth->expects($this->once())->method('getIdentity')->will($this->returnValue($identity)); $app = new \Slim\Slim(array('debug' => false)); $app->error(function (\Exception $e) use($app) { // Example of handling Auth Exceptions if ($e instanceof AuthException) { $app->response->setStatus($e->getCode()); $app->response->setBody($e->getMessage()); } }); $app->get('/', function () { }); $app->get('/member', function () { }); $app->delete('/member/photo/:id', function ($id) { }); $app->get('/admin', function () { }); $app->map('/login', function () { })->via('GET', 'POST')->name('login'); $app->add($this->middleware); ob_start(); $app->run(); ob_end_clean(); $this->assertEquals($httpStatus, $app->response->status()); $this->assertEquals($location, $app->response->header('location')); }
/** * REST actions * * This function contains the REST actions with the assignments to * the functions. * * @param string[] $_argv Konsolenparameter, null = leer */ public function __construct($_argv) { if ($_argv != null) { // es gibt Konsolenparameter, diese werden nun $_POST zugewiesen, // sodass der Installationsassistent sie verwenden kann array_shift($_argv); foreach ($_argv as $arg) { $_POST[$arg] = 'OK'; } $this->CallInstall(true); return; } // initialize slim $app = new \Slim\Slim(array('debug' => true)); $app->contentType('text/html; charset=utf-8'); // POST,GET showInstall $app->map('(/)', array($this, 'CallInstall'))->via('POST', 'GET', 'INFO'); // POST,GET showInstall $app->map('/checkModulesExtern(/)', array($this, 'checkModulesExtern'))->via('POST', 'GET', 'INFO'); // run Slim $app->run(); }
/** * Verify basic behavior of __invoke(). * * @test * @covers ::__invoke * * @return void */ public function invoke() { $storage = new \OAuth2\Storage\Memory(['client_credentials' => ['testClientId' => ['client_id' => 'testClientId', 'client_secret' => 'testClientSecret']]]); $server = new \OAuth2\Server($storage, ['allow_implicit' => true], []); \Slim\Environment::mock(['REQUEST_METHOD' => 'POST', 'PATH_INFO' => '/authorize', 'QUERY_STRING' => 'client_id=testClientId&redirect_uri=http://example.com&response_type=code&state=test', 'slim.input' => 'authorized=yes']); $slim = new \Slim\Slim(); $slim->map('/authorize', new Authorize($slim, $server))->via('POST', 'GET'); ob_start(); $slim->run(); ob_get_clean(); $this->assertSame(302, $slim->response->status()); $location = $slim->response->headers()->get('Location'); $parts = parse_url($location); parse_str($parts['query'], $query); $this->assertTrue(isset($query['code'])); $this->assertSame('test', $query['state']); }
} //check if its expired and that the private token matches the public token if ($decoded->expires < time() && $header['username'] == $decoded->username) { http_response_code(401); die("Token Expired"); } }; //protected route group $app->group('/api/v1', $authenticate, function () use($app, $player, $game) { $app->get('/hello/:name', function ($name) { echo json_encode("{'name':{$name}}"); })->name("route with params"); $app->map('/players', function () use($player) { $players = $player->get_players(); if ($players) { echo json_encode($players); } else { echo $player->last_error(); } })->via('GET', 'POST'); $app->map('/getPlayers', function () use($player) { $players = $player->get_players(); if ($players) { echo json_encode($players); } else { echo $player->last_error(); } })->via('GET', 'POST'); $app->get('/getgame/:id', function () use($app, $game) { //serve up mock data for game $board = file_get_contents("./monopolyData.json"); $mockData = array("title" => "Mock Game", "turn" => 10, "balance" => 524, "currentPlayerTurn" => "Stuart", "board" => json_decode($board));
$app = \Slim\Slim::getInstance(); if ($app->userHelper->checkAdminAuthorization() != true) { $app->halt(403, "You have to have admin rights."); } } $app->map('/', function () use($app) { $page = 'index'; $message = ''; if ($app->request->isPost()) { if (file_exists($_FILES['load']['tmp_name']) && $_FILES['load']['error'] == 0) { $user = $app->userHelper->getUser(); $fileHelper = new FileHelper($app->em); $fileHelper->fileValidate($_FILES['load']); if (empty($fileHelper->errors)) { $file = $fileHelper->fileSave($_FILES['load'], $user, $app->request->post('comment')); $id = $file->getId(); $app->redirect("/view/{$id}"); } else { $message = $fileHelper->errors[0]; } } else { $message = "Вы не выбрали файл"; } } $notification = $app->request->get('notify'); $app->render('file_load.html', array('notification' => $notification, 'page' => $page, 'message' => $message)); })->via('GET', 'POST'); $app->map('/register/', function () use($app) { $errors = ''; $data = ''; if ($app->request->isPost()) { $validation = new \Uppu4\Helper\DataValidator();
/** * Test GENERIC route */ public function testGenericRoute() { $s = new \Slim\Slim(); $callable = function () { echo "foo"; }; $route = $s->map('/bar', $callable); $this->assertInstanceOf('\\Slim\\Route', $route); $this->assertEmpty($route->getHttpMethods()); }
$app->flash('info', 'ログインしました。'); $app->getLog()->info('ユーザー名「' . $user['username'] . '」(メールアドレス"' . $user['email'] . '")がログインしました。'); $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'); });
$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']; $app->response->setStatus($output['code']); $app->response->setBody(json_encode($output)); })->via('DELETE', 'GET', 'POST'); $app->run(); } if (updateDatabase($db) == False) { // Failed to update database // TODO should run una tantum $app->map('/api/(:path+)', function () use($app) { $output['code'] = 500; $output['status'] = 'fail'; $output['message'] = $GLOBALS['messages']['90006']; $app->response->setStatus($output['code']); $app->response->setBody(json_encode($output)); })->via('DELETE', 'GET', 'POST');
$app->map('/subscribe', function () use($app) { $ip = $_SERVER["REMOTE_ADDR"]; $paramOk = true; $message = null; $paramOk = $paramOk && ($name = @$_REQUEST['name']); if (!$paramOk && empty($message)) { $message = "Please input your name"; } $paramOk = $paramOk && ($email = @$_REQUEST['email']); if ($paramOk && empty($message)) { //\w{1,}([\-\+\.]\w{1,}){0,}@\w{1,}([\-\.]\w{1,}){0,}\.\w{1,}([\-\.]\w{1,}){0,} $regex = '/\\w{1,}([\\-\\+\\.]\\w{1,}){0,}@\\w{1,}([\\-\\.]\\w{1,}){0,}\\.\\w{1,}([\\-\\.]\\w{1,}){0,}/'; $email = trim($email); $paramOk = preg_match_all($regex, $email) && true; if ($paramOk && strpos($email, " ") > 0) { $paramOk = false; } if (!$paramOk) { $message = "Please input correct email address"; } } if (!$paramOk && empty($message)) { $message = "Please input your email"; } $paramOk = $paramOk && ($watchType = @$_REQUEST['watchType']); if (!$paramOk && empty($message)) { $message = "Please choose your watch' type"; } $paramOk = $paramOk && ($watchType == "Apple Watch Sport" || $watchType == "Apple Watch" || $watchType == "Apple Watch Edition"); if (!$paramOk && empty($message)) { $message = "Please choose right watch type"; } $paramOk = $paramOk && ($watchSize = @$_REQUEST['watchSize']); if (!$paramOk && empty($message)) { $message = "Please choose your watch' size"; } $paramOk = $paramOk && (strpos($watchSize, "38") === 0 || strpos($watchSize, "42") === 0); if (!$paramOk && empty($message)) { $message = "Please choose right watch size"; } $comment = @$_REQUEST['comment']; if ($paramOk) { $catalog = "Amber"; $name = urldecode($name); $email = urldecode($email); $catalog = urldecode($catalog); $watchType = urldecode($watchType); $watchSize = urldecode($watchSize); $comment = urldecode($comment); $db = connectDb(); $res = $db->insert("subscriber", ["name" => $name, "email" => $email, "country" => "", "city" => "", "catalog" => $catalog, "watch_type" => $watchType, "watch_size" => $watchSize, "comment" => $comment, "ip" => $ip]); if ($res) { outPutJson($app, 200, array("code" => 0, "msg" => "Successfully Subscribed")); } else { outPutJson($app, 500, array("code" => 1001, "msg" => "Server Error")); } } else { outPutJson($app, 400, array("code" => 1002, "msg" => $message)); } })->via('GET', 'POST', 'PUT');
<?php session_start(); require 'vendor/autoload.php'; Slim\Slim::registerAutoloader(); $app = new \Slim\Slim(); $app->config(array('debug' => true, 'templates.path' => 'Vista')); $app->map('/', function () use($app) { if (!isset($_SESSION['id_usuario'])) { //render login $app->render('index.php'); } else { //enviar al inicio //$app->redirect($app->urlFor('PaginaInicio')); //$app->response->redirect('Vista/index.html'); } })->via('GET')->name('Inicio'); //redirecionar el hamburgesa $app->get('/tienda', function () use($app) { $app->render('tienda.html'); }); $app->get('/tmp_inicio.php', function () use($app) { $app->render('tmp_inicio.php'); }); $app->get('/configuration', function () use($app) { $app->render('configuration.html'); }); $app->get('/info', function () use($app) { $app->render('info.php'); }); //Login
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) { header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}"); } } session_start(); date_default_timezone_set('America/New_York'); require '../vendor/slim/slim/Slim/Slim.php'; \Slim\Slim::registerAutoloader(); require '../vendor/phpmailer/phpmailer/PHPMailerAutoload.php'; require '../vendor/firebase/php-jwt/Authentication/JWT.php'; require 'control.php'; require 'class.php'; $app = new Slim\Slim(); // return HTTP 200 for HTTP OPTIONS requests $app->map('/:x+', function ($x) { http_response_code(200); })->via('OPTIONS'); // throw new Exception("Invalid Credentials.", 401); // Registration $app->post('/register', function () use($app) { $request = (array) json_decode($app->request->getBody()); $action = new Identity(); $action->register($request); $insert = new Request(); $insert->insert($action->sql); $insert->query($action->get($insert)); $user = $insert->response; $user = $user[0]; $user['fname'] = decode5t($user['fname']); $user['lname'] = decode5t($user['lname']); $auth = new AUTH();
} } else { $render("invalid.php", 422); } } else { // Simply render the home page $render(); } }; $reverse = function ($shortened) use($render_with_url, $render, $app, $helper) { $row = $helper->find_by_shortened($shortened); if (isset($row)) { $original = $row["original"]; // Decide on the type of answer, depending on the request $req = $app->request->headers()->get('ACCEPT'); if ($req == 'application/javascript' || $req == 'text/xml') { // API call echo $original; $app->stop(); } else { // Normal browser $render_with_url($original, $shortened); } } else { $render("not_found.php", 404); } }; $app->get('/:shortened', $redirect); $app->get('/reverse/:shortened', $reverse); $app->map('/', $shorten)->via('GET', 'POST'); $app->run();
<?php //header("Content-Type: text/html; charset=utf-8"); header('Content-Type: application/json'); chdir("../server"); require_once 'system/includes.php'; require_once 'libs/Slim/Slim.php'; \Slim\Slim::registerAutoloader(); $app = new \Slim\Slim(); $app->config('debug', true); //here set all routes $app->map('/writesketch', 'writesketchController')->via('POST'); $app->map('/diyexec', 'diyexecController')->via('POST'); $app->map('/reboot', 'rebootController')->via('GET'); $app->map('/reload', 'reloadController')->via('GET'); $app->map('/showall', 'showallController')->via('GET'); $app->map('/ps', 'psController')->via('GET'); $app->map('/isAlive', 'isAliveController')->via('GET'); $app->map('/isAlivelocal', 'isAlivelocalController')->via('GET'); //function not found $app->notFound(function () use($app) { $controller = $app->environment(); $controller = substr($controller["PATH_INFO"], 1); try { if (strtoupper($app->request()->getMethod() != 'GET')) { throw new Exception(ExceptionMessages::MethodNotFound, ExceptionCodes::MethodNotFound); } else { throw new Exception(ExceptionMessages::FunctionNotFound, ExceptionCodes::FunctionNotFound); } } catch (Exception $e) { $result["status"] = $e->getCode();
$app->db = $e; } /** * Application GetTweet Singleton object */ /** * use $app->getTweet to */ $app->container->singleton('getTweet', function () { return new Twitter\GetTweet(AppConfig::TWITTER_CONSUMNER_KEY, AppConfig::TWITTER_CONSUMNER_SECRET); }); /** * Create route for landing page */ $app->map('/', function () use($app) { $app->view()->appendData(array('APP_TITLE' => AppConfig::APP_TITLE, 'GOOGLE_API_KEY' => AppConfig::GOOGLE_API_KEY)); $app->render('map.html'); })->via('GET', 'POST'); /** * Api Route Group */ $app->group('/api', function () use($app) { //Api Group tweet $app->group('/tweet', function () use($app) { //Get tweets by location name $app->get('/recent/:locationName/', function ($locationName) use($app) { $tweets = Service\TweetService::getTweets($locationName); $app->render(200, $tweets); }); //->conditions(array('locationName' => '[a-zA-Z\+]+')); }); /**
/* If user who manually arrived here redirect to tab. */ } else { $app->redirect($app->config("tab_url")); } }); $app->get("/install", function () use($app, $facebook) { $app->render("install.html", array("app_id" => $facebook->getAppId())); }); /* Facebook converts GET request to POST. Provide both for easier */ /* development. */ $app->map("/tab", function () use($app, $facebook) { $signed_request = $facebook->getSignedRequest(); /* If you need to like gate (yuck) you can do something like if ($signed_request["page"]["liked"]) { render liked tab } else { render not liked tab } */ $app->render("tab.html", array("facebook" => $facebook, "app" => $app)); $app->getLog()->info("Tab rendered"); })->via("GET", "POST"); /* User gave permissions to application. */ $app->post("/entries", function () use($app, $facebook) { /* Creates new user with uid, oauth_token and name if does not exist. */ $user = current_user(); /* Save extra data if needed. */ /* $user->foo = $app->request()->post("foo"); $user->save(); */ /* Also log to a file. */
$app->container->singleton('filesHelper', function () use($app) { return new Filehosting\Helpers\FilesHelper(__DIR__, $app->filesMapper, $app->config('safeExtensions'), $app->config('maxsize')); }); if (!$app->getCookie('token')) { $app->setCookie('token', Filehosting\Helpers\FilesHelper::generateToken(), '90 days'); } $token = $app->getCookie('token'); $view->setData('filesHelper', $app->filesHelper); $app->map("/", function () use($app) { $error = ""; if ($_FILES) { $files = $app->filesMapper; $file = new Filehosting\File(); $postData = array('name' => $_FILES['userfile']['name'], 'size' => $_FILES['userfile']['size'], 'tmp_name' => $_FILES['userfile']['tmp_name'], 'error' => $_FILES['userfile']['error']); $error = $app->filesHelper->validateFileUpload($postData); if (!$error) { $app->filesHelper->uploadFile($file, $postData, $app->getCookie('token')); $id = $file->getId(); $app->redirect("/files/{$id}"); } } $app->render("index.html.twig", array('maxSize' => $app->config('maxsize'), 'error' => $error)); })->via('GET', 'POST'); $app->get("/main", function () use($app) { $lastUploadedFiles = $app->filesMapper->fetchLastUploadedFiles(); $app->render("main.html.twig", array('files' => $lastUploadedFiles)); }); $app->map("/files/:id", function ($id) use($app, $token) { $files = $app->filesMapper; if (!($file = $files->fetchFile($id))) { $app->notFound();
/** * Aplicação Slim */ include __DIR__ . '/vendor/autoload.php'; $app = new Slim\Slim(); $db = new App\DataBase(); $app->response->headers->set('Content-Type', 'application/json'); $app->get('/users', function () use($db) { echo json_encode($db->find()); }); $app->get('/users/:id', function ($id) use($db) { echo json_encode($db->findById($id)); }); $app->map('/users/:id', function ($id) use($app, $db) { $data = $app->request->params(); $db->update($id, $data); echo json_encode($db->find()); })->via('POST', 'PUT'); $app->post('/users', function () use($app, $db) { $data = $app->request->params(); $db->insert($data); echo json_encode($db->find()); }); $app->delete('/users/:id', function ($id) use($db) { $db->delete($id); echo json_encode($db->find()); }); $app->get('/(:name)', function ($name = 'Word') { echo 'Hello ' . $name . '!'; }); $app->run();
<?php // include Twitter Oauth Library require_once 'includes/library/twitteroauth.php'; // include config files require_once 'includes/twitter-config.php'; // include all models require_once 'models/HashtagSearchModel.php'; // include Slim require 'Slim/Slim.php'; \Slim\Slim::registerAutoloader(); // initiate Slim in DEBUG mode $app = new \Slim\Slim(array('debug' => true, 'mode' => 'development', 'log.enables' => true, 'log.level' => \Slim\Log::DEBUG)); $app->config('debug', true); /** Routes */ $app->map('/', 'showCustservTweets')->via('GET'); $app->map('/get-more-tweets', 'getMoreTweets')->via('GET'); $app->run(); /** Functions */ /** * showCustservTweets() - function catering to route '/' * * @return renders template `show-tweets.php` with the fetched tweets */ function showCustservTweets() { global $app; // hard-code the hashtag for this sample app, can be taken from user $hashtag = 'custserv'; // instantiate new hashtagsearch with the given hashtag $hashtag_search = new HashtagSearchModel($hashtag);
}; // Version endpoint. $app->get('/version', \Jloosli\SwaggerDoc::routeDoc(array('bob', 'june')), $checkRoute, function () use($app, $composer) { $app->response->write($composer->version); })->name('version'); // Version endpoint. $getRoute = $app->get('/get/:first/:second', $checkRoute, function ($first = '', $optional = '') use($app, $composer) { $app->response->write("GET"); })->name('get')->swagger = array('summary' => 'Here is the summary of this path', 'notes' => 'Another note about how this works', 'type' => 'theType', 'nickname' => 'theNickname', 'parameters' => array('should', 'be', 'self', 'generating'), 'responseMessages' => array('404', '304')); $app->post('/post', \Jloosli\SwaggerDoc::routeDoc(array('bob', 'june')), function (\Slim\Route $rt) { echo "<pre>"; print_r($rt); echo "</pre>"; }, function () use($app, $composer) { $app->response->write("POST"); })->name('post'); $app->put('/put', \Jloosli\SwaggerDoc::routeDoc(array('bob', 'june')), function (\Slim\Route $rt) { echo "<pre>"; print_r($rt); echo "</pre>"; }, function () use($app, $composer) { $app->response->write("PUT"); })->name('put'); $app->map('/map/:firstArg/(:optionalSecond)', \Jloosli\SwaggerDoc::routeDoc(array('bob', 'june')), function (\Slim\Route $rt) { echo "<pre>"; print_r($rt); echo "</pre>"; }, function () use($app, $composer) { $app->response->write("MAP"); })->via('GET', 'OPTIONS')->name('map'); $app->run();
$log = new \Monolog\Logger('slim-skeleton'); $log->pushHandler(new \Monolog\Handler\StreamHandler('logs/app.log', \Monolog\Logger::DEBUG)); return $log; }); $app->get('/', function () use($app) { if (isset($_SESSION['user'])) { $app->redirect("play"); } else { $app->render('index.php'); } }); $app->map('/add', function () use($app) { $model = array('qQuestion' => 'Cuantos átomos tiene el água niño ?', 'qAnswer1' => '2', 'qAnswer2' => '1', 'qAnswer3' => '3', 'qCorrectAnswer' => '2', 'qCat' => '3'); if (!$app->database->query_insert('questions', $model)) { $app->view->setData('message', 'Error: No se pudo registrar Jugador'); $app->render('error.php'); } else { $_SESSION['user'] = $app->request->params(); $app->redirect("play"); } })->via('GET', 'POST'); $app->map('/register', function () use($app) { if (!$app->database->query_insert('players', $app->request->params())) { $app->view->setData('message', 'Error: No se pudo registrar Jugador'); $app->render('error.php'); } else { $_SESSION['user'] = $app->request->params(); $app->redirect("play"); } })->via('GET', 'POST'); $app->get('/play', function () use($app) { /*if(!isset($_SESSION['user'])){
$app->map('/:type', function () use($app, $usermanager, $measureService, $dbManager) { $type = null; switch ($app->request()->getResourceUri()) { case "/electra": $type = MeasureService::type_electricity; break; case "/water": $type = MeasureService::type_water; break; case "/gas": $type = MeasureService::type_gas; break; default: $app->response->setStatus(404); return; } $authToken = $app->request->headers->get('X-AUTH-TOKEN'); $body = json_decode($app->request->getBody(), true); if (!$usermanager->validateToken($authToken)) { $app->response->setStatus(403); return; } $userid = $usermanager->getUserByToken($authToken); if ($userid == null) { $app->response->setStatus(403); return; } $conn = $dbManager->getConn(); $stmt = null; $app->response->setStatus(201); switch ($app->request->getMethod()) { case "GET": $page = intval($app->request->params('offset')); $pageSize = intval($app->request->params('pageSize')); $groupBy = $app->request->params('groupBy'); $data = array(); switch ($groupBy) { case 'year': $data = $measureService->getListByYear($userid, $type); break; default: $data = $measureService->getList($userid, $type, $page, $pageSize); } $app->response->write(json_encode($data)); return; case "POST": if (!$measureService->create($userid, $type, $body["date"], $body["value"])) { $app->response->setStatus(500); } $app->response->write(json_encode($measureService->getList($userid, $type))); break; case "PUT": if (!$measureService->update($userid, $app->request->params('id'), $type, $app->request->params('date'), $app->request->params('value'))) { $app->response->setStatus(500); } $app->response->write(json_encode($measureService->getList($userid, $type))); break; case "DELETE": if (!$measureService->delete($userid, $app->request->params('id'))) { $app->response->setStatus(500); } break; } })->VIA('GET', 'POST', 'PUT', 'DELETE')->conditions(array(":type" => "water|gas|electra"));
require_once 'settings.php'; //SETTINGS $app = new \Slim\Slim(array('cookies.encrypt' => COOKIECRYPT, 'cookies.secret_key' => COOKIEKEY, 'cookies.cipher' => MCRYPT_RIJNDAEL_256, 'cookies.cipher_mode' => MCRYPT_MODE_CBC)); $app->response->headers->set('Content-Type', 'application/json'); $app->group('/content', function () use($app) { $app->response->headers->set('Content-Type', 'application/json'); $app->map('/get', function () use($app) { //if(isset($data->token) && security_token($token)){ //if(security_token($token)){ if ($app->getCookie('aco-lan') !== null) { $lan = $app->getCookie('aco-lan'); } else { $app->redirect($app->urlFor('setLanguage', array('lan' => substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2)))); } if ($app->getCookie('aco-user') !== null) { $app->redirect($app->urlFor('getModified')); } else { $app->redirect($app->urlFor('getFinished')); } /*}else{ $app->halt(403, json_encode([ 'type' => 'error', 'title' => 'Forbidden Request', 'message' => 'You do not have the permission to call this request.'])); }*/ })->via('GET', 'PUT', 'POST', 'DELETE')->name('getContent'); $app->map('/get/finished', function () use($app) { if ($app->getCookie('aco-lan') !== null) { $lan = $app->getCookie('aco-lan'); } if (($db = connectToMySql()) !== false) { try {
\t\t\t\tto be properly <i>routed</i> - i.e. sent on to the correct handler that additional capabilities such as high level database access. \t\t\t</p> HTM; echo $html; }); //Connection define('DB_HOST', 'localhost'); define('DB_NAME', 'uas'); define('DB_USER', 'root'); define('DB_PASS', ''); //Laptop $app->get('/laptop', '\\App\\Routes\\Laptop:index'); $app->get('/laptop/find', '\\App\\Routes\\Laptop:find'); $app->get('/laptop/:id', '\\App\\Routes\\Laptop:view'); $app->post('/laptop', '\\App\\Routes\\Laptop:create'); $app->map('/laptop/:id', '\\App\\Routes\\Laptop:update')->via('PUT', 'PATCH'); $app->delete('/laptop/:id', '\\App\\Routes\\Laptop:delete'); //PartCategory $app->get('/part-category', '\\App\\Routes\\PartCategory:index'); $app->get('/part-category/find', '\\App\\Routes\\PartCategory:find'); $app->get('/part-category/:id', '\\App\\Routes\\PartCategory:view'); $app->post('/part-category', '\\App\\Routes\\PartCategory:create'); $app->map('/part-category/:id', '\\App\\Routes\\PartCategory:update')->via('PUT', 'PATCH'); $app->delete('/part-category/:id', '\\App\\Routes\\PartCategory:delete'); //Part $app->get('/part', '\\App\\Routes\\Part:index'); $app->get('/part/find', '\\App\\Routes\\Part:find'); $app->get('/part/by-laptop', '\\App\\Routes\\Part:byLaptop'); $app->get('/part/by-laptop/:id', '\\App\\Routes\\Part:byLaptopId'); $app->get('/part/by-category', '\\App\\Routes\\Part:byCategory'); $app->get('/part/by-category/:id', '\\App\\Routes\\Part:byCategoryId');
<?php // web/index.php use Aura\Input\Builder; use Aura\Input\Filter; require dirname(__DIR__) . '/vendor/autoload.php'; $app = new \Slim\Slim(array('templates' => dirname(__DIR__) . '/templates')); $app->map('/contact', function () use($app) { $form = new ContactForm(new Builder(), new Filter()); if ($app->request->isPost()) { $form->fill($app->request->post('contact')); if ($form->filter()) { echo "Yes successfully validated and filtered"; var_dump($data); $app->halt(); } } $app->render('contact.php', array('form' => $form)); })->via('GET', 'POST')->name('contact'); $app->run();
// We show all errors and that's it. No excuses. error_reporting(E_ALL | E_NOTICE); ini_set('display_errors', 1); // Useful globals defined('APPLICATION_PATH') || define('APPLICATION_PATH', realpath(dirname(__FILE__))); defined('APPLICATION_ENV') || define('APPLICATION_ENV', getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV') : 'production'); // Register autoloaders require 'library/vendor/autoload.php'; require 'library/Glossary/autoload.php'; // Read config file if (file_exists(APPLICATION_PATH . '/config.ini')) { $config = parse_ini_file(APPLICATION_PATH . '/config.ini', true); } else { $config = parse_ini_file(APPLICATION_PATH . '/config-default.ini', true); } // Create database connection $dbConfig = new \Doctrine\DBAL\Configuration(); $connectionParams = array('dbname' => $config['DB']['name'], 'user' => $config['DB']['user'], 'password' => $config['DB']['password'], 'host' => $config['DB']['host'], 'driver' => 'pdo_mysql'); $conn = \Doctrine\DBAL\DriverManager::getConnection($connectionParams, $dbConfig); // Bootstrap the Slim app $app = new \Slim\Slim(array('templates.path' => './templates', 'view' => new \Glossary\View(), 'settings' => $config, 'db' => $conn)); // Add the routes to the app $router = new \Glossary\Router(); foreach ($router->getRoutes() as $route) { $app->map($route['pattern'], function () use($route, $router) { $params = func_get_args(); $router->routeCallback($route, $params); })->via('GET', 'POST'); } // All done, run $app->run();
}); $app->group('/talents', function () use($app, $data) { $app->get('/', function () use($app, $data) { $data['talents'] = Talent::all()->toArray(); $app->render('talents/overview.html', $data); })->name('talents_overview'); $app->map('/edit/:id', function ($id) use($app, $data) { $data['request_method'] = $app->request->getMethod(); $talent = Talent::with('questions')->find($id); if ($app->request->isGet()) { $data['talent'] = $talent->toArray(); } else { if ($app->request->isPost()) { foreach ($app->request->post('question') as $key => $value) { $question = $talent->questions->find((int) $key); if ($question->question != $value) { $question->question = $value; $question->save(); } } $data['new_talent'] = $talent->toArray(); } } $app->render('talents/edit.html', $data); })->via('POST', 'GET')->name('talents_edit'); }); $app->group('/occupations', function () use($app, $data) { $data['request_method'] = $app->request->getMethod(); $app->get('/', function () use($app, $data) { $data['occupations'] = Occupation::with('talent', 'educationLevel')->get()->toArray(); $app->render('occupations/overview.html', $data);
| a. true = show status-code | b. false = dont show status-code | |---------------------------------------------------------------------------- **/ //run $api['LDAP_Api'] = new LDAP_Api(API_HIT_ENTRY_RESTAPI, true, true); $module++; debug("api({$module}): VIA LDAP_Api > "); //@ MAPPING of ROUTES //ldap group $app->group('/ldap', function () use($app, &$api) { $app->group('/restapi', function () use($app, &$api) { //sign-in $app->map('/signin', function () use($app, &$api) { $api['LDAP_Api']->hit(API_HIT_SIGN_IN, $app); return true; })->via('GET', 'POST'); //add entry $app->map('/add', function () use($app, &$api) { $api['LDAP_Api']->hit(API_HIT_ENTRY_ADD, $app); return true; })->via('POST', 'PUT'); //update entry $app->map('/modify', function () use($app, &$api) { $api['LDAP_Api']->hit(API_HIT_ENTRY_UPDATE, $app); return true; })->via('POST', 'PUT'); //search $app->map('/search', function () use($app, &$api) { $api['LDAP_Api']->hit(API_HIT_ENTRY_SEARCH, $app); return true;
<?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()) {
$app->map($route->address, function () use($app, $route) { $req = $app->request(); $res = $app->response(); $res->headers->set('Access-Control-Allow-Origin', '*'); $res->headers->set('Access-Control-Allow-Headers', 'X-HTTP-Method-Override'); // PARAMETERS WILL BE IN AN ARRAY $params = array(); // AUTHENTICATION if (isset($route->auth) && $route->auth == true) { $username = $req->headers('PHP_AUTH_USER'); $result = call_procedure('authenticate', array($username)); if ($result) { $params[] = $result->id; } else { $res->status(401); $res->header('WWW-Authenticate', sprintf('Basic realm="%s"', 'Protected Area')); return; } } // ADD ROUTE PARAMETERS for ($i = 0; $i < func_num_args(); ++$i) { $params[] = func_get_arg($i); } // ADD BODY PARAMETERS $request_body = json_decode($req->getBody()); if (isset($route->body_params)) { foreach ($route->body_params as $body_param => $type) { if (isset($request_body->{$body_param})) { $params[] = $request_body->{$body_param}; } else { $res->setStatus(400); json_error($body_param . ' missing in json request'); return; } } } // CHECK IF RESULT IS ONE OR MANY if (strpos($route->procedure->proc_name, '_all') !== false) { $amount = 'all'; } else { $amount = 'one'; } // CALL THE PROCEDURE AND ECHO JSON RESULT try { $result = call_procedure($route->procedure->proc_name, $params, $amount); //die(gettype($result[0]->id)); $json_result = json_encode($result); } catch (PDOException $e) { $res->setStatus(400); json_error($e->getMessage()); return; } echo $json_result; $res->headers->set('Content-Type', 'application/json'); })->via($route->method);