public function loginAction(Request $request, Application $app) { $username = $app->escape($request->get('username')); $password = $app->escape($request->get('password')); $rememberMe = $app->escape($request->get('rememberMe')); if (!$username || !$password) { $app->abort(Response::HTTP_BAD_REQUEST, 'Missing parameters'); } $user = $app['repository.user']->findByUsername($username); if (!$user) { $app->abort(Response::HTTP_NOT_FOUND, 'User not found'); } if (password_verify($password, $user->getPassword())) { $user->setLastSeen(new \DateTime('now')); $user->setLastIP($request->headers->get('referer')); $user->setFailedLogins(0); $app['repository.user']->save($user); //$access_query = 'SELECT user_level FROM users_access WHERE user_id = ' . $account['id']; //$access = $app['db']->fetchAssoc($access_query); $permissions = []; //foreach ($access as $accessLevel) { // array_push($permissions, $app['api.accessLevels'][$accessLevel]); //} $exp = $rememberMe ? time() + 60 * 60 * 24 * 30 : time() + 60 * 60 * 24; // expire in 30 days or 24h $user = ['id' => $user->getId(), 'username' => $user->getUsername(), 'permissions' => $permissions, 'rememberMe' => $rememberMe]; $token = $app['jwt']->createToken($request, $exp, $user); } else { $user->setFailedLogins($user->getFailedLogins() + 1); $app['repository.user']->save($user); $app->abort(Response::HTTP_FORBIDDEN, 'Wrong password'); } return json_encode(['token' => $token], JSON_NUMERIC_CHECK); }
/** * @param string $username * @param string $password * @return User|null */ public function tryLogin($username, $password) { $salt = $this->app["salt"]; $saltedPass = md5($salt . md5($this->app->escape($password))); $username = $this->app->escape($username); $query = "select\n u.userid,\n u.name,\n u.fullname,\n u.email\n from\n user u\n WHERE\n (\n lower(u.name) = ? or\n lower(u.fullname) = ? or\n lower(u.email) = ?\n ) and\n u.password = ?"; $result = $this->app['db']->fetchAssoc($query, [$username, $username, $username, $saltedPass]); if ($result !== false) { return new User($result['userid'], $result['name'], $result['fullname'], $result['email']); } return null; }
/** * Tweet Detail * @param Application $app An Application instance * @param int $id ID of the tweet (URL Param) * @return string A blob of HTML */ public function detail(Application $app, $id) { // Make sure the given tweet id exists if (!in_array($id, array_column($this->data, 'id'))) { $app->abort(404, "Tweet {$id} does not exist"); } // Extract the tweet by filtering the tweets array based on the value of the id key $tweets = array_filter($this->data, function ($tweet) use($id) { return $tweet['id'] == $id; }); $tweet = array_pop($tweets); // Build and return the HTML representing the tweet $output = '<p>On ' . $tweet['created_at'] . ' ' . $app->escape($tweet['author']) . ' tweeted:</p><blockquote>' . $app->escape($tweet['text']) . '</blockquote><p><a href="' . $app['request']->getBaseUrl() . '/tweets">← Back to overview</a></p>'; return $output; }
/** * Создает новую новость * * @param object $app Silex\Application * @param object $req Symfony\Component\HttpFoundation\Request * @return object Symfony\Component\HttpFoundation\JsonResponse * */ public function createNewPostAction(Application $app, Request $req) { $model = new PostModel(); $model->title = $app->escape($req->get('title')); $model->img = $app->escape($req->get('img')); $model->description = $app->escape($req->get('description')); $model->url = UrlService::makeUrlFromSting($model->title); $model->text = $app->escape($req->get('text')); if ($model->isValid($app['validator'])) { if ($model->save()) { return new JsonResponse(['success' => true, 'message' => 'Новость успешно добавлена!'], JsonResponse::HTTP_CREATED); } } return new JsonResponse(['success' => false, 'message' => $model->getError()], JsonResponse::HTTP_OK); }
public function detail(Application $app, $id) { $link = $app['db.links']->find($id); if (!$link) { $app->abort(404, 'The requested link (id #' . $app->escape($id) . ') does not exist'); } return $app->redirect($link['url']); }
public function register(Application $app) { $app['hello'] = $app->protect(function ($name) use($app) { $default = 'SilexBase'; $name = $name ? $name : $default; return 'Hello ' . $app->escape($name); }); }
public function detail(Application $app, $id) { $link = $app['db']->fetchAssoc('SELECT * FROM links WHERE id = ?', array($id)); if (!$link) { $app->abort(404, 'The requested link (id #' . $app->escape($id) . ') does not exist'); } return $app->redirect($link['url']); }
public function links(Application $app, $id) { $user = $app['db.users']->find($id); if (!$user) { $app->abort(404, 'The requested user (id #' . $app->escape($id) . ') does not exist'); } $links = $app['db.users']->getLinks($id); return $app['twig']->render('users/links.twig', array('user' => $user, 'links' => $links)); }
public function links(Application $app, $id) { $user = $app['db']->fetchAssoc('SELECT * FROM users WHERE id = ?', array($id)); if (!$user) { $app->abort(404, 'The requested user (id #' . $app->escape($id) . ') does not exist'); } $links = $app['db']->fetchAll('SELECT * FROM links WHERE added_by = ?', array($id)); return $app['twig']->render('users/links.twig', array('user' => $user, 'links' => $links)); }
/** * Authenticats the user * @param Request Object - contains email and password * * @return Nothing */ public function authenticate(Application $app, Request $request) { $email = $request->get('email'); $password = $app->escape($request->get('password')); if ($email && $password) { $user = new User($app); $user_info = $user->find('user', array('email' => $email, 'password' => md5($password))); if ($user_info) { $app['session']->set('user', array('id' => $user_info[0])); return $app->redirect($request->getBaseUrl() . '/message/tweets'); } else { return $app->render('index.php.twig', array('error_message' => "Invalid Credentials. Please try again!")); } } else { return $app->render('index.php.twig', array('error_message' => "Valid Email and password are required!")); } }
<?php require_once "./vendor/.composer/autoload.php"; use Silex\Application; use Symfony\Component\HttpFoundation\Response; error_reporting(E_ALL); ini_set("display_errors", 1); $app = new Application(); $app->register(new Silex\Provider\TwigServiceProvider(), array('twig.path' => __DIR__ . '/views', 'twig.class_path' => __DIR__ . '/vendor/twig/lib')); $app->get('/page/{slug}', function (Application $app, $slug) { $template_name = 'pages/' . $app->escape($slug) . '.twig'; if (file_exists(__DIR__ . '/views/' . $template_name)) { return $app['twig']->render($template_name, array('slug' => $slug)); } else { $message = "Template " . $app->escape($slug) . " not exists"; return new Symfony\Component\HttpFoundation\Response($message, 404); } }); $app->get('/', function (Application $app) { //echo ($app['request']->getBaseUrl()); $template_name = "index.twig"; return $app['twig']->render($template_name, array()); }); $app->error(function (\Exception $e, $code) use($app) { switch ($code) { case 404: $message = 'The requested page could not be found.'; $template_name = "errors/404.twig"; return $app['twig']->render($template_name, array()); break; default:
$response['DateStart'] = $dateStart; $response['DateEnd'] = $dateEnd; $response['Reports'] = $reports; $response['SearchText'] = $searchText; $response['Years'] = $years; // Conversion de la réponse en JSON et retour return $app->json($response); }); /***************************************************************************************** * * * Transfert des documents pdf pour tracer leur telechargement. * * * *****************************************************************************************/ $app->get('/files/{path}', function ($path) use($app) { if (!file_exists(__DIR__ . '/reports/' . $path)) { $app->abort(404, "Le fichier " . $app->escape($path) . " n'existe pas."); } return $app->sendFile(__DIR__ . '/reports/' . $path); }); /***************************************************************************************** * * * Page des mentions légales * * * *****************************************************************************************/ $app->get('/mentions-legales', function () use($app) { return $app['twig']->render('mentions.twig', array('layout_template' => 'layout.twig')); })->bind('mentions'); /***************************************************************************************** * * * Page des crédits * * *
public function barAction(Application $app, $name) { return 'Hello ' . $app->escape($name); }
<?php // Constants define('__ROOT', __DIR__); define('DS', DIRECTORY_SEPARATOR); require_once __ROOT . DS . 'vendor' . DS . 'autoload.php'; use Silex\Application; $app = new Application(); // Please set to false in a production environment $app['debug'] = true; $app->get('/{bar}', function ($bar) use($app) { return 'Foo - ' . $app->escape($bar); })->value('bar', 'something'); $app->run();
ob_end_clean(); return $out; } } /* $location = new Location(); $locations = Location::all(); */ // Suppress some libxml DOMDocument errors that aren't helpful. libxml_use_internal_errors(true); // ... definitions $app->get('/vacation/', function (App $app) { $locations = Location::all(); $l = ''; foreach ($locations as $loc) { $l .= '<li><a href="/vacation/' . $app->escape($loc->area) . '/' . $app->escape($loc->slug) . '/">' . $app->escape($loc->title) . '</a></li> '; } return Page::display('Destinations found: <ul>' . $l . '</ul>'); }); // ... definitions $app->get('/vacation/{cont}/', function (App $app, $cont) { $locs = Location::where('area', $cont)->get(); $l = 'Destinations in this area: '; foreach ($locs as $loc) { $l .= '<li><a href="/vacation/' . $app->escape($loc->area) . '/' . $app->escape($loc->slug) . '/">' . $app->escape($loc->title) . '</a></li> '; } return Page::display('Destinations in this area: <ul>' . $l . '</ul> '); }); // ... definitions $app->get('/vacation/{cont}/{slug}/', function (App $app, $cont, $slug) { $loc = Location::where('slug', $slug)->where('area', $cont)->first();
<?php use Silex\Application; use Symfony\Component\HttpFoundation\Cookie; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; require_once __DIR__ . '/../vendor/autoload.php'; $app = new Application(); $app->get('/hello/', function (Request $request) use($app) { $name = $app->escape($request->get('name')); $response = new Response(sprintf('Hello, %s!', $name)); $response->headers->setCookie(new Cookie('silex_test', $name)); $response->headers->setCookie(new Cookie('silex_time', time())); return $response; }); $app->get('/stream/', function () { return new \Symfony\Component\HttpFoundation\StreamedResponse(function () { for ($i = 5; $i !== 0; --$i) { echo 'countdown... ' . $i . '<br>'; sleep(1); } }); }); $app->get('/favicon.ico', function () use($app) { $filepath = __DIR__ . '/favicon.ico'; return new Response(file_get_contents($filepath), 200, ['content-type' => mime_content_type($filepath)]); }); return $app;
throw new RuntimeException('File with parameters not found!'); } //require_once __DIR__.'/../src/Controller/PostController.php'; use Silex\Application as App; $app = new App(); $app['debug'] = true; // Service Providers $app->register(new Silex\Provider\ServiceControllerServiceProvider()); $app->register(new Silex\Provider\DoctrineServiceProvider(), array('db.options' => $parameters['db'])); $app->register(new Silex\Provider\TwigServiceProvider(), array('twig.path' => $parameters['twig']['path'])); $app->register(new Silex\Provider\UrlGeneratorServiceProvider()); // Services $app['post.controller'] = $app->share(function () use($app) { return new \Controller\PostController($app); }); $app['admin.post.controller'] = $app->share(function () use($app) { return new \Controller\Admin\PostController($app); }); // Routes $app->get('/', function () use($app) { return 'Welcome!'; }); $app->get('/hello/{userName}', function ($userName) use($app) { return 'Hello ' . $app->escape($userName); }); $app->get('/blog', 'post.controller:indexAction')->bind('post_index'); $app->get('/blog/{id}', 'post.controller:showAction')->bind('post_show')->method('GET')->assert('id', '[0-9]+'); $app->get('/admin/blog', 'admin.post.controller:indexAction')->bind('admin_post_index'); $app->get('/admin/blog/new', 'admin.post.controller:newAction')->bind('admin_post_new')->method('GET|POST'); $app->get('/admin/blog/edit/{id}', 'admin.post.controller:editAction')->bind('admin_post_edit')->method('GET|POST')->assert('id', '[0-9]+'); $app->run();