public static function init() { $app = new \Slim\Slim(); $app->setName(Application::InstanceName()); if (strpos($app->request()->getPath(), Application::BasePath()) === 0) { Doc::createInstance($app); Posts::createInstance($app); $app->run(); exit; } }
/** * @param One_Scheme $scheme * * PUT schemename/ID * Update an instance */ public static function restPut(One_Scheme $scheme, $idOrAlias) { try { // retrieve input data from body (a JSON encoded structure) $request = $this->slim->request(); $body = $request->getBody(); $input = json_decode($body); $model = One_Repository::selectOne($scheme->getName(), $idOrAlias); if ($model === null) { throw new One_Exception_Rest_404('Cannot locate instance of scheme ' . $scheme->getName() . ' identified by ' . $idOrAlias); } foreach ($input as $k => $v) { $model->{$k} = $v; } $model->update(); echo self::toPrettyJson($model->asRestResponse()); } catch (One_Exception_Rest_404 $e) { // return 404 server error $this->slim->response()->status(404); echo '{}'; } catch (Exception $e) { $this->slim->response()->status(400); $this->slim->response()->header('X-Status-Reason', $e->getMessage()); } }
function autenticar1() { $app = new \Slim\Slim(); $request = $app->request(); echo json_decode($request->getBody()); //var_dump($user); }
function addUser() { $app = new \Slim\Slim(); $request = $app->request(); $data = json_decode($request->getBody(), true); $user = User::create($data); $user->save(); }
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; }
function editUser() { $app = new \Slim\Slim(); $request = $app->request(); $data = json_decode($request->getBody()); $user = User::find($data->id); $user->username = $data->username; $user->fullname = $data->fullname; $user->save(); }
/** * Test default instance properties */ public function testDefaultInstanceProperties() { $s = new \Slim\Slim(); $this->assertInstanceOf('\\Slim\\Http\\Request', $s->request()); $this->assertInstanceOf('\\Slim\\Http\\Response', $s->response()); $this->assertInstanceOf('\\Slim\\Router', $s->router()); $this->assertInstanceOf('\\Slim\\View', $s->view()); $this->assertInstanceOf('\\Slim\\Log', $s->getLog()); $this->assertEquals(\Slim\Log::DEBUG, $s->getLog()->getLevel()); $this->assertTrue($s->getLog()->getEnabled()); $this->assertInstanceOf('\\Slim\\Environment', $s->environment()); }
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' => 'slim-test.dev'), $options)); $app = new \Slim\Slim(); $this->app = $app; $this->request = $app->request(); $this->response = $app->response(); // Return STDOUT return ob_get_clean(); }
/** * @param \Pimple $pimple */ public function setup(\Pimple $pimple) { $me = $this; $pimple['db'] = function () use($me) { $conn = Utils::getConnection(SW_PATH); return $conn; }; $pimple['filesystem.factory'] = function () use($me) { $updateConfig = $me->getParameter('update.config'); $ftp = isset($updateConfig['ftp_credentials']) ? $updateConfig['ftp_credentials'] : array(); return new FilesystemFactory(SW_PATH, $ftp); }; $pimple['path.builder'] = function () use($me) { $baseDir = SW_PATH; $updateDir = UPDATE_FILES_PATH; $backupDir = SW_PATH . '/files/backup'; return new PathBuilder($baseDir, $updateDir, $backupDir); }; $pimple['migration.manager'] = function () use($me) { $migrationPath = UPDATE_ASSET_PATH . '/migrations/'; $db = $me->get('db'); $migrationManger = new MigrationManager($db, $migrationPath); return $migrationManger; }; $pimple['dump'] = function () use($me) { $snippetsSql = UPDATE_ASSET_PATH . '/snippets.sql'; $snippetsSql = file_exists($snippetsSql) ? $snippetsSql : null; if (!$snippetsSql) { return null; } return new Dump($snippetsSql); }; $pimple['app'] = function () use($me) { $slimOptions = $me->getParameter('slim'); $slim = new \Slim\Slim($slimOptions); $me->set('slim.request', $slim->request()); $me->set('slim.response', $slim->response()); return $slim; }; $pimple['controller.batch'] = function () use($me) { return new BatchController($me->get('slim.request'), $me->get('slim.response'), $me); }; }
return true; } $apiResponse = new APIViewData(1, $deployment, "Unable to detect either contacts or contact_group parameter"); $app->halt(404, $apiResponse->returnJson()); } function httpCache($app, $sec = 30) { $app->response()->header('cache-control', 'private, max-age=' . $sec); $app->response()->header('expires', date('r', time() + $sec)); $app->response()->header('pragma', 'cache'); } // Setup our application's environment $app->config(array('debug' => true)); // Setup Lazy Loader for Routes $app->hook('slim.before.router', function () use($app) { $uri = $app->request()->getResourceUri(); if (($k = strpos($uri, "/", 1)) === false) { $controller = $uri; } else { $controller = '/' . strtok($uri, '/'); $controller .= '/' . strtok('/'); } switch ($controller) { case "/sapi/configs": require_once BASE_PATH . "/routes/configs.route.php"; break; case "/sapi/consumer": require_once BASE_PATH . "/routes/consumer.route.php"; break; case "/sapi/commands": case "/sapi/command":
print_r($entry->procedure->proc_name); print_r(": \n"); print_r($proc_params); print_r("\n\n\n"); if (isset($proc_params) && isset($procedure->proc_body)) { $sql_drop = 'DROP PROCEDURE IF EXISTS ' . $procedure->proc_name . "; \n"; $sql_create = "CREATE PROCEDURE " . $procedure->proc_name . "(" . $proc_params . ") " . "BEGIN \n" . $procedure->proc_body . " \nEND; \n\n"; if (!$mysqli->query($sql_drop) || !$mysqli->query($sql_create)) { return false; } } } return true; } $app->group('/', function () use($app, $dbsettings) { $username = $app->request()->headers('PHP_AUTH_USER'); $password = $app->request()->headers('PHP_AUTH_PW'); if ($username != $dbsettings->dbuser || $password != $dbsettings->dbpass) { $app->response()->status(401); $app->response()->header('WWW-Authenticate', sprintf('Basic realm="%s"', 'Protected Area')); return; } $app->get('/', function () use($app) { $app->render('app.html'); }); $app->post('procparams', function () use($app) { $entry = json_decode($app->request()->getBody()); echo getInputParams($entry); }); $app->get('api', function () use($app) { $app->render('../../api/api.json');
*/ foreach ($config['feature'] as $feature) { if ($feature['enabled'] == "on") { $app->log->debug("Including Feature {$feature['name']}"); include 'features/' . $feature['name'] . '/lib.php'; include 'features/' . $feature['name'] . '/routes.php'; } } // set admin info on the environment array // so it's available to our request handlers $env = $app->environment; $env['admin'] = MorgueAuth::get_auth_data(); $app->get('/', function () use($app) { $content = 'content/frontpage'; $show_sidebar = true; $selected_tags = trim($app->request()->get('tags')); if (strlen($selected_tags) > 0) { $selected_tags = explode(",", $selected_tags); $selected_tags = array_map('trim', $selected_tags); $events = Postmortem::get_events_for_tags($selected_tags); } else { $selected_tags = null; $events = Postmortem::get_all_events(); } if ($events["status"] == Postmortem::OK) { $events = $events["values"]; } else { $app->response->status(500); echo json_encode($events["error"]); return; }
header("Content-Type: application/json"); header('HTTP/1.0 200 OK'); echo json_encode($resposta); exit; }); $app->get('/pedido', function () { $pedido = new Pedido(); $itens = $pedido->getPedidoItens(); $resposta = array("status" => "sucesso", "message" => "A lista está vazia", "data" => $itens); header("Content-Type: application/json"); header('HTTP/1.0 200 OK'); echo json_encode($resposta); exit; }); $app->get('/pedido/:id', function ($id) use($app) { $clientenome = $app->request()->get("clientenome"); $resposta = array("status" => "sucesso", "message" => "Seu código é {$id}", "data" => array("clientenome" => $clientenome)); header("Content-Type: application/json"); header('HTTP/1.0 200 OK'); echo json_encode($resposta); exit; }); $app->post('/pedido', function () use($app) { $produtoid = $app->request()->post("produtoid"); $produtonome = $app->request()->post("produtonome"); $produtoestoque = $app->request()->post("produtoestoque"); $produtovalor = $app->request()->post("produtovalor"); $pedido = new Pedido(); $produto = new Produto($produtoid, $produtonome, $produtoestoque, $produtovalor); $pedido->addItemPedido($produto, 1); $pedidoservicos = new PedidoServicos();
} } // echo json response echoRespnse(201, $response); }); /** * User Login * url - /login * method - POST * params - email, password */ $app->post('/login', function () use($app) { // check for required params verifyRequiredParams(array('email', 'password')); // reading post params $email = $app->request()->post('email'); $password = $app->request()->post('password'); $response = array(); $db = new DbHandler(); // check for correct email and password if ($db->checkLogin($email, $password)) { // get the user by email $user = $db->getUserByEmail($email); if ($user != NULL) { $response["error"] = false; $response['name'] = $user['name']; $response['email'] = $user['email']; $response['apiKey'] = $user['api_key']; $response['created_at'] = $user['created_at']; } else { // unknown error occurred
//Do itteration for all document in a collection foreach ($cur as $doc) { $tmp = array(); //Set key and get value from document and store to temporary array $tmp["name"] = $doc["name"]; $tmp["age"] = $doc["age"]; //push temporary array to $result array_push($result, $tmp); } //show result response(200, $result); }); //Post Friends end point $app->post('/friends', function () use($app) { $res = array(); $name = $app->request()->post('name'); $age = $app->request()->post('age'); $db = new dbHandler(); $cur = $db->insertFriend($name, $age); if ($cur == INSERT_COL_SUCCESS) { $res["error"] = FALSE; $res["message"] = "Success to insert a new friend"; response(201, $res); } else { $res["error"] = TRUE; $res["message"] = "Failed to add a new friend"; response(200, $res); } }); //Delete friend end point /*
$db = new PDO("mysql:host={$host};dbname={$dbName};charset=utf8", $userName, $pwd, [\PDO::ATTR_PERSISTENT => false]); } catch (PDOException $e) { die('Error!: ' . $e->getMessage()); } return $db; }); $app->container->singleton('hybridInstance', function () { $instance = new Hybrid_Auth('config.php'); return $instance; }); $model = new \Model\App_Model($app->db); $authenticate = function ($app) { return function () use($app) { $app->hybridInstance; $session_identifier = Hybrid_Auth::storage()->get('user'); if (is_null($session_identifier) && $app->request()->getPathInfo() != '/login/') { $app->redirect('/login/'); } }; }; $app->get('/', function () use($app, $model) { $app->hybridInstance; $session_identifier = Hybrid_Auth::storage()->get('user'); $avatarUrl = $model->getAvatarUrl($session_identifier); if (isset($session_identifier) && !empty($session_identifier)) { $scriptID = 'i'; } else { $scriptID = '!i'; } $app->render('home.php', ['datajs' => 'home.js', 'datagroupjs' => '', 'name' => 'Home', 'avatarURL' => $avatarUrl, 'identifier' => $session_identifier, 'scriptID' => $scriptID]); })->name('home');
} while (in_array($id_producto, $ids)); array_push($datos, $cursor); array_push($ids, $id_producto); } echo json_encode($datos); }); /* * Ruta para mostrar los productos en las vistas con listado de productos */ $app->get('/productos', function () use($app) { // conectar con la BD y seleccionar la colección $mongo = new MongoClient(); $database = $mongo->plazamar; $collection = $database->productos; // recoger la query string de la url pasada por backbone $req = $app->request(); $categoria = $req->get('categoria'); $descuento = $req->get('tieneDescuento'); $ordenar = $req->get('ordenar'); $buscar = $req->get('buscar'); // recoger los productos y enviarlos de vuelta a BAckbone if ($categoria || $descuento || $ordenar) { if ($categoria && $ordenar === 'si') { $cursor = $collection->find(array('categoria' => $categoria))->sort(array("titulo" => 1)); } else { if ($categoria && !$ordenar) { $cursor = $collection->find(array('categoria' => $categoria)); } else { if ($descuento) { $cursor = $collection->find(array('tieneDescuento' => 'true')); }
*/ //first example /* $app->get('/hello/:name', function ($name) { echo "Hello, $name"; }); */ $app->get('/', function () use($app) { $app->render('about.twig'); }); $app->get('/contact', function () use($app) { //DEBUG check it with name function $app->render('contact.twig'); }); $app->post('/contact', function () use($app) { $name = $app->request()->post('name'); $email = $app->request()->post('email'); $msg = $app->request()->post('msg'); if (!empty($name) && !empty($email) && !empty($msg)) { $claenName = filter_var($name, FILTER_SANITIZE_STRING); $claenEmail = filter_var($email, FILTER_SANITIZE_EMAIL); $claenMsg = filter_var($msg, FILTER_SANITIZE_STRING); } else { $app->redirect('contact'); } // Create the Transport $transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 465, 'ssl')->setUsername('*****@*****.**')->setPassword('LittleRichard'); //test it!!!!!!!!! //$transport = Swift_SmtpTransport::newInstance('mail.matenadaran.am', 465, 'ssl') // ->setUsername('*****@*****.**') // ->setPassword('d_404_igit')
'expires' => '20 minutes', 'path' => '/', 'domain' => null, 'secure' => false, 'httponly' => false, 'name' => 'app_session_name', 'secret' => md5('appsecretkey'), 'cipher' => MCRYPT_RIJNDAEL_256, 'cipher_mode' => MCRYPT_MODE_CBC ))); */ /* * SET some globally available view data */ $resourceUri = $_SERVER['REQUEST_URI']; $rootUri = $app->request()->getRootUri(); $assetUri = $rootUri; $app->view()->appendData(array('app' => $app, 'rootUri' => $rootUri, 'assetUri' => $assetUri, 'resourceUri' => $resourceUri)); foreach (glob(ROOT . '/app/controllers/*.php') as $router) { include $router; } // Disable fluid mode in production environment $app->configureMode(SLIM_MODE_PRO, function () use($app) { // note, transactions will be auto-committed in fluid mode R::freeze(true); }); /* |-------------------------------------------------------------------------- | Configure Twig |-------------------------------------------------------------------------- |
}; }; /*********************************************************************************************************************** * ADMIN BLOCK **********************************************************************************************************************/ // Admin $app->get('/admin/', function () use($app) { $twig_vars = $app->config('twigVars'); $app->view->setTemplatesDirectory("admin/"); $app->render('admin.html.twig', $twig_vars); }); // Admin Login $app->post('/admin/login', function () use($app) { $twig_vars = $app->config('twigVars'); $config = $twig_vars['config']; $user = $app->request()->post('user'); $pass = sha1($app->request()->post('password')); if ($config['user'] == $user && $config['password'] == $pass) { $_SESSION['user'] = $user; $_SESSION['pass'] = $pass; $app->redirect($config['url'] . '/admin/pages'); } else { $app->redirect($config['url'] . '/admin'); } }); // Admin Logout $app->get('/admin/logout', function () use($app) { $twig_vars = $app->config('twigVars'); $config = $twig_vars['config']; unset($_SESSION['user']); unset($_SESSION['pass']);
$product_id = $issue['PRODUCT_ID']; // Default to not allow download. $allow_download = false; // Validate that the Product ID (from Issue Name) is an available download for given user if ($product_id) { // Allow download if the issue is marked as purchased $result = $db->query("SELECT COUNT(*) FROM PURCHASES \n\t\t\t\t\t\t\t\t\t\t\t\t\tWHERE APP_ID = '{$app_id}' AND USER_ID = '{$user_id}' AND PRODUCT_ID = '{$product_id}'"); $allow_download = $result->fetchColumn() > 0; } else { if ($issue['PRICING'] == 'free') { // Issue is marked as free, allow download $allow_download = true; } } if ($allow_download) { if (isInDevelopmentMode($app_id) == "TRUE" && !$app->request()->isHead()) { logMessage(LogType::Info, "Downloading ISSUE: " . $name . " for APP ID: " . $app_id . " USER ID: " . $user_id); } logAnalyticMetric(AnalyticType::ApiInteraction, 1, NULL, $app_id, $user_id); if (!$app->request()->isHead()) { logAnalyticMetric(AnalyticType::Download, 1, $name, $app_id, $user_id); } // Redirect to the downloadable file, nothing else needed in API call $app->response()->redirect($issue['URL'], 303); } else { header('HTTP/1.1 403 Forbidden'); die; } } catch (PDOException $e) { // Handle exception logMessage(LogType::Error, $e->getMessage());
/** * kort - the /db webservices */ /** Load Slim library */ require_once '../../../lib/Slim-2.1.0/Slim/Slim.php'; /** Load ClassLoader */ require_once '../../../server/php/ClassLoader.php'; // Load Slim library \Slim\Slim::registerAutoloader(); Kort\ClassLoader::registerAutoLoader(); $app = new \Slim\Slim(); $dbHandler = new \Webservice\Database\DbHandler(); // define REST resources $app->get('/:table(/:fields)', function ($table, $fields = null) use($dbHandler, $app) { if (!$dbHandler->checkAuth($app->request()->params('key'))) { $app->response()->status(403); } else { $fields = isset($fields) ? explode(",", $fields) : array("*"); $where = $app->request()->params('where'); $orderBy = $app->request()->params('orderby'); $limit = $app->request()->params('limit'); $app->response()->write($dbHandler->doSelect($fields, $table, $where, $orderBy, $limit)); } }); $app->post('/:table/:fields', function ($table, $fields) use($dbHandler, $app) { $request = $app->request(); if (!$dbHandler->checkAuth($request->params('key'))) { $app->response()->status(403); return; }
require_once '../service/ContraMedidaService.php'; require_once '../model/ContraMedida.php'; require_once '../Slim/Slim/Slim.php'; \Slim\Slim::registerAutoloader(); $app = new \Slim\Slim(); $contraMedidaService = new ContraMedidaService(); $app->get("/", function () { echo "<h1>Hello World</h1>"; }); $app->get("/contraMedida/getall", function () use($app, $contraMedidaService) { echo '{"contraMedidas": ' . json_encode($contraMedidaService->buscarContraMedidas()) . '}'; }); $app->get("/contraMedida/:id", function ($id) use($app, $contraMedidaService) { echo json_encode($contraMedidaService->buscarContraMedida($id)); }); $app->post("/contraMedida/cadastrar", function () use($app, $contraMedidaService) { $app->response()->header("Content-Type", "application/json"); $resultado = json_decode($app->request()->getBody()); echo json_encode($contraMedidaService->cadastrarContraMedida($resultado->nomeContraMedida)); }); $app->put("/contraMedida/atualizar", function ($id) use($app, $contraMedidaService) { $app->response()->header("Content-Type", "application/json"); $resultado = json_decode($app->request()->getBody()); echo json_encode($contraMedidaService->atualizarContraMedida($resultado->idContraMedida, $resultado->nomeContramedida)); }); $app->delete("/contraMedida/remover/:id", function ($id) use($app, $contraMedidaService) { $app->response()->header("Content-Type", "application/json"); $resultado = json_decode($app->request()->getBody()); echo json_encode($contraMedidaService->removerContraMedida($id)); }); $app->run();
<?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()); }
$oBlogMgr = new BlogMgr(); $oApp = new \Slim\Slim(array('templates.path' => __DIR__ . '/../views')); date_default_timezone_set('Canada/Saskatchewan'); $oApp->add(new \Slim\Middleware\SessionCookie(array('expires' => '60 minutes', 'path' => '/', 'domain' => null, 'secure' => false, 'httponly' => false, 'name' => 'slim_session', 'secret' => 'CHANGE_ME', 'cipher' => MCRYPT_RIJNDAEL_256, 'cipher_mode' => MCRYPT_MODE_CBC))); /*** * Home page ***/ $oApp->get('/', function () use($oApp, $oProductMgr) { $oApp->render('home.phtml', array('title' => '', 'userType' => getUserType(), 'genreAll' => $oProductMgr->getGenre(), 'genreSelected' => 'Action', 'productsInGenre' => $oProductMgr->getProductsByGenre('Action'), 'featuredProducts' => $oProductMgr->getFeaturedProducts())); }); $oApp->get('/home/:genre', function ($sGenre) use($oApp, $oProductMgr) { $oApp->render('home.phtml', array('title' => $sGenre, 'userType' => getUserType(), 'genreAll' => $oProductMgr->getGenre(), 'genreSelected' => $sGenre, 'productsInGenre' => $oProductMgr->getProductsByGenre($sGenre), 'featuredProducts' => $oProductMgr->getFeaturedProducts())); }); // called when user search for items $oApp->post('/search', function () use($oApp, $oProductMgr) { $sKeywords = $oApp->request()->post('keywords'); $oApp->render('searchResult.phtml', array('title' => $sKeywords, 'userType' => getUserType(), 'products' => $oProductMgr->getProductByKeywords($sKeywords), 'keywords' => $sKeywords)); }); $oApp->get('/search', function () use($oApp, $oProductMgr) { $sKeywords = $oApp->request->params('keywords'); //ChromePhp::info($sKeywords); //die(); $oApp->render('searchResult.phtml', array('title' => $sKeywords, 'userType' => getUserType(), 'products' => $oProductMgr->getProductByKeywords($sKeywords), 'keywords' => $sKeywords)); }); /*** * Product page ***/ $oApp->get('/product/:productId', function ($nProductId) use($oApp, $oProductMgr) { if (isset($_SESSION['cart'][$nProductId])) { $numInCart = $_SESSION['cart'][$nProductId]; } else {
require_once 'NotORM.php'; $connection = new PDO('mysql:dbname=homig7y7_main;host=localhost', 'homig7y7_main', 'homigo10450'); $db = new NotORM($connection); require 'Slim/Slim.php'; \Slim\Slim::registerAutoloader(); $app = new \Slim\Slim(); session_start(); $authenticate = function ($app) { return function () use($app) { if (!isset($_SESSION['user'])) { $app->redirect('/login'); } }; }; $app->post("/auth/process/admin", function () use($app, $db) { $array = (array) json_decode($app->request()->getBody()); $email = $array['email']; $password = $array['password']; $person = $db->admin()->where('email', $email)->where('password', $password); $count = count($person); if ($count == 1) { $_SESSION['admin'] = $email; $data = array('login_success' => "true", 'login_attempt_by' => $email, 'message' => "Successfull sigin"); } else { $data = array('login_success' => "false", 'login_attempt_by' => $email, 'message' => "please provide correct details"); } $app->response()->header('Content-Type', 'application/json'); echo json_encode($data); }); $app->get('/auth/process/admin', function () use($app) { if (isset($_SESSION['admin'])) {
$courseController->obtener_clase($id); }); $app->get('/checkname/:name', function ($name) use($app, $db) { //Verificar si existe un curso con nombre "name" $courseController = new \Controllers\Cursos($app, $db); $courseController->checkname($name); }); $app->get('/buscar/:usuario_id/:name', function ($usuario_id, $name) use($app, $db) { //busqueda de un curso por nombre $courseController = new \Controllers\Cursos($app, $db); $courseController->buscar($usuario_id, $name); }); $app->post('/alta', function () use($app, $db) { //dar de alta un nuevo curso try { $request = $app->request(); $courseController = new \Controllers\Cursos($app, $db); $courseController->crearCurso($request->post('nombre'), $request->post('descripcion'), $request->post('horarios'), $request->post('usuario_id')); } catch (Exception $e) { $app->response()->status(400); $app->response()->header('X-Status-Reason', $e->getMessage()); } }); $app->post('/generar_clase/', function () use($app, $db) { //generar una clase para un curso try { $request = $app->request(); $courseController = new \Controllers\Cursos($app, $db); $courseController->generarClase($request->post('curso_id')); } catch (Exception $e) { $app->response()->status(400);
<?php use Shopware\Recovery\Common\Utils; $app = new \Slim\Slim(array('templates.path' => __DIR__ . '/../templates', 'debug' => false)); $app->contentType('text/html; charset=utf-8'); if (!isset($_SESSION)) { $sessionPath = str_replace('index.php', '', $app->request()->getScriptName()); session_cache_limiter(false); session_set_cookie_params(600, $sessionPath); session_start(); } if (!isset($_SESSION["parameters"])) { $_SESSION["parameters"] = array(); } /** * Load language file */ $allowedLanguages = array("de", "en"); $selectedLanguage = "de"; if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { $selectedLanguage = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']); $selectedLanguage = substr($selectedLanguage[0], 0, 2); } if (empty($selectedLanguage) || !in_array($selectedLanguage, $allowedLanguages)) { $selectedLanguage = "de"; } if (isset($_POST["language"]) && in_array($_POST["language"], $allowedLanguages)) { $selectedLanguage = $_POST["language"]; unset($_SESSION["parameters"]["c_config_shop_language"]); unset($_SESSION["parameters"]["c_config_shop_currency"]); unset($_SESSION["parameters"]["c_config_admin_language"]);
<?php include_once dirname(__FILE__) . '/lib/Slim/Slim/Slim.php'; include_once dirname(__FILE__) . '/config.php'; \Slim\Slim::registerAutoloader(); $app = new \Slim\Slim(); function debug($msg) { if (is_string($msg)) { file_put_contents(dirname(__FILE__) . '/log/pfc.log', $msg . "\n", FILE_APPEND); } else { file_put_contents(dirname(__FILE__) . '/log/pfc.log', print_r($msg, true), FILE_APPEND); } } $req = $app->request(); $res = $app->response(); $res['X-Powered-By'] = 'phpfreechat-' . $GLOBALS['pfc_version']; // connect custom user hooks foreach ($GLOBALS['pfc_hooks'] as $hook_name => $hooks) { foreach ($hooks as $priority => $function) { $GLOBALS['pfc_hooks'][$hook_name][$priority] = $function($app, $req, $res); } } require 'routes/auth.php'; require 'routes/channels.php'; require 'routes/users.php'; $app->run();
} } // echo json response echoRespnse(201, $response); }); /** * User Login * url - /login * method - POST * params - email, password */ $app->post('/login', function () use($app) { // check for required params verifyRequiredParams(array('email', 'password')); // reading post params $email = $app->request()->post('email'); $password = $app->request()->post('password'); $response = array(); $db = new DbHandler(); // check for correct email and password if ($db->checkLogin($email, $password)) { // get the user by email $user = $db->getUserByEmail($email); if ($user != NULL) { $response["error"] = false; $response['name'] = $user['name']; $response['email'] = $user['email']; $response['apiKey'] = $user['api_key']; $response['createdAt'] = $user['created_at']; $_SESSION['user'] = $user['email']; $_SESSION['token'] = $user['api_key'];