public function inscription(\Slim\Slim $app) { $allPostVars = $app->request->post(); $username = $allPostVars['username']; $mail = $allPostVars['mail']; $mdp = $allPostVars['mdp']; try { $db = getDB(); $verif = $db->prepare("SELECT username \n\t\t\t\tFROM users\n\t\t\t\tWHERE username = :username"); $verif->bindParam(':username', $username, PDO::PARAM_INT); $verif->execute(); $usernamed = $verif->fetch(PDO::FETCH_OBJ); $verif->closeCursor(); if ($usernamed) { $answer = "Ce nom d'utilisateur est déjà pris, merci de retenter avec un nouveau."; } else { $sth = $db->prepare("INSERT INTO users \n\t\t\t\t(username, mail, mdp)\n\t\t\t\tVALUES (:username, :mail, :mdp)"); $sth->bindParam(':username', $username, PDO::PARAM_INT); $sth->bindParam(':mail', $mail, PDO::PARAM_INT); $sth->bindParam(':mdp', $mdp, PDO::PARAM_INT); $sth->execute(); $answer = array("status" => "success", "code" => 1); } $app->response->setStatus(200); $app->response()->headers->set('Content-Type', 'application/json'); echo json_encode($answer); $db = null; } catch (PDOException $e) { $app->response()->setStatus(404); echo '{"error":{"text":' . $e->getMessage() . '}}'; } }
private function request($method, $path, $data = array(), $optionalHeaders = array()) { // Capture STDOUT ob_start(); $options = array('REQUEST_METHOD' => strtoupper($method), 'PATH_INFO' => $path, 'SERVER_NAME' => 'local.dev'); if ($method === 'get') { $options['QUERY_STRING'] = http_build_query($data); } elseif (is_array($data)) { $options['slim.input'] = http_build_query($data); } else { $options['slim.input'] = $data; } // Prepare a mock environment Slim\Environment::mock(array_merge($options, $optionalHeaders)); $env = Slim\Environment::getInstance(); $this->app->router = new NoCacheRouter($this->app->router); $this->app->request = new Slim\Http\Request($env); // Custom headers $this->app->request->headers = new Slim\Http\Headers($env); $this->app->response = new Slim\Http\Response(); // Establish some useful references to the slim app properties $this->request = $this->app->request(); $this->response = $this->app->response(); // Execute our app $this->app->run(); // Return the application output. Also available in `response->body()` return ob_get_clean(); }
function loginUser(\Slim\Slim $slimApp) { //echo "middleware:loginUser"; $request = $slimApp->request; $response = $slimApp->response(); $response->headers->set('Content-Type', 'application/json'); // $userData = json_decode($request->getBody()); $name = $userData->userName; $password = $userData->password; $email = $userData->email; // $dbUtil = new \icraft\DBUtil(); $DBH = $dbUtil->getConnection(); // $sql = "SELECT * FROM `users` WHERE uName=\'saumya\' && uPassword=\'saumyaPW1\'"; //$STH = $DBH->prepare("SELECT * FROM `users` WHERE uName='$name' && uPassword='******'"); $STH = $DBH->query("SELECT * FROM `users` WHERE uName='{$name}' && uPassword='******'"); $STH->setFetchMode(PDO::FETCH_ASSOC); //$STH->execute(); //var_dump($STH); $response->body('FAIL'); // Default FAIL while ($row = $STH->fetch()) { /* echo $row['uName'] . "\n"; echo $row['uPassword'] . "\n"; echo $row['uEmail'] . "\n"; */ $n = $row['uName']; $p = $row['uPassword']; $e = $row['uEmail']; $responseObj = "{'status':'SUCCESS','userObj':{'name':{$n},'password':{$p},'email':{$e}}}"; $response->body($responseObj); } }
/** * constructor */ final function __construct() { self::$app || (self::$app = \Slim\Slim::getInstance()); $this->request = self::$app->request(); $this->response = self::$app->response(); $this->config = self::$app->config; $this->validator = self::$app->validator; $this->init(); }
/** * @param IXmlExporter $exporter * @param int $status * @param string $contentType */ protected function xmlOutput(IXmlExporter $exporter, $status = 200, $contentType = 'application/xml') { $this->app->expires(0); $this->app->contentType($contentType); $response = $this->app->response(); $response->setStatus($status); $response->header('Content-Description', 'File Transfer'); if ($exporter->isFile()) { $response->header('Content-Disposition', 'attachment; filename=' . $exporter->getFileName()); } $response->body($exporter->buildXml()); }
/** * @param Route $route * @throws \Slim\Exception\Stop */ private function checkAuth(Route $route) { $request = OAuth2\Request::createFromGlobals(); $scopeRequired = []; if ($route->isSecure()) { $scopeRequired = 'admin'; } if (!$this->oauth->verifyResourceRequest($request, NULL, $scopeRequired)) { $response = $this->oauth->getResponse(); $this->app->response()->status($response->getStatusCode()); $response->send(); $this->app->stop(); } }
public function __construct(Slim $app, array $params = array()) { $this->app = $app; $this->request = $app->request(); $this->response = $app->response(); $this->params = $this->buildParams($params); }
/** * Constructor * * @param Slim $app */ public function __construct(Slim $app, array $config = []) { $this->app = $app; $this->dic = $app->dic; $this->request = $app->request(); $this->response = $app->response(); $this->config = $config; }
/** * Call this class as a function. * * @return void */ public function __invoke() { $request = MessageBridge::newOAuth2Request($this->slim->request()); $response = new OAuth2\Response(); $isValid = $this->server->validateAuthorizeRequest($request, $response); if (!$isValid) { MessageBridge::mapResponse($response, $this->slim->response()); return; } $authorized = $this->slim->request()->params('authorized'); if (empty($authorized)) { $this->slim->render($this->template, ['client_id' => $request->query('client_id', false)]); return; } //@TODO implement user_id $this->server->handleAuthorizeRequest($request, $response, $authorized === 'yes'); MessageBridge::mapResponse($response, $this->slim->response()); }
public function request($method, $path, $options = array()) { ob_start(); Environment::mock(array_merge(array('PATH_INFO' => $path, 'SERVER_NAME' => 'slim-test.dev', 'REQUEST_METHOD' => $method), $options)); $app = new Slim(); $this->app = $app; $this->request = $app->request(); $this->response = $app->response(); return ob_get_clean(); }
public function request($method, $path, $options = array()) { // Capture STDOUT ob_start(); // Prepare a mock environment Environment::mock(array_merge(array('REQUEST_METHOD' => $method, 'PATH_INFO' => $path, 'SERVER_NAME' => 'mock.matrix42.com'), $options)); $app = new Slim(); $this->app = $app; $this->request = $app->request(); $this->response = $app->response(); // Return STDOUT return ob_get_clean(); }
/** * Return HTTP status code and message to requester. * * @param Slim $app * @param Exception $e * * @return mixed */ private function handleException($app, Exception $e) { $status = $e->getCode(); $statusText = \Slim\Http\Response::getMessageForCode($status); if ($statusText === null) { $status = 500; $statusText = 'Internal Server Error'; } $app->response->setStatus($status); $app->response->headers->set('Content-Type', 'application/json'); $app->response->setBody(json_encode(array('status' => $status, 'statusText' => preg_replace('/^[0-9]+ (.*)$/', '$1', $statusText), 'description' => $e->getMessage()))); $app->response()->finalize(); return $app->response(); }
public function register(Slim $app) { $app->container->singleton('cache', function () { return new FilesystemCache('tmp/cache/db'); }); $app->container->singleton('connection', function () { $dbOptions = (require 'config/connection.config.php'); $config = new Configuration(); return DriverManager::getConnection($dbOptions, $config); }); $app->container->singleton('log', function () { $logger = new Logger('echale-gas'); $logger->pushHandler(new StreamHandler('tmp/logs/app.log', LogLevel::DEBUG)); return $logger; }); $app->container->singleton('paginator', function () use($app) { return new PagerfantaPaginator($app->config('defaultPageSize')); }); $app->container->singleton('paginatorFactory', function () use($app) { return new PaginatorFactory($app->paginator); }); $app->container->singleton('proxiesConfiguration', function () use($app) { $config = new ProxyConfiguration(); $config->setProxiesTargetDir('tmp/cache/proxies'); spl_autoload_register($config->getProxyAutoloader()); return $config; }); $app->urlHelper = new TwigExtension(); $app->container->singleton('twig', function () use($app) { $twig = new Twig(); $twig->parserOptions = ['charset' => 'utf-8', 'cache' => realpath('tmp/cache/twig'), 'auto_reload' => true, 'strict_variables' => false, 'autoescape' => true]; $twig->parserExtensions = [$app->urlHelper, new HalRendererExtension()]; return $twig; }); $app->container->singleton('controllerEvents', function () use($app) { $eventManager = new EventManager(); // Ensure rendering is performed at the end by assigning a very low priority $eventManager->attach('postDispatch', new RenderResourceListener($app->twig), -100); $eventManager->attach('renderErrors', new RenderErrorsListener($app->twig), -100); return $eventManager; }); $app->container->singleton('controller', function () use($app) { $controller = new RestController($app->request(), $app->response()); $factory = new RestControllerProxyFactory($app->proxiesConfiguration, $app->controllerEvents); $controller = $factory->createProxy($controller); $factory->addEventManagement($controller); return $controller; }); $app->view($app->twig); }
public function checkLimit($package) { $thisHour = floor(time() / 60 / 60); if (isset($_SESSION['requestHour']) && $_SESSION['requestHour'] == $thisHour) { $_SESSION['requestCount']++; } else { $_SESSION['requestHour'] = $thisHour; $_SESSION['requestCount'] = 1; } $package = R::findOne('managepackages', ' name = ?', array($this->cleanup($package))); $this->app->response()->header('Api-Utilization', $_SESSION['requestCount']); $this->app->response()->header('Api-Limit', $package->rate); if ($package->rate >= $_SESSION['requestCount']) { return true; } return false; }
protected function error($message, $status = 404) { $this->app->response()->setStatus($status); $this->app->response->setBody(json_encode(array('error' => array('message' => $message, 'status_code' => $status)))); }
private function loadApplicationPath(Slim $app, ApplicationPath $classAnnotation) { if ($classAnnotation->responseContentType) { $app->response()->header('content-type', $classAnnotation->responseContentType); } }
/** * @param Slim $app * @return $response */ public static function logout(Slim $app) { $response = $app->response(); $response->headers->set('Content-Type', 'application/json'); $username = $app->request->params('username'); $password = $app->request->params('password'); $credentials = self::validateCredentials($app, $username, $password); if ($credentials) { User::where('username', $username)->update(['token' => null, 'token_expire' => null]); $response->body(json_encode(['status' => 200, 'message' => 'session destroyed success!'])); return $response; } }
use PushNotification\Model\Notification; use PushNotification\Model\HttpStatusCode; use PushNotification\Push\PushController; use PushNotification\Push\DeviceManager; use PushNotification\Authorization\Authorization; if (ENVIRONMENT == ENVIRONMENT_DEV) { ini_set('display_errors', 1); error_reporting(E_ALL); } date_default_timezone_set("UTC"); // registra Slim::registerAutoloader(); // inicializa e configura as rotas $app = new Slim(array('mode' => ENVIRONMENT == ENVIRONMENT_PROD ? 'production' : 'development')); if (CROSS_ORIGIN_ENABLED) { $app->response()->header('Access-Control-Allow-Origin', ACCESS_CONTROL_ALLOW_ORIGIN); } $app->get('/users/:userId/devices', 'authorize', 'getUserDevices'); $app->get('/users', 'authorize', 'getUsers'); $app->get('/devices', 'authorize', 'getDevices'); $app->post('/devices', 'authorize', 'createDevice'); $app->put('/devices', 'authorize', 'updateDevice'); $app->delete('/devices', 'authorize', 'deleteDevice'); $app->post('/notifications', 'authorize', 'sendNotification'); $app->run(); /** * Busca usuários que possuem dispositivos cadastrados * * Permite paginação através do parâmetros: * - page: página a ser retornada * - limit: quantidade de resultados a serem retornados
/** * @param $id * @param Slim $app * @return string */ public static function delete(Slim $app, $id) { $response = $app->response(); $response->headers->set('Content-Type', 'application/json'); $name = $app->request->params('name'); $emojichar = $app->request->params('emojichar'); $keywords = $app->request->params('keywords'); $category = $app->request->params('category'); $token = $app->request->headers('Authorization'); $auth = Authorization::isAuthorised($app, $token); try { $delete = Emoji::destroy($id); if ($delete == 1) { $response->body(json_encode(['status' => 200, 'message' => 'successfully deleted!'])); } else { $response->body(json_encode(['status' => 404, 'message' => 'Emoji not found'])); } } catch (QueryException $e) { $response->body(json_encode(['message' => $e->getExceptionMessage()])); } return $response; }
private static function setContentType(Slim $app) { $response = $app->response(); $response->header("Content-type", "application/json"); self::$response = $response; }
/** * Render content and status * * @param $body * @param int $status */ protected function render($body, $status = 200) { $this->app->response()->status($status); $this->app->response()->body($body); }
<?php /** * Piwik - Open source web analytics * * @link http://piwik.org * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later */ require '../vendor/autoload.php'; if (file_exists('../config/local.php')) { require '../config/local.php'; } require '../config/app.php'; use Slim\Slim; use Slim\Views\Twig; use helpers\Log; use helpers\CacheMiddleware; // New Slim App $app = new Slim(array('view' => new Twig(), 'log.enabled' => true, 'debug' => DEBUG, 'templates.path' => '../templates', 'templates.cache' => realpath('../tmp/templates'), 'templates.charset' => 'utf-8', 'templates.auto_reload' => true, 'templates.autoescape' => true, 'log.writer' => new \Slim\Extras\Log\DateTimeFileWriter(array('path' => realpath('../tmp/logs'), 'name_format' => 'Y-m-d')))); $app->add(new CacheMiddleware()); $app->error(function (\Exception $e) use($app) { Log::error('An unhandled exception occurred: ' . $e->getMessage() . $e->getTraceAsString()); $app->response()->status(500); }); $app->setName('developer.piwik.org'); $log = $app->getLog(); $log->setEnabled(true); require '../routes/page.php'; $app->run();
/** * Retrieve the current application response. * * @return Response */ public function response() { return $this->app->response(); }
/** * Here's the endpoint where Telegram will send it's updates to. Register your * commands in the CommandHandler in here. */ $app->post("/webhook", function () use($app) { /** @var Update $update */ $update = $app->telegram->entityFromBody($app->request->getBody(), new Update()); if ($update->message instanceof Message) { try { // Register your commands here $handler = new CommandHandler($app->telegram); $handler->register(new HelloWorldCommand("hello")); $handler->run($update); } catch (\Exception $e) { echo $e->getMessage(); $app->response()->setStatus(500); } } else { echo "Couldn't find the Message in the body."; $app->response()->setStatus(400); } })->name("webhook"); /** * Install webhook with Telegram API. Uses the current url and "webhook" route. * POST to this URL to install your webhook with Telegram. * * Note: Telegram requires your webhooks to use HTTPS. * * For example: * * POST https://bot.mydomain.com/install HTTP/1.1
public function deleteUser(\Slim\Slim $app, $id) { //$app = \Slim\Slim::getInstance(); try { $db = getDB(); $sth = $db->prepare("DELETE FROM users \n\t\t\t\tWHERE id = :id"); $sth->bindParam(':id', $id, PDO::PARAM_INT); $sth->execute(); $app->response->setStatus(200); $app->response()->headers->set('Content-Type', 'application/json'); echo json_encode(array("status" => "success", "code" => 1)); $db = null; } catch (PDOException $e) { $app->response()->setStatus(404); echo '{"error":{"text":' . $e->getMessage() . '}}'; } }
protected function send($content_type, $body) { $res = $this->app->response(); $res['Content-type'] = $content_type; $res->body($body); }
/** * @param $app * @return mixed */ private function getResponse(Slim $app) { $response = $app->response(); $response->header("Content-type", "application/json"); return $response; }
* Time: 9:30 AM */ require_once 'vendor/autoload.php'; use Slim\Slim; use Verem\Emoji\Api\AuthController; use Verem\Emoji\Api\EmojiController; use Verem\Emoji\Api\DAO\UserManager; use Verem\Emoji\Api\Exceptions\RecordNotFoundException; $app = new Slim(['templates.path' => 'templates/', 'debug' => true]); // Prepare view $app->view(new \Slim\Views\Twig()); $app->view->parserOptions = array('charset' => 'utf-8', 'cache' => realpath('templates/cache'), 'auto_reload' => true, 'strict_variables' => false, 'autoescape' => true); $app->view->parserExtensions = array(new \Slim\Views\TwigExtension()); //route middleware $authenticator = function () use($app) { $response = $app->response(); $response->header("Content-type", "application/json"); //determine if the user has authorization. $authorization = $app->request->headers->get('Authorization'); if (!is_null($authorization)) { //check token expiry $manager = new UserManager(); try { $user = $manager->where('token', '=', $authorization); if ($user['token_expire'] < date('Y-m-d H:i:s')) { $response->body(json_encode(['status' => 401, 'message' => 'You have no authorization'])); $response->status(401); $app->stop(); return $response; } $app->response->header('Authorization', $authorization);
//$allPostVars = $app->request->post(); //$allPutVars = $app->request->put(); //var_dump($allGetVars); //var_dump($allPostVars); //var_dump($allPutVars); class ResourceNotFoundException extends Exception { } // handle GET requests for /articles/:id $app->get('/articles/:id', function ($id) use($app) { try { // query database for single article $article = R::findOne('articles', 'id=?', array($id)); if ($article) { // if found, return JSON response $app->response()->header('Content-Type', 'application/json'); echo json_encode(R::exportAll($article)); } else { // else throw exception throw new ResourceNotFoundException(); } } catch (ResourceNotFoundException $e) { // return 404 server error $app->response()->status(404); } catch (Exception $e) { $app->response()->status(400); $app->response()->header('X-Status-Reason', $e->getMessage()); } }); // run $app->run();
/** * Render content and status * * @param mixed $data * @param int $status */ protected function render(array $data, $status = 200) { $this->app->view(new JsonView()); $this->app->response()->setStatus($status); $this->app->render('', $data); }