Beispiel #1
1
R::setup('sqlite:subscribers.sqlite');
$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) {
Beispiel #2
0
        $req = $app->request();
        $tiposelect = $req->post('tiposelect');
        $inputLatitude = $req->post("inputLatitude");
        $inputLongitude = $req->post("inputLongitude");
        $usu = $_SESSION['id_usuario'];
        $result = Dispositivo::anadirDispositivo($tiposelect, $inputLatitude, $inputLongitude, $usu);
        //0->KO / 1->OK / 2->Existe el usuario / 3->registro OK correo KO
        /*Códigos de mensajes= 
        		
        		-err_reg_usr-->Error al registrar el usuario
        		-usr_reg_OK-->Usuario registrado correctamente.
        		-usr_em_exist-->Usuario o email existentes
        		-usr_OK_em_F -->Usuario registrado, correo fallido
        		*/
        if ($result == 1) {
            $app->flash('message', "El dipsositivo insertado correctamente");
            $app->redirect($app->urlfor('panel'));
        } else {
            if ($result == 0) {
                $app->flashNow('message', "No existe el dipsositivo");
                $app->redirect($app->urlfor('panel'));
            } else {
                $app->flashNow('message', "El dipsositivo no está validado, valida para poder acceder.");
                $app->redirect($app->urlfor('panel'));
            }
        }
    }
});
//btnmodDispositivos
$app->post('/btnmodDispositivos', function () use($app) {
    require_once 'Modelos/Dispositivo.php';
Beispiel #3
0
});
// 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();
Beispiel #4
0
$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->flash('fail', 'All Fields Are Required.');
        $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('ssa@example'));
    $message->setBody($cleanMsg);
    $result = $mailer->send($message);
    if ($result > 0) {
        $app->flash('success', 'Thanks So Much! You are AWESOME!!!');
        $app->redirect('/');
    } else {
        $app->flash('fail', 'So Sorry, Something Went Wrong. Please Try Again!');
Beispiel #5
0
|--------------------------------------------------------------------------
| 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'])) {
Beispiel #6
0
// Auto Loaders
include_once '../private/autoloaders/autoloader main.php';
// LESS Compiler
include_once "../private/includes/less.inc.php";
/* Use for when in a sub-folder
define('BASE_PATH', '/subDirectory/directory/');*/
// Start Slim's Instance & Twig View
$app = new \Slim\Slim(array('mode' => 'development', 'view' => new \Slim\Views\Twig(), 'templates.path' => '../private/templates/'));
$app->configureMode('development', function () use($app) {
    $app->config(array('log.enable' => false, 'debug' => true));
    /// Moved to top to catch any bugs above this for now.
    //define('DEBUGGING', true);
    //ini_set("display_errors", 1);
    //error_reporting(E_ALL);
});
// Set Global View Data
$view = $app->view();
$app->view->getInstance()->addFilter(new Twig_SimpleFilter('debug', 'debug'));
$view->setData(array('loggedIn' => UserSession::isLoggedIn(), 'siteName' => 'Lite Stack PHP', 'siteShort' => 'LS'));
//endregion </Init>
//region	<Middleware>
$authCheck = function () use($app) {
    if (!UserSession::isLoggedIn()) {
        $app->flash('error', "You must be logged in to access this page");
        $app->redirect('/');
    }
};
//endregion	</Middleware>
// Routing
include_once 'routing.php';
$app->run();
Beispiel #7
0
}
$payutcClient = getPayutcClient("WEBSALE");
$admin = $payutcClient->isSuperAdmin();
$isAdminFondation = $payutcClient->isAdmin();
$status = $payutcClient->getStatus();
$app = new \Slim\Slim();
$app->hook('slim.before', function () use($app, $payutcClient, $admin) {
    // check that system is installed
    if (!Config::isInstalled()) {
        $app->flashNow('info', 'This application is not yet configured, please click <a href="install" >here</a> !');
    }
    global $status;
    if (!in_array($app->request->getResourceUri(), ['/about', '/login'])) {
        if (!isset($status) || empty($status->user)) {
            // Il n'était pas encore connecté en tant qu'icam.
            $app->flash('info', "Vous devez être connecté pour accéder au reste de l'application");
            $app->redirect('about');
        } else {
            if (!empty($status->user) && (empty($status->application) || isset($status->application->app_url) && strpos($status->application->app_url, 'shotgun') === false)) {
                // il était connecté en tant qu'icam mais l'appli non
                try {
                    $result = $payutcClient->loginApp(array("key" => Config::get('payutc_key')));
                    $status = $payutcClient->getStatus();
                } catch (\JsonClient\JsonException $e) {
                    $app->flashNow('info', "error login application, veuillez finir l'installation de Shotgun");
                    $app->redirect('install');
                }
            }
        }
        if (!empty($status->user)) {
            $_SESSION['username'] = $status->user;
$twig = new Twig_Environment($loader, array());
$app = new \Slim\Slim(array('view' => new \Slim\Views\Twig()));
$app->config = (require __DIR__ . '/app/config/config.php');
$app->add(new \Slim\Middleware\SessionCookie(array()));
$em = new EM($app);
$em = $em->getEntityManager();
/*****************/
/****** WEB ******/
/*****************/
$app->get('/', function () use($app, $twig) {
    echo $twig->render('index.php', array('flash' => isset($_SESSION['slim.flash']) ? $_SESSION['slim.flash'] : null));
})->name('home');
$app->get('/like/:path', function ($path) use($app, $twig, $em) {
    $vote = $app->getCookie("{$path}");
    if ($vote) {
        $app->flash('danger', "Vous avez déjà liké.");
        $app->redirect($app->urlFor('home', array()));
    } else {
        $qr = $em->getRepository("App\\Entity\\QRCode")->findOneBy(array('path' => $path));
        if ($qr == null) {
            $app->notFound();
        }
        $qr->increment();
        $cl = new ClickLog();
        $em->persist($cl);
        $qr->addClickLog($cl);
        $em->persist($qr);
        $em->flush();
        $app->setCookie("{$path}", true);
        //Render
        $title = $qr->getTitle();
        }
    }
    $app->response->redirect($_SERVER['HTTP_REFERER']);
});
$app->get('/adduser', function () use($app) {
    include 'templates/adduser.phtml';
});
$app->post('/adduser', function () use($app) {
    if (($username = $app->request->params("username")) && ($name = $app->request->params("name")) && ($mail = $app->request->params("mail")) && ($password = $app->request->params("password")) && ($password = password_hash($password, PASSWORD_BCRYPT))) {
        $dbh = $GLOBALS['dbh'];
        $userlevel = 0;
        $db_prefix = $GLOBALS['db_prefix'];
        $stmt = $dbh->prepare("INSERT INTO {$db_prefix}users (userlevel, username, name, mail, password) VALUES (:userlevel, :username, :name, :mail, :password)");
        $values = array(':userlevel' => $userlevel, ':username' => $username, ':name' => $name, ':mail' => $mail, ':password' => $password);
        if ($stmt->execute($values)) {
            $app->flash('adduser', "Added User");
            $app->response->redirect($_SERVER['HTTP_REFERER']);
        } else {
            $app->flash('error', "Username taken");
            $app->response->redirect($_SERVER['HTTP_REFERER']);
        }
    } else {
        $app->flash('error', "Please insert into all fields");
        $app->response->redirect($_SERVER['HTTP_REFERER']);
    }
});
$app->get('/clients', function () use($app) {
    $db_prefix = $GLOBALS['db_prefix'];
    $dbh = $GLOBALS['dbh'];
    $sth = $dbh->prepare("SELECT {$db_prefix}clientauthorization.UniqueClientID,{$db_prefix}client.Name, {$db_prefix}clientauthorization.ClientDescription, \n\t\t\t{$db_prefix}clientauthorization.StatusID, {$db_prefix}clientauthorization.SeenTS FROM \n\t\t\t{$db_prefix}clientauthorization, {$db_prefix}client, {$db_prefix}users WHERE \n\t\t\t{$db_prefix}users.Username = ? AND {$db_prefix}clientauthorization.UserID={$db_prefix}users.UserID AND {$db_prefix}clientauthorization.ClientID={$db_prefix}client.ClientID AND {$db_prefix}clientauthorization.StatusID NOT LIKE '-1' ORDER BY \n\t\t\t{$db_prefix}clientauthorization.SeenTS DESC");
    if ($sth->execute(array($_SESSION['username']))) {
Beispiel #10
0
session_start();
require '../Slim/Slim.php';
\Slim\Slim::registerAutoloader();
$app = new \Slim\Slim();
$app->get('/', function () use($app) {
    $app->render('form.php');
});
$app->post('/', function () use($app) {
    $req = $app->request();
    $errors = array();
    $params = array('email' => array('name' => 'Email', 'required' => true, 'max_length' => 64), 'subject' => array('name' => 'Subject', 'required' => true, 'max_length' => 256), 'message' => array('name' => 'Message', 'required' => true, 'max_length' => 512));
    foreach ($params as $param => $options) {
        $value = $req->params($param);
        if ($options['required']) {
            if (!$value) {
                $errors[] = $options['name'] . ' is required!';
            }
        }
        if ($value and strlen($value) > $options['max_length']) {
            $errors[] = $options['name'] . ' must be less than ' . $options['max_length'] . ' characters long!';
        }
    }
    if ($errors) {
        $app->flash('errors', $errors);
    } else {
        //submit_to_db($email, $subject, $message);
        $app->flash('message', 'Form submitted!');
    }
    $app->redirect('./');
});
$app->run();
Beispiel #11
0
    $app->render('info.php');
});
//Login
$app->post('/login', function () use($app) {
    require_once 'Modelo/Usuario.php';
    $mensaje = "val_OK";
    $app->redirect($app->urlfor('resultado', array('mensaje' => $mensaje)));
    $usr = $app->request->post('idUsuario');
    $pass = $app->request->post('pass');
    if (isset($usr) && isset($pass)) {
        $result = Usuario::comprobarUsuario($usr, $pass);
        if ($result == 1) {
            $app->redirect($app->urlFor('Inicio'));
        } else {
            if ($result == 0) {
                $app->flash('message', "No existe el usuario");
                $app->redirect($app->urlFor('Inicio'));
            } else {
                $app->flash('message', "El usuario no está validado, valida para poder acceder.");
                $app->redirect($app->urlFor('Inicio'));
            }
        }
    } else {
        $app->flash('message', "Faltan datos por introducir.");
        $app->redirect($app->urlFor('Inicio'));
    }
});
//Registro usuario
$app->post('/registro', function () use($app) {
    require_once 'Modelo/Usuario.php';
    //require_once 'Modelo/Utils.php';
Beispiel #12
0
$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->flash("fail", "Please fill in all fields!");
        $app->redirect("/slimproject/contact");
    }
    $transport = \Swift_SmtpTransport::newInstance("gator4252.hostgator.com", 465, "ssl")->setUsername("*****@*****.**")->setPassword('helloworld123');
    $mailer = \Swift_Mailer::newInstance($transport);
    $message = \Swift_Message::newInstance("Waldo Contact Form")->setFrom(array($cleanEmail => $cleanName))->setTo(array("*****@*****.**"))->setBody($cleanMSG);
    $result = $mailer->send($message);
    if ($result > 0) {
        //Send thanks message
        $app->flash("success", "Your message has been sent!");
        $app->redirect("/slimproject");
    } else {
        //Send message that email failed
        //Log that there was an error
        $app->flash("fail", "There was an error sending your email. Please try again!");
        $app->redirect("/slimproject/contact");
Beispiel #13
0
            }
        }
    }
});
//login
$app->post('/login', function () use($app) {
    require_once 'Modelos/Usuario.php';
    $usr = $app->request->post('NomUsuario');
    $pass = $app->request->post('pass');
    if (isset($usr) && isset($pass)) {
        $result = Usuario::comprobarUsuario($usr, $pass);
        if ($result == 1) {
            $app->redirect($app->urlFor('PaginaInicio'));
        } else {
            if ($result == 0) {
                $app->flash('message', "No existe el usuario");
                $app->redirect($app->urlFor('Inicio'));
            } else {
                $app->flash('message', "El usuario no est&aacute; validado, valida para poder acceder.");
                $app->redirect($app->urlFor('Inicio'));
            }
        }
    } else {
        $app->flash('message', "Faltan datos por introducir.");
        $app->redirect($app->urlFor('Inicio'));
    }
});
$app->get('/result/:mensaje', function ($mensaje) use($app) {
    /*
    -err_reg_usr-->Error al registrar el usuario
    -usr_reg_OK-->Usuario registrado correctamente.
Beispiel #14
0
session_cache_limiter(false);
session_start();
require 'Slim/Slim.php';
\Slim\Slim::registerAutoLoader();
define("TAB", "&nbsp;&nbsp;&nbsp;&nbsp;");
define("NEWLINE", "<br />");
$app = new \Slim\Slim();
$app->get('/', function () use($app) {
    $flash = $app->view()->getData('flash');
    $app->render('main.php', array('error' => $flash['error']));
});
$app->post('/view', function () use($app) {
    $req = $app->request();
    $text = $req->post('text');
    if (!$text) {
        $app->flash('error', 'Some text to display would be helpful!');
        $app->redirect('index.php');
    }
    $rules = $req->post('rules');
    $rules = array_filter($rules);
    // $rules_string = "newline after sentence|newline and tab after comma";
    // $rules = explode("|", $rules_string);
    $after = false;
    $valid_format_tokens = array("newline", "new-line", "tab");
    $hash_format_tokens = array("newline" => NEWLINE, "new-line" => NEWLINE, "tab" => TAB);
    $valid_character_tokens = array(".", ",", ";", ":", "full-stop", "sentence", "comma", "semi-colon", "colon");
    $hash_character_tokens = array("sentence" => ". ", "." => ". ", "full-stop" => ". ", "comma" => ",", "," => ",", "semi-colon" => ";", ";" => ";", "colon" => ":", ":" => ":");
    foreach ($rules as &$rule) {
        $format_tokens = array();
        $character_tokens = array();
        $tokens = explode(" ", $rule);
define('MODEL_PATH', 'models/');
define('VIEWS_PATH', 'views');
define('CONTROLLER_PATH', 'controllers/');
// CORE THEME SETTINGS
define('THEME_PATH', APP_THEME . '/');
define('THEME_ASSETS', BASE_URL . VIEWS_PATH . '/' . THEME_PATH . 'assets/');
// ADMIN THEME SETTINGS
define('ADMIN_THEME', 'admin/');
define('ADMIN_ASSETS', BASE_URL . VIEWS_PATH . '/' . ADMIN_THEME . 'assets/');
// LOAD ALL MODEL CLASSES
foreach (glob(MODEL_PATH . "*.php") as $class) {
    require_once $class;
}
// REDBEAN ORM CONFIG
R::setup("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME, DB_USER, DB_PASS);
if (APP_MODE == 'production') {
    R::freeze();
}
// SLIM MICROFRAMEWORK
require 'Slim/Slim.php';
\Slim\Slim::registerAutoloader();
// SLIM CSRF GUARD
require 'Slim/Extras/Middleware/CsrfGuard.php';
$app = new \Slim\Slim(array('mode' => APP_MODE, 'templates.path' => VIEWS_PATH));
$app->add(new \Slim\Extras\Middleware\CsrfGuard());
$app->notFound(function () use($app) {
    $app->flash('danger', 'The page you are looking for could not be found.');
    $url = userIsValid() ? ADMIN_MANAGE : BASE_URL;
    $app->redirect($url);
});
$app->flashKeep();
$app->get("/admin/", function () use($app) {
    $articles = $app->db->getArticles();
    $app->render("adminListArticles.twig", ["articles" => $articles]);
});
$app->get("/admin/new/", function () use($app) {
    $dateObj = new DateTime();
    $currentDate = $dateObj->format("Y-m-d");
    $app->render("adminNewArticle.twig", ["currentDate" => $currentDate]);
});
$app->post("/admin/new/", function () use($app) {
    $title = $app->request->post("title");
    $date = $app->request->post("date");
    $content = $app->request->post("content");
    $app->db->insertNewArticle($title, $date, $content);
    // Add flash message to next page request
    $app->flash("info", "Article has been successfully published");
    $app->redirect($app->request()->getRootUri() . "/admin/");
});
$app->get("/admin/edit/:articleId", function ($articleId) use($app) {
    $article = $app->db->getSingleArticle($articleId);
    $app->render("adminEditArticle.twig", ["article" => $article]);
});
$app->post("/admin/edit/:articleId", function ($articleId) use($app) {
    if ($app->request->post("submit") === "update") {
        $title = $app->request->post("title");
        $date = $app->request->post("date");
        $content = $app->request->post("content");
        $app->db->updateArticle($articleId, $title, $date, $content);
        $app->flash("info", "Article has been successfully updated");
        $app->redirect($app->request()->getRootUri() . "/admin/edit/" . $articleId);
    } elseif ($app->request->post("submit") === "delete") {
Beispiel #17
0
$app->response->headers->set('Content-Type', 'application/json');
//$app->add(new AuthMiddleware());
$app->add(new FormatResponseMiddleware());
$app->config('prefix', "bms_");
// Utils
function getMillisecond()
{
    list($s1, $s2) = explode(' ', microtime());
    return (double) sprintf('%.0f', (floatval($s1) + floatval($s2)) * 1000);
}
$app->get('/', function () use($app) {
    $result = array("isLogin" => false);
    try {
        $app->redirect('/index.html');
    } catch (Exception $e) {
        $app->flash('error', $e->getMessage());
    }
    echo json_encode($result);
});
$app->get('/touch', function () use($app) {
    $result = array("isLogin" => false);
    try {
        if (isset($_SESSION["isLogin"]) && $_SESSION["isLogin"]) {
            $result = array("isLogin" => true, "user" => $_SESSION["user"]);
        }
    } catch (Exception $e) {
        $app->flash('error', $e->getMessage());
    }
    echo json_encode($result);
});
// domain/quit
Beispiel #18
0
})->name('test');
$app->get('/', function () use($app) {
    $app->render('about.twig');
})->name('home');
$app->get('/login', function () use($app) {
    $fb = new Facebook\Facebook(['app_id' => '721077627906410', 'app_secret' => '20bdb4b6922430ab7fd49fa9b3d849c7', 'default_graph_version' => 'v2.4']);
    $loginUrl = User::getFacebookUrl($fb);
    $app->render('login.twig', array('loginUrl' => $loginUrl));
})->name('login');
$app->post('/login', function () use($app) {
    $email = $app->request->post("email");
    $password = $app->request->post("password");
    $res = User::login($email, $password);
    if ($res == 200) {
        // Hooray! Let them use the app now.
        $app->flash("fail", "Welcome");
        $app->redirect("/catalogue");
    } else {
        $app->flash("fail", "Data field required");
        $app->redirect("/login");
    }
});
$authAdmin = function ($app) {
    return function () use($app) {
        $currentUser = ParseUser::getCurrentUser();
        if (!$currentUser) {
            $app->flash("fail", "No");
            $app->redirect('/login');
        }
    };
};
Beispiel #19
0
$app->post('/login', function () use($app) {
    session_start();
    $same_username = $_POST['username'];
    $query_username = ORM::for_table('user')->select('username')->where('username', $same_username)->find_one();
    $password = $_POST['password'];
    $pass = $app->request->post($password);
    /*
    $salt= 'CreativeFramworksSalt';
    $pwd = md5($pass.$salt);
    */
    $pwd = $pass;
    $query_password = ORM::for_table('user')->select('password')->where('username', $same_username)->find_one();
    if (!isset($_POST['username']) or !isset($_POST['password'])) {
        // $message = 'Please enter a valid username and password';
        // $app->render('login-error.html', array('message'=>$message));
        $app->flash('loginerror', 'Please enter a valid username and password');
        $app->redirect('/');
    } elseif (strlen($_POST['username']) > 20 || strlen($_POST['username']) < 4) {
        // $message = 'Incorrect Length for Username';
        // $app->render('login-error.html', array('message'=>$message));
        $app->flash('loginerror', 'Incorrect Length for Username');
        $app->redirect('/');
    } elseif (strlen($_POST['password']) > 20 || strlen($_POST['password']) < 4) {
        // $message = 'Incorrect Length for Password';
        // $app->render('login-error.html', array('message'=>$message));
        $app->flash('loginerror', 'Incorrect Length for Password');
        $app->redirect('/');
    } elseif (ctype_alnum($_POST['username']) != true) {
        /*** if there is no match ***/
        // $message = "Username must be alpha numeric";
        // $app->render('login-error.html', array('message'=>$message));
Beispiel #20
0
        $response = $vimeo->request('/me/watchlater/' . $video_id, array(), 'PUT');
        $app->contentType('application/json');
        echo '{"status": ' . json_encode($response['status']) . '}';
    }
});
$app->get('/upload', function () use($app, $vimeo) {
    $page_data = array();
    $app->render('upload.php', $page_data);
});
$app->post('/upload', function () use($app, $vimeo) {
    $vimeo->setToken('0ba6f164ff299c200d5552ae73c52063');
    $storage = new \Upload\Storage\FileSystem('uploads');
    $file = new \Upload\File('video', $storage);
    $new_filename = uniqid();
    $file->setName($new_filename);
    $file->addValidations(array(new \Upload\Validation\Mimetype('video/mp4'), new \Upload\Validation\Size('25M')));
    try {
        $file->upload();
    } catch (\Exception $e) {
        $errors = $file->getErrors();
        $app->flash('errors', $errors);
    }
    $new_filepath = 'uploads/' . $new_filename . '.' . $file->getExtension();
    try {
        $vimeo->upload($new_filepath, false);
    } catch (\Exception $e) {
        $app->flash('errors', array('error uploading to Vimeo'));
    }
    $app->redirect('upload');
});
$app->run();
Beispiel #21
0
    return new SearchGateway($app->mysqli);
});
$app->get('/', function () use($app) {
    $flash = isset($_SESSION['slim.flash']) ? $_SESSION['slim.flash'] : null;
    $app->render('frontpage.phtml', array("flash" => $flash, "title" => "Download.me - файлообменник", "maxFileSize" => $app->config('maxFileSize'), 'active' => 'home'));
});
$app->post('/upload(/:async)', function ($async = false) use($app) {
    $uploader = new Uploader($app->config('uploadDir'), $app->FileGateway);
    $id = $uploader->uploadFile($_FILES);
    if ($id && !$async) {
        $app->response->redirect("/f/{$id}", 303);
    } elseif ($id && $async) {
        header("Content-Type: application/json");
        echo json_encode(array('id' => $id));
    } elseif (!$id && !$async) {
        $app->flash('error', $uploader->getError());
        $app->response->redirect('/', 303);
    }
});
$app->get('/upload-progress', function () use($app) {
    $uploader = new Uploader($app->config('uploadDir'), $app->FileGateway);
    $data = $uploader->getUploadProgress();
    if ($data) {
        $data['ok'] = true;
        header("Content-Type: application/json");
        echo json_encode($data);
    } else {
        $data = array("ok" => false);
        header("Content-Type: application/json");
        echo json_encode($data);
    }
<?php

require 'vendor/autoload.php';
$app = new \Slim\Slim();
$app->add(new \Slim\Middleware\SessionCookie(array('secret' => 'myappsecret')));
$authenticate = function ($app) {
    return function () use($app) {
        if (!isset($_SESSION['user'])) {
            $_SESSION['urlRedirect'] = $app->request()->getPathInfo();
            $app->flash('error', 'Login required');
            $app->redirect('/login');
        }
    };
};
$app->hook('slim.before.dispatch', function () use($app) {
    $user = null;
    if (isset($_SESSION['user'])) {
        $user = $_SESSION['user'];
    }
    $app->view()->setData('user', $user);
});
$app->get("/", function () use($app) {
    $app->render('index.php');
});
$app->get("/about", function () use($app) {
    $app->render('about.php');
});
$app->get("/level/contact", function () use($app) {
    $app->render('levelContact.php');
});
$app->get("/logout", function () use($app) {
Beispiel #23
0
$app->get('/about', function () use($app) {
    $app->render('about.twig');
})->name('about');
$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->flash('fail', 'All fields are required');
        //message the user that there was a problem
        $app->redirect('/contact');
    }
    /*   $transport = Swift_SendmailTransport::newInstance('/usr/sbin/sendmail -bs'); */
    $transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 465, 'ssl');
    $transport->setUsername('*****@*****.**');
    $transport->setPassword('gio22112008');
    $mailer = \Swift_Mailer::newInstance($transport);
    $message = Swift_Message::newInstance('Email From Our Website');
    $message->setFrom(array($cleanEmail => $cleanName));
    $message->setTo(array('*****@*****.**' => 'Ramon Osenga'));
    $message->setReplyTo(array($cleanEmail => $cleanName));
    $message->setBody(" Name: {$cleanName}\n Email adress: {$cleanEmail}\n {$cleanMsg}");
    $result = $mailer->send($message);
    if ($result > 0) {
Beispiel #24
0
    $username = $app->request->post('username');
    $password = $app->request->post('password');
    $mapper = $app->userMapper;
    $user = $mapper->load($username);
    if ($user) {
        $valid = password_verify($password, $user->getPassword());
        if ($valid) {
            if ($user->getSecret()) {
                $_SESSION['user_in_progress'] = $user;
                $app->redirect('/auth2fa');
            }
            $_SESSION['user'] = $user;
            $app->redirect('/setup2fa');
        }
    }
    $app->flash('error', 'Failed to log in');
    $app->redirect('/login');
});
$app->get('/setup2fa', function () use($app) {
    $user = $_SESSION['user'];
    $g = new \Google\Authenticator\GoogleAuthenticator();
    // invent a secret for this user
    $secret = $g->generateSecret();
    $app->flash('secret', $secret);
    // Create a QR code via Google charts. The data to encode (chl) is:
    //      otpauth://totp/{label}?secret={secret}
    // where:
    //      label = {hostname}:{username}
    //
    // (see https://code.google.com/p/google-authenticator/wiki/KeyUriFormat)
    $data = sprintf("otpauth://totp/%s%%3A%s%%3Fsecret%%3D%s", $_SERVER['HTTP_HOST'], $user->getUsername(), $secret);
Beispiel #25
0
             throw new RuntimeException('メールアドレスまたはパスワードに誤りがあります');
         }
         $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();
Beispiel #26
0
     if ($db) {
         $query = $db->prepare("INSERT INTO contacts (name, email, message)\n\t\t\t\t\t\tVALUES (:name, :email, :msg);");
     }
     /* Insert details into contacts database as back up to email sent. */
     $query->bindParam(':name', $cleanName);
     $query->bindParam(':email', $cleanEmail);
     $query->bindParam(':msg', $cleanMsg);
     $query->execute();
     /* If any field is blank*/
 } else {
     /*
      * send message about incomplete fields and send back to contact form.
      * Flash message info is in flash.twig
      * {% include 'flash.twig' %} is in main.twig at start of body.
      */
     $app->flash('fail', "Your name, a complete email address, and\n\t\t\t\tthe reason for your reaching out are all required for us to make a\n\t\t\t\tmeaingful connection");
     $app->redirect('contact');
 }
 /* details for email to be sent */
 $transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 465, 'ssl')->setUsername('placeholder')->setPassword('placeholder');
 $mailer = Swift_Mailer::newInstance($transport);
 $message = Swift_Message::newInstance()->setSubject('Email from Cosette Website')->setFrom(array($cleanEmail => $cleanEmail))->setTo(array('*****@*****.**'))->setBody($cleanMsg);
 // send message & ensure it was sent //
 $result = $mailer->send($message);
 if ($result > 0) {
     // Send message confirming success & route back to about page //
     $app->flash('success', "Thanks. Can't wait to read it!");
     $app->redirect(' ');
 } else {
     // Send a message that email failed to send & log as error //
     $app->flash('fail', "Something went wrong and your message didn't send. " . "Please try again later.");
Beispiel #27
0
})->name('home');
$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("/");
Beispiel #28
0
                array_push($columns, $column);
            }
        }
        $app->flashNow('columns', $columns);
        $app->flashNow('rows', $result);
    }
    $app->flashNow('query', $app->request->post('query'));
    return $app->render('display_table.html', array('page' => 'Display', 'tablename' => $tablename));
})->name('Menu@DisplayTable');
$app->get('/pick-a-query', function () use($app) {
    $app->render('pick_a_query.html', array('page' => 'PickAQuery'));
})->name('Menu@PickAQuery');
$app->post('/pick-a-query', function () use($app) {
    if ($app->request->post('query') == 1) {
        $username = trim($app->request->post('username'));
        $app->flash('1_username', $username);
        $result = DB::statement("SELECT name FROM tags WHERE tags.username='******'");
    } else {
        $username = trim($app->request->post('username'));
        $tag = trim($app->request->post('tag'));
        $app->flash('2_username', $username);
        $app->flash('tag', $tag);
        $result = DB::statement("SELECT id, name, description FROM media_instances, tags_media_instances WHERE id = media_instance_id AND media_instances.username='******' AND tag_name='{$tag}'");
    }
    if (!$result) {
        if (mysql_error() != "") {
            $app->flash('error', mysql_error());
        } else {
            $app->flash('empty', '1');
        }
        $app->redirectTo('Menu@PickAQuery');
 public function testSetFlashForNextRequest()
 {
     $s = new \Slim\Slim();
     $s->get('/bar', function () use($s) {
         $s->flash('info', 'bar');
     });
     $this->assertFalse(isset($_SESSION['slim.flash']));
     $s->run();
     $this->assertEquals('bar', $_SESSION['slim.flash']['info']);
 }
Beispiel #30
0
<?php

require 'vendor/autoload.php';
require_once __DIR__ . '/server.php';
$app = new \Slim\Slim();
$validateToken = function () use($server, $app) {
    return function () use($server, $app) {
        $app->response->headers->set('Content-Type', 'application/json');
        if (!$server->verifyResourceRequest(OAuth2\Request::createFromGlobals())) {
            $app->flash('error', 'Not authorized');
            $error = array("error" => "NOT_AUTHORIZED", "message" => "Not authorized, invalid access_token", "code" => 403);
            $app->halt(403, json_encode($error));
        }
    };
};
//Obtain access token with an auth token (code)
$app->post('/token/', function () use($server) {
    $server->handleTokenRequest(OAuth2\Request::createFromGlobals())->send();
});
//Obtain personal data (Sample rotected Enpoint)
$app->get('/treasure/', $validateToken(), function () use($app) {
    $app->response->headers->set('Content-Type', 'application/json');
    $me = array('first_name' => 'Gary', 'last_name' => 'Smith', 'phone' => '555-555-555', 'email' => '*****@*****.**', 'bank_account' => '888444555222332444487886655');
    echo json_encode($me);
});
//View to accept or decline access to personal data
$app->get('/auth/', function () use($server, $app) {
    $code = $app->request()->get('response_type');
    $client = $app->request()->get('client_id');
    $state = $app->request()->get('state');
    $app->render('authForm.php', array('clientId' => $client, 'authorizePath' => "auth?response_type={$code}&client_id={$client}&state={$state}"));