rework from legacy code on legacy container with php 5

This commit is contained in:
sabelo 2024-07-30 14:58:32 -03:00
parent 5b5c51f66f
commit 8db84d5134
8 changed files with 1109 additions and 2138 deletions

View File

@ -1,76 +0,0 @@
<?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);
?>

View File

@ -1,135 +0,0 @@
<?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

@ -1,7 +1,14 @@
{ {
"name": "slim/slim-skeleton", "name": "slim/slim-skeleton",
"description": "Groups Geometry and Dynamics, ICM2018 Satellite, Web Project", "description": "Groups Geometry and Dynamics, ICM2018 Satellite, Web Project",
"keywords": ["ICM2018", "GGDWorkshop", "Montevideo","Math","Groups","Geometry"], "keywords": [
"ICM2018",
"GGDWorkshop",
"Montevideo",
"Math",
"Groups",
"Geometry"
],
"homepage": "https://ggdworkshop.cmat.edu.uy", "homepage": "https://ggdworkshop.cmat.edu.uy",
"license": "GPLv2", "license": "GPLv2",
"authors": [ "authors": [
@ -12,31 +19,21 @@
} }
], ],
"require": { "require": {
"php": ">=5.5.0", "php": ">=8.2",
"slim/slim": "^3.1", "slim/slim": "^4.14",
"monolog/monolog": "^1.17", "monolog/monolog": "^1.17",
"slim/twig-view": "^2.3", "slim/twig-view": "^3.4",
"google/recaptcha": "^1.1", "google/recaptcha": "^1.1",
"kanellov/slim-twig-flash": "^0.2.0", "slim/flash": "^0.4.0",
"phpmailer/phpmailer": "~6.0", "slim/psr7": "^1.7",
"tuupola/slim-basic-auth": "^3.2", "php-di/php-di": "^7.0",
"symfony/yaml": "^5.0" "symfony/yaml": "^7.1"
},
"require-dev": {
"phpunit/phpunit": ">=4.8 < 6.0"
},
"autoload-dev": {
"psr-4": {
"Tests\\": "tests/"
}
}, },
"config": { "config": {
"process-timeout" : 0 "process-timeout": 0
}, },
"scripts": { "scripts": {
"start": "php -S localhost:8080 -t public index.php", "start": "php -S localhost:8080 -t public index.php",
"test": "phpunit" "test": "phpunit"
} }
} }

2487
composer.lock generated

File diff suppressed because it is too large Load Diff

45
nginx.template.conf Executable file
View File

@ -0,0 +1,45 @@
worker_processes 5;
daemon off;
worker_rlimit_nofile 8192;
events {
worker_connections 4096; # Default: 1024
}
http {
include $!{nginx}/conf/mime.types;
index index.html index.htm index.php;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] $status '
'"$request" $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /dev/stdout;
error_log /dev/stdout;
sendfile on;
tcp_nopush on;
server_names_hash_bucket_size 128; # this seems to be required for some vhosts
server {
listen 80;
server_name localhost;
index index.php index.html index.html;
add_header X-Frame-Options "SAMEORIGIN";
add_header X-Content-Type-Options "nosniff";
charset utf-8;
root /app/public;
location / {
try_files $uri /index.php$is_args$args;
}
location ~ \.php$ {
try_files $uri =404;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
include $!{nginx}/conf/fastcgi_params;
include $!{nginx}/conf/fastcgi.conf;
}
}
}

View File

@ -1,33 +1,36 @@
<?php <?php
// DIC configuration // DIC configuration
use Symfony\Component\Yaml\Yaml; use Symfony\Component\Yaml\Yaml;
$container = $app->getContainer(); use DI\Container;
use Slim\Flash\Messages;
$container['flash'] = function($c){ $container = new Container();
$container->set('flash', function($c){
return new \Slim\Flash\Messages(); return new \Slim\Flash\Messages();
}; });
$container['renderer'] = function ($c) { // $container['renderer'] = function ($c) {
$settings = $c->get('settings')['renderer']; // $settings = $c->get('settings')['renderer'];
$view = new Slim\Views\Twig($settings['template_path'],[ // $view = new Slim\Views\Twig($settings['template_path'],[
'cache' => $settings['cache_path'], // 'cache' => $settings['cache_path'],
]); // ]);
$view->addExtension(new Knlv\Slim\Views\TwigMessages( // $view->addExtension(new Knlv\Slim\Views\TwigMessages(
$c->get('flash') // $c->get('flash')
)); // ));
$noticias = Yaml::parseFile(__DIR__."/../data/noticias.yml"); // $noticias = Yaml::parseFile(__DIR__."/../data/noticias.yml");
$sponsors = Yaml::parseFile(__DIR__."/../data/sponsors.yml"); // $sponsors = Yaml::parseFile(__DIR__."/../data/sponsors.yml");
$view->getEnvironment()->addGlobal('noticias',$noticias); // $view->getEnvironment()->addGlobal('noticias',$noticias);
$view->getEnvironment()->addGlobal('sponsors',$sponsors); // $view->getEnvironment()->addGlobal('sponsors',$sponsors);
return $view; // return $view;
}; // };
$container['db'] = function ($c) { $container -> set('db', function ($c) {
$dbconf = $c->get('settings')['db']; $dbconf = $c->get('settings')['db'];
try{ try{
$pdo = new PDO('sqlite:'.$dbconf['path']); $pdo = new PDO('sqlite:'.$dbconf['path']);
@ -44,16 +47,38 @@ $container['db'] = function ($c) {
echo $e->getMessage(); echo $e->getMessage();
} }
return $db; return $db;
}; });
// monolog
$container['logger'] = function ($c) {
$settings = $c->get('settings')['logger'];
$logger = new Monolog\Logger($settings['name']);
$logger->pushProcessor(new Monolog\Processor\UidProcessor());
$logger->pushHandler(new Monolog\Handler\StreamHandler($settings['path'], $settings['level']));
return $logger;
};
/*$container['mailer'] =function ($c){
};*/ $container->set('settings', function(){
return [
'displayErrorDetails' => true, // set to false in production
'addContentLengthHeader' => false, // Allow the web server to send the content-length header
'debug' => false,
'testing' => false,
'close_registration' => true,
// Renderer settings
'renderer' => [
'template_path' => __DIR__ . '/../templates/',
//'cache_path' => __DIR__.'/../templates/.cache/',
'cache_path' => false,
'autoreload' => true,
'debug' => true
],
'db' => [
'path' => __DIR__."/../db/surfaces2018.db",
'schema' => __DIR__."/../db/schema.sql",
'load_schema' => __DIR__."/../db/.schema.lock"
],
'recaptcha' => [
'secret' => "6LesRDsUAAAAAA6t3UgL4U4Foc9njmXX-8HIiLj_",
'secrettest' => "6LeIxAcTAAAAAGG-vFI1TnRWxMZNFuojJ4WifJWe",
'sitekey' => "6LesRDsUAAAAAJvyoODvjiza9u75qEGJmbKHEV6s",
'sitekeytest' => "6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI"
],
];
});

View File

@ -1,4 +1,11 @@
<?php <?php
// Application middleware // Application middleware
// e.g: $app->add(new \Slim\Csrf\Guard); use Slim\Views\Twig;
use Slim\Views\TwigMiddleware;
// Create Twig
$twig = Twig::create(__DIR__ . '/../templates', ['cache' => false]);
// Add Twig-View Middleware
$app->add(TwigMiddleware::create($app, $twig));

View File

@ -1,231 +1,220 @@
<?php <?php
use Slim\Http\Request; use Psr\Http\Message\ResponseInterface as Response;
use Slim\Http\Response; use Psr\Http\Message\ServerRequestInterface as Request;
use Symfony\Component\Yaml\Yaml; use Slim\Views\Twig;
use Slim\Flash\Message;
// Routes // Routes
$app->add(new Tuupola\Middleware\HttpBasicAuthentication([
"path" => ["/inscriptos", "inscriptoscsv"], /* or ["/admin", "/api"] */
"realm" => "Protected",
"secure" => false,
"users" => [
"admin" => "puntofijo"
]
]));
$app->get('/', function (Request $request, Response $response, array $args) { $app->get('/', function (Request $request, Response $response, array $args) {
$this->logger->info("GDDWorkshop '/' route"); // $this->logger->info("GDDWorkshop '/' route");
return $this->renderer->render($response, 'index.html', $args); $view = Twig::fromRequest($request);
return $view->render($response, 'index.html', $args);
}); });
$app->get('/descripcion', function (Request $request, Response $response, array $args) { $app->get('/descripcion', function (Request $request, Response $response, array $args) {
$this->logger->info("GDDWorkshop '/descripcion' route"); // $this->logger->info("GDDWorkshop '/descripcion' route");
return $this->renderer->render($response, 'descripcion.html', $args); $view = Twig::fromRequest($request);
return $view->render($response, 'descripcion.html', $args);
}); });
$app->get('/registrarse', function (Request $request, Response $response, array $args) { // $app->get('/registrarse', function (Request $request, Response $response, array $args) {
$this->logger->info("GDDWorkshop '/registrtion' route"); // // $this->logger->info("GDDWorkshop '/registrtion' route");
$recapsitekey = $this->settings["recaptcha"]["sitekey"];
if($this->settings["testing"]){ // $recapsitekey = $this->settings["recaptcha"]["sitekey"];
$recapsitekey = $this->settings["recaptcha"]["sitekeytest"]; // if($this->get('settings')["testing"]){
} // $recapsitekey = $this->settings["recaptcha"]["sitekeytest"];
return $this->renderer->render($response, 'registration.html', // }
[ // $view = Twig::fromRequest($request);
'closed' => $this->settings['close_registration'], // return $view->render($response, 'descripcion.html',
'sitekey' => $recapsitekey // [
]); // 'closed' => $this->settings['close_registration'],
}); // 'sitekey' => $recapsitekey
// ]);
// });
$app->get('/participantes', function (Request $request, Response $response, array $args) { // $app->get('/participantes', function (Request $request, Response $response, array $args) {
$this->logger->info("GDDWorkshop '/participants' route"); // // $this->logger->info("GDDWorkshop '/participants' route");
$db = $this->db; // $db = $this->get('db');
$data = $db->getAll(); // $data = $db->getAll();
return $this->renderer->render($response, 'participants.html', ['registros' => $data]); // $view = Twig::fromRequest($request);
}); // return $view->render($response, 'participants.html', ['registros' => $data]);
// });
$app->get('/comites', function (Request $request, Response $response, array $args) { // $app->get('/comites', function (Request $request, Response $response, array $args) {
$this->logger->info("GDDWorkshop '/committess' route"); // // $this->logger->info("GDDWorkshop '/committess' route");
$comites = Yaml::parseFile(__DIR__."/../data/comites.yml"); // $comites = Yaml::parseFile(__DIR__."/../data/comites.yml");
//$strcomites = file_get_contents(__DIR__."/../data/comites.json"); // //$strcomites = file_get_contents(__DIR__."/../data/comites.json");
//$comites = json_decode($strcomites,true); // //$comites = json_decode($strcomites,true);
//echo "<pre>".var_export($comites,true)."</pre>"; // //echo "<pre>".var_export($comites,true)."</pre>";
return $this->renderer->render($response, 'committess.html',['comites' => $comites]); // $view = Twig::fromRequest($request);
}); // return $view->render($response, 'committess.html',['comites' => $comites]);
// });
$app->get('/informacion-practica', function (Request $request, Response $response, array $args) { // $app->get('/informacion-practica', function (Request $request, Response $response, array $args) {
$this->logger->info("GDDWorkshop '/practicalinfo' route"); // // $this->logger->info("GDDWorkshop '/practicalinfo' route");
return $this->renderer->render($response, 'practicalinfo.html', $args); // $view = Twig::fromRequest($request);
}); // return $view->render($response, 'practicalinfo.html', $args);
// });
$app->get('/conferencias', function (Request $request, Response $response, array $args) { // $app->get('/conferencias', function (Request $request, Response $response, array $args) {
$this->logger->info("GDDWorkshop '/charlas' route"); // $charlas = Yaml::parseFile(__DIR__."/../data/conferencias.yml");
//$strcharlas = file_get_contents(__DIR__."/../data/conferencias.json"); // $view = Twig::fromRequest($request);
// return $view->render($response, 'conferencias.html',
// ['charlas' => $charlas]);
// });
$charlas = Yaml::parseFile(__DIR__."/../data/conferencias.yml"); // $app->get('/sesiones', function (Request $request, Response $response, array $args) {
//echo "<pre>".var_export($charlasyml,true)."</pre>"; // // $this->logger->info("GDDWorkshop '/sesiones' route");
//$charlas = json_decode($strcharlas,true); // $sesiones = Yaml::parseFile(__DIR__."/../data/sesiones.yml");
/*function cmp($a, $b){
$aArray = explode(" ", $a.no);
$bArray = explode(" ", $b);
$aApellido = $a
if($a == $b){
return 0;
}
return ($a<$b)?-1:1;
} */
return $this->renderer->render($response, 'conferencias.html',
['charlas' => $charlas]);
});
$app->get('/sesiones', function (Request $request, Response $response, array $args) { // function removeAccents($string) {
$this->logger->info("GDDWorkshop '/sesiones' route"); // return strtolower(trim(preg_replace('~[^0-9a-z]+~i', '-', preg_replace('~&([a-z]{1,2})(acute|cedil|circ|grave|lig|orn|ring|slash|th|tilde|uml);~i', '$1', htmlentities($string, ENT_QUOTES, 'UTF-8'))), ' '));
$sesiones = Yaml::parseFile(__DIR__."/../data/sesiones.yml"); // }
//$strsesiones = file_get_contents(__DIR__."/../data/sesiones.json");
//$sesiones = json_decode($strsesiones,true);
function removeAccents($string) { // usort($sesiones,function($s1,$s2){
return strtolower(trim(preg_replace('~[^0-9a-z]+~i', '-', preg_replace('~&([a-z]{1,2})(acute|cedil|circ|grave|lig|orn|ring|slash|th|tilde|uml);~i', '$1', htmlentities($string, ENT_QUOTES, 'UTF-8'))), ' ')); // $a = removeAccents($s1['titulo']);
} // $b = removeAccents($s2['titulo']);
// return strcasecmp($a,$b)<0?-1:1;
// });
usort($sesiones,function($s1,$s2){ // //echo "<pre>".var_export($sesiones,true)."</pre>";
$a = removeAccents($s1['titulo']); // $view = Twig::fromRequest($request);
$b = removeAccents($s2['titulo']); // return $view->render($response, 'sesiones.html', ["sesiones"=>array_chunk($sesiones,8,true)]);
return strcasecmp($a,$b)<0?-1:1; // });
});
//echo "<pre>".var_export($sesiones,true)."</pre>"; // $app->get('/programa', function (Request $request, Response $response, array $args) {
return $this->renderer->render($response, 'sesiones.html', ["sesiones"=>array_chunk($sesiones,8,true)]); // // $this->logger->info("GDDWorkshop '/program' route");
}); // $view = Twig::fromRequest($request);
// return $view->render($response, 'program.html', $args);
// });
$app->get('/programa', function (Request $request, Response $response, array $args) { // $app->get('/inscriptos', function(Request $request, Response $response, array $args){
$this->logger->info("GDDWorkshop '/program' route"); // // $this->logger->info("GDDWorkshop '/practicalinfo' route");
return $this->renderer->render($response, 'program.html', $args); // $db = $this->get('db');
}); // $data = $db->getAll();
// $view = Twig::fromRequest($request);
// return $view->render($response, 'inscriptos.html', ["registros" => $data]);
// });
$app->get('/inscriptos', function(Request $request, Response $response, array $args){ // $app->get('/inscriptoscsv', function(Request $request, Response $response, array $args){
$this->logger->info("GDDWorkshop '/practicalinfo' route"); // // $this->logger->info("GDDWorkshop '/practicalinfo' route");
$db = $this->db; // $dbfile = $this->get('settings')['db']['path'];
$data = $db->getAll(); // $file = 'inscriptos-surface2018.csv';
return $this->renderer->render($response, 'inscriptos.html', ["registros" => $data]); // exec('sqlite3 -header -csv '.$dbfile.' "select * from registro" > "'.$file.'"');
});
$app->get('/inscriptoscsv', function(Request $request, Response $response, array $args){ // $fh = fopen($file,"rb");
$this->logger->info("GDDWorkshop '/practicalinfo' route"); // $stream = new \Slim\Http\Stream($fh);
$dbfile = $this->settings['db']['path']; // return $response->withHeader('Content-Type', 'application/force-download')
$file = 'inscriptos-surface2018.csv'; // ->withHeader('Content-Type', 'application/octet-stream')
exec('sqlite3 -header -csv '.$dbfile.' "select * from registro" > "'.$file.'"'); // ->withHeader('Content-Type', 'application/download')
// ->withHeader('Content-Description', 'File Transfer')
// ->withHeader('Content-Transfer-Encoding', 'binary')
// ->withHeader('Content-Disposition', 'attachment; filename="' . basename($file) . '"')
// ->withHeader('Expires', '0')
// ->withHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0')
// ->withHeader('Pragma', 'public')
// ->withBody($stream);
// });
$fh = fopen($file,"rb"); // $mw = function ($request, $response, $next) {
$stream = new \Slim\Http\Stream($fh); // $response->getBody()->write('BEFORE');
return $response->withHeader('Content-Type', 'application/force-download') // $response = $next($request, $response);
->withHeader('Content-Type', 'application/octet-stream') // $response->getBody()->write('AFTER');
->withHeader('Content-Type', 'application/download')
->withHeader('Content-Description', 'File Transfer')
->withHeader('Content-Transfer-Encoding', 'binary')
->withHeader('Content-Disposition', 'attachment; filename="' . basename($file) . '"')
->withHeader('Expires', '0')
->withHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0')
->withHeader('Pragma', 'public')
->withBody($stream);
});
$mw = function ($request, $response, $next) { // return $response;
$response->getBody()->write('BEFORE'); // };
$response = $next($request, $response);
$response->getBody()->write('AFTER');
return $response; // // API ROUTES
}; // $app->group('/api', function($app){
// API ROUTES // $app->get("/test", function(Request $request, Response $response, array $args) {
$app->group('/api', function($app){ // // $this->logger->info("GDDWorkshop '/api/test' route");
// return var_dump($request);
$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) {
// $messages = $this->flash;
// $data = $request->getParsedBody();
// $db = $this->db;
// if($this->settings['close_registration']){
// $messages->addMessageNow("submit-register-err", "Registration has benn closed");
// }
// else{
$app->post('/register', function (Request $request, Response $response, array $args) { // if(!isset($data['nombre'])||empty($data['nombre']))
$messages = $this->flash; // $messages->addMessageNow("submit-register-err", "First name could not be empty");
$data = $request->getParsedBody(); // if(!isset($data['apellido'])||empty($data['apellido']))
$db = $this->db; // $messages->addMessageNow("submit-register-err", "Last name could not be empty");
if($this->settings['close_registration']){ // if(!isset($data['email'])||empty($data['email']))
$messages->addMessageNow("submit-register-err", "Registration has benn closed"); // $messages->addMessageNow("submit-register-err", "E-mail could not be empty");
} // if(!isset($data['letterinvited'])||!is_numeric($data['letterinvited']))
else{ // $messages->addMessageNow("submit-register-err", "Question about needing a letter of invitation must have a selected answer");
if(!isset($data['nombre'])||empty($data['nombre'])) // //ReCaptcha Validation
$messages->addMessageNow("submit-register-err", "First name could not be empty"); // if(!isset($data['g-recaptcha-response'])||empty($data['g-recaptcha-response'])){
if(!isset($data['apellido'])||empty($data['apellido'])) // $messages->addMessageNow("submit-register-err", "Please validate captcha!");
$messages->addMessageNow("submit-register-err", "Last name could not be empty"); // }
if(!isset($data['email'])||empty($data['email'])) // else {
$messages->addMessageNow("submit-register-err", "E-mail could not be empty"); // $recapsecret = $this->settings['recaptcha']['secret'];
if(!isset($data['letterinvited'])||!is_numeric($data['letterinvited'])) // if($this->settings['testing']){
$messages->addMessageNow("submit-register-err", "Question about needing a letter of invitation must have a selected answer"); // $recapsecret = $this->settings['recaptcha']['secrettest'];
// }
//ReCaptcha Validation // $recaptcha = new ReCaptcha\ReCaptcha($recapsecret);
if(!isset($data['g-recaptcha-response'])||empty($data['g-recaptcha-response'])){ // //get remote ip from request header TODO
$messages->addMessageNow("submit-register-err", "Please validate captcha!"); // $resp = $recaptcha->verify($data['g-recaptcha-response'], $_SERVER['REMOTE_ADDR']);
} // if(!$resp->isSuccess()){
else { // $messages->addMessageNow("submit-register-err", "ReCaptcha validation error " . implode($resp->getErrorCodes()));
$recapsecret = $this->settings['recaptcha']['secret']; // }
if($this->settings['testing']){ // else {
$recapsecret = $this->settings['recaptcha']['secrettest']; // unset($data['g-recaptcha-response']);
} // }
// }
$recaptcha = new ReCaptcha\ReCaptcha($recapsecret); // try{
//get remote ip from request header TODO // if($db->findByMail($data['email']))
$resp = $recaptcha->verify($data['g-recaptcha-response'], $_SERVER['REMOTE_ADDR']); // $messages->addMessageNow("submit-register-err", $data['email']." is already registered<br/>"
if(!$resp->isSuccess()){ // ."Please contact: <b>surfacedynamics2018@cmat.edu.uy</b>");
$messages->addMessageNow("submit-register-err", "ReCaptcha validation error " . implode($resp->getErrorCodes())); // }catch (Exception $e){
} // $this->logger->debug("Submit register DB error: ".$e->getMessage());
else { // $messages->addMessageNow("submit-register-err", "DB error: ".$e->getMessage());
unset($data['g-recaptcha-response']); // }
} // }
}
try{ // if($messages->hasMessage("submit-register-err")){
if($db->findByMail($data['email'])) // $arrayresponse = array("success" => false,
$messages->addMessageNow("submit-register-err", $data['email']." is already registered<br/>" // "msg"=>"You registration could not be completed:\n",
."Please contact: <b>surfacedynamics2018@cmat.edu.uy</b>"); // "errors"=>$messages->getMessage("submit-register-err"), "data"=>$data);
}catch (Exception $e){ // }
$this->logger->debug("Submit register DB error: ".$e->getMessage());
$messages->addMessageNow("submit-register-err", "DB error: ".$e->getMessage());
}
}
if($messages->hasMessage("submit-register-err")){ // else {
$arrayresponse = array("success" => false, // try{
"msg"=>"You registration could not be completed:\n", // $db->insert($data);
"errors"=>$messages->getMessage("submit-register-err"), "data"=>$data); // }catch (Exception $e){
} // $this->logger->debug("Submit register DB error: ".$e->getMessage());
// $messages->addMessageNow("submit-register-err", "DB error: ".$e->getMessage());
// }
// $arrayresponse = array("success" => true,
// "msg"=>"You have been successfully registered to Workshop on Surface Dynamics 2018",
// "data"=>$data);
// $mailbody = "Hello ".$data["nombre"]." ".$data["apellido"].",\n\n".
// "You have been successfully registered to the Workshop on Surface Dynamics 2018!\n\n".
// "If you need to change the information you have provided and for any ".
// "questions please contact surfacedynamics2018@cmat.edu.uy\n\n".
// "Best!\n\n";
// $headers = 'From: ' . "surfacedynamics2018@cmat.edu.uy" . "\r\n" .
// 'Reply-To: ' . "surfacedynamics2018@edu.uy" . "\r\n" .
// 'Content-Type: ' . "text/plain; charset=UTF-8". "\r\n" .
// 'X-Mailer: PHP/' . phpversion();
// mail($data['email'], 'Successfully registered to the Surface Dynamics 2018 Workshop', $mailbody, $headers);
// }
// $newres = $response->withJson($arrayresponse);
// return $newres;
// });
else { // });
try{
$db->insert($data);
}catch (Exception $e){
$this->logger->debug("Submit register DB error: ".$e->getMessage());
$messages->addMessageNow("submit-register-err", "DB error: ".$e->getMessage());
}
$arrayresponse = array("success" => true,
"msg"=>"You have been successfully registered to Workshop on Surface Dynamics 2018",
"data"=>$data);
$mailbody = "Hello ".$data["nombre"]." ".$data["apellido"].",\n\n".
"You have been successfully registered to the Workshop on Surface Dynamics 2018!\n\n".
"If you need to change the information you have provided and for any ".
"questions please contact surfacedynamics2018@cmat.edu.uy\n\n".
"Best!\n\n";
$headers = 'From: ' . "surfacedynamics2018@cmat.edu.uy" . "\r\n" .
'Reply-To: ' . "surfacedynamics2018@edu.uy" . "\r\n" .
'Content-Type: ' . "text/plain; charset=UTF-8". "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($data['email'], 'Successfully registered to the Surface Dynamics 2018 Workshop', $mailbody, $headers);
}
$newres = $response->withJson($arrayresponse);
return $newres;
});
});