<?php
session_start();
/*
 * Registry/registerNew.php
 * 
 * Copyright 2009, 2018 Pedro Quaresma <pedro@mat.uc.pt>
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301, USA.
 */


// include function files for this application
 */
require('../servidor.php');
require($entradaFILE.'dbLogin.php');


require($entradaFILE.'header.php');
require($entradaFILE.'menuHome.php');

require_once('dataValid.php');

$vEmail          = $_POST['email'];
$vUsername       = $_POST['username'];
$vPasswd         = $_POST['passwd'];
$vPasswd2        = $_POST['passwd2'];
$vName           = $_POST['name'];
$vAffiliation    = $_POST['affiliation'];
$vURL            = $_POST['url'];
$vType           = $_POST['type'];
$vDateSubmission = $_POST['dateSubmission'];


// Verifica o preenchimento dos campos obrigatórios
if (!filled_obligatory($_POST)) {
  echo "<p><b>You have not filled out the obligatory fields correctly.</b></p>";
  echo "<p>Please try again.</p>";
  echo "<meta http-equiv='refresh' content='3; url=".$entradaURL."registration.php?email=$vEmail&username=$vUsername&&name=$vName&affiliation=$vAffiliation&url=$vURL&type=$vType' />";
}
elseif (!valid_email($vEmail)) { // email address not valid
  echo "<p><b>That is not a valid email address.</b></p>";
  echo "<p>Please try again.</p>";
  echo "<meta http-equiv='refresh' content='3; url=".$entradaURL."registration.php?email=$vEmail&username=$vUsername&&name=$vName&affiliation=$vAffiliation&url=$vURL&type=$vType' />";
} 
elseif ($vPasswd != $vPasswd2) { // passwords not the same 
  echo "<p><b>The passwords you entered do not match.</b></p>";
  echo "<p>Please try again.</p>";
  echo "<meta http-equiv='refresh' content='3; url=".$entradaURL."registration.php?email=$vEmail&username=$vUsername&&name=$vName&affiliation=$vAffiliation&url=$vURL&type=$vType' />";
}
elseif (strlen($vPasswd)<6 || strlen($vPasswd) >16) { 
  // check password length is ok
  // ok if username truncates, but passwords will get
  // munged if they are too long.
  echo "<p><b>Your password must be between 6 and 16 characters.</b></p>";
  echo "<p>Please try again.</p>";
  echo "<meta http-equiv='refresh' content='3; url=".$entradaURL."registration.php?email=$vEmail&username=$vUsername&&name=$vName&affiliation=$vAffiliation&url=$vURL&type=$vType' />";
}
else { // os valores do formulário estão correctos
  // obtêm os valores de utilizador e senha das variáveis de Sessão
  $dbregular = $_SESSION['dbregular'];
  $dbregpass = $_SESSION['dbregpass'];
  
  // check if username is unique 
  $sql = "SELECT * 
          FROM users
         WHERE username='$vUsername'";
  
  $resultado = mysqli_query($ligacao,$sql);
  
  if (!$resultado) {
    echo "Could not execute query";
    exit;
  }
  
  // O números de campos obtidos
  $nlinhas=mysqli_num_rows($resultado);
  
  if ($nlinhas>0) {
    echo "<p><b>That username is taken.</b></p>";
    echo "<p>Please choose another one.</p>";
    echo "<meta http-equiv='refresh' content='3; url=".$entradaURL."registration.php?email=$vEmail&username=$vUsername&&name=$vName&affiliation=$vAffiliation&url=$vURL&type=$vType' />";
  }
  else {
    if ($vType=='Contributer') {
      $contributer=true;
      $type='Contributer';
      // Todos os utilizadores são registados como "Regular"
      $vType='Regular';
    }
    else {
      $contributer=false;
      $type='Regular User';
    }

    // Vai tentar inserir o novo utilizador
    $sqlInsert = "INSERT INTO users
                         (name,affiliation,url,email,dateSubmission,
                          username,passwd,type)
                      VALUES 
                         ('$vName','$vAffiliation','$vURL','$vEmail',
                          '$vDateSubmission','$vUsername',sha1('$vPasswd'),
                          '$vType')";
    
    $resultadoInsert =  mysqli_query($ligacao,$sqlInsert);
    if (!$resultadoInsert) {
      echo "<p><b>Could not register you in database</b></p>";
      echo "<p>Please try again later.</p>";
      echo "<meta http-equiv='refresh' content='3; url=../index.html' />";
    }
    else {
      // enviar mensagem ao utilizador e a mim

      // enviar mensagem para mim.
      ob_start();
      echo "$vName register itself at GeoThms\n";
      echo "Name: $vName\n";
      echo "Affiliation: $vAffiliation\n";
      echo "URL: $vURL\n";
      echo "Email: $vEmail\n";
      echo "Date of Submission: $vDateSubmission\n";
      echo "Username: $vUsername\n\n";
      echo "The user wish to be a $type\n\n";
      
      $messagemToAdmin = ob_get_contents();
      $from = "From: geothms@hilbert.mat.uc.pt";

      mail('pedro@mat.uc.pt','GeoThms - Novo utilizador',$messagemToAdmin,$from); 
      ob_end_clean();

      ob_start();
      echo "Welcome to GeoThms $vName\n";
      echo "Name: $vName\n";
      echo "Affiliation: $vAffiliation\n";
      echo "URL: $vURL\n";
      echo "Email: $vEmail\n";
      echo "Date of Submission: $vDateSubmission\n";
      echo "Username: $vUsername\n\n";
      echo "You wish to be a $type\n\n";
      
      $messageToNewUser = ob_get_contents();    
      mail($vEmail, 'Welcome to GeoThms', $messageToNewUser,$from);
      ob_end_clean();

      echo "<h2>Welcome $vName</h2>";
      echo "<meta http-equiv='refresh' content='3; url=../index.html' />";   
    }     
 }
}

?>



<hr/>

<p>&nbsp;</p>

<?php
require($entradaFILE."footer.php");
?>