}); $app->get('/maria', function () use($app) { global $twig; echo $twig->render('contacto.php'); }); $app->post('/guardarParte', function () use($app) { global $twig; // Recogemos datos formulario de contacto $valores = array('alumnoaImplicado' => $app->request()->post('alumnoaImplicado'), 'cursoygrupo' => $app->request()->post('cursoygrupo'), 'fecha' => $app->request()->post('fecha6'), 'hora' => $app->request()->post('hora'), 'asignatura' => $app->request()->post('asignatura')); // Guardamos en la BD $sql = "INSERT INTO contacto (alumnoaImplicado, cursoygrupo, fecha,hora,asignatura) VALUES (:alumnoaImplicado, :cursoygrupo, :fecha,:hora,:asignatura)"; $pdo = $app->db; $q = $pdo->prepare($sql); $q->execute($valores); // Mostramos un mensaje al usuario echo $app->redirect('/'); }); $app->group('/usuario', function () use($app) { // Acción asociada al formulario de login $app->get('/login', 'Login::forzarLogin', function () use($app) { }); // Cierra la sesión de usuario $app->get('/logout', function () use($app) { global $twig; unset($_SESSION['user']); session_destroy(); echo $twig->render('inicio.php'); }); // Accion asociada al email de login $app->get('/autenticar/:token', function ($token) use($app) { $email = $app->request->get('email');
<?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()) {
$oApp->get('/product/:productId', function ($nProductId) use($oApp, $oProductMgr) { if (isset($_SESSION['cart'][$nProductId])) { $numInCart = $_SESSION['cart'][$nProductId]; } else { $numInCart = 0; } $oApp->render('product.phtml', array('title' => $oProductMgr->getProductNameById($nProductId), 'userType' => getUserType(), 'product' => $oProductMgr->getProductById($nProductId), 'reviews' => $oProductMgr->getReviews($nProductId), 'relatedProducts' => $oProductMgr->getRelatedProducts($nProductId), 'numInCart' => $numInCart)); }); // called when user posts review $oApp->post('/product/:productId', function ($nProductId) use($oApp, $oProductMgr) { $req = $oApp->request(); $nStar = $req->post('review_star'); $sComment = $req->post('review_comment'); $sWriter = $req->post('review_writer'); $oProductMgr->setReview($nProductId, $nStar, $sComment, $sWriter); $oApp->redirect('/product/' . $nProductId); }); // called when user click 'Add to cart' $oApp->post('/addCart', function () use($oApp, $oProductMgr) { $req = $oApp->request(); $nProductId = $req->post('productId'); if (isset($_SESSION['cart'][$nProductId])) { $_SESSION['cart'][$nProductId] += 1; } else { $_SESSION['cart'][$nProductId] = 1; } $oApp->redirect('/product/' . $nProductId); }); /*** * Cart/Order sheet ***/
$app->hook('slim.before.router', function () use($app) { $env = $app->environment(); $env['ulogovan'] = is_ulogovan($app->request->params('session')); }); function is_android() { global $app; return stristr($app->request->headers->get('USER_AGENT'), 'Android') != false ? true : false; } $acl_map = array(500 => 'admin', 501 => 'editor', 502 => 'chat', 503 => 'user', 'admin' => 500, 'editor' => 501, 'chat' => 502, 'user' => 503); $login = function ($rola = 'user') { global $app, $acl_map; $env = $app->environment(); return function () use($app, $rola, $env, $acl_map) { if (!$env['ulogovan']['status']) { $app->redirect('/login/'); } else { if (intval($env['ulogovan']['korisnik']->getRola()) > $acl_map[$rola]) { // @TODO rediraktati na stranicu koja kaze da autorizacija nije dovoljna $app->redirect('/login/'); } } }; }; // @TODO obrisati u prod $app->get('/info/', function () { echo phpinfo(); }); $app->get('/', function () use($app, $twig, $urls, $em) { $env = $app->environment(); $m = $em->getRepository('Medium')->findAll();
}); // Cuando accedamos a /nuevousuario se mostrará un formulario de alta. $app->get('/nuevousuario', function () use($app) { $app->render('nuevousuario.php'); })->name('altausuarios'); // Ruta que recibe los datos del formulario $app->post('/nuevousuario', function () use($app, $db) { // Para acceder a los datos recibidos del formulario $datosform = $app->request; // Los datos serán accesibles de esta forma: // $datosform->post('apellidos') // Preparamos la consulta de insert. $consulta = $db->prepare("insert into soporte_usuarios(idusuario,nombre,apellidos,email)\n\t\t\t\tvalues (:idusuario,:nombre,:apellidos,:email)"); $estado = $consulta->execute(array(':idusuario' => $datosform->post('idusuario'), ':nombre' => $datosform->post('nombre'), ':apellidos' => $datosform->post('apellidos'), ':email' => $datosform->post('email'))); if ($estado) { $app->flash('message', 'Usuario insertado correctamente.'); } else { $app->flash('error', 'Se ha producido un error al guardar datos.'); } // Redireccionamos al formulario original para mostrar // los mensajes Flash., $app->redirect('nuevousuario'); // Otra forma de hacerlo es: // $app->redirect($app->urlFor('altausuarios')); }); // Otro ejemplo de aplicación en: // http://coenraets.org/blog/2011/12/restful-services-with-jquery-php-and-the-slim-framework/ /////////////////////////////////////////////////////////////////////////////////////////////////////// // Al final de la aplicación terminamos con $app->run(); /////////////////////////////////////////////////////////////////////////////////////////////////////// $app->run();
db_execute($query, array($user_id, current_user()['id'])); } } function prefectures() { static $PREFS = array('未入力', '北海道', '青森県', '岩手県', '宮城県', '秋田県', '山形県', '福島県', '茨城県', '栃木県', '群馬県', '埼玉県', '千葉県', '東京都', '神奈川県', '新潟県', '富山県', '石川県', '福井県', '山梨県', '長野県', '岐阜県', '静岡県', '愛知県', '三重県', '滋賀県', '京都府', '大阪府', '兵庫県', '奈良県', '和歌山県', '鳥取県', '島根県', '岡山県', '広島県', '山口県', '徳島県', '香川県', '愛媛県', '高知県', '福岡県', '佐賀県', '長崎県', '熊本県', '大分県', '宮崎県', '鹿児島県', '沖縄県'); return $PREFS; } $app->get('/login', function () use($app) { $app->view->setLayout(null); $app->render('login.php', array('message' => '高負荷に耐えられるSNSコミュニティサイトへようこそ!')); }); $app->post('/login', function () use($app) { $params = $app->request->params(); authenticate($params['email'], $params['password']); $app->redirect('/'); }); $app->get('/logout', function () use($app) { $_SESSION['user_id'] = null; $app->redirect('/login'); }); $app->get('/', function () use($app) { authenticated(); $profile = db_execute('SELECT * FROM profiles WHERE user_id = ?', array(current_user()['id']))->fetch(); $entries_query = 'SELECT * FROM entries WHERE user_id = ? ORDER BY created_at LIMIT 5'; $stmt = db_execute($entries_query, array(current_user()['id'])); $entries = array(); while ($entry = $stmt->fetch()) { $entry['is_private'] = $entry['private'] == 1; list($title, $content) = preg_split('/\\n/', $entry['body'], 2); $entry['title'] = $title;
$app->get('/contact', function () use($app) { $app->render('contact.twig'); //starts by looking through templates folder })->name('contact'); $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)) { $cleanName = filter_var($name, FILTER_SANITIZE_STRING); $cleanEmail = filter_var($email, FILTER_SANITIZE_EMAIL); $cleanMsg = filter_var($msg, FILTER_SANITIZE_STRING); } else { //message the user that there's a problem $app->flash('fail', 'All fields are required.'); $app->redirect('/contact'); } $transport = Swift_SendmailTransport::newInstance('/usr/sbin/sendmail -t'); $mailer = \Swift_Mailer::newInstance($transport); $message = \Swift_Message::newInstance(); $message->setSubject('Email From Our Website'); //http://swiftmailer.org/docs/messages.html $message->setFrom(array($cleanEmail => $cleanName)); //if server accepts this email $message->setTo(array('*****@*****.**')); $message->setBody($cleanMsg); $result = $mailer->send($message); if ($result > 0) { $app->flash('success', 'Thank You! You da best!'); $app->redirect("/"); } else {
} var_dump($files); }); //#################################################### USER REGISTER/LOGIN #################################################### $app->get("/auth", function () use($app, $util, $twig) { $req = $app->request(); if (isset($_SESSION["user"])) { $url = urldecode($url); $data = array("menu" => "login", "pageTitle" => "Login", "backUrl" => $url); $app->render("front/user/login.twig", $data); } }); //#################################################### PROCESSOR #################################################### $app->get("/user/logout", function () use($app, $util) { unset($_SESSION["user"]); $app->redirect("/" . $app->request->getRootUri()); }); $app->get("/user/login/twitter/proc/backurl/:url", function ($url) use($app, $util) { $twitteroauth = new TwitterOAuth("KEY", "SECRET"); // Requesting authentication tokens, the parameter is the URL we will be redirected to $request_token = $twitteroauth->getRequestToken("CALLBACKURL?url=" . urlencode($url)); // Saving them into the session $_SESSION["oauth_token"] = $request_token["oauth_token"]; $_SESSION["oauth_token_secret"] = $request_token["oauth_token_secret"]; // If everything goes well.. if ($twitteroauth->http_code == 200) { // Let's generate the URL and redirect $turl = $twitteroauth->getAuthorizeURL($request_token["oauth_token"]); //var_dump($request_token, $twitteroauth, $turl); //exit(); $app->redirect($turl);
$installer->init('0.2'); //Render header and body start. $app->render('head.phtml'); $app->render('top.phtml'); //Root route $app->get('/', function () use($database, $app) { $app->render('logo.phtml'); $posts = $database->select('posts', '*', ['ORDER' => 'id DESC']); // $app->render('static.phtml'); if ($posts) { foreach ($posts as $post) { $app->render('banner.phtml', ['id' => $post['id'], 'title' => $post['title'], 'language' => $post['language'], 'content' => $post['content'], 'time' => $post['time_posted']]); } return true; } $app->redirect('page/fourohfour', 404); }); //Specific post, either by ID or SEO url. $app->get('/:id', function ($id) use($database, $app) { $app->render('logo.phtml'); if ((int) $id !== 0) { $post = $database->select('posts', '*', ['id[=]' => (int) $id]); } else { $post = $database->select('posts', '*', ['urlkey[=]' => $id]); } if ($post) { $post = $post[0]; $app->render('post.phtml', ['title' => $post['title'], 'language' => $post['language'], 'content' => $post['content'], 'time' => $post['time_posted']]); $app->render('back.phtml'); return true; }
$content = reset($layout->featured); $layout->title = $content->title; $layout->description = $content->description; $layout->keywords = $content->getKeywords(); $layout->author = $content->author; $layout->main_image = $content->image->getUrl(); } // Output layout $app->response()->body((string) $layout); }); /* * Change idiom */ $app->get('/idiom/:idiom', function ($idiom) use($app) { BootWiki::setIdiom($idiom); $app->redirect(BASEURL); }); /* * Display search results */ $app->get('/search', function () use($app) { // load query $q = $app->request()->get('q'); // Process results $main = new Results(); $main->find($q); // Load layout $layout = new Layout($main); $layout->loadRecent(); $layout->loadPopular(); $layout->query = $q;
<?php require '../lib/Slim/Slim.php'; require '../lib/facebook/src/facebook.php'; \Slim\Slim::registerAutoloader(); $app = new \Slim\Slim(); $app->config(array('debug' => true, 'templates.path' => './templates')); $facebook = new Facebook(array('appId' => '426557000803058', 'secret' => 'e2119d478b1d693d17d6bb741b9333fe')); $app->get('/facebook', function () use($app) { $app->redirect('/GSP/internal/examples/php/php-slim-framework/public/facebook/login'); }); $app->get('/facebook/channel', function () use($app) { $cache_expire = 60 * 60 * 24 * 365; header("Pragma: public"); header("Cache-Control: max-age=" . $cache_expire); header('Expires: ' . gmdate('D, d M Y H:i:s', time() + $cache_expire) . ' GMT'); $app->render('channel.html'); }); $app->get('/facebook/login', function () use($app, $facebook) { $app->render('login.html'); }); $app->get('/facebook/logged/in', function () use($app, $facebook) { // Get User ID $user = $facebook->getUser(); if ($user) { try { $user_profile = $facebook->api('/me'); $app->render('index.php', array('user' => $user, 'user_profile' => $user_profile)); } catch (FacebookApiException $e) { $user = ''; $app->render('index.php', array('error' => $e));
//BASE 64 IMAGE UPLOAD require_once 'func/security_csrf.php'; //SECURITY 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');
<?php require_once 'NotORM.php'; $pdo = new PDO('mysql:dbname=tourepedia;host=localhost', 'root', ''); $db = new NotORM($pdo); require 'Slim/Slim.php'; \Slim\Slim::registerAutoloader(); $app = new \Slim\Slim(); /********************************** USER LOGIN SIGNUP CHECKING ******************************/ $authenticate = function ($app) { return function () use($app) { if (!isset($_SESSION['user'])) { $app->redirect('/login.html'); } }; }; session_start(); $app->post("/auth/process", function () use($app, $db) { $array = (array) json_decode($app->request()->getBody()); // print_r($array); $email = $array['email']; $pwd = md5($array['pwd']); $user = $db->users()->where('user_email', $email)->where('user_password', $pwd); $count = count($user); if ($count == 1) { $_SESSION['user'] = $email; $data = array("loginStatus" => "success", 'userEmail' => $email); } else { $data = array("loginStatus" => "login failure"); } $app->response()->header('Content-Type', 'application/json');
$app->get("/", function () use($app, $bd) { $solicitud = $app->request(); $consultaResultante = $bd->prepare("SELECT ip FROM bloqueoip WHERE ip='" . $solicitud->getIp() . "'"); $consultaResultante->execute(); if ($consultaResultante->rowCount() > 0) { echo "La ip a sido bloqueada"; $app->stop(); } $app->render("principal.php", array("contenidoDinamico" => file_get_contents("vistas/login.php"), "menu" => "")); }); $app->get("/salir", function () use($app, $bd) { $solicitud = $app->request(); guardarBitacora("Sesion terminada: [" . $_SESSION["usuario"] . "]", $solicitud->getIp()); session_unset(); session_destroy(); $app->redirect("/bibliotecaseguridad"); }); $app->get("/inicio", function () use($app, $bd) { if (sesionExapirada()) { $app->redirect("/bibliotecaseguridad/salir"); } if (!empty($_SESSION["fechaPass"])) { $date = date("Ymd", strtotime("+1 month", strtotime($_SESSION["fechaPass"]))); if ($date < date("Ymd")) { echo "<script>alert('Por seguridad, su contraseña a expirado y es necesario que realice el cambio');</script>"; } } $listaIp = ''; $listaUsuario = ''; //$mostrarUsuarioSesion = ""; if ($_SESSION["rol"] == "administrador") {
$history = $fcache->get('hash_history'); if (!$history) { $history = array(); } if (array_key_exists($chars, $history)) { return array_keys($history); } if (count($history) > $max) { $key_del = array_rand($history, 1); unset($history[$key_del]); } $history[$chars] = ''; $fcache->add('hash_history', $history); return array_keys($history); } // GET route $app->get('/', function () use($app) { $chars = 'DigHash'; $random = get_randoms(20); $history = do_history($chars); $app->render('hash.html', array('chars' => $chars, 'hash_rst' => cal_hash($chars), 'random' => $random, 'history' => $history)); }); $app->get('/:chars.html', function ($chars) use($app) { $random = get_randoms(20); $history = do_history($chars); $app->render('hash.html', array('chars' => $chars, 'hash_rst' => cal_hash($chars), 'random' => $random, 'history' => $history)); }); $app->notFound(function () use($app) { $app->redirect('/', 301); }); $app->run();
| Autenticacion de usuarios |-------------------------------------------------------------------------- | | Funcion $authentitace | Recibe: $app, $role | $app: SLIM $app | $role: El role o nivel del usuario | */ $authenticate = function ($app, $role) { return function () use($app, $role) { $env = $app->environment(); if (!isset($_SESSION['user'])) { $_SESSION['urlRedirect'] = $app->request()->getPathInfo(); $app->flash('danger', 'Necesitas iniciar sesion.'); $app->redirect($env['rootUri'] . 'login'); } else { if ($role == 'admin') { if ($_SESSION['role'] != 'admin') { $app->flash('danger', 'Necesitas iniciar sesion como administrador.'); $app->redirect($env['rootUri']); } } } }; }; //crea variable $user y se la agrega a todos los views para facil deteccion de sesiones $app->hook('slim.before.dispatch', function () use($app) { $user = array(); if (isset($_SESSION['user'])) { $user['email'] = $_SESSION['user'];
$twig_vars = lib\SlimCMS::getTwigVars(); $config = $twig_vars['config']; // Setup custom Twig view $twigView = new \Slim\Views\Twig(); $app = new \Slim\Slim(array('debug' => true, 'view' => $twigView, 'templates.path' => "themes/" . $config["theme"] . "/", 'twigVars' => $twig_vars)); $app->view->parserOptions = array('charset' => 'utf-8', 'auto_reload' => true, 'autoescape' => false); $app->view->parserExtensions = array(new \Slim\Views\TwigExtension()); $app->notFound(function () use($app) { $twig_vars = lib\SlimCMS::getTwigVars(); $app->render('404.html.twig', $twig_vars); }); $authenticate = function ($app) { return function () use($app) { if (!isset($_SESSION['user'])) { $app->flash('error', 'Login required'); $app->redirect('/admin'); } }; }; /*********************************************************************************************************************** * ADMIN BLOCK **********************************************************************************************************************/ // Admin $app->get('/admin/', function () use($app) { $twig_vars = $app->config('twigVars'); $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');
// All requests on /users and behind (/users/search etc) are grouped here. Note that $userModel is passed (as some routes // in /songs... use the model) $app->group('/users', function () use($app, $userModel) { // GET request on /songs. Perform actions getAmountOfSongs() and getAllSongs() and pass the result to the view. // Note that $model is passed to the route via "use ($app, $model)". I've written it like that to prevent creating // the model / database connection in routes that does not need the model / db connection. $app->get('/', function () use($app, $userModel) { $users = $userModel->getAllUsers(); $app->render('users.twig', array('users' => $users)); }); // POST request on /users/adduser (after a form submission from /users). Asks for POST data, performs // model-action and passes POST data to it. Redirects the user afterwards to /users. $app->post('/adduser', function () use($app, $userModel) { // in a real-world app it would be useful to validate the values (inside the model) $userModel->addUser($_POST["firstname"], $_POST["lastname"], $_POST["preferredname"], $_POST["month"], $_POST["day"], $_POST["year"], $_POST["phone1"], $_POST["phone2"], $_POST["email1"], $_POST["email2"]); $app->redirect('/users'); }); $app->get('/:user_id', function ($user_id) use($app) { $app->redirect('/users/edituser/' . $user_id); }); // POST request on /songs/deleteuser after a form submission from /users. Asks for POST data // Performs an action on the model and redirects the user to /users. $app->post('/deleteuser', function () use($app, $userModel) { $userModel->deleteUser($_POST["user_id"]); $app->redirect('/users'); }); // GET request on /users/editusers/:user_id. Should be self-explaining. If user id exists show the editing page, // if not redirect the user. Note the short syntax: 'user' => $model->getUser($user_id) $app->get('/edituser/:user_id', function ($user_id) use($app, $userModel) { $user = $userModel->getUser($user_id); if (!$user) {
require "../vendor/autoload.php"; require "../vendor/phpmailer/phpmailer/PHPMailerAutoload.php"; require "../vendor/phpmailer/phpmailer/function.php"; $app = new \Slim\Slim(); $app->config(array('debug' => true, 'templates.path' => '../views')); $db = new PDO("mysql:host=localhost;dbname=projeto", "root", "root"); $app->get('/', function () use($app) { $app->render("index.php"); }); $app->get('/novo/nome', function () use($app, $db) { $app->render('novo.php'); }); $app->post('/', function () use($app, $db) { $request = $app->request; $name = $request->post('name'); $email = $request->post('email'); $site = $request->post('site'); $inquiry = $request->post('inquiry'); if ($name == '' || $email == '' || $site == '' || $inquiry == '') { $app->redirect("index.php"); } else { $dbquery = $db->prepare("INSERT INTO inquiry(name,email,website,inquiry) VALUES(:name,:email,:site,:inquiry)"); $dbquery->execute(array(":name" => $name, ":email" => $email, ":site" => $site, ":inquiry" => $inquiry)); } $app->redirect("index.php"); }); $app->get('/send_email', function () use($app) { send_email(); }); $app->run();
$mongoCollection = getMongoCollection('user'); foreach ($post as $key => $value) { $encode = mb_detect_encoding($value, array('UTF-8')); if ($encode !== 'UTF-8') { throw new RuntimeException('メールアドレスまたはパスワードに誤りがあります'); } } $result = $mongoCollection->find(array('email' => $post['email'], 'password' => getPasswordHash($post['email'], $post['password'], $app->config('salt')))); if ($result->count()) { session_regenerate_id(true); $user = $result->next(); $_SESSION['user'] = $user; $_SESSION['expires'] = time() + (int) $app->config('timeout'); $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->response->status(500); echo json_encode($events["error"]); return; } uasort($events, 'cmp'); $tags = Postmortem::get_tags(); if ($tags["status"] == Postmortem::OK) { $tags = $tags["values"]; } else { $tags = array(); } include 'views/page.php'; }); $app->post('/timezone', function () use($app) { $_SESSION['timezone'] = $app->request->post('timezone'); $app->redirect($app->request()->getReferrer()); }); $app->post('/events', function () use($app) { $title = $app->request->post('title'); $start_date = $app->request->post('start_date'); $start_time = $app->request->post('start_time'); $end_date = $app->request->post('end_date'); $end_time = $app->request->post('end_time'); $detect_date = $app->request->post('detect_date'); $detect_time = $app->request->post('detect_time'); $status_date = $app->request->post('status_date'); $status_time = $app->request->post('status_time'); $timezone = $app->request->post('timezone'); $severity = $app->request->post('severity'); $startdate = new DateTime($start_date . " " . $start_time, new DateTimeZone($timezone)); $enddate = new DateTime($end_date . " " . $end_time, new DateTimeZone($timezone));
function auth(Slim\Slim $app) { if (!Session::isAuthenticated()) { $app->redirect(createUrl('/login/')); } }
$school->save(); $data['new_school'] = $school->toArray(); } } $app->render('schools/edit.html', $data); })->via('GET', 'POST')->name('schools_edit'); }); $app->map('/login', function () use($app) { $data = array(); if ($app->request->isPost()) { $auth = wp_authenticate_username_password(NULL, $app->request->post('username'), $app->request->post('password')); if (is_wp_error($auth)) { $data['error'] = 'Gebruikersnaam of wachtwoord is fout'; } else { $_SESSION['loggedin'] = true; $app->redirect($app->urlFor('dashboard')); } } $app->render('login.html', $data); })->via('GET', 'POST')->name('login'); $app->get('/logout', function () use($app) { session_destroy(); $app->redirect($app->urlFor('login')); })->name('logout'); if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] == false) { if ($app->request->getResourceUri() != '/login') { try { $app->redirect($app->urlFor('login')); } catch (Exception $e) { } }
$app->render('projects.twig'); })->name("projects"); $app->get('/contact', function () use($app) { $app->render('contact.twig'); })->name("contact"); $app->post('/contact', function () use($app) { $name = $app->request->post("name"); $email = $app->request->post("email"); $message = $app->request->post("message"); if (!empty($name) && !empty($email) && !empty($message)) { $cleanName = filter_var($name, FILTER_SANITIZE_STRING); $cleanEmail = filter_var($email, FILTER_SANITIZE_STRING); $cleanMessage = filter_var($message, FILTER_SANITIZE_STRING); } else { //message user problem $app->redirect("contact"); } // Swift_SmtpTransport::newInstance('smtp.gmail.com' , 465, 'ssl') // ->setUsername("*****@*****.**") // ->setPassword('DeadButDreaming99'); $transport = Swift_SendmailTransport::newInstance('/usr/sbin/sendmail -bs'); $mailer = \Swift_Mailer::newInstance($transport); $swMessage = \Swift_Message::newInstance(); $swMessage->setFrom(array($cleanEmail => $cleanName)); $swMessage->setTo(array('*****@*****.**')); $swMessage->setBody($cleanEmail, $cleanMessage); $result = $mailer->send($swMessage); if ($result > 0) { //send thank you $app->redirect('/'); } else {
/** * Test redirect sets status and header */ public function testRedirect() { $s = new \Slim\Slim(); $s->get('/bar', function () use($s) { echo "Foo"; //<-- Should not be in response body! $s->redirect('/somewhere/else', 303); }); $s->call(); list($status, $header, $body) = $s->response()->finalize(); $this->assertEquals(303, $status); $this->assertEquals('/somewhere/else', $header['Location']); $this->assertEquals('', $body); }
$app->get('/', function () use($app) { $app->render('about.twig'); })->name('home'); $app->get('/contact', function () use($app) { $app->render('contact.twig'); })->name('contact'); $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)) { $cleanName = filter_var($name, FILTER_SANITIZE_STRING); $cleanEmail = filter_var($email, FILTER_SANITIZE_EMAIL); $cleanMsg = filter_var($msg, FILTER_SANITIZE_STRING); } else { $app->redirect('/contact'); } $transport = Swift_SendmailTransport::newInstance('/usr/sbin/sendmail -bs'); $mailer = \Swift_Mailer::newInstance($transport); $message = \Swift_Message::newInstance(); $message->setSubject('Email from our website'); $message->setFrom(array($cleanEmail => $cleanName)); $message->setTo(array('treehouse@localhost')); $message->setBody($cleanMsg); $result = $mailer->send($message); if ($result > 0) { $app->redirect('/'); } else { $app->redirect('/contact'); } });
$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') // ; /* You could alternatively use a different transport such as Sendmail or Mail: // Sendmail $transport = Swift_SendmailTransport::newInstance('/usr/sbin/sendmail -bs'); // Mail
$oper = $row['type']; $response[$resource][$oper][] = array('meta' => $meta, 'data' => $data); } } return $r->respond(200, array('response' => $response, 'last_sync' => $new_last_sync)); }); /* Management Routes */ $app->get('/manage', 'AUTH', function () use($app) { return $app->render("_manage.html"); }); $app->get('/login', function () use($app) { return $app->render("_login.html"); }); $app->get('/logout', function () use($app) { session_destroy(); return $app->redirect(ROOT_URI . "/login"); }); $app->post('/login', function () use($app, $config) { $username = $app->request->params('username'); $password = $app->request->params('password'); if ($username === $config['username'] && $password === $config['password']) { $_SESSION['authenticated'] = true; $_SESSION['expires'] = time() + $config['session_expiry']; return $app->redirect(ROOT_URI . '/manage'); } $app->redirect(ROOT_URI . '/login'); }); /* include predefined routes */ $path = array_filter(explode('/', $app->request->getPath())); $path = array_shift($path); $routesFilePath = 'routes' . DS . $path . '.php';
} 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'); $app->get('/login/', $authenticate($app), function () use($app) {
} catch (Exception $e) { $app->notfound(); } }); $app->get("/thirdindex/:uid/:type", function ($uid, $type) use($app, $databases) { try { $ftype = $app->getCookie("ctype"); $stype = $app->getCookie("csectype"); $ttype = $app->getCookie("csort"); $f = $databases->insert("history", array("uuid" => $uid, "ftype" => $ftype, "stype" => $stype, "ttype" => $ttype)); if ($type > 2) { $datas = $databases->select("user", "expire", array("uuid" => $uid, "ORDER" => array("id DESC", "time DESC"))); if (count($datas) > 0) { $now = time(); if ($now > $datas[0]) { $app->redirect("../../buy"); } else { $app->render("thirdindex.html"); } } else { $app->redirect("../../buy"); } } else { $app->render("thirdindex.html"); } } catch (Exception $e) { $app->notfound(); } }); $app->get("/buy", function () use($app) { try {