fix api group routes, install google/recaptcha, add more templates

This commit is contained in:
German Correa 2017-12-08 11:08:12 -03:00
parent 6cb63e6938
commit 61d954d5fc
9 changed files with 349 additions and 28 deletions

76
api/contact.php Normal file
View File

@ -0,0 +1,76 @@
<?php
function verifyCaptcha(){
$url = 'https://www.google.com/recaptcha/api/siteverify';
$data = array(
'secret' => '6LeLxy4UAAAAABClplWLJUjZ1_nhX_-SI7CuNcm8',
'response' => $_POST["g-recaptcha-response"]
);
$options = array(
'http' => array (
'header' => 'Content-Type: application/x-www-form-urlencoded\r\n',
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$verify = file_get_contents($url, false, $context);
$captcha_success=json_decode($verify);
return $captcha_success;
}
// process.php
$errors = array(); // array to hold validation errors
$data = array(); // array to pass back data
// validate the variables ======================================================
// if any of these variables don't exist, add an error to our $errors array
if (empty($_POST['nombre']))
$errors['nombre'] = 'Name is required.';
if (empty($_POST['email']))
$errors['email'] = 'Email is required.';
if (empty($_POST['mensage']))
$errors['mensage'] = 'Mensaje is required.';
if(empty($_POST['g-recaptcha-response'])){
$errors['recaptcha'] = 'Debe validar el captcha';
}
else if(!verifyCaptcha()){
$errors['recaptcha'] = 'Error en la validación de ReCaptcha';
}
// return a response ===========================================================
// if there are any errors in our errors array, return a success boolean of false
if ( ! empty($errors)) {
// if there are items in our errors array, return those errors
$data['success'] = false;
$data['errors'] = $errors;
} else {
// if there are no errors process our form, then return a message
// DO ALL YOUR FORM PROCESSING HERE
// THIS CAN BE WHATEVER YOU WANT TO DO (LOGIN, SAVE, UPDATE, WHATEVER)
// show a message of success and provide a true success variable
$nombre = $_POST['nombre'];
$mail = $_POST['email'];
$msg = $_POST['mensage'];
$headers = 'From: ' . $mail . "\r\n" .
'Reply-To: ' . $mail . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail('6coloquio@cmat.edu.uy', 'Contacto de ' . $nombre, $msg, $headers);
$data['success'] = true;
$data['message'] = 'Mensaje enviado,<br/>A la brevedad el comite organizador se pondrá en contacto con usted.';
}
// return all our data to an AJAX call
echo json_encode($data);
?>

135
api/register.php Normal file
View File

@ -0,0 +1,135 @@
<?php
$root = realpath($_SERVER["DOCUMENT_ROOT"]);
include_once $root.'/db/db.php';
function verifyCaptcha(){
$url = 'https://www.google.com/recaptcha/api/siteverify';
$data = array(
'secret' => '6LesRDsUAAAAAA6t3UgL4U4Foc9njmXX-8HIiLj_',
'response' => $_POST["g-recaptcha-response"]
);
$options = array(
'http' => array (
'header' => 'Content-Type: application/x-www-form-urlencoded\r\n',
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$verify = file_get_contents($url, false, $context);
$captcha_success=json_decode($verify);
return $captcha_success;
}
/*function verifyExistance($doc,$mail){
$fp = fopen("2021y22.csv", 'r');
fclose($fp);
}*/
/*function setheaders() {
$fp = fopen("2021y22.csv", 'w');
$cabezal = array('Nombre', 'Apellido','TipoDoc','Documento',
'Direccion','Pais','Ciudad', 'Telefono', 'Email',
'Profesión','Trabaja en','Financiación','Detalle Financiación');
if($fp){
fputcsv($fp,$cabezal);
fclose($fp);
}
else{
die("unable to open file");
}
}*/
/*function registrar($fila) {
$fp = fopen("2021y22.csv", 'a');
if($fp){
fputcsv($fp,$fila);
fclose($fp);
}
else{
die("unable to open file");
}
}
function bkpregister(){
$fecha = date("d-m-H:i:s");
$filebkp = "bkp/registro-".$fecha.".bak.csv";
copy("2021y22.csv",$filebkp);
}*/
$errors = array(); // array to hold validation errors
$data = array(); // array to pass back data
// validate the variables ======================================================
$data['nombre'] = $_POST['nombre'];
$data['apellido'] = $_POST['apellido'];
$data['titulo'] = $_POST['titulo'];
$data['afiliacion'] = $_POST['afiliacion'];
$data['ciudad'] = $_POST['ciudad'];
$data['pais'] = $_POST['pais'];
$data['email'] = $_POST['email'];
$data['fechaLlegada'] = $_POST['bda'];
$data['fechaPartida'] = $_POST['eda'];
$data['financiacion'] = $_POST['financiacion'];
$data['invitado'] = $_POST['invited'];
$data['cartaInvitacion'] = $_POST['letterinvited'];
$data['roomingPref'] = $_POST['roomtype'];
$data['roommate'] = $_POST['roomate'];
$data['fechaRegistro'] = date("Y-m-d H:i:s");
$fila = $data;
if (empty($_POST['nombre']))
$errors['nombre'] = 'Nombre is required.';
if (empty($_POST['apellido']))
$errors['apellido'] = 'Apellido is required.';
if (empty($_POST['email']))
$errors['email'] = 'E-Mail de contacto vacio o incorrecto';
if(empty($_POST['g-recaptcha-response'])){
$errors['recaptcha'] = 'Debe validar el captcha';
}
else if(!verifyCaptcha()){
$errors['recaptcha'] = 'Error en la validación de ReCaptcha';
}
/*GUAMBIA ACAAA!!!!*/
$errors=array();
/* NO GILEAR!!!!!*/
if ( !empty($errors)) {
// if there are items in our errors array, return those errors
$data['success'] = false;
$data['errors'] = $errors;
}
else {
$data['success'] = true;
$db->insert($fila);
/*
$mail = $data["email"];
$nombre = $data["nombre"] . " " . $data["apellido"];
$msg = "Hi ". $data["nombre"] ."!\n\n".
"You have been Successfully registered to the workshop on Groups, Geometry and Dynamics!\n\n".
"For any question, write us to: ggdworkshop@cmat.edu.uy\n\n".
"Regards,\n\n".
"Organizing Commite, GGD Workshop.";
$headers = 'From: ' . "ggdworkshop@cmat.edu.uy" . "\r\n" .
'Reply-To: ' . "ggdworkshop@cmat.edu.uy" . "\r\n" .
'Content-Type: ' . "text/plain; charset=UTF-8". "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($mail, 'Registration confirmation for GGDWorkshop', $msg, $headers);
*/
$data['message'] = "Registration Successfully!";
}
// return all our data to an AJAX call
echo json_encode($data);
?>

View File

@ -15,7 +15,8 @@
"php": ">=5.5.0",
"slim/slim": "^3.1",
"monolog/monolog": "^1.17",
"slim/twig-view": "^2.3"
"slim/twig-view": "^2.3",
"google/recaptcha": "^1.1"
},
"require-dev": {
"phpunit/phpunit": ">=4.8 < 6.0"

47
composer.lock generated
View File

@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file",
"This file is @generated automatically"
],
"content-hash": "c068853e76cdab884c36b9e671e23258",
"content-hash": "f85f941c60254a0fb9e6426933aeac77",
"packages": [
{
"name": "container-interop/container-interop",
@ -37,6 +37,51 @@
"homepage": "https://github.com/container-interop/container-interop",
"time": "2017-02-14T19:40:03+00:00"
},
{
"name": "google/recaptcha",
"version": "1.1.3",
"source": {
"type": "git",
"url": "https://github.com/google/recaptcha.git",
"reference": "5a56d15ca10a7b75158178752b2ad8f755eb4f78"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/google/recaptcha/zipball/5a56d15ca10a7b75158178752b2ad8f755eb4f78",
"reference": "5a56d15ca10a7b75158178752b2ad8f755eb4f78",
"shasum": ""
},
"require": {
"php": ">=5.5"
},
"require-dev": {
"phpunit/phpunit": "^4.8"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.1.x-dev"
}
},
"autoload": {
"psr-4": {
"ReCaptcha\\": "src/ReCaptcha"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"BSD-3-Clause"
],
"description": "Client library for reCAPTCHA, a free service that protect websites from spam and abuse.",
"homepage": "http://www.google.com/recaptcha/",
"keywords": [
"Abuse",
"captcha",
"recaptcha",
"spam"
],
"time": "2017-03-09T18:44:34+00:00"
},
{
"name": "monolog/monolog",
"version": "1.23.0",

View File

@ -2,7 +2,7 @@
class DB{
private $pdo;
public function __constructor($dbpdo){
public function __construct($dbpdo){
$this->pdo = $dbpdo;
}

View File

@ -12,10 +12,16 @@ $container['renderer'] = function ($c) {
]);
};
$container['db'] = function ($c) {
$db = $c['settings']['db'];
$pdo = new PDO('sqlite:'.$db['path']);
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$db = $c->get('settings')['db'];
try{
$pdo = new PDO('sqlite:'.$db['path']);
$pdo->setAttribute( \PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION );
$pdo->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_ASSOC);
}
catch(\PDOException $e){
echo $e->getMessage();
}
return $pdo;
};
// monolog

View File

@ -22,36 +22,62 @@ $app->get('/registration', function (Request $request, Response $response, array
return $this->renderer->render($response, 'registration.html', $args);
});
$app->post('/reg', function (Request $request, Response $response, array $args) {
$app->get('/participants', function (Request $request, Response $response, array $args) {
// Sample log message
$this->logger->debug($resquest->getBody());
$db = new DB($this->db);
$data = $request->getParsedBody();
//var_dump($data);
$newresponse = $response->withJson($data);
//echo $newresponse;
$this->logger->info("GDDWorkshop '/participants' route");
$db = new DB($this->db);
$data = $db->getAll();
// Render index view
//return $this->renderer->render($response, 'registration.html', $args);
return $this->renderer->render($response, 'participants.html', ['registros' => $data]);
});
/*$app->get('/caca', function (Request $request, Response $response, array $args) {
// Sample log message
$this->logger->info("GDDWorkshop '/api/register' route");
$db = new DB($this->db);
$data = $request->getParsedBody();
//var_dump($data);
$newresponse = $response->withJson($data);
return "<h1>caca</h1>";
});*/
$app->get('/committess', function (Request $request, Response $response, array $args) {
// Sample log message
$this->logger->info("GDDWorkshop '/committess' route");
// Render index view
return $this->renderer->render($response, 'committess.html', $args);
});
/*
$mw = function ($request, $response, $next) {
$response->getBody()->write('BEFORE');
$response = $next($request, $response);
$response->getBody()->write('AFTER');
return $response;
};*/
// API ROUTES
$app->group('/api', function($app){
$app->get("/test", function(Request $request, Response $response, array $args) {
$this->logger->info("GDDWorkshop '/api/test' route");
return var_dump($request);
});
$app->post('/register', function (Request $request, Response $response, array $args) {
// Sample log message
//$this->logger->debug(var_dump($request->getParsedBody()));
$db = new DB($this->db);
$data = $request->getParsedBody();
try{
$db->insert($data);
}
catch (Exception $e){
$this->logger->debug($e->getMessage());
return $e->getMessage();
}
$newresponse = $response->withJson($data);
return $newresponse;
});
});

View File

@ -4,7 +4,7 @@ return [
'displayErrorDetails' => true, // set to false in production
'addContentLengthHeader' => false, // Allow the web server to send the content-length header
'debug' => true,
// Renderer settings
'renderer' => [
'template_path' => __DIR__ . '/../templates/',

View File

@ -0,0 +1,32 @@
{% extends "layout.html" %}
{% block content %}
<div class="row">
<div class="col-xs-12">
<h1><strong>Participants</strong></h1>
<table class="table table-striped">
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Affiliation</th>
</tr>
</thead>
<tbody>
{% for reg in registros %}
<tr>
<td>{{ reg.nombre }}</td>
<td>{{ reg.apellido }}</td>
<td>{{ reg.afiliacion }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
{% endblock %}